SlideShare a Scribd company logo
1 of 48
Download to read offline
Lecture 10: Data-Flow Analysis
Jeff Smits
CS4200 Compiler Construction
TU Delft
November 2018
Title Text
2
Source
Code
Editor
Parse
Abstract
Syntax
Tree
Type Check
Check that names are used correctly and that expressions are well-typed
Errors
Earlier Lecture
Title Text
3
Source
Code
Editor
Parse
Abstract
Syntax
Tree
Other Check
Check that variables are initialised, statements are reached, etc.
Errors
This Lecture
Title Text
4
Source
Code
Editor
Parse
Abstract
Syntax
Tree
Optimise
Eliminate common subexpressions, reduce loop strength, etc.
Optimised
Abstract
Syntax
Tree
This Lecture
Reading Material
5
The following papers add background, conceptual exposition,
and examples to the material from the slides. Some notation and
technical details have been changed; check the documentation.
6
This paper introduces FlowSpec, the declarative data-flow
analysis specification language in Spoofax. Although the
design of the language described in this paper is still current,
the syntax used is already dated, i.e. the current FlowSpec
syntax in Spoofax is slightly different.
https://doi.org/10.1145/3136014.3136029
SLE 2017
7
Documentation for FlowSpec
at the metaborg.org website.
http://www.metaborg.org/en/latest/source/langdev/meta/lang/flowspec/index.html
Control-Flow
8
What is Control-Flow?
- “Order of evaluation”
Discuss a series of example programs
- What is the control flow?
- What constructs in the program determine that?
Control-Flow
9
What is Control-Flow?
10
function id(x) { return x; }
id(4); id(true);
- Calling a function passes control to that function

- A return passes control back to the caller
Function calls
What is Control-Flow?
11
if (c) { a = 5 } else { a = "four" }
- Control is passed to one of the two branches

- This is dependent on the value of the condition
Branching
What is Control-Flow?
12
while (c) { a = 5 }
- Control is passed to the loop body depending on the condition

- After the body we start over
Looping
What is Control-Flow?
13
float distance = 12.0;
float velocity = time / distance;
- No conditions or anything complicated

- But still order of execution
Sequence
What is Control-Flow?
14
distance = distance + 1;
- The expression needs to be evaluated, 

before we can save its result
Writes and reads
What is Control-Flow?
15
counter.next() / counter.next()
- Order in sub-expressions is usually undefined

- Side-effects make sub-expression order relevant
Expressions & side-effects
- Sequential	 statements

- Conditional	 if / switch / case

- Looping	 while / do while / for / foreach / loop

- Exceptions	 throw / try / catch / finally

- Continuations	 call/cc

- Async-await	 threading

- Coroutines / Generators	 yield

- Dispatch	 function calls / method calls

- Loop jumps	 break / continue

- ... many more ...	
What kind of Control-Flow?
16
Shorter code
- No need to repeat the same statement 10 times
Parametric code
- Extract reusable patterns
- Let user decide repetition amount
Expressive power
- Playing with the Turing Machines
Reason about program execution
- What happens when?
- In what order?
Why Control-Flow?
17
Imperative programming
- Explicit control-flow constructs
Declarative programming
- What, not how
- Less explicit control-flow

- More options for compilers to choose order
- Great if your compiler is often smarter than the programmer
Control-Flow and language design
18
Representation
- Represent control-flow of a program
- Conduct and represent results of data-flow analysis
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
19
Control-Flow Graphs
20
What is a Control-Flow Graph?
21
A control flow graph (CFG) in computer science is a representation, using graph notation, of
all paths that might be traversed through a program during its execution.
https://en.wikipedia.org/wiki/Control_flow_graph
let
var x : int := a + b
var y : int := a * b
in
while y > a + b do
(
a := a + 1;
x := a + b
)
end
Control-Flow Graph example
22
Control-Flow Graph example
23
y > a + b
var y : int := a * b
var x : int := a + b
a := a + 1
x := a + b
Basic blocks
24
var x : int := a + b
var y : int := a * b
y > a + b
a := a + 1
x := a + b
Nodes
- Usually innermost statements and expressions
- Or blocks for consecutive statements (basic blocks)

