Homework #3: Functions Calling Functions, and Recursion
|
|
- Jonas Blankenship
- 5 years ago
- Views:
Transcription
1 Homework #3: Functions Calling Functions, and Recursion Assigned: Tuesday 17 Jun 2014 Due: Monday 23 Jun 2014 (at 23:59:59) This MIPS programming assignment introduces MIPS functions (which [P&H14] calls procedures ), stack frames, and simple recursion. Handing In By to Add [CS 260] to the Subject: line. Fundamentals I: Stack Frames (Reading Assignment) A trivial function doesn t need a stack frame. But most functions are non-trivial. In particular, recursive functions are always non-trivial, and always need a stack frame! High-level languages like C automatically generate all the code to manage stack frames. In MIPS assembly, you must do this explicitly yourself. You might never need to write explicit stack frame code beyond CS 260. But gaining a thorough understanding of the stack is fundamentally useful, in every language. This is because all modern programming languages have functions, and a stack is the natural mechanism for data transfer across function boundaries. Some examples of stack-based constructs include: Local variables Return addresses hence their vulnerability to buffer overrun attacks!! Nested scopes with C name hiding, C++ scope resolution, Emacs Lisp dynamic scoping Variadic function arguments, as in C `printf(fmt, )`, or ParamArray in Perl/ Common Lisp/Visual Basic/, etc. Passing an object (C/C++ struct/class) by value Returning an object by value (C/C++), or multiple values (Common Lisp) 1
2 Higher-language features, such as stack unwinding in exception handling (C++, Java, Common Lisp), return value optimization (C++), stack frame elision for tail-recursive functions (Scheme, Common Lisp), and functional languages (Erlang, ML, Haskell) also reduce to clever manipulations of the stack. By understanding the stack, you can understand exactly what these features are doing, and perhaps go on to help develop new techniques in the next major language. Stack Push, Stack Pop A: #~~~~ stack push ~~~~ addi $sp, $sp, N sw # grow downward code #~~~~ stack pop ~~~~ lw addi $sp, $sp, N # shrink upward # end of A A stack frame saves and restores register values (into memory). The purpose is to make these values persist for some duration (more on this later). Meanwhile, you can re-use those registers for other purposes. You often must do this because MIPS dedicates some registers to specific purposes, which can result in contention for those registers. Example: $a0 is always the first function argument, and $v0 is always the first return value. Whenever you have a sequence of 2+ nested function calls, they will contend for these registers (and possibly others). The code to create a stack frame consists merely of two blocks: a stack push that allocates space and stores register values into it, and a stack pop that does exactly the inverse. These two blocks bracket some region of your code. They correspond to a matched pair of `{}` curly-braces in C/C++/C#/Java, `()` in Common Lisp, etc. 2
3 The stack push must decrement $sp first (and then store to the new $sp + 0, ). Otherwise, you ll clobber memory that belongs to somebody else (usually your own caller). 1 The stack pop must increment $sp by exactly the same amount. (This is [P&H14] s spy covering his tracks on p.97.) Otherwise, you ll probably restore the wrong value into $ra and crash on return or one of your callers will! The stack pop usually restores (loads) everything that was saved in the push. Corollary: If you never need to restore it anywhere, then you didn t need to save it in the first place. Simple guideline: Copy-paste your entire stack push block. Reverse the order of the lines, change all `sw` to `lw`, and delete the ` ` character. The result is a perfectly acceptable stack pop block. Note: It is your responsibility to make sure that your stack pop exactly cancels out your stack push! Non-Leaf Stack Frame: jal changes $ra The simplest case of register contention is when your function makes any function call of its own. (This includes all recursive functions, by definition!) Consider your program s tree of function call dependencies. A leaf (bottommost) node in the call dependency tree is a function that doesn t call any other function. Such a function may be able to omit the stack frame. However, a non-leaf function, i.e. one that contains a `jal` or equivalent instruction anywhere in its body, immediately creates contention for the $ra register. The `jal` automatically changes $ra (that s exactly how `jal` works) so your function must save/restore its own value of $ra first. (It may also need to save/restore some $a* s.) 1 Advanced usage: Some languages permit you to access your caller s local variables, or generally variables in enclosing scopes. They do this by computing (at compile-time) the offsets of those local variables on the stack, relative to your function s stack pointer. You could do the same in MIPS (but we won t in this class). 3
4 f: # when f is done, it must return to $ra s current value #~~~~ stack push ~~~~ addi $sp, $sp, 4 # grow downward sw $ra, 0($sp) # save it while we have it J: jal g # clobbers $ra: sets $ra = (J+4) == K K: # that s how g knows to return to address K #~~~~ stack pop ~~~~ lw $ra, 0($sp) # restore before we use it addi $sp, $sp, 4 # shrink upward # end of f The stack push and pop blocks can go (almost) anywhere in your function. Guidelines: Simplest rule: Stack push at the very top. Stack pop at the very bottom. Non-vacuous rule (a mild optimization): Some functions may have vacuous (empty) or trivial bodies, e.g. a loop of 0 iterations, or a recursive function s base case. If only the recursive branch involves `jal` calls, then you can put the stack push/pop at the top/bottom of the recursive branch only. (Caution: It is your responsibility to make sure that your trivial branches properly jump over the stack pop! An unmatched pop is just as fatal as an unmatched push.) Function Call Boundary: What s the Difference Between $s* and $t*? Consider a function call from the perspective of the caller (parent, outside). A function is now a black box 2, which magically does something. (This is why functions are useful, and why every language has them.) But a MIPS function can also have sideeffects, especially when it clobbers registers (and doesn t bother to save/restore them). Here s a program fragment that includes one `jal` call to an external function. 2 In the real world, we almost never have the source code for library functions, but we can call them anyways, and trust them to do the right thing. 4
5 la $s0, MyArrayStart # char * P = A + 0; li $t1, 2 # int j = 2; addi $s0, $s0, 1 # ++P; #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ jal TransmogrifyBits # v0 = TB(a0, a1) and? #~~~~~~~~~~~~ (boundary) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # now did $s0 persist? -- yes, all $s* persist # now did $t1 persist? -- no, it could be anything # now did $ra persist? -- no, `jal` clobbered it for sure addi $s0, $s0, 1 # ok, $s0 is still P bne $t1, 5, FRO # oops: j could be -298,158!! Hence, a function call is a boundary, beyond which some registers are trustworthy, and others aren t. MIPS adopts the following convention 3 for registers across a function call boundary; see [P&H14] (p.97) (p.105 Fig. 2.14) (p.a-24 Fig. A.6.1) and the green card in the front of the book. Callee-saved registers do persist: $s0 $s7, $sp (stack), $ra (return address). Caller-saved registers do not persist: $t0 $t9, $a0 $a3 (arguments), $v0 $v1 (return values). This means any function can clobber them freely, and the caller can t trust them. Now let s switch hats, and consider this from the perspective of the callee (child, inside, the one that is called ). Then the convention these registers persist becomes the absolute rule: Thou Shalt Make Them Persist 3 This convention isn t enforced at the hardware level, nor even by the MIPS assembler. So you could violate these conventions and still produce running code. But such code would fail to integrate seamlessly with other MIPS code that does adhere to this convention. More practically, this includes the class s automatic grading harness hence code that violates this convention could be mistaken for code that doesn t work! 5
6 It is your responsibility to do this manually! The MIPS assembler doesn t do it for you automatically. Within a callee function body F, the obvious way to make $s* registers persist across a call to F is to save/restore them in F s own stack frame. If F didn t have a stack frame already, it needs one now. (If F already has one, just add $s* to its push/pop blocks.) Here s a plausible way to write that external function, with a proper stack frame: # for reasons of my own, I insist on reusing $s0 TransmogrifyBits: # ~~~~ stack push ~~~~ addi $sp, $sp, -4 sw $s0, 0($sp) # [0] <= s0 # now I ll use $s0 li $s0, 15 li $t0, 0 # I can clobber $t* freely # ~~~~ stack pop ~~~~ lw $s0, 0($sp) # [0] => s0 addi $sp, $sp, 4 # never called `jal`, so $ra never changed Now we can use it, and trust that it behaves itself, like a well-mannered child: addi $s0, $s0, 1 # ++P; jal TransmogrifyBits # ~~~~~~~~ boundary ~~~~~~~~ # now did $s0 persist? -- yes, because I made it persist!! 6
7 Guidelines for callee-saved (persistent) registers: 1. If you never change any callee-saved register (including $ra!), then you don t need a stack frame at all. Hence, one work-around is to use $t* inside your functions, as much as possible. This works for leaf functions only. 2. If you never change a particular $s*, then you don t need to save/restore it. 3. If you do change any $s* (or $ra), then you must have a stack frame, and it must save/restore all of those $s*. Example: Suppose your function is a complex loop. It could be easier to manage if you split it up into 1 outer loop + a few subfunctions, where the loop body calls those functions. Then the outer loop body could put its loop variables into $s* registers, and rely on the convention that these $s* will persist across its subfunction calls. This helps improve clarity for your outer loop. When you write those subfunctions, you must explicitly write them to do #1, #2, or #3. Your outer loop function must do #3. This is a mild burden when you re writing a function. The benefit is that when you call other functions, e.g. system or library functions, or other programmers functions, you can trust that they ve already done #1, #2, or #3, no matter who wrote them. Other programmers will expect the same from you! Caller-Saved Registers and the Point-of-Call Stack Frame What if you have contention for argument registers $a* and/or result registers $v*? This often happens whenever you call non-trivial subfunctions (that require their own arguments, and return intermediate results). These caller-saved registers do not persist, so you can t just change-and-forget them. Generally, you can organize your save/restore code into two places: 1. Outermost. You could treat $a* exactly the same as callee-saved $s* registers, and just add them to your topmost/bottommost stack frame. Disadvantage: The saving/restoring can be far away (in lines) from where you use it, which can be hard to read. 7
8 Caution: Don t blindly save/restore your $v* registers. They re supposed to change, to return the results of a call! If you did save/restore $v*, it could look like your function had no effect at all! 2. Point-of-call. Or, insert a 2-line mini-push block right before the `jal` call, and a 2-line mini-pop block right after it, and think of the entire 5-line block as one atomic (indivisible) chunk. (Bonus: You can even comment your code this way, e.g. by adding a blank line above and below, and/or a comment separator line. Being able to see the chunk as a chunk is also very useful!) Here s a sample code fragment, comparing these two approaches: fe: # 1. Outermost fm: # 2. Point-of-call #~~~~ top push ~~~~ #~~~~ top push ~~~~ addi $sp, $sp, 8 addi $sp, $sp, 4 sw sw $ra, 0($sp) $a0, 4($sp) sw $ra, 0($sp) # caller must save/restore! #~~~~ mini push ~~~~ addi $sp, $sp, 4 sw $a0, 0($sp) mov $a0, $v0 # g(h(a0)) mov $a0, $v0 jal g jal g #~~~~ mini pop ~~~~ lw $a0, 0($sp) addi $sp, $sp, 4 lw $a0, 4($sp) #~~~~ bottom pop ~~~~ #~~~~ bottom pop ~~~~ lw $ra, 0($sp) addi $sp, $sp, 8 lw $ra, 0($sp) addi $sp, $sp, 4 8
9 Note that the stack offsets to $sp differ based on where you re counting from. If in doubt, sketch the stack and label its slots (on scratch paper, or right in your source code as comments in your stack push block). Part II (Programming Assignment) For each function definition below, write an equivalent MIPS function. (That means it must return to its caller using ``.) You may assume n 0 (and you don t have to check for it). Hint: Write all of your functions in the same file. To test your code, write a separate `main:` block that just calls whichever function you re currently testing, then exits gracefully. Update your `main:` block as you reach each problem. 1. A function named quart that implements 4 quarts ( n) = n. (In other words, it returns $v0 = ($a0) 4.) 4 2. A function named qi that implements qi( n) = i, using iteration (a loop). Hint: Call your quart function. (Do not copy-paste its code into qi.) n i= A function named qr that implements qr( n) = i, using recursion. Hint: Call your quart function (again). n i= 1 4. A function named qeq that implements the function qeq(n) = qi(n) qr(n) Hint: Call your previous two functions, subtract their results, and return it. 5. A function named hib. You must use recursion. hib(0) = 0 hib(1) = 1 hib(n) = 3 hib(n 1) + 4 hib(n 2) + n 9
Functions in MIPS. Functions in MIPS 1
Functions in MIPS We ll talk about the 3 steps in handling function calls: 1. The program s flow of control must be changed. 2. Arguments and return values are passed back and forth. 3. Local variables
More informationSubroutines. int main() { int i, j; i = 5; j = celtokel(i); i = j; return 0;}
Subroutines Also called procedures or functions Example C code: int main() { int i, j; i = 5; j = celtokel(i); i = j; return 0;} // subroutine converts Celsius to kelvin int celtokel(int i) { return (i
More informationLecture 5. Announcements: Today: Finish up functions in MIPS
Lecture 5 Announcements: Today: Finish up functions in MIPS 1 Control flow in C Invoking a function changes the control flow of a program twice. 1. Calling the function 2. Returning from the function In
More informationLectures 5. Announcements: Today: Oops in Strings/pointers (example from last time) Functions in MIPS
Lectures 5 Announcements: Today: Oops in Strings/pointers (example from last time) Functions in MIPS 1 OOPS - What does this C code do? int foo(char *s) { int L = 0; while (*s++) { ++L; } return L; } 2
More informationToday. Putting it all together
Today! One complete example To put together the snippets of assembly code we have seen! Functions in MIPS Slides adapted from Josep Torrellas, Craig Zilles, and Howard Huang Putting it all together! Count
More informationCOMP 303 Computer Architecture Lecture 3. Comp 303 Computer Architecture
COMP 303 Computer Architecture Lecture 3 Comp 303 Computer Architecture 1 Supporting procedures in computer hardware The execution of a procedure Place parameters in a place where the procedure can access
More informationCA Compiler Construction
CA4003 - Compiler Construction David Sinclair When procedure A calls procedure B, we name procedure A the caller and procedure B the callee. A Runtime Environment, also called an Activation Record, is
More informationCompilers and computer architecture: A realistic compiler to MIPS
1 / 1 Compilers and computer architecture: A realistic compiler to MIPS Martin Berger November 2017 Recall the function of compilers 2 / 1 3 / 1 Recall the structure of compilers Source program Lexical
More informationMIPS Programming. A basic rule is: try to be mechanical (that is, don't be "tricky") when you translate high-level code into assembler code.
MIPS Programming This is your crash course in assembler programming; you will teach yourself how to program in assembler for the MIPS processor. You will learn how to use the instruction set summary to
More informationBranch Addressing. Jump Addressing. Target Addressing Example. The University of Adelaide, School of Computer Science 28 September 2015
Branch Addressing Branch instructions specify Opcode, two registers, target address Most branch targets are near branch Forward or backward op rs rt constant or address 6 bits 5 bits 5 bits 16 bits PC-relative
More informationControl Instructions
Control Instructions Tuesday 22 September 15 Many slides adapted from: and Design, Patterson & Hennessy 5th Edition, 2014, MK and from Prof. Mary Jane Irwin, PSU Summary Previous Class Instruction Set
More informationMIPS Functions and Instruction Formats
MIPS Functions and Instruction Formats 1 The Contract: The MIPS Calling Convention You write functions, your compiler writes functions, other compilers write functions And all your functions call other
More informationMemory Usage 0x7fffffff. stack. dynamic data. static data 0x Code Reserved 0x x A software convention
Subroutines Why we use subroutines more modular program (small routines, outside data passed in) more readable, easier to debug code reuse i.e. smaller code space Memory Usage A software convention stack
More informationHomework #2 Think in C, Write in Assembly
Homework #2 Think in C, Write in Assembly Assigned: Friday 06 Sep 2013 Due: Monday 16 Sep 2013 (by 23:59:59) Converting C to MIPS Assembly For each block of C code below, convert it into an equivalent
More informationCommon Problems on Homework
MIPS Functions Common Problems on Homework 1.3: Convert -3000 ten to binary in 8bit, 16bit, and 32bit Even though it overflows with 8bits, there is plenty of room with 16 and 32 bit. Common Problems on
More informationControl Instructions. Computer Organization Architectures for Embedded Computing. Thursday, 26 September Summary
Control Instructions Computer Organization Architectures for Embedded Computing Thursday, 26 September 2013 Many slides adapted from: Computer Organization and Design, Patterson & Hennessy 4th Edition,
More informationChapter 2. Computer Abstractions and Technology. Lesson 4: MIPS (cont )
Chapter 2 Computer Abstractions and Technology Lesson 4: MIPS (cont ) Logical Operations Instructions for bitwise manipulation Operation C Java MIPS Shift left >>> srl Bitwise
More informationImplementing Procedure Calls
1 / 39 Implementing Procedure Calls February 18 22, 2013 2 / 39 Outline Intro to procedure calls Caller vs. callee Procedure call basics Calling conventions The stack Interacting with the stack Structure
More informationCalling Conventions. Hakim Weatherspoon CS 3410, Spring 2012 Computer Science Cornell University. See P&H 2.8 and 2.12
Calling Conventions Hakim Weatherspoon CS 3410, Spring 2012 Computer Science Cornell University See P&H 2.8 and 2.12 Goals for Today Calling Convention for Procedure Calls Enable code to be reused by allowing
More informationEE 361 University of Hawaii Fall
C functions Road Map Computation flow Implementation using MIPS instructions Useful new instructions Addressing modes Stack data structure 1 EE 361 University of Hawaii Implementation of C functions and
More informationComputer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: MIPS Programming
Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring 2009 Topic Notes: MIPS Programming We spent some time looking at the MIPS Instruction Set Architecture. We will now consider
More informationCourse Administration
Fall 2018 EE 3613: Computer Organization Chapter 2: Instruction Set Architecture Introduction 4/4 Avinash Karanth Department of Electrical Engineering & Computer Science Ohio University, Athens, Ohio 45701
More informationECE260: Fundamentals of Computer Engineering
Supporting Nested Procedures James Moscola Dept. of Engineering & Computer Science York College of Pennsylvania Based on Computer Organization and Design, 5th Edition by Patterson & Hennessy Memory Layout
More informationCSCI 402: Computer Architectures. Instructions: Language of the Computer (3) Fengguang Song Department of Computer & Information Science IUPUI.
CSCI 402: Computer Architectures Instructions: Language of the Computer (3) Fengguang Song Department of Computer & Information Science IUPUI Recall Big endian, little endian Memory alignment Unsigned
More informationCSE Lecture In Class Example Handout
CSE 30321 Lecture 07-09 In Class Example Handout Part A: A Simple, MIPS-based Procedure: Swap Procedure Example: Let s write the MIPS code for the following statement (and function call): if (A[i] > A
More informationCS 61c: Great Ideas in Computer Architecture
MIPS Functions July 1, 2014 Review I RISC Design Principles Smaller is faster: 32 registers, fewer instructions Keep it simple: rigid syntax, fixed instruction length MIPS Registers: $s0-$s7,$t0-$t9, $0
More informationSPIM Procedure Calls
SPIM Procedure Calls 22C:60 Jonathan Hall March 29, 2008 1 Motivation We would like to create procedures that are easy to use and easy to read. To this end we will discuss standard conventions as it relates
More informationAnne Bracy CS 3410 Computer Science Cornell University
Anne Bracy CS 3410 Computer Science Cornell University The slides are the product of many rounds of teaching CS 3410 by Professors Weatherspoon, Bala, Bracy, McKee, and Sirer. See P&H 2.8 and 2.12, and
More informationCS 61C: Great Ideas in Computer Architecture (Machine Structures) More MIPS Machine Language
CS 61C: Great Ideas in Computer Architecture (Machine Structures) More MIPS Machine Language Instructors: Randy H. Katz David A. PaGerson hgp://inst.eecs.berkeley.edu/~cs61c/sp11 1 2 Machine Interpreta4on
More informationMIPS Functions and the Runtime Stack
MIPS Functions and the Runtime Stack COE 301 Computer Organization Prof. Muhamed Mudawar College of Computer Sciences and Engineering King Fahd University of Petroleum and Minerals Presentation Outline
More informationFunction Calling Conventions 1 CS 64: Computer Organization and Design Logic Lecture #9
Function Calling Conventions 1 CS 64: Computer Organization and Design Logic Lecture #9 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline More on MIPS Calling Convention Functions calling functions
More informationChapter 2A Instructions: Language of the Computer
Chapter 2A Instructions: Language of the Computer Copyright 2009 Elsevier, Inc. All rights reserved. Instruction Set The repertoire of instructions of a computer Different computers have different instruction
More informationCS64 Week 5 Lecture 1. Kyle Dewey
CS64 Week 5 Lecture 1 Kyle Dewey Overview More branches in MIPS Memory in MIPS MIPS Calling Convention More Branches in MIPS else_if.asm nested_if.asm nested_else_if.asm Memory in MIPS Accessing Memory
More informationCS61C Machine Structures. Lecture 12 - MIPS Procedures II & Logical Ops. 2/13/2006 John Wawrzynek. www-inst.eecs.berkeley.
CS61C Machine Structures Lecture 12 - MIPS Procedures II & Logical Ops 2/13/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L12 MIPS Procedures II / Logical (1)
More informationCompiling Code, Procedures and Stacks
Compiling Code, Procedures and Stacks L03-1 RISC-V Recap Computational Instructions executed by ALU Register-Register: op dest, src1, src2 Register-Immediate: op dest, src1, const Control flow instructions
More informationCSCI 2321 (Computer Design), Spring 2018 Homework 3
CSCI 2321 (Computer Design), Spring 2018 Homework 3 Credit: 50 points. 1 Reading Be sure you have read, or at least skimmed, all assigned sections of Chapter 2 and Appendix A. 2 Honor Code Statement Please
More informationECE232: Hardware Organization and Design
ECE232: Hardware Organization and Design Lecture 6: Procedures Adapted from Computer Organization and Design, Patterson & Hennessy, UCB Overview Procedures have different names in different languages Java:
More informationCS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find
CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS
More informationCS153: Compilers Lecture 8: Compiling Calls
CS153: Compilers Lecture 8: Compiling Calls Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Project 2 out Due Thu Oct 4 (7 days) Project 3 out Due Tuesday Oct 9 (12 days) Reminder:
More informationProf. Kavita Bala and Prof. Hakim Weatherspoon CS 3410, Spring 2014 Computer Science Cornell University. See P&H 2.8 and 2.12, and A.
Prof. Kavita Bala and Prof. Hakim Weatherspoon CS 3410, Spring 2014 Computer Science Cornell University See P&H 2.8 and 2.12, and A.5 6 compute jump/branch targets memory PC +4 new pc Instruction Fetch
More informationInstructions: Assembly Language
Chapter 2 Instructions: Assembly Language Reading: The corresponding chapter in the 2nd edition is Chapter 3, in the 3rd edition it is Chapter 2 and Appendix A and in the 4th edition it is Chapter 2 and
More informationCode Generation. The Main Idea of Today s Lecture. We can emit stack-machine-style code for expressions via recursion. Lecture Outline.
The Main Idea of Today s Lecture Code Generation We can emit stack-machine-style code for expressions via recursion (We will use MIPS assembly as our target language) 2 Lecture Outline What are stack machines?
More informationWe can emit stack-machine-style code for expressions via recursion
Code Generation The Main Idea of Today s Lecture We can emit stack-machine-style code for expressions via recursion (We will use MIPS assembly as our target language) 2 Lecture Outline What are stack machines?
More informationFunction Calls. 1 Administrivia. Tom Kelliher, CS 240. Feb. 13, Announcements. Collect homework. Assignment. Read
Function Calls Tom Kelliher, CS 240 Feb. 13, 2002 1 Administrivia Announcements Collect homework. Assignment Read 3.7 9. From Last Time SPIM lab. Outline 1. Function calls: stack execution model, memory
More informationMachine Language Instructions Introduction. Instructions Words of a language understood by machine. Instruction set Vocabulary of the machine
Machine Language Instructions Introduction Instructions Words of a language understood by machine Instruction set Vocabulary of the machine Current goal: to relate a high level language to instruction
More informationDo-While Example. In C++ In assembly language. do { z--; while (a == b); z = b; loop: addi $s2, $s2, -1 beq $s0, $s1, loop or $s2, $s1, $zero
Do-While Example In C++ do { z--; while (a == b); z = b; In assembly language loop: addi $s2, $s2, -1 beq $s0, $s1, loop or $s2, $s1, $zero 25 Comparisons Set on less than (slt) compares its source registers
More informationCOMP2611: Computer Organization MIPS function and recursion
COMP2611 Fall2015 COMP2611: Computer Organization MIPS function and recursion Overview 2 You will learn the following in this lab: how to use MIPS functions in a program; the concept of recursion; how
More informationCS 61C: Great Ideas in Computer Architecture Strings and Func.ons. Anything can be represented as a number, i.e., data or instruc\ons
CS 61C: Great Ideas in Computer Architecture Strings and Func.ons Instructor: Krste Asanovic, Randy H. Katz hdp://inst.eecs.berkeley.edu/~cs61c/sp12 Fall 2012 - - Lecture #7 1 New- School Machine Structures
More informationRuntime management. CS Compiler Design. The procedure abstraction. The procedure abstraction. Runtime management. V.
Runtime management CS3300 - Compiler Design Runtime management V Krishna Nandivada IIT Madras Copyright c 2001 by Antony L Hosking Permission to make digital or hard copies of part or all of this work
More informationAnne Bracy CS 3410 Computer Science Cornell University
Anne Bracy CS 3410 Computer Science Cornell University The slides are the product of many rounds of teaching CS 3410 by Professors Weatherspoon, Bala, Bracy, McKee, and Sirer. compute jump/branch targets
More informationMIPS Procedure Calls - Review
MIPS Stacks and Subroutine Calls Cptr280 Dr Curtis Nelson MIPS Procedure Calls - Review When making a procedure or function call, it is necessary to: Place parameters you wish to pass where they can be
More informationFunction Calling Conventions 2 CS 64: Computer Organization and Design Logic Lecture #10
Function Calling Conventions 2 CS 64: Computer Organization and Design Logic Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline More on MIPS Calling Convention Functions calling functions
More informationComputer Architecture Prof. Mainak Chaudhuri Department of Computer Science & Engineering Indian Institute of Technology, Kanpur
Computer Architecture Prof. Mainak Chaudhuri Department of Computer Science & Engineering Indian Institute of Technology, Kanpur Lecture - 7 Case study with MIPS-I So, we were discussing (Refer Time: 00:20),
More informationInstruction Set Architectures (4)
Computer Architecture Week 06 Instruction Set Architectures (4) College of Information Science and Engineering Ritsumeikan University subroutines functions, procedures remember the next instruction s address
More informationFunction Calls. Tom Kelliher, CS 220. Oct. 24, SPIM programs due Wednesday. Refer to homework handout for what to turn in, and how.
Function Calls Tom Kelliher, CS 220 Oct. 24, 2011 1 Administrivia Announcements Assignment SPIM programs due Wednesday. Refer to homework handout for what to turn in, and how. From Last Time Outline 1.
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c/su06 CS61C : Machine Structures Lecture #9: MIPS Procedures 2006-07-11 CS 61C L09 MIPS Procedures (1) Andy Carle C functions main() { int i,j,k,m;... i = mult(j,k);... m =
More informationFunctions and the MIPS Calling Convention 2 CS 64: Computer Organization and Design Logic Lecture #11
Functions and the MIPS Calling Convention 2 CS 64: Computer Organization and Design Logic Lecture #11 Ziad Matni Dept. of Computer Science, UCSB Administrative Lab 5 due end of day tomorrow Midterm: to
More informationComputer Architecture
Computer Architecture Chapter 2 Instructions: Language of the Computer Fall 2005 Department of Computer Science Kent State University Assembly Language Encodes machine instructions using symbols and numbers
More informationCode Generation. Lecture 12
Code Generation Lecture 12 1 Lecture Outline Topic 1: Basic Code Generation The MIPS assembly language A simple source language Stack-machine implementation of the simple language Topic 2: Code Generation
More informationCS 161 Computer Security
Wagner Spring 2014 CS 161 Computer Security 1/27 Reasoning About Code Often functions make certain assumptions about their arguments, and it is the caller s responsibility to make sure those assumptions
More informationConcepts Introduced in Chapter 7
Concepts Introduced in Chapter 7 Storage Allocation Strategies Static Stack Heap Activation Records Access to Nonlocal Names Access links followed by Fig. 7.1 EECS 665 Compiler Construction 1 Activation
More informationQ1: /20 Q2: /30 Q3: /24 Q4: /26. Total: /100
ECE 2035(B) Programming for Hardware/Software Systems Fall 2013 Exam Two October 22 nd 2013 Name: Q1: /20 Q2: /30 Q3: /24 Q4: /26 Total: /100 1/6 For functional call related questions, let s assume the
More informationMIPS R-format Instructions. Representing Instructions. Hexadecimal. R-format Example. MIPS I-format Example. MIPS I-format Instructions
Representing Instructions Instructions are encoded in binary Called machine code MIPS instructions Encoded as 32-bit instruction words Small number of formats encoding operation code (opcode), register
More informationMidterm II CS164, Spring 2006
Midterm II CS164, Spring 2006 April 11, 2006 Please read all instructions (including these) carefully. Write your name, login, SID, and circle the section time. There are 10 pages in this exam and 4 questions,
More informationStorage in Programs. largest. address. address
Storage in rograms Almost all operand storage used by programs is provided by memory. Even though registers are more efficiently accessed by instructions, there are too few registers to hold the stored
More informationMIPS function continued
MIPS function continued Review Functions Series of related instructions one after another in memory Called through the jal instruction Pointed to by a label like any other Returns by calling Stack Top
More informationWeeks 6&7: Procedures and Parameter Passing
CS320 Principles of Programming Languages Weeks 6&7: Procedures and Parameter Passing Jingke Li Portland State University Fall 2017 PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 1 / 45
More informationUsing the MIPS Calling Convention. Recursive Functions in Assembly. CS 64: Computer Organization and Design Logic Lecture #10 Fall 2018
Using the MIPS Calling Convention Recursive Functions in Assembly CS 64: Computer Organization and Design Logic Lecture #10 Fall 2018 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB Administrative Lab
More informationFunctions and Procedures
Functions and Procedures Function or Procedure A separate piece of code Possibly separately compiled Located at some address in the memory used for code, away from main and other functions (main is itself
More informationTopic Notes: MIPS Instruction Set Architecture
Computer Science 220 Assembly Language & Comp. Architecture Siena College Fall 2011 Topic Notes: MIPS Instruction Set Architecture vonneumann Architecture Modern computers use the vonneumann architecture.
More informationContents. Slide Set 2. Outline of Slide Set 2. More about Pseudoinstructions. Avoid using pseudoinstructions in ENCM 369 labs
Slide Set 2 for ENCM 369 Winter 2014 Lecture Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary Winter Term, 2014 ENCM 369 W14 Section
More informationCSE Lecture In Class Example Handout
CSE 30321 Lecture 07-08 In Class Example Handout Part A: J-Type Example: If you look in your book at the syntax for j (an unconditional jump instruction), you see something like: e.g. j addr would seemingly
More informationCS 110 Computer Architecture Lecture 6: More MIPS, MIPS Functions
CS 110 Computer Architecture Lecture 6: More MIPS, MIPS Functions Instructor: Sören Schwertfeger http://shtech.org/courses/ca/ School of Information Science and Technology SIST ShanghaiTech University
More informationThe plot thickens. Some MIPS instructions you can write cannot be translated to a 32-bit number
The plot thickens Some MIPS instructions you can write cannot be translated to a 32-bit number some reasons why 1) constants are too big 2) relative addresses are too big 3) absolute addresses are outside
More informationCPS311 Lecture: Procedures Last revised 9/9/13. Objectives:
CPS311 Lecture: Procedures Last revised 9/9/13 Objectives: 1. To introduce general issues that any architecture must address in terms of calling/returning from procedures, passing parameters (including
More informationLecture 5: Procedure Calls
Lecture 5: Procedure Calls Today s topics: Memory layout, numbers, control instructions Procedure calls 1 Memory Organization The space allocated on stack by a procedure is termed the activation record
More informationCS 61C: Great Ideas in Computer Architecture Func%ons and Numbers
CS 61C: Great Ideas in Computer Architecture Func%ons and Numbers 9/11/12 Instructor: Krste Asanovic, Randy H. Katz hcp://inst.eecs.berkeley.edu/~cs61c/sp12 Fall 2012 - - Lecture #8 1 New- School Machine
More informationCh. 11: References & the Copy-Constructor. - continued -
Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed
More informationLecture 7: Procedures and Program Execution Preview
Lecture 7: Procedures and Program Execution Preview CSE 30: Computer Organization and Systems Programming Winter 2010 Rajesh Gupta / Ryan Kastner Dept. of Computer Science and Engineering University of
More informationLecture 5: Procedure Calls
Lecture 5: Procedure Calls Today s topics: Procedure calls and register saving conventions 1 Example Convert to assembly: while (save[i] == k) i += 1; i and k are in $s3 and $s5 and base of array save[]
More information2/16/2018. Procedures, the basic idea. MIPS Procedure convention. Example: compute multiplication. Re-write it as a MIPS procedure
Procedures, the basic idea CSCI206 - Computer Organization & Programming Introduction to Procedures zybook: 81 (for next class) MIPS Procedure convention 1 Prepare parameters in $a0 through $a3 2 Return
More informationLec 10: Assembler. Announcements
Lec 10: Assembler Kavita Bala CS 3410, Fall 2008 Computer Science Cornell University Announcements HW 2 is out Due Wed after Fall Break Robot-wide paths PA 1 is due next Wed Don t use incrementor 4 times
More informationECE 30 Introduction to Computer Engineering
ECE 30 Introduction to Computer Engineering Study Problems, Set #3 Spring 2015 Use the MIPS assembly instructions listed below to solve the following problems. arithmetic add add sub subtract addi add
More informationLAB C Translating Utility Classes
LAB C Translating Utility Classes Perform the following groups of tasks: LabC1.s 1. Create a directory to hold the files for this lab. 2. Create and run the following two Java classes: public class IntegerMath
More informationCode Generation & Parameter Passing
Code Generation & Parameter Passing Lecture Outline 1. Allocating temporaries in the activation record Let s optimize our code generator a bit 2. A deeper look into calling sequences Caller/Callee responsibilities
More informationProcedure Call and Return Procedure call
Procedures int len(char *s) { for (int l=0; *s!= \0 ; s++) l++; main return l; } void reverse(char *s, char *r) { char *p, *t; int l = len(s); reverse(s,r) N/A *(r+l) = \0 ; reverse l--; for (p=s+l t=r;
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #8: MIPS Procedures 2005-06-30 CS 61C L08 MIPS Procedures (1) Andy Carle Topic Outline Functions More Logical Operations CS 61C L08
More informationECE260: Fundamentals of Computer Engineering. Supporting Procedures in Computer Hardware
Supporting Procedures in Computer Hardware James Moscola Dept. of Engineering & Computer Science York College of Pennsylvania Based on Computer Organization and Design, 5th Edition by Patterson & Hennessy
More informationCS 61C: Great Ideas in Computer Architecture. MIPS Instruction Formats
CS 61C: Great Ideas in Computer Architecture MIPS Instruction Formats Instructor: Justin Hsia 6/27/2012 Summer 2012 Lecture #7 1 Review of Last Lecture New registers: $a0-$a3, $v0-$v1, $ra, $sp Also: $at,
More informationInstructor: Randy H. Katz hap://inst.eecs.berkeley.edu/~cs61c/fa13. Fall Lecture #7. Warehouse Scale Computer
CS 61C: Great Ideas in Computer Architecture Everything is a Number Instructor: Randy H. Katz hap://inst.eecs.berkeley.edu/~cs61c/fa13 9/19/13 Fall 2013 - - Lecture #7 1 New- School Machine Structures
More informationECE 331 Hardware Organization and Design. Professor Jay Taneja UMass ECE - Discussion 3 2/8/2018
ECE 331 Hardware Organization and Design Professor Jay Taneja UMass ECE - jtaneja@umass.edu Discussion 3 2/8/2018 Study Jams Leader: Chris Bartoli Tuesday 5:30-6:45pm Elab 325 Wednesday 8:30-9:45pm Elab
More informationRun-time Environment
Run-time Environment Prof. James L. Frankel Harvard University Version of 3:08 PM 20-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Storage Organization Automatic objects are
More informationCS356: Discussion #6 Assembly Procedures and Arrays. Marco Paolieri
CS356: Discussion #6 Assembly Procedures and Arrays Marco Paolieri (paolieri@usc.edu) Procedures Functions are a key abstraction in software They break down a problem into subproblems. Reusable functionality:
More informationChapter 2. Instructions: Language of the Computer. Adapted by Paulo Lopes
Chapter 2 Instructions: Language of the Computer Adapted by Paulo Lopes Instruction Set The repertoire of instructions of a computer Different computers have different instruction sets But with many aspects
More informationThomas Polzer Institut für Technische Informatik
Thomas Polzer tpolzer@ecs.tuwien.ac.at Institut für Technische Informatik Branch to a labeled instruction if a condition is true Otherwise, continue sequentially beq rs, rt, L1 if (rs == rt) branch to
More informationcomp 180 Lecture 10 Outline of Lecture Procedure calls Saving and restoring registers Summary of MIPS instructions
Outline of Lecture Procedure calls Saving and restoring registers Summary of MIPS instructions Procedure Calls A procedure of a subroutine is like an agent which needs certain information to perform a
More informationThe plot thickens. Some MIPS instructions you can write cannot be translated to a 32-bit number
The plot thickens Some MIPS instructions you can write cannot be translated to a 32-bit number some reasons why 1) constants are too big 2) relative addresses are too big 3) absolute addresses are outside
More informationArchitecture II. Computer Systems Laboratory Sungkyunkwan University
MIPS Instruction ti Set Architecture II Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Making Decisions (1) Conditional operations Branch to a
More informationCS 316: Procedure Calls/Pipelining
CS 316: Procedure Calls/Pipelining Kavita Bala Fall 2007 Computer Science Cornell University Announcements PA 3 IS out today Lectures on it this Fri and next Tue/Thu Due on the Friday after Fall break
More informationChapter 10 Memory Model for Program Execution. Problem
Chapter 10 Memory Model for Program Execution Original slides by Chris Wilcox, Colorado State University Problem How do we allocate memory during the execution of a program written in C?! Programs need
More information