SlideShare a Scribd company logo
Intermediate Representations
Control Flow Graphs (CFG)
Don by khalid alsediri
COMP2105
Intermediate Representations(IR)
An intermediate representation is a representation of a program
part way between the source and target language
.
IR use many technique for representation
-Structured (graph or tree-based)
-Flat, tuple-based
-Flat, stack-based
-Or any combination of the above three
Optimization
Code transformations to improve program
-minimize execution time.
-reduce program size .
Must be save, the result program should give same
result to all possible input
Control Flow Graphs(CFG)
A control flow graph (CFG) is a data structure for High level
representation or low level representation .
1. break the big problem into smaller piece which are
manageable
2. To perform machine independent optimizations
3. Can easily find unreachable code
4. Makes syntactic structure (like loops) easy to find
The CFG is a directed graph where the vertices represent
basic blocks and edges represent possible transfer of control
flow from one basic block to another
Building CFG
• We divide the intermediate code of each procedure into basic
blocks. A basic block is a piece of straight line code, i.e. there
are no jumps in or out of the middle of a block.
• The basic blocks within one procedure are organized as a
(control) flow graph, or CFG. A flow-graph has
• basic blocks 𝑩 𝟏· · · 𝑩 𝒏 as nodes,
• a directed edge 𝑩 𝟏 𝑩 𝟐 if control can flow from 𝑩 𝟏 to 𝑩 𝟐.
• Special nodes ENTER and EXIT that are the source and sink
of the graph.
• Inside each basic block can be any of the IRs we’ve seen:
tuples, trees, DAGs, etc.
Building CFG
Building the CFG
• High-level representation
– Control flow is implicit in an AST.
• Low-level representation:
– Nodes represent statements (low-level linear IR)
– Edges represent explicit flow of control
• Program
x = z-2 ;
y = 2*z;
if (c) {
x = x+1;
y = y+1;
}
else {
x = x-1;
y = y-1;
}
z = x+y;
x = z-2 ;
y = 2*z;
if (c)
x = x+1;
y = y+1;
x = x-1;
y = y-1;
z = x+y;
B3
B1
B2
B4
FT
Example high level
1 a := 0
2 b := a * b
3 L1: c := b/d
4 if c < x goto L2
5 e := b / c
6 f := e + 1
7 L2: g := f
8 h := t - g
9 if e > 0 goto L3
10 goto L1
11 L3: return
a := 0
b := a * b
c := b/d
if c < x
e := b / c
f := e + 1
g := f
h := t - g
if e > 0
goto return
B1
B2
B3
B4
B6 B5
Low level example
---------Source Code-----------------------
X := 20; WHILE X < 10 DO
X := X-1; A[X] := 10;
IF X = 4 THEN X := X - 2; ENDIF;
ENDDO; Y := X + 5;
---------Intermediate Code---------------
(1) X := 20
(2) if X>=10 goto (8)
(3) X := X-1
(4) A[X] := 10
(5) if X<>4 goto (7)
(6) X := X-2
(7) goto (2)
(8) Y := X+5
X := 20
Y := X+5
goto B2
X := X-2
X := X-1
(4) A[X] := 10
(5) if X<>4 goto B6
if X>=10 goto B4
B1
B2
B4B3
B5
B6
Building basic blocks algorithm
• Identify leaders
1-The first instruction in a procedure, or
2-The target of any branch, or
3-An instruction immediately following a branch (implicit target)
• For each leader, its basic block is the leader
and all statements up to, but not including, the
next leader or the end of the program.
Building basic blocks algorithm
• Input: List of n instructions (instr[i] =𝑖 𝑡ℎ instruction),
A sequence of intermediate code statements
Output: Set of leaders & list of basic blocks
(block[x] is block with leader x)
leaders = {1} // First instruction is a leader
for i = 1 to n // Find all leaders
if instr[i] is a branch
leaders = leaders ∪ set of potential targets of instr[i]
foreach x ∈ leaders //each leader is leader of it self
block[x] = { x }
i = x+1 // Fill out x’s basic block
while i ≤ n and i ∉ leaders
block[x] = block[x] ∪ { i }
i = i + 1
Building basic blocks algorithm
1 a := 0
2 b := a * b
3 L1: c := b/d
4 if c < x got L2
5 e := b / c
6 f := e + 1
7 L2: g := f
8 h := t - g
9 if e > 0 goto L3
10 goto L1
11 L3: return
Building basic blocks algorithm
1 a := 0
2 b := a * b
3 L1: c := b/d
4 if c < x got L2
5 e := b / c
6 f := e + 1
7 L2: g := f
8 h := t - g
9 if e > 0 goto L3
10 goto L1
11 L3: return
Leaders?
– {1, 3, 5, 7, 10, 11}
Blocks?
– {1, 2}
– {3, 4}
– {5, 6}
– {7, 8, 9}
– {10}
– {11}
Building CFG
• Input: A list of m basic blocks (block)
Output: A CFG where each node is a basic block
for i = 1 to m
x = last instruction of block[i]
if instr x is a branch
for each target (to block j) of instr x
create an edge from block i to block j
if instr x is not an unconditional branch
create an edge from block i to block i+1
Building basic blocks algorithm
1 a := 0
2 b := a * b
3 L1: c := b/d
4 if c < x got L2
5 e := b / c
6 f := e + 1
7 L2: g := f
8 h := t - g
9 if e > 0 goto L3
10 goto L1
11 L3: return
Leaders?
– {1, 3, 5, 7, 10, 11}
Blocks?
– {1, 2}
– {3, 4}
– {5, 6}
– {7, 8, 9}
– {10}
– {11}
1 a := 0
2 b := a * b
3 L1: c := b/d
4 if c < x got L2
5 e := b /
c
6 f := e +
1
7 L2: g := f
8 h := t - g
9 if e > 0 goto
L3
10 goto
L1
11 L3:
return
Variation of CFG
• Extended basic blocks
-A maximal sequence of instructions that
-has no merge points in it (except perhaps in the leader)
-Single entry, multiple exits
• Reverse extended basic blocks
-Useful for “backward flow” problems
Reference
• Modern Compilers: Theory , V. Krishna Nandivada,
2015,http://www.cse.iitm.ac.in/~krishna/courses/2015/even-
cs6013/lecture4.pdf ,accessed(19-14-2016).
• Introduction to Compilers,Tim
Teitelbaum,2008,http://www.cs.cornell.edu/courses/cs412/2008sp/l
ectures/lec24.pdf,accessed(19-14-2016).
• Modern Programming Language Implementation , E Christopher
Lewis ,2006,http://www.cis.upenn.edu/~cis570/slides/lecture03.pdf,
accessed(19-14-2016).

