24
MIPS Assembly Language Programming Bob Britton Chapter 1 The MIPS Architecture Prentice Hall My objective in teaching assembly language is to introduce students to the fundamental concepts of contemporary computer architecture. First impressions are important. When students are first introduced to computer architecture it is important that they are exposed to the fundamentals of how modern computers are organized. The MIPS architecture embodies the fundamental design principles of all contemporary RISC architectures. All instructions are directly executed in hardware The rate at which instructions are issued is maximized Instructions are easy to decode Only load and store instructions reference memory Plenty of general purpose registers are provided (32 for MIPS) Suggested Background Preparation Experience in developing algorithms, and running programs in some high level language such as C, C++, or Java

MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

MIPS Assembly Language Programming

Bob BrittonChapter 1

The MIPS Architecture

Prentice Hall

My objective in teaching assembly language is to introduce students to the fundamental concepts of contemporary computer architecture.

First impressions are important.

When students are first introduced to computer architecture it is important that they are exposed to the fundamentals of how modern computers are organized.

The MIPS architecture embodies the fundamental design principles of all contemporary RISC architectures.

• All instructions are directly executed in hardware

• The rate at which instructions are issued is maximized

• Instructions are easy to decode• Only load and store instructions reference

memory• Plenty of general purpose registers are

provided (32 for MIPS)

Suggested Background Preparation

Experience in developing algorithms, and running programs in some high level language such as C, C++, or Java

Page 2: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Benefits of Studying Assembly Language Programming

Obtain Insights into writing more efficient code

Will become familiar with what compilers do

Acquire an understanding of how a RISC CPU is organized

Open new opportunities in the field of embedded processors

The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has the largest share of the 64-bit embedded processor market.

http://www.mips.com/

Going to the web site http://www.mips.com/ you will find that the MIPS processor is used in:

•Cisco Routers

•Laser Printers built by HP and Fuji Xerox

•PDA’s

•Set-Top Boxes

•Sony AIBO™ Entertainment Robot

•Minolta Digital Camera

•Sony PlayStation

Course DescriptionChapter 1 - The MIPS architectureChapter 2 - Algorithm Development in Pseudocode Chapter 3 - Number SystemsChapter 4 - PCSpim The MIPS SimulatorChapter 5 - Efficient Algorithm DevelopmentChapter 6 - Passing Parameters on the StackChapter 7 - Reentrant FunctionsChapter 8 - Memory-Mapped I/OChapter 9 - Exceptions and InterruptsChapter 10 - A Pipelined Implementation Chapter 11 - Floating-Point Instructions

Page 3: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

MIPS

MIPS

The Datapath Diagram

DataPath DiagramProgram Counter (PC)

Instruction Register

Register File

ALU

Cache Memory

Data In

Address

4

Out

Rs

RtRd

ControlLogic

Program Counter (PC)

Instruction Register

Register File

ALU

Cache Memory

Data In

Address

4

Rs

RtRd

ControlLogic

Out

Reg. File[Rd] = Rs operation Rt

A Register Transfer Description of the Control Logic

IR = Mem[PC]

PC = PC + 4

Decode Instruction

Read from Reg. Filelw or sw

Memory[Address] = Rt

sw

lw

R-TypeIf (Rs == 0 ) thenPC = PC + Offset

beqz

Address = Rs + Offset

Reg. File[Rt] = Memory[Address]

Fetch Execute Cycle

0 $zero

1 $at

2 $v0

3 $v1

4 $a0

5 $a1

6 $a2

7 $a3

8 $t0

9 $t1

10 $t2

11 $t3

12 $t4

13 $t5

14 $t6

15 $t7

16 $s0

17 $s1

18 $s2

19 $s3

20 $s4

21 $s5

22 $s6

23 $s7

24 $t8

Number NameValue

RegisterFile

Pass parametersto functions

Return valuesfrom functions

Callee-SavedRegisters –Use these registers for valuesthat must be maintainedacross function calls.

Caller SavedRegisters –Use these registers in functions

Register File

Page 4: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

25 $t926 $k027 $k128 $gp29 $sp30 $fp31 $ra

Number Value Name MIPS Register FileRegister Naming Convention

(See Table 1.1)

$0 : Constant Zero$v0 : Returned values from functions$a0 : Arguments passed to functions$t0 : Temporary registers (functions)$s0 : Saved registers (main program)$sp : Stack Pointer$ra : Return address

Three Instruction Word Formats• Register Format

• Immediate Format

• Jump Format

Op-Code Rs Rt Rd Code

Op-Code Rs Rt 16 - Bit Immediate Value

Op-Code 26 Bit Current Segment Address

6 5 5 16

6 5 5 5 6

6 26

Instruction Word Formats

MIPS Assembly Language Programming

Bob BrittonChapter 1 - b

The MIPS Architecture

Page 5: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

MIPS Instruction SetSee Appendix C in the textbook for a detailed