Edges
- Back edges: show loops
- Splits: conditionally split the control flow
- Merges: combine previously split control flow
Control Flow Graphs
25
Equivalent to unstructured control-flow
26
a ← 0
L1: b ← a + 1
c ← c + b
a ← 2 * b
if a < N goto L1
return c
a ← 0
b ← a + 1
c ← c + b
a ← 2 * b
a < N
return c
Representation
- Represent control-flow of a program
- Conduct and represent results of data-flow analysis
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
27
Representation
-
- Conduct and represent results of data-flow analysis
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
28
Control Flow Graphs
Data-Flow
29
What is Data-Flow?
- Possible values (data) that flow through the program
- Relations between that data (data dependence)
Discuss a series of example programs
- What is wrong or can be optimised?
- What is the flow we can use for this?
Data-Flow
30
Source
Code
Editor
Parse
Abstract
Syntax
Tree
Other Check
Check that code is reachable or observable
Errors
31
public int ComputeFac(int num) {
return num;
int num_aux;
if (num < 1)
num_aux = 1;
else
num_aux = num * this.ComputeFac(num-1);
return num_aux;
}
What is wrong here?
32
- Most of the code is never reached because of the early return

- This is usually considered an error by compilers
Dead code (control-flow)
x := 2;
y := 4;
x := 1;
// x and y used later
What is “wrong” here?
33
- The first value of x is never observed

- This is sometimes warned about by compilers
Dead code (data-flow)
Live variable analysis
Source
Code
Editor
Parse
Abstract
Syntax
Tree
Optimise
Eliminate common subexpressions, reduce loop strength, etc.
Optimised
Abstract
Syntax
Tree
34
let
var x : int := a + b
var y : int := a * b
in
if y > a + b then
(
a := a + 1;
x := a + b
)
end
What is suboptimal here?
35
- a + b is already computed when you get to the condition

- There is no need to compute it again
Common subexpression elimination
Available expression analysis
What is suboptimal here?
for i := 1 to 100 do
(
x[i] := y[i];
if w > 0 then
y[i] := 0
)
- The if condition is not dependent on i, x or y

- Still it is checked in the loop, which is slowing the loop
Loop unswitching
36
Data-dependence analysis
Tiger in FlowSpec
37
Representation
-
- Conduct and represent results of data-flow analysis
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
38
Control Flow Graphs
Representation
-
-
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
39
Control Flow Graphs
Data-flow information on CFG nodes
Representation
-
-
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
40
Control Flow Graphs
Data-flow information on CFG nodes
A domain-specific meta-language for Spoofax: FlowSpec
Map abstract syntax to control-flow (sub)graphs
- Match an AST pattern
- List all edges of that AST
- Use special “context” nodes to connect a subgraph to the outside graph
Control-Flow rules
x := 1;
if y > x then
z := y;
else
z := y * y;
y := a * b;
while y > a + b do
(a := a + 1;
x := a + b)
Control-flow graphs in FlowSpec
root Mod(s) =
start -> s -> end
start
end
While(c, b) =
entry -> node c -> b -> node c,
node c -> exit
IfThenElse(c, t, e) =
entry -> node c -> t -> exit,
node c -> e -> exit
Seq(s1, s2) =
entry -> s1 -> s2 -> exit
node Assign(_, _)
FlowSpec Example program
Data-Flow rules
Define effect of control-flow nodes
- Match an AST pattern on one side of a CFG edge
- Propagate the information from the other side of the edge
- Adapt that information as the effect of the matched CFG node
{z,x}
{z,x}
{z,x}
{z,x}
{z}
{}
{}
{}
{}
{}
{x}
{z}
{}
{}
x := 2;
y := 4;
x := 1;
z := x;
x := z;
{}
{}
{}
{}
{}
{}
{}
Live Variables in FlowSpec
properties
live: MaySet(name)
live(Assign(n, _) -> next) =
{ m | m <- live(next), n != m }
live(Ref(n) -> next) =
live(next) / {n}
live(_.end) =
{}
A variable is live if the current value
of the variable may be read further
along in the program
end
start
property rules
x := 2;
y := 4;
x := 1;
if y > 0 then
z := x;
else
z := y * y;
x := z;
{x,y}
{x}
{y}
{z}
{}
{}
{z}
{}
{}
{x}
{y}
{z}
{}
{}end
start
Live Variables in FlowSpec
A variable is live if the current value
of the variable may be read further
along in the program
properties
live: MaySet(name)
live(Assign(n, _) -> next) =
{ m | m <- live(next), n != m }
live(Ref(n) -> next) =
live(next) / {n}
live(_.end) =
{}
property rules
Conclusion
46
Control-Flow
- Order of execution
- Reasoning about what is reachable
Data-Flow
- Flow of data through a program
- Reasoning about data, and dependencies between data
FlowSpec
- Control-Flow rules to construct the graph
- Annotate with information from analysis by Data-Flow rules
Summary
47
Except where otherwise noted, this work is licensed under