More Related Content

What's hot

Unit 3 Control Flow Testing
Unit 3   Control Flow TestingUnit 3   Control Flow Testing
Unit 3 Control Flow Testing
ravikhimani
 
Matrix chain multiplication
Matrix chain multiplicationMatrix chain multiplication
Matrix chain multiplication
Respa Peter
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
debugging (1).ppt
debugging (1).pptdebugging (1).ppt
debugging (1).ppt
jerlinS1
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
Akhil Kaushik
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Language for specifying lexical Analyzer
Language for specifying lexical AnalyzerLanguage for specifying lexical Analyzer
Language for specifying lexical Analyzer
Archana Gopinath
 
C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#
Dr.Neeraj Kumar Pandey
 
Unit testing
Unit testing Unit testing
Unit testing
Mani Kanth
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
United International University
 
Code generation
Code generationCode generation
Code generation
Aparna Nayak
 
Role-of-lexical-analysis
Role-of-lexical-analysisRole-of-lexical-analysis
Role-of-lexical-analysis
Dattatray Gandhmal
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Lexical Analysis - Compiler Design
Lexical Analysis - Compiler DesignLexical Analysis - Compiler Design
Lexical Analysis - Compiler Design
Akhil Kaushik
 
Symbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code GenerationSymbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code Generation
Akhil Kaushik
 
software quality
software qualitysoftware quality
software quality
preetikapri1
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translation
Akshaya Arunan
 
Lecture optimal binary search tree
Lecture optimal binary search tree Lecture optimal binary search tree
Lecture optimal binary search tree
Divya Ks
 

What's hot (20)

Unit 3 Control Flow Testing
Unit 3   Control Flow TestingUnit 3   Control Flow Testing
Unit 3 Control Flow Testing
 
