0% found this document useful (0 votes)
445 views226 pages

Final ARM Instruction 04 Lecture

Uploaded by

raghav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
445 views226 pages

Final ARM Instruction 04 Lecture

Uploaded by

raghav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 226

By,

Dr. Amit M. Joshi,


Assistant Professor, MNIT
Jaipur
Content

qThe ARM processor


qARM instruction set
qSummary
The ARM processor

3
ARM Ltd
q ARM was originally developed at Acron Computer Limited, of
Cambridge, England between 1983 and 1985.
– 1980, RISC concept at Stanford and Berkeley universities.
– First RISC processor for commercial use
q 1990 Nov, ARM Ltd was founded
q ARM cores
– Licensed to partners who fabricate and sell to customers.
q Technologies assist to design in the ARM application
– Software tools, boards, debug hardware, application software, bus
architectures, peripherals etc…
q Modification of the acronym expansion to Advanced RISC
Machine.

4
ARM Ltd
Design and license ARM core design but not fabricate
Why ARM?
qOne of the most licensed and thus widespread
processor cores in the world
– Used in PDA, cell phones, multimedia players, handheld
game console, digital TV and cameras
qUsed especially in portable devices due to its low
power consumption and reasonable performance
ARM processors
qA simple but powerful design
qA whole family of designs sharing similar design
principles and a common instruction set
ARM powered products
Naming ARM
qARMxyzTDMIEJFS
– x: series
– y: MMU
– z: cache
– T: Thumb
– D: debugger
– M: Multiplier
– I: EmbeddedICE (built-in debugger hardware)
– E: Enhanced instruction
– J: Jazelle (JVM)
– F: Floating-point
– S: Synthesizible version (source code version for EDA
tools)
ARM 7 applications
ARM9 applications
ARM11 applications
ARM CortexM applications

• Dell E4300
Latitude Laptop
• instant boot-up
for users and
access to select
applications,
with multi-day
battery lifetimes
ARM CortexA applications
ARM CortexR
Popular ARM architectures (selection)
qARM7TDMI
– 3 pipeline stages (fetch/decode/execute)
– High code density/low power consumption
– One of the most used ARM-version (for low-end systems)
– All ARM cores after ARM7TDMI include TDMI even if they
do not include TDMI in their labels
qARM9TDMI
– Compatible with ARM7
– 5 stages (fetch/decode/execute/memory/write)
– Separate instruction and data cache
qARM11
ARM design philosophy
qSmall processor for lower power consumption (for
embedded system)
qHigh code density for limited memory and physical
size restrictions
qThe ability to use slow and low-cost memory
qReduced die size for reducing manufacture cost and
accommodating more peripherals
ARM architecture
ARM architecture

qLoad/store architecture
qA large array of uniform
registers
qFixed-length 32-bit
instructions
q3-address instructions
RISC Architecture
qBerkeley incorporated a Reduced Instruction Set
Computer (RISC) architecture.
qIt has the following key features:
– A fixed (32-bit) instruction size with few formats;
• CISC processors typically had variable length instruction sets with
many formats.
– A load–store architecture where instructions that process
data operate only on registers and are separate from
instructions that access memory;
• CISC processors typically allowed values in memory to be used as
operands in data processing instructions.
– A large register bank of thirty-two 32-bit registers, all of
which could be used for any purpose, to allow the load-
store architecture to operate efficiently;
• CISC register sets were getting larger, but none was this large and
most had different registers for different purposes
22
RISC Organization
qHard-wired instruction decode logic
– CISC processor used large microcode ROMs to decode
their instructions
qPipelined execution
– CISC processors allowed little, if any, overlap between
consecutive instructions (though they do now)
qSingle-cycle execution
– CISC processors typically took many clock cycles to
completes a single instruction

→ Simple is beauty
Compiler plays an important role
23
ARM Architecture vs. Berkeley RISC
q Features used
– Load/Store architecture
– Fixed-length 32-bit instructions
– 3-address instruction formats

f bits n bits n bits n bits


function op 1 addr. op 2 addr. dest. addr.
ADD d, S1, S2 ; d := S1 + S2

q Features rejected
– Register windows → costly
• Use shadow (banked) registers in ARM
– Delay branch
• Badly with branch prediction
– Single-cycle execution of all instructions
• Most single cycle, many other take multiple clock cycles
24
ARM features
qDifferent from pure RISC in several ways:
– Variable cycle execution for certain instructions: multiple-
register load/store (faster/higher code density)
– Inline barrel shifter leading to more complex instructions:
improves performance and code density
– Thumb 16-bit instruction set: 30% code density
improvement
– Conditional execution: improve performance and code
density by reducing branch
– Enhanced instructions: DSP instructions
Data Size and Instruction Set
qARM processor is a 32-bit architecture
qWhen used in relation to the ARM
– Byte means 8 bits
– Halfword means 16 bits (two bytes)
– Word means 32 bits (four bytes)
qMost ARM’s implement two instruction sets
– 32-bit ARM instruction set
– 16-bit Thumb instruction set

26
Data Types
qARM processor supports 6 data types
– 8-bits signed and unsigned bytes
– 16-bits signed and unsigned half-word, aligned on 2-byte
boundaries
– 32-bits signed and unsigned words, aligned on 4-byte
boundaries
qARM instructions are all 32-bit words, word-aligned
qThumb instructions are half-words, aligned on 2-
byte boundaries

27
Processor Modes
qThe ARM has seven basic operating modes
– User: unprivileged mode under which most tasks run
– FIQ: entered when a high priority (fast) interrupts is raised
– IRQ: entered when a low priority (normal) interrupts is
raised
– Supervisor: entered on reset and when a software
interrupt instruction is executed
– Abort: used to handle memory access violations
– Undefined: used to handle undefined instructions
– System: privileged mode using the same registers as
user mode
• Not in ARM architecture 1, 2, or 3

28
Processor Modes (cont.)
qException modes
– FIQ, IRQ, Supervisor, Abort, and Undefined

qPrivileged modes
– FIQ, IRQ, Supervisor, Abort, Undefined, and System

29
The Mode Bits
qMode changes by software control or external
interrupts
qCurrent program status register, CPSR
CPS R[ 4 : 0 ] Mo de Us e Re g i s t e rs
10000 User Normal user code user
10001 FIQ Processing fast interrupts _fiq
10010 IRQ Processing standard interrupts _irq
10011 SVC Processing software interrupts (SWIs) _svc
10111 Abort Processing memory faults _abt
11011 Undef Handling undefined instruction traps _und
11111 System Running privileged operating system tasks user

30
The Registers
qARM has 37 registers, all of which are 32 bits long
– 1 dedicated program counter
– 1 dedicated current program status register
– 5 dedicated saved program status registers
– 31 general purpose registers
qThe current processor mode governs which bank is
accessible
– Each mode can access
• A particular set of r0 – r12 registers
• A particular r13 (stack pointer, SP) and r14 (link register, LR)
• The program counter, r15 (PC)
• The current program status register, CPSR
– Privileged modes (except system) can access
• A particular SPSR (Saved Program Status Register)

31
Register Banking

r0
usable in user mode
r1
r2
r3 exception modes only
r4
r5
r6
r7
r8_fiq
r8
r9 r9_fiq
r10_fiq
r10
r1 1 r11_fiq
r12_fiq r13_irq r13_und
r12 r13_abt
r13_fiq r13_svc r14_irq r14_und
r13 r14_svc r14_abt
r14 r14_fiq
r15 (PC)

SPSR_und
SPSR_abt SPSR_irq
CPSR SPSR_fiq SPSR_svc

system mode fiq svc abort irq undefined


user mode mode mode mode mode mode

