CS计算机代考程序代写 assembly assembler DT131B

DT131B
Embedded Systems Programming
Lecture 6: Instruction Set and Assembly Programming
Dawit Mengistu (dawit.mengistu@hkr.se)

Why Assembly?
• Assemblerinstructions(code)translatelinebylineto executable machine code
– No extra loops – No extra code
• Becauseonlynecessarycodestepsareexecuted, assembly programs are sometimes the only way to meet real-time requirements.
• Thedurationofexecutionforeverylineofcodeis known.
– Time critical applications, are often written in assembler for better precision in time measurements.
2

Why Assembly?
• Codeisoptimizedandcompactenoughtofit into memory constrained microcontrollers (compared with C or other HLL).
• Assemblyinstructionsaresometimestheonly way to access system resources (registers, memory, I/O.)
• Assembly languages are easier to learn. (Learn only the instruction set of the microcontroller.)
• Easiertotestanddebug.
3

Why NOT Assembly?
• One can write code only using primitive CPU instructions (arithmetic, logic, shift).
• Data size depends on processor (8-bit?, 16-bit?, etc.)
• Time consuming if used to write code for mathematical tasks involving trigonometric, logarithmic, exponential, etc., functions.
• Instruction set is architecture or processor dependent. Not possible to write code that is portable across different architectures.
• Difficult to maintain.
4

Hierarchy of Languages

The Instruction Set
• The complete collection of instructions that are understood by a certain CPU or processor architecture.
• Is the machine code in human readable or hexadecimal (binary) format
• Usually represented by assembly codes because machine code is not ‘human readable’
6

Elements of an Instruction
• Operation code (Op code) – Do this,
• Source Operand reference – To this.
• Result Operand reference – Put the answer here
• Next Instruction Reference
– When you have done that, do this…
7

Review: Instruction Cycle
8

Instruction (Opcode) Representation
• In machine code, each instruction has a unique bit pattern
• For human consumption (programmers) a symbolic representation is used
– e.g. ADD, SUB, LOAD
• Opcodes and operands can also be
represented in this way
– ADD A,B
9

Instruction Types
• Data processing
• Data storage (main memory) • Data movement (I/O)
• Program flow control
10

Types of Operands
• Addresses • Numbers
– Integer/floating point • Characters
– ASCII etc.
• Logical Data
– Bits or flags
11

Number of Operands
• Number of addresses used in an instruction.
• Example:
• A 3 address machine uses 3 addresses – Operand 1, Operand 2, Result
– a = b + c;
– Not common
– Needs very long words to hold everything
12

Number of Operands (cont’)
• 2 addresses : (used in a 2 address machine) – One address doubles as operand and result –a = a + b
– Reduces length of instruction
– Requires some extra work
• Temporary storage to hold some results
13

Number of Operands (cont’)
• 1 address: (used in called 1 address machines) – Implicit second address
– Usually a register (accumulator)
– Common on early machines
14

Number of Operands (cont’)
• 0 (zero) addresses
– All addresses implicit – Uses a stack
– e.g. push a
push b add pop c
–c = a+ b
15

Design Decision: How Many Addresses?
• More addresses means
– More complex (powerful?) instructions
– More registers
• Inter-register operations are quicker
– Fewer instructions per program
• Fewer addresses
– Less complex (powerful?) instructions – More instructions per program
– Faster fetch/execution of instructions
16

Design Decisions (cont’)
• Registers
– Number of CPU registers available
– Which operations can be performed on which registers?
• Addressing modes (later…) • RISC v CISC
17

RISC vs CISC
• RISC:ReducedInstructionSetComputers – 100 –200 instructions
– Includes all variations of addressing modes
– Faster: usually executes instructions in one clock cycle – Difficult to program complex math
• CISC:ComplexInstructionSetComputers – Hundreds of instructions
– Many special purpose, complicated math functions
– Suitable for programming in many high level languages – Mostly appropriate for general purpose computers
18

Types of Operations
• Data Transfer • Arithmetic
• Logical
• Conversion
• I/O
• System Control
• Transfer of Control
19

Data Transfer Instructions
• Specifyaddress:couldbearegisterormemory – Source address
– Destination address – Amount of data
• Maybedifferentinstructionsfordifferent movements
• Oroneinstructionanddifferentaddresses
• Highlydependentonprocessortype(x86,ARM, AVR, etc.)
20

Addressing Modes
• Register addressing – transfers a byte or word from the source register (R2) to the destination register (R1)
MOV R1, R2 ;R1 = R2
• Immediate addressing: – transfers an immediate byte
or word of data into the destination register
MOV R1, 3456h ;R1 = 0x3456
• Direct addressing: moves a byte or word between a
memory location and a register
MOV R1, [1234h] ;1234h is a reachable memory address
21