More Related Content

What's hot

Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc pptpssraikar
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generationrawan_z
 
Code optimization in compiler design
Code optimization in compiler designCode optimization in compiler design
Code optimization in compiler designKuppusamy P
 
Chapter Eight(1)
Chapter Eight(1)Chapter Eight(1)
Chapter Eight(1)bolovv
 
Intermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignIntermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignKuppusamy P
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingEelco Visser
 
Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Robert Pickering
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler DesignKuppusamy P
 
Three address code In Compiler Design
Three address code In Compiler DesignThree address code In Compiler Design
Three address code In Compiler DesignShine Raj
 

What's hot (20)

Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
 
Compiler unit 4
Compiler unit 4Compiler unit 4
Compiler unit 4
 
Ch4c
Ch4cCh4c
Ch4c
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generation
 
Code optimization in compiler design
Code optimization in compiler designCode optimization in compiler design
Code optimization in compiler design
 
Introduction to HDLs
Introduction to HDLsIntroduction to HDLs
Introduction to HDLs
 
Chapter Eight(1)
Chapter Eight(1)Chapter Eight(1)
Chapter Eight(1)
 
Intermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignIntermediate code generation in Compiler Design
Intermediate code generation in Compiler Design
 
Code optimization
Code optimizationCode optimization
Code optimization
 
Code Generation
Code GenerationCode Generation
Code Generation
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | Parsing
 
Compiler unit 2&3
Compiler unit 2&3Compiler unit 2&3
Compiler unit 2&3
 
Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#
 
Code generation
Code generationCode generation
Code generation
 
C language
C languageC language
C language
 
Interm codegen
Interm codegenInterm codegen
Interm codegen
 
Compiler unit 5
Compiler  unit 5Compiler  unit 5
Compiler unit 5
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler Design
 
Three address code In Compiler Design
Three address code In Compiler DesignThree address code In Compiler Design
Three address code In Compiler Design
 

Similar to Compiler Construction | Lecture 10 | Data-Flow Analysis

7-White Box Testing.ppt
7-White Box Testing.ppt7-White Box Testing.ppt
7-White Box Testing.pptHirenderPal
 
Compiler Construction for DLX Processor
Compiler Construction for DLX Processor Compiler Construction for DLX Processor
Compiler Construction for DLX Processor Soham Kulkarni
 
Reverse Engineering automation
Reverse Engineering automationReverse Engineering automation
Reverse Engineering automationPositive Hack Days
 
Taking Spark Streaming to the Next Level with Datasets and DataFrames
Taking Spark Streaming to the Next Level with Datasets and DataFramesTaking Spark Streaming to the Next Level with Datasets and DataFrames
Taking Spark Streaming to the Next Level with Datasets and DataFramesDatabricks
 
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das Databricks
 
Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0Anyscale
 
My Postdoctoral Research
My Postdoctoral ResearchMy Postdoctoral Research
My Postdoctoral ResearchPo-Ting Wu
 
Measuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedMeasuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedDennis de Greef
 