32
General Purpose Registers
qThe unbanked registers
– r0 – r15
– user and system mode refer to the same physical
registers
qThe banked registers
– r8_fiq – r12_fiq, r13_<mode>, and r14_<mode>
– The set of physical registers depend on the processor
mode
– r13 is normally used as the stack pointer (SP)
– r14 is also known as the link register (LR), which is used
to store the return address from a subroutine
qRegister 15, PC
– r15 is the program counter
33
Program Counter (r15)
qWhen the processor is executing in ARM state:
– All instructions are 32 bits wide
– All instructions must be word-aligned
– Therefore the PC value is stored in bits [32:2] with bits
[1:0] undefined (as instruction cannot be halfword)
qWhen the processor is executing in Thumb state:
– All instructions are 16 bits wide
– All instructions must be halfword-aligned
– Therefore the PC value is stored in bits [32:1] with bits [0]
undefined (as instruction cannot be byte-aligned)

34
Current Program Status Registers
(CPSR)

q Condition code flags q Interrupt disable bits


– N: Negative result form ALU – I = 1, disable the IRQ
– Z: Zero result from ALU – F = 1, disable the FIQ
– C: ALU Operation Carried out
– V: ALU operation oVerflowed
q T Bit
– Architecture xT only
q Sticky overflow flag – Q flag – T = 0, processor in ARM state
– Architecture 5TE only – T = 1, processor in Thumb
– Indicates if saturation has state
occurred during certain
operations
q Mode bits
– Specify the processor mode

35
Accessing Registers using
ARM Instructions
qNo breakdown of currently accessible registers.
– All instructions can access r0-r14 directly.
– Most instructions also allow use of the PC.
qSpecific instructions to allow access to CPSR and
SPSR.
qNote : When in a privileged mode, it is also possible
to load / store the (banked out) user mode registers
to or from memory.
– See later for details.
The Program Status Registers
(CPSR and SPSRs)

31 28 8 4 0

N Z CV I F T Mode

Copies of the ALU status flags (latched if the


instruction has the "S" bit set).

* Condition Code Flags * Interrupt Disable bits.


N = Negative result from ALU flag. I = 1, disables the IRQ.
Z = Zero result from ALU flag. F = 1, disables the FIQ.
C = ALU operation Carried out
V = ALU operation oVerflowed * T Bit (Architecture v4T only)
T = 0, Processor in ARM state
* Mode Bits T = 1, Processor in Thumb state
M[4:0] define the processor mode.
Condition Flags

Logical Instruction Arithmetic Instruction

Flag

Negative No meaning Bit 31 of the result has been set


(N=‘1’) Indicates a negative number in
signed operations

Zero Result is all zeroes Result of operation was zero


(Z=‘1’)

Carry After Shift operation Result was greater than 32 bits


(C=‘1’) ‘1’ was left in carry flag

oVerflow No meaning Result was greater than 31 bits


(V=‘1’) Indicates a possible corruption of
the sign bit in signed
numbers
The Program Counter (R15)
q When the processor is executing in ARM state:
– All instructions are 32 bits in length
– All instructions must be word aligned

q R14 is used as the subroutine link register (LR) and stores the
return address when Branch with Link operations are performed,
calculated from the PC.
q Thus to return from a linked branch
– MOV r15,r14
or
– MOV pc,lr
Exception Handling
and the Vector Table
qWhen an exception occurs, the
core:
– Copies CPSR into SPSR_<mode>
– Sets appropriate CPSR bits 0x00000000 Reset
u If core implements ARM Architecture 4T and
0x00000004 Undefined Instruction
is currently in Thumb state, then
0x00000008 Software Interrupt
n ARM state is entered.
0x0000000C Prefetch Abort
u Mode field bits
0x00000010 Data Abort
u Interrupt disable flags if appropriate.
0x00000014 Reserved
– Maps in appropriate banked registers
IRQ
– Stores the “return address” in LR_<mode>
0x00000018

FIQ
– Sets PC to vector address
0x0000001C

qTo return, exception handler


needs to:
– Restore CPSR from SPSR_<mode>
– Restore PC from LR_<mode>
The Instruction Pipeline
qThe ARM uses a pipeline in order to increase
the speed of the flow of instructions to the
processor.
– Allows several operations to be undertaken
simultaneously, rather than serially.
ARM

PC FETCH Instruction fetched from memory

DECODE Decoding of registers used in instruction


PC - 4

Register(s) read from Register Bank


PC - 8 EXECUTE
Shift and ALU operation
Write register(s) back to Register Bank
ARM Instruction Set Format
31 2827 1615 87 0 Instruction type
Cond 0 0 I Opcode S Rn Rd Operand2 Data processing / PSR
Transfer
Cond 0 0 0 0 0 0 A S Rd Rn Rs 1 0 0 1 Rm
Multiply
Cond 0 0 0 0 1 U A S RdHi RdLo Rs 1 0 0 1 Rm
Long Multiply (v3M / v4
Cond 0 0 0 1 0 B 0 0 Rn Rd 0 0 0 0 1 0 0 1 Rm only)
Cond 0 1 I P U B W L Rn Rd Offset Swap
Cond 1 0 0 P U S W L Rn Register List Load/Store Byte/Word
Cond 0 0 0 P U 1 W L Rn Rd Offset1 1 S H 1 Offset2 Load/Store Multiple
Cond 0 0 0 P U 0 W L Rn Rd 0 0 0 0 1 S H 1 Rm Halfword transfer : Immediate offset (v4
only)
Cond 1 0 1 L Offset
Halfword transfer: Register offset (v4 only)
Cond 0 0 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 Rn
Branch
Cond 1 1 0 P U N W L Rn CRd CPNum Offset
Branch Exchange (v4T
Cond 1 1 1 0 Op1 CRn CRd CPNum Op2 0 CRm
only)
Cond 1 1 1 0 Op1 L CRn Rd CPNum Op2 1 CRm
Coprocessor data transfer
Cond 1 1 1 1 SWI Number Coprocessor data operation
Coprocessor register transfer
Software interrupt
Conditional Execution
qMost instruction sets only allow branches to be
executed conditionally.
qHowever by reusing the condition evaluation
hardware, ARM effectively increases number of
instructions.
– All instructions contain a condition field which determines
whether the CPU will execute them.
– Non-executed instructions soak up 1 cycle.
• Still have to complete cycle so as to allow fetching and decoding
of following instructions.
qThis removes the need for many branches, which
stall the pipeline (3 cycles to refill).
– Allows very dense in-line code, without branches.
– The Time penalty of not executing several conditional
The Condition Field

31 28 24 20 16 12 8 4 0

Cond

0000 = EQ - Z set (equal) 1001 = LS - C clear or Z (set


0001 = NE - Z clear (not equal) unsigned lower or same)

0010 = HS / CS - C set (unsigned 1010 = GE - N set and V set, or N


higher or same) clear and V clear (>or =)
0011 = LO / CC - C clear (unsigned 1011 = LT - N set and V clear, or N
lower) clear and V set (>)
0100 = MI -N set (negative) 1100 = GT - Z clear, and either N set
0101 = PL - N clear (positive or and V set, or N clear and V
zero) set (>)
0110 = VS - V set (overflow) 1101 = LE - Z set, or N set and V
0111 = VC - V clear (no overflow) clear,or N clear and V set (<,
or =)
1000 = HI - C set and Z clear
(unsigned higher) 1110 = AL - always
1111 = NV - reserved.
DATA PROCESSING INSTRUCTIONS
q Move Instructions, Arithmetic instruction, logical
instructions, comparision and multiply instructions
qIf you use s suffix then cpsr flags updation possible.
q Move and logical instructions update carry flag C,
negative flag N, and zero flag Z.