Addressing Modes (cont’)
• Register Indirect: (base relative or indexed) – transfers a byte or word of data between a register and the memory location addressed by an index or base register
MOV R1, [RB] ;Get data from address indexed by RB
• Base Plus Index: (base relative indexed) – transfers a byte or word of data between a register and the memory location addressed by a base register plus index register
MOV R1, [RB + RI] ;Get data from address indexed by RB+RI
22

Addressing Modes (cont’)
• Register Relative – transfers a byte or word of data between a register and the memory location addressed by an index or base register plus displacement
MOV R1, [RB + 1000h] ;RB is a base register
Combinations of the above addressing modes are also possible.
23

Instruction Types
• Arithmetic
– Add, Subtract, Multiply, Divide
– Signed Integer
– May include
• Increment (a++)
• Decrement (a–) • Negate (-a)
• Logical
– Bitwise AND, OR, XOR, NOT, – Comparison CMP or CP
• ShiftandRotate(nextslide)
24

Shift and Rotate Operations
25

Instruction Types (cont’)
• DataMovement
– Between registers (like assignment)
– From registers to regular memory or stack memory – From memory to registers
• Input/output
– May be specific instructions (e.g. IN, OUT)
– Often uses specific registers
– May be done using data movement instructions (memory mapped)
26

Transfer of Control Operations
• Branch mem_addr (or Jump)
– Unconditionallytransferscontroltoinstructionatmem_addr.
• Conditional Branching:
– BZmem_addr(branchifzero)
• branch to mem_addr if result is zero
– BRNZmem_addr(branchifNOTzero)
• branch to mem_addr if result is not zero
– Other forms of branching may also exist (BRE,BRNE, BRL, BRNLE…)
• Subroutine call (CALL mem_addr) – Controltransferstomem_addr
27

Branch Instruction
28

Stack Usage
• Datamovementinstructionsandsubroutine calls affect the content and position of the stack.
• Aspecialregistercalledstackpointertracksthis storage
• Becareful!StackoperationsuseLIFOfordata storage and retrieval
29

Byte Order
• What order do we read numbers that occupy more than one byte
• e.g. (numbers in hex to make it easy to read)
• 0X12345678 can be stored in 4x8bit locations as follows
30

Byte Order (example)
Address
184
185
186
186
Value (1) Value(2)
12 78 34 56 56 34 78 12
i.e. read top down or bottom up?
• This problem is called endian-ness.
• The system on the left has the least significant byte in the lowest address: called big-endian
• The system on the right has the least significant byte in the highest address: called little-endian
31

Assembly Programming
• Use hexadecimal rather than binary
– Codeasseriesoflines
– Needtoreadinstructionsetandmachinecodetranslations
• Add symbolic names or mnemonics for instructions instead of hexadecimal coding.
• Typical instruction has the following format: mnemonic operand1, operand2
• Optionally, add comment for readability and documentation
Ex: add R0, R1 ;add x and y
32

Programming the AVR
• We shall use the ATMega168 and 328 series microcontrollers.
• These are 8-bit AVR processors.
• Have 32 registers (R0, R1, …, R31)
• The last six registers (R26 – R31) serve as index registers as well.
• Have one status register, stack pointer
• Nodivisionarithmetic!
• Refertothedatasheettolearntheassembler.
33

Programming the AVR (cont’)
• We use the Atmel Studio IDE for writing and testing AVR assembly codes.
• TheIDEhasapowerfuldebuggerandsimulator. • Withthesimulator,youcan:
– test your assembler code without running your code on a real microcontroller;
– See the execution time of your code;
– See the contents of your program and data memory
– See the contents of important registers such as: • Status register
• Program counter • Stack pointer, etc.
34

AVR Instruction Set
The following notation is used in the datasheet.
35

AVR Instruction Examples
36

Instruction Examples (cont’)
Data Movement Examples
37

Instruction Examples (cont’)
Branch Instructions Examples
38

The Status Register (SREG)
Each bit location stores important information about the just completed instruction/operation.
The contents of these fields are used for control (Branching)
39

Programming Examples -1
• Write an AVR assembly code to:
– Perform the task in the C code below:
int X, Y, Z, A, B, C; X = 45;
Y = 32;
Z = X – Y;
A = Z * 2; B = Y / 2; C = A * B;
40

Programming Examples – 2
• Write an AVR assembly code to:
1. Calculate the sum of N 8-bit integers stored in N
consecutive memory locations.
2. Write subroutine (function) that performs the above task.
3. Write a subroutine to calculate the factorial of a number
4. Write a subroutine to arrange numbers in ascending order.
41

References
• Inthezipfile(AVR.zipunderResources)
– Atmel AVR 8-bit Instruction Set Manual
– Beginners Introduction to the Assembly Language of Atmel AVR Microprocessors Gerhard Schmidt, 2017 http://www.avrasmtutorial.net
• Barnett,CoxandO’Cull(2007),EmbeddedC Programming and the Atmel AVR. (Chapter 2)
• AdditionalReading
– William Stallings, Computer Organization and Architecture 8th ed. (2010) – Chapter 12