NSC #2 - D2 06 - Richard Johnson - SAGEly Advice
NSC #2 - D2 06 - Richard Johnson - SAGEly AdviceNSC #2 - D2 06 - Richard Johnson - SAGEly Advice
NSC #2 - D2 06 - Richard Johnson - SAGEly AdviceNoSuchCon
 
Lecture1-Algorithms-and-Flowcharts-ppt.ppt
Lecture1-Algorithms-and-Flowcharts-ppt.pptLecture1-Algorithms-and-Flowcharts-ppt.ppt
Lecture1-Algorithms-and-Flowcharts-ppt.pptReshuReshma8
 
Apache Flink Deep Dive
Apache Flink Deep DiveApache Flink Deep Dive
Apache Flink Deep DiveVasia Kalavri
 
A Deep Dive into Structured Streaming: Apache Spark Meetup at Bloomberg 2016
A Deep Dive into Structured Streaming:  Apache Spark Meetup at Bloomberg 2016 A Deep Dive into Structured Streaming:  Apache Spark Meetup at Bloomberg 2016
A Deep Dive into Structured Streaming: Apache Spark Meetup at Bloomberg 2016 Databricks
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapKostas Tzoumas
 
2007 Tidc India Profiling
2007 Tidc India Profiling2007 Tidc India Profiling
2007 Tidc India Profilingdanrinkes
 
cs241-f06-final-overview
cs241-f06-final-overviewcs241-f06-final-overview
cs241-f06-final-overviewColin Bell
 
AlgorithmAndFlowChart.pdf
AlgorithmAndFlowChart.pdfAlgorithmAndFlowChart.pdf
AlgorithmAndFlowChart.pdfSusieMaestre1
 
Basic Slides on Algorithms and Flowcharts
Basic Slides on Algorithms and FlowchartsBasic Slides on Algorithms and Flowcharts
Basic Slides on Algorithms and Flowchartsmoazwinner
 
advanced computer architesture-conditions of parallelism
advanced computer architesture-conditions of parallelismadvanced computer architesture-conditions of parallelism
advanced computer architesture-conditions of parallelismPankaj Kumar Jain
 

Similar to Compiler Construction | Lecture 10 | Data-Flow Analysis (20)

7-White Box Testing.ppt
7-White Box Testing.ppt7-White Box Testing.ppt
7-White Box Testing.ppt
 
Compiler Construction for DLX Processor
Compiler Construction for DLX Processor Compiler Construction for DLX Processor
Compiler Construction for DLX Processor
 
Reverse Engineering automation
Reverse Engineering automationReverse Engineering automation
Reverse Engineering automation
 
Taking Spark Streaming to the Next Level with Datasets and DataFrames
Taking Spark Streaming to the Next Level with Datasets and DataFramesTaking Spark Streaming to the Next Level with Datasets and DataFrames
Taking Spark Streaming to the Next Level with Datasets and DataFrames
 
Flink internals web
Flink internals web Flink internals web
Flink internals web
 
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
 
Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0
 
My Postdoctoral Research
My Postdoctoral ResearchMy Postdoctoral Research
My Postdoctoral Research
 
Measuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedMeasuring maintainability; software metrics explained
Measuring maintainability; software metrics explained
 
SWEET - A Tool for WCET Flow Analysis - Björn Lisper
SWEET - A Tool for WCET Flow Analysis - Björn LisperSWEET - A Tool for WCET Flow Analysis - Björn Lisper
SWEET - A Tool for WCET Flow Analysis - Björn Lisper
 
NSC #2 - D2 06 - Richard Johnson - SAGEly Advice
NSC #2 - D2 06 - Richard Johnson - SAGEly AdviceNSC #2 - D2 06 - Richard Johnson - SAGEly Advice
NSC #2 - D2 06 - Richard Johnson - SAGEly Advice
 
Lecture1-Algorithms-and-Flowcharts-ppt.ppt
Lecture1-Algorithms-and-Flowcharts-ppt.pptLecture1-Algorithms-and-Flowcharts-ppt.ppt
Lecture1-Algorithms-and-Flowcharts-ppt.ppt
 
Apache Flink Deep Dive
Apache Flink Deep DiveApache Flink Deep Dive
Apache Flink Deep Dive
 