description of every instruction.

• Arithmetic, Logic, and Shifting Instructions• Conditional Branch Instructions• Load and Store Instructions• Function Call Instructions

Instruction Set

An ExampleLet us suppose that an assembly language programmerwants to add the contents of register $a1 to the contents

of register $s1, and to place the result in register $v1. The assembly language instruction to accomplish this is:

add $v1, $a1, $s1

The equivalent pseudocode statement is:

$v1 = $a1 + $s1

Quick Reference – Appendix AInteger Instruction SetName Syntax Space/TimeAdd: add Rd, Rs, Rt 1/1Add Immediate: addi Rt, Rs, Imm 1/1Add Immediate Unsigned: addiu Rt, Rs, Imm 1/1Add Unsigned: addu Rd, Rs, Rt 1/1And: and Rd, Rs, Rt 1/1And Immediate: andi Rt, Rs, Imm 1/1Branch if Equal: beq Rs, Rt, Label 1/1Branch if Greater Than or Equal to Zero: bgez Rs, Label 1/1Branch if Greater Than or Equal to Zero and Link: bgezal Rs, Label 1/1Branch if Greater Than Zero: bgtz Rs, Label 1/1Branch if Less Than or Equal to Zero: blez Rs, Label 1/1Branch if Less Than Zero and Link: bltzal Rs, Label 1/1Branch if Less Than Zero: bltz Rs, Label 1/1Branch if Not Equal: bne Rs, Rt, Label 1/1Divide: div Rs, Rt 1/38Divide Unsigned: divu Rs, Rt 1/38Jump: j Label 1/1Jump and Link: jal Label 1/1Jump and Link Register: jalr Rd, Rs 1/1Jump Register: jr Rs 1/1

Integer Instruction SetName Syntax Space/TimeLoad Byte: lb Rt, offset(Rs) 1/1Load Byte Unsigned: lbu Rt, offset(Rs) 1/1Load Halfword: lh Rt, offset(Rs) 1/1Load Halfword Unsigned: lhu Rt, offset(Rs) 1/1Load Upper Immediate: lui Rt, Imm 1/1Load Word: lw Rt, offset(Rs) 1/1Load Word Left: lwl Rt, offset(Rs) 1/1Load Word Right: lwr Rt, offset(Rs) 1/1Move From Coprocessor 0 mfc0 Rd, Cs 1/1Move From High: mfhi Rd 1/1Move From Low: mflo Rd 1/1Move To Coprocessor 0 mtc0 Rt, Cd 1/1Move to High: mthi Rs 1/1Move to Low: mtlo Rs 1/1Multiply: mult Rs, Rt 1/32 Multiply Unsigned: multu Rs, Rt 1/32NOR: nor Rd, Rs, Rt 1/1OR: or Rd, Rs, Rt 1/1OR Immediate: ori Rt, Rs, Imm 1/1Return From Exception: rfe 1/1Store Byte: sb Rt, offset(Rs) 1/1Store Halfword: sh Rt, offset(Rs) 1/1Shift Left Logical: sll Rd, Rt, sa 1/1Shift Left Logical Variable: sllv Rd, Rt, Rs 1/1

Page 6: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Integer Instruction SetName Syntax Space/TimeSet on Less Than: slt Rd, Rt, Rs 1/1Set on Less Than Immediate: slti Rt, Rs, Imm 1/1Set on Less Than Immediate Unsigned: sltiu Rt, Rs, Imm 1/1Set on Less Than Unsigned: sltu Rd, Rt, Rs 1/1Shift Right Arithmetic: sra Rd, Rt, sa 1/1Shift Right Arithmetic Variable: srav Rd, Rt, Rs 1/1Shift Right Logical: srl Rd, Rt, sa 1/1Shift Right Logical Variable: srlv Rd, Rt, Rs 1/1Subtract: sub Rd, Rs, Rt 1/1Subtract Unsigned: subu Rd, Rs, Rt 1/1Store Word: sw Rt, offset(Rs) 1/1Store Word Left: swl Rt, offset(Rs) 1/1Store Right: swr Rt, offset(Rs) 1/1System Call: syscall 1/1Exclusive OR: xor Rd, Rs, Rt 1/1Exclusive OR Immediate: xori Rt, Rs, Imm 1/1

Macro Instructions

• Load Address la $s0, table• Load Immediate li $v0, 10• Move mov $t8, $sp• Multiply mul $t2, $a0, $a1• Divide div $s1, $v1, $t7• Remainder rem $s2, $v1, $t7 • Negate neg $s0, $s0

There are instructions to implement control structures such as:“if ... then ... else ...”

Let us suppose that if the contents of register $s6 is less than zero, in other words negative, we want to branch to a location in the program labeled “Quit.” Otherwise (else) we want to decrement the contents of register $s6.

if ($s6 >= 0) then ($s6 = $s6 – 1) else goto Quit

The assembly language instructions to accomplish this are:

