Post on 16-Jul-2020
Chapters3ARMAssemblyEmbeddedSystemswithARMCortext-M
Updated:Wednesday,February7,2018
Programminglanguages-Categories
Efficient,morecomplex
Lesscomplex,notasefficient
Interpretedbasedonthemachine
Programminglanguages-InterpreterVs.Compiler
AssemblerconversinstructionsintoMachineLanguage1sand0s.
CCompiler
AssemblersandCCompilers
AssemblersandCCompilersIDE-
IntegratedDevelopmentEnvironment
ARMAssembly• ModernARMprocessorshaveseveralinstructionsets:• Thefully-featured32-bitARMinstructionset,• Themorerestricted,butspaceefficient,16-bit Thumb instructionset,• Thenewermixed16/32-bit Thumb-2 instructionset,• Jazelle DBX forJavabytecodes,• The NEON 64/128-bitSIMDinstructionset,• The VFP vectorfloatingpointinstructionset.• à Thumb-2istheprogressionofThumb(strictlyitisThumbv3).Itimprovesperformancewhilstkeepingthecodedensitytightbyallowingamixtureof16- and32-bitinstructions.
http://www.davespace.co.uk/arm/introduction-to-arm/instruction-sets.html
LevelsofProgramCodeCCodeà AssemblyàMachineLanguage
8
} High-levellanguage} Levelofabstraction
closertoproblemdomain
} Providesforproductivityandportability
CProgram
Compile Assemble
AssemblyProgram
} Assemblylanguage} Textualrepresentation
ofinstructions
MachineProgram
} Hardwarerepresentation} Binarydigits(bits)} Encodedinstructions
anddata
001000010000000000100000000000001110000000000001010001000000000100011100010000000010100000001010110111001111101110111111000000001110011111111110
int main(void){int i;int total = 0;for (i = 0; i < 10; i++) {total += i;
} while(1); // Dead loop
}
LevelsofProgramCodeCCodeà AssemblyàMachineLanguage
9
MachineProgram
} Hardwarerepresentation} Binarydigits(bits)} Encodedinstructionsand
data
001000010000000000100000000000001110000000000001010001000000000100011100010000000010100000001010110111001111101110111111000000001110011111111110
;MOVSr1,#0x00;MOVSr2,#0x01;ADDSr3,r1,r2;MOVSr0,#0x00;BXlr
21002201188B20004770
InHex
AssemblyInstructionSetsforCortex-M
10fromarm.com
Examples:• ADD• AND• CMP• SUB• MUL• MOV• etc.
AssemblyInstructionsSupported
11
• Arithmeticandlogic• Add,Subtract,Multiply,Divide,Shift,Rotate
• Datamovement• Load,Store,Move
• Compareandbranch• Compare,Test,If-then,Branch,compareandbranchonzero
• Miscellaneous• Breakpoints,waitforevents,interruptenable/disable,datamemorybarrier,datasynchronizationbarrier
Compare&Branch DataMovement
Misc. Arithmetic
ARMInstructionFormat
12
label mnemonic operand1, operand2, operand3 ; comments
} Labelisareferencetothememoryaddressofthisinstruction.} Mnemonicrepresentstheoperationtobeperformed(ADD,SUB,etc.).} Thenumberofoperands varies,dependingoneachspecificinstruction.
Someinstructionshavenooperandsatall.} Typically,operand1 isthedestination register,andoperand2 andoperand3 are
sourceoperands.} operand2 isusuallyaregister.} operand3 maybearegister,animmediatenumber,aregistershiftedtoa
constantamountofbits,oraregisterplusanoffset(usedformemoryaccess).
} Everythingafterthesemicolon“;”isacomment,whichisanannotationexplicitlydeclaringprogrammers’intentionsorassumptions.
ARMInstructionFormat
13
label mnemonic operand1, operand2, operand3 ; comments
target ADD r0, r2, r3 ; r0 = r2 + r3
label mnemonic commentdestinationoperand
2nd sourceoperand
1st sourceoperand
ARMInstructionFormat
14
label mnemonic operand1, operand2, operand3 ; comments
Examples:VariantsoftheADDinstructionADD r1, r2, r3 ; r1 = r2 + r3ADD r1, r3 ; r1 = r1 + r3ADD r1, r2, #4 ; r1 = r2 + 4ADD r1, #15 ; r1 = r1 + 15
Remember:Rhastwocomponents:• RegisterAddress• RegisterContent
FirstAssembly
15
AssemblyDirectives
16
AREA Make a new block of data or codeENTRY Declare an entry point where the program execution startsALIGN Align data or code to a particular memory boundaryDCB Allocate one or more bytes (8 bits) of dataDCW Allocate one or more half-words (16 bits) of dataDCD Allocate one or more words (32 bits) of dataSPACE Allocate a zeroed block of memory with a particular sizeFILL Allocate a block of memory and fill with a given value.EQU Give a symbol name to a numeric constantRN Give a symbol name to a registerEXPORT Declare a symbol and make it referable by other source filesIMPORT Provide a symbol defined outside the current source fileINCLUDE/GET Include a separate source file within the current source filePROC Declare the start of a procedureENDP Designate the end of a procedureEND Designate the end of a source file
} DirectivesareNOT instruction;allocatespaceanddefinetypesinmanycases.Theyareusedtoprovidekeyinformationforassembly.
Startofnewdataset;Atleastonecodeareaisrequiredperprogram;couldbe
READONLYorREADWRITE
ReferstoPROCEDUREandEndofPROCEDURE;itdefinesthefunction;
similartomain()inC
ENDofsourcefile
Typically2^N
INCLUDE constants.s ; Load Constant Definitions
ForExampleINCLUDE constants.s; Load Constant Definitions
Let’sPracticeFirst….
AssemblyEmulator
• Gotohttps://salmanarif.bitbucket.io/visual/index.html• Downloadtheappropriateversionforyourcomputer• Thisisthelistofsupportedinstructions:https://salmanarif.bitbucket.io/visual/supported_instructions.html
CODE
CPUREGISTORS
RunyourAssemblyCode MoveONEinstructionatatime
WhatisyourfinalPCvalue?
TryThis&AnswertheQuestions…..
Let’sContinuewithSomeSimpleCommands….
Let’sTakeaMOV&MVNCommands
• MOVr0,#42• Movetheconstant42intoregisterR0.
• MOVr2,r3• MovethecontentsofregisterR3intoregisterR2.
• MVNr1,r0• R1=NOT(R0)=-43
• MOVr0,r0• ANOP(nooperation)instruction.
• <operation>• MOV – move• Rd:=Operand2
• MVN – moveNOT• Rd:=0xFFFFFFFFEOROperand2
ArithmeticOperation
• <operation>• ADD – Add
• Rd:=Rn+Operand2• ADC – AddwithCarry
• Rd:=Rn+Operand2+Carry• SUB – Subtract
• Rd:=Rn−Operand2• SBC – SubtractwithCarry
• Rd:=Rn−Operand2−NOT(Carry)• RSB – ReverseSubtract
• Rd:=Operand2−Rn• RSC – ReverseSubtractwithCarry
• Rd:=Operand2−Rn−NOT(Carry)
• ADDr0,r1,r2• R0=R1+R2
• SUBr5,r3,#10• R5=R3−10
• RSBr2,r5,#0xFF00• R2=0xFF00−R5
RSB and RSC subtract in reverse order (e.g. y - x not x - y).
LogicalInstructions
• AND – logicalAND• Rd:=RnANDOperand2
• EOR – ExclusiveOR• Rd:=RnEOROperand2
• ORR – logicalOR• Rd:=RnOROperand2
• BIC – BitwiseClear• Rd:=RnANDNOTOperand2
• ANDr8,r7,r2• R8=R7&R2
• ORRr11,r11,#1• R11|=1
• BICr11,r11,#1• R11&=~1
• EORr11,r11,#1• R11^=1
CompareInstructions:<operation>{cond}Rn,Operand2• <operation>• CMP – compare
• Flagssettoresultof(Rn−Operand2).• CMN – comparenegative
• Flagssettoresultof(Rn+Operand2).• TST – bitwisetest
• Flagssettoresultof(RnANDOperand2).
• TEQ – testequivalence• Flagssettoresultof(RnEOROperand2).
• CMPr0,#42• CompareR0to42.
• CMNr2,#42• CompareR2to-42.
• TSTr11,#1• Testbitzero.
• TEQr8,r9• TestR8equalsR9.
• SUBSr1,r0,#42• CompareR0to42,withresult.
•CMP is like SUB.•CMN is like ADD – subtract of a negative number is the same as add.•TST is like AND.•TEQ is like EOR – exclusive or of identical numbers gives result of zero.
Directive:AREA
26
AREA myData, DATA, READWRITE ; Define a data sectionArray DCD 1, 2, 3, 4, 5 ; Define an array with five integers
AREA myCode, CODE, READONLY ; Define a code sectionEXPORT __main ; Make __main visible to the linkerENTRY ; Mark the entrance to the entire program
__main PROC ; PROC marks the begin of a subroutine... ; Assembly program starts here.ENDP ; Mark the end of a subroutineEND ; Mark the end of a program
• TheAREAdirectiveindicatestotheassemblerthestartofanewdataorcodesection.
• Areasarethebasicindependentandindivisibleunitprocessedbythelinker.
• Eachareaisidentifiedbyanameandareaswithinthesamesourcefilecannotsharethesamename.
• Anassemblyprogrammusthaveatleastonecodearea.
• Bydefault,acodeareacanonlyberead(READONLY)andadataareamaybereadfromandwrittento(READWRITE).
Directive:ENTRY
27
AREA myData, DATA, READWRITE ; Define a data sectionArray DCD 1, 2, 3, 4, 5 ; Define an array with five integers
AREA myCode, CODE, READONLY ; Define a code sectionEXPORT __main ; Make __main visible to the linkerENTRY ; Mark the entrance to the entire program
__main PROC ; PROC marks the begin of a subroutine... ; Assembly program starts here.ENDP ; Mark the end of a subroutineEND ; Mark the end of a program
• TheENTRYdirectivemarksthefirstinstructiontobeexecutedwithinanapplicationprogram.
• Theremustbeexactlyone ENTRYdirectiveinanapplication,nomatterhowmanysourcefilestheapplicationhas.
Directive:END
28
AREA myData, DATA, READWRITE ; Define a data sectionArray DCD 1, 2, 3, 4, 5 ; Define an array with five integers
AREA myCode, CODE, READONLY ; Define a code sectionEXPORT __main ; Make __main visible to the linkerENTRY ; Mark the entrance to the entire program
__main PROC ; PROC marks the begin of a subroutine... ; Assembly program starts here.ENDP ; Mark the end of a subroutineEND ; Mark the end of a program
• TheENDdirectiveindicatestheendofasourcefile.
• Eachassemblyprogrammustendwiththisdirective.
Directive:PROC andENDP
29
AREA myData, DATA, READWRITE ; Define a data sectionArray DCD 1, 2, 3, 4, 5 ; Define an array with five integers
AREA myCode, CODE, READONLY ; Define a code sectionEXPORT __main ; Make __main visible to the linkerENTRY ; Mark the entrance to the entire program
__main PROC ; PROC marks the begin of a subroutine... ; Assembly program starts here.ENDP ; Mark the end of a subroutineEND ; Mark the end of a program
• PROC andENDP aretomarkthestartandendofafunction(alsocalledsubroutineorprocedure).
• Asinglesourcefilecancontainmultiplesubroutines,witheachofthemdefinedbyapairofPROC andENDP.
• PROC andENDP cannotbenested.Wecannotdefineafunctionwithinanotherfunction.
Directive:EXPORTandIMPORT
30
AREA myData, DATA, READWRITE ; Define a data sectionArray DCD 1, 2, 3, 4, 5 ; Define an array with five integers
AREA myCode, CODE, READONLY ; Define a code sectionEXPORT __main ; Make __main visible to the linkerENTRY ; Mark the entrance to the entire program
__main PROC ; PROC marks the begin of a subroutine... ; Assembly program starts here.ENDP ; Mark the end of a subroutineEND ; Mark the end of a program
• TheEXPORTdeclaresasymbolandmakesthissymbolvisibletothelinker.
• TheIMPORTgivestheassemblerasymbolthatisnotdefinedlocallyinthecurrentassemblyfile.Thesymbolmustbedefinedinanotherfile.
• TheIMPORTissimilartothe“extern”keywordinC.
Directive:DataAllocation
31
Directive Description Memory SpaceDCB Define Constant Byte Reserve 8-bit valuesDCW Define Constant Half-word Reserve 16-bit valuesDCD Define Constant Word Reserve 32-bit valuesDCQ Define Constant Reserve 64-bit valuesDCFS Definesingle-precision
floating-pointnumbersReserve 32-bit values
DCFD Definedouble-precisionfloating-pointnumbers
Reserve 64-bit values
SPACE Defined Zeroed Bytes Reserve a number of zeroed bytesFILL Defined Initialized Bytes Reserve and fill each byte with a value
Directive:DataAllocation
32
AREA myData, DATA, READWRITEhello DCB "Hello World!",0 ; Allocate a string that is null-terminated
dollar DCB 2,10,0,200 ; Allocate integers ranging from -128 to 255
scores DCD 2,3.5,-0.8,4.0 ; Allocate 4 words containing decimal values
miles DCW 100,200,50,0 ; Allocate integers between –32768 and 65535
Pi DCFS 3.14 ; Allocate a single-precision floating number
Pi DCFD 3.14 ; Allocate a double-precision floating number
p SPACE 255 ; Allocate 255 bytes of zeroed memory space
f FILL 20,0xFF,1 ; Allocate 20 bytes and set each byte to 0xFF
binary DCB 2_01010101 ; Allocate a byte in binary
octal DCB 8_73 ; Allocate a byte in octal
char DCB ‘A’ ; Allocate a byte initialized to ASCII of ‘A’
Directive:EQU andRN
33
• TheEQU directiveassociatesasymbolicnametoanumericconstant.Similartotheuseof#defineinaCprogram,theEQU canbeusedtodefineaconstantinanassemblycode.
• TheRNdirectivegivesasymbolicnametoaspecificregister.
; Interrupt Number Definition (IRQn)BusFault_IRQn EQU -11 ; Cortex-M3 Bus Fault Interrupt SVCall_IRQn EQU -5 ; Cortex-M3 SV Call Interrupt PendSV_IRQn EQU -2 ; Cortex-M3 Pend SV Interrupt SysTick_IRQn EQU -1 ; Cortex-M3 System Tick Interrupt
Dividend RN 6 ; Defines dividend for register 6Divisor RN 5 ; Defines divisor for register 5
Directive:ALIGN
34
AREA example, CODE, ALIGN = 3 ; Memory address begins at a multiple of 8ADD r0, r1, r2 ; Instructions start at a multiple of 8
AREA myData, DATA, ALIGN = 2 ; Address starts at a multiple of foura DCB 0xFF ; The first byte of a 4-byte word
ALIGN 4, 3 ; Align to the last byte (3) of a word (4)b DCB 0x33 ; Set the fourth byte of a 4-byte wordc DCB 0x44 ; Add a byte to make next data misaligned
ALIGN ; Force the next data to be alignedd DCD 12345 ; Skip three bytes and store the word
Directive:INCLUDEorGET
35
• TheINCLUDEorGETdirectiveistoincludeanassemblysourcefilewithinanothersourcefile.
• ItisusefultoincludeconstantsymbolsdefinedbyusingEQU andstoredinaseparatesourcefile.
INCLUDE constants.s ; Load Constant DefinitionsAREA main, CODE, READONLYEXPORT __main ENTRY
__main PROC...ENDPEND