A Deep Dive into Structured Streaming: Apache Spark Meetup at Bloomberg 2016
A Deep Dive into Structured Streaming:  Apache Spark Meetup at Bloomberg 2016 A Deep Dive into Structured Streaming:  Apache Spark Meetup at Bloomberg 2016
A Deep Dive into Structured Streaming: Apache Spark Meetup at Bloomberg 2016
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmap
 
2007 Tidc India Profiling
2007 Tidc India Profiling2007 Tidc India Profiling
2007 Tidc India Profiling
 
cs241-f06-final-overview
cs241-f06-final-overviewcs241-f06-final-overview
cs241-f06-final-overview
 
AlgorithmAndFlowChart.pdf
AlgorithmAndFlowChart.pdfAlgorithmAndFlowChart.pdf
AlgorithmAndFlowChart.pdf
 
Basic Slides on Algorithms and Flowcharts
Basic Slides on Algorithms and FlowchartsBasic Slides on Algorithms and Flowcharts
Basic Slides on Algorithms and Flowcharts
 
advanced computer architesture-conditions of parallelism
advanced computer architesture-conditions of parallelismadvanced computer architesture-conditions of parallelism
advanced computer architesture-conditions of parallelism
 

More from Eelco Visser

CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingEelco Visser
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesEelco Visser
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionEelco Visser
 
CS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionCS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionEelco Visser
 
A Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesA Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesEelco Visser
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with StatixEelco Visser
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionEelco Visser
 
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Eelco Visser
 
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementCompiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementEelco Visser
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersEelco Visser
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionEelco Visser
 
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsCompiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsEelco Visser
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingEelco Visser
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisEelco Visser
 
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingCompiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingEelco Visser
 
Compiler Construction | Lecture 4 | Parsing
Compiler Construction | Lecture 4 | Parsing Compiler Construction | Lecture 4 | Parsing
Compiler Construction | Lecture 4 | Parsing Eelco Visser
 
Compiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionCompiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionEelco Visser
 
Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Eelco Visser
 
Declare Your Language: Virtual Machines & Code Generation
Declare Your Language: Virtual Machines & Code GenerationDeclare Your Language: Virtual Machines & Code Generation
Declare Your Language: Virtual Machines & Code GenerationEelco Visser
 
Declare Your Language: Dynamic Semantics
Declare Your Language: Dynamic SemanticsDeclare Your Language: Dynamic Semantics
Declare Your Language: Dynamic SemanticsEelco Visser
 

More from Eelco Visser (20)

CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic Services
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 
CS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionCS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: Introduction
 
A Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesA Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation Rules
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler Construction
 
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
 
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementCompiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory Management
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | Interpreters
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
 
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsCompiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type Constraints
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type Checking
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static Analysis
 
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingCompiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
 
Compiler Construction | Lecture 4 | Parsing
Compiler Construction | Lecture 4 | Parsing Compiler Construction | Lecture 4 | Parsing
Compiler Construction | Lecture 4 | Parsing
 
Compiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionCompiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax Definition
 
Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?
 
Declare Your Language: Virtual Machines & Code Generation
Declare Your Language: Virtual Machines & Code GenerationDeclare Your Language: Virtual Machines & Code Generation
Declare Your Language: Virtual Machines & Code Generation
 
Declare Your Language: Dynamic Semantics
Declare Your Language: Dynamic SemanticsDeclare Your Language: Dynamic Semantics
Declare Your Language: Dynamic Semantics
 

Recently uploaded

Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 

Recently uploaded (20)

Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 

