ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.

Slides:



Advertisements
Similar presentations
Assembly Language for x86 Processors 6th Edition Chapter 5: Procedures (c) Pearson Education, All rights reserved. You may modify and copy this slide.
Advertisements

There are two types of addressing schemes:
1 Lecture 4: Procedure Calls Today’s topics:  Procedure calls  Large constants  The compilation process Reminder: Assignment 1 is due on Thursday.
Procedures in more detail. CMPE12cGabriel Hugh Elkaim 2 Why use procedures? –Code reuse –More readable code –Less code Microprocessors (and assembly languages)
The University of Adelaide, School of Computer Science
The Assembly Language Level
EENG 4005 Microprocessors.
Procedures and Stacks. Outline Stack organization PUSH and POP instructions Defining and Calling procedures.
Subroutines: Passing Arguments Using the Stack. Passing Arguments via the Stack Arguments to a subroutine are pushed onto the stack. The subroutine accesses.
More about procedures and Video Processing. Lesson plan Review existing concepts More about procedures and boolean expression Video processing.
Azir ALIU 1 What is an assembly language?. Azir ALIU 2 Inside the CPU.
1 Storage Registers vs. memory Access to registers is much faster than access to memory Goal: store as much data as possible in registers Limitations/considerations:
1 ICS 51 Introductory Computer Organization Fall 2006 updated: Oct. 2, 2006.
1 Lecture 5: Procedures Assembly Language for Intel-Based Computers, 4th edition Kip R. Irvine.
Chapter 12: High-Level Language Interface. Chapter Overview Introduction Inline Assembly Code C calls assembly procedures Assembly calls C procedures.
Run time vs. Compile time
Semantics of Calls and Returns
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
ICS312 Set 11 Introduction to Subroutines. All the combinations in which a subroutine can be written 1. The subroutine may be: a. Internal or b. External.
Chapter 8 :: Subroutines and Control Abstraction
Universal Concepts of Programming Creating and Initializing local variables on the stack Variable Scope and Lifetime Stack Parameters Stack Frames Passing.
Introduction to Subroutines. All the combinations in which a subroutine can be written 1. The subroutine may be: a. Internal or b. External 2. The type.
Lecture 11 Last notes on interrupts and exam review Dr. Dimitrios S. Nikolopoulos CSL/UIUC.
Objective At the conclusion of this chapter you will be able to:
Richard P. Paul, SPARC Architecture, Assembly Language Programming, and C Chapter 7 – Subroutines These are lecture notes to accompany the book SPARC Architecture,
Strings, Procedures and Macros
Lecture 7 A closer look at procedures Dr. Dimitrios S. Nikolopoulos CSL/UIUC.
Computer Architecture and Operating Systems CS 3230 :Assembly Section Lecture 4 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
Implementing Subprograms What actions must take place when subprograms are called and when they terminate? –calling a subprogram has several associated.
Module R3 Process Scheduling. Module R3 involves the creation of a simple “Round Robin” dispatcher. The successful completion of this module will require.
UHD:CS2401: A. Berrached1 The Intel x86 Hardware Organization.
4-Oct Fall 2001: copyright ©T. Pearce, D. Hutchinson, L. Marshall Sept  direct mode: OK for static addresses  indirect register mode:
Microprocessors The ia32 User Instruction Set Jan 31st, 2002.
ITCS 3181 Logic and Computer Systems 2015 B. Wilkinson Slides4-2.ppt Modification date: March 23, Procedures Essential ingredient of high level.
by Richard P. Paul, 2nd edition, 2000.
Subroutines: Passing Arguments Using the Stack. Passing Arguments via the Stack Arguments to a subroutine are pushed onto the stack. The subroutine accesses.
CSC 8505 Compiler Construction Runtime Environments.
The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.
EEL 3801 Part IV The Assembler. OFFSET Operator Returns address of variable used as operand. Actually, it represents the offset from the beginning of.
Lecture 9 (The Stack and Procedures). 1 Lecture Outline Introduction The Stack The PUSH Instruction The POP Instruction Terminology of Procedures INDEC.
Assembly 08. Outline Local Labels Jump Lengths External Libraries Macros 1.
ARM-7 Assembly: Example Programs 1 CSE 2312 Computer Organization and Assembly Language Programming Vassilis Athitsos University of Texas at Arlington.
Calling Procedures C calling conventions. Outline Procedures Procedure call mechanism Passing parameters Local variable storage C-Style procedures Recursion.
ECE291 Computer Engineering II Lecture 8 Josh Potts University of Illinois at Urbana- Champaign.
ICS312 Set 12 Subroutines: Passing Arguments Using the Stack.
Preocedures A closer look at procedures. Outline Procedures Procedure call mechanism Passing parameters Local variable storage C-Style procedures Recursion.
Internal Programming Architecture or Model
LECTURE 19 Subroutines and Parameter Passing. ABSTRACTION Recall: Abstraction is the process by which we can hide larger or more complex code fragments.
7-Nov Fall 2001: copyright ©T. Pearce, D. Hutchinson, L. Marshall Oct lecture23-24-hll-interrupts 1 High Level Language vs. Assembly.
I NTEL 8086 M icroprocessor بسم الله الرحمن الرحيم 1.
Procedures Dr. Hadi Al Saadi Large problems can be divided into smaller tasks to make them more manageable A procedure is the ASM equivalent of a Java.
Assembly language programming
Instruction set Architecture
Format of Assembly language
Data Transfers, Addressing, and Arithmetic
COURSE OUTCOMES OF Microprocessor and programming
Microprocessor and Assembly Language
Microprocessor and Assembly Language
Introduction to Compilers Tim Teitelbaum
Assembly Language Programming Part 2
(The Stack and Procedures)
Chapter 9 :: Subroutines and Control Abstraction
Programming 8086 – Part IV Stacks, Macros
(The Stack and Procedures)
by Richard P. Paul, 2nd edition, 2000.
Morgan Kaufmann Publishers Computer Organization and Assembly Language
(The Stack and Procedures)
Procedures & Macros Introduction Syntax Difference.
Procedures and Macros.
Presentation transcript:

