0% found this document useful (0 votes)
1 views19 pages

CD UNIT 3 PART B

The document provides a comprehensive overview of Three-Address Code (TAC), its types, and its implementation in compiler design. It explains the structure of TAC, its purpose in simplifying high-level language constructs, and various forms of representation such as quadruples and triples. Additionally, it covers the translation schemes for declarations in procedures, syntax-directed translation for assignment statements, and the conversion of control flow statements into intermediate code.

Uploaded by

navya shreya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views19 pages

CD UNIT 3 PART B

The document provides a comprehensive overview of Three-Address Code (TAC), its types, and its implementation in compiler design. It explains the structure of TAC, its purpose in simplifying high-level language constructs, and various forms of representation such as quadruples and triples. Additionally, it covers the translation schemes for declarations in procedures, syntax-directed translation for assignment statements, and the conversion of control flow statements into intermediate code.

Uploaded by

navya shreya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIT 3

1.Demonstrate the concept of three address code with its types and implementation.

Three-Address Code with Its Types and Implementation

1. Introduction to Three-Address Code (TAC)

Three-Address Code (TAC) is an intermediate representation (IR) used by compilers to


bridge the gap between source code and machine code. TAC simplifies complex high-level
language constructs into simple instructions with at most three operands.

Each TAC instruction typically contains:

• One operator

• At most two operands (addresses or variables)

• One result (assigned to a temporary variable)

Format:

x = y op z

Where x, y, and z are variables or constants, and op is an operator such as +, -, *, /, etc.

2. Purpose and Role in Compilation

Three-Address Code plays a crucial role in compiler design:

• Simplifies complex expressions

• Makes optimization easier

• Easier translation to machine or assembly code

• Used during intermediate code generation phase

3. Basic Forms of Three-Address Code

There are several common forms of TAC instructions:

Type Syntax Example Description

Assignment with operation x = y + z Performs operation and stores result

Assignment with unary op x = -y Unary minus or not

Copy x=y Simple assignment

Unconditional jump goto L1 Jumps to label


Type Syntax Example Description

Conditional jump if x < y goto L1 Conditional branching

Label declaration L1: Used as jump target

Function call param x, call p, n Parameter passing and function calling

Return return x Return statement

4. Temporary Variables

Most TAC instructions use temporary variables (t1, t2, ...) to hold intermediate results.

Example:
Expression: a + b * c
TAC:

t1 = b * c

t2 = a + t1

5. Types of Three-Address Code Representations

The Three-Address Code can be implemented in several internal representations, each


suited for different stages of compiler optimization and code generation.

A. Quadruples (Quad)
B. Triples

Advantages: Uses less memory, useful in some optimization passes.

C. Indirect Triples

Modifies triples to use an array of pointers to instructions (indirection) to simplify code


movement and optimization.

6. Example: Convert an Expression to TAC

Expression:

a = (b + c) * (d - e)
Step-by-step TAC:

t1 = b + c

t2 = d - e

t3 = t1 * t2

a = t3

Each instruction here has at most three addresses, and each operation is reduced to a
simple step.

Implementation Steps of Three-Address Code (TAC)

1. Parse the code


→ Compiler checks the syntax and builds a parse tree.

2. Build AST
→ Converts parse tree to a simpler Abstract Syntax Tree (AST).

3. Generate TAC
→ Traverses AST, creates temporary variables, and forms TAC instructions.

4. Store TAC
→ Saves instructions as Quadruples or Triples for further optimization or machine
code generation.

8. TAC for Control Flow Statements

Example: if-else statement