bltz $s6, Quitaddi $s6, $s6, -1

The multiply instruction “mult” multiplies two 32-bit binary values and produces a 64-bit product which is stored in two special registers named High and Low. In this case, the destination for the result is implicitly understood.

Register High will be loaded with the upper 32-bits of the product and register Low will be loaded with the lower 32-bits of the product.

To move a copy of the value in the High register to the register file we use the instruction mfhi and to move a copy of the value in the Low register to the register file we use the instruction mflo.

The following code segment shows how the 64-bit product of $a1 times $s1 can be moved into $v0 and $v1:

mult $a1, $s1mfhi $v0mflo $v1

Page 7: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

The following divide instruction divides the 32-bit binary value in register $a1 by the 32-bit value in register $s1. The quotient is stored in the Low register and the remainder is stored in the High register. The following code segment shows how the quotient is moved into $v0 and the remainder is moved into $v1:div $a1, $s1mflo $v0mfhi $v1

In the MIPS architecture, division by zero is undefined. If it is possible that the divisor could be zero, then it is the programmers responsibility to test for this condition and to provide code to handle this special situation.

Label Op-Code Dest. S1, S2 Commentsmove $a0, $0 # $a0 = 0li $t0, 99 # $t0 = 99

loop:add $a0, $a0, $t0 # $a0 = $a0 + $t0addi $t0, $t0, -1 # $t0 = $t0 - 1bnez $t0, loop # if ($t0 != zero) branch loop li $v0, 1 # Print the value in $a0syscallli $v0, 10 # Terminate Program Runsyscall

An Example MIPS Assembly Language Program to find the sum of the integers from 1 to 99

Memory Addressing ModesThe MIPS architecture is a Load/Store architecture, which means the only instructions that access main memory are the load and store instructions.

Only one addressing mode is implemented in the hardware.

The addressing mode is referred to as base address plus displacement.

Addressing Modes

A load instruction accesses a value from memory and places a copy of the value found in memory in the register file. For example, the instruction:

lw $s1, 8($a0)

computes the effective address of the memory location to be accessed by adding together the contents of register $a0 (the base address) and the constant value eight (the displacement). A copy of the value accessed from memory at the effective address is loaded into register $s1. The equivalent pseudocode statement would be:

$s1 = Mem[$a0 + 8]

Page 8: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

The syntax of the assembly language load instruction is somewhat confusing.

lw $s1, 8($a0)

If someone were to write a new MIPS assembler, the following syntax would do a better job of conveying what the instruction actually does:

lw $s1, [$a0+8]

The following is an example of a “Store Word” instruction:sw $s1, 12($a0)

When the hardware executes this instruction it will compute the effective address of the destination memory location by adding together the contents of register $a0 and the constant value 12. A copy of the contents of register $s1 is stored in memory at the effective address.

The equivalent pseudocode statement would be:

Mem[$a0 + 12] = $s1

From the point of view of an assembly language programmer, memory can be thought of as a very long linear array of locations where binary codes are stored. An effective address is a pointer to some location in this array.

Reg. File[Rd] = Rs operation Rt

A Register Transfer Description of the Control Logic

IR = Mem[PC]

PC = PC + 4

Decode Instruction

Read from Reg. Filelw or sw

Memory[Address] = Rt

sw

lw

R-TypeIf (Rs == 0 ) thenPC = PC + Offset

beqz

Address = Rs + Offset

Reg. File[Rt] = Memory[Address]

Fetch Execute Cycle

DataPath DiagramProgram Counter (PC)

Instruction Register

Register File

ALU

Cache Memory

Data In

Address

4

Out

Rs

RtRd

ControlLogic

Program Counter (PC)

Instruction Register

Register File

ALU

Cache Memory

Data In

Address

4

Rs

RtRd

ControlLogic

Out

Page 9: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Exercises1.1 Explain the difference between a register and the ALU.

1.2 Explain the difference between Assembly Language and Machine Language.

1.3 Explain the difference between Cache Memory and the Register File.

1.4 Explain the difference between the Instruction Register and the Program Counter.

1.5 Explain the difference between a buss and a control line.

1.6 Identify a kitchen appliance that contains a control unit.

1.7 What is an algorithm?

1.8 Provide a step-by-step description of the sequence of operations that must take place within a MIPS processor to fetch and execute the “load word” instruction.

1.9 Provide a step-by-step description of the sequence of operations that must take place within a MIPS processor to fetch and execute the “store word” instruction.

Exercises

MIPS Assembly Language Programming

Bob Britton

Chapter 2

Algorithm Development in Pseudocode

PseudocodeUsing Pseudocode to Document a MIPS Assembly Language Program

When documenting an algorithm in a language such as C, programmers use descriptive variable names such as: speed, volume, size, count, amount, etc. After the program is compiled, these variable names correspond to memory locations. To efficiently execute code, a compiler will attempt to keep the variables that are referenced most often in processor registers because access to a variable in a processor register is much faster than access to memory. MIPS has 32 processor registers. The names used to reference these registers are defined in Table 1.1 in the textbook.