45
MOVE INSTRUCTIONS

46
BARREL SHIFTER

47
ARITHMETIC INSTRUCTION

48
Examples

49
50
51
BARREL SHIFTER WITH ARITHMETIC
INSTRUCTIONS

52
53
Logical Instruction

54
55
COMPARISION INSTRUCTION

56
EXAMPLES

57
58
59
60
61
62
Using and updating the Condition Field
q To execute an instruction conditionally, simply postfix it with the
appropriate condition:
– For example an add instruction takes the form:
• ADD r0,r1,r2 ; r0 = r1 + r2 (ADDAL)
– To execute this only if the zero flag is set:
• ADDEQ r0,r1,r2 ; If zero flag set then…
; ... r0 = r1 + r2
q By default, data processing operations do not affect the condition
flags (apart from the comparisons where this is the only effect). To
cause the condition flags to be updated, the S bit of the instruction
needs to be set by postfixing the instruction (and any condition
code) with an “S”.
– For example to add two numbers and set the condition flags:
• ADDS r0,r1,r2 ; r0 = r1 + r2
; ... and set flags
Branch instructions (1)
qBranch : B{<cond>} label
qBranch with Link : BL{<cond>}
sub_routine_label
31 28 27 25 24 23 0

Cond 1 0 1 L Offset

Link bit 0 = Branch


1 = Branch with link
Condition field
Branch instructions (1)
qBranch : B{<cond>} label
qBranch with Link : BL{<cond>}
sub_routine_label
31 28 27 25 24 23 0

Cond 1 0 1 L Offset

Link bit 0 = Branch


1 = Branch with link
Condition field
q The offset for branch instructions is calculated by the
assembler:
– By taking the difference between the branch instruction
and the target address minus 8 (to allow for the
pipeline).
– This gives a 26 bit offset which is right shifted 2 bits (as
the bottom two bits are always zero as instructions are
word – aligned) and stored into the instruction
encoding.
– This gives a range of ± 32 Mbytes.
Branch instructions (2)
q When executing the instruction, the processor:
– shifts the offset left two bits, sign extends it to 32 bits, and adds
it to PC.
q Execution then continues from the new PC, once the pipeline has
been refilled.
q The "Branch with link" instruction implements a subroutine call by
writing PC-4 into the LR of the current bank.
– i.e. the address of the next instruction following the branch with
link (allowing for the pipeline).
q To return from subroutine, simply need to restore the PC from the
LR:
– MOV pc, lr
– Again, pipeline has to refill before execution continues.
q The "Branch" instruction does not affect LR.
q Note: Architecture 4T offers a further ARM branch instruction, BX
– See Thumb Instruction Set Module for details.
Data processing Instructions
q Largest family of ARM instructions, all sharing the same instruction
format.
q Contains:
– Arithmetic operations
– Comparisons (no results - just set condition codes)
– Logical operations
– Data movement between registers
q Remember, this is a load / store architecture
– These instruction only work on registers, memory.
q They each perform a specific operation on one or two operands.
– First operand always a register - Rn
– Second operand sent to the ALU via barrel shifter.
q We will examine the barrel shifter shortly.
Arithmetic Operations
qOperations are:
– ADD operand1 + operand2
– ADC operand1 + operand2 + carry
– SUB operand1 - operand2
– SBC operand1 - operand2 + carry -1
– RSB operand2 - operand1
– RSC operand2 - operand1 + carry - 1
qSyntax:
– <Operation>{<cond>}{S} Rd, Rn, Operand2
qExamples
– ADD r0, r1, r2
– SUBGT r3, r3, #1
– RSBLES r4, r5, #5
Comparisons
qThe only effect of the comparisons is to
. Thus no need to set
S bit.
qOperations are:
– CMP operand1 - operand2, but result not written
– CMN operand1 + operand2, but result not written
– TST operand1 AND operand2, but result not written
– TEQ operand1 EOR operand2, but result not written
qSyntax:
– <Operation>{<cond>} Rn, Operand2
qExamples:
– CMP r0, r1
– TSTEQ r2, #5
Logical Operations
qOperations are:
– AND operand1 AND operand2
– EOR operand1 EOR operand2
– ORR operand1 OR operand2
– BIC operand1 AND NOT operand2 [ie bit clear]
qSyntax:
– <Operation>{<cond>}{S} Rd, Rn, Operand2
qExamples:
– AND r0, r1, r2
– BICEQ r2, r3, #7
– EORS r1,r3,r0
Data Movement
qOperations are:
– MOV operand2
– MVN NOT operand2
Note that these make no use of operand1.
qSyntax:
– <Operation>{<cond>}{S} Rd, Operand2
qExamples:
– MOV r0, r1
– MOVS r2, #10
– MVNEQ r1,#0
72
Extended Multiply Instructions
q M variants of ARM cores contain extended multiplication
hardware. This provides three enhancements:
– An is used
• Multiplication is carried out faster (maximum for
standard instructions is now 5 cycles).
so that now
completes multiplication when all remaining bit sets
contain
• all zeroes (as with non-M ARMs), or
• all ones.
Thus the previous example would early terminate in 2
cycles in both cases.
can now be produced from two 32bit
operands
• Higher accuracy.
• Pair of registers used to store result.
Multiply-Long and
Multiply-Accumulate Long
q Instructions are
– MULL which gives RdHi,RdLo:=Rm*Rs
– MLAL which gives RdHi,RdLo:=(Rm*Rs)+RdHi,RdLo
q However the full 64 bit of the result now matter (lower precision
multiply instructions simply throws top 32bits away)
– Need to specify whether operands are signed or unsigned
q Therefore syntax of new instructions are:
– UMULL{<cond>}{S} RdLo,RdHi,Rm,Rs
– UMLAL{<cond>}{S} RdLo,RdHi,Rm,Rs
– SMULL{<cond>}{S} RdLo, RdHi, Rm, Rs
– SMLAL{<cond>}{S} RdLo, RdHi, Rm, Rs
q Not generated by the compiler.
Warning : Unpredictable on non-M ARMs.
The Barrel Shifter
qThe ARM doesn’t have actual shift instructions.

qInstead it has a barrel shifter which provides a


mechanism to carry out shifts as part of other
instructions.

qSo what operations does the barrel shifter support?


Barrel Shifter - Left Shift
qShifts left by the specified amount (multiplies by
powers of two) e.g.
LSL #5 = multiply by 32

Logical Shift Left (LSL)

CF Destination 0
Barrel Shifter - Right Shifts

Logical Shift Logical Shift Right


Right
•Shifts right by ...0 Destination CF

the specified
amount
(divides by Arithmetic Shift Right
powers of two)
e.g. Destination CF

LSR #5 = Sign bit shifted in


divide by 32
Barrel Shifter - Rotations

Rotate Right (ROR) Rotate Right

• Similar to an Destination CF
ASR but the bits
wrap around as
they leave the LSB
and appear as the
MSB.
e.g. ROR #5 Rotate Right through Carry

•Note the last bit


rotated is also Destination CF

used as the Carry


Out.
Using the Barrel Shifter:
The Second Operand

Operand 1 Operand 2 q Register, optionally with shift


operation applied.
q Shift value can be either be:
– 5 bit unsigned integer
Barrel – Specified in bottom byte
of another register.
Shifter
* Immediate value
• 8 bit number
• Can be rotated right through
an even number of
ALU
positions.
• Assembler will calculate
rotate for you from
constant.
Result
Second Operand :
Shifted Register
qThe amount by which the register is to be
shifted is contained in either:
– the immediate 5-bit field in the instruction

• Shift is done for free - executes in single cycle.


