175
CS2100 Computer Organisation MIPS Programming

cs2100-10-MIPS

  • Upload
    amanda

  • View
    221

  • Download
    0

Embed Size (px)

Citation preview

  • CS2100 Computer Organisation

    MIPS Programming

    MIPS Programming

  • 2011 Sem 1MIPS Programming*RECAP: BELOW YOUR PROGRAMYou write programs in high level programming languages, e.g., C, JavaA+BCompiler translates this into assembly language statementadd A,BAssembler translates this statement into machine language instructions that the processor can execute1000110010100000

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION EXECUTION CYCLEInstruction execution cycle: fetch, decode, execute.Fetch: fetch next instruction (using PC) from memory into IR.Decode: decode the instruction.Execute: execute instruction.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION SET ARCHITECTURE (1/5)Instruction Set Architecture (ISA): an abstraction on the interface between the hardware and the low-level software.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION SET ARCHITECTURE (2/5)The ISA includes everything programmers need to know to make the machine code work correctly.It allows computer designers to talk about functions independently from the hardware that performs them.This abstraction allows many implementations of varying cost and performance to run identical software.Example: Intel x86/IA-32 ISA has been implemented by a range of processors starting from 80386 [1985] to Pentium 4 [2005] Other companies such as AMD and Transmeta have implemented IA-32 ISA as wellA program compiled for IA-32 ISA can execute on any of these implementations

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION SET ARCHITECTURE (3/5)ISA is determined byOrganization of programmable storage.Data types and data structures: encoding and representations.Instruction formats.Instruction (or operation code, opcode) set.Modes of addressing and accessing data items and instructions.Exceptional conditions.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION SET ARCHITECTURE (4/5)Instruction format or encodinghow is it decoded?Location of operands and resultwhere other than memory?how many explicit operands?how are memory operands located?which can or cannot be in memory?Data type and sizeOperationswhat are supported?Successor instructionjumps, conditions, branchesFetch-decode-execute is always done for any instruction!

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION SET ARCHITECTURE (5/5)Instruction set: language of the machine.More primitive than high-level languages (eg: no sophisticated control flow).More restrictive instructions.We will study MIPS instruction set, used by NEC, Nintendo, Silicon Graphics, Sony.Bonus: hope to do a quickie on the x86 instruction set.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ASSEMBLY LANGUAGEMachine codeInstructions are represented in binary1000110010100000 is an instruction that tells one computer to add two numbersHard and tedious for programmerAssembly languageSymbolic version of machine codeHuman readableadd A, B is equivalent to 1000110010100000Assembler translates from assembly language to machine codeAssembly can provide pseudo-instructions. Example: In MIPS, move $t0, $t1 is a pseudo-instructions; the actual instruction is add $t0, $t1, $zero.When considering performance, only real instructions are counted.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*RISC VERSUS CISCComplex Instruction Set Computer (CISC) e.g. x86Single instruction performs complex operationVAX architecture had an instruction to multiply polynomials Smaller program size as memory was premiumComplex implementation, no room for hardware optimizationReduced Instruction Set Computer (RISC) e.g. MIPSKeep the instruction set small and simple, makes it easier to build/optimize hardwareBurden on software to combine simpler operations to implement high-level language statementsPentium 4 decomposes many x86 instructions into a series of internal micro-operations that are executed by the processor core CISC ISA but internal RISC implementation

    MIPS Programming

  • 2011 Sem 1MIPS Programming*CONCEPT #1: DATA STORAGEMemory OrganizationRegistersConcept #1: Data StorageConcept #2: Memory Addressing ModesConcept #3: Operations in the Instruction SetConcept #4: Instruction FormatsConcept #5: Encoding the Instruction SetConcept #6: Compilers View

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MEMORY ORGANIZATION (1/2)The main memory can be viewed as a large, single-dimension array of memory locations.Each location of the memory has an address, which is an index into the array.The memory map on the right contains one byte (8 bits) in every location/address.Byte addressing means the index points to a byte of memory.Word addressing: see next slide.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MEMORY ORGANIZATION (2/2)A word is unit of transfer between processor and memory.Assuming 4-byte words and n-bit address.2n bytes with byte addresses from 0 to 2n 1.2n-2 words with byte addresses 0, 4, 8, , 2n 4.Words are aligned.What are the last two bits of the address of a word, if each word contains 4 bytes? Answer: 00

    MIPS Programming

  • 2011 Sem 1MIPS Programming*REGISTERS (1/3)Fast memories in the processor.Data are transferred from memory to registers for faster processing.Compiler associates variables in program with registers. (What about programs with many variables?)Registers have no type, unlike variables.Code density improves.Modern architectures predominantly use the load-store register architecture.Limited in number. A typical system has 16 to 32 registers.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*REGISTERS (2/3)MIPS assembly language: 32 registers, referred to by a number ($0, $1, , $31) or a name (eg: $a0, $t1).$at (register 1) is reserved for the assembler.$k0-$k1 (registers 26-27) are reserved for the operation system.

    NameRegister numberUsage$zero0Constant value 0$v0-$v12-3Values for results and expression evaluation$a0-$a34-7Arguments$t0-$t78-15Temporaries$s0-$s716-23Program variables

    NameRegister numberUsage$t8-$t924-25More temporaries$gp28Global pointer$sp29Stack pointer$fp30Frame pointer$ra31Return address

    MIPS Programming

  • 2011 Sem 1MIPS Programming*REGISTERS (3/3)Classifying general-purpose register computers:ALU (Arithmetic-Logic Unit) instruction has two or three operands?Add R2, R1 (R2=R2+R1) or Add R3, R2, R1 (R3=R2+R1)How many operands may be memory addresses in an ALU instruction?Zero? One? Two? Three?What are the advantages and disadvantages of each of these options?

    MIPS Programming

  • 2011 Sem 1MIPS Programming*CONCEPT #2: MEMORY ADDRESSING MODEMemory Locations and AddressesMemory OperationsAddressing ModesConcept #1: Data StorageConcept #2: Memory Addressing ModesConcept #3: Operations in the Instruction SetConcept #4: Instruction FormatsConcept #5: Encoding the Instruction SetConcept #6: Compilers View

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MEMORY LOCATIONS AND ADDRESSES (1/3)Memory is viewed as a large one-dimensional array of bits.Group of n bits to store or retrieve in a single operation to/from the memory is a word.A word is usually a multiple of bytes and typically 2, 4 or 8 bytes.Memory is addressed to access a single word or a byte using a distinct address.Given k-bit address, the address space is of size 2k.24-bit address generates 224 (= 16,777,216) addresses or locations. This is 16M.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MEMORY LOCATIONS AND ADDRESSES (2/3)Byte addressability: Successive memory addresses refer to successive byte locations in the memory.Big-endian: most significant byte stored in lowest address.IBM 360/370, Motorola 68000, MIPS (Silicon Graphics), SPARC.Little-endian: least significant byte stored in lowest address.Intel 80x86, DEC VAX, DEC Alpha.

    Example: 0xDEADBEEFBig-endian: Most significant byte first: DE AD BE EF.Little-endian: Least significant byte first: EF BE AD DE.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MEMORY LOCATIONS AND ADDRESSES (3/3)Word alignment: Words are aligned in memory if they begin at a byte address that is a multiple of the number of bytes in a word.Example: If a word consists of 4 bytes, then:

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MEMORY OPERATIONS (1/2)Load (Read): Transfers the contents of a specific memory location to the processor. The processor sends address to the memory, and the memory reads data at that address and sends to processor.Store (Write): Data from the processor is written at a specified memory location. Processor sends address and data to the memory.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MEMORY OPERATIONS (2/2)

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ADDRESSING MODES

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MIPS ADDRESSING MODES (1/4)Register (direct) modeExample: add $r3, $r1, $r2op: opcoders: first source registerrt: second source registerrd: destination registerNote: For illustration only. This is not the exact MIPS syntax.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MIPS ADDRESSING MODES (2/4)Immediate modeExample: addi $r3, $r1, 12op: opcoders: source registerrt: destination registerimmed: constant

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MIPS ADDRESSING MODES (3/4)Displacement mode (base addressing)Example: lw $r1, 100($r2)$r2 = 150; 100($r2) = 88Address = 250

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MIPS ADDRESSING MODES (4/4)PC-relative modeExample: beq $r1, $r2, 6

    MIPS Programming

  • 2011 Sem 1MIPS Programming*CONCEPT #3: OPERATIONS IN THE INSTRUCTION SETStandard Operations in an Instruction SetFrequently Used InstructionsInstructions for Control FlowConcept #1: Data StorageConcept #2: Memory Addressing ModesConcept #3: Operations in the Instruction SetConcept #4: Instruction FormatsConcept #5: Encoding the Instruction SetConcept #6: Compilers View

    MIPS Programming

  • 2011 Sem 1MIPS Programming*STANDARD OPERATIONS

    MIPS Programming

  • 2011 Sem 1MIPS Programming*FREQUENTLY USED INSTRUCTIONSMake these instructions fast!Amdahls law make the common case fast!

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTIONS FOR CONTROL FLOWBranch: conditional (if go to )Jump: unconditional (go to )Procedure calls/returnsAddressing modes for control-flow instructions:PC-relative: destination address = displacement + value in PC (When target address is near the current instruction, it requires only a few bit. Code can run independently of where it is loaded position independence.)Register indirect jumps: a register is specified, which will contain the target address. (Value in the specified register is usually not known at compile time, but is computed at run time.)

    MIPS Programming

  • 2011 Sem 1MIPS Programming*CONCEPT #4: INSTRUCTION FORMATSInstruction LengthInstruction FieldsType and Size of OperandsConcept #1: Data StorageConcept #2: Memory Addressing ModesConcept #3: Operations in the Instruction SetConcept #4: Instruction FormatsConcept #5: Encoding the Instruction SetConcept #6: Compilers View

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION LENGTHVariable-length instructions.Intel 80x86: Instructions vary from 1 to 17 bytes long.Digital VAX: Instructions vary from 1 to 54 bytes long.Require multi-step fetch and decode.Allow for a more flexible (but complex) and compact instruction set.Fixed-length instructions.Used in most RISC (Reduced Instruction Set Computers)MIPS, PowerPC: Instructions are 4 bytes long.Allow for easy fetch and decode.Simply pipelining and parallelism.Instruction bits are scarce.Hybrid instructions: a mix of variable- and fixed-length instructions.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION FIELDSAn instruction consists of opcode and a certain number (possible zero) of operands.Each instruction has a unique opcode, but:How many operands?Are the operands registers or memory?Current high-end processors allow for three register operands.Hence if there are 32 registers, then 3 x 5 = 15 bits are used up for the operands.For every direct memory operand, at least one operand will be taken away.Example: LOAD/STORE instructions only have two operands.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*TYPE AND SIZE OF OPERANDSEncoding in the opcode designates the type of an operand.Add R3, R2, R1Character (8 bits), half-word (eg: 16 bits), word (eg: 32 bits), single-precision floating point (eg: 1 word), double-precision floating point (eg: 2 words).Expectations from any new 32-bit architecture:Support for 8-, 16- and 32-bit integer and 32-bit and 64-bit floating point operations. A 64-bit architecture would need to support 64-bit integers as well.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*CONCEPT #5: ENCODING THE INSTRUCTION SETInstruction EncodingEncoding for Fixed-Length InstructionsConcept #1: Data StorageConcept #2: Memory Addressing ModesConcept #3: Operations in the Instruction SetConcept #4: Instruction FormatsConcept #5: Encoding the Instruction SetConcept #6: Compilers View

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION ENCODING (1/2)How are instructions represented in binary format for execution by the processor?Issues:Code size, speed/performance, design complexity.Things to be decided:Number of registersNumber of addressing modesNumber of operands in an instructionThe different competing forces:Have many registers and addressing modesReduce code sizeHave instruction length that is easy to handle (fixed-length instructions are easy to handle)

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION ENCODING (2/2)Three encoding choices: variable, fixed, hybrid.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ENCODING FOR FIXED-LENGTH INSTRUCTIONS (1/4)How to fit multiple sets of instruction types into a fixed-length instruction format? Work out the most constrained set first.An expanding opcode scheme is one where the opcode has variable lengths for different instructions. This maximizes the instruction bits.Example: Given a fixed-length instruction set where each instruction contains 16 bits. Some instructions (call it type-A) require 2 operands, while other instructions (call it type-B) require only 1 operand. Each operand takes up 5 bits.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ENCODING FOR FIXED-LENGTH INSTRUCTIONS (2/4)If we assume the all opcodes must have the same size, to allow for the maximum number of instructions, the opcodes must be 6 bits long.We see that there are wasted bits, and the maximum total number of instructions is 26 or 64.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ENCODING FOR FIXED-LENGTH INSTRUCTIONS (3/4)If we allow the opcode for type-B instructions to be 11 bits long, we may have a bigger set of instructions.This is known as expanding opcode. Encoding concern: The first 6 bits of the opcode for any type-B instruction must not be identical to the opcode of any of the type-A instructions. (Why?)

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ENCODING FOR FIXED-LENGTH INSTRUCTIONS (4/4)What is the maximum total number of instructions possible?Answer: 1 + (26 1) 25 = 1 + 6332 = 2017.How? Let there be 1 type-A instruction (assume the opcode is 000000 the choice is arbitrary), then there are (26 1) valid patterns for the first 6 bits of the type-B instructions, followed by any 5 bits.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*EXAMPLEDesign an expanding opcode for the following to be encoded in a 36-bit instruction format. An address takes up 15 bits and a register number 3 bits.7 instructions with two addresses and one register number.500 instructions with one address and one register number.50 instructions with no address or register. One possible answer:

    MIPS Programming

  • 2011 Sem 1MIPS Programming*CONCEPT #6: COMPILERS VIEWConsiderations for CompilerConcept #1: Data StorageConcept #2: Memory Addressing ModesConcept #3: Operations in the Instruction SetConcept #4: Instruction FormatsConcept #5: Encoding the Instruction SetConcept #6: Compilers View

    MIPS Programming

  • 2011 Sem 1MIPS Programming*CONSIDERATIONS FOR COMPILEREase of compilation.Orthogonality: no special registers, few special cases, all operand modes available with any data type or instruction type.Completeness: support for a wide range of operations and target applications.Regularity: no overloading for the meanings of instruction fields.Streamlined: resource needs easily determined.Provide at least 16 general-purpose registers plus separate floating-point registers.Be sure all addressing modes apply to all data transfer instructions.Aim for a minimalist instruction set.

    MIPS Programming

  • MIPS ASSEMBLY LANGUAGE

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MIPS ASSEMBLY LANGUAGEIn MIPS assembly language, each instruction executes a simple commandEach line of assembly code contains at most 1 instructionInstructions are related to operations (+, -, *, /, =) in C/Java# is used for commentsAnything from # mark to end of line is a comment and will be ignoredadd $t0, $s1, $s2 # tmp = b + csub $s0, $t0, $s3 # a = tmp - d

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ARITHMETIC: ADDITIONAddition in assemblyC: a = b + c; MIPS: add $s0, $s1, $s2 $s0 variable a$s1 variable b$s2 variable cNatural number of operands for an instruction is 3 (2 sources + 1 destination)Why?Keep the hardware simpleDesign principle: Simplicity favors regularity

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION SYNTAX add $s0, $s1, $s2$s0 = $s1 + $s2

    MIPS Programming

  • 2011 Sem 1MIPS Programming*RECALL: MIPS REGISTERSMIPS assembly language: 32 registers, referred to by a number ($0, $1, , $31) or a name (eg: $a0, $t1).$at (register 1) is reserved for the assembler.$k0-$k1 (registers 26-27) are reserved for the operation system.

    NameRegister numberUsage$zero0Constant value 0$v0-$v12-3Values for results and expression evaluation$a0-$a34-7Arguments$t0-$t78-15Temporaries$s0-$s716-23Program variables

    NameRegister numberUsage$t8-$t924-25More temporaries$gp28Global pointer$sp29Stack pointer$fp30Frame pointer$ra31Return address

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ARITHMETIC: SUBTRACTIONSubtraction in assemblyC:a = b c; MIPS:sub $s0, $s1, $s2 $s0 variable a$s1 variable b$s2 variable cPositions of $s1 and $s2 (i.e., source1 and source2) are important for subtraction$s0 = $s1 - $s2

    MIPS Programming

  • 2011 Sem 1MIPS Programming*COMPLEX STATEMENTS (1/2)C statementa = b + c - d;A single instruction can handle at most two source operands.Break it up into multiple instructions and use temporary register $t0 $t7add $t0, $s1, $s2 # tmp = b + csub $s0, $t0, $s3 # a = tmp - d A single line of C statement may break up into several lines of MIPS assemblyWho is doing this break up when you write high-level language code?

    MIPS Programming

  • 2011 Sem 1MIPS Programming*COMPLEX STATEMENTS (2/2)C statementf = (g + h) (i + j);Break it up into multiple instructionsReplace variables by registers $s0 $s7Use two temporary registers $t0, $t1 add $t0, $s1, $s2 # tmp0 = g + h add $t1, $s3, $s4 # tmp1 = i + j sub $s0, $t0, $t1 # a = tmp0 tmp1

    MIPS Programming

  • 2011 Sem 1MIPS Programming*TRY IT YOURSELFz = a + b + c + d;a:$s0 b:$s1 c:$s2 d:$s3 z:$s4

    z = (a b) + c;a:$s0 b:$s1 c:$s2 z:$s4 add $t0, $s0, $s1 # tmp0 = a + badd $t1, $s2, $s3 # tmp1 = c + d add $s4, $t0, $t1 # z = tmp0 + tmp1sub $t0, $s0, $s1 # tmp0 = a - badd $s4, $t0, $s2 # z = tmp0 + c

    MIPS Programming

  • 2011 Sem 1MIPS Programming*CONSTANT/IMMEDIATE OPERANDSImmediates are numerical constantsThey appear often in operations; so there is special instruction for themAdd immediate (addi) C:a = a + 4; MIPS:addi $s0, $s0, 4 # $s0 = $s0 + 4 Syntax is similar to add instruction; but source2 is a constant instead of registerDesign principle: Make common case fastNo subi instruction in MIPS why?

    MIPS Programming

  • 2011 Sem 1MIPS Programming*REGISTER ZEROOne particular immediate, the number zero (0), appears very often in codeDefine register zero ($0 or $zero) to always have the value 0 C:f = g; MIPS:add $s0, $s1, $zero where MIPS registers $s0 and $s1 are associated with variables f and gThis instruction add $zero, $zero, $s0does not do anything!

    MIPS Programming

  • 2011 Sem 1MIPS Programming*LOGICAL OPERATIONSArithmetic instructions view content of a register as a single quantity (signed or unsigned integer)New perspective: View register as 32 raw bits rather than as a single 32-bit numberConsequence: Useful to operate on individual bytes or bits within a word

    Logical operationC operatorJava operatorMIPS instructionShift Left>>, >>>srlBitwise AND&&and, andiBitwise OR||or, oriBitwise NOT~~nor

    MIPS Programming

  • 2011 Sem 1MIPS Programming*SHIFT INSTRUCTIONS (1/2)Opcode: sll (shift left logical)Move all the bits in a word to the left by a number of bits; fill the emptied bits with zeroesExample: register $s0 contains 0000 1000 0000 0000 0000 0000 0000 1001 sll $t2, $s0, 4 # $t2 = $s0
  • 2011 Sem 1MIPS Programming*SHIFT INSTRUCTIONS (2/2)Opcode: srl (shift right logical)Shifts right and fills emptied bits with zeroesQ: Shifting right by n bits is the same as what mathematical operation? Answer: Division by 2n Shifting is faster than multiplication/divisionGood compiler translates such multiplication/division into shift instructions:C: a = a * 8; MIPS: sll $s0, $s0, 3

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BITWISE AND INSTRUCTION (1/2)AND: bitwise operation that leaves a 1 only if both the bits of the operands are 1Example: and $t0, $t1, $t2 $t1: 0000 0000 0000 0000 0000 1101 0000 0000 $t2: 0000 0000 0000 0000 0011 1100 0000 0000 $t0: 0000 0000 0000 0000 0000 1100 0000 0000AND can be used to create a mask. Force 0s into the positions that you are not interested; other bits will remain the same as the original.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BITWISE AND INSTRUCTION (1/2)Example: andi $t0, $t1, 0xFFF $t1: 0000 1001 1100 0011 0101 1101 1001 1100 0xFFF: 0000 0000 0000 0000 0000 1111 1111 1111 $t0: 0000 0000 0000 0000 0000 1101 1001 1100In the above example we are interested in the last 12 bits of the word in register $t1. So we use 0xFFF as the mask.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BITWISE OR INSTRUCTIONOR: bitwise operation that places a 1 in the result if either operand bit is 1Can be used to force certain bits to 1sExample: ori $t0, $t1, 0xFFF $t1: 0000 1001 1100 0011 0101 1101 1001 1100 OxFFF: 0000 0000 0000 0000 0000 1111 1111 1111 $t0: 0000 1001 1100 0011 0101 1111 1111 1111If both operands are registers then use orExample: or $t0, $t1, $t2

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BITWISE NOR INSTRUCTIONRequired operation is NOT; toggles the bits of an operand (1 with 0, 0 with 1)To maintain regularity (simplicity favors regularity), MIPS uses NOR instead of NOTIf one operand of NOR is 0, then it is equivalent to NOT: A NOR 0 = NOT(A OR 0) = NOT(A)Example: nor $t0, $t1, $zero$t1: 0000 1001 1100 0011 0101 1101 1001 1100$t0: 1111 0110 0011 1100 1010 0010 0110 0011There is no nori in MIPS why?

    MIPS Programming

  • 2011 Sem 1MIPS Programming*READING ASSIGNMENTInstructions: Language of the ComputerRead up COD Chapter 2, pages 46-53, 58-59, 68-71.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Programming in MIPS Assembly Code

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MIPS PROGRAMMING MODELDataMIPS memory is an array of 232 bytes. Each byte has a 32 bit addressUser programs and data are restricted to the first 231 bytesSecond half of memory is used by operating systemOperationsLoad: a word (4 bytes) is transferred from memory to registerStore: a word (4 bytes) is transferred from memory to a registerArithmetic-logic operationsBetween registersBetween registers and immediate operands

    MIPS Programming

  • 2011 Sem 1MIPS Programming*REGISTERSGeneral purpose registers: may contain integers, or addresses$0$31Also denoted by functional mnemonics$t0-$t10$s0-$s7$a0-$a3$v0-$v1$sp, $ra, $zero, etcFloating point registers

    MIPS Programming

  • 2011 Sem 1MIPS Programming*REGISTERS AND THE ALU

    MIPS Programming

  • 2011 Sem 1MIPS Programming*REGISTER USE CONVENTION

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MEMORY LAYOUTText Segment: holds the machine code of the user program (the text).

    Data Segment: data that the program operates on. Static: size in bytes does not change during executionDynamic data: This is data that is allocated and deallocated as the program executes. In "C" dynamic allocation and deallocation is done with malloc() and free().

    Stack Segment: top of user address space is the stack. local variables and parameters are pushed and popped on the stack as procedures are activated and deactivated.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MEMORY LAYOUT

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MEMORY ACCESS INSTRUCTIONSOnly load and store instructions can access memory data.Example: Each array element occupies a word.C code: A[7] = h + A[10];MIPS code: lw $t0, 40($s3)add $t0, $s2, $t0sw $t0, 28($s3)Each array element occupies a word (4 bytes).$s3 contains the base address (address of first element) of array A.Remember arithmetic operands (for add) are registers, not memory!

    MIPS Programming

  • 2011 Sem 1MIPS Programming*LOAD WORD INSTRUCTIONExample: lw $t0, 4($s0) Load (read) the content from the memory word at address $s0 + 4 to the register $t0.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*STORE WORD INSTRUCTIONExample: sw $t0, 12($s0) Store (write) the content of register $t0 to the memory word at address $s0 + 12.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*OTHER LOAD/STORE INSTRUCTIONS (1/2)Besides the load word (lw) and store word (sw) instructions, there are also the load byte (lb) and store byte (sb) instructions.Similar in format:lb $t1, 12($s3)sb $t2, 13($s3)Similar in working except that one byte, instead of one word, is loaded or stored.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*OTHER LOAD/STORE INSTRUCTIONS (2/2)MIPS disallows loading/storing a word that crosses the word boundary. Use the unaligned load word (ulw) and unaligned store word (usw) instructions instead. These are pseudo-instructions.There are other instructions such aslh and sh: load halfword and store halfwordlwl, lwr, swl, swr: load word left, load word right, store word left, store word right.And others.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ARRAYS (1/2)Variable h is associated with register $s2. Array A has starting (base) address in register $s3C statement: A[3] = h + A[1];Transfer A[1] from memory to registerlw $t0, 4($s3) # offset = 14 = 4Perform addition; reuse temp register $t0add $t0, $s2, $t0 Store the sum into A[3]sw $t0, 12($s3) # offset = 34 = 12

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ARRAYS (2/2)A[3] = h + A[1];

    lw $t0, 4($s3) add $t0, $s2, $t0 sw $t0, 12($s3)

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ADDRESS VERSUS VALUEKey concept: Registers do not have typesA register can hold any 32-bit number. That number can be a value; but it can also be a memory address.If you write add $t2, $t1, $t0 then $t0 and $t1 should contain data values.If you write lw $t2,0($t0) then $t0 should contain a memory address.Do not mix these things up!

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BYTE VERSUS WORDImpt: Consecutive word addresses in machines with byte-addressing do not differ by 1.Many an assembly language programmer has toiled over errors made by assumption that the address of the next word can be found by incrementing the address in a register by 1 instead of by the word size in bytes.For both lw and sw the sum of base address and offset must be multiple of 4.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*EXAMPLEswap(int v[], int k){ int temp;temp = v[k]v[k] = v[k+1];v[k+1] = temp;}swap:muli $2, $5, 4add $2, $4, $2lw $15, 0($2)lw $16, 4($2)sw $16, 0($2)sw $15, 4($2)jr $31

    MIPS Programming

  • 2011 Sem 1MIPS Programming*CONSTANTSSmall constants are used quite frequently (50% of operands). Examples:A = A + 5;B = B + 1;C = C 18;Solution:Put typical constants in memory and load them.Create hard-wired registers (like $zero) for constants like one.Embed them into the instruction code.For MIPS instructions, we use the immediate operand version:addi$29, $29, 4slti$8, $18, 10andi$29, $29, 6ori$29, $29, 4

    MIPS Programming

  • 2011 Sem 1MIPS Programming*LARGE CONSTANTS (1/3)Recall bit-wise operations: or, ori, and, andi.Examples:Question: How to load a 32-bit constant into a register?Example: 1010101010101010 1111000011110000

    MIPS Programming

  • 2011 Sem 1MIPS Programming*LARGE CONSTANTS (2/3)Need to use two instructions: load upper immediate (lui) and or immediate (ori):lui$t0, 1010101010101010Then to get the lower-order bits correct: ori$t0, $t0, 1111000011110000Question: Why do we use ori instead of addi?

    MIPS Programming

  • 2011 Sem 1MIPS Programming*LARGE CONSTANTS (3/3)The above are just illustration of the concept. In the actual instruction, the value is entered as a decimal value or an hexadecimal value (prefixed by 0x).Example:lui $t0, 43690 # 4369010 = 10101010101010102orlui $t0, 0xAAAA # AAAA16 = 10101010101010102Example: To add 0xABABCDCD to $t0:lui $at, 0xABABori $at, $at, 0xCDCDadd $t0, $t0, $at$at is a special register used by compiler to form large constants

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Load Address Pseudoinstruction

    MIPS Programming

  • 2011 Sem 1MIPS Programming*LA Example

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Symbolic Address

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MAKING DECISIONS (1/2)So far all the instructions only manipulate data weve built a calculatorA computer needs the ability to make decisionsHigh-level language decisionsif and goto statementsMIPS decision making instructions are similar to if statement with a gotogoto is discouraged in high-level languages but necessary in assembly

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MAKING DECISIONS (2/2)Decision-making instructionsAlter the control flow of the programChange the next instruction to be executedTwo type of decision-making statementsConditional (branch)bne $t0, $t1, labelbeq $t0, $t1, labelUnconditional (jump)j label

    MIPS Programming

  • 2011 Sem 1MIPS Programming*CONDITIONAL BRANCHProcessor follows the branch conditionallybeq $r1,$r2, L1go to statement labeled L1 if the value in register $r1 equals the value in register $r2beq is branch if equalC code: if (a == b) goto L1bne $r1, $r2, L1go to statement labeled L1 if the value in register $r1 does not equal the value in register $r2 bne is branch if not equalC code: if (a != b) goto L1

    MIPS Programming

  • 2011 Sem 1MIPS Programming*UNCONDITIONAL JUMPProcessor always follows the branchj L1Jump to label L1 unconditionallyC code: goto L1Technically equivalent to such statementbeq $s0, $s0, L1

    MIPS Programming

  • 2011 Sem 1MIPS Programming*IF STATEMENT (1/2)C statement: if (i == j) f = g + h;Mapping f:$s0; g:$s1; h:$s2; i:$s3; j:$s4MIPS statements: bne $s3, $s4, Exit # if (i!=j) Exit add $s0, $s1, $s2 # f = g + h Exit:Why use bne instead of beq? For efficiency. beq $s3, $s4, L1 # if (i==j) goto L1 j Exit # goto Exit L1: add $s0, $s1, $s2 # f = g + h Exit:

    MIPS Programming

  • 2011 Sem 1MIPS Programming*IF STATEMENT (2/2)C statement: if (i == j) f = g + h; else f = g - h;Mapping f:$s0; g:$s1; h:$s2; i:$s3; j:$s4MIPS statements: bne $s3, $s4, Else add $s0, $s1, $s2 j Exit Else: sub $s0, $s1, $s2 Exit:Q: Rewrite using beq

    MIPS Programming

  • 2011 Sem 1MIPS Programming*LOOPS (1/2)C statement: while (j == k) i = i+1;Rewrite code with if and goto statements Loop: if (j != k) Exit; i = i+1; goto Loop; Exit:Key concept: The key to decision making is conditional branches. Any form of loop can be written in assembly with the help of conditional branches and jumps.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*LOOPS (2/2)Code: Loop: if (j != k) Exit; i = i+1; goto Loop; Exit:Write MIPS statement using mapping i:$s3; j:$s4; k:$s5 Loop: bne $s4, $s5, Exit # if (j!= k) Exit addi $s3, $s3, 1 j Loop # repeat loop Exit:

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INEQUALITIES (1/2)We have beq and bne, what about branch-if-less-than? We do not have a blt instruction.Use slt (set on less than) or slti.slt $t0, $s1, $s2

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INEQUALITIES (2/2)To build a blt $s1, $s2, L instruction:slt $t0, $s1, $s2bne $t0, $zero, LC code: if (a < b) goto L;

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ARRAY AND LOOPTypical example of accessing array elements in a loop:Initialization for result variables, loop counter, and array pointers.Work by:Calculating addressLoad dataPerform taskUpdate loop counter and array pointers.Compare and branch.Label:

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ARRAY AND LOOP: EXAMPLE (1/3)Given a word array A with 40 elements A[0], A[1], , A[39], with the starting array address stored in $t0. Count the number of array elements with value zero, and store the result in $t8.Answer 1:addi$t8, $zero, 0# initialize counter to zeroaddi$t1, $zero, 0# $t1 as index, init. to point to 1st elementL1:add$t2, $t0, $t1# address of current elementlw$t3, 0($t2)# load current element from memorybne$zero, $t3, L2# check if data is zero, if not, skip updateaddi$t8, $t8, 1# increment counterL2:addi$t1, $t1, 4# point to next elementHow to compare and loop back?bne$t1, 160, L1 ? No immediate compare operand!

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ARRAY AND LOOP: EXAMPLE (2/3)How about the iteration for the first element?Answer 2:addi$t8, $zero, 0# initialize counter to zeroaddi$t1, $zero, 156# $t1 as index, init. to pt to last elementL1:add$t2, $t0, $t1# address of current elementlw$t3, 0($t2)# load current element from memorybne$zero, $t3, L2# check if data is zero, if not, skip updateaddi$t8, $t8, 1# increment counterL2:addi$t1, $t1, 4# point to previous elementbne$t1, $zero, L1

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ARRAY AND LOOP: EXAMPLE (3/3)Is this correct now?Answer 3:addi$t8, $zero, 0# initialize counter to zeroaddi$t1, $zero, 160# $t1 as index, init. to point pass # last elementL1:add$t2, $t0, $t1# address of current elementlw$t3, 4($t2)# load preceding element from memorybne$zero, $t3, L2# check if data is zero, if not, skip updateaddi$t8, $t8, 1# increment counterL2:addi$t1, $t1, 4# point to previous elementbne$t1, $zero, L1

    MIPS Programming

  • Calling procedures

    MIPS Programming

  • 2011 Sem 1MIPS Programming*PROCEDURE CALLjal ProcedureAddress

    jal = jump and linkFirst, PC + 4 is stored in $raThen, an unconditional jump is performed to ProcedureAddressAt the end of the procedure, return with jr $ra

    MIPS Programming

  • 2011 Sem 1MIPS Programming*REGISTER USERegisters $s0-$s7: saved registers must be preserved by callee, i.e. saved before use, and then restored at the end of procedureSpace to save: a stack, whose top is stored in register $spRegisters $t0-$t9: temporary registers, not preserved by callee.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Stack

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Upside-Down MIPS Stack

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Push

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Pop

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Callers and Callees

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Callers and CalleesThe subroutine is only used once in the main program because it always returns to the same location. A subroutine call is when a main routine passes control to a subroutine. The main routine is said to be the CALLER and the subroutine is said to be the CALLEE. A return from a subroutine is when a subroutine passes control back to its CALLER. When the CALLEE finishes execution it nearly always returns control to its CALLER.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Many Calls but One Return

    MIPS Programming

  • 2011 Sem 1MIPS Programming*The jal Instruction

    MIPS Programming

  • 2011 Sem 1MIPS Programming*The jal Instruction

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Example jal Instruction

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Example jal Instruction

    MIPS Programming

  • 2011 Sem 1MIPS Programming*The jr Instruction

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Calling Convention

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Simple Linkage Convention

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Pushing the Return Address

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Chain of Calls

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Register ProblemRegisters $s0$s7 must not be altered by a subroutine.This restriction creates a problem when subroutines call other subroutines. The solution is to allow a subroutine to use $s0$s7. However, before using one of these registers, the subroutine must save its value on the stack. Later, when the subroutine returns to its caller, it must restore the register to its initial state.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Stack Linkage

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Stack Linkage

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Nested Subroutine Calls

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Frame Pointer

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Frame-Based Linkage Convention

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Frame-Based Linkage Convention

    MIPS Programming

  • 2011 Sem 1MIPS Programming*Frame-Based Linkage Convention

    MIPS Programming

  • 2011 Sem 1MIPS Programming*NON-NESTED PROCEDUREint leaf_example (int g, int h, int i, int j) { int f ; f = (g+h)-(i+j) ; return f ;}

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MIPS TRANSLATIONLeaf_example: addi $sp,$sp,-12 # room for 3 vars sw $t1,8($sp) sw $t0,4($sp) sw $s0,0($sp) add $t0,$a0,$a1 # $t0=g+h add $t1,$a2,$a3 # $t1=i+j sub $s0,$t0,$t1 # f = $t0-$t1 add $v0,$s0,$zero # returns the result in $v0 lw $s0,0($sp) # restore $s0 lw $t0,4($sp) # restore $t0 lw $t1,8($sp) # restore $t1 add $sp,$sp,12 # restore stack jr $ra # jump back to calling routine

    MIPS Programming

  • 2011 Sem 1MIPS Programming*NESTED PROCEDURE

    int fact (int n) { if ( n < 1 ) return 1 ; else return n * fact(n-1) ;}

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MIPS TRANSLATIONFact: addi $sp,$sp,8 # make room for 2 items sw $ra,4($sp) # save the return address sw $a0,0($sp) # save the argument n slti $t0,$a0,1 # test for n=1, to to L1 addi $v0,$zero,1 # return 1 addi $sp,$sp,8 # pop 2 items off stack jr $ra # return to after jalL1: addi $a0,$a0,-1 # n>=1: argument gets (n-1) jal fact lw $a0,0($sp) # return from jal: restore arguments lw $ra,4($sp) addi $sp,$sp,8 mul $v0,$a0,$v0 # return n* fact(n-1) jr $ra # return to caller

    MIPS Programming

  • 2011 Sem 1MIPS Programming*STACK ALLOCATION$fp $sp High addressLow address$fp $sp Activation record /Stack frame

    MIPS Programming

  • 2011 Sem 1MIPS Programming*SYSCALLOne of the main role of the operating system is to provide user task access to shared resources like the screenUser must rely on the OS for I/OIn MIPS, request to OS is done by the syscall instruction

    li $v0, code# load $v0 with the request code for an OS service # put the parameters in where the OS service # expects it to beSyscall# invoke the OS# return value (if any) is in $v0 or $f0

    MIPS Programming

  • 2011 Sem 1MIPS Programming*IMPORTANT SYSCALL

    MIPS Programming

  • 2011 Sem 1MIPS Programming*EXAMPLE: PRINT STRINGli$v0, 4# code 4 print stringla$a0, string# $a0 contains address of stringsyscall# ask OS to perform requested#service.datastring:.asciizHello world!\n

    MIPS Programming

  • 2011 Sem 1MIPS Programming*AN EXAMPLEli$v0, 5# code 5 read integersyscall# read in one line of ascii characters# convert them into a 32 bit integer# $v0
  • 2011 Sem 1MIPS Programming*MIPS SIMULATORTry out PCSpim (MIPS simulator)ftp://ftp.cs.wisc.edu/pub/spim/pcspim.exe orhttp://www.cs.wisc.edu/~larus/spim.html

    MIPS Programming

  • MIPS INSTRUCTION FORMATS

    MIPS Programming

  • 2011 Sem 1MIPS Programming*MIPS INSTRUCTIONS CLASSIFICATIONInstructions are classified according to their operands; instructions with same operand types have same representationR-format (Register format)add, sub, and, or, nor, slt require 2 source registers and 1 destination registersrl, sll also belong hereI-format (Immediate format)addi, subi, andi, ori, slti, lw, sw, beq, bne require 1 source register, 1 immediate and 1 destination registerJ-format (Jump format)j instruction requires only one immediate

    MIPS Programming

  • 2011 Sem 1MIPS Programming*R-FORMAT (1/2)Define fields of the following number of bits each: 6 + 5 + 5 + 5 + 5 + 6 = 32For simplicity, each field has a name:A field is viewed as 5- or 6-bit unsigned integer, not as part of 32-bit integer5-bit fields can represent any number 0-316-bit fields can represent any number 0-63

    MIPS Programming

  • 2011 Sem 1MIPS Programming*R-FORMAT (2/2)opcode partially specifies what instruction it isequal to 0 for all R-Format instructionsfunct combined with opcode exactly specifies the instructionrs (Source Register)used to specify register containing first operandrt (Target Register)used to specify register containing second operand (note that name is misleading)rd (Destination Register)used to specify register which will receive result of computationshamtamount a shift instruction will shift by. Shifting a 32-bit word by more than 31 is useless, so this field is only 5 bits (so it can represent the numbers 0-31)set to 0 in all but the shift instructions

    MIPS Programming

  • 2011 Sem 1MIPS Programming*R-FORMAT: EXAMPLE (1/3)MIPS instruction:add $8, $9, $10opcode = 0 funct = 32rd= 8 (destination)rs= 9 (first operand)rt= 10 (second operand)shamt= 0 (not a shift)

    MIPS Programming

  • 2011 Sem 1MIPS Programming*R-FORMAT: EXAMPLE (2/3)MIPS instruction:add $8, $9, $10Hexadecimal representation of instruction: 012A 402016

    MIPS Programming

  • 2011 Sem 1MIPS Programming*R-FORMAT: EXAMPLE (3/3)MIPS instruction:sll $8, $9, 4Hexadecimal representation of instruction: 0009 410016

    MIPS Programming

  • 2011 Sem 1MIPS Programming*I-FORMAT (1/4)What about instructions with immediates?5-bit shamt field only represents numbers up to the value 31immediates (for example for lw, sw instructions) may be much larger than thisCompromise: Define new instruction format partially consistent with R-format:If instruction has immediate, then it uses at most 2 registers

    MIPS Programming

  • 2011 Sem 1MIPS Programming*I-FORMAT (2/4)Define fields of the following number of bits each: 6 + 5 + 5 + 16 = 32Again, each field has a name:Only one field is inconsistent with R-format. opcode, rs, and st are still in the same locations.

    MIPS Programming

  • 2011 Sem 1MIPS Programming*I-FORMAT (3/4)opcodesame as before except that, since there is no funct field, opcode uniquely specifies an instructionrsspecifies the source register operand (if any)rtspecifies register to receive resultnote the difference from R-format instructions

    MIPS Programming

  • 2011 Sem 1MIPS Programming*I-FORMAT (4/4)The immediate field:Treated as a signed integer16 bits can be used to represent a constant up to 216 different valuesThis is large enough to handle the offset in a typical lw or sw, plus a vast majority of values that will be used in the addi,subi, slti instructions

    MIPS Programming

  • 2011 Sem 1MIPS Programming*I-FORMAT: EXAMPLE (1/2)MIPS instruction:addi $21, $22, -50opcode = 8rs= 22 (register containing operand)rt= 21 (target register)immediate= -50 (by default, this is decimal)

    MIPS Programming

  • 2011 Sem 1MIPS Programming*I-FORMAT: EXAMPLE (2/2)MIPS instruction:addi $21, $22, -50Hexadecimal representation of instruction: 22D5 FFCE16

    MIPS Programming

  • 2011 Sem 1MIPS Programming*INSTRUCTION ADDRESSAs instructions are stored in memory, they too have addressesbeq, bne, j instructions use these addressesAs instructions are 32-bit long, instruction addresses are word-aligned as wellOne register keeps address of instruction being executed: Program Counter (PC)

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BRANCHES: PC-RELATIVE ADDRESSING (1/5)Use I-Formatopcode specifies beq, bners and rt specify registers to compareWhat can immediate specify?Immediate is only 16 bitsMemory address is 32-bitSo immediate cannot specify entire address to branch to

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BRANCHES: PC-RELATIVE ADDRESSING (2/5)How do we usually use branches?Answer: if-else, while, forLoops are generally small: typically up to 50 instructionsUnconditional jumps are done using jump instructions (j), not the branchesConclusion: may want to branch to anywhere in memory, but a branch often changes PC by a small amount

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BRANCHES: PC-RELATIVE ADDRESSING (3/5)Solution: specify target address relative to the PCLet the 16-bit immediate field be a signed twos complement integer to be added to the PC if we take the branch.Now we can branch 215 bytes from the PC, which should be enough to cover almost any loop

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BRANCHES: PC-RELATIVE ADDRESSING (4/5)Instructions are word-aligned number of bytes to add to the PC will always be a multiple of 4.specify the immediate in words.Now we can branch 215 words from the PC (or 217 bytes)We can handle loops 4 times as large

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BRANCHES: PC-RELATIVE ADDRESSING (5/5)Branch Calculation:If we dont take the branch:PC = PC + 4 PC+4 = address of next instructionIf we do take the branch:PC = (PC + 4) + (immediate 4)Observationsimmediate field specifies the number of words to jump, which is simply the number of instructions to jumpimmediate field can be positive or negative.Due to hardware, add immediate to (PC+4), not to PC; will be clearer why later in the course

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BRANCH: EXAMPLE (1/3)MIPS Code:Loop:beq $9, $0, End add $8, $8, $10 addi $9, $9, -1 j LoopEnd:beq branch is I-Format: opcode = 4 (look up in table) rs = 9 (first operand) rt = 0 (second operand) immediate = ???

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BRANCH: EXAMPLE (2/3)MIPS Code:Loop:beq $9, $0, End # rel addr: 0 add $8, $8, $10 # rel addr: 4 addi $9, $9, -1 # rel addr: 8 j Loop # rel addr: 12End: # rel addr: 16immediate field:Number of instructions to add to (or subtract from) the PC, starting at the instruction following the branchIn beq case, immediate = 3End = (PC + 4) + (immediate 4)

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BRANCH: EXAMPLE (3/3)MIPS Code:Loop:beq $9, $0, End # rel addr: 0 add $8, $8, $10 # rel addr: 4 addi $9, $9, -1 # rel addr: 8 j Loop # rel addr: 12End: # rel addr: 16

    MIPS Programming

  • 2011 Sem 1MIPS Programming*J-FORMAT (1/5)For branches, we assumed that we wont want to branch too far, so we can specify change in PC.For general jumps (j), we may jump to anywhere in memory.Ideally, we could specify a 32-bit memory address to jump toUnfortunately, we cant (why?)

    MIPS Programming

  • 2011 Sem 1MIPS Programming*J-FORMAT (2/5)Define fields of the following number of bits each:As usual, each field has a name:Keep opcode field identical to R-format and I-format for consistencyCombine all other fields to make room for larger target address

    MIPS Programming

  • 2011 Sem 1MIPS Programming*J-FORMAT (3/5)We can specify 26 bits of 32-bit addressOptimization:Just like with branches, jumps will only jump to word-aligned addresses, so last two bits are always 00 (in binary)So lets just take this for granted and not even specify themNow we can specify 28 bits of 32-bit address

    MIPS Programming

  • 2011 Sem 1MIPS Programming*J-FORMAT (4/5)Where do we get the other 4 bits?By definition, take the 4 highest order bits from the PCTechnically, this means that we cannot jump to anywhere in memory, but its adequate 99.9999% of the time, since programs arent that long only if straddle a 256 MB boundarySpecial instruction if the program straddles 256MB boundaryLook up jr instruction if you are interestedTarget address is specified through a register

    MIPS Programming

  • 2011 Sem 1MIPS Programming*J-FORMAT (5/5)Summary:New PC = { PC[31..28], target address, 00 }Understand where each part came from!Note: { , , } means concatenation { 4 bits , 26 bits , 2 bits } = 32 bit Eg: {1010, 11111111111111111111111111, 00} = 10101111111111111111111111111100Assuming PC[31..28] = 1010Target address = 11111111111111111111111111

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ADDRESSING FOR BRANCH (1/2)Loop:beq $9,$0,End #Addr: 8add $8,$8,$10 #Addr:12addi $9,$9,-1 #Addr:16beq $0, $0, Loop#Addr:20End: #Addr:24PC = 8PC + 4 = 12Distance between End and (PC+4) = (24 12) bytes = 12 bytes = 3 words immediate = 3 new PC = (PC+4) + (immediatex4) = 12 + (3x4) = 24

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ADDRESSING FOR BRANCH (2/2)Loop:beq $9,$0,End #Addr: 8add $8,$8,$10 #Addr:12addi $9,$9,-1 #Addr:16beq $0, $0, Loop#Addr:20End: #Addr:24PC = ?PC + 4 = ?Distance between Loop and (PC+4) = = = immediate =

    MIPS Programming

  • ADDRESSING FOR JUMP (1/2)Loop:beq $9,$0,End #Addr: 8add $8,$8,$10 #Addr:12addi $9,$9,-1 #Addr:16j Loop#Addr:20End: #Addr:242011 Sem 1MIPS Programming*

    MIPS Programming

  • ADDRESSING FOR JUMP (2/2)Loop:beq $9,$0,End #Addr: 8add $8,$8,$10 #Addr:12addi $9,$9,-1 #Addr:16j Far#Addr:20End: #Addr:24Cannot jump to Far as PC[31..28] Far[31..28]2011 Sem 1MIPS Programming*

    MIPS Programming

  • 2011 Sem 1MIPS Programming*BRANCHING FAR AWAYGiven the instruction beq $s0, $s1, L1 Assume that the address L1 is farther away from the PC than can be supported by beq and bne instructionsConstruct an equivalent code sequence with the help of unconditional (j) and conditional branch (beq, bne) instructions to accomplish this far away branching

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ADDRESSING MODES (1/3)Register addressing: operand is a registerImmediate addressing: operand is a constant within the instruction itself (addi, andi, ori, slti)

    MIPS Programming

  • 2011 Sem 1MIPS Programming*ADDRESSING MODES (2/3)Base addressing (displacement addressing): operand is at the memory location whose address is sum of a register and a constant in the instruction (lw, sw)

    MIPS Programming

  • ADDRESSING MODES (3/3)PC-relative addressing: address is sum of PC and constant in the instruction (beq, bne)Pseudo-direct addressing: 26-bit of instruction concatenated with upper 4-bits of PC (j)2011 Sem 1MIPS Programming*

    MIPS Programming

  • 2011 Sem 1MIPS Programming*END

    MIPS Programming

    *******************************************************************************************************************************************************************************