Advanced Compilers Code Generation. Fall Chungnam National Univ. Eun-Sun Cho
|
|
- Victor Benjamin Harper
- 6 years ago
- Views:
Transcription
1 Advanced Compilers Code Generation Fall Chungnam National Univ. Eun-Sun Cho 1
2 Backend of Compilers Machine -independent Optimization Machine-independent Optimization Virtual to physical Mapping / Machine-dependent Optimization Instruction Selection Instruction Scheduling Register Allocation Machine Code Emission/Opti Backend = Code generation + Optimization
3 Storage Management Exception Handling Instruction Selection Register Allocation Code Generation 3
4 Storage Management 4
5 Management of Storage In compiler generated machine codes, memory management codes play critical roles. #include <stdio.h> void main(){ int i; printf( Hello, CSE!\n ); }.file "s09.c".section.rodata.lc0:.string "Hello, CSE!".text.globl main.type main: pushl %ebp allocate stack movl %esp, %ebp memory for subl $20, %esp int i, and the string movl $.LC0, (%esp) parameter call puts compile addl $20, %esp popl %ebp ret.size main,.-main 5
6 2 Classes of Storage in Process Registers Fast access Invisible for users (programmers) in most cases NO indirect access is allowed Memory (relatively) Slow access, indirect accesses are allowed Candidates: Globals/statics, Composite types (structs, arrays..), Variables accessed via & operator *Whether a variable is translated as a register or a memory variable should be determined in the middle of HIR to LIR translation
7 4 Categories of Memory Code space : an area of memory for instruction sequence read-only, if possible Static (or Global) an area of memory for a set of variables with the same life time as the program Stack an area of memory for a set of local variables (with block life time) Heap an area of dynamically allocated memory by System calls (via malloc, new, etc.)
8 Memory Organization Stack... Heap Static Data Code stack, heap : variable sizes at runtime Stack: grows upward Heap; grows downward The relative positions of stack/heap might be switched code, static data : fixed sizes (by the compiler)
9 Executable Formats Windows PE (Portable Excutable) ELF (Executable and Linkable Format) 9
10 Memory Organization Stack... Heap Static Data Code stack, heap : variable sizes at runtime Stack: grows upward Heap; grows downward The relative positions of stack/heap might be switched code, static data : fixed sizes (by the compiler)
11 Run-time stack A stack made of frames one frame (or an activation record) for each function call Activation record : execution environment for execution of a corresponding function Each call has one frame even for recursive calls contents: local variables, arguments, return values, other temporary storage... Heap allocation a contiguous portion of the global area, returned from OS operations for memory-request and memory-return during the program execution are necessary, otherwise, garbage collection should be supported in the programming language keep available memory categorized into free section and in-use section (see OS textbook!)
12 Initial Stack Frame (startup state) Command line arguments argc, argv Environment variables (env) NULL env[0] env[1] env[n] NULL argv[1] argv[arc-1] argv[0] argc end of environment (integer) environment variables (pointers) end of args (integer) program args (pointer) program name (poiner) argument counter (integer) bottom top <Initial stack layout for ELF binaries> A figure in used with some modificcation address decreasing
13 stack system env / argv / argc stack frame for main() available for stack growth higher addr. ebp of main() stack pointer : esp Runtime Layout (ELF) shared library malloc.o (lib*.so) printf.o (lib*.so) library functions (dynamically linked) available for heap heap data text heap (malloc(), calloc(), new) int x; (global var) int y = 100; (global var) xx.o (lib*.a) xxx.o (lib*.a) file.o what existed from before loading.text,.data.. library functions (static linked) What if main() calls function func(72, 73)? (a.out) main.o func(72,73); crt0.o (startup routine) lower addr. 13
14 stack system env / argv / argc stack frame for main() stack frame for func() available for stack growth higher addr. ebp of main() ebp of func() stack pointer : esp Runtime Layout (ELF) ; while executing func() shared library malloc.o (lib*.so) printf.o (lib*.so) library functions (dynamically linked) available for heap heap data text heap (malloc(), calloc(), new) int x; (global var) int y = 100; (global var) xx.o (lib*.a) xxx.o (lib*.a) file.o (a.out) main.o func(72,73); crt0.o (startup routine) what existed from before loading.text,.data.. library functions (static linked) lower addr. What if main() calls function func(72, 73)? 14
15 Functions and Run-time stacks Call/return of a function and run-time stack operation when f is called, push f s frame to RT stack when f is returned, pop-up f s frame from RT stack Top frame = frame of the function currently being executed How to access the top frame? Stack pointer (esp): top position of the frame Base pointer (ebp): base position of the frame A local variable is accessed via its offset from FP (or SP) Role of Compiler to generate codes which force the above system 15
16 When main()calls func(72, 73) stack system env / argv / argc mpf main() s local variables y frame for main() x +4 ra return address ebp 0 mpf caller s frame pointer func( -4 garbage a -8 garbage b[2] -12 garbage b[1] frame for func() { int x, int y) int a; -16 garbage b[0] int b[3]; esp available for stack growth 16
17 mpf ebp esp stack Variables and Arguments func(72, 73) system env / argv / argc main() s local variables y x +4 ra return address 0 mpf caller s frame pointer -4 garbage a -8 garbage b[2] -12 garbage b[1] -16 garbage b[0] available for stack growth [ebp+4] : return address [ebp+8] : 72, that is, x [ebp+12] : 73, that is, y [ebp] : main() s ebp a b[1] frame for main() frame for func() : [ebp-4] : [ebp-12] func( { int x, int y) int a; int b[3]; 17
18 mpf ebp esp stack Variables and Arguments system env / argv / argc func(72, 73) main() s local variables y x +4 ra return address 0 mpf caller s frame pointer -4 garbage a -8 garbage b[2] -12 garbage b[1] -16 garbage b[0] available for stack growth push 73 ; y push 72 ; x call func ; frame for main() frame for func() func( { int x, int y) int a; int b[3]; 18
19 Alignment In most cases, a variable is aligned based on its size eg. C/C++ : char byte aligned, short halfword aligned, int word aligned char w; eg. int x[3] char y; short z; char w 1 byte x[3] 12 bytes, starting at a word aligned address (3 empty bytes between w and x) char y 1byte, starting at any address short z 2 bytes, starting at a halfword aligned address (1 empty byte between y and z) Total size = 20 bytes!
20 Alignment of Structures struct { char w; int x[3] char y; short z; } fields in struct : align to the largest field size eg. the largest field is int (4 bytes) size of the struct : a multilcation of 4 starting address of the struct : also a multiplication of 4 word aligned
21 Example. GCC-x x 16 for i and 4 for the string pointer in gcc-x86 16 for i, because of their own alignment policy #include <stdio.h> void main(){ } int i; printf( Hello,CSE!\n );.file "s09.c".section.rodata.lc0:.string "Hello, CSE!".text.globl main.type main: pushl %ebp movl %esp, %ebp subl $20, %esp movl $.LC0, (%esp) compile call puts addl $20, %esp popl %ebp ret.size main,.-main allocate stack memory for int i, and the string parameter 21
22 Exception Handling Codes 22
23 Exceptions Exception is for error-handling invalid input invalid resource state file not exists, network error, erroraneous execution condition divide-by-zero, In real production code, error-handling code may be a large part (30%-50% or more) 23
24 C++ #include <iostream> #include <fstream> using namespace std; int main () { ifstream file; //Set the state flags for which a failure exception is thrown. file.exceptions ( ifstream::failbit ifstream::badbit ); try { file.open ("test.txt"); while (!file.eof()) file.get(); } catch (ifstream::failure e) { } cout << "Exception opening/reading file"; file.close(); class ios_base::failure : public exception { // the exceptions thrown by the elements of // the standard input/output library public: explicit failure (const string& msg); virtual ~failure(); virtual const char* what() const noexcept; } flag values of std::ios_base::iostate eofbit failbit badbit goodbit 24
25 Java InputStream input = null; try{ input = new FileInputStream("c:\\data\\input-text.txt"); int data = input.read(); while(data!= -1) { //do something with data... dosomethingwithdata(data); data = input.read(); } }catch(ioexception e){ //do something with e... log, perhaps rethrow etc. } finally { if(input!= null) input.close(); } Note : C++ does not support 'finally' blocks. 25
26 Throw int main () { } try { throw 20; } catch (int e) { } cout << "An exception occurred. Exception Nr. " return 0; << e << endl; An exception occurred. Exception Nr
27 Chaining InputStream input = null; try{ input = new FileInputStream("c:\\data\\input-text.txt"); int data = input.read(); while(data!= -1) { //do something with data... dosomethingwithdata(data); data = input.read(); } }catch(ioexception e){ throw new MyException(); } 27
28 What Should Do for An Exception Occurs try { f(1); Object x; g(2); }catch (Exc) { } when an exception occurs when an exception occurs // handler goto handler A destroy x + goto handler A handler A: catches type Exc Note: Try can be nested, so the handlers are organized in a stack 28
29 Basic Exception Handling Mechanism 1 Setjmp/longjmp-based global goto C s primitive exception 2 Table-driven method more complex and more space usage but faster 29
30 1 Setjmp/longjmp #include < setjmp.h > main() { jmp_buf env; int i; i = setjmp(env); printf("i = %d\n", i); if (i!= 0) exit(0); longjmp(env, 2); printf("get printed?\n"); } setjmp() : save the contents of the registers longjmp() : restore them later. ``returns'' to the state of the program when setjmp() was called. $ sj1 i = 0 i = 2 $ _ First, we call setjmp(), and it returns 0. Then we call longjmp() with a value of 2, which causes the code to return from setjmp() with a value of 2. That value is printed out, and the code exits. ( get printed? will not be printed) 30
31 Setjmp/longjmp Approach buffer buf; void f() { if (0 == setjmp(buf)) g(); } void g() { h(); } void h() { longjmp(buf, 1); } struct context { int ebx; int edi; int esi; int ebp; int esp; int eip; }; typedef struct context buffer[1]; 31
32 Setjmp/longjmp Approach Conts' buffer buf; void f () { if (0==setjmp (buf)) g (); else k(); } void g () { h (); } void h () { longjmp (buf, 1); } try..catch Save the context before try block This context also calls handler Handle exception with k() throws Fetch the handler, restore machine states and jump to the handler s code 32
33 2 Table Driven Approach Table 1 : Each throw point to its action table from the program counter (PC) at the point where the exception is thrown to an action table Table 2 : Action table perform the various operations required for exception processing eg. invoking destructors adjusting the stack matching the exception type to the address of an exception handling 33
34 Discussions All variables that are declared outside the try block have to be restored to their initial value Lecture s = new Lecture(); // s.lecturer is assumed initially null try { s.lecturer = new ThatMan(); FileInputStream(); // exception! // s.lecturer (in memory) should be restored... } catch (IOException e) {...} 34
35 Discussions Setjmp/longjmp approach setjump should be called at the beginning of every try block even if no exception is ever thrown list of buf must be maintained list of objects on the stack must be maintained (in C++) 35
36 Discussions Conts Table driven approach Mostly used Significantly more efficient than setjmp/longjmp approach Table themselves have to encode a lot of possible actions Space problem Reorganizing the code implies reorganizing the table accordingly Vulnerable to attack Compiler optimization should not be allowed void f(){ int x = 0; // dead code, but cannot be optimized out try { x = f1(x); } catch ( ) { cout << ;} } 36
37 Exception Handling in GIMPLE throw is NOT directly supported BUT by function calls 37
38 invoking destructors and adjusting the stack 38
39 for throwing an exception ref 39
40 Instruction Selection 40
41 Low-level, Tree-based Intermediate Representation Tree-based IR With abstract machine instructions used in machine code generation eg) from Tiger book MEM cf. RTL BINOP PLUS CONST e c e + c 41
42 Tree-based Intermediate Representation from Tiger book MEM(e) : this means the value of one word of memory starting at the address e. When this is used at left-hand side of MOVE, it is interpreted as store, otherwise it means a fetch operation TEMP(t) : register t SEQ (s1, s2) : after evaluation of statement s1, statement s2 is evaluated ESEQ(s,e) : statement s evaluated for side effects and then e is evaluated for a result BINOP(o, e1, e2) : o is a binary operator like PLUS and MINUS. The result is the evaluation of o with e1 and e2 as operands This result is saved in memory and the address is returned const(i) : integer constant i 42
43 Simple Equivalence Relationships We can choose one among the sub-trees of the same semantics ESEQ ESEQ s1 ESEQ SEQ e s2 e s1 s2 43
44 op BINOP e1 ESEQ s e2 ESEQ MOVE TEMP e1 t ESEQ s BINOP op TEMP e2 t BINOP BINOP ESEQ op e1 ESEQ op ESEQ e2 s BINOP s e2 s e1 op e1 e2 44
45 More Instruction Selection (Option1) MOVE MEM MEM BINOP BINOP PLUS MEM BINOP PLUS TEMP CONST PLUS BINOP TEMP fp MULT TEMP CONST i a CONST 4 fp x 45
46 More Instruction Selection (Option2) MOVE MEM MEM BINOP BINOP PLUS MEM BINOP PLUS TEMP CONST PLUS BINOP TEMP fp MULT TEMP CONST i a CONST 4 fp x 46
47 Equivalence of The Machine Codes LOAD r1 M[fp+a] ADDI r2 r0 + 4 MUL r2 ri r2 ADD r1 r1 + r2 LOAD r2 M[fp+x] STORE M[r1+0] r2 LOAD r1 M[fp+a] ADDI r2 r0 + 4 MUL r2 ri r2 ADD r1 r1 + r2 LOAD r2 fp + x STORE M[r1] M[r2] 47
48 Register Allocation 48
49 Operand in Low Level IR Review Operands Virtual registers We assume infinitely many virtual registers Special registers stack pointer, pc, Literals We assume there is no limits of values of literals Symbolic names in most cases, labels 49
50 Register Allocation Motivation Virtual register (VR) Although we assume infinitely many virtual registers The number of actual registers is finite, and various from machine to machine Register allocation Put as many as VRs to physical registers, and allocate the remained VRs to memory Optimization for the best performance : put frequently used VRs to physical registers Spilling : allocating virtual registers to memory, inevitably
51 Interference Interference : two different definitions have a common operations in their live ranges Live range : generated from liveness analysis and reaching definition analysis Interference graph Nodes of the graph = variables Edges : linked if two nodes interfere each other 1: a = 0 2: b = a 3: b*b 4: c = 2 5: a*c+3 b a c For def1 a = {1,2,3,4,5} For def2 b = {2,3} For def4 c = {4,5} examples and materials from Princeton Univ. 51
52 Graph Coloring Graph Coloring Used to allocate virtual registers (that is, variables) to physical registers Linked nodes should be painted in different colors Simple example: Two registers : 2-coloring (two colors) color register 1: a = 0 2: b = a 3: b*b 4: c = 2 5: a*c+3 b a c eax ebx
53 K-Graph Coloring Algorithm Kempe s algorithm [1879] --- Old problem Step 1 (simplify) Find a node linked with less than k edges, and cut that node with the edges linked to it save these to a stack Step 2 (color) if a remaining graph is a simplied subgraph and can be k-graphed colored pop a node (and all the related edges pushed together) from the stack, and color the node in different colors from all the neighbor nodes Step 3 (Spill) optional If failed with above the algorithm Actually Step1~step2 is not applicable to many cases Graph coloring is NP-complete problem Solution : select several (victim) variables and allocate them to memory 53
54 Step 1 stack: a stack: a c b c e c b c d e d e stack: b a e c b a c stack: a e c b a c d e d e
55 stack: b a e c b a c Step 2 stack: a e c b a c d e d e stack: a stack: a c b c e c b c d e d e
56 Case of Step 3(1) Some lucky cases! color register eax a ebx b c stack: d d e all nodes have 2 neighbours!
57 Case of Step 3 (2) But there exist graphs where coloring with only k colors is impossible spilling! a b c d e no colors left for e or a!
58 Spilling code Code rewriting Introduce new temporary, and rewrite codes eg. Assuming that t2 is supposed to be spilled Then, add t1, t2 will be; define a memory area bound to to-be-spilled variables (here, t2) eg. [ebp-24] in runtime stack and introduce a new temporary variable (here, t35) mov t35, [ebp 24] add t1, t35 note : t35 s live range is very short (one or two commands) so possibility of interference is very low (much less than t2)
x86 assembly CS449 Fall 2017
x86 assembly CS449 Fall 2017 x86 is a CISC CISC (Complex Instruction Set Computer) e.g. x86 Hundreds of (complex) instructions Only a handful of registers RISC (Reduced Instruction Set Computer) e.g. MIPS
More informationCIT Week13 Lecture
CIT 3136 - Week13 Lecture Runtime Environments During execution, allocation must be maintained by the generated code that is compatible with the scope and lifetime rules of the language. Typically there
More informationCMSC 313 Lecture 12 [draft] How C functions pass parameters
CMSC 313 Lecture 12 [draft] How C functions pass parameters UMBC, CMSC313, Richard Chang Last Time Stack Instructions: PUSH, POP PUSH adds an item to the top of the stack POP removes an
More informationAssembly Language: Function Calls
Assembly Language: Function Calls 1 Goals of this Lecture Help you learn: Function call problems: Calling and returning Passing parameters Storing local variables Handling registers without interference
More informationAssembly Language: Function Calls" Goals of this Lecture"
Assembly Language: Function Calls" 1 Goals of this Lecture" Help you learn:" Function call problems:" Calling and returning" Passing parameters" Storing local variables" Handling registers without interference"
More informationAssembly Language: Function Calls. Goals of this Lecture. Function Call Problems
Assembly Language: Function Calls 1 Goals of this Lecture Help you learn: Function call problems: Calling and urning Passing parameters Storing local variables Handling registers without interference Returning
More informationAssembly Language: Function Calls" Goals of this Lecture"
Assembly Language: Function Calls" 1 Goals of this Lecture" Help you learn:" Function call problems:" Calling and urning" Passing parameters" Storing local variables" Handling registers without interference"
More informationAn Experience Like No Other. Stack Discipline Aug. 30, 2006
15-410 An Experience Like No Other Discipline Aug. 30, 2006 Bruce Maggs Dave Eckhardt Slides originally stolen from 15-213 15-410, F 06 Synchronization Registration If you're here but not registered, please
More informationCS241 Computer Organization Spring 2015 IA
CS241 Computer Organization Spring 2015 IA-32 2-10 2015 Outline! Review HW#3 and Quiz#1! More on Assembly (IA32) move instruction (mov) memory address computation arithmetic & logic instructions (add,
More informationCSC 2400: Computing Systems. X86 Assembly: Function Calls"
CSC 24: Computing Systems X86 Assembly: Function Calls" 1 Lecture Goals! Challenges of supporting functions" Providing information for the called function" Function arguments and local variables" Allowing
More informationProcedure Calls. Young W. Lim Mon. Young W. Lim Procedure Calls Mon 1 / 29
Procedure Calls Young W. Lim 2017-08-21 Mon Young W. Lim Procedure Calls 2017-08-21 Mon 1 / 29 Outline 1 Introduction Based on Stack Background Transferring Control Register Usage Conventions Procedure
More informationCMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING PREVIEW SLIDES 16, SPRING 2013
CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING PREVIEW SLIDES 16, SPRING 2013 CONST POINTERS CONST POINTERS 4 ways to declare pointers in combination with const:!! int *ptr! const int *ptr!
More informationTHEORY OF COMPILATION
Lecture 10 Activation Records THEORY OF COMPILATION EranYahav www.cs.technion.ac.il/~yahave/tocs2011/compilers-lec10.pptx Reference: Dragon 7.1,7.2. MCD 6.3,6.4.2 1 You are here Compiler txt Source Lexical
More informationProcedure Calls. Young W. Lim Sat. Young W. Lim Procedure Calls Sat 1 / 27
Procedure Calls Young W. Lim 2016-11-05 Sat Young W. Lim Procedure Calls 2016-11-05 Sat 1 / 27 Outline 1 Introduction References Stack Background Transferring Control Register Usage Conventions Procedure
More informationFunction Calls COS 217. Reading: Chapter 4 of Programming From the Ground Up (available online from the course Web site)
Function Calls COS 217 Reading: Chapter 4 of Programming From the Ground Up (available online from the course Web site) 1 Goals of Today s Lecture Finishing introduction to assembly language o EFLAGS register
More informationSecure Programming Lecture 3: Memory Corruption I (Stack Overflows)
Secure Programming Lecture 3: Memory Corruption I (Stack Overflows) David Aspinall, Informatics @ Edinburgh 24th January 2017 Outline Roadmap Memory corruption vulnerabilities Instant Languages and Runtimes
More informationWhat the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.
C Flow Control David Chisnall February 1, 2011 Outline What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope Disclaimer! These slides contain a lot of
More informationAS08-C++ and Assembly Calling and Returning. CS220 Logic Design AS08-C++ and Assembly. AS08-C++ and Assembly Calling Conventions
CS220 Logic Design Outline Calling Conventions Multi-module Programs 1 Calling and Returning We have already seen how the call instruction is used to execute a subprogram. call pushes the address of the
More informationCSCI 4061: Virtual Memory
1 CSCI 4061: Virtual Memory Chris Kauffman Last Updated: Thu Dec 7 12:52:03 CST 2017 2 Logistics: End Game Date Lecture Outside Mon 12/04 Lab 13: Sockets Tue 12/05 Sockets Thu 12/07 Virtual Memory Mon
More informationCompilers and Code Optimization EDOARDO FUSELLA
Compilers and Code Optimization EDOARDO FUSELLA Contents Data memory layout Instruction selection Register allocation Data memory layout Memory Hierarchy Capacity vs access speed Main memory Classes of
More informationStack Discipline Jan. 19, 2018
15-410 An Experience Like No Other Discipline Jan. 19, 2018 Dave Eckhardt Brian Railing Slides originally stolen from 15-213 1 15-410, S 18 Synchronization Registration The wait list will probably be done
More informationCS 31: Intro to Systems Functions and the Stack. Martin Gagne Swarthmore College February 23, 2016
CS 31: Intro to Systems Functions and the Stack Martin Gagne Swarthmore College February 23, 2016 Reminders Late policy: you do not have to send me an email to inform me of a late submission before the
More informationCYSE 411/AIT681 Secure Software Engineering Topic #8. Secure Coding: Pointer Subterfuge
CYSE 411/AIT681 Secure Software Engineering Topic #8. Secure Coding: Pointer Subterfuge Instructor: Dr. Kun Sun This lecture: [Seacord]: Chapter 3 Readings 2 Outline Secure Coding Topics String management
More informationQuestion 4.2 2: (Solution, p 5) Suppose that the HYMN CPU begins with the following in memory. addr data (translation) LOAD 11110
Questions 1 Question 4.1 1: (Solution, p 5) Define the fetch-execute cycle as it relates to a computer processing a program. Your definition should describe the primary purpose of each phase. Question
More informationSection 4: Threads CS162. September 15, Warmup Hello World Vocabulary 2
CS162 September 15, 2016 Contents 1 Warmup 2 1.1 Hello World............................................ 2 2 Vocabulary 2 3 Problems 3 3.1 Join................................................ 3 3.2 Stack
More informationSecure Coding Topics. Readings. CYSE 411/AIT681 Secure Software Engineering. Pointer Subterfuge. Outline. Data Locations (cont d) Data Locations
This lecture: [Seacord]: Chapter 3 Readings CYSE 411/AIT681 Secure Software Engineering Topic #8. Secure Coding: Pointer Subterfuge Instructor: Dr. Kun Sun 2 Outline Secure Coding Topics String management
More informationSecure Coding Topics. CYSE 411/AIT681 Secure Software Engineering. Readings. Outline. This lecture: Topic #8. Secure Coding: Pointer Subterfuge
CYSE 411/AIT681 Secure Software Engineering Topic #8. Secure Coding: Pointer Subterfuge Instructor: Dr. Kun Sun This lecture: [Seacord]: Chapter 3 Readings 2 Outline Secure Coding Topics String management
More informationRoadmap: Security in the software lifecycle. Memory corruption vulnerabilities
Secure Programming Lecture 3: Memory Corruption I (introduction) David Aspinall, Informatics @ Edinburgh 24th January 2019 Roadmap: Security in the software lifecycle Security is considered at different
More informationCSC 2400: Computing Systems. X86 Assembly: Function Calls
CSC 24: Computing Systems X86 Assembly: Function Calls 1 Lecture Goals Challenges of supporting functions Providing information for the called function Function arguments and local variables Allowing the
More informationASSEMBLY III: PROCEDURES. Jo, Heeseung
ASSEMBLY III: PROCEDURES Jo, Heeseung IA-32 STACK (1) Characteristics Region of memory managed with stack discipline Grows toward lower addresses Register indicates lowest stack address - address of top
More informationCompiler construction. x86 architecture. This lecture. Lecture 6: Code generation for x86. x86: assembly for a real machine.
This lecture Compiler construction Lecture 6: Code generation for x86 Magnus Myreen Spring 2018 Chalmers University of Technology Gothenburg University x86 architecture s Some x86 instructions From LLVM
More informationAssembly III: Procedures. Jo, Heeseung
Assembly III: Procedures Jo, Heeseung IA-32 Stack (1) Characteristics Region of memory managed with stack discipline Grows toward lower addresses Register indicates lowest stack address - address of top
More informationCompilation /15a Lecture 7. Activation Records Noam Rinetzky
Compilation 0368-3133 2014/15a Lecture 7 Activation Records Noam Rinetzky 1 Code generation for procedure calls (+ a few words on the runtime system) 2 Code generation for procedure calls Compile time
More informationx86 assembly CS449 Spring 2016
x86 assembly CS449 Spring 2016 CISC vs. RISC CISC [Complex instruction set Computing] - larger, more feature-rich instruction set (more operations, addressing modes, etc.). slower clock speeds. fewer general
More informationX86 Review Process Layout, ISA, etc. CS642: Computer Security. Drew Davidson
X86 Review Process Layout, ISA, etc. CS642: Computer Security Drew Davidson davidson@cs.wisc.edu From Last Time ACL-based permissions (UNIX style) Read, Write, execute can be restricted on users and groups
More informationC Compilation Model. Comp-206 : Introduction to Software Systems Lecture 9. Alexandre Denault Computer Science McGill University Fall 2006
C Compilation Model Comp-206 : Introduction to Software Systems Lecture 9 Alexandre Denault Computer Science McGill University Fall 2006 Midterm Date: Thursday, October 19th, 2006 Time: from 16h00 to 17h30
More informationAssembly III: Procedures. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University
Assembly III: Procedures Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu IA-32 (1) Characteristics Region of memory managed with stack discipline
More informationCMSC 313 Lecture 12. Project 3 Questions. How C functions pass parameters. UMBC, CMSC313, Richard Chang
Project 3 Questions CMSC 313 Lecture 12 How C functions pass parameters UMBC, CMSC313, Richard Chang Last Time Stack Instructions: PUSH, POP PUSH adds an item to the top of the stack POP
More informationWinter Compiler Construction T11 Activation records + Introduction to x86 assembly. Today. Tips for PA4. Today:
Winter 2006-2007 Compiler Construction T11 Activation records + Introduction to x86 assembly Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv University Today ic IC Language Lexical Analysis
More informationTopic 7: Activation Records
Topic 7: Activation Records Compiler Design Prof. Hanjun Kim CoreLab (Compiler Research Lab) POSTECH 1 Storage Organization Stack Free Memory Heap Static Code 2 ELF file format example Executable Object
More information7 Translation to Intermediate Code
7 Translation to Intermediate Code ( 7. Translation to Intermediate Code, p. 150) This chpater marks the transition from the source program analysis phase to the target program synthesis phase. All static
More informationProcess Layout and Function Calls
Process Layout and Function Calls CS 6 Spring 07 / 8 Process Layout in Memory Stack grows towards decreasing addresses. is initialized at run-time. Heap grow towards increasing addresses. is initialized
More informationCS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2015 Lecture 11
CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2015 Lecture 11 EXCEPTION HANDLING! Many higher-level languages provide exception handling! Concept: One part of the program knows how to detect a problem,
More informationMachine-level Programming (3)
Machine-level Programming (3) Procedures A: call A call A return Two issues How to return to the correct position? How to pass arguments and return values between callee to caller? 2 Procedure Control
More informationAssembly level Programming. 198:211 Computer Architecture. (recall) Von Neumann Architecture. Simplified hardware view. Lecture 10 Fall 2012
19:211 Computer Architecture Lecture 10 Fall 20 Topics:Chapter 3 Assembly Language 3.2 Register Transfer 3. ALU 3.5 Assembly level Programming We are now familiar with high level programming languages
More informationCompiler Construction D7011E
Compiler Construction D7011E Lecture 8: Introduction to code generation Viktor Leijon Slides largely by Johan Nordlander with material generously provided by Mark P. Jones. 1 What is a Compiler? Compilers
More informationAssignment 11: functions, calling conventions, and the stack
Assignment 11: functions, calling conventions, and the stack ECEN 4553 & 5013, CSCI 4555 & 5525 Prof. Jeremy G. Siek December 5, 2008 The goal of this week s assignment is to remove function definitions
More informationCPS104 Recitation: Assembly Programming
CPS104 Recitation: Assembly Programming Alexandru Duțu 1 Facts OS kernel and embedded software engineers use assembly for some parts of their code some OSes had their entire GUIs written in assembly in
More informationW4118: PC Hardware and x86. Junfeng Yang
W4118: PC Hardware and x86 Junfeng Yang A PC How to make it do something useful? 2 Outline PC organization x86 instruction set gcc calling conventions PC emulation 3 PC board 4 PC organization One or more
More informationPractical Malware Analysis
Practical Malware Analysis Ch 4: A Crash Course in x86 Disassembly Revised 1-16-7 Basic Techniques Basic static analysis Looks at malware from the outside Basic dynamic analysis Only shows you how the
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationCS165 Computer Security. Understanding low-level program execution Oct 1 st, 2015
CS165 Computer Security Understanding low-level program execution Oct 1 st, 2015 A computer lets you make more mistakes faster than any invention in human history - with the possible exceptions of handguns
More informationSection 4: Threads and Context Switching
CS162 September 19-20, 2017 Contents 1 Warmup 2 1.1 Hello World............................................ 2 2 Vocabulary 2 3 Problems 3 3.1 Join................................................ 3 3.2
More informationThe course that gives CMU its Zip! Machine-Level Programming III: Procedures Sept. 17, 2002
15-213 The course that gives CMU its Zip! Machine-Level Programming III: Procedures Sept. 17, 2002 Topics IA32 stack discipline Register saving conventions Creating pointers to local variables class07.ppt
More informationCS213. Machine-Level Programming III: Procedures
CS213 Machine-Level Programming III: Procedures Topics IA32 stack discipline Register saving conventions Creating pointers to local variables IA32 Region of memory managed with stack discipline Grows toward
More informationWhat is a Compiler? Compiler Construction SMD163. Why Translation is Needed: Know your Target: Lecture 8: Introduction to code generation
Compiler Construction SMD163 Lecture 8: Introduction to code generation Viktor Leijon & Peter Jonsson with slides by Johan Nordlander Contains material generously provided by Mark P. Jones What is a Compiler?
More informationCS61, Fall 2012 Midterm Review Section
CS61, Fall 2012 Midterm Review Section (10/16/2012) Q1: Hexadecimal and Binary Notation - Solve the following equations and put your answers in hex, decimal and binary. Hexadecimal Decimal Binary 15 +
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 informationMachine Programming 3: Procedures
Machine Programming 3: Procedures CS61, Lecture 5 Prof. Stephen Chong September 15, 2011 Announcements Assignment 2 (Binary bomb) due next week If you haven t yet please create a VM to make sure the infrastructure
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
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 informationLecture #16: Introduction to Runtime Organization. Last modified: Fri Mar 19 00:17: CS164: Lecture #16 1
Lecture #16: Introduction to Runtime Organization Last modified: Fri Mar 19 00:17:19 2010 CS164: Lecture #16 1 Status Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces
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 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 informationRegister Allocation, iii. Bringing in functions & using spilling & coalescing
Register Allocation, iii Bringing in functions & using spilling & coalescing 1 Function Calls ;; f(x) = let y = g(x) ;; in h(y+x) + y*5 (:f (x
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 informationAssembly Programmer s View Lecture 4A Machine-Level Programming I: Introduction
Assembly Programmer s View Lecture 4A Machine-Level Programming I: Introduction E I P CPU isters Condition Codes Addresses Data Instructions Memory Object Code Program Data OS Data Topics Assembly Programmer
More informationLab 10: Introduction to x86 Assembly
CS342 Computer Security Handout # 8 Prof. Lyn Turbak Wednesday, Nov. 07, 2012 Wellesley College Revised Nov. 09, 2012 Lab 10: Introduction to x86 Assembly Revisions: Nov. 9 The sos O3.s file on p. 10 was
More informationCS 537 Lecture 2 - Processes
CS 537 Lecture 2 - Processes Michael Swift 1 Basic Structure Kernel is a big program that starts when you boot your program Has full access to physical hardware. User programs, utilities, services see
More information2 Sadeghi, Davi TU Darmstadt 2012 Secure, Trusted, and Trustworthy Computing Chapter 6: Runtime Attacks
Runtime attacks are major threats to today's applications Control-flow of an application is compromised at runtime Typically, runtime attacks include injection of malicious code Reasons for runtime attacks
More informationStacks and Frames Demystified. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han
s and Frames Demystified CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han Announcements Homework Set #2 due Friday at 11 am - extension Program Assignment #1 due Tuesday Feb. 15 at 11 am - note extension
More informationCompiler Internals. Reminders. Course infrastructure. Registering for the course
Compiler Internals 15-745 Optimizing Compilers Spring 2006 Peter Lee Reminders Get on the course mailing list Check out the web site http://www.cs.cmu.edu/afs/cs/ academic/class/15745-s06/web subscribe
More informationUniversity of Washington
Roadmap C: car *c = malloc(sizeof(car)); c->miles = 100; c->gals = 17; float mpg = get_mpg(c); free(c); Assembly language: Machine code: Computer system: get_mpg: pushq %rbp movq %rsp, %rbp... popq %rbp
More informationIntel assembly language using gcc
QOTD Intel assembly language using gcc Assembly language programming is difficult. Make no mistake about that. It is not for wimps and weaklings. - Tanenbaum s 6th, page 519 These notes are a supplement
More informationCPEG421/621 Tutorial
CPEG421/621 Tutorial Compiler data representation system call interface calling convention Assembler object file format object code model Linker program initialization exception handling relocation model
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 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 informationRun-time Environments. Lecture 13. Prof. Alex Aiken Original Slides (Modified by Prof. Vijay Ganesh) Lecture 13
Run-time Environments Lecture 13 by Prof. Vijay Ganesh) Lecture 13 1 What have we covered so far? We have covered the front-end phases Lexical analysis (Lexer, regular expressions,...) Parsing (CFG, Top-down,
More informationCS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11
CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2018 Lecture 11 EXCEPTION HANDLING Many higher-level languages provide exception handling Concept: One part of the program knows how to detect a problem,
More informationRun-time Environments
Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation 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 informationRun-time Environments
Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation Instruction
More informationProcesses. Johan Montelius KTH
Processes Johan Montelius KTH 2017 1 / 47 A process What is a process?... a computation a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other
More informationProcesses (Intro) Yannis Smaragdakis, U. Athens
Processes (Intro) Yannis Smaragdakis, U. Athens Process: CPU Virtualization Process = Program, instantiated has memory, code, current state What kind of memory do we have? registers + address space Let's
More informationComputer Systems CEN591(502) Fall 2011
Computer Systems CEN591(502) Fall 2011 Sandeep K. S. Gupta Arizona State University 9 th lecture Machine-Level Programming (4) (Slides adapted from CSAPP) Announcements Potentially Makeup Classes on Sat
More informationA process. the stack
A process Processes Johan Montelius What is a process?... a computation KTH 2017 a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other processes
More informationSystem Software Assignment 1 Runtime Support for Procedures
System Software Assignment 1 Runtime Support for Procedures Exercise 1: Nested procedures Some programming languages like Oberon and Pascal support nested procedures. 1. Find a run-time structure for such
More informationRun-time Environments - 2
Run-time Environments - 2 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler Design Outline of the Lecture n What is run-time
More informationRui Wang, Assistant professor Dept. of Information and Communication Tongji University.
Instructions: ti Language of the Computer Rui Wang, Assistant professor Dept. of Information and Communication Tongji University it Email: ruiwang@tongji.edu.cn Computer Hierarchy Levels Language understood
More informationSystems I. Machine-Level Programming V: Procedures
Systems I Machine-Level Programming V: Procedures Topics abstraction and implementation IA32 stack discipline Procedural Memory Usage void swap(int *xp, int *yp) int t0 = *xp; int t1 = *yp; *xp = t1; *yp
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 informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter
More informationSee P&H 2.8 and 2.12, and A.5-6. Prof. Hakim Weatherspoon CS 3410, Spring 2015 Computer Science Cornell University
See P&H 2.8 and 2.12, and A.5-6 Prof. Hakim Weatherspoon CS 3410, Spring 2015 Computer Science Cornell University Upcoming agenda PA1 due yesterday PA2 available and discussed during lab section this week
More informationTypical Runtime Layout. Tiger Runtime Environments. Example: Nested Functions. Activation Trees. code. Memory Layout
Tiger Runtime Environments Compile-time environments are just symbol tables; they are used to assist static semantic analysis, code generation and code optimization. Run-time environments are about how
More informationCS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 21: Generating Pentium Code 10 March 08
CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 21: Generating Pentium Code 10 March 08 CS 412/413 Spring 2008 Introduction to Compilers 1 Simple Code Generation Three-address code makes it
More informationCS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2016 Lecture 12
CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2016 Lecture 12 CS24 MIDTERM Midterm format: 6 hour overall time limit, multiple sittings (If you are focused on midterm, clock should be running.) Open book
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 informationRegion of memory managed with stack discipline Grows toward lower addresses. Register %esp contains lowest stack address = address of top element
Machine Representa/on of Programs: Procedures Instructors: Sanjeev Se(a 1 IA32 Stack Region of memory managed with stack discipline Grows toward lower addresses Stack BoGom Increasing Addresses Register
More informationSungkyunkwan University
Switch statements IA 32 Procedures Stack Structure Calling Conventions Illustrations of Recursion & Pointers long switch_eg (long x, long y, long z) { long w = 1; switch(x) { case 1: w = y*z; break; case
More informationX86 Assembly -Procedure II:1
X86 Assembly -Procedure II:1 IA32 Object Code Setup Label.L61 becomes address 0x8048630 Label.L62 becomes address 0x80488dc Assembly Code switch_eg:... ja.l61 # if > goto default jmp *.L62(,%edx,4) # goto
More information