Compiler Principles

advertisement
Fall 2015-2016 Compiler Principles
Exercise Set: Lowering and Formal
Semantics
Roman Manevich
Ben-Gurion University of the Negev
Q1: Extending Boolean expressions
• We would like to extend the set of Boolean
expressions with an expression of the form
BB?A:A
• The idea is that in ‘b ? a1 : a2’ is that if b is true
then the result is that of a1 and otherwise the
result is that of a2
• Define the formal semantics for evaluating
these expressions
• Define a corresponding lowering rule (cgen)
2
Q2: Boolean short-cuts
• We would like to extend the set of Boolean
expressions with an expression of the form
B  B && B
• The idea is that in ‘b1 && b2’ if b1 is true then
the result is that of b2, and otherwise it is false
1. Define the formal semantics for evaluating
these expressions
3
Q2: Boolean short-cuts
2. Consider the two following translations.
Are they equivalent?
Explain what is the formal definition of
equivalence that you consider.
1
cgen(b1 && b2) = cgen(b1  b2)
2
cgen(b1) = (P1, t1)
cgen(b2) = (P2, t2)
cgen(b1 && b2) = (P1· l1: t:=t1 · IfZ t Goto lend · P2· l2: t:=t2 · lend: skip, t)
where l1, l2, lend and t are fresh
4
Extending IL with memory
5
Q3: Extending IL with memory
• We would like to support two additional types
of commands, as shown in the next page
1. Explain how the states of the revised
language should be defined
2. Write the rules for the new commands
6
Q3: Extended syntax
n
l
x
Num
Num
Temp
Var
Vn|x
R  V Op V
Op  - | + | * | / | = |
C  l: skip
| l: x := R
| l: x := [y]
| l: [x] := y
| l: Goto l’
| l: IfZ x Goto l’
| l: IfNZ x Goto l’
IR  C+
Numerals
Labels
Temporaries and variables
| << | >> | …
7
solution
8
A1: Extending Boolean expressions
•  b ? a1 : a2   = if b  = tt then a1  else a2 
cgen(b) = (Pb, tb) cgen(a1) = (P1, t1) cgen(a2) = (P2, t2)
cgen(b ? a1 : a2) = (
Pb
IfZ t Goto label(P2)
P1
t := t1
lfinish: Goto Lafter
P2
t := t2
lafter: skip,
t
)
9
A2: Boolean short-cuts
• The two translations are indeed equivalent according to the
truth table of conjunction
• We consider equivalence by projecting states on the variables
(and temporaries) used in the sub-expression b1 and b2 and
the output temporary t
10
A3: Extending program states
Z
IState
Integers {0, 1, -1, 2, -2, …}
(Var  Temp  {pc}) Z 
Z Z
• Intermediate states are pairs:
– The first component, the stack, gives values
to variables
– The second component, the heap, maps
addresses to values
11
A3: adding memory access rules
s(pc) = l
P(l) = x:=[y]
(s,h)  (s[pc l+1, x h(s(y))], h)
s(pc) = l
P(l) = [x]:=y
(s,h)  (s[pc l+1], h[s(x) s(y)])
12
Download