From 10249be5b6b13adfeaea77418a4770f0c39485f5 Mon Sep 17 00:00:00 2001 From: Cliff Click Date: Fri, 27 Oct 2023 20:35:04 +0100 Subject: Chapter 5: If Statement, Phi, and Region MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Dibyendu Majumdar Co-authored-by: XmiliaH <45106915+XmiliaH@users.noreply.github.com> Co-authored-by: Yichen Yan Co-authored-by: Thalia Archibald Co-authored-by: Hsiang-Ying Fu <66062782+fuhsnn@users.noreply.github.com> Co-authored-by: Tamas Hadhazy Co-authored-by: Symious <14933944+symious@users.noreply.github.com> Co-authored-by: Claude Opus 5 Co-authored-by: tannal Co-authored-by: hadha Co-authored-by: Tamás Hadházy <85063808+Hels15@users.noreply.github.com> Co-authored-by: RobertObkircher Co-authored-by: David Rubin <87927264+Rexicon226@users.noreply.github.com> --- Makefile | 106 +---- README.md | 2 +- appendix/dce.md | 166 -------- docs/chapter05/05-grammar.md | 79 ++++ docs/chapter05/05-graph1.gv | 88 +++++ docs/chapter05/05-graph1.svg | 228 +++++++++++ docs/chapter05/05-graph2.gv | 78 ++++ docs/chapter05/05-graph2.svg | 229 +++++++++++ docs/chapter05/05-graph3.gv | 66 ++++ docs/chapter05/05-graph3.svg | 216 +++++++++++ docs/chapter05/05-graph4.gv | 63 +++ docs/chapter05/05-graph4.svg | 216 +++++++++++ docs/chapter05/05-graph5.gv | 60 +++ docs/chapter05/05-graph5.svg | 196 ++++++++++ docs/chapter05/05-graph6.gv | 58 +++ docs/chapter05/05-graph6.svg | 176 +++++++++ docs/chapter05/05-graph7.gv | 72 ++++ docs/chapter05/05-graph7.svg | 269 +++++++++++++ docs/chapter05/05-graph8.gv | 129 +++++++ docs/chapter05/05-graph8.svg | 430 +++++++++++++++++++++ docs/chapter05/05-graph9.svg | 174 +++++++++ docs/chapter05/Makefile | 12 + docs/chapter05/README.md | 384 ++++++++++++++++++ src/main/java/com/seaofnodes/simple/Parser.java | 109 +++++- .../java/com/seaofnodes/simple/node/AddNode.java | 27 +- .../java/com/seaofnodes/simple/node/BoolNode.java | 6 +- .../java/com/seaofnodes/simple/node/DivNode.java | 2 + .../java/com/seaofnodes/simple/node/IfNode.java | 36 ++ .../java/com/seaofnodes/simple/node/MulNode.java | 1 + src/main/java/com/seaofnodes/simple/node/Node.java | 16 +- .../java/com/seaofnodes/simple/node/PhiNode.java | 74 ++++ .../java/com/seaofnodes/simple/node/ProjNode.java | 2 +- .../com/seaofnodes/simple/node/RegionNode.java | 27 ++ .../java/com/seaofnodes/simple/node/ScopeNode.java | 41 ++ .../java/com/seaofnodes/simple/node/StopNode.java | 46 +++ .../java/com/seaofnodes/simple/node/SubNode.java | 1 + .../simple/print/SimpleGraphAdapter.java | 34 +- .../simple/print/SimpleGraphObserver.java | 12 +- src/main/java/com/seaofnodes/simple/type/Type.java | 2 +- .../java/com/seaofnodes/simple/type/TypeTuple.java | 4 +- .../java/com/seaofnodes/simple/Chapter01Test.java | 3 +- .../java/com/seaofnodes/simple/Chapter02Test.java | 14 +- .../java/com/seaofnodes/simple/Chapter03Test.java | 8 +- .../java/com/seaofnodes/simple/Chapter04Test.java | 43 ++- .../java/com/seaofnodes/simple/Chapter05Test.java | 210 ++++++++++ 45 files changed, 3870 insertions(+), 345 deletions(-) delete mode 100644 appendix/dce.md create mode 100644 docs/chapter05/05-grammar.md create mode 100644 docs/chapter05/05-graph1.gv create mode 100644 docs/chapter05/05-graph1.svg create mode 100644 docs/chapter05/05-graph2.gv create mode 100644 docs/chapter05/05-graph2.svg create mode 100644 docs/chapter05/05-graph3.gv create mode 100644 docs/chapter05/05-graph3.svg create mode 100644 docs/chapter05/05-graph4.gv create mode 100644 docs/chapter05/05-graph4.svg create mode 100644 docs/chapter05/05-graph5.gv create mode 100644 docs/chapter05/05-graph5.svg create mode 100644 docs/chapter05/05-graph6.gv create mode 100644 docs/chapter05/05-graph6.svg create mode 100644 docs/chapter05/05-graph7.gv create mode 100644 docs/chapter05/05-graph7.svg create mode 100644 docs/chapter05/05-graph8.gv create mode 100644 docs/chapter05/05-graph8.svg create mode 100644 docs/chapter05/05-graph9.svg create mode 100644 docs/chapter05/Makefile create mode 100644 docs/chapter05/README.md create mode 100644 src/main/java/com/seaofnodes/simple/node/IfNode.java create mode 100644 src/main/java/com/seaofnodes/simple/node/PhiNode.java create mode 100644 src/main/java/com/seaofnodes/simple/node/RegionNode.java create mode 100644 src/main/java/com/seaofnodes/simple/node/StopNode.java create mode 100644 src/test/java/com/seaofnodes/simple/Chapter05Test.java diff --git a/Makefile b/Makefile index 060e0cfd..67307a26 100644 --- a/Makefile +++ b/Makefile @@ -1,105 +1 @@ -SHELL := /bin/bash -# Shared packaging target; included after chapter source variables below. -.DELETE_ON_ERROR: - -# for printing variable values -# usage: make print-VARIABLE -# > VARIABLE = value_of_variable -print-% : ; @echo $* = $($*) - -# literal space -space := $() $() - -# Decide OS-specific questions -# jar-file seperator -ifeq ($(OS),Windows_NT) - SEP = ; -else - SEP = : -endif -# Find a reasonable ctags. -CTAGS = $(shell which ctags) -# Hack for MacOS: /usr/bin/ctags is unfriendly, so look for ctags from brew -ifeq ($(UNAME),Darwin) - CTAGS = $(shell brew list ctags 2> /dev/null | grep bin/ctags) -endif - -# Fun Args to javac. Mostly limit to java8 source definitions, and fairly -# aggressive lint warnings. -JAVAC_ARGS = -g - -# Source code -SIMPLE := com/seaofnodes/simple -SRC := src/main/java -TST := src/test/java -CLZDIR:= build/classes -main_javas := $(wildcard $(SRC)/$(SIMPLE)/*java $(SRC)/$(SIMPLE)/*/*java) -test_javas := $(wildcard $(TST)/$(SIMPLE)/*java $(TST)/$(SIMPLE)/*/*java) -main_classes := $(patsubst $(SRC)/%java,$(CLZDIR)/main/%class,$(main_javas)) -include $(firstword $(wildcard ../graph/graph.mk graph/graph.mk)) -test_classes := $(patsubst $(TST)/%java,$(CLZDIR)/test/%class,$(test_javas)) -test_cp := $(patsubst $(TST)/$(SIMPLE)/%.java,com.seaofnodes.simple.%,$(wildcard $(TST)/$(SIMPLE)/*Test.java)) -classes = $(main_classes) $(test_classes) -# All the libraries -libs = $(wildcard lib/*jar) -jars = $(subst $(space),$(SEP),$(libs)) - - -default_targets := $(main_classes) $(test_classes) -# Optionally add ctags to the default target if a reasonable one was found. -ifneq ($(CTAGS),) -default_targets += tags -endif - -default: $(default_targets) - -.PHONY: build -build: $(main_classes) - -# Compile just the out-of-date files -$(main_classes): $(CLZDIR)/main/%class: $(SRC)/%java $(graph_javas) - @echo "compiling " $@ " because " $? - @[ -d $(CLZDIR)/main ] || mkdir -p $(CLZDIR)/main - @javac $(JAVAC_ARGS) -cp "$(CLZDIR)/main$(SEP)$(jars)" -sourcepath $(SRC) -d $(CLZDIR)/main $(main_javas) - -$(test_classes): $(CLZDIR)/test/%class: $(TST)/%java $(main_classes) - @echo "compiling " $@ " because " $? - @[ -d $(CLZDIR)/test ] || mkdir -p $(CLZDIR)/test - @javac $(JAVAC_ARGS) -cp "$(CLZDIR)/test$(SEP)$(CLZDIR)/main$(SEP)$(jars)" -sourcepath $(TST) -d $(CLZDIR)/test $(test_javas) - -# Base launch line for JVM tests -JVM=nice java -ea -cp "build/classes/main${SEP}${jars}${SEP}$(CLZDIR)/test" - -tests: $(default_targets) - @echo "testing " $(test_cp) - @$(JVM) org.junit.runner.JUnitCore $(test_cp) - -fuzzer: $(default_targets) - @echo "fuzzing " $(test_cp) - @$(JVM) org.junit.runner.JUnitCore com.seaofnodes.simple.FuzzerWrap - - -.PHONY: clean -clean: - rm -rf build - rm -f TAGS - (find . -name "*~" -exec rm {} \; 2>/dev/null; exit 0) - -# Download libs from maven -lib: lib/junit-4.12.jar lib/hamcrest-core-1.3.jar - -# Jars -lib/junit-4.12.jar: - @[ -d lib ] || mkdir -p lib - @(cd lib; wget https://repo1.maven.org/maven2/junit/junit/4.12/junit-4.12.jar) - -lib/hamcrest-core-1.3.jar: - @[ -d lib ] || mkdir -p lib - @(cd lib; wget https://repo1.maven.org/maven2/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar) - -# Build emacs tags (part of a tasty emacs ide experience) -tags: $(main_javas) $(test_javas) - @rm -f TAGS - @$(CTAGS) -e --recurse=yes --extra=+q --fields=+fksaiS $(SRC) $(TST) - -include $(firstword $(wildcard ../build-support/chapter-release.mk build-support/chapter-release.mk)) +include $(firstword $(wildcard ../build-support/early-chapter.mk build-support/early-chapter.mk)) diff --git a/README.md b/README.md index c11da0ff..962ece1f 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ The Simple language is styled after a subset of C or Java. named `arg`. Binary and Comparison operators involving constants and `arg`. Non-zero values will be truthy. Peephole optimizations involving algebraic simplifications. -* Chapter 5: `if` statement. CFG construction. +* [Chapter 5](docs/chapter05/README.md): `if` statement. CFG construction. * Chapter 6: Peephole optimization around dead control flow. * Chapter 7: `while` statement; looping constructs - eager phi approach. * Chapter 8: Looping constructs continued, lazy phi creation, `break` and `continue` statements. diff --git a/appendix/dce.md b/appendix/dce.md deleted file mode 100644 index ad5be2d0..00000000 --- a/appendix/dce.md +++ /dev/null @@ -1,166 +0,0 @@ -# Appendix -## Dead Code Elimination(DCE) -Dead Code Elimination is the process or removing nodes that are dead(unused). - -There are two kinds of dead code eliminations present in this chapter. -- Delete unused nodes when popping the scope. -- Delete old nodes after finding a better replacement(after idealize call). - -Both of the methods mentioned above delete the nodes recursively. However, the first case happens -regardless of whether `peephole` is called or not. - -### Delete unused nodes when popping the scope -A node is unused if it has no outputs(users). - -### Example 1: - ``` - int a = 12; // the only output it has is the scope itself - return 1; - ``` -We clearly see `a` is unused. -This gives us the following graph(without DCE): - -![Graph2](../docs/04-dce1.svg) - -To remove `a` we introduce the following technique when popping the scope. - - ```java - var ret = (ReturnNode) parseBlock(); - _scope.pop(); - ``` -As of now the end of the program is hard-wired to return, after finishing parsing we pop the scope. -The state of the scope before popping it: - ``` - _scope = {ScopeNode@1422} "Scope[$ctrl:null, arg:arg][a:12]" - 1 = {ProjNode@1528} "arg" - 2 = {ConstantNode@1529} "12" - _inputs = {ArrayList@1523} size = 3 - ``` -The output(s) of `a` - ``` - _outputs = {ArrayList@1544} size = 1 - 0 = {ScopeNode@1422} "Scope[$ctrl:null, arg:arg][a:12]" - ``` -Notice how the only output of `a`is the scope itself. When `a` is introduced, it is added to the -inputs of the scope, and the scope is added to the outputs of `a`(recall use-def chains). - -Since `a` is not being returned - it is unused and can be killed. - -`_scope.pop`: -```java -public void pop() { popN(_scopes.pop().size()); } -``` -`_scope.popN`(responsible for killing the unused nodes *recursively*): -```java -void popN(int n) { - for (int i = 0; i < n; i++) { - Node old_def = _inputs.removeLast(); // start from the back - if (old_def != null && // If it exists and - old_def.delUse(this)) { // If we removed the last use, the old def is now dead - old_def.kill(); // Kill the old def - } - } -} -``` -First, we start off by looping through the inputs of the scope(*remember*: scope is just a node like any other, the symbols of the scope are the inputs). -If the node returned by `removeLast` is not null, and if the only user of `old_def` is the current Node then we can delete it. - -`old_def.delUse(this)` - delete *this* from `old_def`'s outputs. -```java -protected boolean delUse( Node use ) { - Utils.del(_outputs, Utils.find(_outputs, use)); - return _outputs.isEmpty(); - } -``` -Returns true if `_outputs` becomes empty after deleting `use`. -`old_def.kill()` starts the killing process recursively. - -`old_def.kill()` -```java -public void kill( ) { - assert isUnused(); // Has no uses, so it is dead - popN(nIns()); // Set all inputs to null, recursively killing unused Nodes - _type=null; // Flag as dead - assert isDead(); // Really dead now - } -``` -`popN` is called again, our goal is to look for nodes that might also get deleted once `a` is freed. -The only input `a` has is the constant node with value 12. As every other node a `ConstantNode` takes in the control node first(`Start`), once we -drop the `Start` node from the inputs of `ConstantNode`: -``` -Node old_def = _inputs.removeLast(); -``` -we can also get rid of `ConstantNode`(`this`) from the outputs of `Start`: -``` -old_def.delUse(this) -``` -### Example 2: -``` -int a = 12; -int b = a + 1; -return 1; -``` -- Call `popN` on current scope. -- Realize that `b = a + 1;` has no uses - so we can kill it. -- In the kill function we can call `popN` but this time with the inputs of `b = a + 1;`(start killing them recursively) -- We start the killing process from the back and examine "1" first. This has no output other than the `AddNode`. Since `this = AddNode` calling `delUse` will mark "1" as dead. -- We now can kill "1" and call the `popN` function with one input(the control node). -- Now we examine "a" which has 2 uses at this point, the scope and `AddNode`. Since `this = AddNode` we will remove `AddNode` from its outputs, it will still have the scope as a user - so we can't delete it just yet. -- We move onto`a = 12`, since "a" has only one user left(the scope) and `this = scope` it can get killed easily. -- Same as before, we go through the inputs of "a" and will delete them from the outputs of the control node. - -*A constant node pointing to "Start"(ignored by the graph visualizer) but still maintains a connection:* - -![Graph3](../docs/04-dce2.svg) - -## Delete old nodes after finding a better replacement -Consider the following code: -``` -return (2+1)+3; -``` -Without DCE after the `idealize` call we would end up with: -![Graph3](../docs/04-dce3.svg) - -After identifying a more optimal replacement value (6) for the expression (2 + 1) + 3, -we created a constant node to store this value. -However, we did not remove the original expression, -resulting in dangling nodes in our structure. - -To fix this, we introduce an extra `deadCodeElim` call that is responsible for deleting unused nodes. - - -```java -public final Node peephole( ) { - ... - if (!(this instanceof ConstantNode) && type.isConstant()) - return new deadCodeElim(ConstantNode(type).peephole()); - - ... - - Node n = idealize(); - if( n != null ) // Something changed - // Recursively optimize - return deadCodeElim(n.peephole()); - - ... -} -``` - -```java -// m is the new Node, self is the old. -// Return 'm', which may have zero uses but is alive nonetheless. -// If self has zero uses (and is not 'm'), {@link #kill} self. -private Node deadCodeElim(Node m) { - // If self is going dead and not being returned here (Nodes returned - // from peephole commonly have no uses (yet)), then kill self. - if( m != this && isUnused() ) { - // Killing self - and since self recursively kills self's inputs we - // might end up killing 'm', which we are returning as a live Node. - // So we add a bogus extra null output edge to stop kill(). - m.addUse(null); // Add bogus null use to keep m alive - kill(); // Kill self because replacing with 'm' - m.delUse(null); // Remove bogus null. - } - return m; -} -``` \ No newline at end of file diff --git a/docs/chapter05/05-grammar.md b/docs/chapter05/05-grammar.md new file mode 100644 index 00000000..8eba1581 --- /dev/null +++ b/docs/chapter05/05-grammar.md @@ -0,0 +1,79 @@ +# Grammar for Chapter 1 + +```antlrv4 +grammar SimpleLanguage; + +program + : statement+ EOF + ; + +statement + : returnStatement + | declStatement + | blockStatment + | expressionStatement + | ifStatement + ; + +ifStatement + : 'if' '(' expression ')' statement ('else' statement)? + ; + + +expressionStatement + : IDENTIFIER '=' expression ';' + ; + +blockStatement + : '{' statement+ '}' + ; + +declStatement + : 'int' IDENTIFIER '=' expression ';' + ; + +returnStatement + : 'return' expression ';' + ; + +expression + : comparisonExpression + ; + +comparisonExpression + : additiveExpression (('==' | '!='| '>'| '<'| '>='| '<=') additiveExpression)* + ; + +additiveExpression + : multiplicativeExpression (('+' | '-') multiplicativeExpression)* + ; + +multiplicativeExpression + : unaryExpression (('*' | '/') unaryExpression)* + ; + +unaryExpression + : ('-') unaryExpression + | primaryExpression + ; + +primaryExpression + : IDENTIFIER + | INTEGER_LITERAL + | 'true' + | 'false' + | '(' expression ')' + ; + +INTEGER_LITERAL + : [1-9][0-9]* + | [0] + ; + +IDENTIFIER + : NON_DIGIT (NON_DIGIT | DIGIT)* + ; + +NON_DIGIT: [a-zA-Z_]; +DEC_DIGIT: [0-9]; +``` diff --git a/docs/chapter05/05-graph1.gv b/docs/chapter05/05-graph1.gv new file mode 100644 index 00000000..b5cf8370 --- /dev/null +++ b/docs/chapter05/05-graph1.gv @@ -0,0 +1,88 @@ +digraph chapter05 { +/* +int a = 1; +if (arg == 1) + a = arg+2; +else { + a = arg-3; + +} + +return a; + +*/ + rankdir=BT; + ordering="in"; + concentrate="true"; + subgraph cluster_Nodes { + Start2 [ shape=plaintext label=< + + + +
Start
+ + +
$ctrlarg
+
> + ]; + Con_7 [ label="#1" ]; + EQNode8 [ label="==" ]; + If9 [ shape=plaintext label=< + + + +
If
+ + +
TrueFalse
+
> + ]; + Con_13 [ label="#2" ]; + Add14 [ label="+" ]; + Con_15 [ label="#3" ]; + Sub16 [ label="-" ]; + } + node [shape=plaintext]; + subgraph cluster_Scope1_0 { + Scope1_0 [label=< + + +
0$ctrlarg
>]; + subgraph cluster_Scope1_1 { + Scope1_1 [label=< + + +
1a
>]; + } + } + node [shape=plaintext]; + subgraph cluster_Scope12_0 { + Scope12_0 [label=< + + +
0$ctrlarg
>]; + subgraph cluster_Scope12_1 { + Scope12_1 [label=< + + +
1a
>]; + } + } + edge [ fontname=Helvetica, fontsize=8 ]; + EQNode8 -> Start2:p1[taillabel=1]; + EQNode8 -> Con_7[taillabel=2]; + If9 -> Start2:p0[taillabel=0; color=red]; + If9 -> EQNode8[taillabel=1]; + Add14 -> Start2:p1[taillabel=1]; + Add14 -> Con_13[taillabel=2]; + Sub16 -> Start2:p1[taillabel=1]; + Sub16 -> Con_15[taillabel=2]; + edge [style=dashed color=cornflowerblue]; + Scope1_0:"Scope1_0_$ctrl" -> If9:p0; + Scope1_0:"Scope1_0_arg" -> Start2:p1; + Scope1_1:"Scope1_1_a" -> Add14; + edge [style=dashed color=cornflowerblue]; + Scope12_0:"Scope12_0_$ctrl" -> If9:p1; + Scope12_0:"Scope12_0_arg" -> Start2:p1; + Scope12_1:"Scope12_1_a" -> Sub16; +} diff --git a/docs/chapter05/05-graph1.svg b/docs/chapter05/05-graph1.svg new file mode 100644 index 00000000..efe0a0e8 --- /dev/null +++ b/docs/chapter05/05-graph1.svg @@ -0,0 +1,228 @@ + + + + + + +chapter05 + + +cluster_Nodes + + + +cluster_Scope1_0 + + + +cluster_Scope1_1 + + + +cluster_Scope12_0 + + + +cluster_Scope12_1 + + + + +Start2 + + +Start + + + +$ctrl + +arg + + + +Con_7 + +#1 + + + +EQNode8 + +== + + + +EQNode8->Start2:p1 + + +1 + + + +EQNode8->Con_7 + + +2 + + + +If9 + + +If + + + +True + + +False + + + +If9->Start2:p0 + + +0 + + + +If9->EQNode8 + + +1 + + + +Con_13 + +#2 + + + +Add14 + ++ + + + +Add14->Start2:p1 + + +1 + + + +Add14->Con_13 + + +2 + + + +Con_15 + +#3 + + + +Sub16 + +- + + + +Sub16->Start2:p1 + + +1 + + + +Sub16->Con_15 + + +2 + + + +Scope1_0 + + +0 + +$ctrl + +arg + + + +Scope1_0:Scope1_0_arg->Start2:p1 + + + + + +Scope1_0:Scope1_0_$ctrl->If9:p0 + + + + + +Scope1_1 + + +1 + +a + + + +Scope1_1:Scope1_1_a->Add14 + + + + + +Scope12_0 + + +0 + +$ctrl + +arg + + + +Scope12_0:Scope12_0_arg->Start2:p1 + + + + + +Scope12_0:Scope12_0_$ctrl->If9:p1 + + + + + +Scope12_1 + + +1 + +a + + + +Scope12_1:Scope12_1_a->Sub16 + + + + + diff --git a/docs/chapter05/05-graph2.gv b/docs/chapter05/05-graph2.gv new file mode 100644 index 00000000..a560bc49 --- /dev/null +++ b/docs/chapter05/05-graph2.gv @@ -0,0 +1,78 @@ +digraph chapter05 { +/* +int a = 1; +if (arg == 1) + a = arg+2; +else { + a = arg-3; + +} + +return a; +*/ + rankdir=BT; + ordering="in"; + concentrate="true"; + subgraph cluster_Nodes { + Start2 [ shape=plaintext label=< + + + +
Start
+ + +
$ctrlarg
+
> + ]; + Con_7 [ label="#1" ]; + EQNode8 [ label="==" ]; + If9 [ shape=plaintext label=< + + + +
If
+ + +
TrueFalse
+
> + ]; + Con_13 [ label="#2" ]; + Add14 [ label="+" ]; + Con_15 [ label="#3" ]; + Sub16 [ label="-" ]; + Region17 [ shape=box style=filled fillcolor=yellow label="Region" ]; + Phi_a18 [ style=filled fillcolor=lightyellow label="φ_a" ]; + { rank=same; Region17;Phi_a18;} + } + node [shape=plaintext]; + subgraph cluster_Scope1_0 { + Scope1_0 [label=< + + +
0$ctrlarg
>]; + subgraph cluster_Scope1_1 { + Scope1_1 [label=< + + +
1a
>]; + } + } + edge [ fontname=Helvetica, fontsize=8 ]; + EQNode8 -> Start2:p1[taillabel=1]; + EQNode8 -> Con_7[taillabel=2]; + If9 -> Start2:p0[taillabel=0 color=red]; + If9 -> EQNode8[taillabel=1]; + Add14 -> Start2:p1[taillabel=1]; + Add14 -> Con_13[taillabel=2]; + Sub16 -> Start2:p1[taillabel=1]; + Sub16 -> Con_15[taillabel=2]; + Region17 -> If9:p0[taillabel=1 color=red]; + Region17 -> If9:p1[taillabel=2 color=red]; + Phi_a18 -> Region17 [style=dotted taillabel=0]; + Phi_a18 -> Add14[taillabel=1]; + Phi_a18 -> Sub16[taillabel=2]; + edge [style=dashed color=cornflowerblue]; + Scope1_0:"Scope1_0_$ctrl" -> Region17; + Scope1_0:"Scope1_0_arg" -> Start2:p1; + Scope1_1:"Scope1_1_a" -> Phi_a18; +} diff --git a/docs/chapter05/05-graph2.svg b/docs/chapter05/05-graph2.svg new file mode 100644 index 00000000..d5e48a9e --- /dev/null +++ b/docs/chapter05/05-graph2.svg @@ -0,0 +1,229 @@ + + + + + + +chapter05 + + +cluster_Nodes + + + +cluster_Scope1_0 + + + +cluster_Scope1_1 + + + + +Start2 + + +Start + + + +$ctrl + +arg + + + +Con_7 + +#1 + + + +EQNode8 + +== + + + +EQNode8->Start2:p1 + + +1 + + + +EQNode8->Con_7 + + +2 + + + +If9 + + +If + + + +True + + +False + + + +If9->Start2:p0 + + +0 + + + +If9->EQNode8 + + +1 + + + +Con_13 + +#2 + + + +Add14 + ++ + + + +Add14->Start2:p1 + + +1 + + + +Add14->Con_13 + + +2 + + + +Con_15 + +#3 + + + +Sub16 + +- + + + +Sub16->Start2:p1 + + +1 + + + +Sub16->Con_15 + + +2 + + + +Region17 + +Region + + + +Region17->If9:p0 + + +1 + + + +Region17->If9:p1 + + +2 + + + +Phi_a18 + +φ_a + + + +Phi_a18->Add14 + + +1 + + + +Phi_a18->Sub16 + + +2 + + + +Phi_a18->Region17 + + +0 + + + +Scope1_0 + + +0 + +$ctrl + +arg + + + +Scope1_0:Scope1_0_arg->Start2:p1 + + + + + +Scope1_0:Scope1_0_$ctrl->Region17 + + + + + +Scope1_1 + + +1 + +a + + + +Scope1_1:Scope1_1_a->Phi_a18 + + + + + diff --git a/docs/chapter05/05-graph3.gv b/docs/chapter05/05-graph3.gv new file mode 100644 index 00000000..688c5ca9 --- /dev/null +++ b/docs/chapter05/05-graph3.gv @@ -0,0 +1,66 @@ +digraph chapter05 { +/* +int a = 1; +if (arg == 1) + a = arg+2; +else { + a = arg-3; + +} + +return a; +*/ + rankdir=BT; + ordering="in"; + concentrate="true"; + subgraph cluster_Nodes { + Start2 [ shape=plaintext label=< + + + +
Start
+ + +
$ctrlarg
+
> + ]; + Stop3 [ shape=box style=filled fillcolor=yellow label="Stop" ]; + Con_7 [ label="#1" ]; + EQNode8 [ label="==" ]; + If9 [ shape=plaintext label=< + + + +
If
+ + +
TrueFalse
+
> + ]; + Con_13 [ label="#2" ]; + Add14 [ label="+" ]; + Con_15 [ label="#3" ]; + Sub16 [ label="-" ]; + Region17 [ shape=box style=filled fillcolor=yellow label="Region" ]; + Phi_a18 [ style=filled fillcolor=lightyellow label="φ_a" ]; + Return19 [ shape=box style=filled fillcolor=yellow label="Return" ]; + { rank=same; Region17;Phi_a18;} + } + edge [ fontname=Helvetica, fontsize=8 ]; + Stop3 -> Return19[taillabel=0 color=red]; + EQNode8 -> Start2:p1[taillabel=1]; + EQNode8 -> Con_7[taillabel=2]; + If9 -> Start2:p0[taillabel=0 color=red]; + If9 -> EQNode8[taillabel=1]; + Add14 -> Start2:p1[taillabel=1]; + Add14 -> Con_13[taillabel=2]; + Sub16 -> Start2:p1[taillabel=1]; + Sub16 -> Con_15[taillabel=2]; + Region17 -> If9:p0[taillabel=1 color=red]; + Region17 -> If9:p1[taillabel=2 color=red]; + Phi_a18 -> Region17 [style=dotted taillabel=0]; + Phi_a18 -> Add14[taillabel=1]; + Phi_a18 -> Sub16[taillabel=2]; + Return19 -> Region17[taillabel=0 color=red]; + Return19 -> Phi_a18[taillabel=1]; +} diff --git a/docs/chapter05/05-graph3.svg b/docs/chapter05/05-graph3.svg new file mode 100644 index 00000000..855fdc2c --- /dev/null +++ b/docs/chapter05/05-graph3.svg @@ -0,0 +1,216 @@ + + + + + + +chapter05 + + +cluster_Nodes + + + + +Start2 + + +Start + + + +$ctrl + +arg + + + +Stop3 + +Stop + + + +Return19 + +Return + + + +Stop3->Return19 + + +0 + + + +Con_7 + +#1 + + + +EQNode8 + +== + + + +EQNode8->Start2:p1 + + +1 + + + +EQNode8->Con_7 + + +2 + + + +If9 + + +If + + + +True + + +False + + + +If9->Start2:p0 + + +0 + + + +If9->EQNode8 + + +1 + + + +Con_13 + +#2 + + + +Add14 + ++ + + + +Add14->Start2:p1 + + +1 + + + +Add14->Con_13 + + +2 + + + +Con_15 + +#3 + + + +Sub16 + +- + + + +Sub16->Start2:p1 + + +1 + + + +Sub16->Con_15 + + +2 + + + +Region17 + +Region + + + +Region17->If9:p0 + + +1 + + + +Region17->If9:p1 + + +2 + + + +Phi_a18 + +φ_a + + + +Phi_a18->Add14 + + +1 + + + +Phi_a18->Sub16 + + +2 + + + +Phi_a18->Region17 + + +0 + + + +Return19->Region17 + + +0 + + + +Return19->Phi_a18 + + +1 + + + diff --git a/docs/chapter05/05-graph4.gv b/docs/chapter05/05-graph4.gv new file mode 100644 index 00000000..88120b4a --- /dev/null +++ b/docs/chapter05/05-graph4.gv @@ -0,0 +1,63 @@ +digraph chapter05 { +/* +int a=arg==2; +if( arg==1 ) +{ + a=arg==3; +} +return a; +*/ + rankdir=BT; + ordering="in"; + concentrate="true"; + subgraph cluster_Nodes { + Start2 [ shape=plaintext label=< + + + +
Start
+ + +
$ctrlarg
+
> + ]; + Stop3 [ shape=box style=filled fillcolor=yellow label="Stop" ]; + Con_6 [ label="#2" ]; + EQNode7 [ label="==" ]; + Con_8 [ label="#1" ]; + EQNode9 [ label="==" ]; + If10 [ shape=plaintext label=< + + + +
If
+ + +
TrueFalse
+
> + ]; + Con_14 [ label="#3" ]; + EQNode15 [ label="==" ]; + Region16 [ shape=box style=filled fillcolor=yellow label="Region" ]; + Phi_a17 [ style=filled fillcolor=lightyellow label="φ_a" ]; + Return18 [ shape=box style=filled fillcolor=yellow label="Return" ]; + { rank=same; Region16;Phi_a17;} + } + edge [ fontname=Helvetica, fontsize=8 ]; + Stop3 -> Return18[taillabel=0 color=red]; + EQNode7 -> Start2:p1[taillabel=1]; + EQNode7 -> Con_6[taillabel=2]; + EQNode9 -> Start2:p1[taillabel=1]; + EQNode9 -> Con_8[taillabel=2]; + If10 -> Start2:p0[taillabel=0 color=red]; + If10 -> EQNode9[taillabel=1]; + EQNode15 -> Start2:p1[taillabel=1]; + EQNode15 -> Con_14[taillabel=2]; + Region16 -> If10:p0[taillabel=1 color=red]; + Region16 -> If10:p1[taillabel=2 color=red]; + Phi_a17 -> Region16 [style=dotted taillabel=0]; + Phi_a17 -> EQNode15[taillabel=1]; + Phi_a17 -> EQNode7[taillabel=2]; + Return18 -> Region16[taillabel=0 color=red]; + Return18 -> Phi_a17[taillabel=1]; +} diff --git a/docs/chapter05/05-graph4.svg b/docs/chapter05/05-graph4.svg new file mode 100644 index 00000000..3fcee500 --- /dev/null +++ b/docs/chapter05/05-graph4.svg @@ -0,0 +1,216 @@ + + + + + + +chapter05 + + +cluster_Nodes + + + + +Start2 + + +Start + + + +$ctrl + +arg + + + +Stop3 + +Stop + + + +Return18 + +Return + + + +Stop3->Return18 + + +0 + + + +Con_6 + +#2 + + + +EQNode7 + +== + + + +EQNode7->Start2:p1 + + +1 + + + +EQNode7->Con_6 + + +2 + + + +Con_8 + +#1 + + + +EQNode9 + +== + + + +EQNode9->Start2:p1 + + +1 + + + +EQNode9->Con_8 + + +2 + + + +If10 + + +If + + + +True + + +False + + + +If10->Start2:p0 + + +0 + + + +If10->EQNode9 + + +1 + + + +Con_14 + +#3 + + + +EQNode15 + +== + + + +EQNode15->Start2:p1 + + +1 + + + +EQNode15->Con_14 + + +2 + + + +Region16 + +Region + + + +Region16->If10:p0 + + +1 + + + +Region16->If10:p1 + + +2 + + + +Phi_a17 + +φ_a + + + +Phi_a17->EQNode7 + + +2 + + + +Phi_a17->EQNode15 + + +1 + + + +Phi_a17->Region16 + + +0 + + + +Return18->Region16 + + +0 + + + +Return18->Phi_a17 + + +1 + + + diff --git a/docs/chapter05/05-graph5.gv b/docs/chapter05/05-graph5.gv new file mode 100644 index 00000000..b03e90b5 --- /dev/null +++ b/docs/chapter05/05-graph5.gv @@ -0,0 +1,60 @@ +digraph chapter05 { +/* +int a=arg==2; +if( arg==1 ) +{ + a=arg==3; +} +return a; +*/ + rankdir=BT; + ordering="in"; + concentrate="true"; + subgraph cluster_Nodes { + Start2 [ shape=plaintext label=< + + + +
Start
+ + +
$ctrlarg
+
> + ]; + Stop3 [ shape=box style=filled fillcolor=yellow label="Stop" ]; + Con_6 [ label="#2" ]; + Con_8 [ label="#1" ]; + EQNode9 [ label="==" ]; + If10 [ shape=plaintext label=< + + + +
If
+ + +
TrueFalse
+
> + ]; + Con_14 [ label="#3" ]; + Region16 [ shape=box style=filled fillcolor=yellow label="Region" ]; + Phi_a19 [ style=filled fillcolor=lightyellow label="φ_a" ]; + EQNode20 [ label="==" ]; + Return21 [ shape=box style=filled fillcolor=yellow label="Return" ]; + { rank=same; Region16;Phi_a19;} + } + edge [ fontname=Helvetica, fontsize=8 ]; + Stop3 -> Return21[taillabel=0 color=red]; + EQNode9 -> Start2:p1[taillabel=1]; + EQNode9 -> Con_8[taillabel=2]; + If10 -> Start2:p0[taillabel=0 color=red]; + If10 -> EQNode9[taillabel=1]; + Region16 -> If10:p0[taillabel=1 color=red]; + Region16 -> If10:p1[taillabel=2 color=red]; + Phi_a19 -> Region16 [style=dotted taillabel=0]; + Phi_a19 -> Con_14[taillabel=1]; + Phi_a19 -> Con_6[taillabel=2]; + EQNode20 -> Start2:p1[taillabel=1]; + EQNode20 -> Phi_a19[taillabel=2]; + Return21 -> Region16[taillabel=0 color=red]; + Return21 -> EQNode20[taillabel=1]; +} diff --git a/docs/chapter05/05-graph5.svg b/docs/chapter05/05-graph5.svg new file mode 100644 index 00000000..4f6fa4bd --- /dev/null +++ b/docs/chapter05/05-graph5.svg @@ -0,0 +1,196 @@ + + + + + + +chapter05 + + +cluster_Nodes + + + + +Start2 + + +Start + + + +$ctrl + +arg + + + +Stop3 + +Stop + + + +Return21 + +Return + + + +Stop3->Return21 + + +0 + + + +Con_6 + +#2 + + + +Con_8 + +#1 + + + +EQNode9 + +== + + + +EQNode9->Start2:p1 + + +1 + + + +EQNode9->Con_8 + + +2 + + + +If10 + + +If + + + +True + + +False + + + +If10->Start2:p0 + + +0 + + + +If10->EQNode9 + + +1 + + + +Con_14 + +#3 + + + +Region16 + +Region + + + +Region16->If10:p0 + + +1 + + + +Region16->If10:p1 + + +2 + + + +Phi_a19 + +φ_a + + + +Phi_a19->Con_6 + + +2 + + + +Phi_a19->Con_14 + + +1 + + + +Phi_a19->Region16 + + +0 + + + +EQNode20 + +== + + + +EQNode20->Start2:p1 + + +1 + + + +EQNode20->Phi_a19 + + +2 + + + +Return21->Region16 + + +0 + + + +Return21->EQNode20 + + +1 + + + diff --git a/docs/chapter05/05-graph6.gv b/docs/chapter05/05-graph6.gv new file mode 100644 index 00000000..1ad7b94a --- /dev/null +++ b/docs/chapter05/05-graph6.gv @@ -0,0 +1,58 @@ +digraph chapter05 { +/* +int c = 3; +int b = 2; +if (arg == 1) { + b = 3; + c = 4; +} +return c; +*/ + rankdir=BT; + ordering="in"; + concentrate="true"; + subgraph cluster_Nodes { + Start2 [ shape=plaintext label=< + + + +
Start
+ + +
$ctrlarg
+
> + ]; + Stop3 [ shape=box style=filled fillcolor=yellow label="Stop" ]; + Con_6 [ label="#3" ]; + Con_8 [ label="#1" ]; + EQNode9 [ label="==" ]; + If10 [ shape=plaintext label=< + + + +
If
+ + +
TrueFalse
+
> + ]; + Con_15 [ label="#4" ]; + Region16 [ shape=box style=filled fillcolor=yellow label="Region" ]; + Phi_c17 [ style=filled fillcolor=lightyellow label="φ_c" ]; + Return19 [ shape=box style=filled fillcolor=yellow label="Return" ]; + { rank=same; Region16;Phi_c17;} + } + edge [ fontname=Helvetica, fontsize=8 ]; + Stop3 -> Return19[taillabel=0 color=red]; + EQNode9 -> Start2:p1[taillabel=1]; + EQNode9 -> Con_8[taillabel=2]; + If10 -> Start2:p0[taillabel=0 color=red]; + If10 -> EQNode9[taillabel=1]; + Region16 -> If10:p0[taillabel=1 color=red]; + Region16 -> If10:p1[taillabel=2 color=red]; + Phi_c17 -> Region16 [style=dotted taillabel=0]; + Phi_c17 -> Con_15[taillabel=1]; + Phi_c17 -> Con_6[taillabel=2]; + Return19 -> Region16[taillabel=0 color=red]; + Return19 -> Phi_c17[taillabel=1]; +} diff --git a/docs/chapter05/05-graph6.svg b/docs/chapter05/05-graph6.svg new file mode 100644 index 00000000..71527d7f --- /dev/null +++ b/docs/chapter05/05-graph6.svg @@ -0,0 +1,176 @@ + + + + + + +chapter05 + + +cluster_Nodes + + + + +Start2 + + +Start + + + +$ctrl + +arg + + + +Stop3 + +Stop + + + +Return19 + +Return + + + +Stop3->Return19 + + +0 + + + +Con_6 + +#3 + + + +Con_8 + +#1 + + + +EQNode9 + +== + + + +EQNode9->Start2:p1 + + +1 + + + +EQNode9->Con_8 + + +2 + + + +If10 + + +If + + + +True + + +False + + + +If10->Start2:p0 + + +0 + + + +If10->EQNode9 + + +1 + + + +Con_15 + +#4 + + + +Region16 + +Region + + + +Region16->If10:p0 + + +1 + + + +Region16->If10:p1 + + +2 + + + +Phi_c17 + +φ_c + + + +Phi_c17->Con_6 + + +2 + + + +Phi_c17->Con_15 + + +1 + + + +Phi_c17->Region16 + + +0 + + + +Return19->Region16 + + +0 + + + +Return19->Phi_c17 + + +1 + + + diff --git a/docs/chapter05/05-graph7.gv b/docs/chapter05/05-graph7.gv new file mode 100644 index 00000000..3abd6455 --- /dev/null +++ b/docs/chapter05/05-graph7.gv @@ -0,0 +1,72 @@ +digraph chapter05 { +/* +int a=arg+1; +int b=arg+2; +if( arg==1 ) + b=b+a; +else + a=b+1; +return a+b; +*/ + rankdir=BT; + ordering="in"; + concentrate="true"; + subgraph cluster_Nodes { + Start2 [ shape=plaintext label=< + + + +
Start
+ + +
$ctrlarg
+
> + ]; + Stop3 [ shape=box style=filled fillcolor=yellow label="Stop" ]; + Phi_b37 [ style=filled fillcolor=lightyellow label="φ_b" ]; + Con_10 [ label="#1" ]; + Add42 [ label="+" ]; + EQNode11 [ label="==" ]; + If12 [ shape=plaintext label=< + + + +
If
+ + +
TrueFalse
+
> + ]; + Con_46 [ label="#4" ]; + Con_48 [ label="#5" ]; + Phi_ab49 [ style=filled fillcolor=lightyellow label="φ_ab" ]; + Add50 [ label="+" ]; + Con_19 [ label="#2" ]; + Return51 [ shape=box style=filled fillcolor=yellow label="Return" ]; + Mul20 [ label="*" ]; + Region31 [ shape=box style=filled fillcolor=yellow label="Region" ]; + { rank=same; Region31;Phi_b37;Phi_ab49;} + } + edge [ fontname=Helvetica, fontsize=8 ]; + Stop3 -> Return51[taillabel=0 color=red]; + Phi_b37 -> Region31 [style=dotted taillabel=0]; + Phi_b37 -> Mul20[taillabel=1]; + Phi_b37 -> Start2:p1[taillabel=2]; + Add42 -> Phi_b37[taillabel=1]; + Add42 -> Start2:p1[taillabel=2]; + EQNode11 -> Start2:p1[taillabel=1]; + EQNode11 -> Con_10[taillabel=2]; + If12 -> Start2:p0[taillabel=0 color=red]; + If12 -> EQNode11[taillabel=1]; + Phi_ab49 -> Region31 [style=dotted taillabel=0]; + Phi_ab49 -> Con_46[taillabel=1]; + Phi_ab49 -> Con_48[taillabel=2]; + Add50 -> Add42[taillabel=1]; + Add50 -> Phi_ab49[taillabel=2]; + Return51 -> Region31[taillabel=0 color=red]; + Return51 -> Add50[taillabel=1]; + Mul20 -> Start2:p1[taillabel=1]; + Mul20 -> Con_19[taillabel=2]; + Region31 -> If12:p0[taillabel=1 color=red]; + Region31 -> If12:p1[taillabel=2 color=red]; +} diff --git a/docs/chapter05/05-graph7.svg b/docs/chapter05/05-graph7.svg new file mode 100644 index 00000000..8ba5ebd6 --- /dev/null +++ b/docs/chapter05/05-graph7.svg @@ -0,0 +1,269 @@ + + + + + + +chapter05 + + +cluster_Nodes + + + + +Start2 + + +Start + + + +$ctrl + +arg + + + +Stop3 + +Stop + + + +Return51 + +Return + + + +Stop3->Return51 + + +0 + + + +Phi_b37 + +φ_b + + + +Phi_b37->Start2:p1 + +2 + + + +Mul20 + +* + + + +Phi_b37->Mul20 + + +1 + + + +Region31 + +Region + + + +Phi_b37->Region31 + + +0 + + + +Con_10 + +#1 + + + +Add42 + ++ + + + +Add42->Start2:p1 + + + + +2 + + + +Add42->Phi_b37 + + +1 + + + +EQNode11 + +== + + + +EQNode11->Start2:p1 + + +1 + + + +EQNode11->Con_10 + + +2 + + + +If12 + + +If + + + +True + + +False + + + +If12->Start2:p0 + + +0 + + + +If12->EQNode11 + + +1 + + + +Con_46 + +#4 + + + +Con_48 + +#5 + + + +Phi_ab49 + +φ_ab + + + +Phi_ab49->Con_46 + + +1 + + + +Phi_ab49->Con_48 + + +2 + + + +Phi_ab49->Region31 + + +0 + + + +Add50 + ++ + + + +Add50->Add42 + + +1 + + + +Add50->Phi_ab49 + + +2 + + + +Con_19 + +#2 + + + +Return51->Add50 + + +1 + + + +Return51->Region31 + + +0 + + + +Mul20->Start2:p1 + +1 + + + +Mul20->Con_19 + + +2 + + + +Region31->If12:p0 + + +1 + + + +Region31->If12:p1 + + +2 + + + diff --git a/docs/chapter05/05-graph8.gv b/docs/chapter05/05-graph8.gv new file mode 100644 index 00000000..8f28207c --- /dev/null +++ b/docs/chapter05/05-graph8.gv @@ -0,0 +1,129 @@ +digraph chapter05 { +/* +int a=1; +if( arg==1 ) + if( arg==2 ) + a=2; + else + a=3; +else if( arg==3 ) + a=4; +else + a=5; +return a; + +*/ + rankdir=BT; + ordering="in"; + concentrate="true"; + subgraph cluster_Nodes { + Start2 [ shape=plaintext label=< + + + +
Start
+ + +
$ctrlarg
+
> + ]; + Stop3 [ shape=box style=filled fillcolor=yellow label="Stop" ]; + Con_7 [ label="#1" ]; + EQNode8 [ label="==" ]; + If9 [ shape=plaintext label=< + + + +
If
+ + +
TrueFalse
+
> + ]; + Con_13 [ label="#2" ]; + EQNode14 [ label="==" ]; + If15 [ shape=plaintext label=< + + + +
If
+ + +
TrueFalse
+
> + ]; + Con_19 [ label="#2" ]; + Con_20 [ label="#3" ]; + Region21 [ shape=box style=filled fillcolor=yellow label="Region" ]; + Phi_a22 [ style=filled fillcolor=lightyellow label="φ_a" ]; + Con_23 [ label="#3" ]; + EQNode24 [ label="==" ]; + If25 [ shape=plaintext label=< + + + +
If
+ + +
TrueFalse
+
> + ]; + Con_29 [ label="#4" ]; + Con_30 [ label="#5" ]; + Region31 [ shape=box style=filled fillcolor=yellow label="Region" ]; + Phi_a32 [ style=filled fillcolor=lightyellow label="φ_a" ]; + Region33 [ shape=box style=filled fillcolor=yellow label="Region" ]; + Phi_a34 [ style=filled fillcolor=lightyellow label="φ_a" ]; + Return35 [ shape=box style=filled fillcolor=yellow label="Return" ]; + { rank=same; Region21;Phi_a22;} + { rank=same; Region31;Phi_a32;} + { rank=same; Region33;Phi_a34;} + } + node [shape=plaintext]; + subgraph cluster_Scope1_0 { + Scope1_0 [label=< + + +
0$ctrlarg
>]; + subgraph cluster_Scope1_1 { + Scope1_1 [label=< + + +
1a
>]; + } + } + edge [ fontname=Helvetica, fontsize=8 ]; + Stop3 -> Return35[taillabel=0 color=red]; + EQNode8 -> Start2:p1[taillabel=1]; + EQNode8 -> Con_7[taillabel=2]; + If9 -> Start2:p0[taillabel=0 color=red]; + If9 -> EQNode8[taillabel=1]; + EQNode14 -> Start2:p1[taillabel=1]; + EQNode14 -> Con_13[taillabel=2]; + If15 -> If9:p0[taillabel=0 color=red]; + If15 -> EQNode14[taillabel=1]; + Region21 -> If15:p0[taillabel=1 color=red]; + Region21 -> If15:p1[taillabel=2 color=red]; + Phi_a22 -> Region21 [style=dotted taillabel=0]; + Phi_a22 -> Con_19[taillabel=1]; + Phi_a22 -> Con_20[taillabel=2]; + EQNode24 -> Start2:p1[taillabel=1]; + EQNode24 -> Con_23[taillabel=2]; + If25 -> If9:p1[taillabel=0 color=red]; + If25 -> EQNode24[taillabel=1]; + Region31 -> If25:p0[taillabel=1 color=red]; + Region31 -> If25:p1[taillabel=2 color=red]; + Phi_a32 -> Region31 [style=dotted taillabel=0]; + Phi_a32 -> Con_29[taillabel=1]; + Phi_a32 -> Con_30[taillabel=2]; + Region33 -> Region21[taillabel=1 color=red]; + Region33 -> Region31[taillabel=2 color=red]; + Phi_a34 -> Region33 [style=dotted taillabel=0]; + Phi_a34 -> Phi_a22[taillabel=1]; + Phi_a34 -> Phi_a32[taillabel=2]; + Return35 -> Region33[taillabel=0 color=red]; + Return35 -> Phi_a34[taillabel=1]; + edge [style=dashed color=cornflowerblue]; + Scope1_0:"Scope1_0_arg" -> Start2:p1; + Scope1_1:"Scope1_1_a" -> Phi_a34; +} diff --git a/docs/chapter05/05-graph8.svg b/docs/chapter05/05-graph8.svg new file mode 100644 index 00000000..e5310db4 --- /dev/null +++ b/docs/chapter05/05-graph8.svg @@ -0,0 +1,430 @@ + + + + + + +chapter05 + + +cluster_Nodes + + + +cluster_Scope1_0 + + + +cluster_Scope1_1 + + + + +Start2 + + +Start + + + +$ctrl + +arg + + + +Stop3 + +Stop + + + +Return35 + +Return + + + +Stop3->Return35 + + +0 + + + +Con_7 + +#1 + + + +EQNode8 + +== + + + +EQNode8->Start2:p1 + + +1 + + + +EQNode8->Con_7 + + +2 + + + +If9 + + +If + + + +True + + +False + + + +If9->Start2:p0 + + +0 + + + +If9->EQNode8 + + +1 + + + +Con_13 + +#2 + + + +EQNode14 + +== + + + +EQNode14->Start2:p1 + + +1 + + + +EQNode14->Con_13 + + +2 + + + +If15 + + +If + + + +True + + +False + + + +If15->If9:p0 + + +0 + + + +If15->EQNode14 + + +1 + + + +Con_19 + +#2 + + + +Con_20 + +#3 + + + +Region21 + +Region + + + +Region21->If15:p0 + + +1 + + + +Region21->If15:p1 + + +2 + + + +Phi_a22 + +φ_a + + + +Phi_a22->Con_19 + + +1 + + + +Phi_a22->Con_20 + + +2 + + + +Phi_a22->Region21 + + +0 + + + +Con_23 + +#3 + + + +EQNode24 + +== + + + +EQNode24->Start2:p1 + + +1 + + + +EQNode24->Con_23 + + +2 + + + +If25 + + +If + + + +True + + +False + + + +If25->If9:p1 + + +0 + + + +If25->EQNode24 + + +1 + + + +Con_29 + +#4 + + + +Con_30 + +#5 + + + +Region31 + +Region + + + +Region31->If25:p0 + + +1 + + + +Region31->If25:p1 + + +2 + + + +Phi_a32 + +φ_a + + + +Phi_a32->Con_29 + + +1 + + + +Phi_a32->Con_30 + + +2 + + + +Phi_a32->Region31 + + +0 + + + +Region33 + +Region + + + +Region33->Region21 + + +1 + + + +Region33->Region31 + + +2 + + + +Phi_a34 + +φ_a + + + +Phi_a34->Phi_a22 + + +1 + + + +Phi_a34->Phi_a32 + + +2 + + + +Phi_a34->Region33 + + +0 + + + +Return35->Region33 + + +0 + + + +Return35->Phi_a34 + + +1 + + + +Scope1_0 + + +0 + +$ctrl + +arg + + + +Scope1_0:Scope1_0_arg->Start2:p1 + + + + + +Scope1_1 + + +1 + +a + + + +Scope1_1:Scope1_1_a->Phi_a34 + + + + + diff --git a/docs/chapter05/05-graph9.svg b/docs/chapter05/05-graph9.svg new file mode 100644 index 00000000..dff4d63f --- /dev/null +++ b/docs/chapter05/05-graph9.svg @@ -0,0 +1,174 @@ + + + + + + +chapter05 + + +cluster_Nodes + + + + +Start2 + + +Start + + + +$ctrl + +arg + + + +Stop3 + +Stop + + + +Return20 + +Return + + + +Stop3->Return20 + + +0 + + + +Con_8 + +1 + + + +EQ9 + +== + + + +EQ9->Start2:p1 + + +1 + + + +EQ9->Con_8 + + +2 + + + +If10 + + +If + + + +True + + +False + + + +If10->Start2:p0 + + +0 + + + +If10->EQ9 + + +1 + + + +Con_14 + +2 + + + +Con_16 + +1 + + + +Region17 + +Region + + + +Region17->If10:p0 + + +1 + + + +Region17->If10:p1 + + +2 + + + +Phi_b18 + +φ_b + + + +Phi_b18->Con_14 + + +1 + + + +Phi_b18->Con_16 + + +2 + + + +Phi_b18->Region17 + + +0 + + + +Return20->Region17 + + +0 + + + +Return20->Phi_b18 + + +1 + + + \ No newline at end of file diff --git a/docs/chapter05/Makefile b/docs/chapter05/Makefile new file mode 100644 index 00000000..12659b8f --- /dev/null +++ b/docs/chapter05/Makefile @@ -0,0 +1,12 @@ +GV := $(wildcard *.gv) +SVG := $(patsubst %.gv,%.svg,$(GV)) + +.PHONY: all +all: $(SVG) + +%.svg: %.gv + dot -Tsvg $< > $@ + +.PHONY: clean +clean: + @rm -f $(SVG) diff --git a/docs/chapter05/README.md b/docs/chapter05/README.md new file mode 100644 index 00000000..aea98d02 --- /dev/null +++ b/docs/chapter05/README.md @@ -0,0 +1,384 @@ +# Chapter 5: If Statement, Phi, and Region + +# Table of Contents + +1. [Recap](#recap) +2. [New Nodes](#new-nodes) +3. [`IfNode`](#ifnode) +4. [`PhiNode` ](#phinode) +5. [`RegionNode`](#regionnode) +6. [Pinned data nodes](#we-do-not-associate-a-control-edge-on-every-data-node-in-the-graph) +7. [`Stop` Nodes](#stop-nodes) +8. [Parsing an `if` Statement](#parsing-an-if-statement) +9. [Operations on ScopeNodes](#operations-on-scopenodes) +10. [Duplicating a ScopeNode](#duplicating-a-scopenode) +11. [Merging two ScopeNodes](#merging-two-scopenodes) +12. [Example 1](#example-1) +13. [Before Merging](#before-merging) +14. [After Merging](#after-merging) +15. [Finally](#finally) +16. [Example 2](#example-2) +17. [Example 3](#example-3) +18. [Example 3](#example-3) +19. [More Examples](#more-examples) + + +You can also read [this chapter](https://github.com/SeaOfNodes/Simple/tree/linear-chapter05) in a linear Git revision history on the [linear](https://github.com/SeaOfNodes/Simple/tree/linear) branch and [compare](https://github.com/SeaOfNodes/Simple/compare/linear-chapter04...linear-chapter05) it to the previous chapter. + +In this chapter we extend the language grammar with the following features: + +* We introduce the `if` statement. +* To support splitting of control flow and merging, we introduce new nodes: `Region` and `Phi`. +* Since we can now have multiple return points, we also introduce the `Stop` node as the termination. + +Here is the [complete language grammar](05-grammar.md) for this chapter. + +## Recap + +Here is a recap of the nodes introduced in previous chapters: + +| Node Name | Type | Chapter | Description | Inputs | Value | +|-----------|----------------|---------|------------------------------------------------|-------------------------------------------------------------------------------|----------------------------------------------------------------------------| +| Multi | Abstract class | 4 | A node that has a tuple result | | A tuple | +| Start | Control | 1 | Start of function, now a MultiNode | | A tuple with a ctrl token and an `arg` data node | +| Proj | Data / Control | 4 | Projection nodes extract values from MultiNode | A MultiNode and index | Result is the extracted value from the input MultiNode at offset index | +| Bool | Data | 4 | Represents results of a comparison operator | Two data nodes | Result is a comparison, represented as integer value where 1=true, 0=false | +| Not | Data | 4 | Logical not | One data node | Result converts 0 to 1 and vice versa | +| Return | Control | 1 | End of function | Predecessor control node and a data node for the return value of the function | Return value of the function | +| Constant | Data | 1 | Represents constants such as integer literals | None, however Start node is set as input to enable graph walking | Value of the constant | +| Add | Data | 2 | Add two values | Two data nodes without restrictions on the order | Result of the add operation | +| Sub | Data | 2 | Subtract a value from another | Two data nodes, the first one is subtracted by the second one | Result of the subtraction | +| Mul | Data | 2 | Multiply two values | Two data nodes without restrictions on the order | Result of the multiplication | +| Div | Data | 2 | Divide a value by another | Two data nodes, the first one is divided by the second one | Result of the division | +| Minus | Data | 2 | Negate a value | One data node which value is negated | Result of the negation | +| Scope | Symbol Table | 3 | Represents scopes in the graph | Nodes that represent the current value of variables | None | + +> A `Proj` is a control node when it projects a control slot: `Proj#0` off `Start`, +> and both projections off an `If`. Every other projection is a data node. +> See `ProjNode.isCFG()`. + +## New Nodes + +The following new nodes are introduced in this chapter: + +| Node Name | Type | Chapter | Description | Inputs | Value | +|-----------|---------|---------|----------------------------------------------------|------------------------------------------------|----------------------------------------------------| +| If | Control | 5 | A branching test, sub type of `MultiNode` | A control node and a data predicate node | A tuple of two values: one for true, one for false | +| Region | Control | 5 | A merge point for multiple control flows | An input for each control flow that is merging | Merged control | +| Phi | Data | 5 | A phi function picks a value based on control flow | A Region, and data nodes for each control path | Depends on control flow path taken | +| Stop | Control | 5 | Termination of the program | All return nodes of the function | None | + +#### `IfNode` + +`If` node takes in both control and data (predicate expression) and routes the +control token to one of the two control flows, represented by true and false +`Proj` nodes. + +#### `PhiNode` + +A `Phi` reads in both data and control, and outputs a data value. The control +input to the `Phi` points to a `Region` node. The data inputs to the `Phi` are +one for each of the control inputs to that `Region`. The result computed by a +`Phi` depends both on the data and the matching control input. At most one +control input to the `Region` can be active at a time, and the `Phi` passes +through the data value from the matching input.[^1] + +Its type is the meet of its data-input types. Two different integer constants +merge to `TypeInteger.BOT`: the value is unknown, but it is still an integer. +Integer arithmetic likewise retains an integer result type when it cannot fold. + +#### `RegionNode` + +In this Sea of Nodes, there is an embedded Control Flow Graph - and like a +normal CFG there are merge points where two basic blocks flow into one. The +`Region` node takes control from each predecessor control (block) as input and +produces a merged control as an output.[^2] + +Both `Return` and `If` take control in slot 0. `PhiNode`s need their +corresponding `RegionNode` to know when to merge data values, so again slot 0 +is set, and data values show up in slots 1 and onward. `RegionNode`s keep +their control inputs in sync with `PhiNode`s, so again their control inputs show up +in slots 1 and onward. + +#### We do not associate a control edge on every data node in the graph + +If we want to track the basic block a normal instruction is in, we will set the +control input (always slot 0) to some control-producing Node. Typically we do +not need to (nor want to) track this - so control is `null` for most data ops. +The correctness of such a data op is solely determined by the remaining data +dependencies. It, and the Nodes that depend on it or on which it depends, +exists in a “sea” of Nodes, with little control structure. + +The “sea” of Nodes is useful for optimization, but does not represent any +traditional intermediate representation such as a CFG. We need a way to +serialize the graph and get back the control dependences. We do this with a +simple global code motion algorithm.[^3] + +#### `Stop` Nodes +`StopNode`s only have `ReturnNode` inputs. They mark the program termination. + + + +## Parsing an `if` Statement + +When we parse an `if` statement, the control flow splits at that point. We +must track the names being updated in each part of the `if` statement, and then +merge them at the end. The implementation follows the description in *Combining Analyses, Combining Optimizations*[^4]. + +This involves following: + +1. We create an `IfNode` with the current control token, i.e. the node mapped to + `$ctrl`, and the `if` predicate expression as inputs. +2. We add two `ProjNodes` - one for the `True` branch (call it `ifT`), and the + other for the `False` branch (call it `ifF`) - these extract values from the + tuple result of the `IfNode`. +3. We duplicate the current `ScopeNode`. The duplicated `ScopeNode` contains + all the same symbol tables as the original, and has the same edges. +4. We set the control token to the `True` projection node `ifT`, and parse the true + branch of the `if` statement. +5. We set the duplicated `ScopeNode` as the current one. +6. The control token is set to the `False` projection node `ifF`, and if there is an + `else` statement we parse it. +7. At this point we have two `ScopeNode`s; the original one, potentially updated + by the `True` branch, and the duplicate one, potentially updated by the + `False` branch. +8. We create a `Region` node to represent a merge point. +9. We *merge* the two `ScopeNode`s. We create `Phi` nodes for any names whose + bindings differ. The `Phi` nodes take the `Region` node as the control input + and the two data nodes from each of the `ScopeNode`s. The name binding is + updated to point to the `Phi` node. +10. Finally, we set the `Region` node as the control token, and discard the duplicated `ScopeNode`. + +Implementation is in [`parseIf` method in `Parser`](https://github.com/SeaOfNodes/Simple/blob/main/chapter05/src/main/java/com/seaofnodes/simple/Parser.java#L149-L185). + +## Operations on ScopeNodes + +As explained above, we duplicate ScopeNodes and merge them at a later point. There are some +subtleties in how this is implemented that is worth going over. + +### Duplicating a ScopeNode + +Below is the code for duplicating a ScopeNode. + +Our goals are: +1) Duplicate the name bindings across all stack levels +2) Make the new ScopeNode a user of all the bound nodes +3) Ensure that the order of defs in the duplicate is the same to allow easy merging + +For implementation [see `scopeNode.dup()`](https://github.com/SeaOfNodes/Simple/blob/main/chapter05/src/main/java/com/seaofnodes/simple/node/ScopeNode.java#L142-L154) + +### Merging two ScopeNodes + +At the merge point we merge two ScopeNodes. The goals are: + +1) Merge names whose bindings have changed between the two nodes. For each such name, a Phi node is created, referencing the two original data nodes. +2) A new Region node is created representing the merged control flow. The phis have this region node as the first input. +3) After the merge is completed, the duplicate is discarded, and its use of each of the nodes is also deleted. + +The merging logic takes advantage of that fact that the two ScopeNodes have the bound nodes in the same order in the list of inputs. This was ensured during duplicating the ScopeNode. +Although only the innermost occurrence of a name can have its binding changed, we scan all the nodes in our input list, and simply ignore ones where the binding has not changed. + +For implementation [see `ScopeNode.mergeScopes()`](https://github.com/SeaOfNodes/Simple/blob/main/chapter05/src/main/java/com/seaofnodes/simple/node/ScopeNode.java#L164-L173) + + +## Example #1 + +We show the graph for the following code snippet: +```java +int a = 1; +if (arg == 1) + a = arg+2; +else + a = arg-3; +return a; +``` + +### Before Merging + +Following shows the graph just before we merge the two branches of the `if` statement in a `Region` node. + +![Graph1](./05-graph1.svg) + +Note the two `ScopeNode`s in the graph. +One has its `$ctrl` pointing to the `True` projection, while the other has `$ctrl` pointing to `False` projection. +The variable `a` is bound to the `Add` node in the `True` branch, whereas it is bound to the `Sub` node in the `False` branch. +Thus `a` will need a `Phi` node when merging the two scopes. + +### After Merging + +Below is the graph after we created a `Region` node and merged the two definitions of `a` in a `Phi` node. + +![Graph2](./05-graph2.svg) + +The duplicate `ScopeNode` has been discarded and was merged into the other one. +Since `a` had two different definitions in both scopes a `Phi` node was created and is now referenced from `a`. +The `Phi` node's inputs are the `Region` node and the `Add` node from the `True` branch, and `Sub` node from the `False` branch. + +### Finally + +Here is the graph after the `return` statement was parsed and processed. + +![Graph3](./05-graph3.svg) + + + +## Example #2 + +Consider the following code snippet: +```java +int b = 0; +int c = 0; +if (arg == 1) { + b = 2; + c = 1; +} +else { + b = 1; +} +return b; +``` + +The value of `b` depends on which path the control flow took. +To resolve this, a Φ (Phi) function is inserted. + +``` +b = Phi(Region,2, 1); // values vary +c = Phi(Region,1, 0); // valuse vary, but dead +``` + +The `Phi` for `c` will die when the scope where `c` is defined dies. This does +not happen when merging but after the `return`. `return` is using `b` so `b` +stays alive. + +Before, we go ahead and parse down the if statement we duplicate the scope: +```java +ScopeNode fScope = _scope.dup(); +/* Scope[$ctrl:$ctrl, arg:arg][b:0, c:0]*/ +``` + +We then will proceed and parse down the first branch of the if statement: +```java +// Parse the true side +ctrl(ifT); // set ctrl token to ifTrue projection +parseStatement(); // Parse true-side +ScopeNode tScope = _scope; + +/* Scope[$ctrl:True, arg:arg][b:2, c:1]*/ +``` + +Notice, this branch modified and set a new value for both symbols currently existing in the symbol table. +Now, we set the scope back to where we started (without the modifications that `ifT` made) + +```java +_scope = fScope; +``` + +We then will proceed and parse down the second branch of the if statement: +```java +if (matchx("else")) { + parseStatement(); + fScope = _scope; + + /* Scope[$ctrl:False, arg:arg][b:1, c:0]*/ +} +``` + +This branch modified the values of `b` and `c`. Since the branch arms are also +lexical scopes, they cannot introduce new symbols in the current (outer) scope. +This means that the order of the name bindings stayed the same. Excluding the +first control node, we loop through and compare the nodes corresponding to the +same name binding to see if the nodes are different, if so we create a phi node +representing this conflict: + +```java + /* in(i); 2 */ + /* that.in(i); 1 */ + if( in(i) != that.in(i) ) // No need for redundant Phis + setDef(i, new PhiNode(ns[i], r, in(i), that.in(i)).peephole()); +``` + +![Graph8](./05-graph9.svg) + + + +## Example #3 + +Phi's implement a peephole illustrated in the example: + +```java +int a=arg==2; +if( arg==1 ) +{ + a=arg==3; +} +return a; +``` + +Pre-peephole we have: + +![Graph4](./05-graph4.svg) + +Post-peephole: + +![Graph5](./05-graph5.svg) + +The common operator was pulled out and the Phi node only got applied to the +operands. Notice how only the second operand of the `==` changes, the first +one stays the same (`arg`). The implementation is in +[`PhiNode.idealize()`](https://github.com/SeaOfNodes/Simple/blob/main/chapter05/src/main/java/com/seaofnodes/simple/node/PhiNode.java#L31-L71) + + +## More examples +```java +int c = 3; +int b = 2; +if (arg == 1) { + b = 3; + c = 4; +} +return c; +``` + +![Graph6](./05-graph6.svg) + +```java +int a=arg+1; +int b=arg+2; +if( arg==1 ) + b=b+a; +else + a=b+1; +return a+b; +``` + +![Graph7](./05-graph7.svg) + +```java +int a=1; +if( arg==1 ) + if( arg==2 ) + a=2; + else + a=3; +else if( arg==3 ) + a=4; +else + a=5; +return a; +``` + +![Graph8](./05-graph8.svg) + + + +[^1]: Click, C. (1995). + Combining Analyses, Combining Optimizations, 132. + +[^2]: Click, C. (1995). + Combining Analyses, Combining Optimizations, 129. + +[^3]: Click, C. (1995). + Combining Analyses, Combining Optimizations, 86. + +[^4]: Click, C. (1995). + Combining Analyses, Combining Optimizations, 102-103. diff --git a/src/main/java/com/seaofnodes/simple/Parser.java b/src/main/java/com/seaofnodes/simple/Parser.java index 487afee9..359d0175 100644 --- a/src/main/java/com/seaofnodes/simple/Parser.java +++ b/src/main/java/com/seaofnodes/simple/Parser.java @@ -1,6 +1,7 @@ package com.seaofnodes.simple; import com.seaofnodes.graph.GraphObserver; + import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.type.*; @@ -15,6 +16,11 @@ import java.util.*; */ public class Parser { + // Current compilation context; the observer belongs to the parser. + public static Parser PARSER; + public GraphObserver _obs; + public int pos() { return _lexer._position; } + /** * A Global Static, unique to each compilation. This is a public, so we @@ -24,17 +30,23 @@ public class Parser { * To make the compiler multithreaded, this field will have to move into a TLS. */ public static StartNode START; - // Current compilation context, like START; the observer belongs to the parser. - public static Parser PARSER; - public GraphObserver _obs; - public int pos() { return _lexer._position; } + + public StopNode STOP; // The Lexer. Thin wrapper over a byte[] buffer with a cursor. private final Lexer _lexer; /** - * A ScopeNode contains a stack of lexical scopes, each scope is a symbol table that binds + * Current ScopeNode - ScopeNodes change as we parse code, but at any point of time + * there is one current ScopeNode. The reason the current ScopeNode can change is to do with how + * we handle branching. See {@link #parseIf()}. + *