– the bottom byte of a register (not PC)
• Then takes extra cycle to execute
• ARM doesn’t have enough read ports to read 3
registers at once.
• Then same as on other processors where shift is
separate instruction.
qIf no shift is specified then a default shift is
applied: LSL #0
– i.e. barrel shifter has no effect on value in
register.
Second Operand :
Using a Shifted Register
q Using a multiplication instruction to multiply by a constant means
first loading the constant into a register and then waiting a number
of internal cycles for the instruction to complete.
q A more optimum solution can often be found by using some
combination of MOVs, ADDs, SUBs and RSBs with shifts.
– Multiplications by a constant equal to a ((power of 2) ± 1) can
be done in one cycle.
q Example: r0 = r1 * 5
Example: r0 = r1 + (r1 * 4)
ï ADD r0, r1, r1, LSL #2
q Example: r2 = r3 * 105
Example: r2 = r3 * 15 * 7
Example: r2 = r3 * (16 - 1) * (8 - 1)
ï RSB r2, r3, r3, LSL #4 ; r2 = r3 * 15
ï RSB r2, r2, r2, LSL #3 ; r2 = r2 * 7
Second Operand :
Immediate Value (1)
q There is no single instruction which will load a 32 bit immediate
constant into a register without performing a data load from
memory.
– All ARM instructions are 32 bits long
– ARM instructions do not use the instruction stream as data.
q The data processing instruction format has 12 bits available for
operand2
– If used directly this would only give a range of 4096.
q Instead it is used to store 8 bit constants, giving a range of 0 - 255.
q These 8 bits can then be rotated right through an even number of
positions (ie RORs by 0, 2, 4,..30).
– This gives a much larger range of constants that can be directly
loaded, though some constants will still need to be loaded
from memory.
Second Operand :
Immediate Value (2)
q This gives us:
– 0 - 255 [0 - 0xff]
– 256,260,264,..,1020 [0x100-0x3fc, step 4, 0x40-0xff ror 30]
– 1024,1040,1056,..,4080 [0x400-0xff0, step 16, 0x40-0xff ror 28]
– 4096,4160, 4224,..,16320 [0x1000-0x3fc0, step 64, 0x40-0xff ror 26]
q These can be loaded using, for example:
– MOV r0, #0x40, 26 ; => MOV r0, #0x1000 (ie 4096)
q To make this easier, the assembler will convert to this form for us if
simply given the required constant:
– MOV r0, #4096 ; => MOV r0, #0x1000 (ie 0x40 ror 26)
q The bitwise complements can also be formed using MVN:
– MOV r0, #0xFFFFFFFF ; assembles to MVN r0, #0
q If the required constant cannot be generated, an error will
be reported.
Loading full 32 bit constants
q Although the MOV/MVN mechansim will load a large range of constants
into a register, sometimes this mechansim will not generate the required
constant.
q Therefore, the assembler also provides a method which will load 32
bit constant:
– LDR rd,=numeric constant
q If the constant can be constructed using either a MOV or MVN then this
will be the instruction actually generated.
q Otherwise, the assembler will produce an LDR instruction with a PC-
relative address to read the constant from a literal pool.
– LDR r0,=0x42 ; generates MOV r0,#0x42
– LDR r0,=0x55555555 ; generate LDR r0,[pc, offset
to lit pool]
q As this mechanism will always generate the best instruction for a given
case, it is the recommended way of loading constants.
Multiplication Instructions
q The Basic ARM provides two multiplication instructions.
q Multiply
– MUL{<cond>}{S} Rd, Rm, Rs ; Rd = Rm * Rs
q Multiply Accumulate - does addition for free
– MLA{<cond>}{S} Rd, Rm, Rs,Rn ; Rd = (Rm * Rs) + Rn
q Restrictions on use:
– Rd and Rm cannot be the same register
• Can be avoid by swapping Rm and Rs around. This works
because multiplication is commutative.
– Cannot use PC.
These will be picked up by the assembler if overlooked.
q Operands can be considered signed or unsigned
– Up to user to interpret correctly.
Load / Store Instructions

q The ARM is a Load / Store Architecture:


– Does not support memory to memory data processing
operations.
– Must move data values into registers before using them.
q This might sound inefficient, but in practice isn’t:
– Load data values from memory into registers.
– Process data in registers using a number of data
processing instructions which are not slowed down by
memory access.
– Store results from registers out to memory.
q The ARM has three sets of instructions which interact with
main memory. These are:
– Single register data transfer (LDR / STR).
– Block data transfer (LDM/STM).
– Single Data Swap (SWP).
Single register data transfer
q The basic load and store instructions are:
– Load and Store Word or Byte
• LDR / STR / LDRB / STRB
q ARM Architecture Version 4 also adds support for halfwords and
signed data.
– Load and Store Halfword
• LDRH / STRH
– Load Signed Byte or Halfword - load value and sign extend it to
32 bits.
• LDRSB / LDRSH
q All of these instructions can be conditionally executed by inserting
the appropriate condition code after STR / LDR.
– e.g. LDREQB
q Syntax:
– <LDR|STR>{<cond>}{<size>} Rd, <address>
Load and Store Word or Byte:
Base Register

88
Load and Store Word or Byte:
Offsets from the Base Register
q As well as accessing the actual location contained in the base
register, these instructions can access a location offset from the
base register pointer.
q This offset can be
– An unsigned 12bit immediate value (ie 0 - 4095 bytes).
– A register, optionally shifted by an immediate value
q This can be either added or subtracted from the base register:
– Prefix the offset value or register with ‘+’ (default) or ‘-’.
q This offset can be applied:
– before the transfer is made:
• optionally the base register, by
postfixing the instruction with an ‘!’.
– after the transfer is made:
• causing the base register to be .
90
91
Load AND Store Architecture
Load AND Store Architecture
SINGLE REGISTER LOAD-STORE
ADDRESSING MODE
SINGLE REGISTER LOAD-STORE
ADDRESSING MODE
Single Register Load & Store Instruction
qLDRB r1,[r0]
qLDRH r1,[r0]
qLDR r1,[r0]
Graphical Representation
Branch Instructions
Branch Instructions
Branch Instructions
Branch Instructions
Example: Block Copy

– Copy a block of memory, which is an exact multiple


of 12 words long from the location pointed to by r12
to the location pointed to by r13. r14 points to the
end of block to be copied.
; r12 points to the start of the source data
; r14 points to the end of the source data
; r13 points to the start of the destination data
r13
loop LDMIA r12!, {r0-r11} ; load 48 bytes
STMIA r13!, {r0-r11} ; and store them r14 IncreasingM
CMP r12, r14 ; check for the end emory

BNE loop ; and loop until done

