Docsity

Code Generation in Compilers: Instruction Selection, Scheduling, and Allocation, Study notes of Computer Science

Toggle sidebar
bg1
1
Code Generation
CS430 2
Roadmap (Where are we?)
Last lecture
•
Type checking
•
Intermediate representations
This lecture
•
Code generation
→
Code shape
→
Expressions
3-address code
Stack code
→
Assignments
CS430 3
Code Generation: Structure of a Compiler (EaC Ch. 7)
A compiler is a lot of fast stuff followed by some hard problems
→
The hard stuff is mostly in code generation and optimization
→
For superscalars, allocation & sch eduling is particularly important
Instruction
Selection
Register
Allocation
Instruction
Scheduling
Scanner Parser Analysis
&
Optimization
O(n), O(n log n), … NP-CompleteO(n)O(n)
NP-Complete NP-CompleteEither fast or
NP-Complete
words
IR
IR
asm asm asm
∞
regs
∞
regs k
regs
CS430 4
Structure of a Compiler
We assume the following model
•
Selection is fairly simple (problem of the 1980s)
•
Allocation & scheduling are complex
What about the IR ?
•
Low-level, R
ISC
-like
IR
called I
LOC
•
Has “enough” registers
•
I
LOC
was designed for compiler
backend research
{
Branches, compares, & labels
Memory tags
Provision for multiple ops/cycle
Instruction
Selection
Instruction
Scheduling
Register
Allocation
Analysis
&
Optimization
IR
asm
asm
∞
regs
∞
regs
∞
regs
∞
regs k
regs
asm
IR
CS430 5
Definitions
Instruction selection
•
Mapping
IR
into assembly code
•
Assumes a fixed storage mapping & code shape
•
Combining operations, using address modes
Instruction scheduling
•
Reordering operations to hide latencies
•
Assumes a fixed program
(set of operations)
•
Changes demand for registers
Register allocation
•
Deciding which values will reside in registers
•
Changes the storage mapping, may add false sharing
These 3 problems
are tightly coupled.
CS430 6
The Big Picture
How hard are these problems?
Instruction selection
•
Can make locally optimal choices, with automated tool
•
Global optimality is (undoubtedly) NP-Complete
Instruction scheduling
•
Single basic block
⇒
heuristics work quickly
•
General problem, with control flow
⇒
NP-Complete
Register allocation
•
Single basic block, no spilling, & 1 register size
⇒
linear time
•
Whole procedure is NP-Complete
pf3
pf4
pf5

Partial preview of the text

Download Code Generation in Compilers: Instruction Selection, Scheduling, and Allocation and more Study notes Computer Science in PDF only on Docsity!

Code Generation

CS430 2

Roadmap (Where are we?)

Last lecture

  • Type checking
  • Intermediate representations

This lecture

  • Code generation → Code shape → Expressions  3-address code  Stack code → Assignments

CS430 3

Code Generation: Structure of a Compiler (EaC Ch. 7)

A compiler is a lot of fast stuff followed by some hard problems

→ The hard stuff is mostly in code generation and optimization → For superscalars, allocation & scheduling is particularly important

Instruction Selection

Register Allocation

Instruction Scheduling

Scanner Parser

Analysis & Optimization

O(n) O(n) O(n), O(n log n), … NP-Complete

Either fast or NP-Complete NP-Complete NP-Complete

words IR

IR asm asm asm ∞ regs

∞ regs

k regs

CS430 4

Structure of a Compiler

We assume the following model

  • Selection is fairly simple (problem of the 1980s)
  • Allocation & scheduling are complex

What about the IR?

  • Low-level, RISC-like IR called ILOC
  • Has “enough” registers
  • ILOC was designed for compiler backend research

Branches, compares, & labels Memory tags Provision for multiple ops/cycle

Instruction Selection

Instruction Scheduling

Register Allocation

Analysis & Optimization

IR^ asm^ asm

∞ regs

regs

regs

regs

k regs

IR^ asm

CS430 5

Definitions

Instruction selection

  • Mapping IR into assembly code
  • Assumes a fixed storage mapping & code shape
  • Combining operations, using address modes

Instruction scheduling

  • Reordering operations to hide latencies
  • Assumes a fixed program (set of operations)
  • Changes demand for registers

Register allocation

  • Deciding which values will reside in registers
  • Changes the storage mapping, may add false sharing

These 3 problems are tightly coupled.

CS430 6

The Big Picture

How hard are these problems?

Instruction selection

  • Can make locally optimal choices, with automated tool
  • Global optimality is (undoubtedly) NP-Complete

Instruction scheduling

  • Single basic block ⇒ heuristics work quickly
  • General problem, with control flow ⇒ NP-Complete

Register allocation

  • Single basic block, no spilling, & 1 register size ⇒ linear time
  • Whole procedure is NP-Complete

CS430 7

The Big Picture

Conventional wisdom says that we lose little by solving these problems independently

Instruction selection

  • Use some form of pattern matching
  • Assume enough registers or target “important” values

Instruction scheduling

  • Within a block, list scheduling is “close” to optimal
  • Across blocks, build framework to apply list scheduling

Register allocation

  • Start from virtual registers & map into k
  • Focus on good priority heuristic

Optimal for

85% of blocks

Note: many fuzzy terms here!

CS430 8

Code Shape

Definition

  • All those nebulous properties of the code that impact performance & code “quality”
  • Includes code, approach for different constructs, cost, storage requirements & mapping, & choice of operations
  • Code shape is the end product of many decisions (big & small)

Impact

  • Code shape influences algorithm choice & results
  • Code shape can encode important facts, or hide them

Rule of thumb: expose as much derived information as possible

  • Example: explicit branch targets in ILOC simplify analysis

CS430 9

Code Shape (assuming no rule for associativity)

An example

  • What if x is 2 and z is 3?
  • What if y+z is evaluated earlier?

The “best” shape for x+y+z depends on contextual knowledge → There may be several conflicting options

x + y + z x + y → t t1+ z → t

x + z → t t1+ y → t

y + z → t t1+ z → t

x y z

z

x y

y

x z

x

y z

Addition is commutative & associative for integers

source level intermediate level

CS430 10

Code Shape

Another example -- the case statement

  • Implement it as cascaded if-then-else statements → Cost depends on where your case actually occurs → O(number of cases)
  • Implement it as a binary search → Uniform (log n) cost
  • Implement it as a jump table → Lookup address in a table & jump to it → Uniform (constant) cost

Compiler must choose best implementation strategy No amount of massaging or transforming will convert one into another

CS430 11

Generating 3-address Code

  • We’ll first target RISC architectures
  • Properties

→ Explicit loads and stores (to registers) → Explicit references to registers  Either virtual or physical registers

  • Example instructions

→ load r1, // r1 ← value at → loadi r1, // r1 ← value of → store r1, // ← r → move r1, r2 // r1 ← r → add r1, r2, r3 // r1 ← r2 + r → sub r1, r2, r3 // r1 ← r2 - r → mult r1, r2, r3 // r1 ← r2 * r → neg, r1, r2 // r2 ← –r → jmp // jump to CS430 12

Generating 3-address Code for Expressions

The key code quality issue is holding values in registers

  • When can a value be safely allocated to a register? → When only 1 name can reference its value → Pointers, parameters, aggregates & arrays all cause trouble
  • When should a value be allocated to a register? → When it is both safe & profitable

Encoding this knowledge into the IR

  • Use code shape to make it known to every later phase
  • Assign a virtual register to anything that can go into one
  • Load or store the others at each reference

Relies on a strong register allocator (register-register model)

CS430 19

Extending the Simple Treewalk Algorithm

Adding other operators

  • Evaluate the operands, then perform the operation
  • Complex operations may turn into library calls
  • Handle assignment as an operator

Mixed-type expressions

  • Insert conversions as needed from conversion table
  • Most languages have symmetric & rational conversion tables
  • Integer Real Double Complex Integer Integer Real Double Complex Real Real Real Double Complex Double Double Double Double Complex Complex Complex Complex Complex Complex

Typical Addition Table

CS430 20

Extending the Simple Treewalk Algorithm

What about evaluation order?

  • Can use commutativity & associativity to improve code
  • This problem is truly hard

What about order of evaluating operands?

  • 1 st^ operand must be preserved while 2nd^ is evaluated
  • Takes an extra register that cannot be used for 2nd^ operand
  • Should evaluate more demanding operand expression first (Ershov in the 1950’s, Sethi in the 1970’s)

Taken to its logical conclusion, this creates Sethi-Ullman register allocation scheme (ASU p. 564)

CS430 21

Generating Code in the Parser

Need to generate an initial IR form

  • Might generate an AST, use it for some high-level, near- source work (type checking, optimization, alias analysis), then traverse it and emit a lower-level IR similar to ILOC

The big picture

  • Recursive algorithm really works bottom-up

→ Actions on non-leaves occur after children are done

  • Can encode same basic structure into ad-hoc SDT scheme

→ Identifiers load themselves & stack virtual register name → Operators emit appropriate code & stack resulting VR name → Assignment requires evaluation to an lvalue or an rvalue

CS430 22

Ad-hoc SDT versus a Recursive Treewalk

Goal : Expr { $$ = $1; } ; Expr: Expr PLUS Term { t = NextRegister(); emit(add,$1,$3,t); $$ = t; } | Expr MINUS Term {…} | Term { $$ = $1; } ; Term: Term TIMES Factor { t = NextRegister(); emit(mult,$1,$3,t); $$ = t; }; | Term DIVIDES Factor {…} | Factor { $$ = $1; }; Factor: NUMBER { t = NextRegister(); emit(loadI,val($1),none, t ); $$ = t; } | ID { t1 = base($1); t2 = offset($1); t = NextRegister(); emit(loadAO,t1,t2,t); $$ = t; }

expr(node) { int result, t1, t2; switch ( type(node)) { case ×,÷,+,− : t1← expr( left child(node)); t2← expr( right child(node)); result ← NextRegister(); emit ( op(node), t1, t2, result); break; case IDENTIFIER: t1← base(node); t2← offset(node); result ← NextRegister(); emit (loadAO, t1, t2, result); break; case NUMBER: result ← NextRegister(); emit (loadI, val(node), none, result); break; } return result; }

CS430 23

Handling Assignment (just another operator)

lhs ← rhs

Strategy

  • Evaluate rhs to a value (an rvalue)
  • Evaluate lhs to a location (an lvalue)

→ lvalue is a register ⇒ move rhs ( register/register copy) → lvalue is an address ⇒ store rhs

  • If rvalue & lvalue have different types

→ Evaluate rvalue to its “ natural” type → Convert that value to the type of * lvalue

Unambiguous scalars go into registers

Ambiguous scalars or aggregates go into memory

CS430 24

Handling Assignment

What if the compiler cannot determine the rhs’s type?

  • This is a property of the language & the specific program
  • If type-safety is desired, compiler must insert a run-time check
  • Add a tag field to the data items to hold type information

Code for assignment becomes more complex

evaluate rhsevaluate rhsevaluate rhsevaluate rhs if type(lhs)if type(lhs)if type(lhs)if type(lhs) ≠≠≠≠ rhs.tagrhs.tagrhs.tagrhs.tag thenthenthenthen convert rhs to type(lhs)convert rhs to type(lhs)convert rhs to type(lhs)convert rhs to type(lhs) orororor signal a runsignal a runsignal a runsignal a run----time errortime errortime errortime error lhslhslhslhs ←←←← rhsrhsrhsrhs

This is much more complex than if it knew the types

CS430 25

Handling Assignment

Compile-time type-checking

  • Goal is to eliminate both the check & the tag
  • Determine, at compile time, the type of each subexpression
  • Use compile-time types to determine if a run-time check is

needed

Optimization strategy

  • If compiler knows the type, move the check to compile-time
  • Unless tags are needed for garbage collection, eliminate them
  • If check is needed, try to overlap it with other computation

( assumes target machine with instruction-level parallelism)

CS430 26

Handling Assignment (with reference counting)

The problem with reference counting

  • Must adjust the count on each pointer assignment
  • Overhead is significant, relative to assignment Code for assignment becomes

This adds 1 +, 1 -, 2 loads, & 2 stores

With extra functional units & large caches, this may become either cheap or free. What about power consumption?

evaluate rhsevaluate rhsevaluate rhsevaluate rhs lhslhslhslhs→→→→countcountcountcount ←←←← lhslhslhslhs→→→→countcountcountcount --- 1- 111 lhslhslhslhs ←←←← addr(rhs)addr(rhs)addr(rhs)addr(rhs) rhsrhsrhsrhs→→→→countcountcountcount ←←←← rhsrhsrhsrhs→→→→count + 1count + 1count + 1count + 1

Plus a check for zero at the end