+ * Each ScopeNode contains a stack of lexical scopes, each scope is a symbol table that binds * variable names to Nodes. The top of this stack represents current scope. + *

+ * We keep a list of all ScopeNodes so that we can show them in graphs. + * @see #parseIf() + * @see #_xScopes */ public ScopeNode _scope; @@ -42,18 +54,28 @@ public class Parser { * List of keywords disallowed as identifiers */ private final HashSet KEYWORDS = new HashSet<>(){{ + add("else"); + add("false"); + add("if"); add("int"); add("return"); + add("true"); }}; + /** + * We clone ScopeNodes when control flows branch; it is useful to have + * a list of all active ScopeNodes for purposes of visualization of the SoN graph + */ + public final Stack _xScopes = new Stack<>(); + public Parser(String source, TypeInteger arg) { PARSER = this; Node.reset(); _lexer = new Lexer(source); _scope = new ScopeNode(); START = new StartNode(new Type[]{ Type.CONTROL, arg }); - START.peephole(); + STOP = new StopNode(); } public Parser(String source) { @@ -72,17 +94,21 @@ public class Parser { private Node ctrl(Node n) { return _scope.ctrl(n); } - public ReturnNode parse() { + public StopNode parse() { + _xScopes.push(_scope); // Enter a new scope for the initial control and arguments _scope.push(); _scope.define(ScopeNode.CTRL, new ProjNode(START, 0, ScopeNode.CTRL).peephole()); _scope.define(ScopeNode.ARG0, new ProjNode(START, 1, ScopeNode.ARG0).peephole()); - var ret = (ReturnNode) parseBlock(); + parseBlock(); _scope.pop(); + _xScopes.pop(); if (!_lexer.isEOF()) throw error("Syntax error, unexpected " + _lexer.getAnyNextToken()); - return ret; + STOP.peephole(); + return STOP; } + /** * Parses a block * @@ -95,21 +121,18 @@ public class Parser { private Node parseBlock() { // Enter a new scope _scope.push(); - Node n = null; - while (!peek('}') && !_lexer.isEOF()) { - Node n0 = parseStatement(); - if (n0 != null) n = n0; // Empty statements can return null - }; + while (!peek('}') && !_lexer.isEOF()) + parseStatement(); // Exit scope _scope.pop(); - return n; + return null; } /** * Parses a statement * *