r12
– This loop transfers 48 bytes in 31 cycles
– Over 50 Mbytes/sec at 33 MHz
148
150
Stack Operation
q Traditionally, a stack grows down in memory, with the last
“pushed” value at the lowest address. The ARM also supports
ascending stacks, where the stack structure grows up through
memory.
q The value of the stack pointer can either:
– Point to the last occupied address (Full stack)
• and so needs pre-decrementing (ie before the push)
– Point to the next occupied address (Empty stack)
• and so needs post-decrementing (ie after the push)
q The stack type to be used is given by the postfix to the instruction:
– STMFD / LDMFD : Full Descending stack
– STMFA / LDMFA : Full Ascending stack.
– STMED / LDMED : Empty Descending stack
– STMEA / LDMEA : Empty Ascending stack
q Note: ARM Compiler will always use a Full descending stack.
152
Stacks and Subroutines
q One use of stacks is to create temporary register workspace for
subroutines. Any registers that are needed can be pushed onto
the stack at the start of the subroutine and popped off again at the
end so as to restore them before return to the caller :
STMFD sp!,{r0-r12, lr} ; stack all registers
........ ; and the return address
........
LDMFD sp!,{r0-r12, pc} ; load all the
registers
; and return automatically
q See the chapter on the ARM Procedure Call Standard in the SDT
Reference Manual for further details of register usage within
subroutines.
q If the pop instruction also had the ‘S’ bit set (using ‘^’) then the
transfer of the PC when in a priviledged mode would also cause
the SPSR to be copied into the CPSR (see exception handling
Direct functionality of
Block Data Transfer
qWhen LDM / STM are not being used to implement
stacks, it is clearer to specify exactly what
functionality of the instruction is:
– i.e. specify whether to increment / decrement the base
pointer, before or after the memory access.
qIn order to do this, LDM / STM support a further
syntax in addition to the stack one:
– STMIA / LDMIA : Increment After
– STMIB / LDMIB : Increment Before
– STMDA / LDMDA : Decrement After
– STMDB / LDMDB : Decrement Before
Load and Stores
with User Mode Privilege

qWhen using post-indexed addressing, there is a


further form of Load/Store Word/Byte:
– <LDR|STR>{<cond>}{B}T Rd, <post_indexed_address>

qWhen used in a privileged mode, this does the


load/store with user mode privilege.
– Normally used by an exception handler that is emulating a
memory access instruction that would normally execute in
user mode.
156
Offsets for Halfword and Signed Halfword /
Byte Access

qThe Load and Store Halfword and Load Signed Byte


or Halfword instructions can make use of pre- and
post-indexed addressing in much the same way as
the basic load and store instructions.
qHowever the actual offset formats are more
constrained:
– The immediate value is limited to 8 bits (rather than 12
bits) giving an offset of 0-255 bytes.
– The register form cannot have a shift applied to it.
Effect of endianess
qThe ARM can be set up to access its data
in either little or big endian format.
qLittle endian:
– Least significant byte of a word is stored in
of an addressed word.
qBig endian:
– Least significant byte of a word is stored in
of an addressed word.
qThis has no real relevance unless data is
stored as words and then accessed in
smaller sized quantities (halfwords or
bytes).
– Which byte / halfword is accessed will depend
on the endianess of the system involved.
Endianess Example

r0 = 0x11223344
31 24 23 16 15 87 0

11 22 33 44

STR r0, [r1]

31 24 23 16 15 87 0 31 24 23 16 15 87 0

r1 = 0x100 11 22 33 44 Memory 44 33 22 11 r1 = 0x100

Little-endian LDRB r2, [r1] Big-endian


31 24 23 16 15 87 0 31 24 23 16 15 87 0

00 00 00 44 00 00 00 11

r2 = 0x44 r2 = 0x11
Block Data Transfer (1)
q The Load and Store Multiple instructions (LDM / STM) allow
betweeen 1 and 16 registers to be transferred to or from memory.
q The transferred registers can be either:
– Any subset of the current bank of registers (default).
– Any subset of the user mode bank of registers when in a
priviledged mode (postfix instruction with a ‘ ’).

31 28 27 24 23 22 21 20 19 16 15 0

Cond 1 0 0 P U S W L Rn Register list

Condition field Base register Each bit corresponds to a particular


Up/Down bit register. For example:
Load/Store bit • Bit 0 set causes r0 to be transferred.
0 = Down; subtract offset from base 0 = Store to memory • Bit 0 unset causes r0 not to be transferred.
1 = Up ; add offset to base 1 = Load from memory
At least one register must be transferred
Pre/Post indexing bit Write- back bit as the list cannot be empty.
0 = Post; add offset after transfer, 0 = no write-back
1 = Pre ; add offset before transfer 1 = write address into base
PSR and force user bit
0 = don’t load PSR or force user mode
1 = load PSR or force user mode
Block Data Transfer (2)
qBase register used to determine where memory
access should occur.
– 4 different addressing modes allow increment and
decrement inclusive or exclusive of the base register
location.
– Base register can be optionally updated following the
transfer (by appending it with an ‘ ’.
– Lowest register number is always transferred to/from
lowest memory location accessed.
qThese instructions are very efficient for
– Saving and restoring context
• For this useful to view memory as a stack.
– Moving large blocks of data around memory
• For this useful to directly represent functionality of the instructions.
Software Interrupt (SWI)
31 28 27 24 23 0

Cond 1 1 1 1 Comment field (ignored by Processor)

Condition Field
q In effect, a SWI is a user-defined instruction.
q It causes an exception trap to the SWI hardware vector
(thus causing a change to supervisor mode, plus the
associated state saving), thus causing the SWI exception
handler to be called.
q The handler can then examine the comment field of the
instruction to decide what operation has been requested.
q By making use of the SWI mechansim, an operating system
can implement a set of privileged operations which
applications running in user mode can request.
q See Exception Handling Module for further details.
Saved Program Status Register
(SPSR)
qEach privileged mode (except system mode) has
associated with it a SPSR
qThis SPSR is used to save the state of CPSR when
the privileged mode is entered in order that the user
state can be fully restored when the user process is
resumed
qOften the SPSR may be untouched from the time
the privileged mode is entered to the time it is used
to restore the CPSR
qIf the privileged supervisor calls to itself the SPSR
must be copied into a general register and saved

163
Exceptions
qExceptions are usually used to handle unexpected
events which arise during the execution of a
program, such as interrupts or memory faults, also
cover software interrupts, undefined instruction
traps, and the system reset
qThree groups:
– Exceptions generated as the direct effect of executing an
instruction
• Software interrupts, undefined instructions, and prefetch abort
– Exceptions generated as a side effect of an instruction
• Data aborts
– Exceptions generated externally
• Reset, IRQ and FIQ

164
Exception Entry (1/2)
qWhen an exception arises
– ARM completes the current instruction as best it can
(except that reset exception)
– handle the exception which starts from a specific location
(exception vector).
qProcessor performs the following sequence:
– Change to the operating mode corresponding to the
particular exception
– Stores the return address in LR_<mode>
– Copy old CPSR into SPSR_<mode>
– Set appropriate CPSR bits
• If core currently in Thumb state then ARM state is entered.
• Disable IRQs by setting bit 7
• If the exception is a fast interrupt, disable further faster interrupt
by setting bit 6 of the CPSR
165
Exception Entry (2/2)
– Force PC to relevant vector address
Priority Exception Mode vector address
1 Reset SVC 0x00000000
2 Data abort (data access memory fault) Abort 0x00000010
3 FIQ (fast interrupt ) FIQ 0x0000001C
4 IRQ (normal interrupt) IRQ 0x00000018
5 Prefetch abort (instruction fetch memory Abort 0c0000000C
fault)
6 Undefined instruction UND 0x00000004
Software interrupt (SWI) SVC 0x00000008
qNormally the vector address contains a branch to
the relevant routine
qException handler use r13_<mode> and
r14_<mode> to hold the stack point and return
address
166
Exception Return
qOnce the exception has been handled, the user task
is normally resumed
qThe sequence is
– Any modified user registers must be restored from the
handler’s stack
– CPSR must be restored from the appropriate SPSR
– PC must be changed back to the relevant instruction
address
qThe last two steps happen atomically as part of a
single instruction

167
Memory Organization

qWord, half-word alignment (xxxx00 or xxxxx0)


qARM can be set up to access data in either little-
endian or big-endian format, through they default to
little-endian.
168
Features of the ARM Instruction Set
qLoad-store architecture
– Process values which are in registers
– Load, store instructions for memory data accesses
q3-address data processing instructions
qConditional execution of every instruction
qLoad and store multiple registers
qShift, ALU operation in a single instruction
qOpen instruction set extension through the
coprocessor instruction
qVery dense 16-bit compressed instruction set
(Thumb)

169
Coprocessors

– Up to 16 coprocessors can be defined


– Expands the ARM instruction set
– Each coprocessor can have up to 16 private registers of
any reasonable size
– Load-store architecture
170
Thumb
qThumb is a 16-bit instruction set
– Optimized for code density from C code
– Improved performance form narrow memory
– Subset of the functionality of the ARM instruction set
qCore has two execution states – ARM and Thumb
– Switch between them using BX instruction
qThumb has characteristic features:
– Most Thumb instructions are executed unconditionally
– Many Thumb data process instruction use a 2-address
format
– Thumb instruction formats are less regular than ARM
instruction formats, as a result of the dense encoding.

171
I/O System
qARM handles input/output peripherals as memory-
mapped with interrupt support
qInternal registers in I/O devices as addressable
locations with ARM’s memory map read and written
using load-store instructions
qInterrupt by normal interrupt (IRQ) or fast interrupt
(FIQ)
qInterrupt input signals are level-sensitive and
maskable
qMay include Direct Memory Access (DMA) hardware

172
ARM instruction set

173
qARM assembly language program
– ARM development board or ARM emulator
qARM instruction set
– Standard ARM instruction set
– A compressed form of the instruction set, a subset of the
full ARM instruction set is encoded into 16-bit instructions
– Thumb instruction
– Some ARM cores support instruction set extensions to
enhance signal processing capabilities

174
Instructions
qData processing instructions
qData transfer instructions
qControl flow instructions

175
Conditional Execution
qMost instruction sets only allow branches to be
executed conditionally.
qHowever by reusing the condition evaluation
hardware, ARM effectively increase number of
instruction
– All instructions contain a condition field which determines
whether the CPU will execute them
– Non-executed instruction still take up 1 cycle
• To allow other stages in the pipeline to complete
qThis reduces the number of branches which would
stall the pipeline
– Allows very dense in-line code
– The time penalty of not executing several conditional
instructions is frequently less than overhead of the branch
or instruction call that would otherwise be needed
176
Condition code
31 28 27 0
con
d
Opcode Mnemonic
[31:28] extension Interpretation Status flag state for execution
0000 EQ Equal / equals zero Z set
0001 NE Not equal Z clear
0010 CS/HS Carry set / unsigned higher or some C set
0011 CC/LO Carry clear / unsigned lower C clear
0100 MI Minus / negative N set
0101 PL Plus / positive or zero N clear
0110 VS Overflow V set
0111 VC No overflow V clear
1000 HI Unsigned higher C set and Z clear
1001 LS Unsigned lower or same C clear or Z set
1010 GE Signed greater than or equal N equals V
1011 LT Signed less than N is not equal to V
1100 GT Signed greater than Z clear and N equals V
1101 LE Signed less than or equal Z sets or N is not equal to V
1110 AL Always any
1111 NV Never (do not use!) none

177
Example of Conditional Execution
q An unusual feature of the ARM instruction set is that
conditional execution applies not only to branches but to all
ARM instructions
CMP r0,#5 CMP r0,#5
BEQ Bypass ;if (r0!=5) ADDNE r1,r1,r0
ADD r1,r1,r0 ;{r1=r1+r0} SUBNE r1,r1,r2
SUB r1,r1,r2
Bypass …

q Whenever the conditional sequence is 3 instructions or


fewer it is better (smaller and faster) to exploit conditional
execution than to use a branch
CMP r0,r1
if((a==b)&&(c==d)) CMPEQ r2,r3
e++;
ADDEQ r4,r4,#1
178
Using and Updating the condition Field
q To execute an instruction conditionally, simply postfix it with
the appropriate condition:
– For example an add instruction takes the form
• ADD r0, r1, r2 ; r0 = r1 + r2 (ADDAL)
– To execute this only if the zero flag is set
• ADDEQ r0, r1, r2 ; r0 = r1 + r2 iff zero flag set
q By default, data processing operations do not affect the
condition flags
– With comparison instructions this is the only effect
q To cause the condition flags to be updated, the S bit of the
instruction needs to be set by postfixing the instruction (and
any condition codes) with an “S”.
– For example to add two numbers and set the condition flags:
• ADDS r0, r1, r2 ; r0 = r1 + r2 and set flags

179
Data Processing Instruction (1/3)
q Consist of
– Arithmetic (ADD, SUB, RSB)
– Logical (BIC, AND)
– Compare (CMP, TST)
– Register movement (MOV, MVN)
q All operands are 32-bit wide; come from registers or
specified as literal in the instruction itself
q Second operand sent to ALU via barrel shifter
q 32-bit result placed in register; long multiply instruction
produces 64-bit result
q 3-address instruction format
– 2 source operands and 1 destination register
– One source is always a register, the second may be a register, a
shifted register or an immediate value

180
Data Processing Instruction (2/3)
q Allows direct control of whether or not the condition codes
are affected by S bit (condition code unchanged when S = 0)
– N = 1 if the result is negative; 0 otherwise (i.e. N = bit 31 of the result)
– Z = 1 if the result is zero; 0 otherwise
– C = 1 carry out from the ALU when ADD, ADC, SUB, SBC, RSB,
RSC, CMP, or CMN; carry out from the shifter
– V = 1 if overflow from bit 30 to bit 31; 0 if no overflow
(V is preserved in non-arithmetic operations)
q PC may be used as a source operand (address of the
instruction plus 8) except when a register-specified shift
amount is used
q PC may be specified as the destination register, the
instruction is a form of branch (return from a subroutine)

181
Data Processing Instruction (3/3)
31 28 27 26 25 24 21 20 19 16 15 12 11 0

cond 00 # opcode S Rn Rd operand 2

destination register
first operand register
set condition codes
arithmetic/logic function

25 11 8 7 0

1 #rot 8-bit immediate

immediate alignment
11 7 6 5 4 3 0

#shift Sh 0 Rm

25 immediate shift length


0 shift type
second operand register
11 8 7 6 5 4 3 0

Rs 0 Sh 1 Rm

register shift length

182
Simple Register Operands (1/2)
qArithmetic Operations
ADD r0,r1,r2 ;r0:=r1+r2
ADC r0,r1,r2 ;r0:=r1+r2+C
SUB r0,r1,r2 ;r0:=r1–r2
SBC r0,r1,r2 ;r0:=r1–r2+C–1
RSB r0,r1,r2 ;r0:=r2–r1, reverse subtraction
RSC r0,r1,r2 ;r0:=r2–r1+C–1
– By default data processing operations do no affect the
condition flags

qBit-wise Logical Operations


AND r0,r1,r2 ;r0:=r1ANDr2
ORR r0,r1,r2 ;r0:=r1ORr2
EOR r0,r1,r2 ;r0:=r1XORr2
BIC r0,r1,r2 ;r0:=r1AND(NOT r2), bit clear

183
Simple Register Operands (2/2)
qRegister Movement Operations
– Omit 1st source operand from the format
MOV r0,r2 ;r0:=r2
MVN r0,r2 ;r0:=NOT r2, move 1’s complement

qComparison Operations
– Not produce result; omit the destination from the format
– Just set the condition code bits (N, Z, C and V) in CPSR
CMP r1,r2 ;set cc on r1 - r2, compare
CMN r1,r2 ;set cc on r1 + r2, compare negated
TST r1,r2 ;set cc on r1 AND r2, bit test
TEQ r1,r2 ;set cc on r1 XOR r2, test equal

184
Immediate Operands
qReplace the second source operand with an
immediate operand, which is a literal constant,
preceded by “#”
ADD r3,r3,#1 ;r3:=r3+1
AND r8,r7,#&FF ;r8:=r7[7:0], &:hexadecimal

qSince the immediate value is coded within the 32


bits of the instruction, it is not possible to enter
every possible 32-bit value as an immediate.

Immediate = (0 → 255) × 22n where 0  n  12

185
Shift Register Operands
– ADD
r3,r2,r1,LSL#3 ;r3 := 31 0 31 0

r2 + 8 * r1
• A single instruction executed in
a single cycle 00000 00000

q LSL: Logical Shift Left by 0 to LSL #5 LSR #5

31 places, 0 filled at the lsb 31

0
0 31

1
0

end
q LSR, ASL (Arithmetic Shift 00000 0 11111 1

Left), ASR, ROR (Rotate ASR #5 , positive operand ASR #5 , negative operand

Right), RRX (Rotate Right 31 0 31 0

eXtended by 1 place)
C

– ADD r5,r5,r3,LSL r2 ; C C
r5:=r5+r3*2r2
ROR #5 RRX
– MOV r12,r4,ROR r3
;r12:=r4 rotated right
by value of r3 186
Multiply Instructions (1/2)
q32-bit product (Least Significant)
– MUL{<cond>}{S} Rd,Rm,Rs
– MLA{<cond>}{S} Rd,Rm,Rs,Rn
MUL r4,r3,r2; r4:=(r3*r2)[31:0]
MLA r4,r3,r2,r1; r4:=(r3*r2+r1)[31:0]
q64-bit Product
– <mul>{<cond>}{S} RdHi,RdLo,Rm,Rs
– <mul> is UMULL,UMLAL,SMULL,SMLAL
Opcode Mnemoni c Meani ng Effect
[23:21]
000 MUL Multiply (32-bit result) Rd := (Rm * Rs) [31:0]
001 MLA Multiply-accumulate (32-bit result) Rd := (Rm * Rs + Rn) [31:0]
100 UMULL Unsigned multiply long RdHi:RdLo := Rm * Rs
101 UMLAL Unsigned multiply-accumulate long RdHi:RdLo += Rm * Rs
110 SMULL Signed multiply long RdHi:RdLo := Rm * Rs
111 SMLAL Signed multiply-accumulate long RdHi:RdLo += Rm * Rs
187
Multiply Instructions (2/2)
qBooth’s algorithm is used to perform integer
multiplication
– Instructions will early terminate wherever possible
– On ARM7TDMI Mul will execute in minimum of 2 clock
cycles and maximum of 5 clock cycles
qRestrictions on use:
– Rd and Rm cannot be the same register (can be avoided
by swapping over Rm and Rs – multiplication is
commutative)

188
Multiplication by a Constant
qMultiplication by a constant equals to a ((power of 2)
+/- 1) can be done in a single cycle
– Using MOV, ADD or RSB with an inline shift
qExample: r0 = r1 * 5
qExample: r0 = r1 + (r1 * 4)
– ADD r0,r1,r1,LSL #2 ;r0:=r1+r1*4
qCan combine several instruction to carry out other
multiplies
qExample: r2 = r3 * 119
qExample: r2 = r3 * 17 * 7
qExample: r2 = r3 * (16 + 1) * (8 - 1)
– ADD r2,r3,r3,LSL #4 ;r2:=r3*17
– RSB r2,r2,r2,LSL #3 ;r2:=r2*7
189
Loading Constants (1/2)
q No single ARM instruction can load a 32-bit immediate
constant directly into a register
– All ARM instructions are 32-bit long
– ARM instructions do not use the instruction stream as data
q The data processing instruction format has 12 bits available
for operand 2 (refer to P.44)
– If used directly, this would only give a range of 4096
q Instead it is used to store 8-bit constants, give a range of 0-
255
q These 8 bits can then be rotated right through an even
number of positions
q This gives a much larger range of constants that can be
directly loaded, through some constants will still need to be
loaded from memory

190
Loading Constant (2/2)
qTo load a constant, simply move the required value
into a register – the assembler will convert to the
rotate form for us
– MOV r0,#4096 ;MOV r0,#&1000 (0x40 ror 26)

qThe bitwise complements can also be formed using


MVN:
– MOV r0,#&FFFFFFFF ;MVN r0,#0

qValue that cannot be generated in this way will


cause an error

191
Loading 32-bit Constants
q To allow larger constants to be loaded, the assembler offers
a pseudo-instruction:
– LDR Rd,=const
q This will either:
– Produce a MOV or MVN instruction to generate the value (if possible)
or
– Generate a LDR instruction with a PC-relative address to read the
constant from a literal pool (constant data area embedded in the
code)
q For example
– MOV r0,=&FF ;MOV r0,#0xFF
– LDR r0,=&55555555 ;LDR r0,[PC,#Imm10]
q As this mechanism will always generate the best instruction
for a given case, it is the recommended way of loading
constant
192
Data Transfer Instructions
qThree basic forms to move data between ARM
registers and memory
– Single register load and store instruction
• A byte, a 16-bit half word, a 32-bit word
– Multiple register load and store instruction
• To save or restore workspace registers for procedure entry and
exit
• To copy blocks of data
– Single register swap instruction
• A value in a register to be exchanged with a value in memory
• To implement semaphores to ensure mutual exclusion on
accesses

193
Single Register Data Transfer
qWord transfer
– LDR / STR
qByte transfer
– LDRB / STRB
qHalfword transfer
– LDRH / STRH
qLoad single byte or halfword-load value and sign
extended to 32 bits
– LDRSB / LDRSH
qAll of these can be conditionally executed by insert-
ing the appropriate condition code after STR/LDR
– LDREQB
194
Addressing mode
qRegister-indirect addressing
qBase-plus-offset addressing
– Base register
• r0 – r15
– Offset, and or subtract an unsigned number
• Immediate
• Register (not PC)
• Scaled register (only available for word and unsigned byte
instructions)
qStack addressing
qBlock-copy addressing

195
Register-Indirect Addressing
qUse a value in one register (base register) as a
memory address
LDR r0,[r1] ;r0:=mem32[r1]
STR r0,[r1] ;mem32[r1]:=r0

qOther forms
– Adding immediate or register offsets to the base address

196
Initializing an Address Pointer
qA small offset to the program counter, r15
– ARM assembler has a “pseudo” instruction, ADR
qAs an example, a program which must copy data
from TABLE1 to TABLE2, both of which are near to
the code
Copy ADR r1,TABLE1 ;r1 points to TABLE1
ADR r2,TABLE2 ;r2 points to TABLE2

TABLE1
… ;<source>
TABLE2
… ;<destination>

197
Base-plus-offset Addressing (1/2)
qPre-indexing
LDR r0,[r1,#4] ;r0:=mem32[r1+4]
– Offset up to 4K, added or subtracted, (# -4)

qPost-indexing
LDR r0,[r1],#4 ;r0:=mem32[r1], r1:=r1+4
– Equivalent to a simple register-indirect load, but faster,
less code space

qAuto-indexing
LDR r0, [r1,#4]! ;r0:=mem32[r1+4], r1:=r1+4
– No extra time, auto-indexing performed while the data is
being fetched from memory
198
Base-plus-offset Addressing (2/2)

199
Multiple Register Data Transfer (1/2)
q The load and store multiple instructions (LDM/STM) allow
between 1 and 16 registers to be transferred to or from
memory
– Order of register transfer cannot be specified, order in the list is
insignificant
– Lowest register number is always transferred to/from lowest memory
location accessed
q The transferred registers can be either
– Any subset of the current bank of registers (default)
– Any subset of the user mode bank of registers when in a privileged
mode (postfix instruction with a “^”)
q Base register used to determine where memory access
should occur
– 4 different addressing modes
– Base register can be optionally updated following the transfer (using
“!”)

200
Multiple Register Data Transfer (2/2)
q These instruction are very efficient for
– Moving block of data around memory
– Saving and restoring context – stack
q The direction that the base pointer moves through memory is
given by the postfix to the STM/LDM instruction
– STMIA/LDMIA: Increment After
– STMIB/LDMIB: Increment Before
– STMDA/LDMDA: Decrement After
– STMDB/LDMDB: Decrement Before
q Allow any subset (or all, r0 to r15) of the 16 registers to be
transferred with a single instruction

LDMIA r1,{r0,r2,r5} ;r0:=mem32[r1]


;r2:=mem32[r1+4]
;r5:=mem32[r1+8]

201
Stack Processing
q The stack type to be used is given by the postfix to the
instruction:
– STMFD/LDMFD: Full Descending stack
– STMFA/LDMFA: Full Ascending stack
– STMED/LDMED: Empty Descending stack
– STMEA/LDMEA: Empty Ascending stack
q Note: ARM Compilers will always use a Full descending
stack

202
Swap Memory and Register Instructions
qSyntax
– SWP{<cond>}{B} Rd,Rm,[Rn]
– Rd <- [Rn], [Rn] <- Rm

qCombine a load and a store of a word or an


unsigned byte in a single instruction

qExample
ADR r0,SEMAPHORE
SWPB r1,r1,[r0] ;exchange byte

203
Status Register to General Register
Transfer instructions
qSyntax
– MRS{<cond>} Rd,CPSR|SPSR

qThe CPSR or the current mode SPSR is copied into


the destination register. All 32 bits are copied.

qExample
MRS r0,CPSR
MRS r3,SPSR

204
General Register to Status Register
Transfer instructions
qSyntax
– MSR{<cond>}
CPSR_<field>|SPSR_<field>,#<32-bit
immediate>
– MSR{<cond>} CPSR_<field>|SPSR_<field>,Rm
– <field> is one of
• c – the control field PSR[7:0]
• x – the extension field PSR[15:8]
• s – the status field PSR[23:16]
• f – the flag field PSR[31:24]
qExample
– Set N, X, C, V flags
• MSR CPSR_f, #&f0000000

205
Branch Instructions
q Syntax
– Branch: B{<cond>} Label
– Branch with Link: BL{<cond>} subroutine_label

31 28 27 25 24 23 0
cond 101 L 24-bit signed word offset

Link bit
0 = Branch
1 = Branch with Link
Condition field

q The PC-relative offset for branch instructions is calculated by:


– Taking the difference between the branch instruction and the target
address minus 8 (to allow for the pipeline)
– This gives a 26 bit offset which is right shifted 2 bits (as the bottom
two bits are always zero as instruction are word-aligned) and stored
into the instruction encoding
– This gives a range of +/- 32Mbytes.
206
Conditional Branch (1/2)
qThe branch has a condition associated with it and it
is only executed if the condition codes have the
correct value – taken or not taken

MOV r0,#0 ;initialize counter


Loop …
ADD r0,r0,#1 ;increment loop counter
CMP r0,#10 ;compare with limit
BNE Loop ;repeat if not equal
;else fail through

207
Conditional Branch (2/2)
B ran c h In t e rp re t at i o n No rmal us e s
B Unconditional Always take this branch
BAL Always Always take this branch
BEQ Equal Comparison equal or zero result
BNE Not equal Comparison not equal or non-zero result
BPL Plus Result positive or zero
BMI Minus Result minus or negative
BCC Carry clear Arithmetic operation did not give carry-out
BLO Lower Unsigned comparison gave lower
BCS Carry set Arithmetic operation gave carry-out
BHS Higher or same Unsigned comparison gave higher or same
BVC Overflow clear Signed integer operation; no overflow occurred
BVS Overflow set Signed integer operation; overflow occurred
BGT Greater than Signed integer comparison gave greater than
BGE Greater or equal Signed integer comparison gave greater or equal
BLT Less than Signed integer comparison gave less than
BLE Less or equal Signed integer comparison gave less than or equal
BHI Higher Unsigned comparison gave higher
BLS Lower or same Unsigned comparison gave lower or same
208
Examples
qUnconditional jump qConditional subroutine
B LABEL call
… CMP r0,#5
LABEL … BLLT SUB1 ;if r0<5,
qLoop ten times ;call sub1
MOV r0,#10 BLGE SUB2 ;else call
Loop … ;SUB2
SUBS r0,#1
BNE Loop

qCall a subroutine
BL SUB

SUB …
MOV PC,r14
209
Branch, Branch with Link and eXchange
qB{L}X{<cond>} Rm
– The branch target is specified in a register, Rm
– Bit[0] of Rm is copied into the T bit in CPSR; bit[31:1] is
moved into PC
– If Rm[0] is 1, the processor switches to execute Thumb
instructions and begins executing at the address in Rm
aligned to a half-word boundary by clearing the bottom bit
– If Rm[0] is 0, the processor continues executing ARM
instructions and begins executing at the address in Rm
aligned to a word boundary by clearing Rm[1]
qBLX <target address>
– Call Thumb subroutine from ARM
– The H bit (bit 24) is also added into bit 1 of the resulting
addressing, allowing an odd half-word address to be
selected for the target instruction which will always be a
Thumb instruction
210
Software Interrupt (SWI)
qSWI{<cond>}<24-bit immediate>
– Used for calls to the operating system and is often called
a “supervisor call”
– It puts the processor into supervisor mode and begins
executing instruction from address 0x08 (refer to P.21)
• Save the address of the instruction after SWI in r14_svc
• Save the CPSR in SPSR_svc
• Enter supervisor mode and disable IRQs by setting CPSR[4:0] to
100112 and CPSR[7] to 1
• Set PC to 0816 and begin executing the instruction there
– The 24-bit immediate does not influence the operation of
the instruction but may be interpreted by the system code

211
Supervisor Calls
qThe supervisor is a program which operates at a
privileged level, which means that it can do things
that a use-level program cannot do directly (e.g.
input or output)
qSWI instruction
– Software interrupt or supervisor call

SWI SWI_WriteC ;output r0[7:0]


SWI SWI_Exit ;return to monitor program

212
Coprocessor Instructions
qThe ARM architecture supports 16 coprocessors
qThe instructions for each coprocessor occupy a
fixed part of the ARM instruction set
– If the appropriate coprocessor is not present in the system,
an undefined instruction exception occurs.
qThere are three types of coprocessor instruction
– Coprocessor data processing
• CDP: Initiate a coprocessor data processing operation
– Coprocessor register transfers
• MRC: Move to ARM register from coprocessor register
• MCR: Move to Coprocessor register from ARM register
– Coprocessor memory transfers
• LDC: Load coprocessor register from memory
• STC: Store from coprocessor register to memory

213
ARM Instruction Set Summary (1/4)

214
ARM Instruction Set Summary (2/4)

215
ARM Instruction Set Summary (3/4)

216
ARM Instruction Set Summary (4/4)

217
ARM Instruction Set Format

218
Summary
q ARM architecture q Instruction set
– Load/Store architecture – Conditional execution
– Fixed-length 32-bit – 32-bit ARM instruction
architecture • Data processing instructions
– 3-address instruction formats – Arithmetic/Logical/Compare
/Multiply
– 37 registers
• Data transfer instructions
– Little endian/big endian – Load/Store/Swap
– Memory maped IO • Control flow instructions
– Coprocessors – Branch/SWI
– 16-bit Thumb instruction (next
class)

219
Content

qThe ARM processor


qARM instruction set
qSummary
Homework
q ARM architecture
– Which are the characteristics of ARM architecture? What advantages
do they bring?

221

You might also like