ECE291 Lecture 6 Procedures and macros

ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable storage C-Style procedures RecursionMacros

ECE 291 Lecture 6Page 3 of 36 Procedures defined Procedures are chunks of code that usually perform specific frequently used tasks They can be repeatedly called from someplace else in your programs These are essentially the same thing as functions or subroutines in high-level languages Procedures may have inputs/outputs, both, either, neither Essentially just labeled blocks of assembly language instructions with a special return instruction at the end

ECE 291 Lecture 6Page 4 of 36 Procedure example..start ;here’s my main program mov ax, 10h mov bx, 20h mov cx, 30h mov dx, 40h call AddRegs;this proc does AX + BX + CX + DX  AX ;here’s the rest of my main program call DosExit ; AddRegs add ax, bx add ax, cx add ax, dx ret

ECE 291 Lecture 6Page 5 of 36 Proc prime directive Procs should never alter the contents of any register that the procedure isn’t explicitly supposed to modify If for example a proc is supposed to return a value in AX, it is not only okay but required for it to modify AX No other registers should be left changed Push them at the beginning and pop them at the end

ECE 291 Lecture 6Page 6 of 36 Call Call does two things It pushes the address of the instruction immediately following the call statement onto the stack It pushes the address of the instruction immediately following the call statement onto the stack It loads the instruction pointer with the value of the label marking the beginning of the procedure you’re calling (this is essentially an unconditional jump to the beginning of the procedure It loads the instruction pointer with the value of the label marking the beginning of the procedure you’re calling (this is essentially an unconditional jump to the beginning of the procedure

ECE 291 Lecture 6Page 7 of 36 Two kinds of calls Near calls Allow jumps to procedures within the same code segment Allow jumps to procedures within the same code segment In this case, only the instruction pointer gets pushed onto the stack In this case, only the instruction pointer gets pushed onto the stack Far calls Allow jumps to anywhere in the memory space Allow jumps to anywhere in the memory space In this case, both the contents of the CS and IP registers get pushed onto the stack In this case, both the contents of the CS and IP registers get pushed onto the stack

ECE 291 Lecture 6Page 8 of 36 Passing parameters Using registers Registers are the ultimate global variables Registers are the ultimate global variables Your proc can simply access information the calling program placed in specific registers Your proc can simply access information the calling program placed in specific registers Also a simple way for your proc to send data back to the caller Also a simple way for your proc to send data back to the caller The previous example used this method The previous example used this method

ECE 291 Lecture 6Page 9 of 36 Passing parameters Using global memory locations Memory locations declared at the beginning of your program are global and can be accessed from any procedure Memory locations declared at the beginning of your program are global and can be accessed from any procedure Using a parameter block You may pass a pointer to an array or other type of memory block instead of an individual data value You may pass a pointer to an array or other type of memory block instead of an individual data value

ECE 291 Lecture 6Page 10 of 36 Passing parameters Using the stack Caller pushes all arguments expected by the proc onto the stack Caller pushes all arguments expected by the proc onto the stack Proc can access these args directly from the stack by setting up the stack frame. Proc can access these args directly from the stack by setting up the stack frame. push bp; save value of bp mov bp, sp; mark start of stack frame arg1 is at [ss:bp+4] assuming call arg1 is at [ss:bp+6] assuming call far

ECE 291 Lecture 6Page 11 of 36 Example ;call proc to calculate area of right triangle. ;proc expects two word sized args to be on the stack push 3 push 4 call TriangleArea ;now we must remove the variables from the stack ;every push must be popped. add sp, 4 ; ax now contains 6

ECE 291 Lecture 6Page 12 of 36 Example continued TriangleArea push bp mov bp, sp y equ bp+4;[bp+4] = y x equ bp+6;[bp+6] = x push dx mov ax, [y];same as mov ax, [bp+4] mul word [x];same as mul word, [bp+6] shr ax, 1;divide by two pop dx pop bp ret

ECE 291 Lecture 6Page 13 of 36 What just happened… E C A SP 0003h SS:0000 Saved BP 0004h Return IP Push 3 Push 4 Call TriangleArea TriangleArea push bp mov bp, sp push dx mov ax, [bp+4] mul word [bp+6] shr ax, 1 pop dx pop bp ret Add sp, 4 Saved DXSP Stack frame BP

ECE 291 Lecture 6Page 14 of 36 Local variable storage You may allocate stack space for use as local variables within procedures Subtract from the stack pointer the number of bytes you need to allocate after setting up the stack frame At the end of your procedure, just add the same amount you subtracted to free the memory you allocated just before you pop bp In the procedure, use the stack frame to address local variable storage

ECE 291 Lecture 6Page 15 of 36 Local variable storage MyProc ;setup stack frame push bp mov bp, sp;allocate space for two words sub sp, 4;access words at [bp-2] and [bp-4] … add sp, 4;destroy local variables pop bp;restore original bp ret

ECE 291 Lecture 6Page 16 of 36 Things to remember Always make sure that your stack is consistent (a proc doesn’t leave information on the stack that wasn’t there before the procedure ran) Always remember to save registers you modify that don’t contain return values

ECE 291 Lecture 6Page 17 of 36 C style procedures Assembly procedures that can be called by C programs Must follow the same calling procedure that C compilers use when building C programs You can also call C functions from assembly programs using the same protocol

ECE 291 Lecture 6Page 18 of 36 C style procedures Suppose a C program calls an assembly procedure as follows Proc1(a, b, c) Proc1(a, b, c) Assume each argument is word-sized Further, assume the C compiler generates code to push a, b, and c onto the stack The assembly language procedure must be assembled with the correct ret (near or far) and stack handling of its procedures matching the corresponding values in the high-level module

ECE 291 Lecture 6Page 19 of 36 C style procedures Assume C program always makes far call So far return (retf) must end the C style procedure So far return (retf) must end the C style procedure Return CS gets pushed onto the stack as well as return IP Return CS gets pushed onto the stack as well as return IP Makes a difference when accessing arguments using the stack frame Makes a difference when accessing arguments using the stack frame C compilers push arguments in reverse order, from right to left. C is pushed first, then B, then A C is pushed first, then B, then A Lowest index from BP corresponds to first argument Lowest index from BP corresponds to first argument BP+10 BP+8 BP+6 BP+4 BP+2 BP c Return CS b a Return IP Saved BP Proc1(a, b, c)

ECE 291 Lecture 6Page 20 of 36 C style procedures If the returned value needs four or fewer bytes, it is by default returned in registers one or two bytes - returned in AX one or two bytes - returned in AX three or four bytes - returned in AX (low word) and in DX (high byte or word), (in EAX in 32-bit mode) three or four bytes - returned in AX (low word) and in DX (high byte or word), (in EAX in 32-bit mode) More than four bytes the called procedure stores data in some address and returns the offset and segment parts of that address in AX and DX, respectively the called procedure stores data in some address and returns the offset and segment parts of that address in AX and DX, respectively

ECE 291 Lecture 6Page 21 of 36 C style procedures Caller is responsible for clearing the arguments from the stack as soon as it regains control after the call this done by the compiler that generates the appropriate code this done by the compiler that generates the appropriate code a far procedure called from C should end with RETF instead of RET a far procedure called from C should end with RETF instead of RET

ECE 291 Lecture 6Page 22 of 36 Example Calling and ASM proc from a C program – the proc lets you display a string at a given row and column # include # include extern void placeStr (char *, unsigned, unsigned); voidmain (void) { intn; for (n = 10; n < 20; ++n) placeStr (“This is the string”, n, 45); placeStr (“This is the string”, n, 45);}

ECE 291 Lecture 6Page 23 of 36 Example GLOBAL_placeStr SEGMENT code _placeStr ; setup stack frame and save state PUSHBP MOVBP, SP PUSHAX PUSHBX PUSHDX ; get current page - returns in BH MOVAH, 0fh INT10h ; read unsigned args 2 and 3 MOVDL, [BP+10] MOVDH, [BP+8] ;set cursor position MOV AH, 02h INT 10h ;point to string MOV BX, [BP+6] ;call outAsc to disp string call outAsc ;restore state POP DX POP BX POP AX POP BP RETF

ECE 291 Lecture 6Page 24 of 36 Putting the two together The C module must be compiled The assembly language module assembled The pair must be linked together into an executable Extern in C is exactly the same as Extern in assembly programs Notice that the procedure is named _placeStr, because C compilers preface all external variables with an underscore

ECE 291 Lecture 6Page 25 of 36 Complete calling procedure Program writes function parameters to stack (C is right-pusher) CALL saves program’s return address on the stack [PUSH CS (Far Proc); PUSH IP] CALL saves program’s return address on the stack [PUSH CS (Far Proc); PUSH IP] Routine marks stack frame (PUSH BP; MOV BP, SP) Routine marks stack frame (PUSH BP; MOV BP, SP) Routine allocates stack memory for local variables (SUB SP, n) Routine allocates stack memory for local variables (SUB SP, n) Routine saves registers it modifies (push SI, push BX, push CX) Routine saves registers it modifies (push SI, push BX, push CX) Subroutine Code Additional CALLs, PUSHs, POPs) Routine restores registers it modifies (pop CX, pop BX, pop SI) Routine restores registers it modifies (pop CX, pop BX, pop SI) Routine deallocates stack memory for local variables (ADD SP, n) Routine deallocates stack memory for local variables (ADD SP, n) Routine restores original value of BP (POP BP) Routine restores original value of BP (POP BP) Subroutine Returns (RETF) Subroutine Returns (RETF) Program clears parameters from stack (ADD SP,p)

ECE 291 Lecture 6Page 26 of 36 Recursion Recursion: procedure calls itself RecursiveProc DECAX JZ.QuitRecursion CALLRecursiveProc.QuitRecursion:RET Requires a termination condition in order to stop infinite recursion Many recursively implemented algorithms are more efficient than their iterative counterparts

ECE 291 Lecture 6Page 27 of 36 Recursion example Factorial ; Input AX = CX = Value ; Output AX = Value ! DEC CX ;Test for base case CMP CX,0 JE.FactDone IMUL CX ; Recurs Call Factorial.FactDone:RET Stack contents Assume: AX = CX = 4 Return IP Iteration 1 CX = 4; AX = 4 Return Iteration IP 2 CX = 3; AX = 12 Return Iteration IP 3 CX = 2; AX = 24 Return Iteration IP 4 CX = 1; AX = 24

ECE 291 Lecture 6Page 28 of 36 Recursion Recursion must maintain separate copies of all pertinent information (parameter value, return address, local variables) for each active call Recursive routines can consume a considerable amount of stack space Remember to allocate sufficient memory in your stack segment when using recursion In general you will not know the depth to which recursion will take you allocate a large block of memory for the stack allocate a large block of memory for the stack

ECE 291 Lecture 6Page 29 of 36 Macros A macro inserts a block of statements at various points in a program during assembly Substitutions made at compile time Not a procedure—code is literally dumped into the program with each instantiation Not a procedure—code is literally dumped into the program with each instantiation Parameter names are substituted Parameter names are substituted Useful for tedious programming tasks Useful for tedious programming tasks

ECE 291 Lecture 6Page 30 of 36 Macros Generic Format %macro MACRO_NAME numargs Your Code %{1}... … %{2}... Your Code... JMP %MyLabel Your Code... %MyLabel:... %{N}... Your Code... %endmacro

ECE 291 Lecture 6Page 31 of 36 Local Variables in a Macro A local label is one that appears in the macro, but is not available outside the macro We use the % prefix for defining a local label If the label MyLabel in the previous example is not defined as local, the assembler will flag it with errors on the second and subsequent attempts to use the macro because there would be duplicate label names If the label MyLabel in the previous example is not defined as local, the assembler will flag it with errors on the second and subsequent attempts to use the macro because there would be duplicate label names Macros can be placed in a separate file use %include directive to include the file with external macro definitions into a program use %include directive to include the file with external macro definitions into a program no EXTERN statement is needed to access the macro statements that have been included no EXTERN statement is needed to access the macro statements that have been included

ECE 291 Lecture 6Page 32 of 36 Macros ; Store into Result the signed result of X / Y ; Calculate Result = X / Y ; (all 16-bit signed integers) ; Destroys Registers AX,DX %macro DIV16 3; Args: Result, X, Y MOV AX, %{2} ; Load AX with Dividend CWD ; Extend Sign into DX IDIV %{3} ; Signed Division MOV %{1}, AX ; Store Quotient %endmacro

ECE 291 Lecture 6Page 33 of 36 Macros ; Example: Using the macro in a program ; Variable Section varX1 DW 20 varX2 DW 4 varR RESW ; Code Section DIV16 word [varR], word [varX1], word [varX2] ;Will actually generate the following code inline in your program for every instantiation of the DIV16 macro (You won't actually see this unless you debug the program). MOV AX, word [varX1] CWD IDIV word [varX2] MOV word [varR], AX

ECE 291 Lecture 6Page 34 of 36 Macros vs. Procedures Proc_1 MOVAX, 0 MOVBX, AX MOVCX, 5 RET %macro Macro_1 0 MOVAX, 0 MOVAX, 0 MOVBX, AX MOVBX, AX MOVCX, 5 MOVCX, 5%endmacro CALL Proc_1 … …Macro_1…Macro_1

ECE 291 Lecture 6Page 35 of 36 Macros vs. Procedures In the example the macro and procedure produce the same result The procedure definition generates code in your executable The macro definition does not produce any code Upon encountering Macro_1 in your code, NASM assembles every statement between the %macro and %endmacro directives for Macro_1 and produces that code in the output file At run time, the processor executes these instructions without the call/ret overhead because the instructions are themselves inline in your code

ECE 291 Lecture 6Page 36 of 36 Macros vs. Procedures Advantage of using macros execution of macro expansion is faster (no call and ret) than the execution of the same code implemented with procedures execution of macro expansion is faster (no call and ret) than the execution of the same code implemented with proceduresDisadvantages assembler copies the macro code into the program at each macro invocation assembler copies the macro code into the program at each macro invocation if the number of macro invocations within the program is large then the program will be much larger than when using procedures if the number of macro invocations within the program is large then the program will be much larger than when using procedures