Code Generation for Conditional Judgment Statements
st1
if(r1<r2)
st2
else
st3
st4
st1
BB1 com_LT r1,r2 → r3
cbr r3 → L1,L2
L1 : st2
BB2 jumpI L3
BB3 L2 : st3
BB4 L3 : st4
The com_LT here is less than if r1 is smaller than r2, return true to r3
cbr is a condition branch, if r3 is true, go to L1, otherwise go to L2
The basic block represented by BB is a basic block when encountering a branch or jump or a new label.
Control Flow Graph(CFG)
Dividing the code into these basic blocks will make the logic clearer and the optimization work easier.
After obtaining the AST, the compiler will build such a CFG as a part of the middle expression. There are some linear assembly instructions in each baisc block.
Cyclic code generation
st1
while(r1==r2)
st2
st3
The first way of writing:
st1
BB1 com_EQ r1,r2 → r3
cbr r3 → L1,L2
L1 : st2
BB3 com_EQ r1,r2 → r3
cbr r3 → L1,L2
BB3 L2 : st3
CFG:
second way of writing
BB1 st1
BB2 L0 : com_EQ r1,r2 → r3
cbr r3 → L1,L2
BB3 L1 : st2
jumpI L0
BB4 L2 : st3
Because L0 has 4 basic block
CFGs at this time:
boolean type
a > b && c==d || e<=f
loadAI rarp,@a → r1
loadAI rarp,@b → r2
comp_GT r1,r2 → r3
loadAI rarp,@c → r4
loadAI rarp,@d → r5
cmp_EQ r4,r5 → r6
and r3,r6 → r7
loadAI rarp,@e → r8
loadAI rarp,@f → r9
cmp_LE r8, r9 → r10
or r7,r10 → r11
Nested loops:
st1;
while(r1>r2)
{
st2;
while(r3<=r4)
{
st3;
}
st4;
}
st5;
L1_B : Loop body
L1_O : Loop out
L1_C : Loop condition
st1
L1_C : cmp_GT r1,r2 → r5
cbr r5 → L1_B,L1_O
L1_B st2
L1_C cmp_LE r3,r4 → r6
cbr r6 → L2_B,L2_O
L2_B : st3
jumpI L2_C
L2_O : st4
jumpI L1_C
L1_O : st5