Matrix chain multiplication
Matrix chain multiplicationMatrix chain multiplication
Matrix chain multiplication
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
debugging (1).ppt
debugging (1).pptdebugging (1).ppt
debugging (1).ppt
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Language for specifying lexical Analyzer
Language for specifying lexical AnalyzerLanguage for specifying lexical Analyzer
Language for specifying lexical Analyzer
 
C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#
 
Unit testing
Unit testing Unit testing
Unit testing
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
 
Code generation
Code generationCode generation
Code generation
 
Role-of-lexical-analysis
Role-of-lexical-analysisRole-of-lexical-analysis
Role-of-lexical-analysis
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Lexical Analysis - Compiler Design
Lexical Analysis - Compiler DesignLexical Analysis - Compiler Design
Lexical Analysis - Compiler Design
 
Symbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code GenerationSymbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code Generation
 
software quality
software qualitysoftware quality
software quality
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translation
 
Lecture optimal binary search tree
Lecture optimal binary search tree Lecture optimal binary search tree
Lecture optimal binary search tree
 
Uml class-diagram
Uml class-diagramUml class-diagram
Uml class-diagram
 

Similar to Control Flow Graphs

Principal Sources of Optimization in compiler design
Principal Sources of Optimization in compiler design Principal Sources of Optimization in compiler design
Principal Sources of Optimization in compiler design
LogsAk
 
Code Optimization.ppt
Code Optimization.pptCode Optimization.ppt
Code Optimization.ppt
JohnSamuel280314
 
CS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.pptCS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.ppt
ssuser0be977
 
ERTS UNIT 3.ppt
ERTS UNIT 3.pptERTS UNIT 3.ppt
ERTS UNIT 3.ppt
Pavithra525349
 
Code optimization lecture
Code optimization lectureCode optimization lecture
Code optimization lecture
Prashant Singh
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5PRADEEP
 
Compiler unit 4
Compiler unit 4Compiler unit 4
Compiler unit 4
BBDITM LUCKNOW
 
Control Flow Analysis
Control Flow AnalysisControl Flow Analysis
Control Flow Analysis
Edgar Barbosa
 
ESL Anyone?
ESL Anyone? ESL Anyone?
ESL Anyone? DVClub
 
vlsi design using verilog presentaion 1
vlsi design using verilog   presentaion 1vlsi design using verilog   presentaion 1
vlsi design using verilog presentaion 1
MANDHASAIGOUD1
 
Lcdf4 chap 03_p2
Lcdf4 chap 03_p2Lcdf4 chap 03_p2
Lcdf4 chap 03_p2
ozgur_can
 
1.ppt
1.ppt1.ppt
Boosting Developer Productivity with Clang
Boosting Developer Productivity with ClangBoosting Developer Productivity with Clang
Boosting Developer Productivity with Clang
Samsung Open Source Group
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
Wei-Ren Chen
 
Basic Block
Basic BlockBasic Block
Basic Block
Shiv1234567
 
Verilogforlab
VerilogforlabVerilogforlab
Verilogforlab
Shankar Bhukya
 
Lecture 16 RC Architecture Types & FPGA Interns Lecturer.pptx
Lecture 16 RC Architecture Types & FPGA Interns Lecturer.pptxLecture 16 RC Architecture Types & FPGA Interns Lecturer.pptx
Lecture 16 RC Architecture Types & FPGA Interns Lecturer.pptx
wafawafa52
 
Archi Modelling
Archi ModellingArchi Modelling
Archi Modellingdilane007
 
Mcs 10 104 compiler design dec 2014
Mcs 10 104 compiler design dec 2014Mcs 10 104 compiler design dec 2014
Mcs 10 104 compiler design dec 2014
Sreeju Sree
 

Similar to Control Flow Graphs (20)

Lecture03
Lecture03Lecture03
Lecture03
 
Principal Sources of Optimization in compiler design
Principal Sources of Optimization in compiler design Principal Sources of Optimization in compiler design
Principal Sources of Optimization in compiler design
 
Code Optimization.ppt
Code Optimization.pptCode Optimization.ppt
Code Optimization.ppt
 
CS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.pptCS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.ppt
 