if (a < b) {

x = y + z;

} else {

x = y - z;

TAC:

if a < b goto L1

goto L2

L1: t1 = y + z

x = t1

goto L3
L2: t2 = y - z

x = t2

L3:

Labels and conditional jumps help simulate control flow using TAC.

9. TAC for Loops

Example: while loop

while (a < b) {

a = a + 1;

TAC:

L1: if a >= b goto L2

t1 = a + 1

a = t1

goto L1

L2:

10. Advantages of Three-Address Code

• Simple and uniform representation

• Facilitates code optimization (constant folding, dead code elimination)

• Easily translated to target machine code

• Ideal for intermediate stage of compilation

2.Illustrate the translation scheme for declaration in a procedure and nested procedures.

Translation Scheme for Declarations in Procedures and Nested Procedures

1. What is a Translation Scheme?

A translation scheme is a set of rules and actions used by the compiler to process parts of a
program (like variable declarations or functions) while building symbol tables and generating
code.

In simple terms, it tells the compiler what to do when it sees things like:

• Variable declarations (x: integer)


• Procedures/functions

• Nested procedures (a procedure inside another)

2. Declarations in a Single Procedure

In a single procedure, all variable declarations can be processed sequentially. The compiler
maintains:

• An offset: indicating the memory location (relative address) for the next variable.

• A symbol table: storing information about each variable (name, type, offset).

The compiler:

• Sets offset = 0

• x gets offset 0, width 4

• y gets offset 4, width 8

• z gets offset 12, width 12 (3 elements × 4)


Symbol Table:

Name Type Offset

x Integer 0

y Real 4

z Array[3]int 12

3. Declarations with Nested Procedures

In languages with nested procedures, a procedure can be defined inside another. Each
nested procedure gets its own symbol table, which points back to the enclosing procedure’s
table.

This allows the compiler to:

• Handle scoping correctly.

• Prevent inner procedures from accidentally modifying outer variables (unless


allowed).

Extended Grammar

P→D

D→D;D

| id : T

| proc id ; D ; S

Key Operations:

• mktable(prev) – Create a new symbol table pointing to the parent.

• enter(table, name, type, offset) – Add variable info.

• addwidth(table, width) – Store total size.

• enterproc(table, name, newtable) – Link procedure to its symbol table.


5. Tree Representation of Symbol Table Scopes

Let’s consider a sample structure:

Scope Tree

Symbol Table Chain

• partition → points to quicksort

• quicksort → points to sort

• sort → base table (global)

This enables variable lookup from inner scopes to outer.


3 Develop the syntax directed translation scheme for following Assignment
statements.
S -> id: = E
E -> E1 + E2
E -> E1 * E2
E -> - E1
E -> (E1)
E -> id

Syntax Directed Translation Scheme for Assignment Statements

1. Introduction

In compiler design, syntax-directed translation (SDT) is used to generate intermediate code


like three-address code (TAC) during parsing. It attaches semantic actions (code or logic) to
grammar rules.

For assignment statements and arithmetic expressions, we want to:

• Track how expressions are computed.

• Use temporary variables for intermediate results.

• Generate TAC step by step.

This approach makes it easier to convert high-level source code into low-level instructions
that can later be translated into machine code.

Video link: https://youtu.be/yFEzslEhdhE?si=7spu_b_sa156uNqH


4.Consider the following CFG

E->E or T|T

T->T and F|F

F->not F|(E)|True|False

Identify the semantic rules and explain the process of converting the Boolean

expression “not (true or false)” to intermediate form.

Videolinks:

1. https://youtu.be/zWKlmk1POPg?si=jLAtTXQWEoPz81x4

2. https://youtu.be/5H0Kp7TwvG0?si=0Z2Gb0l-Fo9s-o1F
For expression asked in question:

5 Explain the procedure to convert the flow of control statements into


intermediate form. Develop intermediate form from the following statements.
if(a>b)
x=a+b
else
x=a-b
To convert flow of control statements (like if, else, while, for, etc.) into intermediate code
form, the goal is to represent these high-level constructs using a lower-level, simpler three-
address code (TAC) or similar format. This intermediate code is closer to assembly and
easier for further compilation or optimization.

General Procedure to Convert Flow of Control to Intermediate Code

1. Identify Control Flow Statements

• Examples: if, if-else, while, for, do-while, switch, etc.

• Focus on branching conditions and loop structures.

2. Generate Labels for Control Transfers

• Use labels (like L1, L2, etc.) to mark points where control jumps.

• Labels are essential in intermediate code for jumps (goto-like statements).

3. Translate Boolean Conditions

• Convert logical expressions (a > b, x == y) into conditional jumps.

• Use:

o if condition goto Ltrue

o goto Lfalse

4. Use Goto Statements and Labels for Flow

• Replace structured control (like if) with goto and label-based control.

Video link:https://youtu.be/75Tme7scP2k?si=Ld20v8JENNuvGMGo
(write rules given in the video)

Code for statement given in question:

if (a > b)

x = a + b;

else

x = a - b;

Step-by-step Translation:

1. Check the condition: if (a > b)

2. If true, jump to the label that performs x = a + b

3. If false, execute x = a - b
4. After executing either branch, jump to a common point to continue

For understanding no need to study


Explanation:

• Condition: if a > b goto L1 — If condition is true, go to label L1

• goto L2 — If false, go to the else block at L2

• Label L1 (True Block):

o t1 = a + b — Temporary variable stores the result

o x = t1 — Assignment to x

o goto L3 — Jump over the else part

• Label L2 (False Block):

o t2 = a - b — Subtraction result

o x = t2 — Assignment to x

• Label L3: End point of the control flow

6 Develop the syntax directed translation scheme for case statements and

Translate the following into intermediate form.

switch(ch)

case 1:

c-=a+b;

break;
case 2:

c=a-b;

break;

Introduction

Intermediate code generation is an essential phase in a compiler where high-level control


flow statements like if, switch, and loops are converted into a simpler, machine-independent
form. This is usually done using Three-Address Code (TAC), which uses temporary variables,
labels, and jumps to represent program logic clearly and efficiently.

Video link: https://youtu.be/AToIZOsjxiY?si=1g0G29KLmn0PMubN

(write rules given in the video)

Code for statement given in question:

switch(ch) {

case 1:

c -= a + b;

break;

case 2:

c = a - b;

break;

}
Explanation:

1. Evaluate the Switch Expression:

o t = ch: Store the value of ch in a temporary variable t for comparison.

2. Conditional Jumps:

o if t == 1 goto L1: If t equals 1, jump to label L1.

o if t == 2 goto L2: If t equals 2, jump to label L2.

o goto L3: If none of the above conditions are met, jump to L3 (end of the
switch).

3. Case 1 (L1):

o t1 = a + b: Compute the sum of a and b, store in t1.

o c = c - t1: Subtract t1 from c.

o goto L3: After executing case 1, jump to the end of the switch.

4. Case 2 (L2):

o t2 = a - b: Compute the difference between a and b, store in t2.

o c = t2: Assign the result to c.

o goto L3: After executing case 2, jump to the end of the switch.

5. End of Switch (L3):

o Marks the point where control resumes after the switch statement.

7 Explain synthesized attribute and inherited attribute with suitable examples.

Video link: https://youtu.be/nIMBA0qO684?si=i__N2N9vG6GJXdTT

8 Explain in detail about the back patching procedure to replace the goto statements by its
target address in intermediate code conversion.

Video link: https://youtu.be/uFqYXPExTuU?si=mdoWDv8-DyKAZeHC

You might also like