-     *     returnStatement | declStatement | blockStatement | expressionStatement
+     *     returnStatement | declStatement | blockStatement | ifStatement | expressionStatement
      * 
* @return a {@link Node} or {@code null} */ @@ -117,10 +140,58 @@ public class Parser { if (matchx("return") ) return parseReturn(); else if (matchx("int")) return parseDecl(); else if (match ("{" )) return require(parseBlock(),"}"); + else if (matchx("if" )) return parseIf(); else if (matchx(";")) return null; // Empty statement else return parseExpressionStatement(); } + /** + * Parses a statement + * + *
+     *     if ( expression ) statement [else statement]
+     * 
+ * @return a {@link Node}, never {@code null} + */ + private Node parseIf() { + require("("); + // Parse predicate + var pred = require(parseExpression(), ")"); + // IfNode takes current control and predicate + IfNode ifNode = (IfNode)new IfNode(ctrl(), pred).keep().peephole(); + // Setup projection nodes + Node ifT = new ProjNode(ifNode, 0, "True" ).peephole(); + Node ifF = new ProjNode(ifNode, 1, "False").peephole(); + // In if true branch, the ifT proj node becomes the ctrl + // But first clone the scope and set it as current + int ndefs = _scope.nIns(); + ScopeNode fScope = _scope.dup(); // Duplicate current scope + fScope.ctrl(ifF); // The pending arm already starts at False + _xScopes.push(fScope); // For graph visualization we need all scopes + + // Parse the true side + ctrl(ifT); // set ctrl token to ifTrue projection + parseStatement(); // Parse true-side + ScopeNode tScope = _scope; + + // Parse the false side + _scope = fScope; // Restore scope, then parse else block if any + if (matchx("else")) { + parseStatement(); + fScope = _scope; + } + + if( tScope.nIns() != ndefs || fScope.nIns() != ndefs ) + throw error("Cannot define a new name on one arm of an if"); + + // Merge results + _scope = tScope; + _xScopes.pop(); // Discard pushed from graph display + + return ctrl(tScope.mergeScopes(fScope)); + } + + /** * Parses a return statement; "return" already parsed. * The $ctrl edge is killed. @@ -132,7 +203,7 @@ public class Parser { */ private Node parseReturn() { var expr = require(parseExpression(), ";"); - Node ret = new ReturnNode(ctrl(), expr).peephole(); + Node ret = STOP.addReturn(new ReturnNode(ctrl(), expr).peephole()); ctrl(null); // Kill control return ret; } @@ -250,13 +321,15 @@ public class Parser { * Parse a primary expression: * *
-     *     primaryExpr : integerLiteral | Identifier | '(' expression ')'
+     *     primaryExpr : integerLiteral | Identifier | true | false | '(' expression ')'
      * 
* @return a primary {@link Node}, never {@code null} */ private Node parsePrimary() { if( _lexer.isNumber() ) return parseIntegerLiteral(); if( match("(") ) return require(parseExpression(), ")"); + if( matchx("true" ) ) return new ConstantNode(TypeInteger.constant(1)).peephole(); + if( matchx("false") ) return new ConstantNode(TypeInteger.constant(0)).peephole(); String name = _lexer.matchId(); if( name == null) throw errorSyntax("an identifier or expression"); Node n = _scope.lookup(name); diff --git a/src/main/java/com/seaofnodes/simple/node/AddNode.java b/src/main/java/com/seaofnodes/simple/node/AddNode.java index 0291a900..2772c4c5 100644 --- a/src/main/java/com/seaofnodes/simple/node/AddNode.java +++ b/src/main/java/com/seaofnodes/simple/node/AddNode.java @@ -70,6 +70,24 @@ public class AddNode extends Node { if( lhs.in(2)._type.isConstant() && t2.isConstant() ) return new AddNode(lhs.in(1),new AddNode(lhs.in(2),rhs).peephole()); + if( lhs.in(2) instanceof PhiNode phi && phi.allCons() && + // Do we have ((x + (phi cons)) + con) ? + // Do we have ((x + (phi cons)) + (phi cons)) ? + // Push constant up through the phi: x + (phi con0+con0 con1+con1...) + + // Note that this is the exact reverse of Phi pulling a common op + // down to reduce total op-count. We don't get in an endless push- + // up push-down peephole cycle because the constants all fold first. + (t2.isConstant() || (rhs instanceof PhiNode && phi.in(0) == rhs.in(0) && rhs.allCons()) ) ) { + Node[] ns = new Node[phi.nIns()]; + ns[0] = phi.in(0); + // Push constant up through the phi: x + (phi con0+con0 con1+con1...) + for( int i=1; i hi._nid; } + @Override Node copy(Node lhs, Node rhs) { return new AddNode(lhs,rhs); } } diff --git a/src/main/java/com/seaofnodes/simple/node/BoolNode.java b/src/main/java/com/seaofnodes/simple/node/BoolNode.java index 143a6fde..87acc6cc 100644 --- a/src/main/java/com/seaofnodes/simple/node/BoolNode.java +++ b/src/main/java/com/seaofnodes/simple/node/BoolNode.java @@ -43,7 +43,7 @@ abstract public class BoolNode extends Node { return null; } - public static class EQ extends BoolNode { public EQ(Node lhs, Node rhs) { super(lhs,rhs); } String op() { return "=="; } boolean doOp(long lhs, long rhs) { return lhs == rhs; } } - public static class LT extends BoolNode { public LT(Node lhs, Node rhs) { super(lhs,rhs); } String op() { return "<" ; } boolean doOp(long lhs, long rhs) { return lhs < rhs; } } - public static class LE extends BoolNode { public LE(Node lhs, Node rhs) { super(lhs,rhs); } String op() { return "<="; } boolean doOp(long lhs, long rhs) { return lhs <= rhs; } } + public static class EQ extends BoolNode { public EQ(Node lhs, Node rhs) { super(lhs,rhs); } String op() { return "=="; } boolean doOp(long lhs, long rhs) { return lhs == rhs; } Node copy(Node lhs, Node rhs) { return new EQ(lhs,rhs); } } + public static class LT extends BoolNode { public LT(Node lhs, Node rhs) { super(lhs,rhs); } String op() { return "<" ; } boolean doOp(long lhs, long rhs) { return lhs < rhs; } Node copy(Node lhs, Node rhs) { return new LT(lhs,rhs); } } + public static class LE extends BoolNode { public LE(Node lhs, Node rhs) { super(lhs,rhs); } String op() { return "<="; } boolean doOp(long lhs, long rhs) { return lhs <= rhs; } Node copy(Node lhs, Node rhs) { return new LE(lhs,rhs); } } } diff --git a/src/main/java/com/seaofnodes/simple/node/DivNode.java b/src/main/java/com/seaofnodes/simple/node/DivNode.java index bffa4b44..f80f092d 100644 --- a/src/main/java/com/seaofnodes/simple/node/DivNode.java +++ b/src/main/java/com/seaofnodes/simple/node/DivNode.java @@ -35,4 +35,6 @@ public class DivNode extends Node { return in(1); return null; } + + @Override Node copy(Node lhs, Node rhs) { return new DivNode(lhs,rhs); } } diff --git a/src/main/java/com/seaofnodes/simple/node/IfNode.java b/src/main/java/com/seaofnodes/simple/node/IfNode.java new file mode 100644 index 00000000..6124b893 --- /dev/null +++ b/src/main/java/com/seaofnodes/simple/node/IfNode.java @@ -0,0 +1,36 @@ +package com.seaofnodes.simple.node; + +import com.seaofnodes.simple.type.Type; +import com.seaofnodes.simple.type.TypeInteger; +import com.seaofnodes.simple.type.TypeTuple; + +public class IfNode extends MultiNode { + + public IfNode(Node ctrl, Node pred) { + super(ctrl, pred); + } + + @Override + public String label() { return "If"; } + + @Override + StringBuilder _print1(StringBuilder sb) { + sb.append("if( "); + return in(1)._print0(sb).append(" )"); + } + + @Override public boolean isCFG() { return true; } + + public Node ctrl() { return in(0); } + public Node pred() { return in(1); } + + @Override + public Type compute() { + return TypeTuple.IF; + } + + @Override + public Node idealize() { + return null; + } +} diff --git a/src/main/java/com/seaofnodes/simple/node/MulNode.java b/src/main/java/com/seaofnodes/simple/node/MulNode.java index 60103b8b..b1d9e44a 100644 --- a/src/main/java/com/seaofnodes/simple/node/MulNode.java +++ b/src/main/java/com/seaofnodes/simple/node/MulNode.java @@ -44,4 +44,5 @@ public class MulNode extends Node { return null; } + @Override Node copy(Node lhs, Node rhs) { return new MulNode(lhs,rhs); } } diff --git a/src/main/java/com/seaofnodes/simple/node/Node.java b/src/main/java/com/seaofnodes/simple/node/Node.java index fdde869b..e17d7b9a 100644 --- a/src/main/java/com/seaofnodes/simple/node/Node.java +++ b/src/main/java/com/seaofnodes/simple/node/Node.java @@ -250,7 +250,7 @@ public abstract class Node { return deadCodeElim(n.peephole()); return null; // No progress - } + } // m is the new Node, self is the old. // Return 'm', which may have zero uses but is alive nonetheless. @@ -346,6 +346,20 @@ public abstract class Node { return this; } + // does this node contain all constants? + // Ignores in(0), as is usually control. + boolean allCons() { + for( int i=1; i + * The new Scope is a full-fledged Node with proper use<->def edges. + */ + public ScopeNode dup() { + ScopeNode dup = new ScopeNode(); + // Our goals are: + // 1) duplicate the name bindings of the ScopeNode across all stack levels + // 2) Make the new ScopeNode a user of all the nodes bound + // 3) Ensure that the order of defs is the same to allow easy merging + for( HashMap syms : _scopes ) + dup._scopes.push(new HashMap<>(syms)); + dup.addDef(ctrl()); // Control input is just copied + for( int i=1; i { @Override protected boolean dead(Node n) { return n.isDead(); } @Override protected int id(Node n) { return n._nid; } @@ -17,23 +17,37 @@ public class SimpleGraphAdapter extends GraphAdapter { @Override protected Node out(Node n, int idx) { return n.out(idx); } private ArrayList edges(Node n) { - String[] names = n instanceof ScopeNode scope && n.nIns() != 0 ? scope.reverseNames() : null; var edges = new ArrayList(); + String[] names = n instanceof ScopeNode scope && n.nIns() != 0 ? scope.reverseNames() : null; for( int i = 0; i < n.nIns(); i++ ) { - Role role = n instanceof ScopeNode || n instanceof ConstantNode ? Role.ASSOC - : n instanceof ProjNode ? (n.isCFG() ? Role.CTRL : Role.DATA) - : i == 0 ? Role.CTRL : Role.DATA; - edges.add(new Edge(i, ref(n.in(i)), role, names == null ? null : names[i])); + String name = names == null || i >= names.length ? null : names[i]; + edges.add(new Edge(i, ref(n.in(i)), role(n, i), name)); } return edges; } @Override protected GraphSnapshot.Node desc(Node n) { - Projection proj = n instanceof ProjNode p - ? new Projection(n.nIns() == 0 ? 0 : ref(n.in(0)), p._idx) : null; - Kind kind = n instanceof ScopeNode ? Kind.SCOPE : n.isCFG() ? Kind.CTRL : Kind.DATA; + Projection proj = n instanceof ProjNode p ? new Projection(ref(n.in(0)), p._idx) : null; String label = n.label(); return new GraphSnapshot.Node(n._nid, label == null ? n.getClass().getSimpleName() : label, - n._type == null ? null : n._type.toString(), kind, edges(n), proj); + n._type == null ? null : n._type.toString(), kind(n), edges(n), proj); + } + + private Kind kind(Node n) { + if( n instanceof StopNode ) return Kind.STOP; + if( n instanceof ScopeNode ) return Kind.SCOPE; + if( n instanceof StartNode ) return Kind.CTRL; + if( n instanceof RegionNode ) return Kind.REGION; + if( n instanceof PhiNode ) return Kind.PHI; + return n.isCFG() ? Kind.CTRL : Kind.DATA; + } + + private Role role(Node n, int i) { + if( n instanceof ScopeNode || n instanceof ConstantNode ) return Role.ASSOC; + if( n instanceof PhiNode ) return i == 0 ? Role.ASSOC : Role.DATA; + if( n instanceof ProjNode ) return n.isCFG() ? Role.CTRL : Role.DATA; + if( n instanceof RegionNode && i == 0 ) return Role.ASSOC; + if( i == 0 || n instanceof RegionNode || n instanceof StopNode ) return Role.CTRL; + return Role.DATA; } } diff --git a/src/main/java/com/seaofnodes/simple/print/SimpleGraphObserver.java b/src/main/java/com/seaofnodes/simple/print/SimpleGraphObserver.java index d655ed4a..a7604165 100644 --- a/src/main/java/com/seaofnodes/simple/print/SimpleGraphObserver.java +++ b/src/main/java/com/seaofnodes/simple/print/SimpleGraphObserver.java @@ -7,10 +7,11 @@ import com.seaofnodes.simple.node.Node; import java.util.ArrayList; import java.io.IOException; -/** Chapter 4 needs only a parser; it has no worklist or distant dependencies. */ +/** Chapter 5's compilation context; capture and event bookkeeping are shared. */ public class SimpleGraphObserver extends GraphCapture { private Parser _parser; private Node _ret; + private String _phase; public SimpleGraphObserver() { super(new SimpleGraphAdapter()); } public static void main(String[] args) throws IOException { GraphViewer.run(new SimpleGraphObserver()); @@ -18,11 +19,12 @@ public class SimpleGraphObserver extends GraphCapture { @Override protected void compile(String src) { _parser = new Parser(src); _parser._obs = this; + _phase = "Parse"; _ret = _parser.parse(); - phase("Parse"); + phase(_phase); } - @Override protected String phase() { return "Parse"; } - @Override protected int pos() { return _parser.pos(); } + @Override protected String phase() { return _phase; } + @Override protected int pos() { return "Parse".equals(_phase) ? _parser.pos() : -1; } @Override protected void detach() { if( _parser != null ) _parser._obs = null; _parser = null; @@ -31,6 +33,8 @@ public class SimpleGraphObserver extends GraphCapture { @Override protected Node scope() { return _parser._scope; } @Override protected void roots(ArrayList roots) { roots.add(Parser.START); + roots.add(_parser.STOP); + roots.addAll(_parser._xScopes); roots.add(_ret); } } diff --git a/src/main/java/com/seaofnodes/simple/type/Type.java b/src/main/java/com/seaofnodes/simple/type/Type.java index 1e50bdda..6b9130ba 100644 --- a/src/main/java/com/seaofnodes/simple/type/Type.java +++ b/src/main/java/com/seaofnodes/simple/type/Type.java @@ -43,7 +43,7 @@ public class Type { public StringBuilder print(StringBuilder sb) {return is_simple() ? sb.append(STRS[_type]) : sb;} - public Type meet(Type other) { return Type.BOTTOM; } + public Type meet(Type other) { return BOTTOM; } @Override public final String toString() { diff --git a/src/main/java/com/seaofnodes/simple/type/TypeTuple.java b/src/main/java/com/seaofnodes/simple/type/TypeTuple.java index 52befa38..da701865 100644 --- a/src/main/java/com/seaofnodes/simple/type/TypeTuple.java +++ b/src/main/java/com/seaofnodes/simple/type/TypeTuple.java @@ -16,11 +16,13 @@ public class TypeTuple extends Type { @Override public StringBuilder print(StringBuilder sb) { - sb.append("[ "); + sb.append("["); for( Type t : _types ) t.print(sb).append(","); sb.setLength(sb.length()-1); sb.append("]"); return sb; } + + public static final TypeTuple IF = new TypeTuple(new Type[]{Type.CONTROL,Type.CONTROL}); } diff --git a/src/test/java/com/seaofnodes/simple/Chapter01Test.java b/src/test/java/com/seaofnodes/simple/Chapter01Test.java index 3d568337..547c36f8 100644 --- a/src/test/java/com/seaofnodes/simple/Chapter01Test.java +++ b/src/test/java/com/seaofnodes/simple/Chapter01Test.java @@ -11,8 +11,9 @@ public class Chapter01Test { @Test public void testSimpleProgram() { Parser parser = new Parser("return 1;"); - ReturnNode ret = parser.parse(); + StopNode stop = parser.parse(); StartNode start = Parser.START; + ReturnNode ret = (ReturnNode)stop.in(0); assertTrue(ret.ctrl() instanceof ProjNode); Node expr = ret.expr(); diff --git a/src/test/java/com/seaofnodes/simple/Chapter02Test.java b/src/test/java/com/seaofnodes/simple/Chapter02Test.java index 6c816a23..a6075b75 100644 --- a/src/test/java/com/seaofnodes/simple/Chapter02Test.java +++ b/src/test/java/com/seaofnodes/simple/Chapter02Test.java @@ -11,49 +11,49 @@ public class Chapter02Test { @Test public void testParseGrammar() { Parser parser = new Parser("return 1+2*3+-5;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 2;", ret.print()); } @Test public void testAddPeephole() { Parser parser = new Parser("return 1+2;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 3;", ret.print()); } @Test public void testSubPeephole() { Parser parser = new Parser("return 1-2;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return -1;", ret.print()); } @Test public void testMulPeephole() { Parser parser = new Parser("return 2*3;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 6;", ret.print()); } @Test public void testDivPeephole() { Parser parser = new Parser("return 6/3;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 2;", ret.print()); } @Test public void testMinusPeephole() { Parser parser = new Parser("return 6/-3;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return -2;", ret.print()); } @Test public void testExample() { Parser parser = new Parser("return 1+2*3+-5;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 2;", ret.print()); } diff --git a/src/test/java/com/seaofnodes/simple/Chapter03Test.java b/src/test/java/com/seaofnodes/simple/Chapter03Test.java index 46b1ca33..c3cd43c3 100644 --- a/src/test/java/com/seaofnodes/simple/Chapter03Test.java +++ b/src/test/java/com/seaofnodes/simple/Chapter03Test.java @@ -11,28 +11,28 @@ public class Chapter03Test { @Test public void testVarDecl() { Parser parser = new Parser("int a=1; return a;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 1;", ret.print()); } @Test public void testVarAdd() { Parser parser = new Parser("int a=1; int b=2; return a+b;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 3;", ret.print()); } @Test public void testVarScope() { Parser parser = new Parser("int a=1; int b=2; int c=0; { int b=3; c=a+b; } return c;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 4;", ret.print()); } @Test public void testVarDist() { Parser parser = new Parser("int x0=1; int y0=2; int x1=3; int y1=4; return (x0-x1)*(x0-x1) + (y0-y1)*(y0-y1);"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 8;", ret.print()); } diff --git a/src/test/java/com/seaofnodes/simple/Chapter04Test.java b/src/test/java/com/seaofnodes/simple/Chapter04Test.java index 195afbb7..e5840622 100644 --- a/src/test/java/com/seaofnodes/simple/Chapter04Test.java +++ b/src/test/java/com/seaofnodes/simple/Chapter04Test.java @@ -11,77 +11,78 @@ public class Chapter04Test { @Test public void testPeephole() { Parser parser = new Parser("return 1+arg+2;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return (arg+3);", ret.print()); } @Test public void testPeephole2() { Parser parser = new Parser("return (1+arg)+2;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return (arg+3);", ret.print()); } @Test public void testAdd0() { Parser parser = new Parser("return 0+arg;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return arg;", ret.print()); } @Test public void testAddAddMul() { Parser parser = new Parser("return arg+0+arg;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return (arg*2);", ret.print()); } @Test public void testPeephole3() { Parser parser = new Parser("return 1+arg+2+arg+3;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return ((arg*2)+6);", ret.print()); } @Test public void testMul1() { Parser parser = new Parser("return 1*arg;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return arg;", ret.print()); } @Test public void testSub0() { Parser parser = new Parser("return arg-0;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return arg;", ret.print()); } @Test public void test0Sub() { Parser parser = new Parser("return 0-arg;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return (-arg);", ret.print()); } @Test public void testSubNeg() { Parser parser = new Parser("return 3--arg;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return (arg+3);", ret.print()); } @Test public void testNegSub() { Parser parser = new Parser("return -arg-3;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return (-(arg+3));", ret.print()); } @Test public void testVarArg() { - Parser parser = new Parser("return arg;", TypeInteger.BOT); - ReturnNode ret = parser.parse(); + Parser parser = new Parser("return arg;"); + StopNode stop = parser.parse(); + ReturnNode ret = stop.ret(); assertTrue(ret.in(0) instanceof ProjNode); assertTrue(ret.in(1) instanceof ProjNode); } @@ -89,49 +90,49 @@ public class Chapter04Test { @Test public void testConstantArg() { Parser parser = new Parser("return arg;", TypeInteger.constant(2)); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 2;", ret.print()); } @Test public void testCompEq() { Parser parser = new Parser("return 3==3;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 1;", ret.print()); } @Test public void testCompEq2() { Parser parser = new Parser("return 3==4;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 0;", ret.print()); } @Test public void testCompNEq() { Parser parser = new Parser("return 3!=3;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 0;", ret.print()); } @Test public void testCompNEq2() { Parser parser = new Parser("return 3!=4;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return 1;", ret.print()); } @Test public void testBug1() { Parser parser = new Parser("int a=arg+1; int b=a; b=1; return a+2;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return (arg+3);", ret.print()); } @Test public void testBug2() { Parser parser = new Parser("int a=arg+1; a=a; return a;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return (arg+1);", ret.print()); } @@ -148,14 +149,14 @@ public class Chapter04Test { @Test public void testBug4() { Parser parser = new Parser("return -arg;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return (-arg);", ret.print()); } @Test public void testBug5() { Parser parser = new Parser("return arg--2;"); - ReturnNode ret = parser.parse(); + StopNode ret = parser.parse(); assertEquals("return (arg--2);", ret.print()); } } diff --git a/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/src/test/java/com/seaofnodes/simple/Chapter05Test.java new file mode 100644 index 00000000..31ca56a0 --- /dev/null +++ b/src/test/java/com/seaofnodes/simple/Chapter05Test.java @@ -0,0 +1,210 @@ +package com.seaofnodes.simple; + +import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.type.TypeInteger; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class Chapter05Test { + + @Test + public void testIfStmt() { + Parser parser = new Parser( +""" +int a = 1; +if (arg == 1) + a = arg+2; +else { + a = arg-3; +} +return a;"""); + StopNode ret = parser.parse(); + assertEquals("return Phi(Region17,(arg+2),(arg-3));", ret.toString()); + } + + @Test + public void testTest() { + Parser parser = new Parser( +""" +int c = 3; +int b = 2; +if (arg == 1) { + b = 3; + c = 4; +} +return c;""", TypeInteger.BOT); + StopNode ret = parser.parse(); + assertEquals("return Phi(Region16,4,3);", ret.toString()); + } + + @Test + public void testReturn2() { + Parser parser = new Parser( +""" +if( arg==1 ) + return 3; +else + return 4; +""", TypeInteger.BOT); + StopNode stop = parser.parse(); + assertEquals("Stop[ return 3; return 4; ]", stop.toString()); + } + + @Test + public void testIfMergeB() { + Parser parser = new Parser( +""" +int a=arg+1; +int b=0; +if( arg==1 ) + b=a; +else + b=a+1; +return a+b;"""); + StopNode ret = parser.parse(); + assertEquals("return ((arg*2)+Phi(Region20,2,3));", ret.toString()); + } + + @Test + public void testIfMerge2() { + Parser parser = new Parser( +""" +int a=arg+1; +int b=arg+2; +if( arg==1 ) + b=b+a; +else + a=b+1; +return a+b;"""); + StopNode ret = parser.parse(); + assertEquals("return ((Phi(Region31,(arg*2),arg)+arg)+Phi(Region31,4,5));", ret.toString()); + } + + @Test + public void testMerge3() { + Parser parser = new Parser( +""" +int a=1; +if( arg==1 ) + if( arg==2 ) + a=2; + else + a=3; +else if( arg==3 ) + a=4; +else + a=5; +return a; +""", TypeInteger.BOT); + StopNode stop = parser.parse(); + assertEquals("return Phi(Region33,Phi(Region21,2,3),Phi(Region31,4,5));", stop.toString()); + } + + @Test + public void testMerge4() { + Parser parser = new Parser( +""" +int a=0; +int b=0; +if( arg ) + a=1; +if( arg==0 ) + b=2; +return arg+a+b; +""", TypeInteger.BOT); + StopNode stop = parser.parse(); + assertEquals("return ((arg+Phi(Region13,1,0))+Phi(Region22,2,0));", stop.toString()); + } + + @Test + public void testMerge5() { + Parser parser = new Parser( +""" +int a=arg==2; +if( arg==1 ) +{ + a=arg==3; +} +return a;"""); + StopNode ret = parser.parse(); + assertEquals("return (arg==Phi(Region16,3,2));", ret.toString()); + } + + @Test + public void testTrue() { + StopNode stop = new Parser("return true;").parse(); + assertEquals("return 1;",stop.toString()); + } + + @Test + public void testHalfDef() { + try { + new Parser("if( arg==1 ) int b=2; return b;").parse(); + fail(); + } catch( RuntimeException e ) { + assertEquals("Cannot define a new name on one arm of an if",e.getMessage()); + } + } + + @Test + public void testHalfDef2() { + try { + new Parser("if( arg==1 ) { int b=2; } else { int b=3; } return b;").parse(); + fail(); + } catch( RuntimeException e ) { + assertEquals("Undefined name 'b'",e.getMessage()); + } + } + + @Test + public void testRegress1() { + try { + new Parser("if(arg==2) int a=1; else int b=2; return a;").parse(); + fail(); + } catch( RuntimeException e ) { + assertEquals("Cannot define a new name on one arm of an if",e.getMessage()); + } + } + + @Test + public void testBadNum() { + try { + new Parser("return 1-;").parse(); + fail(); + } catch( RuntimeException e ) { + assertEquals("Syntax error, expected an identifier or expression: ;",e.getMessage()); + } + } + + @Test + public void testKeyword1() { + try { + new Parser("int true=0; return true;").parse(); + fail(); + } catch( RuntimeException e ) { + assertEquals("Expected an identifier, found 'true'",e.getMessage()); + } + } + + @Test + public void testKeyword2() { + try { + new Parser("int else=arg; if(else) else=2; else else=1; return else;").parse(); + fail(); + } catch( RuntimeException e ) { + assertEquals("Expected an identifier, found 'else'",e.getMessage()); + } + } + + @Test + public void testKeyword3() { + try { + new Parser("int a=1; ififif(arg)inta=2;return a;").parse(); + fail(); + } catch( RuntimeException e ) { + assertEquals("Syntax error, expected =: (",e.getMessage()); + } + } + +} -- cgit v1.2.3