ERTS UNIT 3.ppt
ERTS UNIT 3.pptERTS UNIT 3.ppt
ERTS UNIT 3.ppt
 
Code optimization lecture
Code optimization lectureCode optimization lecture
Code optimization lecture
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5
 
Compiler unit 4
Compiler unit 4Compiler unit 4
Compiler unit 4
 
Control Flow Analysis
Control Flow AnalysisControl Flow Analysis
Control Flow Analysis
 
ESL Anyone?
ESL Anyone? ESL Anyone?
ESL Anyone?
 
vlsi design using verilog presentaion 1
vlsi design using verilog   presentaion 1vlsi design using verilog   presentaion 1
vlsi design using verilog presentaion 1
 
Lcdf4 chap 03_p2
Lcdf4 chap 03_p2Lcdf4 chap 03_p2
Lcdf4 chap 03_p2
 
1.ppt
1.ppt1.ppt
1.ppt
 
Boosting Developer Productivity with Clang
Boosting Developer Productivity with ClangBoosting Developer Productivity with Clang
Boosting Developer Productivity with Clang
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
Basic Block
Basic BlockBasic Block
Basic Block
 
Verilogforlab
VerilogforlabVerilogforlab
Verilogforlab
 
Lecture 16 RC Architecture Types & FPGA Interns Lecturer.pptx
Lecture 16 RC Architecture Types & FPGA Interns Lecturer.pptxLecture 16 RC Architecture Types & FPGA Interns Lecturer.pptx
Lecture 16 RC Architecture Types & FPGA Interns Lecturer.pptx
 
Archi Modelling
Archi ModellingArchi Modelling
Archi Modelling
 
Mcs 10 104 compiler design dec 2014
Mcs 10 104 compiler design dec 2014Mcs 10 104 compiler design dec 2014
Mcs 10 104 compiler design dec 2014
 

Recently uploaded

Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 

Recently uploaded (20)

Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 

