Docsity

Code Generation for Control Structures - Lecture Notes | CS 4240, Study notes of Computer Science

Partial preview of the text

Download Code Generation for Control Structures - Lecture Notes | CS 4240 and more Study notes Computer Science in PDF only on Docsity!

Code Generation for Control Structures

If Statements

Code Template:

  1. If (^) condition

(^) is false go to 4.

  1. Execute statements in

(^) thenPart

.

  1. Execute statements in3. Go to 5.

(^) elsePart

.

  1. Statements following the if statement.

AST Node Structure:

condition

thenPartIfNode

elsePart

Exp

Stmts

Stmts

Special case -- no else part:

if (b) a=1;

will result in code with an extra jump:

iload

(^2) ; Push local #2 (B) onto the stack

ifeq

L1 ; Goto L1 if B is 0 (false)

iconst_

; Push 1

istore

(^1) ; Store stack top into local #1 (a)

goto

L2 ; Skip around else statements

L2:L1:

Improved Code Generation:

  1. fNode.CodeGen ( )

ElseLabel

(^) CreateUniqueLabel()

condition.Result

(^) AddressNode(JumpIfFalse, ElseLabel)

condition.CodeGen()

thenPart.CodeGen()

if elsePart = null

then GenLabel(ElseLabel)

else OutLabel

(^) CreateUniqueLabel()

GenGoTo(OutLabel)

GenLabel(ElseLabel)

elsePart.CodeGen()

GenLabel(OutLabel)

While Loops

Code Template:

  1. If (^) condition

(^) is false go to 4.

  1. Execute statements in

(^) loopBody

.

  1. Statements following the while loop.3. Go to 1.

Better version:

  1. Execute statements in 1. Go to 3.

(^) loopBody

.

  1. If (^) condition

(^) is true go to 2.

AST Node Structure:

condition

loopBody

whileNode

Exp

Stmts

C-style For Loops

Code Template:

1.Execute

(^) initializer

(^) code.

3.Execute statements in2.Go to 5.

(^) loopBody

4.Execute

(^) increment

(^) code.

5.If (^) condition

(^) is true go to 3.

AST Node Structure

condition

forNode

increment

Exp

StmtExpr

Stmts

initializer

loopBody

StmtExpr

Code Generation:

  1. ForNode.CodeGen ( )

initializer.CodeGen()

SkipLabel

(^) CreateUniqueLabel()

GenGoTo(SkipLabel)

TopLabel

(^) CreateUniqueLabel()

GenLabel(TopLabel)

loopBody.CodeGen()

ContinueLabel

(^) getContinueLabel()

GenLabel(ContinueLabel)

increment.CodeGen()

12.11. if condition = null10. GenLabel(SkipLabel)

then GenGoTo(TopLabel)

else condition.Result

(^) AddressNode(JumpIfTrue, TopLabel)

condition.CodeGen()

Special Case Example:

The special case of

for (;;) {}

generates:

goto

L

L1: L2: L3:

goto

L