Compiler Construction | Lecture 10 | Data-Flow Analysis

  • 1. Lecture 10: Data-Flow Analysis Jeff Smits CS4200 Compiler Construction TU Delft November 2018
  • 2. Title Text 2 Source Code Editor Parse Abstract Syntax Tree Type Check Check that names are used correctly and that expressions are well-typed Errors Earlier Lecture
  • 3. Title Text 3 Source Code Editor Parse Abstract Syntax Tree Other Check Check that variables are initialised, statements are reached, etc. Errors This Lecture
  • 4. Title Text 4 Source Code Editor Parse Abstract Syntax Tree Optimise Eliminate common subexpressions, reduce loop strength, etc. Optimised Abstract Syntax Tree This Lecture
  • 5. Reading Material 5 The following papers add background, conceptual exposition, and examples to the material from the slides. Some notation and technical details have been changed; check the documentation.
  • 6. 6 This paper introduces FlowSpec, the declarative data-flow analysis specification language in Spoofax. Although the design of the language described in this paper is still current, the syntax used is already dated, i.e. the current FlowSpec syntax in Spoofax is slightly different. https://doi.org/10.1145/3136014.3136029 SLE 2017
  • 7. 7 Documentation for FlowSpec at the metaborg.org website. http://www.metaborg.org/en/latest/source/langdev/meta/lang/flowspec/index.html
  • 9. What is Control-Flow? - “Order of evaluation” Discuss a series of example programs - What is the control flow? - What constructs in the program determine that? Control-Flow 9
  • 10. What is Control-Flow? 10 function id(x) { return x; } id(4); id(true); - Calling a function passes control to that function - A return passes control back to the caller Function calls
  • 11. What is Control-Flow? 11 if (c) { a = 5 } else { a = "four" } - Control is passed to one of the two branches - This is dependent on the value of the condition Branching
  • 12. What is Control-Flow? 12 while (c) { a = 5 } - Control is passed to the loop body depending on the condition - After the body we start over Looping
  • 13. What is Control-Flow? 13 float distance = 12.0; float velocity = time / distance; - No conditions or anything complicated - But still order of execution Sequence
  • 14. What is Control-Flow? 14 distance = distance + 1; - The expression needs to be evaluated, 
 before we can save its result Writes and reads
  • 15. What is Control-Flow? 15 counter.next() / counter.next() - Order in sub-expressions is usually undefined - Side-effects make sub-expression order relevant Expressions & side-effects
  • 16. - Sequential statements - Conditional if / switch / case - Looping while / do while / for / foreach / loop - Exceptions throw / try / catch / finally - Continuations call/cc - Async-await threading - Coroutines / Generators yield - Dispatch function calls / method calls - Loop jumps break / continue - ... many more ... What kind of Control-Flow? 16
  • 17. Shorter code - No need to repeat the same statement 10 times Parametric code - Extract reusable patterns - Let user decide repetition amount Expressive power - Playing with the Turing Machines Reason about program execution - What happens when? - In what order? Why Control-Flow? 17
  • 18. Imperative programming - Explicit control-flow constructs Declarative programming - What, not how - Less explicit control-flow
 - More options for compilers to choose order - Great if your compiler is often smarter than the programmer Control-Flow and language design 18
  • 19. Representation - Represent control-flow of a program - Conduct and represent results of data-flow analysis Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 19
  • 21. What is a Control-Flow Graph? 21 A control flow graph (CFG) in computer science is a representation, using graph notation, of all paths that might be traversed through a program during its execution. https://en.wikipedia.org/wiki/Control_flow_graph
  • 22. let var x : int := a + b var y : int := a * b in while y > a + b do ( a := a + 1; x := a + b ) end Control-Flow Graph example 22
  • 23. Control-Flow Graph example 23 y > a + b var y : int := a * b var x : int := a + b a := a + 1 x := a + b
  • 24. Basic blocks 24 var x : int := a + b var y : int := a * b y > a + b a := a + 1 x := a + b
  • 25. Nodes - Usually innermost statements and expressions - Or blocks for consecutive statements (basic blocks) Edges - Back edges: show loops - Splits: conditionally split the control flow - Merges: combine previously split control flow Control Flow Graphs 25
  • 26. Equivalent to unstructured control-flow 26 a ← 0 L1: b ← a + 1 c ← c + b a ← 2 * b if a < N goto L1 return c a ← 0 b ← a + 1 c ← c + b a ← 2 * b a < N return c
  • 27. Representation - Represent control-flow of a program - Conduct and represent results of data-flow analysis Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 27
  • 28. Representation - - Conduct and represent results of data-flow analysis Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 28 Control Flow Graphs
  • 30. What is Data-Flow? - Possible values (data) that flow through the program - Relations between that data (data dependence) Discuss a series of example programs - What is wrong or can be optimised? - What is the flow we can use for this? Data-Flow 30
  • 31. Source Code Editor Parse Abstract Syntax Tree Other Check Check that code is reachable or observable Errors 31
  • 32. public int ComputeFac(int num) { return num; int num_aux; if (num < 1) num_aux = 1; else num_aux = num * this.ComputeFac(num-1); return num_aux; } What is wrong here? 32 - Most of the code is never reached because of the early return - This is usually considered an error by compilers Dead code (control-flow)
  • 33. x := 2; y := 4; x := 1; // x and y used later What is “wrong” here? 33 - The first value of x is never observed - This is sometimes warned about by compilers Dead code (data-flow) Live variable analysis
  • 34. Source Code Editor Parse Abstract Syntax Tree Optimise Eliminate common subexpressions, reduce loop strength, etc. Optimised Abstract Syntax Tree 34
  • 35. let var x : int := a + b var y : int := a * b in if y > a + b then ( a := a + 1; x := a + b ) end What is suboptimal here? 35 - a + b is already computed when you get to the condition - There is no need to compute it again Common subexpression elimination Available expression analysis
  • 36. What is suboptimal here? for i := 1 to 100 do ( x[i] := y[i]; if w > 0 then y[i] := 0 ) - The if condition is not dependent on i, x or y - Still it is checked in the loop, which is slowing the loop Loop unswitching 36 Data-dependence analysis
  • 38. Representation - - Conduct and represent results of data-flow analysis Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 38 Control Flow Graphs
  • 39. Representation - - Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 39 Control Flow Graphs Data-flow information on CFG nodes
  • 40. Representation - - Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 40 Control Flow Graphs Data-flow information on CFG nodes A domain-specific meta-language for Spoofax: FlowSpec
  • 41. Map abstract syntax to control-flow (sub)graphs - Match an AST pattern - List all edges of that AST - Use special “context” nodes to connect a subgraph to the outside graph Control-Flow rules
  • 42. x := 1; if y > x then z := y; else z := y * y; y := a * b; while y > a + b do (a := a + 1; x := a + b) Control-flow graphs in FlowSpec root Mod(s) = start -> s -> end start end While(c, b) = entry -> node c -> b -> node c, node c -> exit IfThenElse(c, t, e) = entry -> node c -> t -> exit, node c -> e -> exit Seq(s1, s2) = entry -> s1 -> s2 -> exit node Assign(_, _) FlowSpec Example program
  • 43. Data-Flow rules Define effect of control-flow nodes - Match an AST pattern on one side of a CFG edge - Propagate the information from the other side of the edge - Adapt that information as the effect of the matched CFG node
  • 44. {z,x} {z,x} {z,x} {z,x} {z} {} {} {} {} {} {x} {z} {} {} x := 2; y := 4; x := 1; z := x; x := z; {} {} {} {} {} {} {} Live Variables in FlowSpec properties live: MaySet(name) live(Assign(n, _) -> next) = { m | m <- live(next), n != m } live(Ref(n) -> next) = live(next) / {n} live(_.end) = {} A variable is live if the current value of the variable may be read further along in the program end start property rules
  • 45. x := 2; y := 4; x := 1; if y > 0 then z := x; else z := y * y; x := z; {x,y} {x} {y} {z} {} {} {z} {} {} {x} {y} {z} {} {}end start Live Variables in FlowSpec A variable is live if the current value of the variable may be read further along in the program properties live: MaySet(name) live(Assign(n, _) -> next) = { m | m <- live(next), n != m } live(Ref(n) -> next) = live(next) / {n} live(_.end) = {} property rules
  • 47. Control-Flow - Order of execution - Reasoning about what is reachable Data-Flow - Flow of data through a program - Reasoning about data, and dependencies between data FlowSpec - Control-Flow rules to construct the graph - Annotate with information from analysis by Data-Flow rules Summary 47
  • 48. Except where otherwise noted, this work is licensed under