Control Flow Graphs

  • 1. Intermediate Representations Control Flow Graphs (CFG) Don by khalid alsediri COMP2105
  • 2. Intermediate Representations(IR) An intermediate representation is a representation of a program part way between the source and target language . IR use many technique for representation -Structured (graph or tree-based) -Flat, tuple-based -Flat, stack-based -Or any combination of the above three
  • 3. Optimization Code transformations to improve program -minimize execution time. -reduce program size . Must be save, the result program should give same result to all possible input
  • 4. Control Flow Graphs(CFG) A control flow graph (CFG) is a data structure for High level representation or low level representation . 1. break the big problem into smaller piece which are manageable 2. To perform machine independent optimizations 3. Can easily find unreachable code 4. Makes syntactic structure (like loops) easy to find The CFG is a directed graph where the vertices represent basic blocks and edges represent possible transfer of control flow from one basic block to another
  • 5. Building CFG • We divide the intermediate code of each procedure into basic blocks. A basic block is a piece of straight line code, i.e. there are no jumps in or out of the middle of a block. • The basic blocks within one procedure are organized as a (control) flow graph, or CFG. A flow-graph has • basic blocks 𝑩 𝟏· · · 𝑩 𝒏 as nodes, • a directed edge 𝑩 𝟏 𝑩 𝟐 if control can flow from 𝑩 𝟏 to 𝑩 𝟐. • Special nodes ENTER and EXIT that are the source and sink of the graph. • Inside each basic block can be any of the IRs we’ve seen: tuples, trees, DAGs, etc.
  • 7. Building the CFG • High-level representation – Control flow is implicit in an AST. • Low-level representation: – Nodes represent statements (low-level linear IR) – Edges represent explicit flow of control
  • 8. • Program x = z-2 ; y = 2*z; if (c) { x = x+1; y = y+1; } else { x = x-1; y = y-1; } z = x+y; x = z-2 ; y = 2*z; if (c) x = x+1; y = y+1; x = x-1; y = y-1; z = x+y; B3 B1 B2 B4 FT Example high level
  • 9. 1 a := 0 2 b := a * b 3 L1: c := b/d 4 if c < x goto L2 5 e := b / c 6 f := e + 1 7 L2: g := f 8 h := t - g 9 if e > 0 goto L3 10 goto L1 11 L3: return a := 0 b := a * b c := b/d if c < x e := b / c f := e + 1 g := f h := t - g if e > 0 goto return B1 B2 B3 B4 B6 B5 Low level example
  • 10. ---------Source Code----------------------- X := 20; WHILE X < 10 DO X := X-1; A[X] := 10; IF X = 4 THEN X := X - 2; ENDIF; ENDDO; Y := X + 5; ---------Intermediate Code--------------- (1) X := 20 (2) if X>=10 goto (8) (3) X := X-1 (4) A[X] := 10 (5) if X<>4 goto (7) (6) X := X-2 (7) goto (2) (8) Y := X+5 X := 20 Y := X+5 goto B2 X := X-2 X := X-1 (4) A[X] := 10 (5) if X<>4 goto B6 if X>=10 goto B4 B1 B2 B4B3 B5 B6
  • 11. Building basic blocks algorithm • Identify leaders 1-The first instruction in a procedure, or 2-The target of any branch, or 3-An instruction immediately following a branch (implicit target) • For each leader, its basic block is the leader and all statements up to, but not including, the next leader or the end of the program.
  • 12. Building basic blocks algorithm • Input: List of n instructions (instr[i] =𝑖 𝑡ℎ instruction), A sequence of intermediate code statements Output: Set of leaders & list of basic blocks (block[x] is block with leader x) leaders = {1} // First instruction is a leader for i = 1 to n // Find all leaders if instr[i] is a branch leaders = leaders ∪ set of potential targets of instr[i] foreach x ∈ leaders //each leader is leader of it self block[x] = { x } i = x+1 // Fill out x’s basic block while i ≤ n and i ∉ leaders block[x] = block[x] ∪ { i } i = i + 1
  • 13. Building basic blocks algorithm 1 a := 0 2 b := a * b 3 L1: c := b/d 4 if c < x got L2 5 e := b / c 6 f := e + 1 7 L2: g := f 8 h := t - g 9 if e > 0 goto L3 10 goto L1 11 L3: return
  • 14. Building basic blocks algorithm 1 a := 0 2 b := a * b 3 L1: c := b/d 4 if c < x got L2 5 e := b / c 6 f := e + 1 7 L2: g := f 8 h := t - g 9 if e > 0 goto L3 10 goto L1 11 L3: return Leaders? – {1, 3, 5, 7, 10, 11} Blocks? – {1, 2} – {3, 4} – {5, 6} – {7, 8, 9} – {10} – {11}
  • 15. Building CFG • Input: A list of m basic blocks (block) Output: A CFG where each node is a basic block for i = 1 to m x = last instruction of block[i] if instr x is a branch for each target (to block j) of instr x create an edge from block i to block j if instr x is not an unconditional branch create an edge from block i to block i+1
  • 16. Building basic blocks algorithm 1 a := 0 2 b := a * b 3 L1: c := b/d 4 if c < x got L2 5 e := b / c 6 f := e + 1 7 L2: g := f 8 h := t - g 9 if e > 0 goto L3 10 goto L1 11 L3: return Leaders? – {1, 3, 5, 7, 10, 11} Blocks? – {1, 2} – {3, 4} – {5, 6} – {7, 8, 9} – {10} – {11} 1 a := 0 2 b := a * b 3 L1: c := b/d 4 if c < x got L2 5 e := b / c 6 f := e + 1 7 L2: g := f 8 h := t - g 9 if e > 0 goto L3 10 goto L1 11 L3: return
  • 17. Variation of CFG • Extended basic blocks -A maximal sequence of instructions that -has no merge points in it (except perhaps in the leader) -Single entry, multiple exits • Reverse extended basic blocks -Useful for “backward flow” problems
  • 18. Reference • Modern Compilers: Theory , V. Krishna Nandivada, 2015,http://www.cse.iitm.ac.in/~krishna/courses/2015/even- cs6013/lecture4.pdf ,accessed(19-14-2016). • Introduction to Compilers,Tim Teitelbaum,2008,http://www.cs.cornell.edu/courses/cs412/2008sp/l ectures/lec24.pdf,accessed(19-14-2016). • Modern Programming Language Implementation , E Christopher Lewis ,2006,http://www.cis.upenn.edu/~cis570/slides/lecture03.pdf, accessed(19-14-2016).