As an assembly language programmer you must takemaximum advantage of the processor registers.

When using pseudocode to document an assembly language program, you will be expected to use the names of the registers you intend to use in the assembly language code.

It is advisable to create a cross reference table between the processor register name and what it is being used for in the program .

Page 10: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

We use register names in pseudocodebecause the purpose of the pseudocodeis to document an assembly language program.

Unless you identify the registers being used, the pseudocode is quite limited in terms of having any correspondence to the assembly language code.

You will also find that as soon as you are able to develop the pseudocode in this format it is a very simple process to translate pseudocode into assembly language code.

For (t0=1; t0 < s0; t0++) do {this block of code};

Pseudocode for assembly language programs will have the appearance of C in terms of control structures and arithmetic expressions, but descriptive variable names will usually only appear in the LOAD ADDRESS (la) instruction where there is a reference to a symbolic memory address.

In assembly language you define and allocate space for variables in the data segment of memory using assembler directives such as .word and .space.

You will find that all of the MIPS instructions require the use of processor registers.

When writing pseudocode you should specify the processor registers you are planning to use to accomplish the task.

Page 11: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

MIPS Assembly Language Syntax

[label:] Op-Code [operand], [operand], [operand] [#comment]

Label Op-Code Dest. S1, S2 Commentchico: add $a0, $t0, $t1 # a0 = t0 + t1

Translation an Arithmetic Expression$s0 = srt ( $a0 * $a0 + $a1 * $a1)

Hypotenuse:mult $a0, $a0 # Square $a0mflo $t0 # t0 = Lower 32-bits of productmult $a1, $a1 # Square $a1mflo $t1 # t1 = Lower 32-bits of productadd $a0, $t0, $t1 # a0 = t0 + t1jal srt # Call the square root functionmove $s0, $v0 # By convention, the result of sqr

# is returned in $v0

Area of a Circle$s0 = π * $t8 * $t8

Area:li $t0, 314156 # Load immediate Pi scaled up 100,000mult $t8, $t8 # Radius squaredmflo $t1 # Move lower 32-bits of product in

# Low register to $t1mult $t1, $t0 # Multiply by scaled Pimflo $s0 # Move lower 32-bits of product in

# Low register to $s0li $t1, 100000 # Load immediate scale factor of 100,000div $s0, $t1 # Divide by scale factormflo $s0 # Truncated integer result left in $s0

Translation of an “if … then … else …” Control Structureif ($t8 < 0) then

{$s0 = 0 - $t8; $t1 = $t1 +1}else

{$s0 = $t8; $t2 = $t2 + 1}

bgez $t8, else # if ($t8 is greater than or # equal to zero) branch to else

sub $s0, $zero, $t8 # $s0 gets the negative of $t8addi $t1, $t1, 1 # increment $t1 by 1b next # branch around the else code

else:move $s0, $t8 # $s0 gets a copy of $t8addi $t2, $t2, 1 # increment $t2 by 1

next:

Page 12: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Translation of a “while” Control Structurewhile ($a1 < $a2) do

{ $a1 = $a1 + 1

$a2 = $a2 - 1}

while:bgeu $a1, $a2, done # If( $a1 >= $a2) Branch to doneaddi $a1, $a1, 1 # $a1 = $a1 + 1addi $a2, $a2, -1 # $a2 = $a2 - 1b while # Branch to while

done:

Translation of a “for” Loop Control Structure

$a0 = 0;for ( $t0 =10; $t0 > 0; $t0 = $t0 -1) do

{$a0 = $a0 + $t0}

li $a0, 0 # $a0 = 0li $t0, 10 # Initialize loop counter to 10

loop:add $a0, $a0, $t0addi $t0, $t0, -1 # Decrement loop counterbgtz $t0, loop # If ($t0 > 0) Branch to loop

Now for an example, let us suppose that we want to write an assembly language program to find the sum of the integers from 1 to N. In other words do the following: 1 + 2 + 3 + 4 + 5 + 6 + 7 + ....+ N, where “N” is an input value.

On the next slide you will see a pseudocode description of the algorithm and following that the corresponding assembly language program, where processor register $t0 is used to accumulate the sum, and processor register $v0 is used as a loop counter.

Use a word processor to create the following program file. Be sure to save as text only.

Next, load the program into SPIM. Run the program and experiment with the different features of the MIPS simulator. ( For example: Single Step)

Read the help file for a description of how to use the simulator.

An Example MIPS Program# Program #1 : (descriptive name) Programmer: YOUR NAME# Due Date : Sep. 13, 2001 Course: CSCI 221# Last Modified: Sep. 12, 2006# Functional Description: Find the sum of the integers from 1 to N where# N is a value input from the keyboard.########################################################## Algorithmic Description in Pseudocode:# main: v0 << value read from the keyboard (syscall 4)# if (v0 < = 0 ) stop# t0 = 0; # t0 is used to accumulate the sum# While (v0 > 0) { t0 = t0 + v0; v0 = v0 - 1}# Output to monitor syscall(1) << t0; goto main########################################################### Register Usage: $t0 is used to accumulate the sum# $v0 the loop counter, counts down to zero##########################################################

Page 13: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

.dataprompt: .asciiz "\n\n Please Input a value for N = "result: .asciiz " The sum of the integers from 1 to N is "bye: .asciiz "\n **** Adios Amigo - Have a good day **** "

.globl main

.textmain: li $v0, 4 # system call code for print_str

la $a0, prompt # load address of prompt into a0syscall # print the prompt messageli $v0, 5 # system call code for read_intsyscall # reads a value of N into v0blez $v0, done # if ( v0 < = 0 ) go to doneli $t0, 0 # clear $t0 to zero

loop: add $t0, $t0, $v0 # sum of integers in register $t0addi $v0, $v0, -1 # summing in reverse orderbnez $v0, loop # branch to loop if $v0 is != zeroli $v0, 4 # system call code for print_strla $a0, result # load address of message into $a0syscall # print the stringli $v0, 1 # system call code for print_intmove $a0, $t0 # a0 = $t0syscall # prints the value in register $a0b main

done: li $v0, 4 # system call code for print_strla $a0, bye # load address of msg. into $a0syscall # print the string

li $v0, 10 # terminate programsyscall # return control to system

MUST HAVE A BLANK LINE AT THE END OF THE TEXT FILE

Translation of a “switch” Control Structure

$s0 = 32;top: cout << “Input a value from 1 to 3”

cin >> $v0 switch ($v0)

{ case(1):{$s0 = $s0 << 1; break;}case(2):{$s0 = $s0 << 2; break;}case(3):{$s0 = $s0 << 3; break;}default: goto top; }

cout << $s0

.data

.align 2jumptable: .word top, case1, case2, case3prompt: .asciiz “\n\n Input a value from 1 to 3: ”

.texttop:

li $v0, 4 # Code to print a stringla $a0, promptsyscallli $v0, 5 # Code to read an integersyscallblez $v0, top # Default for less than oneli $t3, 3bgt $v0, $t3, top # Default for greater than 3la $a1, jumptable # Load address of jumptablesll $t0, $v0, 2 # Compute word offset (multiply by 4)add $t1, $a1, $t0 # Form a pointer into jumptablelw $t2, 0($t1) # Load an address from jumptablejr $t2 # Jump to specific case “switch”

case1: sll $s0, $s0, 1 # Shift left logical one bitb output

case2: sll $s0, $s0, 2 # Shift left logical two bitsb output

case3: sll $s0, $s0, 3 # Shift left logical three bitsoutput:

li $v0, 1 # Code to print an integer is 1move $a0, $s0 # Pass argument to system in $a0syscall # Output result

Page 14: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Assembler Directives

To allocate space in memory for a one-dimensional array of 1024 integers, the following construct is used in the C language:

int ARRAY[1024] ;

In MIPS assembly language, the corresponding construct is:

.dataARRAY: .space 4096

To initialize a memory array before program execution begins with a set of 16 values corresponding to the powers of 2 ( 2N with N going from 0 to 15) , the following construct is used in the C language:Int Pof2[16] ={ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 }

In MIPS assembly language the corresponding construct is:.data

Pof2: .word 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768

Here is an example of how MIPS code can be written to access element two in the array and place a copy of the value in reg. $s0. The load address la macro instruction is used to initialize a pointer in “$a0” with the base address of the array labeled “Pof2.”

la $a0, Pof2 # a0 = &Pof2lw $s0, 8($a0) # s0 = MEM[a0 + 8]

Input/Output System Calls

See Appendix A$v0

Service Call Code Arguments ResultsPrint_integer 1 $a0 = integerPrint_ string 4 $a0 = &stringRead_integer 5 $v0= integerRead_string 8 $a0 = &buffer

$a1 = Length of bufferExit 10

A Complete Example################################################################### Program Name: Sum of Integers# Programmer: YOUR NAME# Date last modified:################################################################### Functional Description:# A program to find the Sum of the Integers from 1 to N, where N is a value # read in from the keyboard.################################################################## # Pseudocode description of algorithm:# main: cout << “\n Please input a value for N = ”# cin >> v0 # If ( v0 > 0 ) # {t0 = 0;# While (v0 > 0 ) do # {t0 = t0 + v0; # v0 = v0 – 1}# cout << “ The sum of the integers from 1 to N is ”, t0;# go to main# }# else# cout << “\n **** Adios Amigo - Have a good day ****”################################################################### Cross References:

Page 15: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

#####################################################################.data

Prompt: .asciiz “\n Please Input a value for N = ”Result: .asciiz “ The sum of the integers from 1 to N is ”Bye: .asciiz “\n **** Adios Amigo - Have a good day ****”

.globl main

.textmain:

li $v0, 4 # system call code for Print Stringla $a0, Prompt # load address of prompt into $a0syscall # print the prompt messageli $v0, 5 # system call code for Read Integersyscall # reads the value of N into $v0blez $v0, End # branch to end if $v0 < = 0 li $t0, 0 # clear register $t0 to zero

Loop:add $t0, $t0, $v0 # sum of integers in register $t0addi $v0, $v0, -1 # summing integers in reverse orderbnez $v0, Loop # branch to loop if $v0 is != zeroli $v0, 4 # system call code for Print Stringla $a0, Result # load address of message into $a0syscall # print the stringli $v0, 1 # system call code for Print Integermove $a0, $t0 # move value to be printed to $a0 syscall # print sum of integersb main # branch to main

End: li $v0, 4 # system call code for Print Stringla $a0, Bye # load address of msg. into $a0syscall # print the stringli $v0, 10 # terminate program run andsyscall # return control to system

Exercises – Chapter 22.1 Using Appendix A, translate each of the following pseudocode expressions

into MIPS assembly language:

(a) t3 = t4 + t5 – t6;

(b) s3 = t2 / (s1 – 4321);

(c) sp = sp – 16;

(d) cout << t3;

(e) cin >> t0;

(f) a0 = &array;

(g) t8 = Mem(a0);

(h) Mem(a0+ 16) = 32768;

(i) cout << “Hello World”;

Solutions to Chap 2 Exerciseslabel op-code Rd, Rs, Rta: add $t3, $t4, $t5

sub $t3, $t3, $t6b: addi $s3, $s1, -4321

div $t2, $s3mflo $s3

c: addi $sp, $sp, -16

d: move $a0, $t3li $v0, 1syscall

e: li $v0, 5syscallmove $t0, $v0

Page 16: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Solutions to Chap 2 Exerciseslabel op-code Rd, Rs, Rtf: la $a0, array

g: lw $t8, 0($a0)

h: li $t0, 32768sw $t0, 16($a0)

i: .dataMsg: .asciiz “Hello World”

.textli $v0, 4la $a0, Msgsyscall

(j) If (t0 < 0) then t7 = 0 – t0 else t7 = t0;bgez $t0, elsesub $t7, $0, $t0b next

else:move $t7, $t0

(k) while ( t0 != 0) { s1 = s1 + t0; t2 = t2 + 4; t0 = Mem(t2) };while: beqz $t0, done

add $s1, $s1, $t0addi $t2, $t2, 4lw $t0, 0($t2)b while

done:

Solutions to Chap 2 Exercises

Solutions to Chap 2 Exercises(l) for ( t1 = 99; t1 > 0; t1 = t1 -1) v0 = v0 + t1;

li $t1, 99loop:

add $v0, $v0, $t1addi $t1, $t1, -1bgtz $t1, loop

(m) t0 = 2147483647 - 2147483648;

li $t0, -1

(n) s0 = -1 * s0;

sub $s0, $0, $s0

Exercises – Chapter 2(o) s1 = s1 * a0;

mult $s1, $a0

mflo $s1

(p) s2 = srt(s02 + 56) / a3;

mult $s0, $s0

mflo $a0

addi $a0, $a0, 56

jal srt

div $v0, $a3

mflo $s2

Page 17: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Exercises – Chapter 2(q) s3 = s1 - s2 / s3;

div $s2, $s3mflo $t0sub $s3, $s1, $t0

(r) s4 = s4 * 8;sll $s4, $s4, 3

(s) s5 = 7 * s5;sll $t1, $s5, 1sll $t2, $s5, 2add $t1, $t1, $t2add $s5, $s5, $t1

2.2 Analyze the assembly language code that you developed for each of the pseudocode expressions and calculate the number of clock cycles required to fetch and execute the code corresponding to each expression.(Assume it takes one clock cycle to fetch and execute every instruction except multiply and divide, which require 32 clock cycles and 38 clock cycles respectively.)

Exercises Continued2.3 Show how the following expression can be evaluated in MIPS assembly

language, without modifying the contents of the “s” registers:

$t0 = ( $s1 - $s0 / $s2) * $s4 ;

div $s0, $s2

mflo $t0

sub $t0, $s1, $t0

mult $t0, $s4

mflo $t0

2.4 Show how the following expression can be efficiently evaluated in MIPS assembly language.

$t0 = $s0/ 8 – 2*$s1 + $s2

sra $t0, $s0, 3sll $t1, $s1, 1sub $t0, $t0, $t1add $t0, $t0, $s2

Page 18: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Clock Cycles Exercises 2.3 & 2.4

Clock Cycles2.3 div $s0, $s2 38

mflo $t0 1sub $t0, $s1, $t0 1mult $t0, $s4 32mflo $t0 1

Total= 73

2.4 sra $t0, $s0, 3 1sll $t1, $s1, 1 1sub $t0, $t0, $t1 1add $t0, $t0, $s2 1

Total= 4

Bonus Exercise #1Show how the following pseudo code can be evaluated in MIPS assembly language.How many clock cycles will it take to execute your code? _______

$s0 = 1;$s1 = &arrayFor ($t7 = 40; $t7 > 0; $t7 = $t7 – 4)

{$s0 = $s0 * Mem[$s1 + $t7]

}

Solution to “for loop” Exercise############################# Clock Cycles

li $s0, 1 # 1la $s1, array # 2li $t7, 40 # 1

loop:addu $t1, $s1, $t7 # 1lw $t2, 0($t1) # 1mult $s0, $t2 # 32mflo $s0 # 1addi $t7, $t7, -4 # 1bgtz $t7, loop # 1

Bonus Exercise #2Show how the following pseudo code can be

evaluated in MIPS assembly language.How many clock cycles will it take to execute your code? _______

$t1 = 40;$s1 = -2;$s2 = &array;While ($t1 > 0){ $s1 = Mem[$t1 + $s2] * $s1;$t1 = $t1 – 4}

Page 19: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Solution to “while” Exercise############################ Clock Cycles

li $t1, 40 # 1li $s1, -2 # 1la $s2, array # 2

while:addu $t7, $t1, $s2 # 1lw $t6, 0($t7) # 1mult $t6, $s1 # 32mflo $s1 # 1addi $t1, $t1, -4 # 1bgtz $t1, while # 1

MIPS Assembly Language Programming

Bob Britton

Chapter 3

Number Systems

Number Systems• Introduction• Polynomial Expansion• Binary Numbers• Hexadecimal Numbers• Two’s Complement Number System• Arithmetic & Overflow Detection• American Standard Code for

Information Interchange (ASCII)

Polynomial Expansion of a Decimal Number (Base 10)

496 = 4 x 10 + 9 x 10 + 6 x 10

Polynomial Expansion of a Binary Number (Base 2)

2 1 0

10

00101101 = 1 x 2 + 0 x 2 + 1 x 2 + 1 x 2 + 0 x 2 + 1x 25 4 3 2 1 0

2

A Faster Method ------ Double and Add

00101101 = 45 (1, 2, 5, 11, 22, 45)

Page 20: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Conversion of Decimal Numbers to Binary

Divide by 2 and extract the remainder

45 Remainder 1 0 1 1 0 122 111 05 12 11 00 1

Practice - Convert 25 to BinaryDivide by 2 and record the remainder

25 Remainder12

To represent binary values in the positive and negative domains we use the

Two’s Complement Number System

Here is the polynomial expansion of a two’scomplement 8-bit binary number N:

N = - d7x2 + d6x2 + d5x2 + d4x2 + d3x2 + d2x2 + d1x2 +d0x2

Notice the Minus sign !!!!!!!!

*** You need to memorize powers of 2 ***

7 56 4 3 2 1 0

The Two’s Complement Operation

When we take the two’s complement of a binary number, the result will be the negative of the value we started with.

For example, the 8-bit binary value 00011010 is 26 in decimal.

To find the value negative 26 (-26) in binary we perform the two’s complement operation on 00011010.

Scan the binary number from right to left leaving all least significantzeros (0) and the first one (1) unchanged, and then complement theremaining digits to the left: 11100110

The result is the value negative 26 (-26) in binary.

Page 21: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Binary Arithmetic & Overflow Detectionin the Two’s Complement Number System

Here is an addition example where we assume we are limited to 8 binary digits.

01000100 = 68+ 00111100 = 60

10000000 = -128 Overflow Occurred

Overflow0000

0010

0001

0011

0100

0101

0110

0111

10001001

1010

1011

1101

1110

1111

1

2

0

3

4

5

6

7-8

-7

-6

-5

-4

-3

-2

-1

1100

Binary Arithmeticin the Two’s Complement Number System

Here is a subtraction example where we assume we are limited to 8 binary digits. To subtract in binary we always add the two’s complement of the subtrahend.

01000100 = 01000100 68-00111100 = +11000100 6000001000 = 00001000 = 8

The Rule for Detection of Overflow

#################################################Adding numbers of opposite signs, overflow is impossible.

When adding numbers of the same sign, if the result is not the same as the operands then overflow occurred.

#################################################Here is an example:You are given the following two numbers in two’s complement representation.Perform the binary subtraction and indicate if there is signed overflow. ______Explain Why:

11101000-00010011 11101000 = -24

+11101101 = -1911010101 Correct

Result = -43

Page 22: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Sign ExtensionThe value –43 as an 8-bit binary number is: 11010101The value –43 as an 32-bit binary number is:

11111111111111111111111111010101In Hexadecimal – 43 appears as: 0xFFFFFFD5

###############################################

The value 68 as an 8-bit binary number is: 01000100The value 68 as an 32-bit binary number is:

00000000000000000000000001000100In Hexadecimal 68 appears as: 0x00000044

The Hexadecimal Number SystemDecimal Hex Binary0 0 00001 1 00012 2 00103 3 00114 4 01005 5 01016 6 01107 7 01118 8 10009 9 100110 A 101011 B 101112 C 110013 D 110114 E 111015 F 1111

Here is an example of how wecompactly represent binary numbers in hexadecimal:

| | | | |001111001000111101111110

0x 3 C 8 F 7 E

MIPS Assembly Language Programming

Bob BrittonChapter 3 -b

Number Systems

Exercises3.1 Convert the decimal number 35 to an 8-bit binary number.

3.2 Convert the decimal number 32 to an 8-bit binary number.

3.3 Using the double and add method convert 00010101 to a decimal number.

3.4 Using the double and add method convert 00011001 to a decimal number.

3.5 Explain why the Least Significant digit of a binary number indicates if the number is odd or even.

3.6 Convert the binary number 00010101 to a hexadecimal number.

3.7 Convert the binary number 00011001 to a hexadecimal number.

3.8 Convert the hexadecimal number 0x15 to a decimal number.

3.9 Convert the hexadecimal number 0x19 to a decimal number.

3.10 Convert the decimal number -35 to an 8-bit two’s complement binary number.

00100011

00100000

21

25

LSD is a 1

0x15

0x19

21

25

11011101

Page 23: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Exercises3.11 Convert the decimal number -32 to an 8-bit

two’s complement binary number.

3.12 Assuming the use of the two’s complement number system find the equivalent decimal values for the following 8-bit binary numbers:(a) 10000001(b) 11111111(c) 01010000(d) 11100000(e) 10000011

3.13 Convert the base 8 number 204 to decimal

3.14 Convert the base 7 number 204 to decimal

3.15 Convert the base 6 number 204 to decimal

3.16 Convert the base 5 number 204 to decimal

3.17 Convert the base 10 number 81 to a base 9 number.

11100000

-127-180-32

-125

132

102

76

54

100

Exercises3.18 For each row of the table below convert the given 16 bit number to each of the other two bases, assuming the two’s complement number system is used.

16 Bit Binary Hexadecimal Decimal

1111111100111100

0xFF88

-128

1111111111111010

0x0011

-25

3.19 You are given the following two numbers in two’s complement representation. Perform the binary addition and indicate if there is signed overflow. __

Explain Why:

0110111000011010

10001000 Yes overflow occurred – Sign of the result is differentfrom the operands

Exercises3.20 You are given the following two numbers in two’s complement representation.

Perform the binary subtraction and indicate if there is signed overflow. ______Explain Why:

3.21 Sign extend the 8 bit hex number 0x88 to a 16 bit number. 0x_________

3.22 The following subtract instruction is located at address 0x00012344. What are the two possible values for the contents of the PC after the branch instruction executed? 0x_____________ 0x ____________This branch instruction is described in Appendix C.

loop: addi $t4, $t4, -8

sub $t2, $t2, $t0

bne $t4, $t2,loop

11101000-00010011

11101000+ 11101101

11010101 No Overflow

FF88

00012340 0001234C

Exercises

3.23 You are given the following two 8-bit binary numbers in the two’s complement number system. What values do they represent in decimal?

X = 10010100 = __________ Y = 00101100 = __________2 10 2 10

Perform the following arithmetic operations on X and Y. Show your answers as8-bit binary numbers in the two’s complement number system.

To subtract Y from X, find the two’s complement of Y and add it to X. Indicate if overflow occurs in performing any of these operations.

X+Y X-Y Y-X

10010100 10010100 0010110000101100

-108 44

+11010100 +0110110011000000 01101000 10011000

Page 24: MIPS Assembly Language Programming - Semantic Scholar · 2017. 10. 11. · The most likely area where assembly language programming is done is with embedded Processors ,and MIPS has

Exercise 3.24

The following code segment is stored in memory starting at memory location 0x00012344. What are the two possible values for the contents of the PC after the branch instruction has executed? 0x___ ____________Add in line pseudocode to describe each instruction.

loop: lw $t0, 0($a0) #addi $a0, $a0, 4 #andi $t1, $t0, 1 #beqz $t1, loop #

00012344 0x 00012354

t0 = Mem[a0]a0 = a0 +4t1 = t1 & 1 “Extract LSD”if t0 is even go to loop

Example QuizYou are given the following two 8 bit binary numbers in the two’s

complement number system. What values do they represent in decimal?X= 10010100 =

2

Y= 00101100 =2

Perform the following arithmetic operations on X and Y. Show your answers as 8 bit binary numbers in the two’s complement number system. To subtract Y from X find the two’s complement of Y and add it to X. Indicate if overflow occurs in performing any of these operations.

X+Y X-Y Y-X

10010100 10010100 0010110000101100