diff options
Diffstat (limited to 'chapter10b')
80 files changed, 0 insertions, 11196 deletions
diff --git a/chapter10b/Makefile b/chapter10b/Makefile deleted file mode 100644 index 5ed21084..00000000 --- a/chapter10b/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -# Standalone compiler snapshot; shared rules also work in linearized checkouts. -include $(firstword $(wildcard ../build-support/early-chapter.mk build-support/early-chapter.mk)) -test_cp += com.seaofnodes.simple.FuzzerWrap - -.PHONY: fuzzer -fuzzer: $(test_classes) - java -ea -cp "$(CLZDIR)/main$(SEP)$(CLZDIR)/test$(SEP)$(jars)" org.junit.runner.JUnitCore com.seaofnodes.simple.FuzzerWrap diff --git a/chapter10b/README.md b/chapter10b/README.md deleted file mode 100644 index 7cb4cc75..00000000 --- a/chapter10b/README.md +++ /dev/null @@ -1,218 +0,0 @@ -# Chapter 10b: Splitting Memory - -[Previous: Chapter 10a](../chapter10a/README.md) | -[Next: Chapter 11](../chapter11/README.md) - -Chapter 10a made memory effects explicit with one SSA memory value. This -chapter keeps exactly that parser model and recovers independent memory chains -through graph rewrites. There is no new language syntax; the -[grammar](docs/10-grammar.md), pointer types, and null checks are unchanged. - -## Why split memory? - -```java -struct Point { int x; int y; } -Point p = new Point; -p.x = 42; -while (arg > 0) { - p.y = p.y + arg; - arg = arg - 1; -} -return p.x; -``` - -The loop changes `y`, so it cannot affect `x`. With one memory chain the load -of `x` follows the loop's stores. Splitting the fields lets ordinary -load-after-store forwarding turn the return value into 42. - - - -The graph shows the split chains before the final Load folds. Its memory input -goes straight to the Store of 42, bypassing the loop's `y` chain. As in 10a, -definitions appear above uses, apart from loop backedges, and arrows point -from use to definition. As in 10a, small, detached True/False projections -show the source branches gating Loads and Stores. Other control-flow context, -including Regions and their Phi bindings, is omitted. Chapter 11 chooses -the actual scheduling inputs; the vertical placement of independent chains -does not specify their execution order. - -## Equivalence-class aliasing - -Each struct field has an integer alias identity. Two different fields receive -different identities, even if they have the same spelling in different structs. -Two instances of the same struct share their field aliases. Thus different -classes never alias; accesses in the same class **may alias**. Same-class does -not mean same-address: forwarding still checks pointer identity. - -The parser assigns field identities at struct declarations, beginning at 2. -These identities are independent of Start's output indices. The default slot -of a memory aggregate is 1; precise slots are greater than 1. - -We do not allocate a Start projection, scope binding, or loop Phi for every -declared field. Start supplies one memory value, Scope holds one `$mem` binding, -and Return consumes `{ctrl, $mem, result}`. As with Start's outputs, control is -in slot 0 and memory in slot 1. The optimizer introduces slices -only where graph operations require them. - -## Three memory nodes - -| Node | Meaning | -|---|---| -| `MemMerge` | A complete memory state: a default plus precise alias overrides | -| `MemPhi` | One alias selected according to the incoming control path | -| `BulkMemPhi` | All aliases except an explicit exclusion set, selected by control | - -`MemMerge` combines independent pieces of memory at one program point. It is -not a control-flow merge. For example, after storing to alias `x`: - -```text -prior = current memory -store = Store_x(prior, pointer, value) -current memory = MemMerge(default=prior, x=store) -``` - -The Store selects its precise input from any incoming MemMerge. Loads and -precise memory Phis do the same. A missing precise entry falls back to the -default, provided that default still covers the requested alias. - -The explicit entries override the default: the semantic slices are disjoint, -and their union covers all memory. Flattening stacked aggregates preserves -entries that the outer aggregate has not replaced. This allows an `x` store -and a later `y` store to remain visible together at Return. - -The graph below shows `p.x = arg; p.y = 42; return p;` after redundant -initialization stores have been removed. MemMerge takes the default memory -in slot 1 and the `x` and `y` overrides in slots 2 and 3. - - - - -## Splitting a memory Phi - -Scope initially creates a BulkMemPhi wherever the ordinary SSA algorithm needs -to merge memory. It starts by covering all aliases and an empty exclusion set -while the merge point is finalized. Later, peeps will split out precise memory -slices from the bulk memory, lazily on demand. - -Precise single aliases can be split out from the bulk by this transformation: - -```text -BulkPhi(R, left, right) - becomes -MemMerge( - default = BulkPhi_except{x}(R, left, right), - x = MemPhi_x(R, slice(left,x), slice(right,x))) -``` - -The new precise Phi and the remaining bulk Phi share a Region (omitted from -the illustrations) and matching control-path indices. A loop uses the same -transformation, with the backedge among those inputs. Each further split preserves all previously extracted -slices (and peephole optimizations tidy up the stacked splits). - -Here the two branches store 3 or 4 into `p.x`, then return `p`. The graph shows -the partition immediately after extracting `x`, before further simplification -of the bulk Phi and its incoming aggregates. - - - -This transform is invasive, and is disallowed from being called recursively; -you can end up splitting around a loop (which is good) but then visiting a -1/2-split loop head (which is bad). The new nodes from the split are put -on the worklist and visited after the current split completes. - -Since bulk Phis merge a bunch of aliases, they have to take care when -peepholing vs MemMerges: there cannot be any overlap between the MemMerge -precise merges and the bulk Phi. - -Phi refactoring can combine matching Loads or Stores as in Chapter 10a (pushing -up or pulling down). The Phi new memory operands can use precise MemPhis for -the alias. This peep requires precise aliases, and is otherwise blocked by -BulkMems - and thus is a trigger for splitting a BulkMem. - -This also extends the worklist lesson from Chapter 9. A bulk Phi inspects its -users, so changes to a user's partition must wake the producer - job for -`addDep()`. Selecting a slice from an aggregate can expose a new bulk-Phi -user; that selected definition must be queued too. In short, any time we're -working with MemMerge, MemPhi or BulkMemPhi we can expect some non-local -dependencies. - -Memory splitting can increase node count - but Phis (Mem, Bulk or otherwise) -make no code. Progress comes from extracting an alias from a bulk Phi and -removing some Loads & Stores, rather than from requiring every rewrite -to shrink the graph. In other words, the total Load/Store count is going down -even if the MemPhi count is going up. - - - -## Types - -The type lattice retains Chapter 10a's six domains, colors, and notation: -`⊤` means top, `⊥` means bottom, and a suffix names the domain. The other five -domains are unchanged; memory now adds a flat element `MEM#N` for each precise -alias between memory top (`TypeMem.TOP`) and memory bottom (`TypeMem.BOT`). - - - -The parallel `MEM#2`, `MEM#3`, and further alias elements describe independent -field slices. For the first `Point` declaration above, these two aliases identify -`Point.x` and `Point.y`. Meeting different aliases gives memory bottom; joining -them gives memory top. Each precise alias is its own dual. (And the ellipsis stands -for more parallel aliases, not a type representing a set of aliases). - -Memory bottom covers all memory. The default aggregate slot numbered 1 is a -graph input position, not a precise field alias in this diagram. Types do not -track field values, private objects, or escape information. Bulk exclusion sets -and the default-plus-overrides structure of MemMerge belong to graph nodes, -not to an expanded type lattice. As in Chapter 10a, diagram edges show lattice -order, with top above bottom; field and tuple-element type lattices are elided. - - -## Evaluation and ordering - -MemMerge is a dependency node; it emits no heap operation. Its evaluator result -is a memory token, while Store mutates the object's fields. The scheduler must -distinguish aggregation from overwriting memory. A MemMerge is not a clobber, -and stores in different alias classes do not impose load/store anti-dependencies. - -In `int old = p.x; p.x = arg; p.y = arg; return old;`, the Load must precede -the later `x` Store; the `y` Store has an independent memory chain. The graph -retains the Load to show this scheduling requirement before local folding. - - - -Tests cover independent-field folding, parallel memory Phis, multiple field -updates surviving at Return, early returns, nested loops with break/continue, -and reads before subsequent stores through potentially aliased pointers. - -## What remains for later chapters? - -Chapter 10b knows every access's alias while parsing. What is lazy here is the -construction of memory partitions. Chapter 25 also allows an existing access's -alias to become known later, using the same representation. Its private -constructor memory, escape tracking, incomplete types, and module alias -remapping are separate extensions and are not needed here. - -Chapters 11-24 use this representation, including alias-specific load/store -anti-dependencies. Chapter 15 adds allocation with partial memory and typed -alias contents. Chapter 16 extends initialization to constructor values, and -Chapter 18 carries whole memory across function calls. - -## Build and test - -With JDK 21 or newer, from this directory: - -```sh -make lib -make tests -make release -make view -``` - -Make builds this complete snapshot without Maven. `make release` writes -`build/release/simple.jar`; `make view` launches the shared graph viewer. -Both the root Maven reactor and the supplied IDEA module descriptor include -the chapter. From the repository root, test both halves with: - -```sh -make tests CHAPTERS="chapter10a chapter10b" -``` diff --git a/chapter10b/chapter10b.iml b/chapter10b/chapter10b.iml deleted file mode 100644 index 74da25d0..00000000 --- a/chapter10b/chapter10b.iml +++ /dev/null @@ -1,28 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<module type="JAVA_MODULE" version="4"> - <component name="NewModuleRootManager" inherit-compiler-output="false"> - <output url="file://$MODULE_DIR$/../build/idea/production/chapter10b" /> - <output-test url="file://$MODULE_DIR$/../build/idea/test/chapter10b" /> - <exclude-output /> - <content url="file://$MODULE_DIR$"> - <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" /> - <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" /> - <excludeFolder url="file://$MODULE_DIR$/build" /> - <excludeFolder url="file://$MODULE_DIR$/target" /> - </content> - <orderEntry type="inheritedJdk" /> - <orderEntry type="sourceFolder" forTests="false" /> - <orderEntry type="module" module-name="graph" /> - <orderEntry type="module" module-name="print" /> - <orderEntry type="module-library" scope="TEST"> - <library name="JUnit4"> - <CLASSES> - <root url="jar://$MODULE_DIR$/lib/junit-4.12.jar!/" /> - <root url="jar://$MODULE_DIR$/lib/hamcrest-core-1.3.jar!/" /> - </CLASSES> - <JAVADOC /> - <SOURCES /> - </library> - </orderEntry> - </component> -</module> diff --git a/chapter10b/docs/10-grammar.md b/chapter10b/docs/10-grammar.md deleted file mode 100644 index 9a80d6ea..00000000 --- a/chapter10b/docs/10-grammar.md +++ /dev/null @@ -1,125 +0,0 @@ -# Grammar for Chapter 10b - -```antlrv4 -grammar SimpleLanguage; - -program - : statement+ EOF - ; - -statement - : returnStatement - | structDeclaration - | declStatement - | blockStatment - | expressionStatement - | ifStatement - | whileStatement - | breakStatement - | continueStatment - ; - -field - : 'int' IDENTIFIER ';' - ; - -fields - : field+ - ; - -structDeclaration - : 'struct' IDENTIFIER '{' fields '}' - ; - -whileStatement - : 'while' '(' expression ')' statement - ; - -breakStatement - : 'break' ';' - ; - -continueStatement - : 'continue' ';' - ; - -ifStatement - : 'if' '(' expression ')' statement ('else' statement)? - ; - - -expressionStatement - : IDENTIFIER '=' expression ';' - | fieldExpression '=' expression ';' - ; - -blockStatement - : '{' statement+ '}' - ; - -structName - : IDENTIFIER - ; - -declStatement - : 'int' IDENTIFIER '=' expression ';' - | structName ('?')? IDENTIFIER '=' expression ';' - ; - -returnStatement - : 'return' expression ';' - ; - -expression - : comparisonExpression - ; - -comparisonExpression - : additiveExpression (('==' | '!='| '>'| '<'| '>='| '<=') additiveExpression)* - ; - -additiveExpression - : multiplicativeExpression (('+' | '-') multiplicativeExpression)* - ; - -multiplicativeExpression - : unaryExpression (('*' | '/') unaryExpression)* - ; - -unaryExpression - : ('-') unaryExpression - | '!' unaryExpression - | primaryExpression - ; - -newExpression - : 'new' IDENTIFIER - ; - -fieldExpression - : primaryExpresson '.' IDENTIFIER - ; - -primaryExpression - : IDENTIFIER - | INTEGER_LITERAL - | 'true' - | 'false' - | 'null' - | newExpression - | '(' expression ')' - | fieldExpression - ; - -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/chapter10b/docs/Makefile b/chapter10b/docs/Makefile deleted file mode 100644 index 6fa0f057..00000000 --- a/chapter10b/docs/Makefile +++ /dev/null @@ -1 +0,0 @@ -include ../../graph/docs.mk diff --git a/chapter10b/docs/example1.gv b/chapter10b/docs/example1.gv deleted file mode 100644 index 5e059d77..00000000 --- a/chapter10b/docs/example1.gv +++ /dev/null @@ -1,20 +0,0 @@ -digraph Memory { - // IR styles match graph/web/render.js; arrows are use -> definition. - graph [bgcolor="#fafbfc" fontname="Helvetica" nodesep=0.35 ranksep=0.55 splines=ortho]; - node [fontname="Helvetica" fontsize=12 color="#758191" fontcolor="#152330" shape=box style="rounded,filled" fillcolor="#edf3f7"]; - edge [fontname="Helvetica" fontsize=9 color="#536477" fontcolor="#364352" arrowsize=0.7 penwidth=1.5]; - - rankdir=BT; - - M [label="Initial memory" shape=octagon style="filled" fillcolor="#dcecff"]; - X [label="Store x = 42" shape=octagon style="filled" fillcolor="#dcecff"]; - Y [label="Loop: Store y" shape=octagon style="filled" fillcolor="#dcecff"]; - L [label="Load x (42)" shape=box style="rounded,filled" fillcolor="#edf3f7"]; - L -> X -> M [color="#2867b2"]; Y -> M [color="#2867b2"]; - MemMerge -> X [color="#2867b2"]; MemMerge -> Y [color="#2867b2"]; - Return -> MemMerge [color="#2867b2"]; Return -> L; - { rank=same; MemMerge -> L [style=invis]; } - Y -> X [style=invis]; // Layout only: keep the stores in code order. - Return [shape=box style="filled" fillcolor="#fff1c4"]; - MemMerge [shape=octagon style="filled" fillcolor="#dcecff"]; -} diff --git a/chapter10b/docs/example1.json b/chapter10b/docs/example1.json deleted file mode 100644 index 67c277e1..00000000 --- a/chapter10b/docs/example1.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "ver": 1, - "comp": "chapter10b/docs/example1.svg", - "step": 1, - "roots": [24], - "scope": 0, - "nodes": [ - {"id": 1, "label": "Start", "type": null, "kind": "CTRL", "edges": [], "proj": null}, - {"id": 3, "label": "$mem", "type": null, "kind": "MEM", "edges": [{"idx": 0, "def": 1, "role": "MEM", "label": null}], "proj": {"par": 1, "idx": 1}}, - {"id": 4, "label": "arg", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 1, "role": "DATA", "label": null}], "proj": {"par": 1, "idx": 2}}, - {"id": 5, "label": "new Point", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}], "proj": null}, - {"id": 6, "label": "#0", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 1, "role": "ASSOC", "label": null}], "proj": null}, - {"id": 7, "label": "#42", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 1, "role": "ASSOC", "label": null}], "proj": null}, - {"id": 8, "label": "Store p.x", "type": "MEM#2", "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 7, "role": "DATA", "label": null}], "proj": null}, - {"id": 9, "label": "Store p.y", "type": "MEM#3", "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 6, "role": "DATA", "label": null}], "proj": null}, - {"id": 11, "label": "MemPhi y", "type": "MEM#3", "kind": "PHI", "edges": [{"idx": 0, "def": 0, "role": "ASSOC", "label": null}, {"idx": 1, "def": 9, "role": "MEM", "label": null}, {"idx": 2, "def": 19, "role": "MEM", "label": null}], "proj": null}, - {"id": 12, "label": "Phi arg", "type": null, "kind": "PHI", "edges": [{"idx": 0, "def": 0, "role": "ASSOC", "label": null}, {"idx": 1, "def": 4, "role": "DATA", "label": null}, {"idx": 2, "def": 21, "role": "DATA", "label": null}], "proj": null}, - {"id": 15, "label": "True", "type": null, "kind": "CTRL", "edges": [], "proj": {"par": 0, "idx": 0}}, - {"id": 16, "label": "False", "type": null, "kind": "CTRL", "edges": [], "proj": {"par": 0, "idx": 1}}, - {"id": 17, "label": "Load p.y", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 15, "role": "CTRL", "label": null}, {"idx": 1, "def": 11, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 0, "role": "DATA", "label": null}], "proj": null}, - {"id": 18, "label": "+", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 17, "role": "DATA", "label": null}, {"idx": 2, "def": 12, "role": "DATA", "label": null}], "proj": null}, - {"id": 19, "label": "Store p.y", "type": "MEM#3", "kind": "MEM", "edges": [{"idx": 0, "def": 15, "role": "CTRL", "label": null}, {"idx": 1, "def": 11, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 18, "role": "DATA", "label": null}], "proj": null}, - {"id": 20, "label": "#1", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 1, "role": "ASSOC", "label": null}], "proj": null}, - {"id": 21, "label": "-", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 12, "role": "DATA", "label": null}, {"idx": 2, "def": 20, "role": "DATA", "label": null}], "proj": null}, - {"id": 22, "label": "MemMerge", "type": null, "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 8, "role": "MEM", "label": null}, {"idx": 3, "def": 11, "role": "MEM", "label": null}], "proj": null}, - {"id": 23, "label": "Load p.x", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 16, "role": "CTRL", "label": null}, {"idx": 1, "def": 8, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 0, "role": "DATA", "label": null}], "proj": null}, - {"id": 24, "label": "Return", "type": null, "kind": "CTRL", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 22, "role": "MEM", "label": null}, {"idx": 2, "def": 23, "role": "DATA", "label": null}], "proj": null} - ], - "groups": [ - ] -} diff --git a/chapter10b/docs/example1.svg b/chapter10b/docs/example1.svg deleted file mode 100644 index 46faf818..00000000 --- a/chapter10b/docs/example1.svg +++ /dev/null @@ -1,155 +0,0 @@ -<svg aria-label="Compiler graph" width="929" height="674" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 929 674" style="font-family: sans-serif;"><style> - html, body { height:100%; margin:0; font-family:sans-serif; } - .viewer { height:100%; display:grid; grid-template-rows:auto minmax(0,1fr) auto; } - .source { padding:8px; border-bottom:1px solid #ccc; } - #program { width:min(600px,80vw); vertical-align:middle; } - #status { margin-top:4px; } - #graph { min-height:0; overflow:hidden; position:relative; background:#fafbfc; } - #elk { width:100%; height:100%; } - #graph svg { display:block; } - .tools { display:flex; flex-wrap:wrap; align-items:center; gap:14px; margin-top:8px; font-size:12px; } - .hint { color:#616c78; } - .ctrl { color:#b63838; } .mem { color:#2867b2; } .data { color:#536477; } - .edge { fill:none; stroke-width:1.5; } - .edge.CTRL { stroke-width:2; } - .edge.ASSOC { stroke-dasharray:4 4; } - .edge.PARSER { stroke-dasharray:5 4; } - .parser rect { fill:#f6f0ff; stroke:#7956a5; stroke-width:1.5; stroke-dasharray:5 4; } - .edge.selected { stroke-width:3.5; } - .edge.bundle { stroke-width:4; } - .edge.bundle.selected { stroke-width:6; } - .edge-hit { fill:none; stroke:transparent; stroke-width:12; vector-effect:non-scaling-stroke; pointer-events:stroke; cursor:pointer; } - .edge-jump { fill:transparent; pointer-events:all; cursor:pointer; } - .node { cursor:pointer; } - .box { stroke:#758191; stroke-width:1; } - .node.held .box { stroke-dasharray:5 3; } - .node.near .box { stroke:#c18221; stroke-width:2; } - .node.focus .box { stroke:#9c4900; stroke-width:3; } - .node.selected .box { stroke:#1569b9; stroke-width:3; } - .node.folded .box { stroke-width:4; } - .node.folding .box { fill:#f4ccd7; } - .fold-tag { font-size:9px; font-weight:700; fill:#963751; } - .peep-area { fill:#fff3d9; fill-opacity:.8; stroke:#c18221; stroke-width:2; pointer-events:none; } - .node.peep-edit .box { stroke:#9c4900; stroke-width:3; } - .node.error .box { stroke:#b42318; stroke-width:4; } - #event.error { color:#b42318; font-weight:600; white-space:pre-wrap; overflow-wrap:anywhere; } - .peep-ghosts { pointer-events:none; } - .region-box { stroke:#9da9b8; stroke-width:1.5; } - .fold-btn { cursor:pointer; } - .fold-btn rect { fill:white; stroke:#596674; } - .fold-btn text { font-size:14px; fill:#152330; } - .fold-btn:focus rect { stroke:#1569b9; stroke-width:2; } - .shortcut { cursor:pointer; } - .shortcut path { fill:none; stroke-width:1.5; } - .shortcut rect { fill:#fff8ec; stroke:#b63838; stroke-dasharray:3 2; } - .shortcut text { font-size:11px; fill:#783030; } - .shortcut.selected rect, .shortcut:focus rect { stroke-width:2.5; } - .label { font-size:12px; fill:#152330; font-weight:600; } - .node-id { font-size:10px; fill:#596674; font-weight:400; } - .type { font-size:11px; fill:#455768; } - .port { stroke:#536477; stroke-width:1; } - .row { stroke:#b6afcf; stroke-width:1; } - .bind { font-size:12px; fill:#152330; } - .slot { font-size:10px; fill:#364352; paint-order:stroke; stroke:#fafbfc; stroke-width:3; } - #detail { position:absolute; top:8px; right:8px; margin:0; padding:12px; max-width:320px; - max-height:45%; overflow:auto; white-space:pre-wrap; overflow-wrap:anywhere; - background:#fffffff2; border:1px solid #bac5d0; border-radius:4px; font-size:12px; } - .controls { display:flex; flex-wrap:wrap; justify-content:center; align-items:center; gap:6px; padding:6px; } - .button { color:white; background:black; font-size:20px; min-width:30px; } - .button:disabled { background:grey; } - .count { font-size:20px; min-width:35px; text-align:center; } - #N { width:6ch; } - #scrub { width:clamp(120px,35vw,600px); } - </style><defs><marker id="arrow-CTRL" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#b63838"/></marker><marker id="arrow-DATA" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#536477"/></marker><marker id="arrow-MEM" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#2867b2"/></marker><marker id="arrow-ASSOC" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#9396a3"/></marker><marker id="arrow-PARSER" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#7956a5"/></marker></defs><rect width="100%" height="100%" fill="rgb(250, 251, 252)"/><g><g class="regions" style="opacity: 1;"/><rect class="peep-area" rx="36" style="opacity: 0;"/><g class="edges"><path class="edge ASSOC" id="e6i0" d="M435,46 C435,70 682,41 682,65" stroke="#9396a3" marker-start="url(#arrow-ASSOC)" style="opacity: 1;"><title>#6[0] → #1 · ASSOC</title></path><path class="edge ASSOC" id="e7i0" d="M435,46 C435,70 100,41 100,65" stroke="#9396a3" marker-start="url(#arrow-ASSOC)" style="opacity: 1;"><title>#7[0] → #1 · ASSOC</title></path><path class="edge MEM" id="e8i1" d="M252,118 L252,168" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#8[1] → #3 · MEM</title></path><path class="edge DATA" id="e8i2" d="M530,118 L530,140 Q530,148 522,148 L284,148 Q276,148 276,156 L276,168" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#8[2] → #5 · DATA</title></path><path class="edge DATA" id="e8i3" d="M100,118 L100,150 Q100,158 108,158 L295,158 Q300,158 300,163 L300,168" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#8[3] → #7 · DATA</title></path><path class="edge MEM" id="e9i1" d="M252,118 L252,130 Q252,138 260,138 L385,138 Q393,138 393,146 L393,168" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#9[1] → #3 · MEM</title></path><path class="edge DATA" id="e9i2" d="M530,118 L530,140 Q530,148 522,148 L425,148 Q417,148 417,156 L417,168" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#9[2] → #5 · DATA</title></path><path class="edge DATA" id="e9i3" d="M682,118 L682,150 Q682,158 674,158 L446,158 Q441,158 441,163 L441,168" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#9[3] → #6 · DATA</title></path><path class="edge MEM" id="e11i1" d="M405,224 L405,272" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#11[1] → #9 · MEM</title></path><path class="edge MEM" id="e11i2" d="M777,640 L777,645 Q777,650 772,650 L32,650 Q24,650 24,642 L24,242 Q24,234 32,234 L437,234 Q445,234 445,242 L445,272" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#11[2] → #19 · MEM</title></path><path class="edge DATA" id="e12i1" d="M372,118 L372,123 Q372,128 377,128 L684,128 Q692,128 692,136 L692,168" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#12[1] → #4 · DATA</title></path><path class="edge DATA" id="e12i2" d="M620,328 L620,333 Q620,338 625,338 L682,338 Q690,338 690,330 L690,252 Q690,244 698,244 L774,244 Q782,244 782,236 L782,166 Q782,158 774,158 L737,158 Q732,158 732,163 L732,168" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#12[2] → #21 · DATA</title></path><path class="edge CTRL" id="e17i0" d="M741,328 L741,340 Q741,348 749,348 L790,348 Q798,348 798,356 L798,376" stroke="#b63838" marker-start="url(#arrow-CTRL)" style="opacity: 1;"><title>#17[0] → #15 · CTRL</title></path><path class="edge MEM" id="e17i1" d="M425,328 L425,350 Q425,358 433,358 L814,358 Q822,358 822,366 L822,376" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#17[1] → #11 · MEM</title></path><path class="edge DATA" id="e17i2" d="M530,118 L530,140 Q530,148 538,148 L784,148 Q792,148 792,156 L792,330 Q792,338 800,338 L838,338 Q846,338 846,346 L846,376" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#17[2] → #5 · DATA</title></path><path class="edge DATA" id="e18i1" d="M834,432 L834,480" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#18[1] → #17 · DATA</title></path><path class="edge DATA" id="e18i2" d="M712,224 L712,229 Q712,234 717,234 L896,234 Q904,234 904,242 L904,434 Q904,442 896,442 L872,442 Q864,442 864,450 L864,480" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#18[2] → #12 · DATA</title></path><path class="edge CTRL" id="e19i0" d="M741,328 L741,584" stroke="#b63838" marker-start="url(#arrow-CTRL)" style="opacity: 1;"><title>#19[0] → #15 · CTRL</title></path><path class="edge MEM" id="e19i1" d="M425,328 L425,350 Q425,358 433,358 L744,358 Q752,358 752,366 L752,549.5 Q752,556 758.5,556 L758.5,556 Q765,556 765,562.5 L765,584" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#19[1] → #11 · MEM</title></path><path class="edge DATA" id="e19i2" d="M530,118 L530,140 Q530,148 538,148 L784,148 Q792,148 792,156 L792,330 Q792,338 784,338 L771,338 Q763,338 763,346 L763,538 Q763,546 771,546 L781,546 Q789,546 789,554 L789,584" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#19[2] → #5 · DATA</title></path><path class="edge DATA" id="e19i3" d="M834,536 L834,541 Q834,546 829,546 L821,546 Q813,546 813,554 L813,584" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#19[3] → #18 · DATA</title></path><path class="edge ASSOC" id="e20i0" d="M435,46 C435,70 557,147 557,171" stroke="#9396a3" marker-start="url(#arrow-ASSOC)" style="opacity: 1;"><title>#20[0] → #1 · ASSOC</title></path><path class="edge DATA" id="e21i1" d="M712,224 L712,229 Q712,234 707,234 L628,234 Q620,234 620,242 L620,272" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#21[1] → #12 · DATA</title></path><path class="edge DATA" id="e21i2" d="M557,224 L557,236 Q557,244 565,244 L642,244 Q650,244 650,252 L650,272" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#21[2] → #20 · DATA</title></path><path class="edge MEM" id="e22i1" d="M252,118 L252,130 Q252,138 244,138 L82,138 Q74,138 74,146 L74,333.5 Q74,338 78.5,338 L78.5,338 Q83,338 83,342.5 L83,376" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#22[1] → #3 · MEM</title></path><path class="edge MEM" id="e22i2" d="M264,224 L264,236 Q264,244 256,244 L102,244 Q94,244 94,252 L94,331.5 Q94,338 100.5,338 L100.5,338 Q107,338 107,344.5 L107,376" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#22[2] → #8 · MEM</title></path><path class="edge MEM" id="e22i3" d="M425,328 L425,350 Q425,358 417,358 L139,358 Q131,358 131,366 L131,376" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#22[3] → #11 · MEM</title></path><path class="edge CTRL" id="e23i0" d="M129,224 L129,272" stroke="#b63838" marker-start="url(#arrow-CTRL)" style="opacity: 1;"><title>#23[0] → #16 · CTRL</title></path><path class="edge MEM" id="e23i1" d="M264,224 L264,236 Q264,244 256,244 L161,244 Q153,244 153,252 L153,272" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#23[1] → #8 · MEM</title></path><path class="edge DATA" id="e23i2" d="M530,118 L530,140 Q530,148 522,148 L342,148 Q334,148 334,156 L334,246 Q334,254 326,254 L185,254 Q177,254 177,262 L177,272" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#23[2] → #5 · DATA</title></path><path class="edge MEM" id="e24i1" d="M95,432 L95,437 Q95,442 100,442 L127,442 Q135,442 135,450 L135,480" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#24[1] → #22 · MEM</title></path><path class="edge DATA" id="e24i2" d="M165,328 L165,480" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#24[2] → #23 · DATA</title></path></g><g class="edge-hits"/><g class="parser" style="opacity: 1;"/><g class="nodes"><g class="node" id="n1" data-id="1" transform="translate(192,24)" style="opacity: 1;"><path class="box" d="M0,0H240V44H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="120" y="18"><tspan>Start</tspan><tspan class="node-id"> #1</tspan></text><text class="type" text-anchor="middle" y="35" x="120"/><title>#1 Start -Type not computed - -</title></g><g class="node" id="n3" data-id="3" transform="translate(192,68)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>$mem</tspan><tspan class="node-id"> #3/1</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#3 $mem -Projection 1 of #1 -Type not computed - -[0] → #1 MEM</title></g><g class="node" id="n4" data-id="4" transform="translate(312,68)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>arg</tspan><tspan class="node-id"> #4/2</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#4 arg -Projection 2 of #1 -Type not computed - -[0] → #1 DATA</title></g><g class="node" id="n5" data-id="5" transform="translate(470,68)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>new Point</tspan><tspan class="node-id"> #5</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#5 new Point -Type not computed - -[0] → — CTRL</title><circle class="port" cx="60" cy="-3" r="3" fill="white"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n6" data-id="6" transform="translate(622,68)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>#0</tspan><tspan class="node-id"> #6</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#6 #0 -Type not computed - -[0] → #1 ASSOC</title><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n7" data-id="7" transform="translate(40,68)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>#42</tspan><tspan class="node-id"> #7</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#7 #42 -Type not computed - -[0] → #1 ASSOC</title><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n8" data-id="8" transform="translate(204,174)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.x</tspan><tspan class="node-id"> #8</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#2</text><title>#8 Store p.x -MEM#2 - -[0] → — CTRL -[1] → #3 MEM -[2] → #5 DATA -[3] → #7 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n9" data-id="9" transform="translate(345,174)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.y</tspan><tspan class="node-id"> #9</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#3</text><title>#9 Store p.y -MEM#3 - -[0] → — CTRL -[1] → #3 MEM -[2] → #5 DATA -[3] → #6 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n11" data-id="11" transform="translate(365,278)" style="opacity: 1;"><path class="box" d="M12,0H108L120,22L108,44H12L0,22Z" fill="#f5e4fa"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>MemPhi y</tspan><tspan class="node-id"> #11</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#3</text><title>#11 MemPhi y -MEM#3 - -[0] → — ASSOC -[1] → #9 MEM -[2] → #19 MEM</title><circle class="port" cx="0" cy="-3" r="3" fill="white"/><circle class="port" cx="40" cy="-3" r="3" fill="#536477"/><circle class="port" cx="80" cy="-3" r="3" fill="#536477"/><text class="slot" x="0" y="-10" text-anchor="middle">0</text><text class="slot" x="40" y="-10" text-anchor="middle">1</text><text class="slot" x="80" y="-10" text-anchor="middle">2</text></g><g class="node" id="n12" data-id="12" transform="translate(652,174)" style="opacity: 1;"><path class="box" d="M12,0H108L120,22L108,44H12L0,22Z" fill="#f5e4fa"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Phi arg</tspan><tspan class="node-id"> #12</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#12 Phi arg -Type not computed - -[0] → — ASSOC -[1] → #4 DATA -[2] → #21 DATA</title><circle class="port" cx="0" cy="-3" r="3" fill="white"/><circle class="port" cx="40" cy="-3" r="3" fill="#536477"/><circle class="port" cx="80" cy="-3" r="3" fill="#536477"/><text class="slot" x="0" y="-10" text-anchor="middle">0</text><text class="slot" x="40" y="-10" text-anchor="middle">1</text><text class="slot" x="80" y="-10" text-anchor="middle">2</text></g><g class="node" id="n15" data-id="15" transform="translate(700,296)" style="opacity: 1;"><path class="box" d="M0,0H82V26H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="41" y="17"><tspan>True</tspan><tspan class="node-id"> #15/0</tspan></text><text class="type" text-anchor="middle" y="35" x="41"/><title>#15 True -Projection 0 of #0 -Type not computed - -</title></g><g class="node" id="n16" data-id="16" transform="translate(85,192)" style="opacity: 1;"><path class="box" d="M0,0H87V26H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="43.5" y="17"><tspan>False</tspan><tspan class="node-id"> #16/1</tspan></text><text class="type" text-anchor="middle" y="35" x="43.5"/><title>#16 False -Projection 1 of #0 -Type not computed - -</title></g><g class="node" id="n17" data-id="17" transform="translate(774,382)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Load p.y</tspan><tspan class="node-id"> #17</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#17 Load p.y -Type not computed - -[0] → #15 CTRL -[1] → #11 MEM -[2] → #5 DATA -[3] → — DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="#536477"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="white"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n18" data-id="18" transform="translate(774,486)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>+</tspan><tspan class="node-id"> #18</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#18 + -Type not computed - -[0] → — CTRL -[1] → #17 DATA -[2] → #12 DATA</title><circle class="port" cx="30" cy="-3" r="3" fill="white"/><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><circle class="port" cx="90" cy="-3" r="3" fill="#536477"/><text class="slot" x="30" y="-10" text-anchor="middle">0</text><text class="slot" x="60" y="-10" text-anchor="middle">1</text><text class="slot" x="90" y="-10" text-anchor="middle">2</text></g><g class="node" id="n19" data-id="19" transform="translate(717,590)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.y</tspan><tspan class="node-id"> #19</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#3</text><title>#19 Store p.y -MEM#3 - -[0] → #15 CTRL -[1] → #11 MEM -[2] → #5 DATA -[3] → #18 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="#536477"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n20" data-id="20" transform="translate(497,174)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>#1</tspan><tspan class="node-id"> #20</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#20 #1 -Type not computed - -[0] → #1 ASSOC</title><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n21" data-id="21" transform="translate(560,278)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>-</tspan><tspan class="node-id"> #21</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#21 - -Type not computed - -[0] → — CTRL -[1] → #12 DATA -[2] → #20 DATA</title><circle class="port" cx="30" cy="-3" r="3" fill="white"/><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><circle class="port" cx="90" cy="-3" r="3" fill="#536477"/><text class="slot" x="30" y="-10" text-anchor="middle">0</text><text class="slot" x="60" y="-10" text-anchor="middle">1</text><text class="slot" x="90" y="-10" text-anchor="middle">2</text></g><g class="node" id="n22" data-id="22" transform="translate(35,382)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>MemMerge</tspan><tspan class="node-id"> #22</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#22 MemMerge -Type not computed - -[0] → — CTRL -[1] → #3 MEM -[2] → #8 MEM -[3] → #11 MEM</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n23" data-id="23" transform="translate(105,278)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Load p.x</tspan><tspan class="node-id"> #23</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#23 Load p.x -Type not computed - -[0] → #16 CTRL -[1] → #8 MEM -[2] → #5 DATA -[3] → — DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="#536477"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="white"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n24" data-id="24" transform="translate(75,486)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Return</tspan><tspan class="node-id"> #24</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#24 Return -Type not computed - -[0] → — CTRL -[1] → #22 MEM -[2] → #23 DATA</title><circle class="port" cx="30" cy="-3" r="3" fill="white"/><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><circle class="port" cx="90" cy="-3" r="3" fill="#536477"/><text class="slot" x="30" y="-10" text-anchor="middle">0</text><text class="slot" x="60" y="-10" text-anchor="middle">1</text><text class="slot" x="90" y="-10" text-anchor="middle">2</text></g></g><g class="region-heads" style="opacity: 1;"/><g class="shortcuts" style="opacity: 1;"/><g class="peep-ghosts" pointer-events="none"/></g></svg> diff --git a/chapter10b/docs/example2a.gv b/chapter10b/docs/example2a.gv deleted file mode 100644 index 187e63b9..00000000 --- a/chapter10b/docs/example2a.gv +++ /dev/null @@ -1,17 +0,0 @@ -digraph Memory { - // IR styles match graph/web/render.js; arrows are use -> definition. - graph [bgcolor="#fafbfc" fontname="Helvetica" nodesep=0.35 ranksep=0.55 splines=ortho]; - node [fontname="Helvetica" fontsize=12 color="#758191" fontcolor="#152330" shape=box style="rounded,filled" fillcolor="#edf3f7"]; - edge [fontname="Helvetica" fontsize=9 color="#536477" fontcolor="#364352" arrowsize=0.7 penwidth=1.5]; - - rankdir=RL; - - M [label="Default memory" shape=octagon style="filled" fillcolor="#dcecff"]; - X [label="Store x" shape=octagon style="filled" fillcolor="#dcecff"]; - Y [label="Store y" shape=octagon style="filled" fillcolor="#dcecff"]; - X -> M [color="#2867b2"]; Y -> M [color="#2867b2"]; - MemMerge -> M [xlabel="default",color="#2867b2"]; MemMerge -> X [xlabel="x",color="#2867b2"]; - MemMerge -> Y [xlabel="y",color="#2867b2"]; Return -> MemMerge [color="#2867b2"]; - Return [shape=box style="filled" fillcolor="#fff1c4"]; - MemMerge [shape=octagon style="filled" fillcolor="#dcecff"]; -} diff --git a/chapter10b/docs/example2a.json b/chapter10b/docs/example2a.json deleted file mode 100644 index 2a9461b6..00000000 --- a/chapter10b/docs/example2a.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "ver": 1, - "comp": "chapter10b/docs/example2a.svg", - "step": 1, - "roots": [11], - "scope": 0, - "nodes": [ - {"id": 1, "label": "Start", "type": null, "kind": "CTRL", "edges": [], "proj": null}, - {"id": 3, "label": "$mem", "type": null, "kind": "MEM", "edges": [{"idx": 0, "def": 1, "role": "MEM", "label": null}], "proj": {"par": 1, "idx": 1}}, - {"id": 4, "label": "arg", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 1, "role": "DATA", "label": null}], "proj": {"par": 1, "idx": 2}}, - {"id": 5, "label": "new Point", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}], "proj": null}, - {"id": 7, "label": "Store p.x", "type": "MEM#2", "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 4, "role": "DATA", "label": null}], "proj": null}, - {"id": 8, "label": "#42", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 1, "role": "ASSOC", "label": null}], "proj": null}, - {"id": 9, "label": "Store p.y", "type": "MEM#3", "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 8, "role": "DATA", "label": null}], "proj": null}, - {"id": 10, "label": "MemMerge", "type": null, "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 7, "role": "MEM", "label": null}, {"idx": 3, "def": 9, "role": "MEM", "label": null}], "proj": null}, - {"id": 11, "label": "Return", "type": null, "kind": "CTRL", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 10, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}], "proj": null} - ], - "groups": [ - ] -} diff --git a/chapter10b/docs/example2a.svg b/chapter10b/docs/example2a.svg deleted file mode 100644 index b43a55b4..00000000 --- a/chapter10b/docs/example2a.svg +++ /dev/null @@ -1,103 +0,0 @@ -<svg aria-label="Compiler graph" width="598" height="454" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 598 454" style="font-family: sans-serif;"><style> - html, body { height:100%; margin:0; font-family:sans-serif; } - .viewer { height:100%; display:grid; grid-template-rows:auto minmax(0,1fr) auto; } - .source { padding:8px; border-bottom:1px solid #ccc; } - #program { width:min(600px,80vw); vertical-align:middle; } - #status { margin-top:4px; } - #graph { min-height:0; overflow:hidden; position:relative; background:#fafbfc; } - #elk { width:100%; height:100%; } - #graph svg { display:block; } - .tools { display:flex; flex-wrap:wrap; align-items:center; gap:14px; margin-top:8px; font-size:12px; } - .hint { color:#616c78; } - .ctrl { color:#b63838; } .mem { color:#2867b2; } .data { color:#536477; } - .edge { fill:none; stroke-width:1.5; } - .edge.CTRL { stroke-width:2; } - .edge.ASSOC { stroke-dasharray:4 4; } - .edge.PARSER { stroke-dasharray:5 4; } - .parser rect { fill:#f6f0ff; stroke:#7956a5; stroke-width:1.5; stroke-dasharray:5 4; } - .edge.selected { stroke-width:3.5; } - .edge.bundle { stroke-width:4; } - .edge.bundle.selected { stroke-width:6; } - .edge-hit { fill:none; stroke:transparent; stroke-width:12; vector-effect:non-scaling-stroke; pointer-events:stroke; cursor:pointer; } - .edge-jump { fill:transparent; pointer-events:all; cursor:pointer; } - .node { cursor:pointer; } - .box { stroke:#758191; stroke-width:1; } - .node.held .box { stroke-dasharray:5 3; } - .node.near .box { stroke:#c18221; stroke-width:2; } - .node.focus .box { stroke:#9c4900; stroke-width:3; } - .node.selected .box { stroke:#1569b9; stroke-width:3; } - .node.folded .box { stroke-width:4; } - .node.folding .box { fill:#f4ccd7; } - .fold-tag { font-size:9px; font-weight:700; fill:#963751; } - .peep-area { fill:#fff3d9; fill-opacity:.8; stroke:#c18221; stroke-width:2; pointer-events:none; } - .node.peep-edit .box { stroke:#9c4900; stroke-width:3; } - .node.error .box { stroke:#b42318; stroke-width:4; } - #event.error { color:#b42318; font-weight:600; white-space:pre-wrap; overflow-wrap:anywhere; } - .peep-ghosts { pointer-events:none; } - .region-box { stroke:#9da9b8; stroke-width:1.5; } - .fold-btn { cursor:pointer; } - .fold-btn rect { fill:white; stroke:#596674; } - .fold-btn text { font-size:14px; fill:#152330; } - .fold-btn:focus rect { stroke:#1569b9; stroke-width:2; } - .shortcut { cursor:pointer; } - .shortcut path { fill:none; stroke-width:1.5; } - .shortcut rect { fill:#fff8ec; stroke:#b63838; stroke-dasharray:3 2; } - .shortcut text { font-size:11px; fill:#783030; } - .shortcut.selected rect, .shortcut:focus rect { stroke-width:2.5; } - .label { font-size:12px; fill:#152330; font-weight:600; } - .node-id { font-size:10px; fill:#596674; font-weight:400; } - .type { font-size:11px; fill:#455768; } - .port { stroke:#536477; stroke-width:1; } - .row { stroke:#b6afcf; stroke-width:1; } - .bind { font-size:12px; fill:#152330; } - .slot { font-size:10px; fill:#364352; paint-order:stroke; stroke:#fafbfc; stroke-width:3; } - #detail { position:absolute; top:8px; right:8px; margin:0; padding:12px; max-width:320px; - max-height:45%; overflow:auto; white-space:pre-wrap; overflow-wrap:anywhere; - background:#fffffff2; border:1px solid #bac5d0; border-radius:4px; font-size:12px; } - .controls { display:flex; flex-wrap:wrap; justify-content:center; align-items:center; gap:6px; padding:6px; } - .button { color:white; background:black; font-size:20px; min-width:30px; } - .button:disabled { background:grey; } - .count { font-size:20px; min-width:35px; text-align:center; } - #N { width:6ch; } - #scrub { width:clamp(120px,35vw,600px); } - </style><defs><marker id="arrow-CTRL" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#b63838"/></marker><marker id="arrow-DATA" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#536477"/></marker><marker id="arrow-MEM" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#2867b2"/></marker><marker id="arrow-ASSOC" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#9396a3"/></marker><marker id="arrow-PARSER" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#7956a5"/></marker></defs><rect width="100%" height="100%" fill="rgb(250, 251, 252)"/><g><g class="regions" style="opacity: 1;"/><rect class="peep-area" rx="36" style="opacity: 0;"/><g class="edges"><path class="edge MEM" id="e7i1" d="M84,118 L84,140 Q84,148 92,148 L135,148 Q143,148 143,156 L143,166" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#7[1] → #3 · MEM</title></path><path class="edge DATA" id="e7i2" d="M362,118 L362,123 Q362,128 357,128 L175,128 Q167,128 167,136 L167,166" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#7[2] → #5 · DATA</title></path><path class="edge DATA" id="e7i3" d="M204,118 L204,131.5 Q204,138 197.5,138 L197.5,138 Q191,138 191,144.5 L191,166" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#7[3] → #4 · DATA</title></path><path class="edge ASSOC" id="e8i0" d="M267,46 C267,70 514,41 514,65" stroke="#9396a3" marker-start="url(#arrow-ASSOC)" style="opacity: 1;"><title>#8[0] → #1 · ASSOC</title></path><path class="edge MEM" id="e9i1" d="M84,118 L84,140 Q84,148 92,148 L287,148 Q295,148 295,156 L295,166" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#9[1] → #3 · MEM</title></path><path class="edge DATA" id="e9i2" d="M362,118 L362,123 Q362,128 357,128 L327,128 Q319,128 319,136 L319,166" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#9[2] → #5 · DATA</title></path><path class="edge DATA" id="e9i3" d="M514,118 L514,130 Q514,138 506,138 L351,138 Q343,138 343,146 L343,166" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#9[3] → #8 · DATA</title></path><path class="edge MEM" id="e10i1" d="M84,118 L84,224 Q84,232 92,232 L123,232 Q131,232 131,240 L131,270" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#10[1] → #3 · MEM</title></path><path class="edge MEM" id="e10i2" d="M155,222 L155,270" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#10[2] → #7 · MEM</title></path><path class="edge MEM" id="e10i3" d="M307,222 L307,227 Q307,232 302,232 L187,232 Q179,232 179,240 L179,270" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#10[3] → #9 · MEM</title></path><path class="edge MEM" id="e11i1" d="M143,326 L143,331 Q143,336 148,336 L339,336 Q347,336 347,344 L347,374" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#11[1] → #10 · MEM</title></path><path class="edge DATA" id="e11i2" d="M362,118 L362,123 Q362,128 367,128 L369.5,128 Q377,128 377,135.5 L377,374" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#11[2] → #5 · DATA</title></path></g><g class="edge-hits"/><g class="parser" style="opacity: 1;"/><g class="nodes"><g class="node" id="n1" data-id="1" transform="translate(24,24)" style="opacity: 1;"><path class="box" d="M0,0H240V44H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="120" y="18"><tspan>Start</tspan><tspan class="node-id"> #1</tspan></text><text class="type" text-anchor="middle" y="35" x="120"/><title>#1 Start -Type not computed - -</title></g><g class="node" id="n3" data-id="3" transform="translate(24,68)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>$mem</tspan><tspan class="node-id"> #3/1</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#3 $mem -Projection 1 of #1 -Type not computed - -[0] → #1 MEM</title></g><g class="node" id="n4" data-id="4" transform="translate(144,68)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>arg</tspan><tspan class="node-id"> #4/2</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#4 arg -Projection 2 of #1 -Type not computed - -[0] → #1 DATA</title></g><g class="node" id="n5" data-id="5" transform="translate(302,68)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>new Point</tspan><tspan class="node-id"> #5</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#5 new Point -Type not computed - -[0] → — CTRL</title><circle class="port" cx="60" cy="-3" r="3" fill="white"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n7" data-id="7" transform="translate(95,172)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.x</tspan><tspan class="node-id"> #7</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#2</text><title>#7 Store p.x -MEM#2 - -[0] → — CTRL -[1] → #3 MEM -[2] → #5 DATA -[3] → #4 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n8" data-id="8" transform="translate(454,68)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>#42</tspan><tspan class="node-id"> #8</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#8 #42 -Type not computed - -[0] → #1 ASSOC</title><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n9" data-id="9" transform="translate(247,172)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.y</tspan><tspan class="node-id"> #9</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#3</text><title>#9 Store p.y -MEM#3 - -[0] → — CTRL -[1] → #3 MEM -[2] → #5 DATA -[3] → #8 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n10" data-id="10" transform="translate(83,276)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>MemMerge</tspan><tspan class="node-id"> #10</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#10 MemMerge -Type not computed - -[0] → — CTRL -[1] → #3 MEM -[2] → #7 MEM -[3] → #9 MEM</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n11" data-id="11" transform="translate(287,380)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Return</tspan><tspan class="node-id"> #11</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#11 Return -Type not computed - -[0] → — CTRL -[1] → #10 MEM -[2] → #5 DATA</title><circle class="port" cx="30" cy="-3" r="3" fill="white"/><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><circle class="port" cx="90" cy="-3" r="3" fill="#536477"/><text class="slot" x="30" y="-10" text-anchor="middle">0</text><text class="slot" x="60" y="-10" text-anchor="middle">1</text><text class="slot" x="90" y="-10" text-anchor="middle">2</text></g></g><g class="region-heads" style="opacity: 1;"/><g class="shortcuts" style="opacity: 1;"/><g class="peep-ghosts" pointer-events="none"/></g></svg> diff --git a/chapter10b/docs/example2b.gv b/chapter10b/docs/example2b.gv deleted file mode 100644 index 39b87a6a..00000000 --- a/chapter10b/docs/example2b.gv +++ /dev/null @@ -1,19 +0,0 @@ -digraph Memory { - // IR styles match graph/web/render.js; arrows are use -> definition. - graph [bgcolor="#fafbfc" fontname="Helvetica" nodesep=0.35 ranksep=0.55 splines=ortho]; - node [fontname="Helvetica" fontsize=12 color="#758191" fontcolor="#152330" shape=box style="rounded,filled" fillcolor="#edf3f7"]; - edge [fontname="Helvetica" fontsize=9 color="#536477" fontcolor="#364352" arrowsize=0.7 penwidth=1.5]; - - rankdir=RL; - - P [label="MemPhi(x)" shape=hexagon style="filled" fillcolor="#f5e4fa"]; - B [label="BulkMemPhi(All except x)" shape=hexagon style="filled" fillcolor="#f5e4fa"]; - P -> Left [xlabel="slice x",color="#2867b2"]; P -> Right [xlabel="slice x",color="#2867b2"]; - B -> Left [color="#2867b2"]; B -> Right [color="#2867b2"]; - P -> Region [style=dashed,color="#9396a3"]; B -> Region [style=dashed,color="#9396a3"]; - MemMerge -> P [xlabel="x",color="#2867b2"]; MemMerge -> B [xlabel="default",color="#2867b2"]; - MemMerge [shape=octagon style="filled" fillcolor="#dcecff"]; - Left [shape=octagon style="filled" fillcolor="#dcecff"]; - Right [shape=octagon style="filled" fillcolor="#dcecff"]; - Region [shape=trapezium style="filled" fillcolor="#fff1c4"]; -} diff --git a/chapter10b/docs/example2b.json b/chapter10b/docs/example2b.json deleted file mode 100644 index 3d919618..00000000 --- a/chapter10b/docs/example2b.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "ver": 1, - "comp": "chapter10b/docs/example2b.svg", - "step": 1, - "roots": [23], - "scope": 0, - "nodes": [ - {"id": 1, "label": "Start", "type": null, "kind": "CTRL", "edges": [], "proj": null}, - {"id": 3, "label": "$mem", "type": null, "kind": "MEM", "edges": [{"idx": 0, "def": 1, "role": "MEM", "label": null}], "proj": {"par": 1, "idx": 1}}, - {"id": 5, "label": "new Point", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}], "proj": null}, - {"id": 6, "label": "#0", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 1, "role": "ASSOC", "label": null}], "proj": null}, - {"id": 7, "label": "Store p.x", "type": "MEM#2", "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 6, "role": "DATA", "label": null}], "proj": null}, - {"id": 8, "label": "Store p.y", "type": "MEM#3", "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 6, "role": "DATA", "label": null}], "proj": null}, - {"id": 9, "label": "MemMerge", "type": null, "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 7, "role": "MEM", "label": null}, {"idx": 3, "def": 8, "role": "MEM", "label": null}], "proj": null}, - {"id": 11, "label": "True", "type": null, "kind": "CTRL", "edges": [], "proj": {"par": 0, "idx": 0}}, - {"id": 12, "label": "False", "type": null, "kind": "CTRL", "edges": [], "proj": {"par": 0, "idx": 1}}, - {"id": 13, "label": "#3", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 1, "role": "ASSOC", "label": null}], "proj": null}, - {"id": 14, "label": "Store p.x", "type": "MEM#2", "kind": "MEM", "edges": [{"idx": 0, "def": 11, "role": "CTRL", "label": null}, {"idx": 1, "def": 7, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 13, "role": "DATA", "label": null}], "proj": null}, - {"id": 15, "label": "#4", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 1, "role": "ASSOC", "label": null}], "proj": null}, - {"id": 16, "label": "Store p.x", "type": "MEM#2", "kind": "MEM", "edges": [{"idx": 0, "def": 12, "role": "CTRL", "label": null}, {"idx": 1, "def": 7, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 15, "role": "DATA", "label": null}], "proj": null}, - {"id": 17, "label": "MemMerge", "type": null, "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 9, "role": "MEM", "label": null}, {"idx": 2, "def": 14, "role": "MEM", "label": null}], "proj": null}, - {"id": 18, "label": "MemMerge", "type": null, "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 9, "role": "MEM", "label": null}, {"idx": 2, "def": 16, "role": "MEM", "label": null}], "proj": null}, - {"id": 20, "label": "MemPhi x", "type": "MEM#2", "kind": "PHI", "edges": [{"idx": 0, "def": 0, "role": "ASSOC", "label": null}, {"idx": 1, "def": 14, "role": "MEM", "label": null}, {"idx": 2, "def": 16, "role": "MEM", "label": null}], "proj": null}, - {"id": 21, "label": "BulkMemPhi except x", "type": null, "kind": "PHI", "edges": [{"idx": 0, "def": 0, "role": "ASSOC", "label": null}, {"idx": 1, "def": 17, "role": "MEM", "label": null}, {"idx": 2, "def": 18, "role": "MEM", "label": null}], "proj": null}, - {"id": 22, "label": "MemMerge", "type": null, "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 21, "role": "MEM", "label": null}, {"idx": 2, "def": 20, "role": "MEM", "label": null}], "proj": null}, - {"id": 23, "label": "Return", "type": null, "kind": "CTRL", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 22, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}], "proj": null} - ], - "groups": [ - ] -} diff --git a/chapter10b/docs/example2b.svg b/chapter10b/docs/example2b.svg deleted file mode 100644 index 54ddad9d..00000000 --- a/chapter10b/docs/example2b.svg +++ /dev/null @@ -1,150 +0,0 @@ -<svg aria-label="Compiler graph" width="886" height="768" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 886 768" style="font-family: sans-serif;"><style> - html, body { height:100%; margin:0; font-family:sans-serif; } - .viewer { height:100%; display:grid; grid-template-rows:auto minmax(0,1fr) auto; } - .source { padding:8px; border-bottom:1px solid #ccc; } - #program { width:min(600px,80vw); vertical-align:middle; } - #status { margin-top:4px; } - #graph { min-height:0; overflow:hidden; position:relative; background:#fafbfc; } - #elk { width:100%; height:100%; } - #graph svg { display:block; } - .tools { display:flex; flex-wrap:wrap; align-items:center; gap:14px; margin-top:8px; font-size:12px; } - .hint { color:#616c78; } - .ctrl { color:#b63838; } .mem { color:#2867b2; } .data { color:#536477; } - .edge { fill:none; stroke-width:1.5; } - .edge.CTRL { stroke-width:2; } - .edge.ASSOC { stroke-dasharray:4 4; } - .edge.PARSER { stroke-dasharray:5 4; } - .parser rect { fill:#f6f0ff; stroke:#7956a5; stroke-width:1.5; stroke-dasharray:5 4; } - .edge.selected { stroke-width:3.5; } - .edge.bundle { stroke-width:4; } - .edge.bundle.selected { stroke-width:6; } - .edge-hit { fill:none; stroke:transparent; stroke-width:12; vector-effect:non-scaling-stroke; pointer-events:stroke; cursor:pointer; } - .edge-jump { fill:transparent; pointer-events:all; cursor:pointer; } - .node { cursor:pointer; } - .box { stroke:#758191; stroke-width:1; } - .node.held .box { stroke-dasharray:5 3; } - .node.near .box { stroke:#c18221; stroke-width:2; } - .node.focus .box { stroke:#9c4900; stroke-width:3; } - .node.selected .box { stroke:#1569b9; stroke-width:3; } - .node.folded .box { stroke-width:4; } - .node.folding .box { fill:#f4ccd7; } - .fold-tag { font-size:9px; font-weight:700; fill:#963751; } - .peep-area { fill:#fff3d9; fill-opacity:.8; stroke:#c18221; stroke-width:2; pointer-events:none; } - .node.peep-edit .box { stroke:#9c4900; stroke-width:3; } - .node.error .box { stroke:#b42318; stroke-width:4; } - #event.error { color:#b42318; font-weight:600; white-space:pre-wrap; overflow-wrap:anywhere; } - .peep-ghosts { pointer-events:none; } - .region-box { stroke:#9da9b8; stroke-width:1.5; } - .fold-btn { cursor:pointer; } - .fold-btn rect { fill:white; stroke:#596674; } - .fold-btn text { font-size:14px; fill:#152330; } - .fold-btn:focus rect { stroke:#1569b9; stroke-width:2; } - .shortcut { cursor:pointer; } - .shortcut path { fill:none; stroke-width:1.5; } - .shortcut rect { fill:#fff8ec; stroke:#b63838; stroke-dasharray:3 2; } - .shortcut text { font-size:11px; fill:#783030; } - .shortcut.selected rect, .shortcut:focus rect { stroke-width:2.5; } - .label { font-size:12px; fill:#152330; font-weight:600; } - .node-id { font-size:10px; fill:#596674; font-weight:400; } - .type { font-size:11px; fill:#455768; } - .port { stroke:#536477; stroke-width:1; } - .row { stroke:#b6afcf; stroke-width:1; } - .bind { font-size:12px; fill:#152330; } - .slot { font-size:10px; fill:#364352; paint-order:stroke; stroke:#fafbfc; stroke-width:3; } - #detail { position:absolute; top:8px; right:8px; margin:0; padding:12px; max-width:320px; - max-height:45%; overflow:auto; white-space:pre-wrap; overflow-wrap:anywhere; - background:#fffffff2; border:1px solid #bac5d0; border-radius:4px; font-size:12px; } - .controls { display:flex; flex-wrap:wrap; justify-content:center; align-items:center; gap:6px; padding:6px; } - .button { color:white; background:black; font-size:20px; min-width:30px; } - .button:disabled { background:grey; } - .count { font-size:20px; min-width:35px; text-align:center; } - #N { width:6ch; } - #scrub { width:clamp(120px,35vw,600px); } - </style><defs><marker id="arrow-CTRL" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#b63838"/></marker><marker id="arrow-DATA" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#536477"/></marker><marker id="arrow-MEM" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#2867b2"/></marker><marker id="arrow-ASSOC" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#9396a3"/></marker><marker id="arrow-PARSER" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#7956a5"/></marker></defs><rect width="100%" height="100%" fill="rgb(250, 251, 252)"/><g><g class="regions" style="opacity: 1;"/><rect class="peep-area" rx="36" style="opacity: 0;"/><g class="edges"><path class="edge ASSOC" id="e6i0" d="M147,46 C147,70 279,41 279,65" stroke="#9396a3" marker-start="url(#arrow-ASSOC)" style="opacity: 1;"><title>#6[0] → #1 · ASSOC</title></path><path class="edge MEM" id="e7i1" d="M84,118 L84,140 Q84,148 92,148 L341,148 Q349,148 349,156 L349,166" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#7[1] → #3 · MEM</title></path><path class="edge DATA" id="e7i2" d="M431,118 L431,130 Q431,138 423,138 L381,138 Q373,138 373,146 L373,166" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#7[2] → #5 · DATA</title></path><path class="edge DATA" id="e7i3" d="M279,118 L279,123 Q279,128 284,128 L389,128 Q397,128 397,136 L397,166" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#7[3] → #6 · DATA</title></path><path class="edge MEM" id="e8i1" d="M84,118 L84,166" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#8[1] → #3 · MEM</title></path><path class="edge DATA" id="e8i2" d="M431,118 L431,130 Q431,138 423,138 L116,138 Q108,138 108,146 L108,166" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#8[2] → #5 · DATA</title></path><path class="edge DATA" id="e8i3" d="M279,118 L279,123 Q279,128 274,128 L140,128 Q132,128 132,136 L132,166" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#8[3] → #6 · DATA</title></path><path class="edge MEM" id="e9i1" d="M84,118 L84,140 Q84,148 76,148 L33,148 Q25,148 25,156 L25,234 Q25,242 33,242 L93,242 Q101,242 101,250 L101,272" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#9[1] → #3 · MEM</title></path><path class="edge MEM" id="e9i2" d="M361,222 L361,234 Q361,242 353,242 L133,242 Q125,242 125,250 L125,272" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#9[2] → #7 · MEM</title></path><path class="edge MEM" id="e9i3" d="M96,222 L96,227 Q96,232 101,232 L141,232 Q149,232 149,240 L149,272" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#9[3] → #8 · MEM</title></path><path class="edge ASSOC" id="e13i0" d="M147,46 C147,70 502,145 502,169" stroke="#9396a3" marker-start="url(#arrow-ASSOC)" style="opacity: 1;"><title>#13[0] → #1 · ASSOC</title></path><path class="edge CTRL" id="e14i0" d="M229,222 L229,272" stroke="#b63838" marker-start="url(#arrow-CTRL)" style="opacity: 1;"><title>#14[0] → #11 · CTRL</title></path><path class="edge MEM" id="e14i1" d="M361,222 L361,234 Q361,242 353,242 L261,242 Q253,242 253,250 L253,272" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#14[1] → #7 · MEM</title></path><path class="edge DATA" id="e14i2" d="M431,118 L431,244 Q431,252 423,252 L285,252 Q277,252 277,260 L277,272" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#14[2] → #5 · DATA</title></path><path class="edge DATA" id="e14i3" d="M502,222 L502,254 Q502,262 494,262 L306,262 Q301,262 301,267 L301,272" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#14[3] → #13 · DATA</title></path><path class="edge ASSOC" id="e15i0" d="M147,46 C147,70 762,145 762,169" stroke="#9396a3" marker-start="url(#arrow-ASSOC)" style="opacity: 1;"><title>#15[0] → #1 · ASSOC</title></path><path class="edge CTRL" id="e16i0" d="M638,222 L638,272" stroke="#b63838" marker-start="url(#arrow-CTRL)" style="opacity: 1;"><title>#16[0] → #12 · CTRL</title></path><path class="edge MEM" id="e16i1" d="M361,222 L361,234 Q361,242 369,242 L654,242 Q662,242 662,250 L662,272" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#16[1] → #7 · MEM</title></path><path class="edge DATA" id="e16i2" d="M431,118 L431,130 Q431,138 439,138 L683,138 Q691,138 691,146 L691,229.5 Q691,232 688.5,232 L688.5,232 Q686,232 686,234.5 L686,272" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#16[2] → #5 · DATA</title></path><path class="edge DATA" id="e16i3" d="M762,222 L762,227 Q762,232 757,232 L718,232 Q710,232 710,240 L710,272" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#16[3] → #15 · DATA</title></path><path class="edge MEM" id="e17i1" d="M113,328 L113,340 Q113,348 121,348 L227,348 Q235,348 235,356 L235,376" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#17[1] → #9 · MEM</title></path><path class="edge MEM" id="e17i2" d="M265,328 L265,376" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#17[2] → #14 · MEM</title></path><path class="edge MEM" id="e18i1" d="M113,328 L113,340 Q113,348 121,348 L491,348 Q499,348 499,356 L499,376" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#18[1] → #9 · MEM</title></path><path class="edge MEM" id="e18i2" d="M674,328 L674,340 Q674,348 666,348 L537,348 Q529,348 529,356 L529,376" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#18[2] → #16 · MEM</title></path><path class="edge MEM" id="e20i1" d="M265,328 L265,333 Q265,338 270,338 L626,338 Q634,338 634,346 L634,376" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#20[1] → #14 · MEM</title></path><path class="edge MEM" id="e20i2" d="M674,328 L674,376" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#20[2] → #16 · MEM</title></path><path class="edge MEM" id="e21i1" d="M235,432 L235,437 Q235,442 240,442 L436,442 Q444,442 444,450 L444,480" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#21[1] → #17 · MEM</title></path><path class="edge MEM" id="e21i2" d="M499,432 L499,480" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#21[2] → #18 · MEM</title></path><path class="edge MEM" id="e22i1" d="M472,536 L472,541 Q472,546 477,546 L616,546 Q624,546 624,554 L624,584" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#22[1] → #21 · MEM</title></path><path class="edge MEM" id="e22i2" d="M654,432 L654,584" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#22[2] → #20 · MEM</title></path><path class="edge MEM" id="e23i1" d="M624,640 L624,645 Q624,650 629,650 L794,650 Q802,650 802,658 L802,688" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#23[1] → #22 · MEM</title></path><path class="edge DATA" id="e23i2" d="M431,118 L431,130 Q431,138 439,138 L824,138 Q832,138 832,146 L832,688" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#23[2] → #5 · DATA</title></path></g><g class="edge-hits"/><g class="parser" style="opacity: 1;"/><g class="nodes"><g class="node" id="n1" data-id="1" transform="translate(24,24)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Start</tspan><tspan class="node-id"> #1</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#1 Start -Type not computed - -</title></g><g class="node" id="n3" data-id="3" transform="translate(24,68)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>$mem</tspan><tspan class="node-id"> #3/1</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#3 $mem -Projection 1 of #1 -Type not computed - -[0] → #1 MEM</title></g><g class="node" id="n5" data-id="5" transform="translate(371,68)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>new Point</tspan><tspan class="node-id"> #5</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#5 new Point -Type not computed - -[0] → — CTRL</title><circle class="port" cx="60" cy="-3" r="3" fill="white"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n6" data-id="6" transform="translate(219,68)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>#0</tspan><tspan class="node-id"> #6</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#6 #0 -Type not computed - -[0] → #1 ASSOC</title><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n7" data-id="7" transform="translate(301,172)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.x</tspan><tspan class="node-id"> #7</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#2</text><title>#7 Store p.x -MEM#2 - -[0] → — CTRL -[1] → #3 MEM -[2] → #5 DATA -[3] → #6 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n8" data-id="8" transform="translate(36,172)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.y</tspan><tspan class="node-id"> #8</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#3</text><title>#8 Store p.y -MEM#3 - -[0] → — CTRL -[1] → #3 MEM -[2] → #5 DATA -[3] → #6 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n9" data-id="9" transform="translate(53,278)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>MemMerge</tspan><tspan class="node-id"> #9</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#9 MemMerge -Type not computed - -[0] → — CTRL -[1] → #3 MEM -[2] → #7 MEM -[3] → #8 MEM</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n11" data-id="11" transform="translate(188,190)" style="opacity: 1;"><path class="box" d="M0,0H81V26H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="40.5" y="17"><tspan>True</tspan><tspan class="node-id"> #11/0</tspan></text><text class="type" text-anchor="middle" y="35" x="40.5"/><title>#11 True -Projection 0 of #0 -Type not computed - -</title></g><g class="node" id="n12" data-id="12" transform="translate(594,190)" style="opacity: 1;"><path class="box" d="M0,0H87V26H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="43.5" y="17"><tspan>False</tspan><tspan class="node-id"> #12/1</tspan></text><text class="type" text-anchor="middle" y="35" x="43.5"/><title>#12 False -Projection 1 of #0 -Type not computed - -</title></g><g class="node" id="n13" data-id="13" transform="translate(442,172)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>#3</tspan><tspan class="node-id"> #13</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#13 #3 -Type not computed - -[0] → #1 ASSOC</title><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n14" data-id="14" transform="translate(205,278)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.x</tspan><tspan class="node-id"> #14</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#2</text><title>#14 Store p.x -MEM#2 - -[0] → #11 CTRL -[1] → #7 MEM -[2] → #5 DATA -[3] → #13 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="#536477"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n15" data-id="15" transform="translate(702,172)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>#4</tspan><tspan class="node-id"> #15</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#15 #4 -Type not computed - -[0] → #1 ASSOC</title><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n16" data-id="16" transform="translate(614,278)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.x</tspan><tspan class="node-id"> #16</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#2</text><title>#16 Store p.x -MEM#2 - -[0] → #12 CTRL -[1] → #7 MEM -[2] → #5 DATA -[3] → #15 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="#536477"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n17" data-id="17" transform="translate(175,382)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>MemMerge</tspan><tspan class="node-id"> #17</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#17 MemMerge -Type not computed - -[0] → — CTRL -[1] → #9 MEM -[2] → #14 MEM</title><circle class="port" cx="30" cy="-3" r="3" fill="white"/><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><circle class="port" cx="90" cy="-3" r="3" fill="#536477"/><text class="slot" x="30" y="-10" text-anchor="middle">0</text><text class="slot" x="60" y="-10" text-anchor="middle">1</text><text class="slot" x="90" y="-10" text-anchor="middle">2</text></g><g class="node" id="n18" data-id="18" transform="translate(439,382)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>MemMerge</tspan><tspan class="node-id"> #18</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#18 MemMerge -Type not computed - -[0] → — CTRL -[1] → #9 MEM -[2] → #16 MEM</title><circle class="port" cx="30" cy="-3" r="3" fill="white"/><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><circle class="port" cx="90" cy="-3" r="3" fill="#536477"/><text class="slot" x="30" y="-10" text-anchor="middle">0</text><text class="slot" x="60" y="-10" text-anchor="middle">1</text><text class="slot" x="90" y="-10" text-anchor="middle">2</text></g><g class="node" id="n20" data-id="20" transform="translate(594,382)" style="opacity: 1;"><path class="box" d="M12,0H108L120,22L108,44H12L0,22Z" fill="#f5e4fa"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>MemPhi x</tspan><tspan class="node-id"> #20</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#2</text><title>#20 MemPhi x -MEM#2 - -[0] → — ASSOC -[1] → #14 MEM -[2] → #16 MEM</title><circle class="port" cx="0" cy="-3" r="3" fill="white"/><circle class="port" cx="40" cy="-3" r="3" fill="#536477"/><circle class="port" cx="80" cy="-3" r="3" fill="#536477"/><text class="slot" x="0" y="-10" text-anchor="middle">0</text><text class="slot" x="40" y="-10" text-anchor="middle">1</text><text class="slot" x="80" y="-10" text-anchor="middle">2</text></g><g class="node" id="n21" data-id="21" transform="translate(390,486)" style="opacity: 1;"><path class="box" d="M12,0H151L163,22L151,44H12L0,22Z" fill="#f5e4fa"/><text class="label" text-anchor="middle" x="81.5" y="18"><tspan>BulkMemPhi except x</tspan><tspan class="node-id"> #21</tspan></text><text class="type" text-anchor="middle" y="35" x="81.5"/><title>#21 BulkMemPhi except x -Type not computed - -[0] → — ASSOC -[1] → #17 MEM -[2] → #18 MEM</title><circle class="port" cx="0" cy="-3" r="3" fill="white"/><circle class="port" cx="54" cy="-3" r="3" fill="#536477"/><circle class="port" cx="109" cy="-3" r="3" fill="#536477"/><text class="slot" x="0" y="-10" text-anchor="middle">0</text><text class="slot" x="54" y="-10" text-anchor="middle">1</text><text class="slot" x="109" y="-10" text-anchor="middle">2</text></g><g class="node" id="n22" data-id="22" transform="translate(564,590)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>MemMerge</tspan><tspan class="node-id"> #22</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#22 MemMerge -Type not computed - -[0] → — CTRL -[1] → #21 MEM -[2] → #20 MEM</title><circle class="port" cx="30" cy="-3" r="3" fill="white"/><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><circle class="port" cx="90" cy="-3" r="3" fill="#536477"/><text class="slot" x="30" y="-10" text-anchor="middle">0</text><text class="slot" x="60" y="-10" text-anchor="middle">1</text><text class="slot" x="90" y="-10" text-anchor="middle">2</text></g><g class="node" id="n23" data-id="23" transform="translate(742,694)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Return</tspan><tspan class="node-id"> #23</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#23 Return -Type not computed - -[0] → — CTRL -[1] → #22 MEM -[2] → #5 DATA</title><circle class="port" cx="30" cy="-3" r="3" fill="white"/><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><circle class="port" cx="90" cy="-3" r="3" fill="#536477"/><text class="slot" x="30" y="-10" text-anchor="middle">0</text><text class="slot" x="60" y="-10" text-anchor="middle">1</text><text class="slot" x="90" y="-10" text-anchor="middle">2</text></g></g><g class="region-heads" style="opacity: 1;"/><g class="shortcuts" style="opacity: 1;"/><g class="peep-ghosts" pointer-events="none"/></g></svg> diff --git a/chapter10b/docs/example2c.gv b/chapter10b/docs/example2c.gv deleted file mode 100644 index b32d186d..00000000 --- a/chapter10b/docs/example2c.gv +++ /dev/null @@ -1,15 +0,0 @@ -digraph Memory { - // IR styles match graph/web/render.js; arrows are use -> definition. - graph [bgcolor="#fafbfc" fontname="Helvetica" nodesep=0.35 ranksep=0.55 splines=ortho]; - node [fontname="Helvetica" fontsize=12 color="#758191" fontcolor="#152330" shape=box style="rounded,filled" fillcolor="#edf3f7"]; - edge [fontname="Helvetica" fontsize=9 color="#536477" fontcolor="#364352" arrowsize=0.7 penwidth=1.5]; - - rankdir=RL; - - M [label="Prior x memory" shape=octagon style="filled" fillcolor="#dcecff"]; - L [label="Load p.x" shape=box style="rounded,filled" fillcolor="#edf3f7"]; - S [label="Store p.x" shape=octagon style="filled" fillcolor="#dcecff"]; - L -> M [color="#2867b2"]; S -> M [color="#2867b2"]; - S -> L [style=dashed,xlabel="execute load first"]; - Y [label="Store p.y: independent" shape=octagon style="filled" fillcolor="#dcecff"]; -} diff --git a/chapter10b/docs/example2c.json b/chapter10b/docs/example2c.json deleted file mode 100644 index 380815a2..00000000 --- a/chapter10b/docs/example2c.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "ver": 1, - "comp": "chapter10b/docs/example2c.svg", - "step": 1, - "roots": [13], - "scope": 0, - "nodes": [ - {"id": 1, "label": "Start", "type": null, "kind": "CTRL", "edges": [], "proj": null}, - {"id": 3, "label": "$mem", "type": null, "kind": "MEM", "edges": [{"idx": 0, "def": 1, "role": "MEM", "label": null}], "proj": {"par": 1, "idx": 1}}, - {"id": 4, "label": "arg", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 1, "role": "DATA", "label": null}], "proj": {"par": 1, "idx": 2}}, - {"id": 5, "label": "new Point", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}], "proj": null}, - {"id": 6, "label": "#0", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 1, "role": "ASSOC", "label": null}], "proj": null}, - {"id": 7, "label": "Store p.x", "type": "MEM#2", "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 6, "role": "DATA", "label": null}], "proj": null}, - {"id": 8, "label": "Store p.y", "type": "MEM#3", "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 6, "role": "DATA", "label": null}], "proj": null}, - {"id": 9, "label": "Load p.x", "type": null, "kind": "DATA", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 7, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 0, "role": "DATA", "label": null}], "proj": null}, - {"id": 10, "label": "Store p.x", "type": "MEM#2", "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 7, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 4, "role": "DATA", "label": null}], "proj": null}, - {"id": 11, "label": "Store p.y", "type": "MEM#3", "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 8, "role": "MEM", "label": null}, {"idx": 2, "def": 5, "role": "DATA", "label": null}, {"idx": 3, "def": 4, "role": "DATA", "label": null}], "proj": null}, - {"id": 12, "label": "MemMerge", "type": null, "kind": "MEM", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 3, "role": "MEM", "label": null}, {"idx": 2, "def": 10, "role": "MEM", "label": null}, {"idx": 3, "def": 11, "role": "MEM", "label": null}], "proj": null}, - {"id": 13, "label": "Return", "type": null, "kind": "CTRL", "edges": [{"idx": 0, "def": 0, "role": "CTRL", "label": null}, {"idx": 1, "def": 12, "role": "MEM", "label": null}, {"idx": 2, "def": 9, "role": "DATA", "label": null}], "proj": null} - ], - "groups": [ - ] -} diff --git a/chapter10b/docs/example2c.svg b/chapter10b/docs/example2c.svg deleted file mode 100644 index 01bbe10a..00000000 --- a/chapter10b/docs/example2c.svg +++ /dev/null @@ -1,121 +0,0 @@ -<svg aria-label="Compiler graph" width="598" height="572" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 598 572" style="font-family: sans-serif;"><style> - html, body { height:100%; margin:0; font-family:sans-serif; } - .viewer { height:100%; display:grid; grid-template-rows:auto minmax(0,1fr) auto; } - .source { padding:8px; border-bottom:1px solid #ccc; } - #program { width:min(600px,80vw); vertical-align:middle; } - #status { margin-top:4px; } - #graph { min-height:0; overflow:hidden; position:relative; background:#fafbfc; } - #elk { width:100%; height:100%; } - #graph svg { display:block; } - .tools { display:flex; flex-wrap:wrap; align-items:center; gap:14px; margin-top:8px; font-size:12px; } - .hint { color:#616c78; } - .ctrl { color:#b63838; } .mem { color:#2867b2; } .data { color:#536477; } - .edge { fill:none; stroke-width:1.5; } - .edge.CTRL { stroke-width:2; } - .edge.ASSOC { stroke-dasharray:4 4; } - .edge.PARSER { stroke-dasharray:5 4; } - .parser rect { fill:#f6f0ff; stroke:#7956a5; stroke-width:1.5; stroke-dasharray:5 4; } - .edge.selected { stroke-width:3.5; } - .edge.bundle { stroke-width:4; } - .edge.bundle.selected { stroke-width:6; } - .edge-hit { fill:none; stroke:transparent; stroke-width:12; vector-effect:non-scaling-stroke; pointer-events:stroke; cursor:pointer; } - .edge-jump { fill:transparent; pointer-events:all; cursor:pointer; } - .node { cursor:pointer; } - .box { stroke:#758191; stroke-width:1; } - .node.held .box { stroke-dasharray:5 3; } - .node.near .box { stroke:#c18221; stroke-width:2; } - .node.focus .box { stroke:#9c4900; stroke-width:3; } - .node.selected .box { stroke:#1569b9; stroke-width:3; } - .node.folded .box { stroke-width:4; } - .node.folding .box { fill:#f4ccd7; } - .fold-tag { font-size:9px; font-weight:700; fill:#963751; } - .peep-area { fill:#fff3d9; fill-opacity:.8; stroke:#c18221; stroke-width:2; pointer-events:none; } - .node.peep-edit .box { stroke:#9c4900; stroke-width:3; } - .node.error .box { stroke:#b42318; stroke-width:4; } - #event.error { color:#b42318; font-weight:600; white-space:pre-wrap; overflow-wrap:anywhere; } - .peep-ghosts { pointer-events:none; } - .region-box { stroke:#9da9b8; stroke-width:1.5; } - .fold-btn { cursor:pointer; } - .fold-btn rect { fill:white; stroke:#596674; } - .fold-btn text { font-size:14px; fill:#152330; } - .fold-btn:focus rect { stroke:#1569b9; stroke-width:2; } - .shortcut { cursor:pointer; } - .shortcut path { fill:none; stroke-width:1.5; } - .shortcut rect { fill:#fff8ec; stroke:#b63838; stroke-dasharray:3 2; } - .shortcut text { font-size:11px; fill:#783030; } - .shortcut.selected rect, .shortcut:focus rect { stroke-width:2.5; } - .label { font-size:12px; fill:#152330; font-weight:600; } - .node-id { font-size:10px; fill:#596674; font-weight:400; } - .type { font-size:11px; fill:#455768; } - .port { stroke:#536477; stroke-width:1; } - .row { stroke:#b6afcf; stroke-width:1; } - .bind { font-size:12px; fill:#152330; } - .slot { font-size:10px; fill:#364352; paint-order:stroke; stroke:#fafbfc; stroke-width:3; } - #detail { position:absolute; top:8px; right:8px; margin:0; padding:12px; max-width:320px; - max-height:45%; overflow:auto; white-space:pre-wrap; overflow-wrap:anywhere; - background:#fffffff2; border:1px solid #bac5d0; border-radius:4px; font-size:12px; } - .controls { display:flex; flex-wrap:wrap; justify-content:center; align-items:center; gap:6px; padding:6px; } - .button { color:white; background:black; font-size:20px; min-width:30px; } - .button:disabled { background:grey; } - .count { font-size:20px; min-width:35px; text-align:center; } - #N { width:6ch; } - #scrub { width:clamp(120px,35vw,600px); } - </style><defs><marker id="arrow-CTRL" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#b63838"/></marker><marker id="arrow-DATA" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#536477"/></marker><marker id="arrow-MEM" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#2867b2"/></marker><marker id="arrow-ASSOC" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#9396a3"/></marker><marker id="arrow-PARSER" viewBox="0 -4 8 8" refX="8" refY="0" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,-4L8,0L0,4Z" fill="#7956a5"/></marker></defs><rect width="100%" height="100%" fill="rgb(250, 251, 252)"/><g><g class="regions" style="opacity: 1;"/><rect class="peep-area" rx="36" style="opacity: 0;"/><g class="edges"><path class="edge ASSOC" id="e6i0" d="M267,46 C267,70 514,41 514,65" stroke="#9396a3" marker-start="url(#arrow-ASSOC)" style="opacity: 1;"><title>#6[0] → #1 · ASSOC</title></path><path class="edge MEM" id="e7i1" d="M84,118 L84,150 Q84,158 92,158 L181,158 Q186,158 186,163 L186,168" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#7[1] → #3 · MEM</title></path><path class="edge DATA" id="e7i2" d="M362,118 L362,140 Q362,148 354,148 L218,148 Q210,148 210,156 L210,168" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#7[2] → #5 · DATA</title></path><path class="edge DATA" id="e7i3" d="M514,118 L514,130 Q514,138 506,138 L242,138 Q234,138 234,146 L234,168" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#7[3] → #6 · DATA</title></path><path class="edge MEM" id="e8i1" d="M84,118 L84,150 Q84,158 92,158 L333,158 Q338,158 338,163 L338,168" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#8[1] → #3 · MEM</title></path><path class="edge DATA" id="e8i2" d="M362,118 L362,168" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#8[2] → #5 · DATA</title></path><path class="edge DATA" id="e8i3" d="M514,118 L514,130 Q514,138 506,138 L394,138 Q386,138 386,146 L386,168" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#8[3] → #6 · DATA</title></path><path class="edge MEM" id="e9i1" d="M198,224 L198,256 Q198,264 206,264 L439,264 Q447,264 447,272 L447,284" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#9[1] → #7 · MEM</title></path><path class="edge DATA" id="e9i2" d="M362,118 L362,140 Q362,148 370,148 L463,148 Q471,148 471,156 L471,284" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#9[2] → #5 · DATA</title></path><path class="edge MEM" id="e10i1" d="M198,224 L198,256 Q198,264 190,264 L151,264 Q143,264 143,272 L143,284" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#10[1] → #7 · MEM</title></path><path class="edge DATA" id="e10i2" d="M362,118 L362,140 Q362,148 354,148 L124,148 Q116,148 116,156 L116,266 Q116,274 124,274 L162,274 Q167,274 167,279 L167,284" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#10[2] → #5 · DATA</title></path><path class="edge DATA" id="e10i3" d="M204,118 L204,123 Q204,128 199,128 L135,128 Q127,128 127,136 L127,226 Q127,234 135,234 L183,234 Q191,234 191,242 L191,284" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#10[3] → #4 · DATA</title></path><path class="edge MEM" id="e11i1" d="M350,224 L350,229 Q350,234 345,234 L303,234 Q295,234 295,242 L295,284" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#11[1] → #8 · MEM</title></path><path class="edge DATA" id="e11i2" d="M362,118 L362,140 Q362,148 370,148 L412,148 Q420,148 420,156 L420,236 Q420,244 412,244 L327,244 Q319,244 319,252 L319,284" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#11[2] → #5 · DATA</title></path><path class="edge DATA" id="e11i3" d="M204,118 L204,123 Q204,128 209,128 L423,128 Q431,128 431,136 L431,246 Q431,254 423,254 L351,254 Q343,254 343,262 L343,284" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#11[3] → #4 · DATA</title></path><path class="edge MEM" id="e12i1" d="M84,118 L84,342 Q84,350 92,350 L123,350 Q131,350 131,358 L131,388" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#12[1] → #3 · MEM</title></path><path class="edge MEM" id="e12i2" d="M155,340 L155,388" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#12[2] → #10 · MEM</title></path><path class="edge MEM" id="e12i3" d="M307,340 L307,345 Q307,350 302,350 L187,350 Q179,350 179,358 L179,388" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#12[3] → #11 · MEM</title></path><path class="edge MEM" id="e13i1" d="M143,444 L143,449 Q143,454 148,454 L421,454 Q429,454 429,462 L429,492" stroke="#2867b2" marker-start="url(#arrow-MEM)" style="opacity: 1;"><title>#13[1] → #12 · MEM</title></path><path class="edge DATA" id="e13i2" d="M459,340 L459,492" stroke="#536477" marker-start="url(#arrow-DATA)" style="opacity: 1;"><title>#13[2] → #9 · DATA</title></path></g><g class="edge-hits"/><g class="parser" style="opacity: 1;"/><g class="nodes"><g class="node" id="n1" data-id="1" transform="translate(24,24)" style="opacity: 1;"><path class="box" d="M0,0H240V44H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="120" y="18"><tspan>Start</tspan><tspan class="node-id"> #1</tspan></text><text class="type" text-anchor="middle" y="35" x="120"/><title>#1 Start -Type not computed - -</title></g><g class="node" id="n3" data-id="3" transform="translate(24,68)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>$mem</tspan><tspan class="node-id"> #3/1</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#3 $mem -Projection 1 of #1 -Type not computed - -[0] → #1 MEM</title></g><g class="node" id="n4" data-id="4" transform="translate(144,68)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>arg</tspan><tspan class="node-id"> #4/2</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#4 arg -Projection 2 of #1 -Type not computed - -[0] → #1 DATA</title></g><g class="node" id="n5" data-id="5" transform="translate(302,68)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>new Point</tspan><tspan class="node-id"> #5</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#5 new Point -Type not computed - -[0] → — CTRL</title><circle class="port" cx="60" cy="-3" r="3" fill="white"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n6" data-id="6" transform="translate(454,68)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>#0</tspan><tspan class="node-id"> #6</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#6 #0 -Type not computed - -[0] → #1 ASSOC</title><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><text class="slot" x="60" y="-10" text-anchor="middle">0</text></g><g class="node" id="n7" data-id="7" transform="translate(138,174)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.x</tspan><tspan class="node-id"> #7</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#2</text><title>#7 Store p.x -MEM#2 - -[0] → — CTRL -[1] → #3 MEM -[2] → #5 DATA -[3] → #6 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n8" data-id="8" transform="translate(290,174)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.y</tspan><tspan class="node-id"> #8</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#3</text><title>#8 Store p.y -MEM#3 - -[0] → — CTRL -[1] → #3 MEM -[2] → #5 DATA -[3] → #6 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n9" data-id="9" transform="translate(399,290)" style="opacity: 1;"><path class="box" d="M14,0H106Q120,0 120,14V30Q120,44 106,44H14Q0,44 0,30V14Q0,0 14,0Z" fill="#edf3f7"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Load p.x</tspan><tspan class="node-id"> #9</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#9 Load p.x -Type not computed - -[0] → — CTRL -[1] → #7 MEM -[2] → #5 DATA -[3] → — DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="white"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n10" data-id="10" transform="translate(95,290)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.x</tspan><tspan class="node-id"> #10</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#2</text><title>#10 Store p.x -MEM#2 - -[0] → — CTRL -[1] → #7 MEM -[2] → #5 DATA -[3] → #4 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n11" data-id="11" transform="translate(247,290)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Store p.y</tspan><tspan class="node-id"> #11</tspan></text><text class="type" text-anchor="middle" y="35" x="60">MEM#3</text><title>#11 Store p.y -MEM#3 - -[0] → — CTRL -[1] → #8 MEM -[2] → #5 DATA -[3] → #4 DATA</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n12" data-id="12" transform="translate(83,394)" style="opacity: 1;"><path class="box" d="M10,0H110L120,10V34L110,44H10L0,34V10Z" fill="#dcecff"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>MemMerge</tspan><tspan class="node-id"> #12</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#12 MemMerge -Type not computed - -[0] → — CTRL -[1] → #3 MEM -[2] → #10 MEM -[3] → #11 MEM</title><circle class="port" cx="24" cy="-3" r="3" fill="white"/><circle class="port" cx="48" cy="-3" r="3" fill="#536477"/><circle class="port" cx="72" cy="-3" r="3" fill="#536477"/><circle class="port" cx="96" cy="-3" r="3" fill="#536477"/><text class="slot" x="24" y="-10" text-anchor="middle">0</text><text class="slot" x="48" y="-10" text-anchor="middle">1</text><text class="slot" x="72" y="-10" text-anchor="middle">2</text><text class="slot" x="96" y="-10" text-anchor="middle">3</text></g><g class="node" id="n13" data-id="13" transform="translate(369,498)" style="opacity: 1;"><path class="box" d="M0,0H120V44H0Z" fill="#fff1c4"/><text class="label" text-anchor="middle" x="60" y="18"><tspan>Return</tspan><tspan class="node-id"> #13</tspan></text><text class="type" text-anchor="middle" y="35" x="60"/><title>#13 Return -Type not computed - -[0] → — CTRL -[1] → #12 MEM -[2] → #9 DATA</title><circle class="port" cx="30" cy="-3" r="3" fill="white"/><circle class="port" cx="60" cy="-3" r="3" fill="#536477"/><circle class="port" cx="90" cy="-3" r="3" fill="#536477"/><text class="slot" x="30" y="-10" text-anchor="middle">0</text><text class="slot" x="60" y="-10" text-anchor="middle">1</text><text class="slot" x="90" y="-10" text-anchor="middle">2</text></g></g><g class="region-heads" style="opacity: 1;"/><g class="shortcuts" style="opacity: 1;"/><g class="peep-ghosts" pointer-events="none"/></g></svg> diff --git a/chapter10b/docs/lattice.gv b/chapter10b/docs/lattice.gv deleted file mode 100644 index 93d99dd8..00000000 --- a/chapter10b/docs/lattice.gv +++ /dev/null @@ -1,133 +0,0 @@ -digraph Lattice { - rankdir=TB; - newrank=true; - // Preserve the same-rank ordering edges through cluster layout. - remincross=false; - nodesep=0.22; - ranksep=0.65; - node [shape=ellipse, style=filled, fontname="DejaVu Sans", fontsize=13]; - edge [color="#555555", arrowsize=0.6]; - - // These arrows are lattice-order edges, not use/definition edges. - TOP [label="⊤", fillcolor=black, fontcolor=white]; - BOT [label="⊥", fillcolor=black, fontcolor=white]; - - subgraph cluster_control { - label="Control"; fontname="Arial"; color="#cccccc"; - node [fillcolor="#ffff00"]; - XCTRL [label="⊤:ctrl"]; - CTRL [label="⊥:ctrl"]; - XCTRL -> CTRL; - } - - subgraph cluster_integer { - label="Integer"; fontname="Arial"; color="#cccccc"; - node [fillcolor="#add8e6"]; - INT_TOP [label="⊤:int"]; - INT_BOT [label="⊥:int"]; - INT_NEG [label="… −2, −1"]; - INT_ZERO [label="0"]; - INT_POS [label="1, 2, …"]; - {rank=same; INT_NEG; INT_ZERO; INT_POS;} - INT_NEG -> INT_ZERO -> INT_POS [style=invis]; - INT_TOP -> {INT_NEG INT_ZERO INT_POS}; - {INT_NEG INT_ZERO INT_POS} -> INT_BOT; - } - - subgraph cluster_pointer { - label="Pointer = nullability × struct type"; - fontname="Arial"; color="#cccccc"; - node [fillcolor="#008000", fontcolor=white]; - PTR_TOP [label="⊤:ptr\n[*⊤:struct]"]; - PTR_BOT [label="⊥:ptr\n[*⊥:struct?]"]; - PTR_NULL [label="null"]; - PTR_ANY [label="*⊥:struct\n[ptr any struct]"]; - PTR_PERSON [label="*Person"]; - PTR_S1 [label="*s1"]; - PTR_MORE [label="*s2, …"]; - PTR_PERSON_NIL [label="*Person?"]; - PTR_S1_NIL [label="*s1?"]; - PTR_MORE_NIL [label="*s2?, …"]; - {rank=same; PTR_PERSON; PTR_S1; PTR_MORE; PTR_NULL;} - {rank=same; PTR_ANY; PTR_PERSON_NIL; PTR_S1_NIL; PTR_MORE_NIL;} - PTR_PERSON -> PTR_S1 -> PTR_MORE -> PTR_NULL [style=invis]; - PTR_ANY -> PTR_PERSON_NIL -> PTR_S1_NIL -> PTR_MORE_NIL [style=invis]; - PTR_TOP -> {PTR_PERSON PTR_S1 PTR_MORE PTR_NULL}; - {PTR_PERSON PTR_S1 PTR_MORE} -> PTR_ANY; - PTR_PERSON -> PTR_PERSON_NIL; - PTR_S1 -> PTR_S1_NIL; - PTR_MORE -> PTR_MORE_NIL; - PTR_NULL -> {PTR_PERSON_NIL PTR_S1_NIL PTR_MORE_NIL}; - {PTR_ANY PTR_PERSON_NIL PTR_S1_NIL PTR_MORE_NIL} -> PTR_BOT; - } - - subgraph cluster_struct { - label="Struct\nnamed collection of named scalar types"; - fontname="Arial"; color="#cccccc"; - node [fillcolor="#90ee90"]; - STRUCT_TOP [label="⊤:struct\n[struct top]"]; - STRUCT_BOT [label="⊥:struct\n[struct bottom]"]; - STRUCT_PERSON [label="Person\nage: int", shape=box]; - STRUCT_S1 [label="s1\nx: int", shape=box]; - STRUCT_S2 [label="s2\nx: int, y: int", shape=box]; - STRUCT_MORE [label="…", shape=box]; - {rank=same; STRUCT_PERSON; STRUCT_S1; STRUCT_S2; STRUCT_MORE;} - STRUCT_PERSON -> STRUCT_S1 -> STRUCT_S2 -> STRUCT_MORE [style=invis]; - STRUCT_TOP -> {STRUCT_PERSON STRUCT_S1 STRUCT_S2 STRUCT_MORE}; - {STRUCT_PERSON STRUCT_S1 STRUCT_S2 STRUCT_MORE} -> STRUCT_BOT; - } - - subgraph cluster_memory { - label="Memory\nprecise alias slices"; fontname="Arial"; color="#cccccc"; - node [fillcolor="#00008b", fontcolor=white]; - MEM_TOP [label="⊤:mem"]; - MEM_BOT [label="⊥:mem"]; - MEM_ALIAS2 [label="MEM#2"]; - MEM_ALIAS3 [label="MEM#3"]; - MEM_MORE [label="…"]; - {rank=same; MEM_ALIAS2; MEM_ALIAS3; MEM_MORE;} - MEM_ALIAS2 -> MEM_ALIAS3 -> MEM_MORE [style=invis]; - MEM_TOP -> {MEM_ALIAS2 MEM_ALIAS3 MEM_MORE}; - {MEM_ALIAS2 MEM_ALIAS3 MEM_MORE} -> MEM_BOT; - } - - subgraph cluster_tuple { - label="Tuple\ncollection of types"; - fontname="Arial"; color="#cccccc"; - node [fillcolor="#ffc0cb"]; - TUPLE_TOP [label="⊤:tuple"]; - TUPLE_BOT [label="⊥:tuple"]; - // Each black element stands for a recursively nested type lattice. - TUPLE1 [shape=plain, label=< - <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="4"> - <TR><TD BGCOLOR="#ffc0cb">tuple</TD></TR> - <TR><TD BGCOLOR="black"><FONT COLOR="white">type</FONT></TD></TR> - </TABLE> - >]; - TUPLE2 [shape=plain, label=< - <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="4"> - <TR><TD BGCOLOR="#ffc0cb">tuple</TD></TR> - <TR><TD BGCOLOR="black"><FONT COLOR="white">type</FONT></TD></TR> - <TR><TD BGCOLOR="black"><FONT COLOR="white">type</FONT></TD></TR> - </TABLE> - >]; - TUPLEN [shape=plain, label=< - <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="4"> - <TR><TD BGCOLOR="#ffc0cb">tuple</TD></TR> - <TR><TD BGCOLOR="black"><FONT COLOR="white">type</FONT></TD></TR> - <TR><TD BGCOLOR="black"><FONT COLOR="white">…</FONT></TD></TR> - <TR><TD BGCOLOR="black"><FONT COLOR="white">type</FONT></TD></TR> - </TABLE> - >]; - {rank=same; TUPLE1; TUPLE2; TUPLEN;} - TUPLE1 -> TUPLE2 -> TUPLEN [style=invis]; - TUPLE_TOP -> {TUPLE1 TUPLE2 TUPLEN}; - {TUPLE1 TUPLE2 TUPLEN} -> TUPLE_BOT; - } - - TOP -> {XCTRL INT_TOP PTR_TOP STRUCT_TOP MEM_TOP TUPLE_TOP}; - {CTRL INT_BOT PTR_BOT STRUCT_BOT MEM_BOT TUPLE_BOT} -> BOT; - {rank=same; XCTRL; INT_TOP; PTR_TOP; STRUCT_TOP; MEM_TOP; TUPLE_TOP;} - {rank=same; CTRL; INT_BOT; PTR_BOT; STRUCT_BOT; MEM_BOT; TUPLE_BOT;} - XCTRL -> INT_TOP -> PTR_TOP -> STRUCT_TOP -> MEM_TOP -> TUPLE_TOP [style=invis]; -} diff --git a/chapter10b/docs/lattice.svg b/chapter10b/docs/lattice.svg deleted file mode 100644 index 8d2e2875..00000000 --- a/chapter10b/docs/lattice.svg +++ /dev/null @@ -1,644 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" - "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> -<!-- Generated by graphviz version 12.2.0 (20241103.1931) - --> -<!-- Title: Lattice Pages: 1 --> -<svg width="1727pt" height="603pt" - viewBox="0.00 0.00 1727.00 603.45" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> -<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 599.45)"> -<title>Lattice</title> -<polygon fill="white" stroke="none" points="-4,4 -4,-599.45 1723,-599.45 1723,4 -4,4"/> -<g id="clust1" class="cluster"> -<title>cluster_control</title> -<polygon fill="none" stroke="#cccccc" points="8,-85.99 8,-524.71 98,-524.71 98,-85.99 8,-85.99"/> -<text text-anchor="middle" x="53" y="-507.41" font-family="Arial" font-size="14.00">Control</text> -</g> -<g id="clust2" class="cluster"> -<title>cluster_integer</title> -<polygon fill="none" stroke="#cccccc" points="106,-85.99 106,-524.71 404,-524.71 404,-85.99 106,-85.99"/> -<text text-anchor="middle" x="255" y="-507.41" font-family="Arial" font-size="14.00">Integer</text> -</g> -<g id="clust6" class="cluster"> -<title>cluster_pointer</title> -<polygon fill="none" stroke="#cccccc" points="412,-75 412,-535.7 893,-535.7 893,-75 412,-75"/> -<text text-anchor="middle" x="652.5" y="-518.4" font-family="Arial" font-size="14.00">Pointer = nullability × struct type</text> -</g> -<g id="clust13" class="cluster"> -<title>cluster_struct</title> -<polygon fill="none" stroke="#cccccc" points="901,-75 901,-551.45 1233,-551.45 1233,-75 901,-75"/> -<text text-anchor="middle" x="1067" y="-534.15" font-family="Arial" font-size="14.00">Struct</text> -<text text-anchor="middle" x="1067" y="-518.4" font-family="Arial" font-size="14.00">named collection of named scalar types</text> -</g> -<g id="clust17" class="cluster"> -<title>cluster_memory</title> -<polygon fill="none" stroke="#cccccc" points="1241,-85.99 1241,-540.46 1523,-540.46 1523,-85.99 1241,-85.99"/> -<text text-anchor="middle" x="1382" y="-523.16" font-family="Arial" font-size="14.00">Memory</text> -<text text-anchor="middle" x="1382" y="-507.41" font-family="Arial" font-size="14.00">precise alias slices</text> -</g> -<g id="clust21" class="cluster"> -<title>cluster_tuple</title> -<polygon fill="none" stroke="#cccccc" points="1531,-85.99 1531,-540.46 1711,-540.46 1711,-85.99 1531,-85.99"/> -<text text-anchor="middle" x="1621" y="-523.16" font-family="Arial" font-size="14.00">Tuple</text> -<text text-anchor="middle" x="1621" y="-507.41" font-family="Arial" font-size="14.00">collection of types</text> -</g> -<!-- TOP --> -<g id="node1" class="node"> -<title>TOP</title> -<ellipse fill="black" stroke="black" cx="887" cy="-577.45" rx="27" ry="18"/> -<text text-anchor="middle" x="887" y="-573.35" font-family="DejaVu Sans" font-size="13.00" fill="white">⊤</text> -</g> -<!-- XCTRL --> -<g id="node3" class="node"> -<title>XCTRL</title> -<ellipse fill="#ffff00" stroke="black" cx="53" cy="-474.96" rx="36.51" ry="18"/> -<text text-anchor="middle" x="53" y="-470.86" font-family="DejaVu Sans" font-size="13.00">⊤:ctrl</text> -</g> -<!-- TOP->XCTRL --> -<g id="edge60" class="edge"> -<title>TOP->XCTRL</title> -<path fill="none" stroke="#555555" d="M859.92,-576.29C725.56,-575.4 135.66,-570.43 102,-551.45 82.17,-540.27 69.05,-517.37 61.41,-499.71"/> -<polygon fill="#555555" stroke="#555555" points="63.45,-499.15 59.23,-494.39 59.57,-500.74 63.45,-499.15"/> -</g> -<!-- INT_TOP --> -<g id="node5" class="node"> -<title>INT_TOP</title> -<ellipse fill="#add8e6" stroke="black" cx="353" cy="-474.96" rx="33.44" ry="18"/> -<text text-anchor="middle" x="353" y="-470.86" font-family="DejaVu Sans" font-size="13.00">⊤:int</text> -</g> -<!-- TOP->INT_TOP --> -<g id="edge61" class="edge"> -<title>TOP->INT_TOP</title> -<path fill="none" stroke="#555555" d="M859.8,-576.38C764.27,-575.97 447.72,-572.97 408,-551.45 387.23,-540.19 372.29,-517.31 363.27,-499.67"/> -<polygon fill="#555555" stroke="#555555" points="365.18,-498.79 360.66,-494.32 361.41,-500.63 365.18,-498.79"/> -</g> -<!-- PTR_TOP --> -<g id="node10" class="node"> -<title>PTR_TOP</title> -<ellipse fill="#008000" stroke="black" cx="715" cy="-474.96" rx="61.7" ry="28.99"/> -<text text-anchor="middle" x="715" y="-479.11" font-family="DejaVu Sans" font-size="13.00" fill="white">⊤:ptr</text> -<text text-anchor="middle" x="715" y="-462.61" font-family="DejaVu Sans" font-size="13.00" fill="white">[*⊤:struct]</text> -</g> -<!-- TOP->PTR_TOP --> -<g id="edge62" class="edge"> -<title>TOP->PTR_TOP</title> -<path fill="none" stroke="#555555" d="M867.27,-564.92C841.1,-549.63 794.17,-522.21 759.3,-501.84"/> -<polygon fill="#555555" stroke="#555555" points="760.48,-500.1 754.24,-498.88 758.36,-503.72 760.48,-500.1"/> -</g> -<!-- STRUCT_TOP --> -<g id="node20" class="node"> -<title>STRUCT_TOP</title> -<ellipse fill="#90ee90" stroke="black" cx="1020" cy="-474.96" rx="64.35" ry="28.99"/> -<text text-anchor="middle" x="1020" y="-479.11" font-family="DejaVu Sans" font-size="13.00">⊤:struct</text> -<text text-anchor="middle" x="1020" y="-462.61" font-family="DejaVu Sans" font-size="13.00">[struct top]</text> -</g> -<!-- TOP->STRUCT_TOP --> -<g id="edge63" class="edge"> -<title>TOP->STRUCT_TOP</title> -<path fill="none" stroke="#555555" d="M904.39,-563.31C923.88,-548.58 956.09,-524.25 981.56,-505"/> -<polygon fill="#555555" stroke="#555555" points="982.82,-506.68 986.34,-501.39 980.29,-503.33 982.82,-506.68"/> -</g> -<!-- MEM_TOP --> -<g id="node26" class="node"> -<title>MEM_TOP</title> -<ellipse fill="#00008b" stroke="black" cx="1347" cy="-474.96" rx="44.7" ry="18"/> -<text text-anchor="middle" x="1347" y="-470.86" font-family="DejaVu Sans" font-size="13.00" fill="white">⊤:mem</text> -</g> -<!-- TOP->MEM_TOP --> -<g id="edge64" class="edge"> -<title>TOP->MEM_TOP</title> -<path fill="none" stroke="#555555" d="M914.28,-576.34C985.84,-575.75 1177.55,-572.23 1237,-551.45 1270.57,-539.71 1303.45,-514.89 1324.38,-496.91"/> -<polygon fill="#555555" stroke="#555555" points="1325.69,-498.56 1328.82,-493.03 1322.92,-495.39 1325.69,-498.56"/> -</g> -<!-- TUPLE_TOP --> -<g id="node31" class="node"> -<title>TUPLE_TOP</title> -<ellipse fill="#ffc0cb" stroke="black" cx="1584" cy="-474.96" rx="44.7" ry="18"/> -<text text-anchor="middle" x="1584" y="-470.86" font-family="DejaVu Sans" font-size="13.00">⊤:tuple</text> -</g> -<!-- TOP->TUPLE_TOP --> -<g id="edge65" class="edge"> -<title>TOP->TUPLE_TOP</title> -<path fill="none" stroke="#555555" d="M914.19,-576.75C1029.19,-577.83 1472.18,-580.1 1527,-551.45 1548.39,-540.27 1564,-517.05 1573.43,-499.3"/> -<polygon fill="#555555" stroke="#555555" points="1575.08,-500.68 1575.93,-494.38 1571.33,-498.78 1575.08,-500.68"/> -</g> -<!-- BOT --> -<g id="node2" class="node"> -<title>BOT</title> -<ellipse fill="black" stroke="black" cx="884" cy="-18" rx="27" ry="18"/> -<text text-anchor="middle" x="884" y="-13.9" font-family="DejaVu Sans" font-size="13.00" fill="white">⊥</text> -</g> -<!-- CTRL --> -<g id="node4" class="node"> -<title>CTRL</title> -<ellipse fill="#ffff00" stroke="black" cx="53" cy="-111.99" rx="36.51" ry="18"/> -<text text-anchor="middle" x="53" y="-107.89" font-family="DejaVu Sans" font-size="13.00">⊥:ctrl</text> -</g> -<!-- XCTRL->CTRL --> -<g id="edge1" class="edge"> -<title>XCTRL->CTRL</title> -<path fill="none" stroke="#555555" d="M53,-456.55C53,-397.7 53,-206.04 53,-137.58"/> -<polygon fill="#555555" stroke="#555555" points="55.1,-137.74 53,-131.74 50.9,-137.74 55.1,-137.74"/> -</g> -<!-- XCTRL->INT_TOP --> -<!-- CTRL->BOT --> -<g id="edge66" class="edge"> -<title>CTRL->BOT</title> -<path fill="none" stroke="#555555" d="M69.29,-95.39C78.22,-87.83 89.91,-79.45 102,-75 242.26,-23.4 717.31,-19.12 849.57,-18.95"/> -<polygon fill="#555555" stroke="#555555" points="849.19,-21.05 855.19,-18.94 849.18,-16.85 849.19,-21.05"/> -</g> -<!-- INT_NEG --> -<g id="node7" class="node"> -<title>INT_NEG</title> -<ellipse fill="#add8e6" stroke="black" cx="169" cy="-345.97" rx="55.45" ry="18"/> -<text text-anchor="middle" x="169" y="-341.87" font-family="DejaVu Sans" font-size="13.00">… −2, −1</text> -</g> -<!-- INT_TOP->INT_NEG --> -<g id="edge4" class="edge"> -<title>INT_TOP->INT_NEG</title> -<path fill="none" stroke="#555555" d="M330.56,-461.28C305.82,-447.02 265.13,-422.74 232,-398.97 218.63,-389.37 204.44,-377.8 192.92,-368"/> -<polygon fill="#555555" stroke="#555555" points="194.57,-366.65 188.64,-364.34 191.83,-369.84 194.57,-366.65"/> -</g> -<!-- INT_ZERO --> -<g id="node8" class="node"> -<title>INT_ZERO</title> -<ellipse fill="#add8e6" stroke="black" cx="267" cy="-345.97" rx="27" ry="18"/> -<text text-anchor="middle" x="267" y="-341.87" font-family="DejaVu Sans" font-size="13.00">0</text> -</g> -<!-- INT_TOP->INT_ZERO --> -<g id="edge5" class="edge"> -<title>INT_TOP->INT_ZERO</title> -<path fill="none" stroke="#555555" d="M341.83,-457.59C331.49,-442.41 315.68,-419.18 302,-398.97 295.36,-389.15 288.04,-378.28 281.81,-369.03"/> -<polygon fill="#555555" stroke="#555555" points="283.64,-367.97 278.55,-364.17 280.15,-370.32 283.64,-367.97"/> -</g> -<!-- INT_POS --> -<g id="node9" class="node"> -<title>INT_POS</title> -<ellipse fill="#add8e6" stroke="black" cx="353" cy="-345.97" rx="43.16" ry="18"/> -<text text-anchor="middle" x="353" y="-341.87" font-family="DejaVu Sans" font-size="13.00">1, 2, …</text> -</g> -<!-- INT_TOP->INT_POS --> -<g id="edge6" class="edge"> -<title>INT_TOP->INT_POS</title> -<path fill="none" stroke="#555555" d="M353,-456.57C353,-434.53 353,-396.41 353,-371.44"/> -<polygon fill="#555555" stroke="#555555" points="355.1,-371.66 353,-365.66 350.9,-371.66 355.1,-371.66"/> -</g> -<!-- INT_TOP->PTR_TOP --> -<!-- INT_BOT --> -<g id="node6" class="node"> -<title>INT_BOT</title> -<ellipse fill="#add8e6" stroke="black" cx="289" cy="-111.99" rx="33.44" ry="18"/> -<text text-anchor="middle" x="289" y="-107.89" font-family="DejaVu Sans" font-size="13.00">⊥:int</text> -</g> -<!-- INT_BOT->BOT --> -<g id="edge67" class="edge"> -<title>INT_BOT->BOT</title> -<path fill="none" stroke="#555555" d="M316.06,-101.31C339.95,-93.13 375.88,-81.69 408,-75 571.35,-40.97 770.86,-25.89 849.65,-20.95"/> -<polygon fill="#555555" stroke="#555555" points="849.52,-23.07 855.38,-20.6 849.26,-18.87 849.52,-23.07"/> -</g> -<!-- INT_NEG->INT_BOT --> -<g id="edge7" class="edge"> -<title>INT_NEG->INT_BOT</title> -<path fill="none" stroke="#555555" d="M177.82,-327.91C199.03,-286.92 252.87,-182.84 276.99,-136.21"/> -<polygon fill="#555555" stroke="#555555" points="278.74,-137.4 279.63,-131.11 275.01,-135.47 278.74,-137.4"/> -</g> -<!-- INT_NEG->INT_ZERO --> -<!-- INT_ZERO->INT_BOT --> -<g id="edge8" class="edge"> -<title>INT_ZERO->INT_BOT</title> -<path fill="none" stroke="#555555" d="M268.65,-327.53C272.53,-286.71 282.19,-184.82 286.66,-137.66"/> -<polygon fill="#555555" stroke="#555555" points="288.74,-137.99 287.21,-131.82 284.56,-137.59 288.74,-137.99"/> -</g> -<!-- INT_ZERO->INT_POS --> -<!-- INT_POS->INT_BOT --> -<g id="edge9" class="edge"> -<title>INT_POS->INT_BOT</title> -<path fill="none" stroke="#555555" d="M348.29,-327.91C337.06,-287.19 308.65,-184.2 295.66,-137.13"/> -<polygon fill="#555555" stroke="#555555" points="297.74,-136.76 294.12,-131.53 293.69,-137.88 297.74,-136.76"/> -</g> -<!-- PTR_NULL --> -<g id="node12" class="node"> -<title>PTR_NULL</title> -<ellipse fill="#008000" stroke="black" cx="799" cy="-345.97" rx="27.3" ry="18"/> -<text text-anchor="middle" x="799" y="-341.87" font-family="DejaVu Sans" font-size="13.00" fill="white">null</text> -</g> -<!-- PTR_TOP->PTR_NULL --> -<g id="edge16" class="edge"> -<title>PTR_TOP->PTR_NULL</title> -<path fill="none" stroke="#555555" d="M732.81,-447.03C748.16,-423.83 770.03,-390.77 784.37,-369.09"/> -<polygon fill="#555555" stroke="#555555" points="785.98,-370.45 787.54,-364.29 782.48,-368.13 785.98,-370.45"/> -</g> -<!-- PTR_PERSON --> -<g id="node14" class="node"> -<title>PTR_PERSON</title> -<ellipse fill="#008000" stroke="black" cx="542" cy="-345.97" rx="45.72" ry="18"/> -<text text-anchor="middle" x="542" y="-341.87" font-family="DejaVu Sans" font-size="13.00" fill="white">*Person</text> -</g> -<!-- PTR_TOP->PTR_PERSON --> -<g id="edge17" class="edge"> -<title>PTR_TOP->PTR_PERSON</title> -<path fill="none" stroke="#555555" d="M675.88,-452.05C651.99,-438.01 621.28,-418.77 596,-398.97 584.24,-389.76 572.18,-378.36 562.44,-368.58"/> -<polygon fill="#555555" stroke="#555555" points="564.05,-367.22 558.35,-364.42 561.06,-370.17 564.05,-367.22"/> -</g> -<!-- PTR_S1 --> -<g id="node15" class="node"> -<title>PTR_S1</title> -<ellipse fill="#008000" stroke="black" cx="631" cy="-345.97" rx="27" ry="18"/> -<text text-anchor="middle" x="631" y="-341.87" font-family="DejaVu Sans" font-size="13.00" fill="white">*s1</text> -</g> -<!-- PTR_TOP->PTR_S1 --> -<g id="edge18" class="edge"> -<title>PTR_TOP->PTR_S1</title> -<path fill="none" stroke="#555555" d="M697.19,-447.03C681.84,-423.83 659.97,-390.77 645.63,-369.09"/> -<polygon fill="#555555" stroke="#555555" points="647.52,-368.13 642.46,-364.29 644.02,-370.45 647.52,-368.13"/> -</g> -<!-- PTR_MORE --> -<g id="node16" class="node"> -<title>PTR_MORE</title> -<ellipse fill="#008000" stroke="black" cx="715" cy="-345.97" rx="40.6" ry="18"/> -<text text-anchor="middle" x="715" y="-341.87" font-family="DejaVu Sans" font-size="13.00" fill="white">*s2, …</text> -</g> -<!-- PTR_TOP->PTR_MORE --> -<g id="edge19" class="edge"> -<title>PTR_TOP->PTR_MORE</title> -<path fill="none" stroke="#555555" d="M715,-445.77C715,-423.52 715,-392.77 715,-371.51"/> -<polygon fill="#555555" stroke="#555555" points="717.1,-371.66 715,-365.66 712.9,-371.66 717.1,-371.66"/> -</g> -<!-- PTR_TOP->STRUCT_TOP --> -<!-- PTR_BOT --> -<g id="node11" class="node"> -<title>PTR_BOT</title> -<ellipse fill="#008000" stroke="black" cx="748" cy="-111.99" rx="66.47" ry="28.99"/> -<text text-anchor="middle" x="748" y="-116.14" font-family="DejaVu Sans" font-size="13.00" fill="white">⊥:ptr</text> -<text text-anchor="middle" x="748" y="-99.64" font-family="DejaVu Sans" font-size="13.00" fill="white">[*⊥:struct?]</text> -</g> -<!-- PTR_BOT->BOT --> -<g id="edge68" class="edge"> -<title>PTR_BOT->BOT</title> -<path fill="none" stroke="#555555" d="M783.38,-87.06C807.3,-70.88 838.29,-49.92 859.52,-35.56"/> -<polygon fill="#555555" stroke="#555555" points="860.46,-37.46 864.25,-32.36 858.1,-33.98 860.46,-37.46"/> -</g> -<!-- PTR_PERSON_NIL --> -<g id="node17" class="node"> -<title>PTR_PERSON_NIL</title> -<ellipse fill="#008000" stroke="black" cx="651" cy="-216.97" rx="50.33" ry="18"/> -<text text-anchor="middle" x="651" y="-212.87" font-family="DejaVu Sans" font-size="13.00" fill="white">*Person?</text> -</g> -<!-- PTR_NULL->PTR_PERSON_NIL --> -<g id="edge26" class="edge"> -<title>PTR_NULL->PTR_PERSON_NIL</title> -<path fill="none" stroke="#555555" d="M790.34,-328.75C783.99,-317.83 774.65,-303.55 764,-292.97 740.64,-269.76 709.08,-249.53 685.25,-235.95"/> -<polygon fill="#555555" stroke="#555555" points="686.33,-234.14 680.07,-233.04 684.27,-237.8 686.33,-234.14"/> -</g> -<!-- PTR_S1_NIL --> -<g id="node18" class="node"> -<title>PTR_S1_NIL</title> -<ellipse fill="#008000" stroke="black" cx="748" cy="-216.97" rx="30.37" ry="18"/> -<text text-anchor="middle" x="748" y="-212.87" font-family="DejaVu Sans" font-size="13.00" fill="white">*s1?</text> -</g> -<!-- PTR_NULL->PTR_S1_NIL --> -<g id="edge27" class="edge"> -<title>PTR_NULL->PTR_S1_NIL</title> -<path fill="none" stroke="#555555" d="M792.23,-328.1C783.31,-305.9 767.59,-266.75 757.49,-241.6"/> -<polygon fill="#555555" stroke="#555555" points="759.55,-241.1 755.36,-236.31 755.65,-242.66 759.55,-241.1"/> -</g> -<!-- PTR_MORE_NIL --> -<g id="node19" class="node"> -<title>PTR_MORE_NIL</title> -<ellipse fill="#008000" stroke="black" cx="840" cy="-216.97" rx="45.21" ry="18"/> -<text text-anchor="middle" x="840" y="-212.87" font-family="DejaVu Sans" font-size="13.00" fill="white">*s2?, …</text> -</g> -<!-- PTR_NULL->PTR_MORE_NIL --> -<g id="edge28" class="edge"> -<title>PTR_NULL->PTR_MORE_NIL</title> -<path fill="none" stroke="#555555" d="M804.53,-327.84C811.65,-305.78 824.07,-267.3 832.17,-242.24"/> -<polygon fill="#555555" stroke="#555555" points="834.12,-243.03 833.96,-236.68 830.12,-241.74 834.12,-243.03"/> -</g> -<!-- PTR_ANY --> -<g id="node13" class="node"> -<title>PTR_ANY</title> -<ellipse fill="#008000" stroke="black" cx="502" cy="-216.97" rx="82.38" ry="28.99"/> -<text text-anchor="middle" x="502" y="-221.12" font-family="DejaVu Sans" font-size="13.00" fill="white">*⊥:struct</text> -<text text-anchor="middle" x="502" y="-204.62" font-family="DejaVu Sans" font-size="13.00" fill="white">[ptr any struct]</text> -</g> -<!-- PTR_ANY->PTR_BOT --> -<g id="edge29" class="edge"> -<title>PTR_ANY->PTR_BOT</title> -<path fill="none" stroke="#555555" d="M554.17,-194.13C595.32,-176.91 652.51,-152.97 694.1,-135.56"/> -<polygon fill="#555555" stroke="#555555" points="694.78,-137.55 699.5,-133.29 693.15,-133.67 694.78,-137.55"/> -</g> -<!-- PTR_ANY->PTR_PERSON_NIL --> -<!-- PTR_PERSON->PTR_ANY --> -<g id="edge20" class="edge"> -<title>PTR_PERSON->PTR_ANY</title> -<path fill="none" stroke="#555555" d="M536.61,-327.84C530.59,-308.74 520.69,-277.32 513.02,-252.97"/> -<polygon fill="#555555" stroke="#555555" points="515.08,-252.52 511.28,-247.43 511.08,-253.78 515.08,-252.52"/> -</g> -<!-- PTR_PERSON->PTR_S1 --> -<!-- PTR_PERSON->PTR_PERSON_NIL --> -<g id="edge23" class="edge"> -<title>PTR_PERSON->PTR_PERSON_NIL</title> -<path fill="none" stroke="#555555" d="M556.03,-328.62C575.38,-306.08 610.32,-265.36 632,-240.11"/> -<polygon fill="#555555" stroke="#555555" points="633.38,-241.73 635.7,-235.81 630.19,-238.99 633.38,-241.73"/> -</g> -<!-- PTR_S1->PTR_ANY --> -<g id="edge21" class="edge"> -<title>PTR_S1->PTR_ANY</title> -<path fill="none" stroke="#555555" d="M621.75,-328.57C615.28,-317.84 606.03,-303.85 596,-292.97 580.61,-276.28 561.35,-260.24 544.26,-247.31"/> -<polygon fill="#555555" stroke="#555555" points="545.84,-245.87 539.78,-243.96 543.32,-249.23 545.84,-245.87"/> -</g> -<!-- PTR_S1->PTR_MORE --> -<!-- PTR_S1->PTR_S1_NIL --> -<g id="edge24" class="edge"> -<title>PTR_S1->PTR_S1_NIL</title> -<path fill="none" stroke="#555555" d="M640.49,-328.79C647.07,-318.15 656.34,-304.18 666,-292.97 684.1,-271.96 707.73,-250.9 724.97,-236.47"/> -<polygon fill="#555555" stroke="#555555" points="726.11,-238.25 729.39,-232.8 723.43,-235.02 726.11,-238.25"/> -</g> -<!-- PTR_MORE->PTR_NULL --> -<!-- PTR_MORE->PTR_ANY --> -<g id="edge22" class="edge"> -<title>PTR_MORE->PTR_ANY</title> -<path fill="none" stroke="#555555" d="M702.63,-328.84C693.45,-317.69 680.11,-303.08 666,-292.97 635.59,-271.17 597.84,-253.38 566.22,-240.61"/> -<polygon fill="#555555" stroke="#555555" points="567.33,-238.79 560.98,-238.52 565.78,-242.69 567.33,-238.79"/> -</g> -<!-- PTR_MORE->PTR_MORE_NIL --> -<g id="edge25" class="edge"> -<title>PTR_MORE->PTR_MORE_NIL</title> -<path fill="none" stroke="#555555" d="M729.86,-328.89C739.5,-318.54 752.38,-304.85 764,-292.97 782,-274.55 802.85,-254.03 818.15,-239.12"/> -<polygon fill="#555555" stroke="#555555" points="819.6,-240.64 822.44,-234.95 816.67,-237.63 819.6,-240.64"/> -</g> -<!-- PTR_PERSON_NIL->PTR_BOT --> -<g id="edge30" class="edge"> -<title>PTR_PERSON_NIL->PTR_BOT</title> -<path fill="none" stroke="#555555" d="M666.58,-199.43C680.58,-184.56 701.51,-162.35 718.65,-144.16"/> -<polygon fill="#555555" stroke="#555555" points="719.75,-146.05 722.33,-140.24 716.69,-143.17 719.75,-146.05"/> -</g> -<!-- PTR_PERSON_NIL->PTR_S1_NIL --> -<!-- PTR_S1_NIL->PTR_BOT --> -<g id="edge31" class="edge"> -<title>PTR_S1_NIL->PTR_BOT</title> -<path fill="none" stroke="#555555" d="M748,-198.5C748,-184.97 748,-165.76 748,-148.97"/> -<polygon fill="#555555" stroke="#555555" points="750.1,-148.97 748,-142.97 745.9,-148.97 750.1,-148.97"/> -</g> -<!-- PTR_S1_NIL->PTR_MORE_NIL --> -<!-- PTR_MORE_NIL->PTR_BOT --> -<g id="edge32" class="edge"> -<title>PTR_MORE_NIL->PTR_BOT</title> -<path fill="none" stroke="#555555" d="M825.62,-199.88C812.53,-185.22 792.8,-163.14 776.51,-144.9"/> -<polygon fill="#555555" stroke="#555555" points="778.14,-143.58 772.58,-140.51 775.01,-146.38 778.14,-143.58"/> -</g> -<!-- STRUCT_PERSON --> -<g id="node22" class="node"> -<title>STRUCT_PERSON</title> -<polygon fill="#90ee90" stroke="black" points="976.5,-237.47 909.5,-237.47 909.5,-196.47 976.5,-196.47 976.5,-237.47"/> -<text text-anchor="middle" x="943" y="-221.12" font-family="DejaVu Sans" font-size="13.00">Person</text> -<text text-anchor="middle" x="943" y="-204.62" font-family="DejaVu Sans" font-size="13.00">age: int</text> -</g> -<!-- STRUCT_TOP->STRUCT_PERSON --> -<g id="edge36" class="edge"> -<title>STRUCT_TOP->STRUCT_PERSON</title> -<path fill="none" stroke="#555555" d="M1011.61,-446.07C996.71,-396.53 965.8,-293.77 951.1,-244.91"/> -<polygon fill="#555555" stroke="#555555" points="953.15,-244.41 949.41,-239.27 949.12,-245.62 953.15,-244.41"/> -</g> -<!-- STRUCT_S1 --> -<g id="node23" class="node"> -<title>STRUCT_S1</title> -<polygon fill="#90ee90" stroke="black" points="1047,-237.47 993,-237.47 993,-196.47 1047,-196.47 1047,-237.47"/> -<text text-anchor="middle" x="1020" y="-221.12" font-family="DejaVu Sans" font-size="13.00">s1</text> -<text text-anchor="middle" x="1020" y="-204.62" font-family="DejaVu Sans" font-size="13.00">x: int</text> -</g> -<!-- STRUCT_TOP->STRUCT_S1 --> -<g id="edge37" class="edge"> -<title>STRUCT_TOP->STRUCT_S1</title> -<path fill="none" stroke="#555555" d="M1020,-445.58C1020,-395.91 1020,-293.85 1020,-245.08"/> -<polygon fill="#555555" stroke="#555555" points="1022.1,-245.25 1020,-239.25 1017.9,-245.25 1022.1,-245.25"/> -</g> -<!-- STRUCT_S2 --> -<g id="node24" class="node"> -<title>STRUCT_S2</title> -<polygon fill="#90ee90" stroke="black" points="1154.88,-237.47 1063.12,-237.47 1063.12,-196.47 1154.88,-196.47 1154.88,-237.47"/> -<text text-anchor="middle" x="1109" y="-221.12" font-family="DejaVu Sans" font-size="13.00">s2</text> -<text text-anchor="middle" x="1109" y="-204.62" font-family="DejaVu Sans" font-size="13.00">x: int, y: int</text> -</g> -<!-- STRUCT_TOP->STRUCT_S2 --> -<g id="edge38" class="edge"> -<title>STRUCT_TOP->STRUCT_S2</title> -<path fill="none" stroke="#555555" d="M1029.69,-446.07C1046.92,-396.53 1082.65,-293.77 1099.64,-244.91"/> -<polygon fill="#555555" stroke="#555555" points="1101.62,-245.61 1101.6,-239.25 1097.65,-244.23 1101.62,-245.61"/> -</g> -<!-- STRUCT_MORE --> -<g id="node25" class="node"> -<title>STRUCT_MORE</title> -<polygon fill="#90ee90" stroke="black" points="1225,-234.97 1171,-234.97 1171,-198.97 1225,-198.97 1225,-234.97"/> -<text text-anchor="middle" x="1198" y="-212.87" font-family="DejaVu Sans" font-size="13.00">…</text> -</g> -<!-- STRUCT_TOP->STRUCT_MORE --> -<g id="edge39" class="edge"> -<title>STRUCT_TOP->STRUCT_MORE</title> -<path fill="none" stroke="#555555" d="M1038.71,-447.05C1073.74,-396.68 1148.63,-288.97 1181.71,-241.39"/> -<polygon fill="#555555" stroke="#555555" points="1183.35,-242.73 1185.05,-236.6 1179.9,-240.33 1183.35,-242.73"/> -</g> -<!-- STRUCT_TOP->MEM_TOP --> -<!-- STRUCT_BOT --> -<g id="node21" class="node"> -<title>STRUCT_BOT</title> -<ellipse fill="#90ee90" stroke="black" cx="1020" cy="-111.99" rx="82.91" ry="28.99"/> -<text text-anchor="middle" x="1020" y="-116.14" font-family="DejaVu Sans" font-size="13.00">⊥:struct</text> -<text text-anchor="middle" x="1020" y="-99.64" font-family="DejaVu Sans" font-size="13.00">[struct bottom]</text> -</g> -<!-- STRUCT_BOT->BOT --> -<g id="edge69" class="edge"> -<title>STRUCT_BOT->BOT</title> -<path fill="none" stroke="#555555" d="M982.84,-85.85C959.17,-69.85 929.19,-49.57 908.49,-35.56"/> -<polygon fill="#555555" stroke="#555555" points="909.78,-33.9 903.63,-32.28 907.42,-37.38 909.78,-33.9"/> -</g> -<!-- STRUCT_PERSON->STRUCT_BOT --> -<g id="edge40" class="edge"> -<title>STRUCT_PERSON->STRUCT_BOT</title> -<path fill="none" stroke="#555555" d="M957.85,-196.12C968.43,-181.96 982.92,-162.59 995.24,-146.11"/> -<polygon fill="#555555" stroke="#555555" points="996.85,-147.46 998.76,-141.4 993.49,-144.94 996.85,-147.46"/> -</g> -<!-- STRUCT_PERSON->STRUCT_S1 --> -<!-- STRUCT_S1->STRUCT_BOT --> -<g id="edge41" class="edge"> -<title>STRUCT_S1->STRUCT_BOT</title> -<path fill="none" stroke="#555555" d="M1020,-196.12C1020,-182.64 1020,-164.43 1020,-148.49"/> -<polygon fill="#555555" stroke="#555555" points="1022.1,-148.87 1020,-142.87 1017.9,-148.87 1022.1,-148.87"/> -</g> -<!-- STRUCT_S1->STRUCT_S2 --> -<!-- STRUCT_S2->STRUCT_BOT --> -<g id="edge42" class="edge"> -<title>STRUCT_S2->STRUCT_BOT</title> -<path fill="none" stroke="#555555" d="M1091.84,-196.12C1079.5,-181.83 1062.57,-162.25 1048.25,-145.68"/> -<polygon fill="#555555" stroke="#555555" points="1050,-144.5 1044.49,-141.33 1046.82,-147.24 1050,-144.5"/> -</g> -<!-- STRUCT_S2->STRUCT_MORE --> -<!-- STRUCT_MORE->STRUCT_BOT --> -<g id="edge43" class="edge"> -<title>STRUCT_MORE->STRUCT_BOT</title> -<path fill="none" stroke="#555555" d="M1177.76,-198.72C1173.05,-195 1167.95,-191.22 1163,-187.98 1135.19,-169.81 1102.49,-152.39 1075.38,-138.93"/> -<polygon fill="#555555" stroke="#555555" points="1076.64,-137.21 1070.33,-136.44 1074.78,-140.97 1076.64,-137.21"/> -</g> -<!-- MEM_ALIAS2 --> -<g id="node28" class="node"> -<title>MEM_ALIAS2</title> -<ellipse fill="#00008b" stroke="black" cx="1294" cy="-216.97" rx="45.21" ry="18"/> -<text text-anchor="middle" x="1294" y="-212.87" font-family="DejaVu Sans" font-size="13.00" fill="white">MEM#2</text> -</g> -<!-- MEM_TOP->MEM_ALIAS2 --> -<g id="edge46" class="edge"> -<title>MEM_TOP->MEM_ALIAS2</title> -<path fill="none" stroke="#555555" d="M1343.44,-456.76C1334.24,-412.32 1309.64,-293.5 1299.01,-242.16"/> -<polygon fill="#555555" stroke="#555555" points="1301.12,-242.02 1297.85,-236.57 1297.01,-242.88 1301.12,-242.02"/> -</g> -<!-- MEM_ALIAS3 --> -<g id="node29" class="node"> -<title>MEM_ALIAS3</title> -<ellipse fill="#00008b" stroke="black" cx="1400" cy="-216.97" rx="45.21" ry="18"/> -<text text-anchor="middle" x="1400" y="-212.87" font-family="DejaVu Sans" font-size="13.00" fill="white">MEM#3</text> -</g> -<!-- MEM_TOP->MEM_ALIAS3 --> -<g id="edge47" class="edge"> -<title>MEM_TOP->MEM_ALIAS3</title> -<path fill="none" stroke="#555555" d="M1350.56,-456.76C1359.76,-412.32 1384.36,-293.5 1394.99,-242.16"/> -<polygon fill="#555555" stroke="#555555" points="1396.99,-242.88 1396.15,-236.57 1392.88,-242.02 1396.99,-242.88"/> -</g> -<!-- MEM_MORE --> -<g id="node30" class="node"> -<title>MEM_MORE</title> -<ellipse fill="#00008b" stroke="black" cx="1488" cy="-216.97" rx="27" ry="18"/> -<text text-anchor="middle" x="1488" y="-212.87" font-family="DejaVu Sans" font-size="13.00" fill="white">…</text> -</g> -<!-- MEM_TOP->MEM_MORE --> -<g id="edge48" class="edge"> -<title>MEM_TOP->MEM_MORE</title> -<path fill="none" stroke="#555555" d="M1356.25,-457.16C1380.82,-412.56 1447.72,-291.1 1475.57,-240.54"/> -<polygon fill="#555555" stroke="#555555" points="1477.29,-241.76 1478.35,-235.49 1473.62,-239.74 1477.29,-241.76"/> -</g> -<!-- MEM_TOP->TUPLE_TOP --> -<!-- MEM_BOT --> -<g id="node27" class="node"> -<title>MEM_BOT</title> -<ellipse fill="#00008b" stroke="black" cx="1347" cy="-111.99" rx="44.7" ry="18"/> -<text text-anchor="middle" x="1347" y="-107.89" font-family="DejaVu Sans" font-size="13.00" fill="white">⊥:mem</text> -</g> -<!-- MEM_BOT->BOT --> -<g id="edge70" class="edge"> -<title>MEM_BOT->BOT</title> -<path fill="none" stroke="#555555" d="M1315.14,-99.08C1293.38,-91.31 1263.76,-81.46 1237,-75 1121.65,-47.17 981.66,-29.67 918.21,-22.6"/> -<polygon fill="#555555" stroke="#555555" points="918.55,-20.52 912.36,-21.95 918.09,-24.7 918.55,-20.52"/> -</g> -<!-- MEM_ALIAS2->MEM_BOT --> -<g id="edge49" class="edge"> -<title>MEM_ALIAS2->MEM_BOT</title> -<path fill="none" stroke="#555555" d="M1302.75,-198.97C1311.5,-181.97 1325.02,-155.71 1334.81,-136.68"/> -<polygon fill="#555555" stroke="#555555" points="1336.66,-137.66 1337.54,-131.37 1332.93,-135.74 1336.66,-137.66"/> -</g> -<!-- MEM_ALIAS2->MEM_ALIAS3 --> -<!-- MEM_ALIAS3->MEM_BOT --> -<g id="edge50" class="edge"> -<title>MEM_ALIAS3->MEM_BOT</title> -<path fill="none" stroke="#555555" d="M1391.25,-198.97C1382.5,-181.97 1368.98,-155.71 1359.19,-136.68"/> -<polygon fill="#555555" stroke="#555555" points="1361.07,-135.74 1356.46,-131.37 1357.34,-137.66 1361.07,-135.74"/> -</g> -<!-- MEM_ALIAS3->MEM_MORE --> -<!-- MEM_MORE->MEM_BOT --> -<g id="edge51" class="edge"> -<title>MEM_MORE->MEM_BOT</title> -<path fill="none" stroke="#555555" d="M1471.42,-202.39C1465.65,-197.74 1459.09,-192.57 1453,-187.98 1426.93,-168.37 1396.47,-146.96 1374.9,-132.06"/> -<polygon fill="#555555" stroke="#555555" points="1376.17,-130.38 1370.03,-128.71 1373.78,-133.84 1376.17,-130.38"/> -</g> -<!-- TUPLE1 --> -<g id="node33" class="node"> -<title>TUPLE1</title> -<polygon fill="#ffc0cb" stroke="none" points="1582.88,-372.47 1539.12,-372.47 1539.12,-319.47 1582.88,-319.47 1582.88,-372.47"/> -<polygon fill="#ffc0cb" stroke="none" points="1539.12,-345.97 1539.12,-372.47 1582.88,-372.47 1582.88,-345.97 1539.12,-345.97"/> -<polygon fill="none" stroke="black" points="1539.12,-345.97 1539.12,-372.47 1582.88,-372.47 1582.88,-345.97 1539.12,-345.97"/> -<text text-anchor="start" x="1544.12" y="-355.12" font-family="DejaVu Sans" font-size="13.00">tuple</text> -<polygon fill="black" stroke="none" points="1539.12,-319.47 1539.12,-345.97 1582.88,-345.97 1582.88,-319.47 1539.12,-319.47"/> -<polygon fill="none" stroke="black" points="1539.12,-319.47 1539.12,-345.97 1582.88,-345.97 1582.88,-319.47 1539.12,-319.47"/> -<text text-anchor="start" x="1546.38" y="-328.62" font-family="DejaVu Sans" font-size="13.00" fill="white">type</text> -</g> -<!-- TUPLE_TOP->TUPLE1 --> -<g id="edge54" class="edge"> -<title>TUPLE_TOP->TUPLE1</title> -<path fill="none" stroke="#555555" d="M1580.85,-456.57C1577.26,-436.74 1571.31,-403.91 1566.86,-379.34"/> -<polygon fill="#555555" stroke="#555555" points="1568.94,-379.03 1565.81,-373.5 1564.81,-379.77 1568.94,-379.03"/> -</g> -<!-- TUPLE2 --> -<g id="node34" class="node"> -<title>TUPLE2</title> -<polygon fill="#ffc0cb" stroke="none" points="1642.88,-385.72 1599.12,-385.72 1599.12,-306.22 1642.88,-306.22 1642.88,-385.72"/> -<polygon fill="#ffc0cb" stroke="none" points="1599.12,-359.22 1599.12,-385.72 1642.88,-385.72 1642.88,-359.22 1599.12,-359.22"/> -<polygon fill="none" stroke="black" points="1599.12,-359.22 1599.12,-385.72 1642.88,-385.72 1642.88,-359.22 1599.12,-359.22"/> -<text text-anchor="start" x="1604.12" y="-368.37" font-family="DejaVu Sans" font-size="13.00">tuple</text> -<polygon fill="black" stroke="none" points="1599.12,-332.72 1599.12,-359.22 1642.88,-359.22 1642.88,-332.72 1599.12,-332.72"/> -<polygon fill="none" stroke="black" points="1599.12,-332.72 1599.12,-359.22 1642.88,-359.22 1642.88,-332.72 1599.12,-332.72"/> -<text text-anchor="start" x="1606.38" y="-341.87" font-family="DejaVu Sans" font-size="13.00" fill="white">type</text> -<polygon fill="black" stroke="none" points="1599.12,-306.22 1599.12,-332.72 1642.88,-332.72 1642.88,-306.22 1599.12,-306.22"/> -<polygon fill="none" stroke="black" points="1599.12,-306.22 1599.12,-332.72 1642.88,-332.72 1642.88,-306.22 1599.12,-306.22"/> -<text text-anchor="start" x="1606.38" y="-315.37" font-family="DejaVu Sans" font-size="13.00" fill="white">type</text> -</g> -<!-- TUPLE_TOP->TUPLE2 --> -<g id="edge55" class="edge"> -<title>TUPLE_TOP->TUPLE2</title> -<path fill="none" stroke="#555555" d="M1588.99,-456.83C1593.76,-440.46 1601.17,-415.04 1607.65,-392.78"/> -<polygon fill="#555555" stroke="#555555" points="1609.64,-393.48 1609.3,-387.13 1605.6,-392.3 1609.64,-393.48"/> -</g> -<!-- TUPLEN --> -<g id="node35" class="node"> -<title>TUPLEN</title> -<polygon fill="#ffc0cb" stroke="none" points="1702.88,-398.97 1659.12,-398.97 1659.12,-292.97 1702.88,-292.97 1702.88,-398.97"/> -<polygon fill="#ffc0cb" stroke="none" points="1659.12,-372.47 1659.12,-398.97 1702.88,-398.97 1702.88,-372.47 1659.12,-372.47"/> -<polygon fill="none" stroke="black" points="1659.12,-372.47 1659.12,-398.97 1702.88,-398.97 1702.88,-372.47 1659.12,-372.47"/> -<text text-anchor="start" x="1664.12" y="-381.62" font-family="DejaVu Sans" font-size="13.00">tuple</text> -<polygon fill="black" stroke="none" points="1659.12,-345.97 1659.12,-372.47 1702.88,-372.47 1702.88,-345.97 1659.12,-345.97"/> -<polygon fill="none" stroke="black" points="1659.12,-345.97 1659.12,-372.47 1702.88,-372.47 1702.88,-345.97 1659.12,-345.97"/> -<text text-anchor="start" x="1666.38" y="-355.12" font-family="DejaVu Sans" font-size="13.00" fill="white">type</text> -<polygon fill="black" stroke="none" points="1659.12,-319.47 1659.12,-345.97 1702.88,-345.97 1702.88,-319.47 1659.12,-319.47"/> -<polygon fill="none" stroke="black" points="1659.12,-319.47 1659.12,-345.97 1702.88,-345.97 1702.88,-319.47 1659.12,-319.47"/> -<text text-anchor="start" x="1674.62" y="-328.62" font-family="DejaVu Sans" font-size="13.00" fill="white">…</text> -<polygon fill="black" stroke="none" points="1659.12,-292.97 1659.12,-319.47 1702.88,-319.47 1702.88,-292.97 1659.12,-292.97"/> -<polygon fill="none" stroke="black" points="1659.12,-292.97 1659.12,-319.47 1702.88,-319.47 1702.88,-292.97 1659.12,-292.97"/> -<text text-anchor="start" x="1666.38" y="-302.12" font-family="DejaVu Sans" font-size="13.00" fill="white">type</text> -</g> -<!-- TUPLE_TOP->TUPLEN --> -<g id="edge56" class="edge"> -<title>TUPLE_TOP->TUPLEN</title> -<path fill="none" stroke="#555555" d="M1600.21,-457.82C1614.47,-443.17 1635.34,-420.61 1651,-398.97 1652.4,-397.02 1653.8,-395.01 1655.17,-392.95"/> -<polygon fill="#555555" stroke="#555555" points="1656.91,-394.14 1658.41,-387.96 1653.38,-391.86 1656.91,-394.14"/> -</g> -<!-- TUPLE_BOT --> -<g id="node32" class="node"> -<title>TUPLE_BOT</title> -<ellipse fill="#ffc0cb" stroke="black" cx="1602" cy="-111.99" rx="44.7" ry="18"/> -<text text-anchor="middle" x="1602" y="-107.89" font-family="DejaVu Sans" font-size="13.00">⊥:tuple</text> -</g> -<!-- TUPLE_BOT->BOT --> -<g id="edge71" class="edge"> -<title>TUPLE_BOT->BOT</title> -<path fill="none" stroke="#555555" d="M1577.54,-96.47C1563.29,-88.74 1544.69,-79.84 1527,-75 1410.53,-43.12 1034.45,-25.23 918.41,-20.37"/> -<polygon fill="#555555" stroke="#555555" points="918.75,-18.28 912.67,-20.13 918.57,-22.48 918.75,-18.28"/> -</g> -<!-- TUPLE1->TUPLE_BOT --> -<g id="edge57" class="edge"> -<title>TUPLE1->TUPLE_BOT</title> -<path fill="none" stroke="#555555" d="M1565.47,-319.7C1573.39,-274.85 1589.82,-181.9 1597.66,-137.56"/> -<polygon fill="#555555" stroke="#555555" points="1599.69,-138.14 1598.66,-131.86 1595.55,-137.4 1599.69,-138.14"/> -</g> -<!-- TUPLE1->TUPLE2 --> -<!-- TUPLE2->TUPLE_BOT --> -<g id="edge58" class="edge"> -<title>TUPLE2->TUPLE_BOT</title> -<path fill="none" stroke="#555555" d="M1617.84,-306.4C1613.91,-258.37 1607.3,-177.75 1604,-137.46"/> -<polygon fill="#555555" stroke="#555555" points="1606.13,-137.74 1603.55,-131.93 1601.95,-138.08 1606.13,-137.74"/> -</g> -<!-- TUPLE2->TUPLEN --> -<!-- TUPLEN->TUPLE_BOT --> -<g id="edge59" class="edge"> -<title>TUPLEN->TUPLE_BOT</title> -<path fill="none" stroke="#555555" d="M1663.37,-293.19C1646.79,-244.5 1622.69,-173.75 1610.2,-137.07"/> -<polygon fill="#555555" stroke="#555555" points="1612.27,-136.64 1608.35,-131.63 1608.3,-137.99 1612.27,-136.64"/> -</g> -</g> -</svg> diff --git a/chapter10b/pom.xml b/chapter10b/pom.xml deleted file mode 100644 index 5378c5eb..00000000 --- a/chapter10b/pom.xml +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>com.seaofnodes</groupId> - <artifactId>simple</artifactId> - <version>1.0</version> - </parent> - <artifactId>chapter10b</artifactId> - <packaging>jar</packaging> - <name>Chapter 10b</name> - <properties> - <simple.graph.directory>${project.basedir}/../graph</simple.graph.directory> - <simple.print.directory>${project.basedir}/../print</simple.print.directory> - </properties> -</project> diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/IRPrinter.java b/chapter10b/src/main/java/com/seaofnodes/simple/IRPrinter.java deleted file mode 100644 index d5ab15fe..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/IRPrinter.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.seaofnodes.simple; - -import com.seaofnodes.print.IRAdapter; -import com.seaofnodes.simple.node.*; - -/** This chapter's read-only IR facts and the familiar debugger entry points. */ -public final class IRPrinter extends IRAdapter<Node> { - private static final com.seaofnodes.print.IRPrinter<Node> PRINT = - new com.seaofnodes.print.IRPrinter<>(new IRPrinter()); - @Override public String type(Node n) { return n._type==null ? "" : n._type.str(); } - @Override public int inputColumns() { return 3; } - @Override public String inputMark(Node n, Node def) { return n instanceof MemMergeNode && def instanceof MemMergeNode ? "^" : " "; } - @Override public Kind kind(Node n) { - if( n instanceof StartNode ) return Kind.START; - if( n instanceof StopNode ) return Kind.STOP; - if( n instanceof LoopNode ) return Kind.LOOP; - if( n instanceof RegionNode ) return Kind.REGION; - if( n instanceof PhiNode ) return Kind.PHI; - if( n instanceof ReturnNode ) return Kind.RETURN; - if( n instanceof ConstantNode ) return Kind.CONSTANT; - if( n instanceof ProjNode ) return n.isCFG() ? Kind.CPROJ : Kind.PROJ; - if( n.isCFG() ) return Kind.CTRL; - if( n instanceof MultiNode ) return Kind.MULTI; - return Kind.DATA; - } - @Override public int index(Node n) { - if( n instanceof ProjNode p ) return p._idx; - return n._nid; - } - - public static String prettyPrint(Node n, int depth) { return PRINT.prettyPrint(n,depth); } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/IterPeeps.java b/chapter10b/src/main/java/com/seaofnodes/simple/IterPeeps.java deleted file mode 100644 index 7075d526..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/IterPeeps.java +++ /dev/null @@ -1,208 +0,0 @@ -package com.seaofnodes.simple; - -import com.seaofnodes.simple.node.*; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.BitSet; -import java.util.Random; - -/** - * The IterOptim runs after parsing. It iterates the peepholes to a fixed point - * so that no more peepholes apply. This should be linear because peepholes rarely - * (never?) increase code size. The graph should monotonically reduce in some - * dimension, which is usually size. It might also reduce in e.g. number of - * MulNodes or Load/Store nodes, swapping out more "expensive" Nodes for cheaper - * ones. - * - * The theoretical overall worklist is mindless just grabbing the next thing and - * doing it. If the graph changes, put the neighbors on the worklist. Lather, - * Rinse, Repeat until the worklist runs dry. - * - * The main issues we have to deal with: - * - * <ul> - * <li>Nodes have uses; replacing some set of Nodes with another requires more graph - * reworking. Not rocket science, but it can be fiddly. Its helpful to have a - * small set of graph munging utilities, and the strong invariant that the graph - * is stable and correct between peepholes. In our case `Node.subsume` does - * most of the munging, building on our prior stable Node utilities.</li> - * - * <li>Changing a Node also changes the graph "neighborhood". The neigbors need to - * be checked to see if THEY can also peephole, and so on. After any peephole - * or graph update we put a Nodes uses and defs on the worklist.</li> - * - * <li>Our strong invariant is that for all Nodes, either they are on the worklist - * OR no peephole applies. This invariant is easy to check, although expensive. - * Basically the normal "iterate peepholes to a fixed point" is linear, and this - * check is linear at each peephole step... so quadratic overall. Its a useful - * assert, but one we can disable once the overall algorithm is stable - and - * then turn it back on again when some new set of peepholes is misbehaving. - * The code for this is turned on in `IterOptim.iterate` as `assert - * progressOnList(stop);`</li> - * </ul> - */ -public abstract class IterPeeps { - - private static final WorkList<Node> WORK = new WorkList<>(); - - public static <N extends Node> N add( N n ) { - return (N)WORK.push(n); - } - - public static void addAll( ArrayList<Node> ary ) { - WORK.addAll(ary); - } - - /** - * Iterate peepholes to a fixed point - */ - public static StopNode iterate(StopNode stop) { - assert progressOnList(stop); - int cnt=0; - - Node n; - while( (n=WORK.pop()) != null ) { - if( n.isDead() ) continue; - cnt++; // Useful for debugging, searching which peephole broke things - var obs = Parser.PARSER == null ? null : Parser.PARSER._obs; - if( obs != null ) obs.before(n); - Node x = n.peepholeOpt(); - if( x != null ) { - if( x.isDead() ) { - if( obs != null ) obs.after(n, x, true); - continue; - } - // peepholeOpt can return brand-new nodes, needing an initial type set - if( x._type==null ) x.setType(x.compute()); - // Changes require neighbors onto the worklist - if( x != n || !(x instanceof ConstantNode) ) { - // All outputs of n (changing node) not x (prior existing node). - for( Node z : n._outputs ) WORK.push(z); - // Everybody gets a free "go again" in case they didn't get - // made in their final form. - WORK.push(x); - // If the result is not self, revisit all inputs (because - // there's a new user), and replace in the graph. - if( x != n ) { - for( Node z : n. _inputs ) WORK.push(z); - n.subsume(x); - } - } - // If there are distant neighbors, move to worklist - n.moveDepsToWorklist(); - assert progressOnList(stop); // Very expensive assert - } - if( n.isUnused() && !(n instanceof StopNode) ) - n.kill(); // Just plain dead - if( obs != null ) obs.after(n, x, true); - } - - return stop; - } - - // Visit ALL nodes and confirm the invariant: - // Either you are on the WORK worklist OR running `iter()` makes no progress. - - // This invariant ensures that no progress is missed, i.e., when the - // worklist is empty we have indeed done all that can be done. To help - // with debugging, the {@code assert} is broken out in a place where it is easy to - // stop if a change is found. - - // Also, the normal usage of `iter()` may attempt peepholes with distance - // neighbors and these should fail, but will then try to add dependencies - // {@link #Node.addDep} which is a side effect in an assert. The {@link - // #midAssert} is used to stop this side effect. - private static boolean MID_ASSERT; - public static boolean midAssert() { return MID_ASSERT; } - private static boolean progressOnList(Node stop) { - MID_ASSERT = true; - int old_cnt = Node.ITER_CNT, old_nop = Node.ITER_NOP_CNT; - Node changed = stop.walk( n -> { - if( WORK.on(n) ) return null; - Node m = n.peepholeOpt(); - if( m==null ) return null; - System.err.println("BREAK HERE FOR BUG"); - return m; - }); - Node.ITER_CNT = old_cnt; Node.ITER_NOP_CNT = old_nop; - MID_ASSERT = false; - return changed==null; - } - - public static void reset() { - WORK.clear(); - } - - /** - * Classic WorkList, with a fast add/remove, dup removal, random pull. - * The Node's nid is used to check membership in the worklist. - */ - public static class WorkList<E extends Node> { - - private Node[] _es; - private int _len; - private final BitSet _on; // Bit set if Node._nid is on WorkList - private final Random _R; // For randomizing pull from the WorkList - private final long _seed; - - /* Useful stat - how many nodes are processed in the post parse iterative opt */ - private long _totalWork = 0; - - WorkList() { this(123); } - WorkList(long seed) { - _es = new Node[1]; - _len=0; - _on = new BitSet(); - _seed = seed; - _R = new Random(); - _R.setSeed(_seed); - } - - /** - * Pushes a Node on the WorkList, ensuring no duplicates - * If Node is null it will not be added. - */ - public E push( E x ) { - if( x==null ) return null; - int idx = x._nid; - if( !_on.get(idx) ) { - _on.set(idx); - if( _len==_es.length ) - _es = Arrays.copyOf(_es,_len<<1); - _es[_len++] = x; - _totalWork++; - } - return x; - } - - public void addAll( ArrayList<E> ary ) { - for( E n : ary ) - push(n); - } - - /** - * True if Node is on the WorkList - */ - boolean on( E x ) { return _on.get(x._nid); } - - /** - * Removes a random Node from the WorkList; null if WorkList is empty - */ - E pop() { - if( _len == 0 ) return null; - int idx = _R.nextInt(_len); - E x = (E)_es[idx]; - _es[idx] = _es[--_len]; // Compress array - _on.clear(x._nid); - return x; - } - - public void clear() { - _len = 0; - _on.clear(); - _R.setSeed(_seed); - _totalWork = 0; - } - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/Parser.java b/chapter10b/src/main/java/com/seaofnodes/simple/Parser.java deleted file mode 100644 index 3b5f2721..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/Parser.java +++ /dev/null @@ -1,843 +0,0 @@ -package com.seaofnodes.simple; - -import com.seaofnodes.graph.GraphObserver; - -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.*; - -import java.util.*; - -/** - * The Parser converts a Simple source program to the Sea of Nodes intermediate - * representation directly in one pass. There is no intermediate Abstract - * Syntax Tree structure. - * <p> - * This is a simple recursive descent parser. All lexical analysis is done here as well. - */ -public class Parser { - - // Current compilation context; the observer belongs to the parser. - public static Parser PARSER; - public GraphObserver<Node> _obs; - public int pos() { return _lexer._position; } - - - /** - * A Global Static, unique to each compilation. This is a public, so we - * can make constants everywhere without having to thread the StartNode - * through the entire parser and optimizer. - * <p> - * To make the compiler multithreaded, this field will have to move into a TLS. - */ - public static StartNode START; - - public StopNode STOP; - - // Field identities are independent of the memory graph and Start's tuple. - private final HashMap<String,Integer> _aliases = new HashMap<>(); - private int _alias = 2; - - // The Lexer. Thin wrapper over a byte[] buffer with a cursor. - private final Lexer _lexer; - - /** - * 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()}. - * <p> - * 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. - * <p> - * We keep a list of all ScopeNodes so that we can show them in graphs. - * @see #parseIf() - * @see #_xScopes - */ - public ScopeNode _scope; - - /** - * List of keywords disallowed as identifiers - */ - private static final HashSet<String> KEYWORDS = new HashSet<>(){{ - add("break"); - add("continue"); - add("else"); - add("false"); - add("if"); - add("int"); - add("new"); - add("null"); - add("return"); - add("struct"); - add("true"); - add("while"); - }}; - - - /** - * 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<ScopeNode> _xScopes = new Stack<>(); - - ScopeNode _continueScope; - ScopeNode _breakScope; - - // Mapping from a Struct name to a Struct. - public static Map<String, TypeStruct> OBJS = new HashMap<>(); - - public Parser(String source, TypeInteger arg) { - PARSER = this; - Node.reset(); - IterPeeps.reset(); - OBJS.clear(); - _lexer = new Lexer(source); - _scope = new ScopeNode(); - _continueScope = _breakScope = null; - START = new StartNode(new Type[]{ Type.CONTROL, TypeMem.BOT, arg }); - STOP = new StopNode(source); - } - - public Parser(String source) { - this(source, TypeInteger.BOT); - } - - @Override - public String toString() { return _lexer.toString(); } - - String src() { return new String( _lexer._input ); } - - // Debugging utility to find a Node by index - public static Node find(int nid) { return START.find(nid); } - - private Node ctrl() { return _scope.ctrl(); } - - private Node ctrl(Node n) { return _scope.ctrl(n); } - - public StopNode parse() { - _xScopes.push(_scope); - // Enter a new scope for the initial control and arguments - _scope.push(); - _scope.define(ScopeNode.CTRL, Type.CONTROL , new ProjNode(START, 0, ScopeNode.CTRL).peephole()); - _scope.define(ScopeNode.ARG0, TypeInteger.BOT, new ProjNode(START, 2, ScopeNode.ARG0).peephole()); - _scope.define("$mem", TypeMem.BOT, new ProjNode(START, 1, "$mem").peephole()); - parseBlock(); - _scope.pop(); - _xScopes.pop(); - if (!_lexer.isEOF()) throw error("Syntax error, unexpected " + _lexer.getAnyNextToken()); - STOP.peephole(); - return STOP; - } - - /** - * Parses a block - * - * <pre> - * '{' statements '}' - * </pre> - * Does not parse the opening or closing '{}' - * @return a {@link Node} or {@code null} - */ - private Node parseBlock() { - // Enter a new scope - _scope.push(); - while (!peek('}') && !_lexer.isEOF()) - parseStatement(); - // Exit scope - _scope.pop(); - return null; - } - - /** - * Parses a statement - * - * <pre> - * returnStatement | declStatement | blockStatement | ifStatement | expressionStatement - * </pre> - * @return a {@link Node} or {@code null} - */ - private Node parseStatement() { - if( false ) return null; - else if (matchx("return") ) return parseReturn(); - else if (matchx("int") ) return parseDecl(TypeInteger.BOT); - else if (match ("{") ) return require(parseBlock(),"}"); - else if (matchx("if") ) return parseIf(); - else if (matchx("while") ) return parseWhile(); - else if (matchx("break") ) return parseBreak(); - else if (matchx("continue")) return parseContinue(); - else if (matchx("struct") ) return parseStruct(); - else if (matchx(";") ) return null; // Empty statement - // declarations of vars with struct type are handled in parseExpressionStatement due - // to ambiguity - else return parseExpressionStatement(); - } - - /** - * Parse a struct field. - * <pre> - * int IDENTIFIER ; - * </pre> - */ - private Field parseField(String sname) { - if( matchx("int") ) // Currently only parsing "int" type fields - return require(Field.make(requireId().intern(),TypeInteger.BOT),";"); - throw errorSyntax("A field type is expected, only type 'int' is supported at present"); - } - - /** - * Parse a struct declaration, and return the following statement. - * Only allowed in top level scope. - * Structs cannot be redefined. - * - * @return The statement following the struct - */ - private Node parseStruct() { - if (_xScopes.size() > 1) throw errorSyntax("struct declarations can only appear in top level scope"); - String typeName = requireId(); - if ( OBJS.containsKey(typeName)) throw errorSyntax("struct '" + typeName + "' cannot be redefined"); - ArrayList<Field> fields = new ArrayList<>(); - require("{"); - while (!peek('}') && !_lexer.isEOF()) { - Field field = parseField(typeName); - if (fields.contains(field)) throw errorSyntax("Field '" + field + "' already defined in struct '" + typeName + "'"); - fields.add(field); - } - require("}"); - // Build and install the TypeStruct - TypeStruct ts = TypeStruct.make(typeName, fields); - _aliases.put(typeName,_alias); - _alias += ts._fields.length; - OBJS.put(typeName, ts); // Insert the struct name in the collection of all struct names - return parseStatement(); - } - - /** - * Parses a while statement - * - * <pre> - * while ( expression ) statement - * </pre> - * @return a {@link Node}, never {@code null} - */ - private Node parseWhile() { - - var savedContinueScope = _continueScope; - var savedBreakScope = _breakScope; - - require("("); - - // Loop region has two control inputs, the first is the entry - // point, and second is back edge that is set after loop is parsed - // (see end_loop() call below). Note that the absence of back edge is - // used as an indicator to switch off peepholes of the region and - // associated phis; see {@code inProgress()}. - - ctrl(new LoopNode(ctrl()).peephole()); // Note we set back edge to null here - - // At loop head, we clone the current Scope (this includes all - // names in every nesting level within the Scope). - // We create phis eagerly for all the names we find, see dup(). - - // Save the current scope as the loop head - ScopeNode head = _scope.keep(); - // Clone the head Scope to create a new Scope for the body. - // Create phis eagerly as part of cloning - _xScopes.push(_scope = _scope.dup(true)); // The true argument triggers creating phis - - // Parse predicate - var pred = require(parseExpression(), ")"); - // IfNode takes current control and predicate - Node ifNode = new IfNode(ctrl(), pred).peephole(); - // Setup projection nodes - Node ifT = new ProjNode(ifNode. keep(), 0, "True" ).peephole().keep(); - Node ifF = new ProjNode(ifNode.unkeep(), 1, "False").peephole(); - - // Clone the body Scope to create the break/exit Scope which accounts for any - // side effects in the predicate. The break/exit Scope will be the final - // scope after the loop, and its control input is the False branch of - // the loop predicate. Note that body Scope is still our current scope. - ctrl(ifF); - _xScopes.push(_breakScope = _scope.dup()); - - // No continues yet - _continueScope = null; - - // Parse the true side, which corresponds to loop body - // Our current scope is the body Scope - ctrl(ifT.unkeep()); // set ctrl token to ifTrue projection - parseStatement(); // Parse loop body - - // Merge the loop bottom into other continue statements - if (_continueScope != null) { - _continueScope = jumpTo(_continueScope); - _scope.kill(); - _scope = _continueScope; - } - - // The true branch loops back, so whatever is current _scope.ctrl gets - // added to head loop as input. endLoop() updates the head scope, and - // goes through all the phis that were created earlier. For each phi, - // it sets the second input to the corresponding input from the back - // edge. If the phi is redundant, it is replaced by its sole input. - var exit = _breakScope; - head.endLoop(_scope, exit); - head.unkeep().kill(); - - _xScopes.pop(); // Cleanup - _xScopes.pop(); // Cleanup - - _continueScope = savedContinueScope; - _breakScope = savedBreakScope; - - // At exit the false control is the current control, and - // the scope is the exit scope after the exit test. - return _scope = exit; - } - - private ScopeNode jumpTo(ScopeNode toScope) { - ScopeNode cur = _scope.dup(); - ctrl(new ConstantNode(Type.XCONTROL).peephole()); // Kill current scope - // Prune nested lexical scopes that have depth > than the loop head - // We use _breakScope as a proxy for the loop head scope to obtain the depth - while( cur._scopes.size() > _breakScope._scopes.size() ) - cur.pop(); - // If this is a continue then first time the target is null - // So we just use the pruned current scope as the base for the - // "continue" - if (toScope == null) - return cur; - // toScope is either the break scope, or a scope that was created here - assert toScope._scopes.size() <= _breakScope._scopes.size(); - toScope.ctrl(toScope.mergeScopes(cur)); - return toScope; - } - - private void checkLoopActive() { if (_breakScope == null) throw Parser.error("No active loop for a break or continue"); } - - private Node parseBreak () { checkLoopActive(); return ( _breakScope = require(jumpTo( _breakScope ),";")); } - private Node parseContinue() { checkLoopActive(); return (_continueScope = require(jumpTo( _continueScope ),";")); } - - /** - * Parses a statement - * - * <pre> - * if ( expression ) statement [else statement] - * </pre> - * @return a {@link Node}, never {@code null} - */ - private Node parseIf() { - require("("); - // Parse predicate - var pred = require(parseExpression(), ")").keep(); - // IfNode takes current control and predicate - Node ifNode = new IfNode(ctrl(), pred).peephole(); - // Setup projection nodes - Node ifT = new ProjNode(ifNode. keep(), 0, "True" ).peephole().keep(); - Node ifF = new ProjNode(ifNode.unkeep(), 1, "False").peephole().keep(); - // 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.unkeep()); // set ctrl token to ifTrue projection - _scope.upcast(ifT,pred,false); // Up-cast predicate - parseStatement(); // Parse true-side - ScopeNode tScope = _scope; - - // Parse the false side - _scope = fScope; // Restore scope, then parse else block if any - ifF.unkeep(); // fScope already owns the false control - if (matchx("else")) { - _scope.upcast(ifF,pred,true); // Up-cast predicate - parseStatement(); - fScope = _scope; - } - pred.unkeep(); - - 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. - * - * <pre> - * 'return' expr ; - * </pre> - * @return an expression {@link Node}, never {@code null} - */ - private Node parseReturn() { - var expr = require(parseExpression(), ";"); - Node ret = STOP.addReturn(new ReturnNode(ctrl(), expr, _scope).peephole()); - ctrl(new ConstantNode(Type.XCONTROL).peephole()); // Kill control - return ret; - } - - - - /** - * Parses an expression statement or a declaration statement where type is a struct - * - * <pre> - * name; // Error - * type name; // Define name with default initial value - * type name = expr; // Define name with given initial value - * name = expr; // Reassign existing - * expr // Something else - * </pre> - * @return an expression {@link Node}, never {@code null} - */ - private Node parseExpressionStatement() { - int old = _lexer._position; - Type t = type(); - String name = requireId(); - Node expr; - if( match(";") ) { // Assign a default value - // No type and no expr is an error - if( t==null ) throw errorSyntax("expression"); - expr = new ConstantNode(t.makeInit()).peephole(); - } else if( match("=") ) { // Assign "= expr;" - expr = require(parseExpression(), ";"); - } else { // Neither, so just a normal expression parse - _lexer._position = old; - return require(parseExpression(),";"); - } - - // Defining a new variable vs updating an old one - if( t != null ) { - if( _scope.define(name,t,expr) == null ) - throw error("Redefining name '" + name + "'"); - } else { - Node n = _scope.lookup(name); - t = _scope.lookupDeclaredType(name); - if( n==null ) - throw error("Undefined name '" + name + "'"); - _scope.update(name,expr); - } - if( !expr._type.isa(t) ) - throw error("Type " + expr._type.str() + " is not of declared type " + t.str()); - return expr; - } - - // Parse a type-or-null - private Type type() { - int old = _lexer._position; - String tname = _lexer.matchId(); - if( tname==null ) return null; - if( tname.equals("int") ) return TypeInteger.BOT; - TypeStruct obj = OBJS.get(tname); - if( obj != null ) - return TypeMemPtr.make(obj,match("?")); - // Not a type; unwind the parse - _lexer._position = old; - return null; - } - - /** - * Parses a declStatement - * - * <pre> - * type name = expression ';' - * </pre> - * @return an expression {@link Node} - */ - private Node parseDecl(Type t) { - var name = requireId(); - var expr = match(";") - // Assign a null value - ? new ConstantNode(t.makeInit()).peephole() - // Assign "= expr;" - : require(require("=").parseExpression(), ";"); - if( !expr._type.isa(t) ) - throw error("Type " + expr._type.str() + " is not of declared type " + t.str()); - if( _scope.define(name,t,expr) == null ) - throw error("Redefining name '" + name + "'"); - return expr; - } - - - /** - * Parse an expression of the form: - * - * <pre> - * expr : compareExpr - * </pre> - * @return an expression {@link Node}, never {@code null} - */ - private Node parseExpression() { return parseComparison(); } - - /** - * Parse an expression of the form: - * - * <pre> - * expr : additiveExpr op additiveExpr - * </pre> - * @return an comparator expression {@link Node}, never {@code null} - */ - private Node parseComparison() { - var lhs = parseAddition(); - while( true ) { - int idx=0; boolean negate=false; - // Test for any local nodes made, and "keep" lhs during peepholes - if( false ) ; - else if( match("==") ) { idx=2; lhs = new BoolNode.EQ(lhs, null); } - else if( match("!=") ) { idx=2; lhs = new BoolNode.EQ(lhs, null); negate=true; } - else if( match("<=") ) { idx=2; lhs = new BoolNode.LE(lhs, null); } - else if( match("<" ) ) { idx=2; lhs = new BoolNode.LT(lhs, null); } - else if( match(">=") ) { idx=1; lhs = new BoolNode.LE(null, lhs); } - else if( match(">" ) ) { idx=1; lhs = new BoolNode.LT(null, lhs); } - else break; - // Peepholes can fire, but lhs is already "hooked", kept alive - lhs.setDef(idx,parseAddition()); - lhs = lhs.peephole(); - if( negate ) // Extra negate for != - lhs = new NotNode(lhs).peephole(); - } - return lhs; - } - - /** - * Parse an additive expression - * - * <pre> - * additiveExpr : multiplicativeExpr (('+' | '-') multiplicativeExpr)* - * </pre> - * @return an add expression {@link Node}, never {@code null} - */ - private Node parseAddition() { - Node lhs = parseMultiplication(); - while( true ) { - if( false ) ; - else if( match("+") ) lhs = new AddNode(lhs,null); - else if( match("-") ) lhs = new SubNode(lhs,null); - else break; - lhs.setDef(2,parseMultiplication()); - lhs = lhs.peephole(); - } - return lhs; - } - - /** - * Parse an multiplicativeExpr expression - * - * <pre> - * multiplicativeExpr : unaryExpr (('*' | '/') unaryExpr)* - * </pre> - * @return a multiply expression {@link Node}, never {@code null} - */ - private Node parseMultiplication() { - var lhs = parseUnary(); - while( true ) { - if( false ) ; - else if( match("*") ) lhs = new MulNode(lhs,null); - else if( match("/") ) lhs = new DivNode(lhs,null); - else break; - lhs.setDef(2,parseUnary()); - lhs = lhs.peephole(); - } - return lhs; - } - - /** - * Parse a unary minus expression. - * - * <pre> - * unaryExpr : ('-') | '!') unaryExpr | postfixExpr | primaryExpr - * </pre> - * @return a unary expression {@link Node}, never {@code null} - */ - private Node parseUnary() { - if (match("-")) return new MinusNode(parseUnary()).peephole(); - if (match("!")) return new NotNode(parseUnary()).peephole(); - return parsePostfix(parsePrimary()); - } - - /** - * Parse a primary expression: - * - * <pre> - * primaryExpr : integerLiteral | Identifier | true | false | null | new Identifier | '(' expression ')' - * </pre> - * @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(); - if( matchx("null" ) ) return new ConstantNode(TypeMemPtr.NULLPTR).peephole(); - if( matchx("new") ) { - String structName = requireId(); - TypeStruct obj = OBJS.get(structName); - if( obj == null) throw errorSyntax("Unknown struct type '" + structName + "'"); - return newStruct(obj); - } - String name = _lexer.matchId(); - if( name == null) throw errorSyntax("an identifier or expression"); - Node n = _scope.lookup(name); - if( n!=null ) return n; - throw error("Undefined name '" + name + "'"); - } - - /** - * Return a NewNode but also generate instructions to initialize it. - */ - private Node newStruct( TypeStruct obj ) { - Node n = new NewNode(TypeMemPtr.make(obj), ctrl()).peephole().keep(); - Node initValue = new ConstantNode(TypeInteger.constant(0)).peephole(); - int alias = _aliases.get(obj._name); - for( Field field : obj._fields ) { - store(field._fname,alias,n,initValue); - alias++; - } - return n.unkeep(); - } - - // Memory is one hidden SSA variable, including across branches and loops. - private Node mem() { return _scope.lookup("$mem"); } - private Node mem(Node n) { return _scope.update("$mem",n); } - - private void store(String name, int alias, Node ptr, Node val) { - Node prior = mem().keep(); - Node st = new StoreNode(name,alias,prior,ptr,val).peephole(); - mem(new MemMergeNode(prior,alias,st).peephole()); - prior.unkeep(); - } - - /** - * Parse postfix expression. For now this is just a field - * expression, but in future could be array index too. - * - * <pre> - * expr ('.' IDENTIFIER)* [ = expr ] - * </pre> - */ - private Node parsePostfix(Node expr) { - if( !match(".") ) return expr; - - if( !(expr._type instanceof TypeMemPtr ptr) ) - throw error("Expected struct reference but got " + expr._type.str()); - - String name = requireId().intern(); - int idx = ptr._obj==null ? -1 : ptr._obj.find(name); - if( idx == -1 ) throw error("Accessing unknown field '" + name + "' from '" + ptr.str() + "'"); - int alias = _aliases.get(ptr._obj._name)+idx; - - if( match("=") ) { - // Disambiguate "obj.fld==x" boolean test from "obj.fld=x" field assignment - if( peek('=') ) _lexer._position--; - else { - Node val = parseExpression(); - store(name,alias,expr,val); - return expr; // "obj.a = expr" returns the expression while updating memory - } - } - - Type declaredType = ptr._obj._fields[idx]._type; - return parsePostfix(new LoadNode(name, alias, declaredType, mem(), expr).peephole()); - } - - /** - * Parse integer literal - * - * <pre> - * integerLiteral: [1-9][0-9]* | [0] - * </pre> - */ - private ConstantNode parseIntegerLiteral() { - return (ConstantNode) new ConstantNode(_lexer.parseNumber()).peephole(); - } - - ////////////////////////////////// - // Utilities for lexical analysis - - // Return true and skip if "syntax" is next in the stream. - private boolean match (String syntax) { return _lexer.match (syntax); } - // Match must be "exact", not be followed by more id letters - private boolean matchx(String syntax) { return _lexer.matchx(syntax); } - // Return true and do NOT skip if 'ch' is next - private boolean peek(char ch) { return _lexer.peek(ch); } - private boolean peekIsId() { return _lexer.peekIsId(); } - - // Require and return an identifier - private String requireId() { - String id = _lexer.matchId(); - if (id != null && !KEYWORDS.contains(id) ) return id; - throw error("Expected an identifier, found '"+id+"'"); - } - - - - // Require an exact match - private Parser require(String syntax) { require(null, syntax); return this; } - private <N> N require(N n, String syntax) { - if (match(syntax)) return n; - throw errorSyntax(syntax); - } - - RuntimeException errorSyntax(String syntax) { - return error("Syntax error, expected " + syntax + ": " + _lexer.getAnyNextToken()); - } - - public static RuntimeException error( String errorMessage ) { - return new RuntimeException(errorMessage); - } - - //////////////////////////////////// - // Lexer components - - private static class Lexer { - - // Input buffer; an array of text bytes read from a file or a string - private final byte[] _input; - // Tracks current position in input buffer - private int _position = 0; - - /** - * Record the source text for lexing - */ - public Lexer(String source) { - this(source.getBytes()); - } - - /** - * Direct from disk file source - */ - public Lexer(byte[] buf) { - _input = buf; - } - - // Very handy in the debugger, shows the unparsed program - @Override - public String toString() { - return new String(_input, _position, _input.length - _position); - } - - // True if at EOF - private boolean isEOF() { - return _position >= _input.length; - } - - // Peek next character, or report EOF - private char peek() { - return isEOF() ? Character.MAX_VALUE // Special value that causes parsing to terminate - : (char) _input[_position]; - } - - private char nextChar() { - char ch = peek(); - _position++; - return ch; - } - - // True if a white space - private boolean isWhiteSpace() { - return peek() <= ' '; // Includes all the use space, tab, newline, CR - } - - /** - * Return the next non-white-space character - */ - private void skipWhiteSpace() { - while (isWhiteSpace()) _position++; - } - - - // Return true, if we find "syntax" after skipping white space; also - // then advance the cursor past syntax. - // Return false otherwise, and do not advance the cursor. - boolean match(String syntax) { - skipWhiteSpace(); - int len = syntax.length(); - if (_position + len > _input.length) return false; - for (int i = 0; i < len; i++) - if ((char) _input[_position + i] != syntax.charAt(i)) - return false; - _position += len; - return true; - } - - // Match must be exact and not followed by more ID characters. - // Prevents identifier "ifxy" from matching an "if" statement. - boolean matchx(String syntax) { - if( !match(syntax) ) return false; - if( !isIdLetter(peek()) ) return true; - _position -= syntax.length(); - return false; - } - - private boolean peek(char ch) { - skipWhiteSpace(); - return peek()==ch; - } - - boolean peekIsId() { - skipWhiteSpace(); - return isIdStart(peek()); - } - - // Return an identifier or null - String matchId() { - return peekIsId() ? parseId() : null; - } - - // Used for errors - String getAnyNextToken() { - if (isEOF()) return ""; - if (isIdStart(peek())) return parseId(); - if (isNumber(peek())) return parseNumberString(); - if (isPunctuation(peek())) return parsePunctuation(); - return String.valueOf(peek()); - } - - boolean isNumber() {return isNumber(peek());} - boolean isNumber(char ch) {return Character.isDigit(ch);} - - private Type parseNumber() { - String snum = parseNumberString(); - if (snum.length() > 1 && snum.charAt(0) == '0') - throw error("Syntax error: integer values cannot start with '0'"); - return TypeInteger.constant(Long.parseLong(snum)); - } - private String parseNumberString() { - int start = _position; - while (isNumber(nextChar())) ; - return new String(_input, start, --_position - start); - } - - // First letter of an identifier - private boolean isIdStart(char ch) { - return Character.isAlphabetic(ch) || ch == '_'; - } - - // All characters of an identifier, e.g. "_x123" - private boolean isIdLetter(char ch) { - return Character.isLetterOrDigit(ch) || ch == '_'; - } - - private String parseId() { - int start = _position; - while (isIdLetter(nextChar())) ; - return new String(_input, start, --_position - start); - } - - private boolean isPunctuation(char ch) { - return "=;[]<>(){}+-/*!".indexOf(ch) != -1; - } - - private String parsePunctuation() { - int start = _position; - return new String(_input, start, 1); - } - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/Utils.java b/chapter10b/src/main/java/com/seaofnodes/simple/Utils.java deleted file mode 100644 index 4f2af769..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/Utils.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.seaofnodes.simple; - -import java.util.ArrayList; - -public class Utils { - public static RuntimeException TODO() { return TODO("Not yet implemented"); } - public static RuntimeException TODO(String msg) { return new RuntimeException(msg); } - - /** - * Fast, constant-time, element removal. Does not preserve order - * - * @param array ArrayList to modify - * @param i element to be removed - * @return element removed - */ - public static <E> E del(ArrayList<E> array, int i) { - if ( i >= 0 && i < array.size() ) { - E tmp = array.get(i); - E last = array.removeLast(); - if (i < array.size()) array.set(i, last); - return tmp; - } - return null; - } - - /** - * Search a list for an element by reference - * - * @param ary List to search in - * @param x Object to be searched - * @return >= 0 on success, -1 on failure - */ - public static <E> int find( ArrayList<E> ary, E x ) { - for( int i=0; i<ary.size(); i++ ) - if( ary.get(i)==x ) - return i; - return -1; - } - /** - * Search a list for an element by reference - * - * @param ary List to search in - * @param x Object to be searched - * @return >= 0 on success, -1 on failure - */ - public static <E> int find( E[] ary, E x ) { - for( int i=0; i<ary.length; i++ ) - if( ary[i]==x ) - return i; - return -1; - } - - // Rotate a long, nice for hashes - public static long rot( long x, int n ) { return (x<<n) | (x>>>n); } - - // Fold a 64bit hash into 32 bits - public static int fold( long x ) { return (int)((x>>32) ^ x); } - - public static boolean eq(String s0, String s1) { - if( s0==s1 ) return true; - assert s0==s0.intern(); - assert s1==s1.intern(); - return false; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/AddNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/AddNode.java deleted file mode 100644 index e235d288..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/AddNode.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.seaofnodes.simple.node; - - -import com.seaofnodes.simple.type.*; - - -public class AddNode extends Node { - public AddNode(Node lhs, Node rhs) { super(null, lhs, rhs); } - - @Override public String label() { return "Add"; } - - @Override protected String format() { return "(%1+%2)"; } - - - @Override - public Type compute() { - Type t1 = in(1)._type, t2 = in(2)._type; - if( t1==Type.TOP || t1==TypeInteger.TOP || - t2==Type.TOP || t2==TypeInteger.TOP ) - return TypeInteger.TOP; - if( t1 instanceof TypeInteger i0 && - t2 instanceof TypeInteger i1 ) { - if (i0.isConstant() && i1.isConstant()) - return TypeInteger.constant(i0.value()+i1.value()); - } - return TypeInteger.BOT; - } - - @Override - public Node idealize () { - Node lhs = in(1); - Node rhs = in(2); - Type t2 = rhs._type; - - // Add of 0. We do not check for (0+x) because this will already - // canonicalize to (x+0) - if( t2 instanceof TypeInteger i && i.value()==0 ) - return lhs; - - // Add of same to a multiply by 2 - if( lhs==rhs ) - return new MulNode(lhs,new ConstantNode(TypeInteger.constant(2)).peephole()); - - // Goal: a left-spine set of adds, with constants on the rhs (which then fold). - - // Move non-adds to RHS - if( !(lhs instanceof AddNode) && rhs instanceof AddNode ) - return swap12(); - - // x+(-y) becomes x-y - if( rhs instanceof MinusNode minus ) - return new SubNode(lhs,minus.in(1)); - - // Now we might see (add add non) or (add non non) or (add add add) but never (add non add) - - // Do we have x + (y + z) ? - // Swap to (x + y) + z - // Rotate (add add add) to remove the add on RHS - if( rhs instanceof AddNode add ) - return new AddNode(new AddNode(lhs,add.in(1)).peephole(), add.in(2)); - - // Now we might see (add add non) or (add non non) but never (add non add) nor (add add add) - if( !(lhs instanceof AddNode) ) - // Rotate; look for (add (phi cons) con/(phi cons)) - return spine_cmp(lhs,rhs,this) ? swap12() : phiCon(this,true); - - // Now we only see (add add non) - - // Dead data cycle; comes about from dead infinite loops. Do nothing, - // the loop will peep as dead after a bit. - if( lhs.in(1) == lhs ) - return null; - - // Do we have (x + con1) + con2? - // Replace with (x + (con1+con2) which then fold the constants - // lhs.in(2) is con1 here - // If lhs.in(2) is not a constant, we add ourselves as a dependency - // because if it later became a constant then we could make this - // transformation. - if( lhs.in(2).addDep(this)._type.isConstant() && rhs._type.isConstant() ) - return new AddNode(lhs.in(1),new AddNode(lhs.in(2),rhs).peephole()); - - - // 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...) - Node phicon = phiCon(this,true); - if( phicon!=null ) return phicon; - - // Now we sort along the spine via rotates, to gather similar things together. - - // Do we rotate (x + y) + z - // into (x + z) + y ? - if( spine_cmp(lhs.in(2),rhs,this) ) - return new AddNode(new AddNode(lhs.in(1),rhs).peephole(),lhs.in(2)); - - return null; - } - - // Rotation is only valid for associative ops, e.g. Add, Mul, And, Or. - // Do we have ((phi cons)|(x + (phi cons)) + con|(phi cons)) ? - // Push constant up through the phi: x + (phi con0+con0 con1+con1...) - static Node phiCon(Node op, boolean rotate) { - Node lhs = op.in(1); - Node rhs = op.in(2); - // LHS is either a Phi of constants, or another op with Phi of constants - PhiNode lphi = pcon(lhs,op); - if( rotate && lphi==null && lhs.nIns() > 2 ) { - // Only valid to rotate constants if both are same associative ops - if( lhs.getClass() != op.getClass() ) return null; - lphi = pcon(lhs.in(2),op); // Will rotate with the Phi push - } - if( lphi==null ) return null; - - // RHS is a constant or a Phi of constants - if( !(rhs instanceof ConstantNode) && pcon(rhs,op)==null ) - return null; - - // If both are Phis, must be same Region - if( rhs instanceof PhiNode && lphi.in(0) != rhs.in(0) ) - return null; - - // 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. - Node[] ns = new Node[lphi.nIns()]; - ns[0] = lphi.in(0); - // Push constant up through the phi: x + (phi con0+con0 con1+con1...) - for( int i=1; i<ns.length; i++ ) - ns[i] = op.copy(lphi.in(i), rhs instanceof PhiNode ? rhs.in(i) : rhs).peephole(); - String label = lphi._label + (rhs instanceof PhiNode rphi ? rphi._label : ""); - Node phi = new PhiNode(label,lphi._declaredType,ns).peephole(); - // Rotate needs another op, otherwise just the phi - return lhs==lphi ? phi : op.copy(lhs.in(1),phi); - } - - /** - * Tests if the op is a phi and has all constant inputs. - * If not, returns null. - * If op is a phi, but its inputs are not all constants, then dep is added as - * a dependency to the phi's non-const input, because if later the input turn into a constant - * dep can make progress. - */ - static PhiNode pcon(Node op, Node dep) { - return op instanceof PhiNode phi && phi.allCons(dep) ? phi : null; - } - - // Compare two off-spine nodes and decide what order they should be in. - // Do we rotate ((x + hi) + lo) into ((x + lo) + hi) ? - // Generally constants always go right, then Phi-of-constants, then muls, then others. - // Ties with in a category sort by node ID. - // TRUE if swapping hi and lo. - static boolean spine_cmp( Node hi, Node lo, Node dep ) { - if( lo._type.isConstant() ) return false; - if( hi._type.isConstant() ) return true ; - - if( lo instanceof PhiNode lphi && lphi.region()._type==Type.XCONTROL ) return false; - if( hi instanceof PhiNode hphi && hphi.region()._type==Type.XCONTROL ) return false; - - if( lo instanceof PhiNode && lo.allCons(dep) ) return false; - if( hi instanceof PhiNode && hi.allCons(dep) ) return true ; - - if( lo instanceof PhiNode && !(hi instanceof PhiNode) ) return true; - if( hi instanceof PhiNode && !(lo instanceof PhiNode) ) return false; - - // Same category of "others" - return lo._nid > hi._nid; - } - - @Override Node copy(Node lhs, Node rhs) { return new AddNode(lhs,rhs); } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/BoolNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/BoolNode.java deleted file mode 100644 index 63452dba..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/BoolNode.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeInteger; -import com.seaofnodes.simple.type.TypeMemPtr; - - -abstract public class BoolNode extends Node { - - public BoolNode(Node lhs, Node rhs) { - super(null, lhs, rhs); - } - - abstract String op(); // String opcode name - - @Override - public String label() { return getClass().getSimpleName(); } - - @Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - return p.open().n(in(1)).p(op()).n(in(2)).close(); - } - - @Override - public Type compute() { - Type t1 = in(1)._type, t2 = in(2)._type; - if( t1==Type.TOP || t1==TypeInteger.TOP || - t2==Type.TOP || t2==TypeInteger.TOP ) - return TypeInteger.TOP; - if( t1 instanceof TypeInteger i0 && - t2 instanceof TypeInteger i1 ) { - if (i0.isConstant() && i1.isConstant()) - return TypeInteger.constant(doOp(i0.value(), i1.value()) ? 1 : 0); - } - return TypeInteger.BOT; - } - - abstract boolean doOp(long lhs, long rhs); - - @Override - public Node idealize() { - // Compare of same - if( in(1)==in(2) ) - return new ConstantNode(TypeInteger.constant(doOp(3,3)?1:0)); - - // Equals pushes constant to the right; 5==X becomes X==5. - if( this instanceof EQ ) { - if( !(in(2) instanceof ConstantNode) ) { - // con==noncon becomes noncon==con - if( in(1) instanceof ConstantNode ) - return new EQ(in(2),in(1)); - // Equals sorts by NID otherwise: non.high == non.low becomes non.low == non.high - else if( in(1)._nid > in(2)._nid ) - return new EQ(in(2),in(1)); - } - // Equals X==0 becomes a !X - if( (in(2)._type == TypeInteger.ZERO || in(2)._type == TypeMemPtr.NULLPTR) ) - return new NotNode(in(1)); - } - - // Do we have ((phi cons) cmp con) ? - // Do we have ((phi cons) cmp (phi cons)) ? - // Push the compare up through the phi: (phi con0 cmp con, con1 cmp con...) - Node phicon = AddNode.phiCon(this,this instanceof EQ); - if( phicon!=null ) return phicon; - - 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; } 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/chapter10b/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java deleted file mode 100644 index 8d512f21..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.simple.IterPeeps; -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeMem; -import java.util.BitSet; - -/** - * A Phi for bulk memory. It covers all aliases except {@link #_aliases}; - * those aliases must be represented by parallel precise MemPhis at the same - * program slice. - */ -public class BulkMemPhiNode extends PhiNode { - - private static final BitSet EMPTY = new BitSet(); - - // Excluded Aliases; empty means NO exclusions. - // Each split clones the exclusions; published sets are never mutated. - public final BitSet _aliases; - - public BulkMemPhiNode(String label, Node... inputs) { - this(label,EMPTY,inputs); - } - - private BulkMemPhiNode(String label, BitSet aliases, Node... inputs) { - super(label,TypeMem.BOT,inputs); - _aliases = aliases; - } - - public boolean isSplit(int alias) { return _aliases.get(alias); } - - @Override public String label() { return "BulkPhi"+_aliases; } - - @Override - public Type compute() { - Type t = super.compute(); - return t instanceof TypeMem mem ? mem : - t==Type.BOTTOM ? TypeMem.BOT : - TypeMem.TOP; - } - - @Override - public Node idealize() { - Node progress = super.idealize(); - if( progress != null ) return progress; - if( ((RegionNode)region()).inProgress() || region().nIns()<=1 ) - return null; // Input is in-progress - - // "Peek through" a MemMerge that covers this alias set on its default - for( int i=1; i<nIns(); i++ ) - if( in(i) instanceof MemMergeNode mmm && canPeek(mmm) ) { - setDef(i,IterPeeps.add(mmm.in(1))); - return this; - } - - // If any input or output uses or defines a specific alias we cover, - // make a private MemPhi for it, and add it to the excluded list. - for( int i=1; i<nIns(); i++ ) { - int alias = inputAlias(in(i)); - if( alias!=0 ) - return slice(alias); - } - - for( int i=0; i<_outputs.size(); i++ ) { - int alias = outputAlias(_outputs.get(i)); - if( alias!=0 ) - return slice(alias); - } - - return null; - } - - static public boolean checkMem(Node n, int alias) { - for( Node m : n._inputs ) - // Bulk memory supplies this alias - if( m instanceof BulkMemPhiNode bulk ) { - if( bulk._aliases.get(alias) ) - return false; - } else if( m instanceof MemMergeNode mmm && - mmm.in(1) instanceof BulkMemPhiNode bulk && - bulk._aliases.get(alias) && - (alias >= mmm.nIns() || mmm.in(alias)==null) ) - return false; - return true; - } - - - // True if the MemMerge has no precise slice still covered by this Phi. - private boolean canPeek(MemMergeNode mmm) { - return missingAlias(mmm,false)==0; - } - - // Return an alias required by an input but still covered by this Phi, or 0. - private int inputAlias(Node n) { - return switch(n) { - case ProjNode proj -> 0; - case ConstantNode con -> 0; - case MemMergeNode mmm -> missingAlias(mmm,false); - case MemOpNode mem -> unsplit(mem._alias); - case BulkMemPhiNode bulk -> missingAlias(bulk); - default -> throw new AssertionError("Unexpected memory input "+n); - }; - } - - // Return an alias required by a user but still covered by this Phi, or 0. - private int outputAlias(Node use) { - // This decision depends backwards on an immediate user's alias/set. - // Normal graph-neighbor enqueueing flows from defs to uses, so retain - // an explicit forward dependency to revisit this Phi when the user - // sharpens. - use.addDepForwards(this); - return switch(use) { - case ScopeNode scope -> 0; - case MemMergeNode mmm -> missingAlias(mmm,true); - case BulkMemPhiNode bulk -> missingAlias(bulk); - case MemOpNode mem -> unsplit(mem._alias); - case MemPhiNode phi -> unsplit(phi._alias); - default -> { - assert use instanceof ReturnNode - : "Unexpected bulk-memory user "+use; - yield 0; - } - }; - } - - // Alias zero/one is bulk, and an already excluded precise alias cannot - // trigger another split of this Phi. - private int unsplit(int alias) { - if( alias <= 1 ) return 0; - assert !_aliases.get(alias); - return alias; - } - - // First alias excluded by the neighboring bulk Phi but not by this one. - private int missingAlias(BulkMemPhiNode bulk) { - for( int alias = bulk._aliases.nextSetBit(0); alias >= 0; alias = bulk._aliases.nextSetBit(alias+1) ) - if( !_aliases.get(alias) ) - return alias; - return 0; - } - - // First precise MemMerge slice still covered by this Phi. When inspecting - // a user, ignore slots which point back to this Phi. - private int missingAlias(MemMergeNode mmm, boolean user) { - for( int alias=2; alias<mmm.nIns(); alias++ ) - if( mmm.in(alias)!=null && - mmm.alias(alias)!=mmm.in(1) && - !_aliases.get(alias) ) - { assert (!user || mmm.in(alias)!=this); return alias; } - return 0; - } - - // Slice out given alias - private MemMergeNode slice( int alias ) { - assert !_aliases.get(alias); - // Inputs are the same; MemPhi will sharpen his own inputs. If a - // parallel precise Phi already exists, reuse it instead of building a - // duplicate for the same Region/alias pair. - Node mem = precisePhi(alias); - - BitSet aliases = ((BitSet)_aliases.clone()); - aliases.set(alias); - BulkMemPhiNode bphi = new BulkMemPhiNode(_label,aliases); - for( int i=0; i<nIns(); i++ ) - bphi.addDef(in(i)); - // Installing bphi creates a new bulk user with a different exclusion - // set. Queue the original memory inputs before bphi itself can peep - // away and hide those neighbor relationships. - for( int i=1; i<bphi.nIns(); i++ ) - IterPeeps.add(bphi.in(i)); - // Do not peephole bphi here, as BulkMemPhi can recursively start a - // second bulk rewrite before this one has finished. Let the worklist - // discover any further splits - bphi.setType(TypeMem.BOT); - Node bulk = bphi; - IterPeeps.add(bulk); - IterPeeps.add(mem); - return aggregate(bulk,alias,mem); - } - - // Build aggregate memory over a bulk Phi, preserving every precise slice - // which the bulk has already excluded. The named alias is newly supplied - // (or replaces its old slice). - MemMergeNode aggregate(Node bulk, int alias, Node precise) { - MemMergeNode mmm = new MemMergeNode(bulk); - for( int old = _aliases.nextSetBit(0); old >= 0; old = _aliases.nextSetBit(old+1) ) - { assert old != alias; mmm.alias(old,precisePhi(old));} - mmm.alias(alias,precise); - assert checkMerge(mmm); - return mmm; - } - - // Find or make the precise Phi parallel to this bulk Phi at the same merge. - private Node precisePhi(int alias) { - MemPhiNode mphi = _findPhi(alias); - if( mphi!=null ) return mphi; - - mphi = new MemPhiNode("$"+alias,alias); - mphi.addDef(region()); - // Due to cycles, must set before calling peephole - mphi.setType(TypeMem.make(alias)); - for( int i=1; i<nIns(); i++ ) - mphi.addDef(IterPeeps.add(preciseInput(in(i),alias))); - return IterPeeps.add(mphi); - } - - MemPhiNode _findPhi(int alias) { - for( Node use : region()._outputs ) - if( use instanceof MemPhiNode mphi && mphi._alias==alias ) - return mphi; - return null; - } - - // Select an alias already split out of a predecessor's bulk memory. - private Node preciseInput(Node mem, int alias) { - if( mem instanceof MemMergeNode mmm ) - return mmm.alias(alias); - if( mem instanceof BulkMemPhiNode bulk && bulk.isSplit(alias) ) - return bulk.precisePhi(alias); - return mem; - } - - // Every alias excluded by a bulk default must be supplied explicitly. - static boolean checkMerge(MemMergeNode mmm) { - if( !(mmm.in(1) instanceof BulkMemPhiNode bulk) ) return true; - for( int alias = bulk._aliases.nextSetBit(0); alias >= 0; alias = bulk._aliases.nextSetBit(alias+1) ) - if( alias >= mmm.nIns() || mmm.in(alias)==null ) - return false; - return true; - } - - @Override public boolean eq(Node n) { - return _aliases.equals(((BulkMemPhiNode)n)._aliases) && super.eq(n); - } - - @Override int hash() { return _aliases.hashCode(); } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/CastNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/CastNode.java deleted file mode 100644 index c1faf210..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/CastNode.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeInteger; -import com.seaofnodes.simple.IterPeeps; - - -// Upcast (join) the input to a t. Used after guard test to lift an input. -// Can also be used to make a type-assertion if ctrl is null. -public class CastNode extends Node { - private final Type _t; - public CastNode(Type t, Node ctrl, Node in) { - super(ctrl, in); - _t = t; - setType(compute()); - } - - @Override public String label() { return "("+_t.str()+")"; } - - - @Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - return p.p(label()).n(in(1)); - } - - @Override - public Type compute() { - return in(1)._type.join(_t); - } - - @Override - public Node idealize() { - return in(1)._type.isa(_t) ? in(1) : null; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/ConstantNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/ConstantNode.java deleted file mode 100644 index 426736ed..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/ConstantNode.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.Parser; -import com.seaofnodes.simple.type.Type; - - -/** - * A Constant node represents a constant value. At present, the only constants - * that we allow are integer literals; therefore Constants contain an integer - * value. As we add other types of constants, we will refactor how we represent - * Constants. - * <p> - * Constants have no semantic inputs. However, we set Start as an input to - * Constants to enable a forward graph walk. This edge carries no semantic - * meaning, and it is present <em>solely</em> to allow visitation. - * <p> - * The Constant's value is the value stored in it. - */ -public class ConstantNode extends Node { - final Type _con; - public ConstantNode( Type type ) { - super(Parser.START); - _con = type; - } - - @Override protected String repeatName() { - return _con==null || _con.toString().length()<=32 ? null : uniqueName(); - } - - @Override - public String label() { return "Con"; } - - - @Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - return p.p(_con); - } - - @Override public boolean isMultiTail() { return true; } - - @Override - public Type compute() { return _con; } - - @Override - public Node idealize() { return null; } - - @Override - boolean eq(Node n) { - ConstantNode con = (ConstantNode)n; // Contract - return _con==con._con; - } - - @Override - int hash() { return _con.hashCode(); } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/DivNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/DivNode.java deleted file mode 100644 index d7244ace..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/DivNode.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.seaofnodes.simple.node; - - -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeInteger; - - -public class DivNode extends Node { - public DivNode(Node lhs, Node rhs) { super(null, lhs, rhs); } - - @Override public String label() { return "Div"; } - - @Override protected String format() { return "(%1/%2)"; } - - @Override - public Type compute() { - Type t1 = in(1)._type, t2 = in(2)._type; - if( t1==Type.TOP || t1==TypeInteger.TOP || - t2==Type.TOP || t2==TypeInteger.TOP ) - return TypeInteger.TOP; - if (t1 instanceof TypeInteger i0 && - t2 instanceof TypeInteger i1) { - if (i0.isConstant() && i1.isConstant()) - return i1.value() == 0 - ? TypeInteger.ZERO - : TypeInteger.constant(i0.value()/i1.value()); - } - return TypeInteger.BOT; - } - - @Override - public Node idealize() { - // Div of 1. - if( in(2)._type.isConstant() && in(2)._type instanceof TypeInteger i && i.value()==1 ) - return in(1); - return null; - } - - @Override Node copy(Node lhs, Node rhs) { return new DivNode(lhs,rhs); } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/IfNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/IfNode.java deleted file mode 100644 index 45f695a5..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/IfNode.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.seaofnodes.simple.node; - - -import com.seaofnodes.simple.IterPeeps; -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); - IterPeeps.add(this); // Because idoms are complex, just add it - } - - @Override - public String label() { return "If"; } - - @Override protected String format() { return "if( %1 )"; } - - @Override public boolean isCFG() { return true; } - @Override public boolean isMultiHead() { return true; } - - public Node ctrl() { return in(0); } - public Node pred() { return in(1); } - - @Override - public Type compute() { - // If the If node is not reachable then neither is any following Proj - if (ctrl()._type != Type.CONTROL && ctrl()._type != Type.BOTTOM ) - return TypeTuple.IF_NEITHER; - Node pred = pred(); - Type t = pred._type; - // High types mean NEITHER side is reachable. - // Wait until the type falls to decide which way to go. - if( t == Type.TOP || t == TypeInteger.TOP ) - return TypeTuple.IF_NEITHER; - // If constant is 0 then false branch is reachable - // Else true branch is reachable - if (t instanceof TypeInteger ti && ti.isConstant()) - return ti==TypeInteger.ZERO ? TypeTuple.IF_FALSE : TypeTuple.IF_TRUE; - - return TypeTuple.IF_BOTH; - } - - @Override - public Node idealize() { - // Hunt up the immediate dominator tree. If we find an identical if - // test on either the true or false branch, that side wins. - if( !pred()._type.isHighOrConst() ) - for( Node dom = idom(), prior=this; dom!=null; prior = dom, dom = dom.idom() ) - if( dom.addDep(this) instanceof IfNode iff && iff.pred().addDep(this)==pred() && prior instanceof ProjNode prj ) { - setDef(1,new ConstantNode(TypeInteger.make(true,prj._idx==0?1:0)).peephole()); - return this; - } - return null; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/LoadNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/LoadNode.java deleted file mode 100644 index 9bf36459..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/LoadNode.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.Utils; -import com.seaofnodes.simple.IterPeeps; -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.Field; - - -/** - * Load represents extracting a value from inside a memory object, - * in chapter 10 this means Struct fields. - */ -public class LoadNode extends MemOpNode { - - Type _declaredType; - /** - * Load a value from a ptr.field. - * - * @param name The field we are loading - * @param memSlice The memory alias node - this is updated after a Store - * @param memPtr The ptr to the struct from where we load a field - */ - public LoadNode(String name, int alias, Type glb, Node memSlice, Node memPtr) { - super(name, alias, memSlice, memPtr, null); - _declaredType = glb; - } - - @Override boolean canDrop(MemOpNode other, Node dep) { - return super.canDrop(other,dep) && _declaredType==((LoadNode)other)._declaredType && !clobbered(dep); - } - - // Check only immediate memory users. Stores clobber memory; Phis and - // aggregates might lead to a clobber, so stop rather than search further. - private boolean clobbered(Node dep) { - Node mem = mem(); - mem.addDepForwards(dep); - for( Node use : mem._outputs ) { - if( use==null ) continue; - use.addDepForwards(dep); - if( use instanceof StoreNode || use instanceof PhiNode || - use instanceof MemMergeNode ) return true; - } - return false; - } - - @Override - public String label() { return "Load"; } - - @Override - protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { return p.p(".").p(_name); } - - @Override - public Type compute() { - return _declaredType; - } - - @Override - public Node idealize() { - if( mem() instanceof MemMergeNode merge ) { - setDef(1,IterPeeps.add(merge.alias(_alias))); - return this; - } - - - // Simple Load-after-Store on same address. - if( mem() instanceof StoreNode st && - ptr() == st.ptr() && _alias==st._alias ) { // Must check same object - assert Utils.eq(_name,st._name); // Equiv class aliasing is perfect - return st.val(); - } - - // Push a Load up through a Phi, as long as it collapses on at least - // one arm. If at a Loop, the backedge MUST collapse - else we risk - // spinning the same transform around the loop indefinitely. - // BEFORE (2 Sts, 1 Ld): AFTER (1 St, 0 Ld): - // if( pred ) ptr.x = e0; val = pred ? e0 - // else ptr.x = e1; : e1; - // val = ptr.x; ptr.x = val; - if( mem() instanceof MemPhiNode memphi && memphi.region()._type == Type.CONTROL && memphi.nIns()== 3 ) { - // Profit on RHS/Loop backedge - if( profit(memphi,2) || - // Else must not be a loop to count profit on LHS. - (!(memphi.region() instanceof LoopNode) && profit(memphi,1)) ) { - Node ld1 = new LoadNode(_name,_alias,_declaredType,memphi.in(1),ptr()).peephole(); - Node ld2 = new LoadNode(_name,_alias,_declaredType,memphi.in(2),ptr()).peephole(); - return new PhiNode(_name,_type,memphi.region(),ld1,ld2); - } - } - - return null; - } - - // Profitable if we find a matching Store on this Phi arm. - private boolean profit(PhiNode phi, int idx) { - Node px = phi.in(idx); - return px!=null && px.addDep(this) instanceof StoreNode st1 && ptr()==st1.ptr() && _alias==st1._alias; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/LoopNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/LoopNode.java deleted file mode 100644 index a0ba973e..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/LoopNode.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.simple.type.Type; - -import java.util.BitSet; - -public class LoopNode extends RegionNode { - - public LoopNode( Node entry ) { super(null,entry,null); } - - Node entry() { return in(1); } - Node back () { return in(2); } - - @Override - public String label() { return "Loop"; } - - @Override - public Type compute() { - if( inProgress() ) return Type.CONTROL; - return entry()._type; - } - - @Override - public Node idealize() { - return inProgress() ? null : super.idealize(); - } - - // Bypass Region idom, same as the default idom() using use entry in(1) instead of in(0) - @Override int idepth() { return _idepth!=0 ? _idepth : cacheIDepth(entry().idepth()+1); } - @Override Node idom() { return entry(); } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java deleted file mode 100644 index f3d5b01e..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.IterPeeps; -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeMem; - -/** All memory: a default slice and explicit overrides for individual aliases. */ -public class MemMergeNode extends Node { - public MemMergeNode(Node bulk) { super(null,bulk); _type = TypeMem.BOT; } - public MemMergeNode(Node bulk, int alias, Node precise) { - this(bulk); - alias(alias,precise); - } - - public Node alias(int alias) { - Node n = alias < nIns() ? in(alias) : null; - assert n!=null || !(in(1) instanceof BulkMemPhiNode bulk) || !bulk.isSplit(alias); - return n==null ? in(1) : n; - } - - public void alias(int alias, Node mem) { - assert alias > 1; - while( nIns()<=alias ) addDef(null); - setDef(alias,mem); - } - - @Override public String label() { return "MemMerge"; } - @Override public boolean isMem() { return true; } - @Override public Type compute() { return TypeMem.BOT; } - @Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - p.p("MEM["); - for( int i=1; i<nIns(); i++ ) - if( in(i)!=null ) { - p.p(i==1 ? "default:" : i+":"); - p.n(in(i)).p(" "); - } - return p.p("]"); - } - - @Override public Node idealize() { - boolean progress=false, allDefault=true; - for( int i=2; i<nIns(); i++ ) { - if( in(i)==in(1) ) { setDef(i,null); progress=true; } - if( in(i)!=null ) allDefault=false; - } - if( allDefault ) return in(1); - - if( in(1) instanceof MemMergeNode mem ) { - for( int i=2; i<mem.nIns(); i++ ) - if( mem.in(i)!=null && (i>=nIns() || in(i)==null) ) - alias(i,mem.in(i)); - IterPeeps.add(mem.in(1)); - setDef(1,mem.in(1)); - return this; - } - assert BulkMemPhiNode.checkMerge(this); - return progress ? this : null; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/MemOpNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/MemOpNode.java deleted file mode 100644 index 44304bcb..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/MemOpNode.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.simple.type.Field; -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeMemPtr; - -/** - * Convenience common base for Load and Store. - */ -public abstract class MemOpNode extends Node { - - public final String _name; - public final int _alias; - - public MemOpNode(String name, int alias, Node memSlice, Node memPtr, Node value) { - super(null, memSlice, memPtr, value); - _name = name; - _alias = alias; - } - - public Node mem() { return in(1); } - public Node ptr() { return in(2); } - - // Extra conditions for factoring matching memory operations through a Phi. - // The caller has already checked the opcode, input shape and control. - boolean canDrop(MemOpNode other, Node dep) { - ptr().addDep(dep); - return _alias==other._alias && err()==null; - } - - @Override - boolean eq(Node n) { - MemOpNode mem = (MemOpNode)n; // Invariant - return _alias==mem._alias; // When comparing types error to use "equals"; always use "==" - } - - @Override - int hash() { return _alias; } - - @Override - String err() { - Type ptr = ptr()._type; - return (ptr==Type.BOTTOM || (ptr instanceof TypeMemPtr tmp && tmp._nil) ) - ? "Might be null accessing '" + _name + "'" - : null; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/MemPhiNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/MemPhiNode.java deleted file mode 100644 index c806bede..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/MemPhiNode.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.simple.IterPeeps; -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeMem; - -/** A Phi for one field alias, parallel to a bulk Phi at the same Region. */ -public class MemPhiNode extends PhiNode { - public final int _alias; - - public MemPhiNode(String label, int alias, Node... inputs) { - super(label,TypeMem.make(alias),inputs); - assert alias > 1; - _alias = alias; - } - - @Override public String label() { return "MemPhi_"+_alias; } - - @Override public Type compute() { - assert BulkMemPhiNode.checkMem(this,_alias); - Type t = super.compute(); - return t==Type.TOP || t==TypeMem.TOP ? TypeMem.TOP : TypeMem.make(_alias); - } - - @Override public Node idealize() { - for( int i=1; i<nIns(); i++ ) - if( in(i) instanceof MemMergeNode mem ) { - setDef(i,IterPeeps.add(mem.alias(_alias))); - return this; - } - return super.idealize(); - } - - @Override boolean eq(Node n) { return _alias==((MemPhiNode)n)._alias && super.eq(n); } - @Override int hash() { return _alias; } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/MinusNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/MinusNode.java deleted file mode 100644 index 5b65b3fb..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/MinusNode.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.seaofnodes.simple.node; - - -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeInteger; - - -public class MinusNode extends Node { - public MinusNode(Node in) { super(null, in); } - - @Override public String label() { return "Minus"; } - - @Override protected String format() { return "(-%1)"; } - - @Override - public Type compute() { - if (in(1)._type instanceof TypeInteger i0) - return i0.isConstant() ? TypeInteger.constant(-i0.value()) : i0; - return in(1)._type==Type.TOP ? TypeInteger.TOP : TypeInteger.BOT; - } - - @Override - public Node idealize() { - // -(-x) is x - if( in(1) instanceof MinusNode minus ) - return minus.in(1); - - return null; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/MulNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/MulNode.java deleted file mode 100644 index 5592c52d..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/MulNode.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.seaofnodes.simple.node; - - -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeInteger; - - -public class MulNode extends Node { - public MulNode(Node lhs, Node rhs) { super(null, lhs, rhs); } - - @Override public String label() { return "Mul"; } - - @Override protected String format() { return "(%1*%2)"; } - - @Override - public Type compute() { - Type t1 = in(1)._type, t2 = in(2)._type; - if( t1==Type.TOP || t1==TypeInteger.TOP || - t2==Type.TOP || t2==TypeInteger.TOP ) - return TypeInteger.TOP; - if (t1 instanceof TypeInteger i0 && - t2 instanceof TypeInteger i1) { - if (i0.isConstant() && i1.isConstant()) - return TypeInteger.constant(i0.value()*i1.value()); - } - return TypeInteger.BOT; - } - - @Override - public Node idealize() { - Node lhs = in(1); - Node rhs = in(2); - Type t1 = lhs._type; - Type t2 = rhs._type; - - // Mul of 1. We do not check for (1*x) because this will already - // canonicalize to (x*1) - if ( t2.isConstant() && t2 instanceof TypeInteger i && i.value()==1 ) - return lhs; - - // Move constants to RHS: con*arg becomes arg*con - if ( t1.isConstant() && !t2.isConstant() ) - return swap12(); - - // 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...) - Node phicon = AddNode.phiCon(this,true); - if( phicon!=null ) return phicon; - - return null; - } - @Override Node copy(Node lhs, Node rhs) { return new MulNode(lhs,rhs); } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/MultiNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/MultiNode.java deleted file mode 100644 index 2743bd19..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/MultiNode.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.seaofnodes.simple.node; - -public abstract class MultiNode extends Node { - - public MultiNode(Node... inputs) { super(inputs); } - - // Find a projection by index - ProjNode proj( int idx ) { - for( Node out : _outputs ) - if( out instanceof ProjNode prj && prj._idx==idx ) - return prj; - return null; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/NewNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/NewNode.java deleted file mode 100644 index 857920bc..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/NewNode.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeMemPtr; - - -public class NewNode extends Node { - - TypeMemPtr _ptr; - - public NewNode(TypeMemPtr ptr, Node ctrl) { - super(ctrl); - this._ptr = ptr; - } - - @Override - public String label() { return "new"; } - - @Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - return p.p("new ").p(_ptr._obj.str()); - } - - @Override - public Type compute() { return _ptr; } - - @Override - public Node idealize() { return null; } - - @Override - boolean eq(Node n) { return this == n; } - - @Override - int hash() { return _ptr.hashCode(); } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/Node.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/Node.java deleted file mode 100644 index 1d8e23f8..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/Node.java +++ /dev/null @@ -1,604 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.BaseNode; - -import com.seaofnodes.simple.Parser; - -import com.seaofnodes.simple.IRPrinter; -import com.seaofnodes.simple.IterPeeps; -import com.seaofnodes.simple.Utils; -import com.seaofnodes.simple.type.Type; - -import java.util.*; -import java.util.function.Function; - -/** - * All Nodes in the Sea of Nodes IR inherit from the Node class. - * The Node class provides common functionality used by all subtypes. - * Subtypes of Node specialize by overriding methods. - */ -public abstract class Node extends BaseNode<Node> implements Cloneable { - - /** - * Inputs to the node. These are use-def references to Nodes. - * <p> - * Generally fixed length, ordered, nulls allowed, no unused trailing space. - * Ordering is required because e.g. "a/b" is different from "b/a". - * The first input (offset 0) is often a {@link #isCFG} node. - */ - public ArrayList<Node> _inputs; - - /** - * Outputs reference Nodes that are not null and have this Node as an - * input. These nodes are users of this node, thus these are def-use - * references to Nodes. - * <p> - * Outputs directly match inputs, making a directed graph that can be - * walked in either direction. These outputs are typically used for - * efficient optimizations but otherwise have no semantics meaning. - */ - public ArrayList<Node> _outputs; - - /** - * Current computed type for this Node. This value changes as the graph - * changes and more knowledge is gained about the program. - */ - public Type _type; - - /** - * A private Global Static mutable counter, for unique node id generation. - * To make the compiler multithreaded, this field will have to move into a TLS. - * Starting with value 1, to avoid bugs confusing node ID 0 with uninitialized values. - * */ - private static int UNIQUE_ID = 1; - public static int UID() { return UNIQUE_ID; } - - protected Node(Node... inputs) { - super(UNIQUE_ID++); // allocate unique dense ID - _inputs = new ArrayList<>(); - Collections.addAll(_inputs,inputs); - _outputs = new ArrayList<>(); - for( Node n : _inputs ) - if( n != null ) - n.addUse( this ); - } - - // Easy reading label for debugger, e.g. "Add" or "Region" or "EQ" - public abstract String label(); - - public String p(int depth) { return IRPrinter.prettyPrint(this,depth); } - - public boolean isMultiHead() { return false; } - public boolean isMultiTail() { return false; } - - // ------------------------------------------------------------------------ - // Graph Node & Edge manipulation - - @Override public String typeName() { return _type==null ? null : _type.toString(); } - - /** - * Gets the ith input node - * @param i Offset of the input node - * @return Input node or null - */ - public Node in(int i) { return _inputs.get(i); } - public Node out(int i) { return _outputs.get(i); } - - public int nIns() { return _inputs.size(); } - - public int nOuts() { return _outputs.size(); } - - public boolean isUnused() { return nOuts() == 0; } - - public boolean isMem() { return false; } - - /** - * Change a <em>def</em> into a Node. Keeps the edges correct, by removing - * the corresponding <em>use->def</em> edge. This may make the original - * <em>def</em> go dead. This function is co-recursive with {@link #kill}. - * <p> - - * This method is the normal path for altering a Node, because it does the - * proper default edge maintenance. It also <em>immediately</em> kills - * Nodes that lose their last use; at times care must be taken to avoid - * killing Nodes that are being used without having an output Node. This - * definitely happens in the middle of recursive {@link #peephole} calls. - * - * @param idx which def to set - * @param new_def the new definition - * @return new_def for flow coding - */ - public Node setDef(int idx, Node new_def ) { - unlock(); - Node old_def = in(idx); - if( old_def == new_def ) return new_def; // No change - // If new def is not null, add the corresponding def->use edge - // This needs to happen before removing the old node's def->use edge as - // the new_def might get killed if the old node kills it recursively. - if( new_def != null ) - new_def.addUse(this); - if( old_def != null && // If the old def exists, remove a def->use edge - old_def.delUse(this) ) // If we removed the last use, the old def is now dead - old_def.kill(); // Kill old def - // Set the new_def over the old (killed) edge - _inputs.set(idx,new_def); - moveDepsToWorklist(); - // Return self for easy flow-coding - return new_def; - } - - // Remove the numbered input, compressing the inputs in-place. This - // shuffles the order deterministically - which is suitable for Region and - // Phi, but not for every Node. If the def goes dead, it is recursively - // killed, which may include 'this' Node. - Node delDef(int idx) { - unlock(); - Node old_def = in(idx); - if( old_def != null && // If the old def exists, remove a def->use edge - old_def.delUse(this) ) // If we removed the last use, the old def is now dead - old_def.kill(); // Kill old def - old_def.moveDepsToWorklist(); - Utils.del(_inputs, idx); - return this; - } - - /** - * Add a new def to an existing Node. Keep the edges correct by - * adding the corresponding <em>def->use</em> edge. - * - * @param new_def the new definition, appended to the end of existing definitions - * @return new_def for flow coding - */ - Node addDef(Node new_def) { - unlock(); - // Add use->def edge - _inputs.add(new_def); - // If new def is not null, add the corresponding def->use edge - if( new_def != null ) - new_def.addUse(this); - return new_def; - } - - // Breaks the edge invariants, used temporarily - protected <N extends Node> void addUse(N n) { _outputs.add(n); } - - // Remove node 'use' from 'def's (i.e. our) output list, by compressing the list in-place. - // Return true if the output list is empty afterward. - // Error is 'use' does not exist; ok for 'use' to be null. - protected boolean delUse( Node use ) { - Utils.del(_outputs, Utils.find(_outputs, use)); - moveDepsToWorklist(); // User-count and anti-dependence queries can now change. - return _outputs.isEmpty(); - } - - // Shortcut for "popping" n nodes. A "pop" is basically a - // setDef(last,null) followed by lowering the nIns() count. - void popN(int n) { - unlock(); - for( int i=0; i<n; i++ ) { - Node old_def = _inputs.removeLast(); - 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 old def - } - } - - /** - * Kill a Node with no <em>uses</em>, by setting all of its <em>defs</em> - * to null. This may recursively kill more Nodes, and is basically dead - * code elimination. - */ - public void kill( ) { - unlock(); - assert isUnused(); // Has no uses, so it is dead - _type=null; // Flag as dead - while( nIns()>0 ) { // Set all inputs to null, recursively killing unused Nodes - Node old_def = _inputs.removeLast(); - if( old_def != null ) { - IterPeeps.add(old_def);// Revisit neighbor because removed use - if( old_def.delUse(this) ) // If we removed the last use, the old def is now dead - old_def.kill(); // Kill old def - } - } - assert isDead(); // Really dead now - } - - // Mostly used for asserts and printing. - public boolean isDead() { return isUnused() && nIns()==0 && _type==null; } - - // Shortcuts to stop DCE mid-parse - // Add bogus null use to keep node alive - public <N extends Node> N keep() { addUse(null); return (N)this; } - // Remove bogus null. - public <N extends Node> N unkeep() { delUse(null); return (N)this; } - // Test "keep" status - public boolean iskeep() { return Utils.find(_outputs,null) != -1; } - - // Replace self with nnn in the graph, making 'this' go dead - public void subsume( Node nnn ) { - assert nnn!=this; - while( nOuts() > 0 ) { - Node n = _outputs.removeLast(); - n.unlock(); - int idx = Utils.find(n._inputs, this); - n._inputs.set(idx,nnn); - n.moveDepsToWorklist(); // Rewiring can change a dependent query without changing type. - nnn.addUse(n); - } - kill(); - } - - // ------------------------------------------------------------------------ - // Graph-based optimizations - - /** - * Try to peephole at this node and return a better replacement Node. - * Always returns some not-null Node (often this). - */ - public final Node peephole() { - var obs = IterPeeps.midAssert() ? null : Parser.PARSER == null ? null : Parser.PARSER._obs; - if( obs != null ) obs.before(this); - Node n = peepholeOpt(); - Node rez = n == null ? this : deadCodeElim(n.peephole()); - if( obs != null ) obs.after(this, n == null ? null : rez, false); - return rez; - } - - /** - * Try to peephole at this node and return a better replacement Node if - * possible. We compute a {@link Type} and then check and replace: - * <ul> - * <li>if the Type {@link Type#isConstant}, we replace with a {@link ConstantNode}</li> - * <li>in a future chapter we will look for a - * <a href="https://en.wikipedia.org/wiki/Common_subexpression_elimination">Common Subexpression</a> - * to eliminate.</li> - * <li>we ask the Node for a better replacement. The "better replacement" - * is things like {@code (1+2)} becomes {@code 3} and {@code (1+(x+2))} becomes - * {@code (x+(1+2))}. By canonicalizing expressions we fold common addressing - * math constants, remove algebraic identities and generally simplify the - * code. </li> - * - * Unlike peephole above, this explicitly returns null for no-change, or not-null - * for a better replacement (which can be this). - * </ul> - */ - public final Node peepholeOpt( ) { - ITER_CNT++; - // Compute initial or improved Type - Type old = setType(compute()); - - // Replace constant computations from non-constants with a constant node - if( !(this instanceof ConstantNode) && _type.isHighOrConst() ) - return new ConstantNode(_type).peepholeOpt(); - - // Global Value Numbering - if( _hash==0 ) { - Node n = GVN.get(this); // Will set _hash as a side effect - if( n==null ) - GVN.put(this,this); // Put in table now - else { - // Because of random worklist ordering, the two equal nodes - // might have different types. Because of monotonicity, both - // types are valid. To preserve monotonicity, the resulting - // shared Node has to have the best of both types. - n.setType(n._type.join(_type)); - _hash = 0; // Clear, since it never went in the table - return deadCodeElim(n);// Return previous; does Common Subexpression Elimination - } - } - - // Ask each node for a better replacement - Node n = idealize(); - if( n != null ) // Something changed - return n; // Report progress - - if( old==_type ) ITER_NOP_CNT++; - return old==_type ? null : this; // Report progress - } - public static int ITER_CNT, ITER_NOP_CNT; - - // 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() && !isDead() ) { - // 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.keep(); // Keep m alive - kill(); // Kill self because replacing with 'm' - m.unkeep(); // Okay to peephole m - } - return m; - } - - /** - * This function needs to be - * <a href="https://en.wikipedia.org/wiki/Monotonic_function">Monotonic</a> - * as it is part of a Monotone Analysis Framework. - * <a href="https://www.cse.psu.edu/~gxt29/teaching/cse597s21/slides/08monotoneFramework.pdf">See for example this set of slides</a>. - * <p> - * For Chapter 2, all our Types are really integer constants, and so all - * the needed properties are trivially true, and we can ignore the high - * theory. Much later on, this will become important and allow us to do - * many fancy complex optimizations trivially... because theory. - * <p> - * {@link #compute()} needs to be stand-alone, and cannot recursively call compute - * on its inputs, because programs are cyclic (have loops!) and this will just - * infinitely recurse until stack overflow. Instead, compute typically - * computes a new type from the {@link #_type} field of its inputs. - */ - public abstract Type compute(); - - // Set the type. Assert monotonic progress. - // If changing, add users to worklist. - public Type setType(Type type) { - Type old = _type; - assert old==null || type.isa(old); // Since _type not set, can just re-run this in assert in the debugger - if( old == type ) return old; - _type = type; // Set _type late for easier assert debugging - IterPeeps.addAll(_outputs); - moveDepsToWorklist(); - return old; - } - - /** - * This function rewrites the current Node into a more "idealized" form. - * This is the bulk of our peephole rewrite rules, and we use this to - * e.g. turn arbitrary collections of adds and multiplies with mixed - * constants into a normal form that's easy for hardware to implement. - * Example: An array addressing expression: - * <pre> ary[idx+1]</pre> - * might turn into Sea-of-Nodes IR: - * <pre> (ary+12)+((idx+1) * 4)</pre> - * This expression can then be idealized into: - * <pre> ary + ((idx*4) + (12 + (1*4)))</pre> - * And more folding: - * <pre> ary + ((idx<<2) + 16)</pre> - * And during code-gen: - * <pre> MOV4 Rary,Ridx,16 // or some such hardware-specific notation </pre> - * <p> - * {@link #idealize} has a very specific calling convention: - * <ul> - * <li>If NO change is made, return {@code null} - * <li>If ANY change is made, return not-null; this can be {@code this} - * <li>The returned Node does NOT call {@link #peephole} on itself; the {@link #peephole} call will recursively peephole it. - * <li>Any NEW nodes that are not directly returned DO call {@link #peephole}. - * </ul> - * <p> - * Examples: - * <table border="3"> - * <tr><th> before </th><th> after </th><th>return </th><th>comment </th></tr> - * <tr><td>{@code (x+5) }</td><td>{@code (x+5) }</td><td>{@code null }</td><td>No change</td></tr> - * <tr><td>{@code (5+x) }</td><td>{@code (x+5) }</td><td>{@code this }</td><td>Swapped arguments</td></tr> - * <tr><td>{@code ((x+1)+2)}</td><td>{@code (x+(1+2))}</td><td>{@code (x+_) }</td><td>Returns 2 new Nodes</td></tr> - * </table> - * - * The last entry deserves more discussion. The new Node {@code (1+2)} - * created in {@link #idealize} calls {@link #peephole} (which then folds - * into a constant). The other new Node {@code (x+3)} does not call - * peephole, because it is returned and peephole itself will recursively - * call peephole. - * <p> - * Since idealize calls peephole and peephole calls idealize, you must be - * careful that all idealizations are <em>monotonic</em>: all transforms - * remove some feature, so that the set of available transforms always - * shrinks. If you don't, you risk an infinite peephole loop! - * - * @return Either a new or changed node, or null for no changes. - */ - public abstract Node idealize(); - - // Some of the peephole rules get complex, and search further afield than - // just the nearest neighbor. These peepholes can fail the pattern match - // on a node some distance away, and if that node ever changes we should - // retry the peephole. Track a set of Nodes dependent on `this`, and - // revisit them if `this` changes. - ArrayList<Node> _deps; - public int nDeps() { return _deps == null ? 0 : _deps.size(); } - public Node dep(int idx) { return _deps.get(idx); } - - /** - * Add a node to the list of dependencies. Only add it if its not an input - * or output of this node, that is, it is at least one step away. The node - * being added must benefit from this node being peepholed. - */ - Node addDep( Node dep ) { - return addDep(dep,false); - } - - // A bulk Phi inspects its users' partitions. Def-to-use propagation does - // not revisit that producer when an immediate user's partition changes. - Node addDepForwards(Node dep) { return addDep(dep,true); } - - private Node addDep(Node dep, boolean forwards) { - // Running peepholes during the big assert cannot have side effects - // like adding dependencies. - if( IterPeeps.midAssert() ) return this; - var obs = IterPeeps.midAssert() ? null : Parser.PARSER == null ? null : Parser.PARSER._obs; - if( obs != null ) obs.dep(this, dep); - if( _deps==null ) _deps = new ArrayList<>(); - if( Utils.find(_deps ,dep) != -1 ) return this; // Already on list - if( !forwards && Utils.find(_inputs,dep) != -1 ) return this; - if( !forwards && Utils.find(_outputs,dep)!= -1 ) return this; - _deps.add(dep); - return this; - } - - // Move the dependents onto a worklist, and clear for future dependents. - public void moveDepsToWorklist( ) { - if( _deps==null ) return; - IterPeeps.addAll(_deps); - _deps.clear(); - } - - // Global Value Numbering. Hash over opcode and inputs; hits in this table - // are structurally equal. - public static final HashMap<Node,Node> GVN = new HashMap<>(); - - // Two nodes are equal if they have the same inputs and the same "opcode" - // which means the same Java class, plus same internal parts. - @Override public final boolean equals( Object o ) { - if( o==this ) return true; - if( o.getClass() != getClass() ) return false; - Node n = (Node)o; - int len = _inputs.size(); - if( len != n._inputs.size() ) return false; - for( int i=0; i<len; i++ ) - if( in(i) != n.in(i) ) - return false; - return eq(n); - } - // Subclasses add extra checks (such as ConstantNodes have same constant), - // and can assume "this!=n" and has the same Java class. - boolean eq( Node n ) { return true; } - - // Cached hash. If zero, then not computed AND this Node is NOT in the GVN - // table - and can have its edges hacked (which will change his hash - // anyway). If Non-Zero then this Node is IN the GVN table, or is being - // probed to see if it can be inserted. His edges are "locked", because - // hacking his edges will change his hash. - int _hash; - - // If the _hash is set, then the Node is in the GVN table; remove it. - void unlock() { - if( _hash==0 ) return; - Node old = GVN.remove(this); // Pull from table - assert old==this; - _hash=0; // Out of table now - } - - // Hash of opcode and inputs - @Override public final int hashCode() { - if( _hash != 0 ) return _hash; - int hash = hash(); - for( Node n : _inputs ) - if( n != null ) - hash = hash ^ (hash<<17) ^ (hash>>13) ^ n._nid; - if( hash==0 ) hash = 0xDEADBEEF; // Bad hash, so use some junky thing - return (_hash=hash); - } - // Subclasses add extra hash info (such as ConstantNodes constant) - int hash() { return 0; } - - // ------------------------------------------------------------------------ - // Peephole utilities - - // Swap inputs without letting either input go dead during the swap. - Node swap12() { - unlock(); // Hash is order dependent - Node tmp = in(1); - _inputs.set(1,in(2)); - _inputs.set(2,tmp); - return this; - } - - /** - * Does this node contain all constants? Ignores in(0), as is usually - * control. In an input is not a constant, we add dep as a dependency to - * it because dep can make progress if the input becomes a constant later. - * It is sufficient for one of the non-const inputs to have the dependency, - * so we don't bother checking the rest. - */ - boolean allCons(Node dep) { - for( int i=1; i<nIns(); i++ ) - if( !(in(i)._type.isConstant()) ) { - in(i).addDep(dep); // If in(i) becomes a constant later, will trigger some peephole - return false; - } - return true; - } - - /** - * Immediate dominator tree depth, used to approximate a real IDOM depth - * during parsing where we do not have the whole program, and also - * peepholes change the CFG incrementally. - * <p> - * See {@link <a href="https://en.wikipedia.org/wiki/Dominator_(graph_theory)">...</a>} - */ - public char _idepth; // IDOM depth approx; Zero is unset; non-zero is cached legit - - // Find the lowest common ancestor in the current dominator tree. - Node domLCA(Node rhs) { - if( rhs==null ) return this; - Node lhs = this; - while( lhs != rhs ) { - if( lhs==null || rhs==null ) return null; - int comp = lhs.idepth() - rhs.idepth(); - if( comp >= 0 ) lhs = lhs.idom(); - if( comp <= 0 ) rhs = rhs.idom(); - } - return lhs; - } - - int idepth() { return _idepth!=0 ? _idepth : cacheIDepth(idom().idepth()+1); } - // Zero depth means uncached. Check before narrowing so overflow cannot wrap. - final int cacheIDepth(int depth) { - assert 0 <= depth && depth <= Character.MAX_VALUE : "Dominator depth exceeds 65535"; - return _idepth = (char)depth; - } - - // Return the immediate dominator of this Node. - Node idom() { return in(0); } - - // Make a shallow copy (same class) of this Node, with given inputs and - // empty outputs and a new Node ID. The original inputs are ignored. - // Does not need to be implemented in isCFG() nodes. - Node copy(Node lhs, Node rhs) { throw Utils.TODO("Binary ops need to implement copy"); } - - // Exact-class copy preserving operation attributes, with fresh identity - // and no edges, dependencies, or GVN membership. - public final Node copyEmpty() { - Node n; - try { n = (Node)clone(); } - catch( CloneNotSupportedException e ) { throw new AssertionError(e); } - n._nid = UNIQUE_ID++; - n._inputs = new ArrayList<>(); - n._outputs = new ArrayList<>(); - n._deps = null; - n._hash = 0; - return n; - } - - // Report any post-optimize errors - String err() { return null; } - - /** - * Used to allow repeating tests in the same JVM. This just resets the - * Node unique id generator, and is done as part of making a new Parser. - */ - public static void reset() { - UNIQUE_ID = 1; - GVN.clear(); - ITER_CNT = ITER_NOP_CNT = 0; - } - - // Utility to walk the entire graph applying a function; return the first - // not-null result. - private static final BitSet WVISIT = new BitSet(); - final public <E> E walk( Function<Node,E> pred ) { - assert WVISIT.isEmpty(); - E rez = _walk(pred); - WVISIT.clear(); - return rez; - } - - private <E> E _walk( Function<Node,E> pred ) { - if( WVISIT.get(_nid) ) return null; // Been there, done that - WVISIT.set(_nid); - E x = pred.apply(this); - if( x != null ) return x; - for( Node def : _inputs ) if( def != null && (x = def._walk(pred)) != null ) return x; - for( Node use : _outputs ) if( use != null && (x = use._walk(pred)) != null ) return x; - return null; - } - - /** - * Debugging utility to find a Node by index - */ - public Node find(int nid) { - return walk( n -> n._nid==nid ? n : null ); - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/NotNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/NotNode.java deleted file mode 100644 index 5e556390..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/NotNode.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.seaofnodes.simple.node; - - -import com.seaofnodes.simple.Utils; -import com.seaofnodes.simple.type.*; - -public class NotNode extends Node { - public NotNode(Node in) { super(null, in); } - - @Override public String label() { return "Not"; } - - @Override protected String format() { return "(!%1)"; } - - @Override - public Type compute() { - Type t0 = in(1)._type; - switch( t0 ) { - case TypeInteger i0: - return i0.isConstant() ? TypeInteger.constant(i0.value()==0 ? 1 : 0) : i0; - case TypeMemPtr p0: - // top->top, bot->bot, null->1, *void->0, not-null ptr->0, ptr/nil->bot - // If input in null then true - // If input is not null ptr then false - if( p0 == TypeMemPtr.TOP ) return TypeInteger.TOP; - if( p0 == TypeMemPtr.NULLPTR ) return TypeInteger.constant(1); - if( !p0._nil ) return TypeInteger.constant(0); - return TypeInteger.BOT; - case Type t: - if( t0.getClass() != Type.class ) - // Only doing NOT on ints and ptrs - throw Utils.TODO(); - return t0==Type.TOP ? TypeInteger.TOP : TypeInteger.BOT; - } - } - - @Override - public Node idealize() { return null; } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/PhiNode.java deleted file mode 100644 index 6995cc2f..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/PhiNode.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeMem; -import com.seaofnodes.simple.Utils; - - -public class PhiNode extends Node { - - final String _label; - - // The Phi type we compute must stay within the domain of the Phi. - // Example Int stays Int, Ptr stays Ptr, Control stays Control, Mem stays Mem. - final Type _declaredType; - - public PhiNode(String label, Type declaredType, Node... inputs) { super(inputs); _label = label; assert declaredType!=null; _declaredType = declaredType; } - - public static PhiNode make(String label, Type type, Node... inputs) { - return type instanceof TypeMem ? new BulkMemPhiNode(label,inputs) : new PhiNode(label,type,inputs); - } - - @Override public String label() { return "Phi_"+_label; } - - @Override - protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - if( !(region() instanceof RegionNode r) || r.inProgress() ) - p.p("Z"); - p.p("Phi("); - for( Node in : _inputs ) p.n(in).p(","); - return p.unchar(',').close(); - } - - Node region() { return in(0); } - @Override public boolean isMultiTail() { return true; } - @Override - public boolean isMem() { return _declaredType instanceof TypeMem; } - - @Override - public Type compute() { - if( !(region() instanceof RegionNode r) ) - return region()._type==Type.XCONTROL ? Type.TOP : _type; - // During parsing Phis have to be computed type pessimistically. - if( r.inProgress() ) return _declaredType; - // Set type to local top of the starting type - Type t = _declaredType.glb().dual(); - for (int i = 1; i < nIns(); i++) - // If the region's control input is live, add this as a dependency - // to the control because we can be peeped should it become dead. - if( r.in(i).addDep(this)._type != Type.XCONTROL ) - t = t.meet(in(i)._type); - return t; - } - - @Override - public Node idealize() { - if( !(region() instanceof RegionNode r ) ) - return in(1); // Input has collapse to e.g. starting control. - if( r.inProgress() || r.nIns()<=1 ) - return null; // Input is in-progress - - // If we have only a single unique input, become it. - Node live = singleUniqueInput(); - if (live != null) - return live; - - // Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...). - Node down; - if( same_op() && (down=drop_same_op())!=null ) return down; - - // If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove. - if( nIns()==3 ) { - if( in(1) instanceof CastNode cast && cast.in(1).addDep(this)==in(2) ) return in(2); - if( in(2) instanceof CastNode cast && cast.in(1).addDep(this)==in(1) ) return in(1); - } - // If merging a null-checked null and the checked value, just use the value. - // if( val ) ..; phi(Region,False=0/null,True=val); - // then replace with plain val. - if( nIns()==3 ) { - int nullx = -1; - if( in(1)._type == in(1)._type.makeInit() ) nullx = 1; - if( in(2)._type == in(2)._type.makeInit() ) nullx = 2; - if( nullx != -1 ) { - Node val = in(3-nullx); - if( region().idom() instanceof IfNode iff && iff.pred().addDep(this)==val ) { - // Must walk the idom on the null side to make sure we hit False. - Node idom = region().in(nullx); - while( idom.in(0) != iff ) idom = idom.idom(); - if( idom instanceof ProjNode proj && proj._idx==1 ) - return val; - } - } - } - - return null; - } - - private boolean same_op() { - Node op = in(1); - if( op.isCFG() || op instanceof ConstantNode || op instanceof PhiNode || - op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false; - // A bulk Phi must split its aliases before factoring precise Stores. - if( this instanceof BulkMemPhiNode ) return false; - // Bulk splitting currently identifies parallel slices by Region/alias. - // Factoring can introduce another slice at a different memory point; - // wait until that Region's bulk partitioning has finished. - if( op instanceof MemOpNode ) - for( Node use : region()._outputs ) - if( use instanceof BulkMemPhiNode ) { - use.addDepForwards(this); - return false; - } - Node busy = null; - for( int i=1; i<nIns(); i++ ) { - Node n = in(i); - if( region().in(i).addDep(this)._type==Type.XCONTROL || - op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false; - if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false; - // Moving a Store must remove the old effect, not duplicate it. - // Allow one shared arm: the other arms disappear into the single - // factored operation, usually reducing the total operation count. - n.addDepForwards(this); - if( n.nOuts()>1 ) { - for( Node use : n._outputs ) - if( use!=null && use!=this ) use.addDepForwards(this); - if( n instanceof StoreNode || busy!=null ) return false; - busy=n; - } - for( int j=1; j<n.nIns(); j++ ) - if( n.in(j) instanceof ScopeNode || ((n.in(j)==null) != (op.in(j)==null)) ) return false; - } - return true; - } - - private Node drop_same_op() { - Node op = in(1), cp = op.copyEmpty(); - cp._type = null; - cp.addDef(null); - for( int j=1; j<op.nIns(); j++ ) { - Node x = op.in(j); - boolean different = false; - for( int i=2; i<nIns(); i++ ) - if( in(i).in(j)!=x ) different=true; - if( different ) { - Node[] ins = new Node[nIns()]; - ins[0] = region(); - Type t = Type.TOP; - for( int i=1; i<nIns(); i++ ) { - ins[i] = in(i).in(j); - t = t.meet(ins[i]._type); - } - PhiNode phi = j==1 && op instanceof MemOpNode mem - ? new MemPhiNode(_label,mem._alias,ins) - : PhiNode.make(_label,t.glb(),ins); - x = phi.peephole(); - } - cp.addDef(x); - } - // Factoring must not widen the result (e.g. correlated And operands). - if( cp.compute().isa(compute()) ) return cp; - cp.kill(); - return null; - } - - /** - * If only single unique input, return it - */ - private Node singleUniqueInput() { - if( region() instanceof LoopNode loop && loop.entry()._type == Type.XCONTROL ) - return null; // Dead entry loops just ignore and let the loop collapse - Node live = null; - for( int i=1; i<nIns(); i++ ) { - // If the region's control input is live, add this as a dependency - // to the control because we can be peeped should it become dead. - if( region().in(i).addDep(this)._type != Type.XCONTROL && in(i) != this ) - if( live == null || live == in(i) ) live = in(i); - else return null; - } - return live; - } - - @Override - boolean allCons(Node dep) { - if( !(region() instanceof RegionNode r) ) return false; - // When the region completes (is no longer in progress) the Phi can - // become a "all constants" Phi, and the "dep" might make progress. - addDep(dep); - if( r.inProgress() ) return false; - return super.allCons(dep); - } - - // True if last input is null - public final boolean inProgress() { - return in(nIns()-1) == null; - } - - // Never equal if inProgress - @Override boolean eq( Node n ) { - return !inProgress(); - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/ProjNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/ProjNode.java deleted file mode 100644 index a2632110..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/ProjNode.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeMem; -import com.seaofnodes.simple.type.TypeTuple; - - -public class ProjNode extends Node { - - // Which slice of the incoming multipart value - public final int _idx; - - // Debugging label - public final String _label; - - public ProjNode(MultiNode ctrl, int idx, String label) { - super(ctrl); - _idx = idx; - _label = label; - } - - @Override - public String label() { return _label; } - - @Override - protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { return p.p(_label); } - - @Override public boolean isCFG() { return _idx==0 || ctrl() instanceof IfNode; } - @Override public boolean isMultiTail() { return in(0).isMultiHead(); } - @Override public boolean isMem() { return _type instanceof TypeMem; } - - public MultiNode ctrl() { return (MultiNode)in(0); } - - @Override - public Type compute() { - Type t = in(0)._type; - return t instanceof TypeTuple tt ? tt._types[_idx] : Type.BOTTOM; - } - - @Override - public Node idealize() { - if ( ctrl() instanceof IfNode iff ) { - if ( iff._type instanceof TypeTuple tt && tt._types[1 - _idx] == Type.XCONTROL ) - return iff.in(0); // We become our input control - - // Flip a negating if-test, to remove the not - if( iff.pred().addDep(this) instanceof NotNode not ) - return new ProjNode((MultiNode)new IfNode(iff.ctrl(),not.in(1)).peephole(),1-_idx,_idx==0 ? "False" : "True"); - } - return null; - } - - @Override - boolean eq( Node n ) { return _idx == ((ProjNode)n)._idx; } - - @Override - int hash() { return _idx; } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/RegionNode.java deleted file mode 100644 index 8b52494a..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/RegionNode.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.IterPeeps; -import com.seaofnodes.simple.Utils; -import com.seaofnodes.simple.type.Type; - -import java.util.ArrayList; -import java.util.Arrays; - -public class RegionNode extends Node { - - public RegionNode(Node... nodes) { super(nodes); } - - @Override - public String label() { return "Region"; } - - @Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - return p.p(label()).p(_nid); - } - - @Override public boolean isCFG() { return true; } - @Override public boolean isMultiHead() { return true; } - - @Override - public Type compute() { - if( inProgress() ) return Type.CONTROL; - Type t = Type.XCONTROL; - for (int i = 1; i < nIns(); i++) - t = t.meet(in(i)._type); - return t; - } - - @Override - public Node idealize() { - if( inProgress() ) return null; - // Delete dead paths into a Region - int path = findDeadInput(); - if( path != 0 && - // Do not delete the entry path of a loop (ok to remove the back - // edge and make the loop a single-entry Region which folds away - // the Loop). Folding the entry path confused the loop structure, - // moving the backedge to the entry point. - !(this instanceof LoopNode loop && loop.entry()==in(path)) ) { - // Cannot use the obvious output iterator here, because a Phi - // deleting an input might recursively delete *itself*. This - // shuffles the output array, and we might miss iterating an - // unrelated Phi. So on rare occasions we repeat the loop to get - // all the Phis. - int nouts = 0; - while( nouts != nOuts() ) { - nouts = nOuts(); - for( int i=0; i<nOuts(); i++ ) - if( out(i) instanceof PhiNode phi && phi.nIns()==nIns() ) { - phi.delDef(path); - IterPeeps.addAll(phi._outputs); - } - } - return isDead() ? new ConstantNode(Type.XCONTROL) : delDef(path); - } - // If down to a single input, become that input - if( nIns()==2 && !hasPhi() ) - return in(1); // Collapse if no Phis; 1-input Phis will collapse on their own - - // If a CFG diamond with no merging, delete: "if( pred ) {} else {};" - if( !hasPhi() && // No Phi users, just a control user - in(1) instanceof ProjNode p1 && - in(2) instanceof ProjNode p2 && - p1.addDepForwards(this).in(0)==p2.addDepForwards(this).in(0) && - p1.in(0) instanceof IfNode iff ) - return iff.ctrl(); - - return null; - } - - private int findDeadInput() { - for( int i=1; i<nIns(); i++ ) - if( in(i)._type==Type.XCONTROL ) - return i; - return 0; // All inputs alive - } - - private boolean hasPhi() { - for( Node phi : _outputs ) - if( phi instanceof PhiNode ) - return true; - return false; - } - - // Immediate dominator of Region is a little more complicated. - @Override int idepth() { - if( _idepth!=0 ) return _idepth; - int depth=0; - for( Node n : _inputs ) - if( n!=null ) - depth = Math.max(depth,n.idepth()+1); - return cacheIDepth(depth); - } - - @Override Node idom() { - Node lca = null; - // Recompute from predecessors: CFG edits can change the dominator. - for( int i=1; i<nIns(); i++ ) - lca = in(i).domLCA(lca); - return lca; - } - - // True if last input is null - public final boolean inProgress() { - return nIns()>1 && in(nIns()-1) == null; - } - - // Never equal if inProgress - @Override boolean eq( Node n ) { - return !inProgress(); - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/ReturnNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/ReturnNode.java deleted file mode 100644 index ef4ddb3a..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/ReturnNode.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.type.*; - - -/** Keeps all preceding memory effects and the return value alive: {ctrl, $mem, value}. */ -public class ReturnNode extends Node { - - public ReturnNode(Node ctrl, Node data, ScopeNode scope) { - super(ctrl, scope.lookup("$mem"), data); - } - - public Node ctrl() { return in(0); } - public Node mem () { return in(1); } - public Node expr() { return in(2); } - - @Override - public String label() { return "Return"; } - - @Override - protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - p.p("return "); - p.n(expr()); - return p.p(";"); - } - - @Override public boolean isCFG() { return true; } - - @Override - public Type compute() { - // Return exposes the complete memory state. - return TypeTuple.make(ctrl()._type,TypeMem.BOT,expr()._type); - } - - @Override - public Node idealize() { - if( ctrl()._type==Type.XCONTROL ) - return ctrl(); - return null; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/ScopeNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/ScopeNode.java deleted file mode 100644 index b408eb2f..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/ScopeNode.java +++ /dev/null @@ -1,305 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.IterPeeps; -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.Utils; -import com.seaofnodes.simple.type.TypeMemPtr; - -import java.util.*; - -/** - * The Scope node is purely a parser helper - it tracks names to nodes with a - * stack of scopes. - */ -public class ScopeNode extends Node { - - /** - * The control is a name that binds to the currently active control - * node in the graph - */ - public static final String CTRL = "$ctrl"; - public static final String ARG0 = "arg"; - - /** - * Names for every input edge - */ - public final Stack<HashMap<String, Integer>> _scopes; - - /** - * Tracks declared types for every name - */ - public Stack<HashMap<String, Type>> _types; - - - // A new ScopeNode - public ScopeNode() { - _scopes = new Stack<>(); - _types = new Stack<>(); - _type = Type.BOTTOM; - } - - - @Override public String label() { return "Scope"; } - - @Override - protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - p.p("Scope[ "); - String[] names = reverseNames(); - for( int j=0; j<nIns(); j++ ) { - p.p(names[j]).p(":"); - Node n = in(j); - while( n instanceof ScopeNode loop ) { - p.p("Lazy_"); - n = loop.in(j); - } - p.n(n).p(" "); - } - return p.unchar(' ').p("]"); - } - - /** - * Recover the names for all variable bindings. - * The result is an array of names that is aligned with the - * inputs to the Node. - * - * This is an expensive operation. - */ - public String[] reverseNames() { - String[] names = new String[nIns()]; - for( HashMap<String,Integer> syms : _scopes ) - for( String name : syms.keySet() ) - names[syms.get(name)] = name; - return names; - } - - @Override public Type compute() { return Type.BOTTOM; } - - @Override public Node idealize() { return null; } - - public void push() { _scopes.push(new HashMap<>()); _types.push(new HashMap<>()); } - public void pop() { popN(_scopes.pop().size()); _types.pop(); } - - /** - * Create a new name in the current scope - */ - public Node define( String name, Type declaredType, Node n ) { - HashMap<String,Integer> syms = _scopes.lastElement(); - _types.lastElement().put(name,declaredType); - if( syms.put(name,nIns()) != null ) - return null; // Double define - return addDef(n); - } - /** - * Lookup a name in all scopes starting from most deeply nested. - * - * @param name Name to be looked up - * @see #update(String, Node, int) - */ - public Node lookup( String name ) { return update(name,null,_scopes.size()-1); } - /** - * If the name is present in any scope, then redefine else null - * - * @param name Name being redefined - * @param n The node to bind to the name - */ - public Node update( String name, Node n ) { return update(name,n,_scopes.size()-1); } - /** - * Both recursive lookup and update. - * <p> - * A shared implementation allows us to create lazy phis both during - * lookups and updates; the lazy phi creation is part of chapter 8. - * - * @param name Name whose binding is being updated or looked up - * @param n If null, do a lookup, else update binding - * @param nestingLevel The starting nesting level - * @return node being looked up, or the one that was updated - */ - private Node update( String name, Node n, int nestingLevel ) { - if( nestingLevel<0 ) return null; // Missed in all scopes, not found - var syms = _scopes.get(nestingLevel); // Get the symbol table for nesting level - var idx = syms.get(name); - if( idx == null ) return update(name,n,nestingLevel-1); // Not found in this scope, recursively look in parent scope - Node old = in(idx); - if( old instanceof ScopeNode loop ) { - // Lazy Phi! - old = loop.in(idx) instanceof PhiNode phi && loop.ctrl()==phi.region() - // Loop already has a real Phi, use it - ? loop.in(idx) - // Set real Phi in the loop head - // The phi takes its one input (no backedge yet) from a recursive - // lookup, which might have insert a Phi in every loop nest. - : loop.setDef(idx,PhiNode.make(name, lookupDeclaredType(name),loop.ctrl(),loop.update(name,null,nestingLevel),null).peephole()); - setDef(idx,old); - } - return n==null ? old : setDef(idx,n); // Not lazy, so this is the answer - } - - // Return declared type - public Type lookupDeclaredType( String name ) { - for( int i=_types.size(); i>0; i-- ) { - Type t = _types.get(i-1).get(name); - if( t != null ) return t; - } - return null; - } - - public Node ctrl() { return in(0); } - - /** - * The ctrl of a ScopeNode is always bound to the currently active - * control node in the graph, via a special name '$ctrl' that is not - * a valid identifier in the language grammar and hence cannot be - * referenced in Simple code. - * - * @param n The node to be bound to '$ctrl' - * - * @return Node that was bound - */ - public Node ctrl(Node n) { return setDef(0,n); } - - /** - * Duplicate a ScopeNode; including all levels, up to Nodes. So this is - * neither shallow (would dup the Scope but not the internal HashMap - * tables), nor deep (would dup the Scope, the HashMap tables, but then - * also the program Nodes). - * <p> - * If the {@code loop} flag is set, the edges are filled in as the original - * Scope, as a indication of Lazy Phis at loop heads. The goal here is to - * not make Phis at loop heads for variables which are never touched in the - * loop body. - * <p> - * The new Scope is a full-fledged Node with proper use<->def edges. - */ - public ScopeNode dup() { return dup(false); } - public ScopeNode dup(boolean loop) { - 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<String,Integer> syms : _scopes ) - dup._scopes.push(new HashMap<>(syms)); - for( HashMap<String,Type> ts : _types ) - dup._types.push(ts); // Types don't change, just keep stacks aligned - - dup.addDef(ctrl()); // Control input is just copied - for( int i=1; i<nIns(); i++ ) - // For lazy phis on loops we use a sentinel - // that will trigger phi creation on update - dup.addDef(loop ? this : in(i)); - return dup; - } - - /** - * Merges the names whose node bindings differ, by creating Phi node for such names - * The names could occur at all stack levels, but a given name can only differ in the - * innermost stack level where the name is bound. - * - * @param that The ScopeNode to be merged into this - * @return A new node representing the merge point - */ - public Node mergeScopes(ScopeNode that) { - RegionNode r = (RegionNode) ctrl(new RegionNode(null,ctrl(), that.ctrl()).keep()); - String[] ns = reverseNames(); - // Note that we skip i==0, which is bound to '$ctrl' - for (int i = 1; i < nIns(); i++) - if( in(i) != that.in(i) ) // No need for redundant Phis - // If we are in lazy phi mode we need to a lookup - // by name as it will trigger a phi creation - setDef(i, PhiNode.make(ns[i], this.lookupDeclaredType(ns[i]), r, this.lookup(ns[i]), that.lookup(ns[i])).peephole()); - that.kill(); // Kill merged scope - IterPeeps.add(r); - return r.unkeep().peephole(); - } - - // Merge the backedge scope into this loop head scope - // We set the second input to the phi from the back edge (i.e. loop body) - public void endLoop(ScopeNode back, ScopeNode exit ) { - Node ctrl = ctrl(); - assert ctrl instanceof LoopNode loop && loop.inProgress(); - ctrl.setDef(2,back.ctrl()); - for( int i=1; i<nIns(); i++ ) { - if( back.in(i) != this ) { - PhiNode phi = (PhiNode)in(i); - assert phi.region()==ctrl && phi.in(2)==null; - phi.setDef(2,back.in(i)); - } - if( exit.in(i) == this ) // Replace a lazy-phi on the exit path also - exit.setDef(i,in(i)); - } - back.kill(); // Loop backedge is dead - // Now one-time do a useless-phi removal - for( int i=1; i<nIns(); i++ ) { - if( in(i) instanceof PhiNode phi ) { - // Do an eager useless-phi removal - Node in = phi.peephole(); - IterPeeps.addAll(phi._outputs); - phi.moveDepsToWorklist(); - if( in != phi ) { - if( !phi.iskeep() ) // Keeping phi around for parser elsewhere - phi.subsume(in); - setDef(i,in); // Set the update back into Scope - } - } - } - - } - - - // Up-casting: using the results of an If to improve a value. - // E.g. "if( ptr ) ptr.field;" is legal because ptr is known not-null. - - // This Scope looks for direct variable uses, or certain simple - // combinations, and replaces the variable with the upcast variant. - public Node upcast( Node ctrl, Node pred, boolean invert ) { - if( ctrl._type==Type.XCONTROL ) return null; - // A single negation is handled below. For !!p (including p != null), - // also refine the underlying p without changing the Boolean result. - if( pred instanceof NotNode not && not.in(1) instanceof NotNode ) { - pred.keep(); // Recursive peepholes may rediscover this Not. - upcast(ctrl,not.in(1),!invert); - pred.unkeep(); - } - // Invert the If conditional - if( invert ) - pred = pred instanceof NotNode not ? not.in(1) : IterPeeps.add(new NotNode(pred).peephole()); - - // Direct use of a value as predicate. This is a zero/null test. - if( Utils.find(_inputs, pred) != -1 ) { - if( !(pred._type instanceof TypeMemPtr tmp) ) - // Must be an `int`, since int and ptr are the only two value types - // being tested. No representation for a generic not-null int, so no upcast. - return null; - if( tmp.isa(TypeMemPtr.VOIDPTR) ) - return null; // Already not-null, no reason to upcast - // Upcast the ptr to not-null ptr, and replace in scope - return replace(pred,new CastNode(TypeMemPtr.VOIDPTR,ctrl,pred).peephole()); - } - - if( pred instanceof NotNode not ) { - // Direct use of a !value as predicate. This is a zero/null test. - if( Utils.find(_inputs, not.in(1)) != -1 ) { - Type tinit = not.in(1)._type.makeInit(); - if( not.in(1)._type.isa(tinit) ) return null; // Already zero/null, no reason to upcast - return replace(not.in(1), new ConstantNode(tinit).peephole()); - } - } - // Apr/9/2024: Attempted to replace X with Y if guarded by a test of - // X==Y. This didn't seem to help very much, or at least in the test - // cases seen so far was a very minor help. - - // No upcast - return null; - } - - private Node replace( Node old, Node cast ) { - assert old!=null && old!=cast; - for( int i=0; i<nIns(); i++ ) - if( in(i)==old ) - setDef(i,cast); - return cast; - } - -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/StartNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/StartNode.java deleted file mode 100644 index 3404f111..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/StartNode.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.type.*; - -/** The entry tuple: control, initial whole-memory state, and argument. */ -public class StartNode extends MultiNode { - final TypeTuple _args; - - public StartNode(Type[] args) { - super(); - _type = _args = TypeTuple.make(args); - } - - @Override - public String label() { return "Start"; } - - @Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - return p.p(label()); - } - - @Override public boolean isCFG() { return true; } - @Override public boolean isMultiHead() { return true; } - - @Override - public TypeTuple compute() { return _args; } - - @Override - public Node idealize() { return null; } - - // No immediate dominator, and idepth==0 - @Override int idepth() { return 0; } - @Override Node idom() { return null; } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/StopNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/StopNode.java deleted file mode 100644 index 4b4e9615..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/StopNode.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.Parser; - -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.IterPeeps; - - -public class StopNode extends Node { - - public final String _src; - - public StopNode(String src) { - super(); - _src = src; - } - - @Override - public String label() { - return "Stop"; - } - - @Override - protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - if( ret()!=null ) return p.n(ret()); - p.p("Stop[ "); - for( Node ret : _inputs ) - p.n(ret).p(" "); - return p.p("]"); - } - - @Override public boolean isCFG() { return true; } - - // If a single Return, return it. - // Otherwise, null because ambiguous. - public ReturnNode ret() { - return nIns()==1 ? (ReturnNode)in(0) : null; - } - - @Override - public Type compute() { - return Type.BOTTOM; - } - - @Override - public Node idealize() { - int len = nIns(); - for( int i=0; i<nIns(); i++ ) - if( in(i)._type==Type.XCONTROL ) - delDef(i--); - if( len != nIns() ) return this; - return null; - } - - @Override public Node idom() { return null; } - - public Node addReturn(Node node) { - return addDef(node); - } - - public StopNode iterate() { return IterPeeps.iterate(this).typeCheck(); } - public StopNode typeCheck() { - var obs = Parser.PARSER == null ? null : Parser.PARSER._obs; - String err = walk(n -> { - String msg = n.err(); - if( msg != null && obs != null ) obs.error(n, msg); - return msg; - }); - if( err != null ) throw new RuntimeException(err); - if( obs != null ) obs.phase("TypeCheck"); - return this; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/StoreNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/StoreNode.java deleted file mode 100644 index 026d5c50..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/StoreNode.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.seaofnodes.simple.node; - -import com.seaofnodes.print.ExprPrinter; - -import com.seaofnodes.simple.Utils; -import com.seaofnodes.simple.IterPeeps; -import com.seaofnodes.simple.type.*; - - -/** - * Store represents setting a value to a memory based object, in chapter 10 - * this means a field inside a struct. - */ -public class StoreNode extends MemOpNode { - - /** - * @param name The struct field we are assigning to - * @param memSlice The memory alias node - this is updated after a Store - * @param memPtr The ptr to the struct where we will store a value - * @param value Value to be stored - */ - public StoreNode(String name, int alias, Node memSlice, Node memPtr, Node value) { - super(name, alias, memSlice, memPtr, value); - } - - @Override - public String label() { return "Store"; } - @Override - public boolean isMem() { return true; } - public Node val() { return in(3); } - - @Override - protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { - return p.p(".").p(_name).p("=").p( val()).p(";"); - } - - @Override - public Type compute() { return TypeMem.make(_alias); } - - @Override - public Node idealize() { - if( mem() instanceof MemMergeNode merge ) { - setDef(1,IterPeeps.add(merge.alias(_alias))); - return this; - } - - - // Simple store-after-store on same address. Should pick up the - // required init-store being stomped by a first user store. - if( mem() instanceof StoreNode st && - ptr()==st.ptr() && _alias==st._alias && // Must check same object - ptr()._type instanceof TypeMemPtr && // No bother if weird dead pointers - // Must have exactly one use of "this" or you get weird - // non-serializable memory effects in the worse case. - st.checkNoUseBeyond(this) ) { - assert Utils.eq(_name,st._name); // Equiv class aliasing is perfect - setDef(1,st.mem()); - return this; - } - - return null; - } - - // Check that `this` has no uses beyond `that` - private boolean checkNoUseBeyond(Node that) { - if( nOuts()==1 ) return true; - // Add deps on the other uses (can be e.g. ScopeNode mid-parse) so that - // when the other uses go away we can retry. - for( Node use : _outputs ) - if( use != that ) - use.addDep(that); - return false; - } - -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/node/SubNode.java b/chapter10b/src/main/java/com/seaofnodes/simple/node/SubNode.java deleted file mode 100644 index 6fa87a07..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/node/SubNode.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.seaofnodes.simple.node; - - -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeInteger; - - -public class SubNode extends Node { - public SubNode(Node lhs, Node rhs) { super(null, lhs, rhs); } - - @Override public String label() { return "Sub"; } - - @Override protected String format() { return "(%1-%2)"; } - - @Override - public Type compute() { - Type t1 = in(1)._type, t2 = in(2)._type; - if( t1==Type.TOP || t1==TypeInteger.TOP || - t2==Type.TOP || t2==TypeInteger.TOP ) - return TypeInteger.TOP; - // Sub of same is 0 - if( in(1)==in(2) ) - return TypeInteger.ZERO; - - if (t1 instanceof TypeInteger i0 && - t2 instanceof TypeInteger i1) { - if (i0.isConstant() && i1.isConstant()) - return TypeInteger.constant(i0.value()-i1.value()); - } - return TypeInteger.BOT; - } - - @Override - public Node idealize() { - Node lhs = in(1); - Node rhs = in(2); - Type t1 = lhs._type; - Type t2 = rhs._type; - - // Keep invalid operands for type checking. - if( t1 instanceof TypeInteger x && t2 instanceof TypeInteger y ) { - if( y.isConstant() && y.value()==0 ) return lhs; - if( x.isConstant() && x.value()==0 ) return new MinusNode(rhs); - } - - // x - (-y) is x+y - if( rhs instanceof MinusNode minus ) - return new AddNode(lhs,minus.in(1)); - - // (-x) - y is -(x+y) - if( lhs instanceof MinusNode minus ) - return new MinusNode(new AddNode(minus.in(1),rhs).peephole()); - - return null; - } - - @Override Node copy(Node lhs, Node rhs) { return new SubNode(lhs,rhs); } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/print/SimpleGraphAdapter.java b/chapter10b/src/main/java/com/seaofnodes/simple/print/SimpleGraphAdapter.java deleted file mode 100644 index 92d970d8..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/print/SimpleGraphAdapter.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.seaofnodes.simple.print; - -import com.seaofnodes.graph.GraphAdapter; -import com.seaofnodes.graph.GraphSnapshot.*; -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.node.Node; -import com.seaofnodes.simple.type.TypeMem; - -/** Chapter 10's view of the IR; browser, transport and layout are shared. */ -public class SimpleGraphAdapter extends GraphAdapter<Node> { - - @Override protected String[] edgeNames(Node n) { - return n instanceof ScopeNode scope && n.nIns()!=0 ? scope.reverseNames() : null; - } - @Override protected int projectionIndex(Node n) { return n instanceof ProjNode p ? p._idx : -1; } - - @Override protected 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 LoopNode ) return Kind.LOOP; - if( n instanceof RegionNode ) return Kind.REGION; - if( n instanceof PhiNode ) return Kind.PHI; - return n.isCFG() ? Kind.CTRL : isMem(n) ? Kind.MEM : Kind.DATA; - } - - @Override protected 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 : isMem(n) ? Role.MEM : Role.DATA; - if( n instanceof ProjNode ) return n.isCFG() ? Role.CTRL : isMem(n) ? Role.MEM : Role.DATA; - if( n instanceof RegionNode && i == 0 ) return Role.ASSOC; - if( i == 0 || n instanceof RegionNode || n instanceof StopNode ) return Role.CTRL; - if( i == 1 && (n instanceof MemOpNode || n instanceof ReturnNode) ) return Role.MEM; - Node def = n.in(i); - if( def != null && isMem(def) ) return Role.MEM; - return Role.DATA; - } - - private boolean isMem(Node n) { return n.isMem() || n._type instanceof TypeMem; } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/print/SimpleGraphObserver.java b/chapter10b/src/main/java/com/seaofnodes/simple/print/SimpleGraphObserver.java deleted file mode 100644 index 1980659e..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/print/SimpleGraphObserver.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.seaofnodes.simple.print; - -import com.seaofnodes.graph.GraphCapture; -import com.seaofnodes.graph.GraphViewer; -import com.seaofnodes.simple.Parser; -import com.seaofnodes.simple.node.Node; -import java.util.ArrayList; -import java.io.IOException; - -/** Chapter 10's compilation context; capture and event bookkeeping are shared. */ -public class SimpleGraphObserver extends GraphCapture<Node> { - 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()); - } - @Override protected void compile(String src) { - _parser = new Parser(src); - _parser._obs = this; - _phase = "Parse"; - _ret = _parser.parse(); - phase(_phase); - _phase = "Iter"; - com.seaofnodes.simple.IterPeeps.iterate(_parser.STOP); - phase(_phase); - _phase = "TypeCheck"; - _parser.STOP.typeCheck(); - } - @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; - _ret = null; - } - @Override protected Node scope() { return _parser._scope; } - @Override protected void roots(ArrayList<Node> roots) { - roots.add(Parser.START); - roots.add(_parser.STOP); - roots.addAll(_parser._xScopes); - roots.add(_ret); - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/type/Field.java b/chapter10b/src/main/java/com/seaofnodes/simple/type/Field.java deleted file mode 100644 index cdc58215..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/type/Field.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.seaofnodes.simple.type; - -import com.seaofnodes.simple.Utils; -import java.util.ArrayList; - -/** - * Represents a field in a struct. This is not a Type in the type system. - */ -public class Field extends Type { - - // The pair {fieldName,type} uniquely identifies a field. - - // Field name - public final String _fname; - // Type of the field - public final Type _type; - - private Field(String fname, Type type ) { - super(TFLD); - _fname = fname; - _type = type; - } - public static Field make( String fname, Type type ) { - return new Field(fname,type).intern(); - } - - public static final Field TEST = make("test",TypeInteger.ZERO); - public static void gather(ArrayList<Type> ts) { ts.add(TEST); } - - @Override Field xmeet( Type that ) { - Field fld = (Field)that; // Invariant - assert _fname.equals(fld._fname); - return make(_fname,_type.meet(fld._type)); - } - - @Override - public Field dual() { return make(_fname,_type.dual()); } - - @Override - public Field glb() { - return make(_fname,_type.glb()); - } - - // Override in subclasses - int hash() { return _fname.hashCode() ^ _type.hashCode(); } - - boolean eq(Type t) { - Field f = (Field)t; - return Utils.eq(_fname,f._fname) && _type==f._type; - } - - - @Override - public StringBuilder print( StringBuilder sb ) { - return _type.print(sb.append(_fname).append(":")); - } - - @Override public String str() { return _fname; } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/type/Type.java b/chapter10b/src/main/java/com/seaofnodes/simple/type/Type.java deleted file mode 100644 index 93e27c76..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/type/Type.java +++ /dev/null @@ -1,187 +0,0 @@ -package com.seaofnodes.simple.type; - -import com.seaofnodes.simple.Utils; - -import java.util.ArrayList; -import java.util.HashMap; - -/** - * These types are part of a Monotone Analysis Framework, - * @see <a href="https://www.cse.psu.edu/~gxt29/teaching/cse597s21/slides/08monotoneFramework.pdf">see for example this set of slides</a>. - * <p> - * The types form a lattice; @see <a href="https://en.wikipedia.org/wiki/Lattice_(order)">a symmetric complete bounded (ranked) lattice.</a> - * <p> - * This wild lattice theory will be needed later to allow us to easily beef up - * the analysis and optimization of the Simple compiler... but we don't need it - * now, just know that it is coming along in a later Chapter. - * <p>g - * One of the fun things here is that while the theory is deep and subtle, the - * actual implementation is darn near trivial and is generally really obvious - * what we're doing with it. Right now, it's just simple integer math to do - * simple constant folding e.g. 1+2 == 3 stuff. - */ - -public class Type { - static final HashMap<Type,Type> INTERN = new HashMap<>(); - - // ---------------------------------------------------------- - // Simple types are implemented fully here. "Simple" means: the code and - // type hierarchy are simple, not that the Type is conceptually simple. - static final byte TBOT = 0; // Bottom (ALL) - static final byte TTOP = 1; // Top (ANY) - static final byte TCTRL = 2; // Ctrl flow bottom - static final byte TXCTRL = 3; // Ctrl flow top (mini-lattice: any-xctrl-ctrl-all) - static final byte TSIMPLE = 4; // End of the Simple Types - static final byte TINT = 5; // All Integers; see TypeInteger - static final byte TTUPLE = 6; // Tuples; finite collections of unrelated Types, kept in parallel - static final byte TMEM = 7; // All memory (alias 0) or A slice of memory - with specific alias - static final byte TMEMPTR = 8; // Memory pointer type - static final byte TSTRUCT = 9; // Structs; tuples with named fields - static final byte TFLD =10; // Fields into struct - - public final byte _type; - - public boolean is_simple() { return _type < TSIMPLE; } - private static final String[] STRS = new String[]{"Bot","Top","Ctrl","~Ctrl"}; - protected Type(byte type) { _type = type; } - - public static final Type BOTTOM = new Type( TBOT ).intern(); // ALL - public static final Type TOP = new Type( TTOP ).intern(); // ANY - public static final Type CONTROL = new Type( TCTRL ).intern(); // Ctrl - public static final Type XCONTROL = new Type( TXCTRL ).intern(); // ~Ctrl - public static Type[] gather() { - ArrayList<Type> ts = new ArrayList<>(); - ts.add(BOTTOM); - ts.add(CONTROL); - Field.gather(ts); - TypeInteger.gather(ts); - TypeMem.gather(ts); - TypeMemPtr.gather(ts); - TypeStruct.gather(ts); - TypeTuple.gather(ts); - int sz = ts.size(); - for( int i = 0; i < sz; i++ ) - ts.add(ts.get(i).dual()); - return ts.toArray(new Type[ts.size()]); - } - - // Is high or on the lattice centerline. - public boolean isHighOrConst() { return _type==TTOP || _type==TXCTRL; } - - // Strict constant values, things on the lattice centerline. - // Excludes both high and low values - public boolean isConstant() { return false; } - - /** - * Display Type name in a format that's good for IR printer - */ - public StringBuilder typeName( StringBuilder sb) { return print(sb); } - - public Type makeInit() { return null; } - - // ---------------------------------------------------------- - - // Notes on Type interning. - // At the moment it is not easy to reset the interned types - // because we hold static references to several types and these are scattered - // around. This means the INTERN cache will retain all types from - // every run of the Parser. For this to work correctly types must be - // rigorous about defining when they are the same. Also types need to be - // immutable once defined. - // The rationale for interning is performance. - - // Factory method which interns "this" - public <T extends Type> T intern() { - T nnn = (T)INTERN.get(this); - if( nnn==null ) - INTERN.put(nnn=(T)this,this); - return nnn; - } - - private int _hash; // Hash cache; not-zero when set. - @Override - public final int hashCode() { - if( _hash!=0 ) return _hash; - _hash = hash(); - if( _hash==0 ) _hash = 0xDEADBEEF; // Bad hash from subclass; use some junk thing - return _hash; - } - // Override in subclasses - int hash() { return _type; } - - @Override - public final boolean equals( Object o ) { - if( o==this ) return true; - if( !(o instanceof Type t)) return false; - if( _type != t._type ) return false; - return eq(t); - } - // Overridden in subclasses; subclass can assume "this!=t" and java classes are same - boolean eq(Type t) { return true; } - - - // ---------------------------------------------------------- - public final Type meet(Type t) { - // Shortcut for the self case - if( t == this ) return this; - // Same-type is always safe in the subclasses - if( _type==t._type ) return xmeet(t); - // Reverse; xmeet 2nd arg is never "is_simple" and never equal to "this". - if( is_simple() ) return this.xmeet(t ); - if( t.is_simple() ) return t .xmeet(this); - return Type.BOTTOM; // Mixing 2 unrelated types - } - - // Compute meet right now. Overridden in subclasses. - // Handle cases where 'this.is_simple()' and unequal to 't'. - // Subclassed xmeet calls can assert that '!t.is_simple()'. - Type xmeet(Type t) { - assert is_simple(); // Should be overridden in subclass - // ANY meet anything is thing; thing meet ALL is ALL - if( _type==TBOT || t._type==TTOP ) return this; - if( _type==TTOP || t._type==TBOT ) return t; - // 'this' is {TCTRL,TXCTRL} - if( !t.is_simple() ) return BOTTOM; - // 't' is {TCTRL,TXCTRL} - return _type==TCTRL || t._type==TCTRL ? CONTROL : XCONTROL; - } - - public Type dual() { - return switch( _type ) { - case TBOT -> TOP; - case TTOP -> BOTTOM; - case TCTRL -> XCONTROL; - case TXCTRL -> CONTROL; - default -> throw Utils.TODO(); // Should not reach here - }; - } - - // ---------------------------------------------------------- - // Our lattice is defined with a MEET and a DUAL. - // JOIN is dual of meet of both duals. - public final Type join(Type t) { - if( this==t ) return this; - return dual().meet(t.dual()).dual(); - } - - // True if this "isa" t; e.g. 17 isa TypeInteger.BOT - public boolean isa( Type t ) { return meet(t)==t; } - - /** - * Compute greatest lower bound in the lattice - */ - public Type glb() { return _type==TCTRL ? XCONTROL : BOTTOM; } - - // ---------------------------------------------------------- - // Useful in the debugger, which calls toString everywhere. - // This is a more verbose dev-friendly print. - @Override - public final String toString() { - return print(new StringBuilder()).toString(); - } - - public StringBuilder print(StringBuilder sb) { return is_simple() ? sb.append(STRS[_type]) : sb;} - - // This is used by error messages, and is a shorted print. - public String str() { return STRS[_type]; } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeInteger.java b/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeInteger.java deleted file mode 100644 index 8c77672b..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeInteger.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.seaofnodes.simple.type; - -import java.util.ArrayList; - -/** - * Integer Type - */ -public class TypeInteger extends Type { - - public final static TypeInteger TOP = make(false, 0); - public final static TypeInteger BOT = make(false, 1); - public final static TypeInteger ZERO= make(true , 0); - - public final boolean _is_con; - - /** - * The constant value or - * if not constant then 1=bottom, 0=top. - */ - public final long _con; - - private TypeInteger(boolean is_con, long con) { - super(TINT); - _is_con = is_con; - _con = con; - } - public static TypeInteger make(boolean is_con, long con) { - return new TypeInteger(is_con,con).intern(); - } - - public static TypeInteger constant(long con) { return make(true, con); } - - public static void gather(ArrayList<Type> ts) { ts.add(ZERO); ts.add(BOT); } - - // FIXME this display format is problematic - // In visualizer '#' gets prepended if its a constant - @Override - public StringBuilder print(StringBuilder sb) { - if( this==TOP ) return sb.append("IntTop"); - if( this==BOT ) return sb.append("IntBot"); - return sb.append(_con); - } - - @Override public String str() { - if( this==TOP ) return "~int"; - if( this==BOT ) return "int"; - return ""+_con; - } - - /** - * Display Type name in a format that's good for IR printer - */ - @Override - public StringBuilder typeName(StringBuilder sb) { - if( this==TOP ) return sb.append("IntTop"); - if( this==BOT ) return sb.append("IntBot"); - return sb.append("Int"); - } - - @Override - public boolean isHighOrConst() { return _is_con || _con==0; } - - @Override - public boolean isConstant() { return _is_con; } - - public long value() { return _con; } - - @Override - public Type xmeet(Type other) { - // Invariant from caller: 'this' != 'other' and same class (TypeInteger) - TypeInteger i = (TypeInteger)other; // Contract - // BOT wins - if ( this==BOT ) return this; - if ( i ==BOT ) return i ; - // TOP loses - if ( i ==TOP ) return this; - if ( this==TOP ) return i ; - // Since both are constants, and are never equals (contract) unequals - // constants fall to bottom - return BOT; - } - - @Override - public Type dual() { - if( isConstant() ) return this; // Constants are a self-dual - return _con==0 ? BOT : TOP; - } - - @Override - public Type glb() { return BOT; } - - @Override public TypeInteger makeInit() { return ZERO; } - - @Override - int hash() { return (int)(_con ^ (_is_con ? 0 : 0x4000)); } - @Override - public boolean eq( Type t ) { - TypeInteger i = (TypeInteger)t; // Contract - return _con==i._con && _is_con==i._is_con; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeMem.java b/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeMem.java deleted file mode 100644 index b6fc8824..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeMem.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.seaofnodes.simple.type; - -import com.seaofnodes.simple.Utils; -import java.lang.Long; -import java.util.BitSet; -import java.util.ArrayList; - - -/** - * Represents a slice of memory corresponding to a set of aliases - */ -public class TypeMem extends Type { - - // Which slice of memory? - // 0 means TOP, no slice. - // -1 means BOT, all memory. - // N means slice#N. - private final int _alias; - - private TypeMem(int alias) { super(TMEM); _alias = alias; } - - public static TypeMem make(int alias) { return new TypeMem(alias).intern(); } - public static final TypeMem TOP = make( 0); - public static final TypeMem BOT = make(-1); - - - public static void gather(ArrayList<Type> ts) { ts.add(make(1)); ts.add(BOT); } - - @Override - TypeMem xmeet(Type t) { - TypeMem that = (TypeMem) t; // Invariant: TypeMem and unequal - return _alias==0 ? that : (that._alias==0 ? this : BOT); - } - - @Override - public Type dual() { - if( _alias== 0 ) return BOT; - if( _alias==-1 ) return TOP; - return this; - } - - @Override - public Type glb() { return TypeMem.BOT; } - - @Override - int hash() { return 9876543 + _alias; } - - @Override - boolean eq(Type t) { - TypeMem that = (TypeMem) t; // Invariant - return _alias == that._alias; - } - - @Override - public StringBuilder print(StringBuilder sb) { - if( this==BOT ) return sb.append("MemBot"); - if( this==TOP ) return sb.append("MemTop"); - return sb.append("MEM#").append( switch(_alias) { - case 0 -> "TOP"; - case -1 -> "BOT"; - default -> ""+_alias; - }); - } - - @Override public String str() { return print(new StringBuilder()).toString(); } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java b/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java deleted file mode 100644 index 6c874a93..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.seaofnodes.simple.type; - -import java.util.ArrayList; - -/** - * Represents a Pointer to memory. - * - * Null is generic pointer to non-existent memory. - * *void is a non-Null pointer to all possible structs. - * Pointers can be to specific struct types, or a union with Null. - * The distinguished *$BOT ptr represents union of *void and Null. - * The distinguished *$TOP ptr represents the dual of *$BOT. - */ -public class TypeMemPtr extends Type { - // A TypeMemPtr is pair (obj,nil) - // where obj is one of - // (null,TypeStruct). - // where nil is one of - // (true,false) meaning an explicit null is allowed or not - - public final TypeStruct _obj; // null, a TypeStruct, or sentinel TypeStruct.MANY - public final boolean _nil; - - private TypeMemPtr(TypeStruct obj, boolean nil) { - super(TMEMPTR); - _obj = obj; - _nil = nil; - } - public static TypeMemPtr make(TypeStruct obj, boolean nil) { return new TypeMemPtr(obj, nil).intern(); } - public static TypeMemPtr make(TypeStruct obj) { return TypeMemPtr.make(obj, false); } - - public static final TypeMemPtr BOT = make(TypeStruct.BOT,true); - public static final TypeMemPtr TOP = BOT.dual(); - public static final TypeMemPtr NULLPTR = make(TypeStruct.TOP,true); - public static final TypeMemPtr VOIDPTR = NULLPTR.dual(); // A bottom mix of not-null ptrs, like C's void* but not null - public static final TypeMemPtr TEST= make(TypeStruct.TEST,false); - public static void gather(ArrayList<Type> ts) { ts.add(NULLPTR); ts.add(BOT); ts.add(TEST); } - - @Override - Type xmeet(Type t) { - TypeMemPtr that = (TypeMemPtr) t; - return TypeMemPtr.make((TypeStruct)_obj.meet(that._obj), _nil | that._nil); - } - - @Override - public TypeMemPtr dual() { return TypeMemPtr.make(_obj==null ? null : _obj.dual(), !_nil); } - - @Override - public Type glb() { - if( _obj==null ) return BOT; - return make(_obj.glb(),true); - } - @Override public TypeMemPtr makeInit() { return NULLPTR; } - - @Override - int hash() { return (_obj==null ? 0xDEADBEEF : _obj.hashCode()) ^ (_nil ? 1024 : 0); } - - @Override - boolean eq(Type t) { - TypeMemPtr ptr = (TypeMemPtr)t; // Invariant - return _obj == ptr._obj && _nil == ptr._nil; - } - - // [void,name,MANY]*[,?] - @Override - public StringBuilder print(StringBuilder sb) { - if( this==BOT ) return sb.append("PtrBot"); - if( this==TOP ) return sb.append("PtrTop"); - if( this== NULLPTR) return sb.append("null"); - if( this== VOIDPTR) return sb.append("*void"); - return _obj.print(sb.append("*")).append(_nil ? "?" : ""); - } - - @Override public String str() { - if( this==BOT ) return "PtrBot"; - if( this==TOP ) return "PtrTop"; - if( this== NULLPTR) return "null"; - if( this== VOIDPTR) return "*void"; - return "*"+_obj.str()+(_nil ? "?" : ""); - } - -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeStruct.java b/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeStruct.java deleted file mode 100644 index 44741def..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeStruct.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.seaofnodes.simple.type; - -import com.seaofnodes.simple.Utils; -import java.util.ArrayList; - -/** - * Represents a struct type. - */ -public class TypeStruct extends Type { - - // For now in terms of the lattice - // a struct type just stays as is - - public final String _name; - public final Field[] _fields; - - private TypeStruct(String name, Field[] fields) { - super(Type.TSTRUCT); - _name = name; - _fields = fields; - } - - public static TypeStruct make(String name, Field[] fields) { return new TypeStruct(name, fields).intern(); } - public static TypeStruct make(String name, ArrayList<Field> fields) { return make(name,fields.toArray(new Field[fields.size()])); } - - public static final TypeStruct TOP = make("$TOP",new Field [0]); - public static final TypeStruct BOT = make("$BOT",new Field [0]); - public static final TypeStruct TEST = make("test",new Field[]{Field.TEST}); - public static void gather(ArrayList<Type> ts) { ts.add(TEST); ts.add(BOT); } - - public int find(String fname) { - for( int i=0; i<_fields.length; i++ ) - if( _fields[i]._fname.equals(fname) ) - return i; - return -1; - } - - @Override - Type xmeet(Type t) { - TypeStruct that = (TypeStruct) t; - if( this==TOP ) return that; - if( that==TOP ) return this; - if( this==BOT ) return BOT; - if( that==BOT ) return BOT; - - // Within the same compilation unit, struct names are unique. If the - // names differ, its different structs. Across many compilation units, - // structs with the same name but different field layouts can be - // interned... which begs the question: - // "What is the meet of structs from two different compilation units?" - // And the answer is: "don't ask". - if( !_name.equals(that._name) ) - return BOT; // It's a struct; that's about all we know - // Now all fields should be the same, so just do field meets - assert _fields.length == that._fields.length; - Field[] flds = new Field[_fields.length]; - for( int i=0; i<_fields.length; i++ ) - flds[i] = (Field)_fields[i].meet(that._fields[i]); - return make(_name,flds); - } - - @Override - public TypeStruct dual() { - if( this==TOP ) return BOT; - if( this==BOT ) return TOP; - Field[] flds = new Field[_fields.length]; - for( int i=0; i<_fields.length; i++ ) - flds[i] = _fields[i].dual(); - return make(_name,flds); - } - - // Keeps the same struct, but lower-bounds all fields. - @Override - public TypeStruct glb() { - if( _glb() ) return this; - // Need to glb each field - Field[] flds = new Field[_fields.length]; - for( int i=0; i<_fields.length; i++ ) - flds[i] = _fields[i].glb(); - return make(_name,flds); - } - private boolean _glb() { - for( Field f : _fields ) - if( f.glb() != f ) - return false; - return true; - } - - @Override - boolean eq(Type t) { - TypeStruct ts = (TypeStruct)t; // Invariant - if( !_name.equals(ts._name) ) - return false; - if( _fields.length!=ts._fields.length ) - return false; - for( int i = 0; i < _fields.length; i++ ) - if( _fields[i] != ts._fields[i] ) - return false; - return true; - } - - @Override - int hash() { - long hash = _name.hashCode(); - for( Field f : _fields ) hash = Utils.rot(hash,13) ^ f.hashCode(); - return Utils.fold(hash); - } - - @Override - public StringBuilder print(StringBuilder sb) { - if( this==BOT ) return sb.append("StructBot"); - if( this==TOP ) return sb.append("StructTop"); - sb.append(_name).append(" {\n"); - for( Field f : _fields ) { - sb.append(" ").append(f._fname).append(":"); - f._type.print(sb); - sb.append(";\n"); - } - return sb.append("}"); - } - - @Override public String str() { - if( this==BOT ) return "StructBot"; - if( this==TOP ) return "StructTop"; - return _name; - } -} diff --git a/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeTuple.java b/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeTuple.java deleted file mode 100644 index 0aa019a7..00000000 --- a/chapter10b/src/main/java/com/seaofnodes/simple/type/TypeTuple.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.seaofnodes.simple.type; - -import java.util.ArrayList; - -public class TypeTuple extends Type { - - public final Type[] _types; - - private TypeTuple(Type[] types) { super(TTUPLE); _types = types; } - public static TypeTuple make(Type... types) { return new TypeTuple(types).intern(); } - - private static TypeTuple TEST = make(TypeInteger.BOT,TypeMemPtr.TEST); - public static void gather(ArrayList<Type> ts) { ts.add(TEST); } - - @Override - Type xmeet(Type other) { - TypeTuple tt = (TypeTuple)other; // contract from xmeet - assert _types.length == tt._types.length; - Type[] ts = new Type[_types.length]; - for( int i=0; i<_types.length; i++ ) - ts[i] = _types[i].meet(tt._types[i]); - return make(ts); - } - - @Override public Type dual() { - Type[] ts = new Type[_types.length]; - for( int i=0; i<_types.length; i++ ) - ts[i] = _types[i].dual(); - return make(ts); - } - - @Override - public Type glb() { - Type[] ts = new Type[_types.length]; - for( int i=0; i<_types.length; i++ ) - ts[i] = _types[i].glb(); - return make(ts); - } - - @Override - public StringBuilder print(StringBuilder sb) { - sb.append("["); - for( Type t : _types ) - t.print(sb).append(","); - sb.setLength(sb.length()-1); - sb.append("]"); - return sb; - } - - @Override public String str() { return print(new StringBuilder()).toString(); } - - /** - * Display Type name in a format that's good for IR printer - */ - @Override - public StringBuilder typeName(StringBuilder sb) { - sb.append("["); - for( Type t : _types ) - t.typeName(sb).append(","); - sb.setLength(sb.length()-1); - sb.append("]"); - return sb; - } - - public static final TypeTuple IF_BOTH = make(new Type[]{Type. CONTROL,Type. CONTROL}); - public static final TypeTuple IF_NEITHER = make(new Type[]{Type.XCONTROL,Type.XCONTROL}); - public static final TypeTuple IF_TRUE = make(new Type[]{Type. CONTROL,Type.XCONTROL}); - public static final TypeTuple IF_FALSE = make(new Type[]{Type.XCONTROL,Type. CONTROL}); - - @Override - int hash() { - int sum = 0; - for( Type type : _types ) sum ^= type.hashCode(); - return sum; - } - - @Override - boolean eq( Type t ) { - TypeTuple tt = (TypeTuple)t; // Contract - if( _types.length != tt._types.length ) return false; - for( int i=0; i<_types.length; i++ ) - if( _types[i]!=tt._types[i] ) - return false; - return true; - } - - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter01Test.java b/chapter10b/src/test/java/com/seaofnodes/simple/Chapter01Test.java deleted file mode 100644 index 89882b2f..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter01Test.java +++ /dev/null @@ -1,100 +0,0 @@ -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 Chapter01Test { - - @Test - public void testSimpleProgram() { - Parser parser = new Parser("return 1;"); - StopNode stop = parser.parse(); - StartNode start = Parser.START; - ReturnNode ret = (ReturnNode)stop.in(0); - - assertTrue(ret.ctrl() instanceof ProjNode); - Node expr = ret.expr(); - if( expr instanceof ConstantNode con ) { - assertEquals(start,con.in(0)); - assertEquals(TypeInteger.constant(1), con._type); - } else { - fail(); - } - } - - @Test - public void testZero() { - Parser parser = new Parser("return 0;"); - parser.parse(); - StartNode start = Parser.START; - for( Node use : start._outputs ) - if( use instanceof ConstantNode con && con._type instanceof TypeInteger ) - assertEquals(TypeInteger.constant(0),con._type); - } - - @Test - public void testBad1() { - try { - new Parser("ret").parse(); - fail(); - } catch( RuntimeException e ) { - assertEquals("Undefined name 'ret'",e.getMessage()); - } - } - - @Test - public void testBad2() { - try { - new Parser("return 0123;").parse(); - fail(); - } catch( RuntimeException e ) { - assertEquals("Syntax error: integer values cannot start with '0'",e.getMessage()); - } - } - - @Test - public void testNotBad3() { - // this test used to fail in chapter 1 - assertEquals("return 12;", new Parser("return --12;").parse().print()); - } - - @Test - public void testBad4() { - try { - new Parser("return 100").parse(); - fail(); - } catch( RuntimeException e ) { - assertEquals("Syntax error, expected ;: ",e.getMessage()); - } - } - - @Test - public void testNotBad5() { - // this test used to fail in chapter 1 - assertEquals("return -100;", new Parser("return -100;").parse().print()); - } - - @Test - public void testBad6() { - try { - new Parser("return100").parse(); - fail(); - } catch( RuntimeException e ) { - assertEquals("Undefined name 'return100'",e.getMessage()); - } - } - - @Test - public void testBad7() { - try { - new Parser("return 1;}").parse(); - fail(); - } catch( RuntimeException e ) { - assertEquals("Syntax error, unexpected }",e.getMessage()); - } - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter02Test.java b/chapter10b/src/test/java/com/seaofnodes/simple/Chapter02Test.java deleted file mode 100644 index a6075b75..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter02Test.java +++ /dev/null @@ -1,60 +0,0 @@ -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 Chapter02Test { - - @Test - public void testParseGrammar() { - Parser parser = new Parser("return 1+2*3+-5;"); - StopNode ret = parser.parse(); - assertEquals("return 2;", ret.print()); - } - - @Test - public void testAddPeephole() { - Parser parser = new Parser("return 1+2;"); - StopNode ret = parser.parse(); - assertEquals("return 3;", ret.print()); - } - - @Test - public void testSubPeephole() { - Parser parser = new Parser("return 1-2;"); - StopNode ret = parser.parse(); - assertEquals("return -1;", ret.print()); - } - - @Test - public void testMulPeephole() { - Parser parser = new Parser("return 2*3;"); - StopNode ret = parser.parse(); - assertEquals("return 6;", ret.print()); - } - - @Test - public void testDivPeephole() { - Parser parser = new Parser("return 6/3;"); - StopNode ret = parser.parse(); - assertEquals("return 2;", ret.print()); - } - - @Test - public void testMinusPeephole() { - Parser parser = new Parser("return 6/-3;"); - StopNode ret = parser.parse(); - assertEquals("return -2;", ret.print()); - } - - @Test - public void testExample() { - Parser parser = new Parser("return 1+2*3+-5;"); - StopNode ret = parser.parse(); - assertEquals("return 2;", ret.print()); - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter03Test.java b/chapter10b/src/test/java/com/seaofnodes/simple/Chapter03Test.java deleted file mode 100644 index 609dff76..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter03Test.java +++ /dev/null @@ -1,69 +0,0 @@ -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 Chapter03Test { - - @Test - public void testVarDecl() { - Parser parser = new Parser("int a=1; return a;"); - 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;"); - 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;"); - 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); "); - StopNode ret = parser.parse(); - assertEquals("return 8;", ret.print()); - } - - @Test - public void testSelfAssign() { - try { - new Parser("int a=a; return a;").parse(); - fail(); - } catch( RuntimeException e ) { - assertEquals("Undefined name 'a'",e.getMessage()); - } - } - - @Test - public void testRedeclareVar() { - try { - new Parser("int a=1; int b=2; int c=0; int b=3; c=a+b;").parse(); - fail(); - } catch( RuntimeException e ) { - assertEquals("Redefining name 'b'",e.getMessage()); - } - } - - @Test - public void testBad1() { - try { - new Parser("int a=1; int b=2; int c=0; { int b=3; c=a+b;").parse(); - fail(); - } catch( RuntimeException e ) { - assertEquals("Syntax error, expected }: ",e.getMessage()); - } - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter04Test.java b/chapter10b/src/test/java/com/seaofnodes/simple/Chapter04Test.java deleted file mode 100644 index edc62f50..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter04Test.java +++ /dev/null @@ -1,165 +0,0 @@ -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 Chapter04Test { - - @Test - public void testPeephole() { - Parser parser = new Parser("return 1+arg+2; "); - StopNode ret = parser.parse(); - assertEquals("return (arg+3);", ret.print()); - } - - @Test - public void testPeephole2() { - Parser parser = new Parser("return (1+arg)+2;"); - StopNode ret = parser.parse(); - assertEquals("return (arg+3);", ret.print()); - } - - @Test - public void testAdd0() { - Parser parser = new Parser("return 0+arg;"); - StopNode ret = parser.parse(); - assertEquals("return arg;", ret.print()); - } - - @Test - public void testAddAddMul() { - Parser parser = new Parser("return arg+0+arg;"); - StopNode ret = parser.parse(); - assertEquals("return (arg*2);", ret.print()); - } - - @Test - public void testPeephole3() { - Parser parser = new Parser("return 1+arg+2+arg+3; "); - StopNode ret = parser.parse(); - assertEquals("return ((arg*2)+6);", ret.print()); - } - - @Test - public void testMul1() { - Parser parser = new Parser("return 1*arg;"); - StopNode ret = parser.parse(); - assertEquals("return arg;", ret.print()); - } - - @Test - public void testSub0() { - Parser parser = new Parser("return arg-0;"); - StopNode ret = parser.parse(); - assertEquals("return arg;", ret.print()); - } - - @Test - public void test0Sub() { - Parser parser = new Parser("return 0-arg;"); - StopNode ret = parser.parse(); - assertEquals("return (-arg);", ret.print()); - } - - @Test - public void testSubNeg() { - Parser parser = new Parser("return 3--arg;"); - StopNode ret = parser.parse(); - assertEquals("return (arg+3);", ret.print()); - } - - @Test - public void testNegSub() { - Parser parser = new Parser("return -arg-3;"); - StopNode ret = parser.parse(); - assertEquals("return (-(arg+3));", ret.print()); - } - - @Test - public void testVarArg() { - 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); - assertEquals(1, ((ProjNode)ret.in(1))._idx); - assertTrue(ret.in(2) instanceof ProjNode); - assertEquals(2, ((ProjNode)ret.in(2))._idx); - } - - @Test - public void testConstantArg() { - Parser parser = new Parser("return arg; ", TypeInteger.constant(2)); - StopNode ret = parser.parse(); - assertEquals("return 2;", ret.print()); - } - - @Test - public void testCompEq() { - Parser parser = new Parser("return 3==3; "); - StopNode ret = parser.parse(); - assertEquals("return 1;", ret.print()); - } - - @Test - public void testCompEq2() { - Parser parser = new Parser("return 3==4; "); - StopNode ret = parser.parse(); - assertEquals("return 0;", ret.print()); - } - - @Test - public void testCompNEq() { - Parser parser = new Parser("return 3!=3; "); - StopNode ret = parser.parse(); - assertEquals("return 0;", ret.print()); - } - - @Test - public void testCompNEq2() { - Parser parser = new Parser("return 3!=4; "); - 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; "); - 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; "); - StopNode ret = parser.parse(); - assertEquals("return (arg+1);", ret.print()); - } - - @Test - public void testBug3() { - try { - new Parser("inta=1; return a;").parse(); - fail(); - } catch( RuntimeException e ) { - assertEquals("Undefined name 'inta'",e.getMessage()); - } - } - - @Test - public void testBug4() { - Parser parser = new Parser("return -arg;"); - StopNode ret = parser.parse(); - assertEquals("return (-arg);", ret.print()); - } - - @Test - public void testBug5() { - Parser parser = new Parser("return arg--2;"); - StopNode ret = parser.parse(); - assertEquals("return (arg--2);", ret.print()); - } -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter10b/src/test/java/com/seaofnodes/simple/Chapter05Test.java deleted file mode 100644 index cf7bd6cf..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter05Test.java +++ /dev/null @@ -1,228 +0,0 @@ -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().iterate(); - assertEquals("return Phi(Region19,(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().iterate(); - assertEquals("return Phi(Region17,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().iterate(); - assertEquals("return ((arg*2)+Phi(Region22,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().iterate(); - assertEquals("return ((Phi(Region33,(arg*2),arg)+arg)+Phi(Region,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().iterate(); - assertEquals("return Phi(Region37,Phi(Region23,2,3),Phi(Region35,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(Region14,1,0))+Phi(Region29,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().iterate(); - assertEquals("return (arg==Phi(Region17,3,2));", ret.toString()); - } - - @Test - public void testMergeSameCon() { - Parser parser = new Parser( -""" -int a=arg; -if( arg==1 ) - a=3; -else - a=3; -return a; -"""); - StopNode ret = parser.parse(); - assertEquals("return 3;", 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("Undefined name 'ififif'",e.getMessage()); - } - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter06Test.java b/chapter10b/src/test/java/com/seaofnodes/simple/Chapter06Test.java deleted file mode 100644 index 920e26e3..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter06Test.java +++ /dev/null @@ -1,294 +0,0 @@ -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 Chapter06Test { - - @Test - public void testPeepholeReturn() { - Parser parser = new Parser( -""" -if( true ) return 2; -return 1; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return 2;", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testPeepholeRotate() { - Parser parser = new Parser( -""" -int a = 1; -if (arg) - a = 2; -return (arg < a) < 3; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return ((arg<Phi(Region13,2,1))<3);", stop.toString()); - } - - @Test - public void testPeepholeCFG() { - Parser parser = new Parser( -""" -int a=1; -if( true ) - a=2; -else - a=3; -return a; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return 2;", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testIfIf() { - Parser parser = new Parser( -""" -int a=1; -if( arg!=1 ) - a=2; -else - a=3; -int b=4; -if( a==2 ) - b=42; -else - b=5; -return b;""", TypeInteger.BOT); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Region38,42,5);", stop.toString()); - } - - @Test - public void testIfArgIf() { - Parser parser = new Parser( -""" -int a=1; -if( 1==1 ) - a=2; -else - a=3; -int b=4; -if( arg==2 ) - b=a; -else - b=5; -return b;""", TypeInteger.BOT); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Region31,2,5);", stop.toString()); - } - - @Test - public void testMerge3With2() { - 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.constant(2)); - StopNode stop = parser.parse(); - assertEquals("return 5;", stop.toString()); - } - - @Test - public void testMerge3With1() { - 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.constant(1)); - StopNode stop = parser.parse().iterate(); - assertEquals("return 3;", stop.toString()); - } - - @Test - public void testMerge3Peephole() { - Parser parser = new Parser( -""" -int a=1; -if( arg==1 ) - if( 1==2 ) - a=2; - else - a=3; -else if( arg==3 ) - a=4; -else - a=5; -return a; -""", TypeInteger.BOT); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Region42,3,Phi(Region40,4,5));", stop.toString()); - } - - @Test - public void testMerge3Peephole1() { - Parser parser = new Parser( -""" -int a=1; -if( arg==1 ) - if( 1==2 ) - a=2; - else - a=3; -else if( arg==3 ) - a=4; -else - a=5; -return a; -""", TypeInteger.constant(1)); - StopNode stop = parser.parse().iterate(); - assertEquals("return 3;", stop.toString()); - } - - @Test - public void testMerge3Peephole3() { - Parser parser = new Parser( -""" -int a=1; -if( arg==1 ) - if( 1==2 ) - a=2; - else - a=3; -else if( arg==3 ) - a=4; -else - a=5; -return a; -""", TypeInteger.constant(3)); - StopNode stop = parser.parse().iterate(); - assertEquals("return 4;", stop.toString()); - } - - @Test - public void testDemo1NonConst() { - Parser parser = new Parser(""" -int a = 0; -int b = 1; -if( arg ) { - a = 2; - if( arg ) { b = 2; } - else b = 3; -} -return a+b; -"""); - StopNode ret = parser.parse().iterate(); - assertEquals("return Phi(Region25,4,1);", ret.toString()); - } - - - @Test - public void testDemo1True() { - Parser parser = new Parser(""" -int a = 0; -int b = 1; -if( arg ) { - a = 2; - if( arg ) { b = 2; } - else b = 3; -} -return a+b; -""", TypeInteger.constant(1)); - StopNode ret = parser.parse().iterate(); - assertEquals("return 4;", ret.toString()); - } - - @Test - public void testDemo1False() { - Parser parser = new Parser(""" -int a = 0; -int b = 1; -if( arg ) { - a = 2; - if( arg ) { b = 2; } - else b = 3; -} -return a+b; -""", TypeInteger.constant(0)); - StopNode ret = parser.parse().iterate(); - assertEquals("return 1;", ret.toString()); - } - - @Test - public void testDemo2NonConst() { - Parser parser = new Parser(""" -int a = 0; -int b = 1; -int c = 0; -if( arg ) { - a = 1; - if( arg==2 ) { c=2; } else { c=3; } - if( arg ) { b = 2; } - else b = 3; -} -return a+b+c; -"""); - StopNode ret = parser.parse().iterate(); - assertEquals("return (Phi(Region37,Phi(Region24,2,3),0)+Phi(Region,3,1));", ret.toString()); - } - - - @Test - public void testDemo2True() { - Parser parser = new Parser(""" -int a = 0; -int b = 1; -int c = 0; -if( arg ) { - a = 1; - if( arg==2 ) { c=2; } else { c=3; } - if( arg ) { b = 2; } - else b = 3; -} -return a+b+c; -""", TypeInteger.constant(1)); - StopNode ret = parser.parse().iterate(); - assertEquals("return 6;", ret.toString()); - } - - @Test - public void testDemo2arg2() { - Parser parser = new Parser(""" -int a = 0; -int b = 1; -int c = 0; -if( arg ) { - a = 1; - if( arg==2 ) { c=2; } else { c=3; } - if( arg ) { b = 2; } - else b = 3; -} -return a+b+c; -""", TypeInteger.constant(2)); - StopNode ret = parser.parse().iterate(); - assertEquals("return 5;", ret.toString()); - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter07Test.java b/chapter10b/src/test/java/com/seaofnodes/simple/Chapter07Test.java deleted file mode 100644 index ff0ca599..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter07Test.java +++ /dev/null @@ -1,222 +0,0 @@ -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 Chapter07Test { - - @Test - public void testExample() { - Parser parser = new Parser( - """ - while(arg < 10) { - arg = arg + 1; - } - return arg; - """); - StopNode stop = parser.parse(); - assertEquals("return Phi(Loop7,arg,(Phi_arg+1));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testRegression() { - Parser parser = new Parser( -""" -int a = 1; -if(arg){}else{ - while(a < 10) { - a = a + 1; - } -} -return a; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Region25,1,Phi(Loop14,1,(Phi_a+1)));", stop.toString()); - } - - @Test - public void testWhileNested() { - Parser parser = new Parser( -""" -int sum = 0; -int i = 0; -while(i < arg) { - i = i + 1; - int j = 0; - while( j < arg ) { - sum = sum + j; - j = j + 1; - } -} -return sum; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop9,0,Phi(Loop21,Phi_sum,(Phi_sum+Phi(Loop,0,(Phi_j+1)))));", stop.toString()); - } - - @Test - public void testWhileScope() { - Parser parser = new Parser( -""" -int a = 1; -int b = 2; -while(a < 10) { - if (a == 2) a = 3; - else b = 4; -} -return b; -"""); - StopNode stop = parser.parse(); - assertEquals("return Phi(Loop9,2,Phi(Region28,Phi_b,4));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testWhileNestedIfAndInc() { - Parser parser = new Parser( -""" -int a = 1; -int b = 2; -while(a < 10) { - if (a == 2) a = 3; - else b = 4; - b = b + 1; - a = a + 1; -} -return b; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop9,2,(Phi(Region28,Phi_b,4)+1));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - - @Test - public void testWhile() { - Parser parser = new Parser( -""" -int a = 1; -while(a < 10) { - a = a + 1; - a = a + 2; -} -return a; -"""); - StopNode stop = parser.parse(); - assertEquals("return Phi(Loop8,1,(Phi_a+3));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testWhilePeep() { - Parser parser = new Parser( -""" -int a = 1; -while(a < 10) { - a = a + 1; - a = a + 2; -} -return a; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop8,1,(Phi_a+3));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testWhile2() { - Parser parser = new Parser( -""" -int a = 1; -while(arg) a = 2; -return a; -"""); - StopNode stop = parser.parse(); - assertEquals("return Phi(Loop8,1,2);", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testWhile2Peep() { - Parser parser = new Parser( -""" -int a = 1; -while(arg) a = 2; -return a; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop8,1,2);", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testWhile3() { - Parser parser = new Parser( -""" -int a = 1; -while(a < 10) { - int b = a + 1; - a = b + 2; -} -return a; -"""); - StopNode stop = parser.parse(); - assertEquals("return Phi(Loop8,1,(Phi_a+3));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testWhile3Peep() { - Parser parser = new Parser( -""" -int a = 1; -while(a < 10) { - int b = a + 1; - a = b + 2; -} -return a; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop8,1,(Phi_a+3));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testWhile4() { - Parser parser = new Parser( -""" -int a = 1; -int b = 2; -while(a < 10) { - int b = a + 1; - a = b + 2; -} -return a; -"""); - StopNode stop = parser.parse(); - assertEquals("return Phi(Loop9,1,(Phi_a+3));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testWhile4Peep() { - Parser parser = new Parser( -""" -int a = 1; -int b = 2; -while(a < 10) { - int b = a + 1; - a = b + 2; -} -return a; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop9,1,(Phi_a+3));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter08Test.java b/chapter10b/src/test/java/com/seaofnodes/simple/Chapter08Test.java deleted file mode 100644 index 4fa08bd9..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter08Test.java +++ /dev/null @@ -1,209 +0,0 @@ -package com.seaofnodes.simple; - -import com.seaofnodes.simple.evaluator.Evaluator; -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.TypeInteger; -import org.junit.Assert; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class Chapter08Test { - - @Test - public void testEx6() { - Parser parser = new Parser( - """ -while(arg < 10) { - arg = arg + 1; - if (arg == 5) - break; - if (arg == 6) - break; -} -return arg; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Region37,Phi(Region26,Phi(Loop7,arg,(Phi_arg+1)),Add),Add);", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof RegionNode); - Assert.assertEquals(5L, Evaluator.evaluate(stop, 1)); - Assert.assertEquals(10L, Evaluator.evaluate(stop, 6)); - } - - - @Test - public void testEx5() { - Parser parser = new Parser( - """ -int a = 1; -while(arg < 10) { - arg = arg + 1; - if (arg == 5) - continue; - if (arg == 7) - continue; - a = a + 1; -} -return a; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop8,1,Phi(Region43,Phi_a,(Phi_a+1)));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - - @Test - public void testEx4() { - Parser parser = new Parser( - """ -while(arg < 10) { - arg = arg + 1; - if (arg == 5) - continue; - if (arg == 6) - break; -} -return arg; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Region35,Phi(Loop7,arg,(Phi_arg+1)),Add);", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof RegionNode); - } - - @Test - public void testEx3() { - Parser parser = new Parser( - """ -while(arg < 10) { - arg = arg + 1; - if (arg == 6) - break; -} -return arg; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Region26,Phi(Loop7,arg,(Phi_arg+1)),Add);", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof RegionNode); - } - - - @Test - public void testEx2() { - Parser parser = new Parser( - """ -while(arg < 10) { - arg = arg + 1; - if (arg == 5) - continue; - if (arg == 6) - continue; -} -return arg; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop7,arg,(Phi_arg+1));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - - @Test - public void testEx1() { - Parser parser = new Parser( - """ -while(arg < 10) { - arg = arg + 1; - if (arg == 5) - continue; -} -return arg; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop7,arg,(Phi_arg+1));", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode); - } - - @Test - public void testRegress1() { - Parser parser = new Parser( - """ -while( arg < 10 ) { - int a = arg+2; - if( a > 4 ) - break; -} -return arg; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return arg;", stop.toString()); - } - - @Test - public void testRegress2() { - Parser parser = new Parser("if(1) return 0; else while(arg>--arg) arg=arg+1; return 0;"); - StopNode stop = parser.parse().iterate(); - assertEquals("return 0;", stop.toString()); - } - - @Test - public void testBreakOutsideLoop() { - try { - new Parser(""" -if(arg <= 10) { - break; - arg = arg + 1; -} -return arg; -""").parse(); - fail(); - } catch( RuntimeException e ) { - assertEquals("No active loop for a break or continue",e.getMessage()); - } - } - - @Test - public void testRegress3() { - Parser parser = new Parser(""" -while(arg < 10) { - break; -} -return arg; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return arg;", stop.toString()); - } - - @Test - public void testRegress4() { - Parser parser = new Parser(""" -int a = 1; -while(arg < 10) { - a = a + 1; - if (arg > 2) { - int a = 17; - break; - } -} -return a; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Region29,Phi(Loop8,1,(Phi_a+1)),Add);", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof RegionNode); - } - - @Test - public void testRegress5() { - Parser parser = new Parser(""" -int a = 1; -while(1) { - a = a + 1; - if (a<10) continue; - break; -} -return a; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return (Phi(Loop8,1,Add)+1);", stop.toString()); - assertTrue(stop.ret().ctrl() instanceof ProjNode prj && prj._idx==1 ); - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter10b/src/test/java/com/seaofnodes/simple/Chapter09Test.java deleted file mode 100644 index 1b1920e8..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter09Test.java +++ /dev/null @@ -1,301 +0,0 @@ -package com.seaofnodes.simple; - -import com.seaofnodes.simple.evaluator.Evaluator; -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeInteger; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.Ignore; - -import static org.junit.Assert.*; - -public class Chapter09Test { - - @Test - @Ignore - public void testJig() { - Parser parser = new Parser(""" -int v0=0; -arg=0; -while(v0) { - while(1) if(arg*arg*0==0) {} - while(0) {} - arg=1; -} -return 0; - """); - StopNode stop = parser.parse().iterate(); - } - - @Test - public void testGVN1() { - Parser parser = new Parser( - """ -int x = arg + arg; -if(arg < 10) { - return arg + arg; -} -else { - x = x + 1; -} -return x; - """); - StopNode stop = parser.parse(); - assertEquals("Stop[ return (arg*2); return (Mul+1); ]", stop.toString()); - Assert.assertEquals(2L, Evaluator.evaluate(stop, 1)); - Assert.assertEquals(23L, Evaluator.evaluate(stop, 11)); - } - - @Test - public void testGVN2() { - Parser parser = new Parser( - """ -return arg*arg-arg*arg; - """); - StopNode stop = parser.parse(); - assertEquals("return 0;", stop.toString()); - Assert.assertEquals(0L, Evaluator.evaluate(stop, 1)); - } - - @Test - public void testWorklist1() { - Parser parser = new Parser( - """ -int step = 1; -while (arg < 10) { - arg = arg + step + 1; -} -return arg; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop8,arg,(Phi_arg+2));", stop.toString()); - Assert.assertEquals(11L, Evaluator.evaluate(stop, 1)); - } - - @Test - public void testWorklist2() { - Parser parser = new Parser( - """ -int cond = 0; -int one = 1; -while (arg < 10) { - if (cond) one = 2; - arg = arg + one*3 + 1; -} -return arg; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop9,arg,(Phi_arg+4));", stop.toString()); - Assert.assertEquals(13L, Evaluator.evaluate(stop, 1)); - } - - @Test - public void testWorklist3() { - Parser parser = new Parser( - """ -int v1 = 0; -int v2 = 0; -int v3 = 0; -int v4 = 0; -int v5 = 0; -int v6 = 0; -int v7 = 0; -int v8 = 0; -while (arg) { - if (v1) v2 = 1; - if (v2) v3 = 1; - if (v3) v4 = 1; - if (v4) v5 = 1; - if (v5) v6 = 1; - if (v6) v7 = 1; - if (v7) v8 = 1; - arg = arg + v8 + 1; -} -return arg; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop15,arg,(Phi_arg+1));", stop.toString()); - } - - @Test - public void testRegionPeepBug() { - Parser parser = new Parser( - """ -int v0=0; -int v1=0; -while(v1+arg) { - arg=0; - int v2=v0; - while(arg+1) {} - v0=1; - v1=v2; -} - """); - StopNode stop = parser.parse().iterate(); - assertEquals("Stop[ ]", stop.toString()); - } - - @Test - public void testWhile0() { - Parser parser = new Parser("while(0) continue; if(0) arg=0;"); - StopNode stop = parser.parse().iterate(); - assertEquals("Stop[ ]", stop.toString()); - } - - @Test - public void testWhile1() { - Parser parser = new Parser(""" -if(0) while(0) { - int arg=arg; - while(0) {} -} -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("Stop[ ]", stop.toString()); - } - - - @Test - public void testPrecedence() { - Parser parser = new Parser("return 3-1+2;"); - StopNode stop = parser.parse().iterate(); - assertEquals("return 4;", stop.toString()); - } - - @Test - public void testSwap2() { - Parser parser = new Parser("return 1+(1+1);"); - StopNode stop = parser.parse().iterate(); - assertEquals("return 3;", stop.toString()); - } - - - @Test - public void testFuzz0() { - Parser parser = new Parser(""" -int one = 1; -int a = 0; -int zero = 0; -while(arg) { - a = -(one + a + 2); - arg = arg + 1; - one = one + zero; -} -return a; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop10,0,(-(Phi_a+3)));", stop.toString()); - } - - @Test - public void testFuzz1() { - Parser parser = new Parser(""" -while(1) {} -while(arg) break; -while(arg) arg=0; -arg=0; -int v0=0!=0<-0; -return -0+0+0; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("Stop[ ]", stop.toString()); - } - - - @Test - public void testFuzz2() { - Parser parser = new Parser("return 0+-0;"); - StopNode stop = parser.parse().iterate(); - assertEquals("return 0;", stop.toString()); - } - - @Test - public void testFuzz3() { - Parser parser = new Parser("int v0=0; while(0==69) while(v0) return 0;"); - StopNode stop = parser.parse().iterate(); - assertEquals("Stop[ ]", stop.toString()); - } - - @Test - public void testFuzz4() { - Parser parser = new Parser(""" -while(1) { - arg=0<=0; - if(1<0) while(arg==-0) arg=arg-arg; -} -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("Stop[ ]", stop.toString()); - } - - @Test - public void testFuzz5() { - Parser parser = new Parser(""" -{ - int v0=0; - while(1) - int v1=0--0; - while(v0) - break; - while(-v0) { - while(0+0+v0) continue; - break; - } - if(-0!=-0+0+v0) while(0+0+0+0) - break; -} -return 0!=0; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("Stop[ ]", stop.toString()); - } - - @Test - public void testFuzz6() { - Parser parser = new Parser(""" -int v0=0; -while(0==1) while(v0) - v0=1+v0; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("Stop[ ]", stop.toString()); - } - - @Test - public void testFuzz7() { - Parser parser = new Parser(""" -while(1) {} -int v0=0; -while(v0) - {} -int v1=0; -while(1) - v1=1; -return v1+v0; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("Stop[ ]", stop.toString()); - } - - @Test - public void testFuzz8() { - Parser parser = new Parser("while(arg) arg = arg - 1; return arg;"); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop7,arg,(Phi_arg-1));", stop.toString()); - } - - @Test - public void testMeet() { - Type t1 = Type.TOP; - Type t2 = TypeInteger.TOP; - Assert.assertEquals(TypeInteger.TOP, t1.meet(t2)); - Assert.assertEquals(TypeInteger.TOP, t2.meet(t1)); - t1 = Type.BOTTOM; - t2 = TypeInteger.BOT; - Assert.assertEquals(Type.BOTTOM, t1.meet(t2)); - Assert.assertEquals(Type.BOTTOM, t2.meet(t1)); - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter10Test.java b/chapter10b/src/test/java/com/seaofnodes/simple/Chapter10Test.java deleted file mode 100644 index 8bf1debe..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter10Test.java +++ /dev/null @@ -1,583 +0,0 @@ -package com.seaofnodes.simple; - -import com.seaofnodes.simple.node.Node; -import com.seaofnodes.simple.node.StopNode; -import com.seaofnodes.simple.type.*; -import com.seaofnodes.simple.node.LoadNode; -import com.seaofnodes.simple.node.StoreNode; -import com.seaofnodes.simple.evaluator.Evaluator; -import java.util.BitSet; -import org.junit.Test; - -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -public class Chapter10Test { - @Test public void testDeadReferenceReturn() { - for( String body : new String[] { - "return new S; return 0;", - "if(1) return new S; else return 0;" - } ) { - String src = "struct S { int x; }; " + body; - var stop = new Parser(src).parse().iterate(); - org.junit.Assert.assertTrue(body, - stop.ret().expr()._type instanceof com.seaofnodes.simple.type.TypeMemPtr); - } - } - - - - // Issue #246: null-check guards start in Chapter 10; arrays arrive in Chapter 15. - private static final String NULLABLE_POINT_SOURCE = """ - struct Point { int x; }; - Point point = new Point; - point.x = 42; - Point? p = null; - if (arg) p = point; - """; - - @Test - public void testNullGuards() { - for( String body : new String[] { - "if (p != null) return p.x; return -1;", - "if (null != p) return p.x; return -1;", - "if (!!!!p) return p.x; return -1;", - "if (!!!p) return -1; else return p.x;", - "int b = !!p; if (b) return p.x + b - 1; return -1;" - } ) { - StopNode stop = new Parser(NULLABLE_POINT_SOURCE+body).parse().iterate(); - assertEquals(body,-1L,com.seaofnodes.simple.evaluator.Evaluator.evaluate(stop,0)); - assertEquals(body,42L,com.seaofnodes.simple.evaluator.Evaluator.evaluate(stop,1)); - } - } - - @Test - public void testNullGuardErrors() { - for( String body : new String[] { - "return p.x;", - "if (p == null) return p.x; return -1;", - "if (!!point) return p.x; return -1;", - "if (!!p) { int x = p.x; } return p.x;" - } ) { - try { - new Parser(NULLABLE_POINT_SOURCE+body).parse().iterate(); - fail(body); - } catch( RuntimeException e ) { - // Known null is rejected during parsing in these chapters. - String expected = body.startsWith("if (p == null)") - ? "Accessing unknown field 'x' from 'null'" : "Might be null accessing 'x'"; - assertEquals(body,expected,e.getMessage()); - } - } - } - - @Test - public void testFuzzer() { - Parser parser = new Parser( -""" -int a = arg/3; -int b = arg*5; -int x = arg*7; -int y = arg/11; -int p; int g; int h; -if( (arg/13)==0 ) { - p = x + y; - g = x; - h = y; -} else { - p = a + b; - g = a; - h = b; -} -int r = g+h; -return p-r; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return 0;", stop.toString()); - } - - @Test - public void testStruct() { - Parser parser = new Parser(""" -struct Bar { - int a; - int b; -} -struct Foo { - int x; -} -Foo? foo = null; -Bar bar = new Bar; -bar.a = 1; -bar.a = 2; -return bar.a; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return 2;", stop.toString()); - } - - @Test - public void testExample() { - Parser parser = new Parser(""" -struct Vector2D { int x; int y; } -Vector2D v = new Vector2D; -v.x = 1; -if (arg) - v.y = 2; -else - v.y = 3; -return v; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return new Vector2D;", stop.toString()); - } - - @Test - public void testBug() { - Parser parser = new Parser(""" -struct s0 { - int v0; -} -s0? v1=null; -int v3=v1.zAicm; -"""); - try { parser.parse(); fail(); } - catch( Exception e ) { assertEquals("Accessing unknown field 'zAicm' from 'null'",e.getMessage()); } - } - - @Test - public void testBug2() { - Parser parser = new Parser(""" -struct s0 { int v0; } -arg=0+new s0.0; -"""); - try { parser.parse(); fail(); } - catch( Exception e ) { assertEquals("Expected an identifier, found 'null'",e.getMessage()); } - } - - @Test - public void testLoop() { - Parser parser = new Parser(""" -struct Bar { int a; } -Bar bar = new Bar; -while (arg) { - bar.a = bar.a + 2; - arg = arg + 1; -} -return bar.a; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop11,0,(Phi_a+2));", stop.toString()); - } - - @Test - public void testIf() { - Parser parser = new Parser(""" -struct Bar { int a; } -Bar bar = new Bar; -if (arg) bar = null; -bar.a = 1; -return bar.a; -"""); - try { parser.parse().iterate(); fail(); } - catch( Exception e ) { assertEquals("Type null is not of declared type *Bar",e.getMessage()); } - } - - @Test - public void testIf2() { - Parser parser = new Parser(""" -struct Bar { int a; } -Bar? bar = null; -if (arg) bar = new Bar; -bar.a = 1; -return bar.a; -"""); - try { parser.parse().iterate(); fail(); } - catch( Exception e ) { assertEquals("Might be null accessing 'a'",e.getMessage()); } - } - - @Test - public void testIf3() { - Parser parser = new Parser(""" -struct Bar { int a; } -Bar bar = null; -if (arg) bar = null; -bar.a = 1; -return bar.a; -"""); - try { parser.parse(); fail(); } - catch( Exception e ) { assertEquals("Type null is not of declared type *Bar", e.getMessage()); } - } - - @Test - public void testIfOrNull() { - Parser parser = new Parser(""" -struct Bar { int a; } -Bar? bar = new Bar; -if (arg) bar = null; -if( bar ) bar.a = 1; -return bar; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Region16,null,new Bar);", stop.toString()); - } - - @Test - public void testIfOrNull2() { - Parser parser = new Parser( -""" -struct Bar { int a; } -Bar? bar = new Bar; -if (arg) bar = null; -int rez = 3; -if( !bar ) rez=4; -else bar.a = 1; -return rez; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Region34,4,3);", stop.toString()); - } - - @Test - public void testWhileWithNullInside() { - Parser parser = new Parser(""" -struct s0 {int v0;} -s0? v0 = new s0; -int ret = 0; -while(arg) { - ret = v0.v0; - v0 = null; - arg = arg - 1; -} -return ret; -"""); - try { parser.parse().iterate(); fail(); } - catch( Exception e ) { assertEquals("Might be null accessing 'v0'", e.getMessage()); } - } - - @Test - public void testRedeclareStruct() { - Parser parser = new Parser(""" -struct s0 { - int v0; -} -s0? v1=new s0; -s0? v1; -v1=new s0; -"""); - try { parser.parse(); fail(); } - catch( Exception e ) { assertEquals("Redefining name 'v1'", e.getMessage()); } - } - - @Test - public void testIter() { - // Build and use an iterator - Parser parser = new Parser( -""" -struct Iter { - int x; - int len; -} -Iter i = new Iter; -i.len = arg; -int sum=0; -while( i.x < i.len ) { - sum = sum + i.x; - i.x = i.x + 1; -} -return sum; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop16,0,(Phi(Loop,0,(Phi_x+1))+Phi_sum));", stop.toString()); - } - - - - - @Test - public void test1() { - Parser parser = new Parser(""" -struct s0 {int v0;} -s0 ret = new s0; -while(arg) { - s0 v0 = new s0; - v0.v0 = arg; - arg = arg-1; - if (arg==5) ret=v0; -} -return ret; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop11,new s0,Phi(Region34,new s0,Phi_ret));", stop.toString()); - } - - @Test - public void test2() { - Parser parser = new Parser(""" -struct s0 {int v0;} -s0 ret = new s0; -s0 v0 = new s0; -while(arg) { - v0.v0 = arg; - arg = arg-1; - if (arg==5) ret=v0; -} -return ret; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop15,new s0,Phi(Region35,new s0,Phi_ret));", stop.toString()); - } - - - @Test - public void test3() { - Parser parser = new Parser(""" -struct s0 {int v0;} -s0 ret = new s0; -while(arg < 10) { - s0 v0 = new s0; - if (arg == 5) ret=v0; - arg = arg + 1; -} -return ret; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return Phi(Loop11,new s0,Phi(Region32,new s0,Phi_ret));", stop.toString()); - } - - @Test - public void testBug3() { - Parser parser = new Parser(""" -struct s0 { - int f0; -} -if(0>=0) return new s0; -return new s0; -int v0=null.f0; -"""); - try { parser.parse(); fail(); } - catch( Exception e ) { assertEquals("Accessing unknown field 'f0' from 'null'", e.getMessage()); } - } - - @Test - public void testBug4() { - Parser parser = new Parser(""" -if(0) { - while(0) if(arg) continue; - int v0=0; - while(1) { - int arg=-arg; - v0=arg; - } -} - """); - StopNode stop = parser.parse().iterate(); - assertEquals("Stop[ ]", stop.toString()); - } - - @Test - public void testBug5() { - Parser parser = new Parser(""" -struct s0 { - int f0; -} -if(0) return 0; -else return new s0; -if(new s0.f0) return 0; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return new s0;", stop.toString()); - } - - @Test - public void testBug6MissedWorklist() { - Parser parser = new Parser(""" -while(0) {} -int v4=0; -while(0<arg) { - v4=v4+1; - while(1) v4=-v4; - while(0) arg=-1; -} -return 0; - """); - StopNode stop = parser.parse().iterate(); - } - - @Test - public void testBug7() { - Parser parser = new Parser(""" -struct s0 { int f0; } -s0 v0 = new s0; -while(v0.f0) {} -s0 v1 = v0; -return v1; - """); - StopNode stop = parser.parse().iterate(); - assertEquals("return new s0;", stop.toString()); - } - - - @Test - public void testBug8() { - Parser parser = new Parser(""" -int v2=0; -while(0) -while(0) {} -{ - { - { - int v36=0; - { - while(0) { - { - while(-v2) { - { - while(v36) { - while(v2) return 0; - break; - } } - if(-v2) break; - } - } - } - } - } } -} -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("Stop[ ]", stop.toString()); - } - - @Test - public void testBug9() { - Parser parser = new Parser(""" -int v0=arg==0; -while(v0) continue; -return 0; -"""); - StopNode stop = parser.parse().iterate(); - assertEquals("return 0;", stop.toString()); - } - - - @Test public void testReadBeforeStores() { - var stop = new Parser(""" - struct S { int x; int y; } - S a = new S; S b = new S; - a.x = 11; b.x = 22; - S p = a; if (arg) p = b; - int before = p.x; - a.y = 55; b.y = 66; - a.x = 33; b.x = 44; - return before*100 + p.x; - """).parse().iterate(); - assertEquals(1133L, com.seaofnodes.simple.evaluator.Evaluator.evaluate(stop,0)); - assertEquals(2244L, com.seaofnodes.simple.evaluator.Evaluator.evaluate(stop,1)); - } - - static final String NESTED_MEMORY = """ - struct S { int x; int y; int z; } - S s = new S; - s.x = 5; s.y = 7; s.z = 11; - while (arg > 0) { - s.x = s.x + 1; - int j = 3; - while (j > 0) { - j = j - 1; - if (j == 1) continue; - s.y = s.y + arg; - if (arg == 2) break; - s.z = s.z + 1; - } - arg = arg - 1; - } - return s; - """; - - @Test public void testMemoryAcrossNestedLoops() { - var stop = new Parser(NESTED_MEMORY).parse().iterate(); - for (int arg=0; arg<7; arg++) { - var obj = (com.seaofnodes.simple.evaluator.Evaluator.Obj) - com.seaofnodes.simple.evaluator.Evaluator.evaluate(stop,arg); - org.junit.Assert.assertArrayEquals(new Object[] { - 5L+arg, 7L+arg*(arg+1)-(arg>=2 ? 2 : 0), 11L+2*arg-(arg>=2 ? 2 : 0) - }, obj.fields()); - } - } - - @Test public void testMemoryAtEarlyReturns() { - var stop = new Parser(""" - struct S { int x; int y; int z; } - S s = new S; - s.x = 3; s.y = 5; s.z = 7; - if (arg) { s.x = 11; s.z = 13; return s; } - s.y = 17; - return s; - """).parse().iterate(); - for (int arg=0; arg<2; arg++) { - var obj = (com.seaofnodes.simple.evaluator.Evaluator.Obj) - com.seaofnodes.simple.evaluator.Evaluator.evaluate(stop,arg); - org.junit.Assert.assertArrayEquals(arg==0 ? new Object[]{3L,17L,7L} : new Object[]{11L,5L,13L}, obj.fields()); - } - } - - @Test public void testKeepLoadsAtMerge() { - StopNode stop = new Parser(""" - struct S { int x; } - S a = new S; S b = new S; - a.x = arg; b.x = arg+1; - S p = a; S q = b; - if (arg<0) { p=b; q=a; } - int v; - if (arg>1) v=p.x; else v=q.x; - return v; - """).parse().iterate(); - // The one-step safety check stops at the memory aggregate. - assertEquals(2,countMemoryNodes(stop,LoadNode.class,new BitSet())); - assertEquals(-1L,Evaluator.evaluate(stop,-1)); - assertEquals(1L,Evaluator.evaluate(stop,0)); - assertEquals(3L,Evaluator.evaluate(stop,3)); - } - - @Test public void testDropStores() { - StopNode stop = new Parser(""" - struct S { int x; } - S s = new S; - if (arg) s.x=arg+1; else s.x=arg+2; - return s; - """).parse().iterate(); - // The initializing slice also remains live as the aggregate default. - assertEquals(2,countMemoryNodes(stop,StoreNode.class,new BitSet())); - assertEquals(2L,((Evaluator.Obj)Evaluator.evaluate(stop,0)).fields()[0]); - assertEquals(4L,((Evaluator.Obj)Evaluator.evaluate(stop,3)).fields()[0]); - } - - @Test public void testKeepReadsBeforeWrites() { - StopNode stop = new Parser(""" - struct S { int x; int y; } - S a = new S; S b = new S; - a.x=arg; b.x=arg+1; - S p=a; S q=b; - if (arg<0) { p=b; q=a; } - int v; - if (arg>1) { v=p.x; p.x=41; p.y=5; } - else { v=q.x; q.x=42; } - return v; - """).parse().iterate(); - assertEquals(2,countMemoryNodes(stop,LoadNode.class,new BitSet())); - assertEquals(-1L,Evaluator.evaluate(stop,-1)); - assertEquals(1L,Evaluator.evaluate(stop,0)); - assertEquals(3L,Evaluator.evaluate(stop,3)); - } - - private static int countMemoryNodes(Node n, Class<?> kind, BitSet seen) { - if (n==null || seen.get(n._nid)) return 0; - seen.set(n._nid); - int cnt=kind.isInstance(n) ? 1 : 0; - for (Node def : n._inputs) cnt+=countMemoryNodes(def,kind,seen); - return cnt; - } -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter10bTest.java b/chapter10b/src/test/java/com/seaofnodes/simple/Chapter10bTest.java deleted file mode 100644 index 6f094cfb..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/Chapter10bTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.seaofnodes.simple; - -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.evaluator.Evaluator; -import org.junit.Test; -import static org.junit.Assert.*; - -public class Chapter10bTest { - @Test public void testIndependentField() { - var stop = new Parser(""" - struct S { int x; int y; } - S s = new S; - s.x = 42; - while (arg > 0) { s.y = s.y + arg; arg = arg - 1; } - return s.x; - """).parse().iterate(); - assertEquals("return 42;",stop.toString()); - assertEquals(42L,Evaluator.evaluate(stop,5)); - assertNull(stop.walk(n -> n instanceof LoadNode ? n : null)); - } - - @Test public void testParallelMemoryPhis() { - var stop = new Parser(""" - struct S { int x; int y; int z; } - S a = new S; S b = new S; - S p = a; if (arg) p = b; - while (arg > 0) { - a.x = p.x + arg; - a.y = p.y + 2; - a.z = p.z + 3; - arg = arg - 1; - } - return a; - """).parse().iterate(); - int[] phis = {0}; - stop.walk(n -> { - if (n instanceof MemPhiNode) phis[0]++; - if (n instanceof MemMergeNode m && m.in(1) instanceof BulkMemPhiNode b) - for(int a=b._aliases.nextSetBit(0); a>=0; a=b._aliases.nextSetBit(a+1)) - assertTrue(a<m.nIns() && m.in(a)!=null); - assertFalse(n instanceof PhiNode && n.isMem() && - !(n instanceof MemPhiNode) && !(n instanceof BulkMemPhiNode)); - return null; - }); - assertTrue(phis[0]>=3); - assertArrayEquals(new Object[]{1L,2L,3L},((Evaluator.Obj)Evaluator.evaluate(stop,4)).fields()); - } - - @Test public void testLateSliceWorklist() throws ReflectiveOperationException { - // Seed 97 exposed a store selecting a bulk predecessor without queuing - // it. Keep both the worklist assertion and the final heap check. - for (int seed : new int[]{0,97,123,456}) { - var parser = new Parser(Chapter10Test.NESTED_MEMORY); - var field = IterPeeps.class.getDeclaredField("WORK"); - field.setAccessible(true); - Object work = field.get(null); - field = work.getClass().getDeclaredField("_R"); - field.setAccessible(true); - ((java.util.Random)field.get(work)).setSeed(seed); - var stop = parser.parse().iterate(); - assertArrayEquals(new Object[]{9L,25L,17L},((Evaluator.Obj)Evaluator.evaluate(stop,4)).fields()); - } - } -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/FuzzerWrap.java b/chapter10b/src/test/java/com/seaofnodes/simple/FuzzerWrap.java deleted file mode 100644 index 019140ad..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/FuzzerWrap.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.seaofnodes.simple; - -import com.seaofnodes.simple.fuzzer.Fuzzer; -import org.junit.Test; -import org.junit.Ignore; - - -import static org.junit.Assert.assertTrue; - -/** - * Normal tests run chapter-local regression seeds. Open failures and exploratory - * fuzzing are opt-in (run directly in the IDE or temporarily remove Ignore). - * Seeds depend on this chapter's generator; do not copy them between chapters. - */ -public class FuzzerWrap { - - private static final long[] REGRESSION_SEEDS = { - }; - - private static final long[] OPEN_FAILING_SEEDS = { - }; - - @Test public void fuzzPeepsRegression () { fuzzPeepsSeeds(REGRESSION_SEEDS); } - @Test @Ignore public void fuzzPeepsOpenFailures() { fuzzPeepsSeeds(OPEN_FAILING_SEEDS); } - - private static void fuzzPeepsSeeds(long... seeds) { - var fuzzer = new Fuzzer(); - for (long seed : seeds) - fuzzer.fuzzPeepsRegression(seed); - } - - @Test - @Ignore - public void fuzzPeepsLarge() { - var fuzzer = new Fuzzer(); - for (int i=0; i<1000000; i++) - fuzzer.fuzzPeeps(i); - assertTrue(fuzzer.noExceptions()); - } - - - @Test - @Ignore - public void fuzzPeepTiming() { - var fuzzer = new Fuzzer(); - int max_nid=0; - for (int i=0; i<1000000; i++) - max_nid = fuzzer.fuzzPeepTiming(i, max_nid); - } -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/SchedulerTest.java b/chapter10b/src/test/java/com/seaofnodes/simple/SchedulerTest.java deleted file mode 100644 index ad595822..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/SchedulerTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.seaofnodes.simple; - -import com.seaofnodes.simple.evaluator.Evaluator; -import com.seaofnodes.simple.node.StopNode; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class SchedulerTest { - - private static void assertObj(Object obj, String name, Object... fields) { - assertEquals(Evaluator.Obj.class, obj.getClass()); - var o = (Evaluator.Obj)obj; - assertEquals(name, o.struct()._name); - Assert.assertArrayEquals(fields, o.fields()); - } - - @Test - @Ignore - public void testJig() { - Parser parser = new Parser(""" -struct S { - int f; -} -S v=new S; -v.f = 2; -int i=v.f; -if (arg) v.f=1; -return i; -"""); - StopNode stop = parser.parse();//.iterate(); - var eval = new Evaluator(stop); - assertEquals(2L, eval.evaluate(1, 10)); - } - - @Test - public void testStoreInIf() { - Parser parser = new Parser(""" -struct S { - int f; -} -S v0=new S; -if(arg) v0.f=1; -return v0; -"""); - StopNode stop = parser.parse().iterate(); - var eval = new Evaluator(stop); - assertObj(eval.evaluate(0, 10), "S", 0L); - assertObj(eval.evaluate(1, 10), "S", 1L); - } - - @Test - public void testStoreInIf2() { - Parser parser = new Parser(""" -struct S { - int f; -} -S v=new S; -v.f = 2; -int i=new S.f; -i=v.f; -if (arg) v.f=1; -return i; -"""); - StopNode stop = parser.parse().iterate(); - var eval = new Evaluator(stop); - assertEquals(2L, eval.evaluate(0, 10)); - assertEquals(2L, eval.evaluate(1, 10)); - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/TypeTest.java b/chapter10b/src/test/java/com/seaofnodes/simple/TypeTest.java deleted file mode 100644 index f9c580cc..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/TypeTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.seaofnodes.simple; - -import com.seaofnodes.simple.type.*; -import org.junit.Assert; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; - -public class TypeTest { - - // Test basic properties and GLB - @Test - public void testTypeAdHoc() { - TypeStruct s1 = TypeStruct.make("s1", new Field[]{ - Field.make("a", TypeInteger.BOT), - Field.make("b", TypeInteger.BOT) }); - TypeStruct s2 = TypeStruct.make("s2", new Field[]{ - Field.make("a", TypeInteger.BOT), - Field.make("b", TypeInteger.BOT) }); - Assert.assertEquals(s1, s1.glb()); - Assert.assertNotEquals(s1, s1.dual()); - Assert.assertEquals(s1, s1.dual().glb()); - - TypeMem m1 = TypeMem.make(1); - TypeMem m2 = TypeMem.make(2); - TypeMem m3 = TypeMem.make(3); - TypeMem m4 = TypeMem.make(4); - - Assert.assertNotEquals(m1, m2); - Assert.assertNotEquals(m2, m3); - Assert.assertNotEquals(m3, m4); - - Assert.assertEquals(TypeStruct.BOT, s1.meet(s2)); - Assert.assertEquals(TypeMem .BOT, m1.meet(m2)); - Assert.assertEquals(TypeMem .BOT, m2.meet(m3)); - Assert.assertEquals(TypeMem .BOT, m3.meet(m4)); - - Assert.assertEquals(TypeMem.BOT, m1.glb()); - Assert.assertEquals(m1, m1.dual()); - Assert.assertEquals(TypeMem.TOP, m1.glb().dual()); - - TypeMemPtr ptr1 = TypeMemPtr.make(s1); - Assert.assertEquals(s1, ptr1._obj); - TypeMemPtr ptr2 = TypeMemPtr.make(s2); - Assert.assertEquals(s2, ptr2._obj); - - TypeMemPtr ptr1nil = TypeMemPtr.make(s1, true); - Assert.assertEquals(s1, ptr1nil._obj); - Assert.assertTrue(ptr1nil._nil); - Assert.assertFalse(ptr1nil._obj==null); - TypeMemPtr ptr2nil = TypeMemPtr.make(s2, true); - Assert.assertEquals(s2, ptr2nil._obj); - - Assert.assertNotEquals(ptr1, ptr2); - Assert.assertNotEquals(ptr1, ptr1.glb()); - Assert.assertEquals(ptr1nil, ptr1.glb()); - - Assert.assertEquals(ptr1, ptr1.dual().dual()); - Assert.assertEquals(ptr1.glb(), ptr1.dual().glb()); - Assert.assertEquals(TypeMemPtr.BOT, ptr1.meet(ptr2nil)); - Assert.assertEquals(ptr1.glb(), ptr1.meet(TypeMemPtr.NULLPTR)); - - TypeMemPtr TOP = TypeMemPtr.TOP; - TypeMemPtr BOT = TypeMemPtr.BOT; - TypeMemPtr PTR = TypeMemPtr.VOIDPTR; - TypeMemPtr NULL = TypeMemPtr.NULLPTR; - Type PTR_meet_NULL = NULL.meet(PTR); - Assert.assertEquals(BOT, PTR_meet_NULL); - Type ptr1_meet_ptr2 = ptr1.meet(ptr2); - Assert.assertEquals(PTR, ptr1_meet_ptr2); - Type NULL_join_ptr1 = NULL.join(ptr1); - Assert.assertEquals(TOP, NULL_join_ptr1); - Type NULL_join_PTR = PTR.join(NULL); - Assert.assertEquals(TOP, NULL_join_PTR); - Type ptr1_dual = ptr1.dual(); - Type nullableptr1_dual = ptr1nil.dual(); - } - - // Test theoretical properties. - // This is a symmetric complete bounded (ranked) lattice. - // Also the meet is commutative and associative. - // The lattice has a dual (symmetric), and join is ~(~x meet ~y). - // See https://en.wikipedia.org/wiki/Lattice_(order). - @Test - public void testLatticeTheory() { - Type[] ts = Type.gather(); - - // Confirm commutative & complete - for( Type t0 : ts ) - for( Type t1 : ts ) { - check_commute (t0,t1); - check_symmetric(t0,t1); - } - - // Confirm associative - for( Type t0 : ts ) - for( Type t1 : ts ) - for( Type t2 : ts ) - assoc(t0,t1,t2); - - // Confirm symmetry. If A isa B, then A.join(C) isa B.join(C) - for( Type t0 : ts ) - for( Type t1 : ts ) - if( t0.isa(t1) ) - for( Type t2 : ts ) { - Type t02 = t0.join(t2); - Type t12 = t1.join(t2); - Type mt = t02.meet(t12); - assertSame(mt,t12); - } - } - - // By design in meet, args are already flipped to order _type, which forces - // symmetry for things with badly ordered _type fields. The question is - // still interesting for other orders. - private static void check_commute( Type t0, Type t1 ) { - if( t0==t1 ) return; - if( t0.is_simple() && !t1.is_simple() ) return; // By design, flipped the only allowed order - Type mta = t0.meet(t1); - Type mtb = t1.meet(t0); // Reverse args and try again - assertSame(mta,mtb); - } - - // A & B = MT - // Expect: ~A & ~MT == ~A - // Expect: ~B & ~MT == ~B - private static void check_symmetric( Type t0, Type t1 ) { - if( t1==t0 ) return; - Type mt = t0.meet(t1); - Type ta = mt.dual().meet(t1.dual()); - Type tb = mt.dual().meet(t0.dual()); - assertSame(ta,t1.dual()); - assertSame(tb,t0.dual()); - } - - private static void assoc( Type t0, Type t1, Type t2 ) { - Type t01 = t0 .meet(t1 ); - Type t12 = t1 .meet(t2 ); - Type t01_2 = t01.meet(t2 ); - Type t0_12 = t0 .meet(t12); - assertSame(t01_2,t0_12); - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/evaluator/Evaluator.java b/chapter10b/src/test/java/com/seaofnodes/simple/evaluator/Evaluator.java deleted file mode 100644 index ac7c5e09..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/evaluator/Evaluator.java +++ /dev/null @@ -1,210 +0,0 @@ -package com.seaofnodes.simple.evaluator; - -import com.seaofnodes.simple.Utils; -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.Field; -import com.seaofnodes.simple.type.TypeInteger; -import com.seaofnodes.simple.type.TypeMemPtr; -import com.seaofnodes.simple.type.TypeStruct; - -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.util.ArrayList; -import java.util.BitSet; -import java.util.Objects; - -public class Evaluator { - - private static final Object MEMORY = new Object(); - - public record Obj(TypeStruct struct, Object[] fields) { - @Override - public String toString() { - var sb = new StringBuilder(); - sb.append("Obj<").append(struct._name).append("> {"); - for(int i=0; i<struct._fields.length; i++) { - sb.append("\n ").append(struct._fields[i]._fname).append("=").append(fields[i]); - } - return sb.append("\n}").toString(); - } - } - - private static int getFieldIndex(TypeStruct struct, MemOpNode memop) { - int idx = struct.find(memop._name); - if( idx >= 0 ) return idx; - throw new AssertionError("Field "+memop._name+" not found in struct " + struct._name); - } - - public enum Status { - TIMEOUT, - FALLTHROUGH - } - - /** - * Find the start node from some node in the graph or null if there is no start node - */ - private static StartNode findStart(BitSet visit, Node node) { - if (node == null) return null; - if( visit.get(node._nid) ) return null; - visit.set(node._nid); - StartNode start = node instanceof StartNode ? (StartNode) node : null; - for( Node def : node._inputs ) { - var res = findStart(visit,def); - if( res != null ) start = res; - } - for( Node use : node._outputs ) { - var res = findStart(visit,use); - if( res != null ) start = res; - } - return start; - } - - private final Object[] values; - private final ArrayList<Object> phiCache = new ArrayList<>(); - private final StartNode start; - private final Scheduler.Block startBlock; - - public Evaluator(Node graph) { - var visited = new BitSet(); - this.start = findStart(visited, graph); - if (this.start == null) { - this.values = null; - this.startBlock = null; - return; - } - this.startBlock = Scheduler.schedule(this.start); - this.values = new Object[visited.length()]; - } - - private long div(DivNode div) { - long in2 = vall(div.in(2)); - return in2 == 0 ? 0 : vall(div.in(1)) / in2; - } - - private Object alloc(NewNode alloc) { - var type = ((TypeMemPtr)alloc.compute())._obj; - return new Obj(type, new Object[type._fields.length]); - } - - private Object load(LoadNode load) { - var from = (Obj)val(load.in(2)); - var idx = getFieldIndex(from.struct, load); - return from.fields[idx]; - } - - private Object store(StoreNode store) { - var to = (Obj)val(store.in(2)); - var val = val(store.in(3)); - var idx = getFieldIndex(to.struct, store); - to.fields[idx] = val; - return null; - } - - private static boolean isTrue(Object obj) { - if (obj == null) return false; - if (obj instanceof Number n) return n.longValue() != 0; - return true; - } - - private Object val(Node node) { - return values[node._nid]; - } - - private long vall(Node node) { - var v = val(node); - if (v instanceof Number n) return n.longValue(); - throw new AssertionError("Not a long " + v); - } - - private Object cons(ConstantNode cons) { - var type = cons.compute(); - if (type instanceof TypeInteger i) return i.value(); - assert type instanceof TypeMemPtr; - return null; - } - - private Object exec(Node node) { - return switch (node) { - case ConstantNode cons -> cons(cons); - case AddNode add -> vall(add.in(1)) + vall(add.in(2)); - case BoolNode.EQ eq -> Objects.equals(val(eq.in(1)), val(eq.in(2))) ? 1L : 0L; - case BoolNode.LE le -> vall(le.in(1)) <= vall(le.in(2)) ? 1L : 0L; - case BoolNode.LT lt -> vall(lt.in(1)) < vall(lt.in(2)) ? 1L : 0L; - case DivNode div -> div(div); - case MinusNode minus -> -vall(minus.in(1)); - case MulNode mul -> vall(mul.in(1)) * vall(mul.in(2)); - case NotNode not -> isTrue(val(not.in(1))) ? 0L : 1L; - case SubNode sub -> vall(sub.in(1)) - vall(sub.in(2)); - case CastNode cast -> val(cast.in(1)); - case LoadNode load -> load(load); - case StoreNode store -> store(store); - case MemMergeNode merge -> MEMORY; - case NewNode alloc -> alloc(alloc); - case ProjNode proj -> ((Object[])val(proj.ctrl()))[proj._idx]; - default -> throw new AssertionError("Unexpected node " + node); - }; - } - - /** - * Run the graph until either a return is found or the number of loop iterations are done. - */ - public Object evaluate(long parameter, int loops) { - if (start == null) return Status.TIMEOUT; - var s = new Object[start.compute()._types.length]; - s[1] = MEMORY; - s[2] = parameter; - values[start._nid] = s; - int i=0; - Scheduler.Block block = this.startBlock; - for(;;) { - for(; i<block.nodes().length;i++) values[block.nodes()[i]._nid] = exec(block.nodes()[i]); - i=0; - switch (block.exit()) { - case null: - return Status.FALLTHROUGH; - case ReturnNode ret: - return val(ret.expr()); - case IfNode ifn: - block = block.next()[isTrue(val(ifn.in(1))) ? 0 : 1]; - if (block == null) return Status.FALLTHROUGH; - break; - case RegionNode region: - if (loops-- <= 0) return Status.TIMEOUT; - int exit = block.exitId(); - assert exit > 0 && region.nIns() > exit; - block = block.next()[0]; - assert block != null; - for (; i < block.nodes().length; i++) { - if (!(block.nodes()[i] instanceof PhiNode)) break; - phiCache.add(val(block.nodes()[i].in(exit))); - } - for (i=0; i<phiCache.size(); i++) { - values[block.nodes()[i]._nid] = phiCache.get(i); - } - phiCache.clear(); - break; - default: - throw Utils.TODO("Unexpected control node " + block.exit()); - } - } - } - - public static Object evaluate(StopNode graph) { - return evaluate(graph, 0); - } - - public static Object evaluate(StopNode graph, long parameter) { - return evaluate(graph, parameter, 1000); - } - - public static Object evaluate(StopNode graph, long parameter, int loops) { - var res = evaluateWithResult(graph, parameter, loops); - if (res == Status.TIMEOUT) throw new RuntimeException("Timeout"); - return res; - } - - public static Object evaluateWithResult(StopNode graph, long parameter, int loops) { - return new Evaluator(graph).evaluate(parameter, loops); - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/evaluator/Scheduler.java b/chapter10b/src/test/java/com/seaofnodes/simple/evaluator/Scheduler.java deleted file mode 100644 index 48ac0562..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/evaluator/Scheduler.java +++ /dev/null @@ -1,599 +0,0 @@ -package com.seaofnodes.simple.evaluator; - -import com.seaofnodes.simple.Utils; -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.Type; - -import java.util.*; - -/** - * A late scheduler for test cases. - * <br> - * <br> - * This scheduler is used for tests and is not the final scheduler. - * <br> - * <br> - * The scheduler schedules not as late as possible. Since it is just for test cases this is fine. - * A better scheduler will try to place nodes outside of loops. Due to the schedule late strategy - * this scheduler might place initialization code in loops. - * <br> - * We schedule late here since memory edges have some implicit information. There can only be one - * memory edge (for a field) at a time. However, before <code>if</code> statements this might split. - * When scheduling early a store might be moved out of the loop but then there are two edges alive. - * The one through the store node and the adjacent one. This is an invalid schedule and instead of - * handling this case a late scheduler does not have this problem as memory edges are combined - * through phi nodes. - * <br> - * <br> - * A bit about this scheduler. It first discovers all alive nodes and allocates side data for them. - * Then the control flow graph is build. Then, all phis are placed and finally all the remaining nodes - * in an order where a node is placed when all alive uses are placed. Finally, the output is produced. - */ -public class Scheduler { - - /** - * A basic block with a schedule of the containing nodes. - * - * @param nodes The nodes in the final schedule of this block - * @param exit The exit node of this block. - * @param exitId In case the next block is a region this gives the entry id into the region. - * @param next The next blocks. - */ - public record Block(Node[] nodes, Node exit, int exitId, Block[] next) {} - - /** - * Definition of a block in the building process. - */ - private static class BasicBlock { - - /** - * Dominator of this block - */ - final BasicBlock dom; - /** - * Id of this block where <code>a.depth < b.depth</code> means that a is before b or - * both are in different branches. - */ - final int depth; - /** - * Previous blocks - */ - final BasicBlock[] prev; - /** - * Entry to this block - */ - final Node entry; - /** - * Schedules node in reverse order. - */ - final ArrayList<Node> reverseSchedule = new ArrayList<>(); - - /** - * Initialize the block. - * @param entry The node that started this block - * @param depth The depth of this node. All previous nodes need to have a lower value. - * @param prev The previous blocks. - */ - BasicBlock(Node entry, int depth, BasicBlock... prev) { - BasicBlock dom = null; - int max = -1; - for(var bb: prev) { - max = Math.max(max, bb.depth); - dom = dom==null?bb:dom(dom, bb); - } - assert depth > max; - this.dom = dom; - this.depth = depth; - this.entry = entry; - this.prev = prev; - } - - } - - /** - * Ancillary data for nodes used during the scheduling process. - */ - private static class NodeData { - - /** - * The node this ancillary data is used for. - */ - final Node node; - - /** - * Number of alive users not yet scheduled. - */ - int users = 1; - - /** - * Block into which the node should be placed so far. - * This will be updated with every placed use. - */ - BasicBlock block; - - /** - * Initialize ancillary data for a node - * @param node The node this ancillary data is associated with. - */ - NodeData(Node node) { - this.node = node; - } - - } - - /** - * Ancillary data for nodes. - */ - private final IdentityHashMap<Node, NodeData> data = new IdentityHashMap<>(); - /** - * List of nodes which can be placed since all users are placed. - */ - private final Stack<NodeData> scheduleQueue = new Stack<>(); - - /** - * Get the ancillary data for an alive node. - * @param node The node for which the ancillary data is requested. - * @return The ancillary data for the node. - */ - NodeData d(Node node) { - return od(node).orElseThrow(AssertionError::new); - } - - /** - * Get the ancillary data for a potentially dead node. - * @param node The node for which the ancillary data is requested. - * @return The ancillary data for the node an alive node or - * <code>Optional.empty()</code> for <code>null</code> or dead nodes. - */ - Optional<NodeData> od(Node node) { - return Optional.ofNullable(data.get(node)); - } - - /** - * Checks a node for validity - * @param data The node to check. - * @return true if all placed inputs are before this node. - */ - private boolean isValid(NodeData data) { - return data.node._inputs.stream().map(i->i==null?null:d(i)).map(d->d==null||d.users>0?null:d.block).allMatch(d->d==null||dom(d, data.block)==d); - } - - /** - * Checks that node is not XCtrl. - * @param node The node to check. - * @return true if the node is not XCtrl. - */ - private static boolean isNotXCtrl(Node node) { - return !(node instanceof ConstantNode c && c.compute() == Type.XCONTROL); - } - - /** - * Return the dominator of <code>a</code> and <code>b</code> - * @param a Block a - * @param b Block b - * @return The dominator of <code>a</code> and <code>b</code> - */ - private static BasicBlock dom(BasicBlock a, BasicBlock b) { - while (a!=b) { - if (a.depth >= b.depth) a=a.dom; - if (b.depth > a.depth) b=b.dom; - } - return a; - } - - /** - * Return if a is before b. - * @param a Block a - * @param b Block b - * @return true is a is before b. - */ - private static boolean isBefore(BasicBlock a, BasicBlock b) { - while (b.depth > a.depth) { - while (b.dom.depth > a.depth) b = b.dom; - for (int i=0; i<b.prev.length-1; i++) { - if (isBefore(a, b.prev[i])) return true; - } - b = b.prev[b.prev.length-1]; - } - return a == b; - } - - /** - * Is node placed during the control flow graph build. - * @param data Node to check. - * @return true if node is placed during the control flow graph build. - */ - private static boolean isPinnedNode(NodeData data) { - return data.node.isCFG() || data.node instanceof PhiNode; - } - - /** - * Refine placement of a node. - * @param data The node to refine. - * @param block The block before the node should be scheduled. - */ - private void refinePlacement(NodeData data, BasicBlock block) { - assert !isPinnedNode(data); - data.block = data.block == null ? block : dom(data.block, block); - assert isValid(data) : data.node.uniqueName()+" at "+data.block.entry.uniqueName(); - } - - /** - * Refine placement if before is happening before data - * @param data The node for which the placement should be refined. - * @param before The node before which the data node should be placed. - */ - private void optionalRefinePlacement(NodeData data, Node before) { - od(before).ifPresent(d->{ - // before might be in a different branch. So check this case with isBefore - // and only refine the placement if it is not in a different branch. - if (isBefore(d.block, data.block)) refinePlacement(data, d.block); - }); - } - - /** - * Schedule all nodes not yet scheduled. - */ - private void doSchedule() { - while (!scheduleQueue.isEmpty()) { - var data = scheduleQueue.pop(); - assert !isPinnedNode(data); - - assert data.block != null; - assert data.users == 0; - - if (data.node instanceof LoadNode l) { - assert isValid(data); - // Handle anti-deps of load nodes. - // At this point all anti-dep nodes are scheduled, - // but they did not refine the placement - // so do that now. - var mem = l.in(1); - for(var out : mem._outputs) { - // Aggregates describe partitions; they do not overwrite - // memory. Only users of this alias constrain the load. - if (out instanceof MemMergeNode || out instanceof ReturnNode) continue; - if (out instanceof StoreNode s && s._alias != l._alias) continue; - if (out instanceof MemPhiNode p && p._alias != l._alias) continue; - if (out instanceof BulkMemPhiNode p && p.isSplit(l._alias)) continue; - if (out instanceof PhiNode p) { - var r = p.in(0); - for (int i = 1; i < p.nIns(); i++) { - if (p.in(i) == mem) optionalRefinePlacement(data, r.in(i)); - } - } else if (!(out instanceof LoadNode)) { - optionalRefinePlacement(data, out); - } - } - } - - assert isValid(data); - data.block.reverseSchedule.add(data.node); - - for(var in:data.node._inputs) { - if (in!=null) update(d(in), data.block); - } - if (data.node instanceof StoreNode s) { - // Store nodes have anti-deps to load nodes. - // So decrease the uses of these loads when the store is placed. - for (var out: s.in(1)._outputs) { - if (out instanceof LoadNode l && l._alias==s._alias) od(out).ifPresent(this::decUsers); - } - } - } - - // Now all nodes should be placed and have a block assigned - assert this.data.values().stream().noneMatch(d->d.block==null); - } - - /** - * Decrement the not-yet-placed users of a block. - * @param data The node for which the users should be decremented. - */ - private void decUsers(NodeData data) { - assert data.users > 0; - if (--data.users == 0) { - assert data.block != null; - assert isValid(data); - - // When all users are gone this node can be scheduled. - scheduleQueue.push(data); - } - } - - /** - * Update the placement of a node - * @param data The node to update - * @param block The block before which the node should happen. - */ - private void update(NodeData data, BasicBlock block) { - assert block != null; - if (data.users == 0) { - assert isPinnedNode(data); - return; - } - refinePlacement(data, block); - decUsers(data); - } - - /** - * Checks if a CFG node is ready to be placed. This is used for regions joining branches. - * @param node The CFG node to check - * @return true if all parents of a CFG node are placed. - */ - private boolean isCFGNodeReady(Node node) { - if (node instanceof LoopNode l) { - assert d(l.in(1)).block != null; - } else if (node instanceof RegionNode r) { - for(int i=1; i<r.nIns(); i++) { - if (od(r.in(i)).map(d->d.block==null).orElse(false)) return false; - } - } else { - assert d(node.in(0)).block != null; - } - return true; - } - - /** - * Schedule all phi nodes. - * @param phiQueue List of all the phi nodes to schedule. - */ - private void schedulePhis(Stack<NodeData> phiQueue) { - while(!phiQueue.empty()) { - var data = phiQueue.pop(); - var phi = (PhiNode) data.node; - var r = phi.in(0); - data.block = d(r).block; - for(int i=1; i<phi.nIns(); i++) { - var in = phi.in(i); - od(r.in(i)).ifPresent(d->update(d(in), d.block)); - } - } - } - - /** - * Build the control flow graph. - * @param start The start node. - */ - private void doBuildCTF(StartNode start) { - var queue = new Stack<NodeData>(); - var phiQueue = new Stack<NodeData>(); - queue.push(d(start)); - int depth = 0; - while (!queue.isEmpty()) { - var data = queue.pop(); - var node = data.node; - assert node.isCFG(); - BasicBlock block; - switch (node) { - case StartNode s: - block = new BasicBlock(s, depth++); - break; - case LoopNode l: - block = new BasicBlock(l, depth++, d(l.in(1)).block); - break; - case RegionNode r: - var prev = new ArrayList<BasicBlock>(); - for(int i=1; i<r.nIns(); i++) { - od(r.in(i)).ifPresent(d->prev.add(d.block)); - } - block = new BasicBlock(r, depth++, prev.toArray(BasicBlock[]::new)); - break; - case IfNode i: - block = d(i.in(0)).block; - break; - case ReturnNode r: - block = d(r.in(0)).block; - break; - default: - block = new BasicBlock(node, depth++, d(node.in(0)).block); - } - data.block = block; - if (node instanceof RegionNode r) { - // Regions might have phis which need to be scheduled. - // Put them on a list for later scheduling. - for (var out:r._outputs) { - if (out instanceof PhiNode p) { - var d = this.data.get(p); - if (d!=null) { - d.users=0; - phiQueue.push(d); - } - } - } - } - if (!(node instanceof ReturnNode)) - for (Node n:node._outputs) if (n.isCFG() && isCFGNodeReady(n) && d(n).block == null) queue.push(d(n)); - var b = block; - for(var in:data.node._inputs) od(in).ifPresent(d->update(d, b)); - } - - // Schedule all phi nodes. - schedulePhis(phiQueue); - } - - /** - * Mark a node alive and create ancillary data for it. - * @param queue List into which this node should be placed if it needs to be visited. - * @param node Node which should be marked alive. - * @param cfg If this node is a CFG node. - */ - private void markAlive(Stack<NodeData> queue, Node node, boolean cfg) { - var nd = od(node).orElse(null); - if (nd != null) { - // Node was already visited, just increase the users. - if (nd.users>0) nd.users++; - return; - } - assert node.isCFG() == cfg; - assert isNotXCtrl(node); - nd = new NodeData(node); - if (cfg) nd.users=0; - data.put(node, nd); - queue.push(nd); - } - - /** - * Mark all alive nodes. - * First all CFG nodes are marked, then all other nodes. - * @param node THe start node. - */ - private void doMarkAlive(Node node) { - var cfgQueue = new Stack<NodeData>(); - var dataQueue = new Stack<NodeData>(); - var mem = new Stack<NodeData>(); - markAlive(cfgQueue, node, true); - // Mark all CFG nodes. - while (!cfgQueue.isEmpty()) { - var data = cfgQueue.pop(); - node = data.node; - assert node.isCFG(); - if (!(node instanceof ReturnNode)) { - for (var out : node._outputs) if (out.isCFG() && isNotXCtrl(out)) markAlive(cfgQueue, out, true); - } - for (var in : node._inputs) if(in!=null && !in.isCFG() && isNotXCtrl(in)) markAlive(dataQueue, in, false); - } - // Mark all other nodes. - while (!dataQueue.isEmpty()) { - var data = dataQueue.pop(); - node = data.node; - assert !node.isCFG(); - if (node instanceof PhiNode phi) { - var r = phi.in(0); - for (int i=1; i<phi.nIns(); i++) { - if (od(r.in(i)).isPresent()) markAlive(dataQueue, phi.in(i), false); - } - } else { - for (var in : node._inputs) if (in != null && !in.isCFG()) markAlive(dataQueue, in, false); - } - if (node instanceof StoreNode) mem.push(data); - } - // Handle store nodes and increase load with an anti-dep to the store. - while (!mem.isEmpty()) { - var data = mem.pop(); - node = data.node; - for(var out:node.in(1)._outputs) { - if (out instanceof LoadNode l && l._alias==((StoreNode)node)._alias) - od(out).ifPresent(d->d.users++); - } - } - } - - /** - * Helper function to append the nodes of a block to an array of nodes - * @param arr The array the nodes of a block should be appended to. - * @param node A potentially separator node - * @param block The block from which the nodes should be appended. - * @return The combined new array. - */ - private static Node[] appendNodes(Node[] arr, Node node, BasicBlock block) { - var idx = arr.length; - arr = Arrays.copyOf(arr, arr.length+block.reverseSchedule.size()+(node==null?0:1)); - if (node != null) arr[idx++] = node; - for(int i=block.reverseSchedule.size()-1;i>=0;i--) { - arr[idx++] = block.reverseSchedule.get(i); - } - return arr; - } - - /** - * Find the CFG output of a node - * @param node The node - * @return THe CFG output of the node. - */ - private static Node findSingleCFGOut(Node node) { - if (node instanceof StartNode) { - for(var n:node._outputs) if (n instanceof ProjNode p && p._idx==0) return p; - return null; - } - assert node._outputs.stream().filter(Node::isCFG).limit(2).count()<=1; - for(var n:node._outputs) if(n.isCFG()) return n; - return null; - } - - /** - * Build the final data structure after all the scheduling happened. - * @param start The start node - * @return The final schedule. - */ - private Block build(Node start) { - var blocks = new IdentityHashMap<Node, Block>(); - var queue = new Stack<NodeData>(); - queue.push(d(start)); - - // Visit all CFG nodes and create blocks for them. - // This can combine blocks. - while(!queue.isEmpty()) { - var data = queue.pop(); - var first = data.node; - Node prev; - var last = first; - Node[] arr = new Node[0]; - if (first instanceof RegionNode) { - var nodes = new ArrayList<Node>(); - for(var out: first._outputs) { - if (out instanceof PhiNode) { - if(od(out).isPresent()) nodes.add(out); - } - } - arr = nodes.toArray(arr); - } - arr = appendNodes(arr, null, data.block); - assert !(first instanceof IfNode); - for(;;) { - prev = last; - last = findSingleCFGOut(last); - if (last == null) break; - if (last instanceof RegionNode) { - if (blocks.get(last) == null && last != first) - queue.push(d(last)); - break; - } - if (last instanceof ReturnNode) break; - if (last instanceof IfNode if_) { - for(var out:if_._outputs) if (out.isCFG() && blocks.get(out) == null) queue.push(d(out)); - break; - } - data = d(last); - arr = appendNodes(arr, data.node, data.block); - } - blocks.put(first, switch(last) { - case null -> new Block(arr, null, -1, new Block[0]); - case IfNode i -> new Block(arr, i, -1, new Block[2]); - case RegionNode r -> new Block(arr, r, Utils.find(r._inputs, prev), new Block[1]); - case ReturnNode r -> new Block(arr, r, -1, new Block[0]); - default -> throw new AssertionError("Unexpected block exit node"); - }); - } - // Update the next pointer of all blocks. - for (var block: blocks.values()) { - switch(block.exit) { - case null: break; - case IfNode i: - for(var out:i._outputs) if (out instanceof ProjNode p) block.next[p._idx] = blocks.get(p); - break; - case RegionNode r: - block.next[0] = blocks.get(r); - break; - default: - assert block.exit instanceof ReturnNode; - } - } - // And return the block for the start node. - return blocks.get(start); - } - - /** - * Create a schedule for the program reachable from start. - * @param start The start node - * @return The final schedule. - */ - public static Scheduler.Block schedule(StartNode start) { - var scheduler = new Scheduler(); - scheduler.doMarkAlive(start); - scheduler.doBuildCTF(start); - scheduler.doSchedule(); - return scheduler.build(start); - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/Fuzzer.java b/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/Fuzzer.java deleted file mode 100644 index 7dcb88e5..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/Fuzzer.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.seaofnodes.simple.fuzzer; - -import com.seaofnodes.simple.Parser; -import com.seaofnodes.simple.evaluator.Evaluator; -import com.seaofnodes.simple.node.Node; -import com.seaofnodes.simple.node.StopNode; - -import java.util.ArrayList; -import java.util.Objects; -import java.util.Random; -import java.util.function.Consumer; - -/** - * Implementation of the fuzzer. - * Random testcases are generated using the ScriptGenerator. - * This will generate a script similar to how the parser parses it but instead of parsing it will - * randomly choose a variation the parser would parse and generate it. - * These scripts are the parsed by the parser and all exceptions are caught and filtered - * to only show one occurrence of one problem. This includes script which generate different - * results when graphs optimized with different worklist seeds are executed. - * To aid debugging scripts that cause errors are then reduced by applying rules and checking - * that the same issue persists. - */ -public class Fuzzer { - - private static final int EVAL_TIMEOUT = 1000; - - /** - * List of exceptions already encountered. - * This is used to filter new exceptions and discard them if they are already found. - */ - private final ArrayList<Throwable> exceptions = new ArrayList<>(); - - /** - * Filter and record an exception in a script. - * @param e The exception caused by the script - * @param script The script causing the exception - * @param reproducer Reproducer which should be used to reproduce the test case. - */ - private void recordException(Throwable e, String script, Consumer<String> reproducer, long seed) { - for (var ex : exceptions) { - if (FuzzerUtils.isExceptionFromSameCause(ex, e)) return; - } - exceptions.add(e); - System.out.println("========== Stack =========="); - e.printStackTrace(System.out); - System.out.println("========== Seed =========="); - System.out.println(seed); - System.out.println("========== Code ==========="); - System.out.println(script); - System.out.println("========= Reduced ========="); - System.out.println(Reducer.reduce(script, e, reproducer)); - System.out.println("==========================="); - System.out.flush(); - } - - private static boolean neq(Object a, Object b) { - if (Objects.equals(a, b)) return false; - if (a instanceof Evaluator.Obj ea && b instanceof Evaluator.Obj eb) { - if (ea.struct() != eb.struct()) return true; - for(int i=0;i<ea.fields().length;i++) { - if (neq(ea.fields()[i], eb.fields()[i])) return true; - } - return false; - } - return true; - } - - /** - * Check that two graphs result in the same output when supplied with a value - * @param e1 Evaluator for the first graph - * @param e2 Evaluator for the second graph - * @param in The input value to both graphs to test for an equal output - */ - private static void checkGraphs(Evaluator e1, Evaluator e2, long in) { - var r1 = e1.evaluate(in, EVAL_TIMEOUT); - var r2 = e2.evaluate(in, EVAL_TIMEOUT); - if (r1 == Evaluator.Status.TIMEOUT || r2 == Evaluator.Status.TIMEOUT) return; - if (neq(r1, r2)) - throw new RuntimeException("Different calculations values " + r1 + " vs " + r2); - } - - /** - * Run checks for script. Compile the script with two different optimizer worklist seeds. - * Check that exceptions raised in the parser by both methods are the same and only happens if the script may be invalid. - * If the script was successfully parsed check that both version behave the same. - * @param script The script to test - * @param valid If the script is definitely valid. If not some exceptions may be suppressed. - */ - private static void runCheck(String script, boolean valid) { - StopNode stop1; - try { - stop1 = FuzzerUtils.parse(script, 123); - } catch (RuntimeException e1) { - try { - FuzzerUtils.parse(script, 456); - } catch (RuntimeException e2) { - if (FuzzerUtils.isExceptionFromSameCause(e1, e2)) { - if (!valid || e1.getClass() == RuntimeException.class) return; - } else { - e1.addSuppressed(e2); - } - } - throw e1; - } - var stop2 = FuzzerUtils.parse(script, 456); - var e1 = new Evaluator(stop1); - var e2 = new Evaluator(stop2); - checkGraphs(e1, e2, 0); - checkGraphs(e1, e2, 1); - checkGraphs(e1, e2, 10); - } - - /** - * Check that the script does not result in exceptions. - * @param script The script to test. - * @param valid If the script is valid or if it might contain syntax errors. - */ - private void check(String script, boolean valid, long seed) { - try { - runCheck(script, valid); - } catch (Throwable e) { - recordException(e, script, s->runCheck(s, valid), seed); - } - } - - /** - * Run one test with the given seed, and check for peephole counts. - * @param seed The seed to use for generating this test case - */ - public int fuzzPeepTiming(long seed, int max_nids) { - var rand = new Random(seed); - var sb = new StringBuilder(); - new ScriptGenerator(rand, sb, true).genProgram(); - try { - var parser = new Parser(sb.toString()); - - var stop = parser.parse(); - int parse_peeps= Node.ITER_CNT; - int parse_nops = Node.ITER_NOP_CNT; - double parse_nop_ratio = (double)parse_nops/parse_peeps; - int nids = Node.UID(); - if( nids <= max_nids ) return max_nids; - - double parse_peeps_per_node = (double)parse_peeps/nids; - - stop.iterate(); - int iter_peeps= Node.ITER_CNT; - int iter_nops = Node.ITER_NOP_CNT; - double iter_nop_ratio = (double)iter_nops/iter_peeps; - double iter_peeps_per_node = (double)iter_peeps/nids; - - System.out.printf("%6d | Parsing: peeps: %5d, nops: %5d, ratio: %5.3f, last UID: %5d ps/node: %5.3f | Iter: peeps: %6d, nops: %6d, ratio: %5.3f, ps/node: %5.3f\n", - seed, - parse_peeps,parse_nops,parse_nop_ratio,nids,parse_peeps_per_node, - iter_peeps , iter_nops, iter_nop_ratio, iter_peeps_per_node); - return nids; - } catch (Throwable e) { - // ignore exceptions, let the normal fullPeeps catch and reduce, - // we're interested in valid program optimizations - } - return max_nids; - } - - - /** - * Run one test with the given seed. - * @param seed The seed to use for generating this test case - */ - public void fuzzPeeps(long seed) { - var rand = new Random(seed); - var sb = new StringBuilder(); - var valid = new ScriptGenerator(rand, sb, true).genProgram(); - check(sb.toString(), valid, seed); - } - - - /** - * Check that no exceptions happened. - * @return true if no exception happened - */ - public boolean noExceptions() { - return exceptions.isEmpty(); - } - - /** Run a fixed chapter-local seed without reducing or swallowing failures. */ - public void fuzzPeepsRegression(long seed) { - var rand = new Random(seed); - var sb = new StringBuilder(); - var valid = new ScriptGenerator(rand, sb, true).genProgram(); - try { - runCheck(sb.toString(), valid); - } catch (Throwable e) { - AssertionError ae = new AssertionError("Fuzzer regression seed failed: " + seed); - ae.initCause(e); - throw ae; - } - } -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/FuzzerUtils.java b/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/FuzzerUtils.java deleted file mode 100644 index f947a234..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/FuzzerUtils.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.seaofnodes.simple.fuzzer; - -import com.seaofnodes.simple.IterPeeps; -import com.seaofnodes.simple.Parser; -import com.seaofnodes.simple.node.Node; -import com.seaofnodes.simple.node.StopNode; - -import java.io.OutputStream; -import java.io.PrintStream; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.reflect.Field; -import java.util.BitSet; - -/** - * Some utilities for the fuzzer. - */ -class FuzzerUtils { - - /** - * Get the val of a private field - */ - @SuppressWarnings("unchecked") - public static <T> T getFieldValue(Object obj, String name) throws NoSuchFieldException, IllegalAccessException { - return (T) (obj instanceof Class<?> clz ? getField(clz, name).get(null) : getField(obj.getClass(), name).get(obj)); - } - - /** - * Get access to a private field - */ - public static Field getField(Class<?> clz, String name) throws NoSuchFieldException { - var field = clz.getDeclaredField(name); - try { - field.setAccessible(true); - } catch (Throwable e) { - // Intentionally left empty - } - return field; - } - - /** - * Try to rethrow an exception or create a runtime exception and throw it. - */ - public static RuntimeException rethrow(Throwable e) { - if (e instanceof RuntimeException re) return re; - if (e instanceof Error er) throw er; - return new RuntimeException(e); - } - - /** - * Copy of Node.WVISIST - * Used to clear as exceptions might happen in the walk and left this bitset not cleared - */ - private static final BitSet NodeWalkVisit; - private static final java.util.Random WorkRandom; - - /** - * Write access to Iterate.MID_ASSERT - * Exception could happen mid assert and left this at true. Used to reset to false prior to parsing. - */ - private static final MethodHandle set_MID_ASSERT; - - /** - * Some problems might trigger debug output. Suppress this output with a null print stream during fuzzing. - */ - public static final PrintStream NULL_PRINT_STREAM = new PrintStream(OutputStream.nullOutputStream()); - - static { - try { - NodeWalkVisit = getFieldValue(Node.class, "WVISIT"); - WorkRandom = getFieldValue(getFieldValue(IterPeeps.class, "WORK"), "_R"); - set_MID_ASSERT = MethodHandles.lookup().unreflectSetter(getField( IterPeeps.class, "MID_ASSERT")); - } catch (Exception e) { - throw new ExceptionInInitializerError(e); - } - } - - /** - * Check that the messages are similar. - */ - private static boolean similarMessages(String a, String b) { - if (a == null || b == null) return true; - a = a.replaceAll("'\\w+'", "'normalized'").replaceAll("variable \\w+", "variable normalized"); - b = b.replaceAll("'\\w+'", "'normalized'").replaceAll("variable \\w+", "variable normalized"); - return a.equals(b); - } - - /** - * Check if both stack traces have the same first entry. Empty stack traces can happen with NPE optimization - * and allow the other to be any stack trace. - */ - private static boolean sameStackTraceOrigin(StackTraceElement[] a, StackTraceElement[] b) { - if (a == null || a.length == 0 || b == null || b.length == 0) return true; // One or both stack traces are missing. - return a[0].equals(b[0]); - } - - /** - * Checks if two exceptions are caused by the same problem. - */ - public static boolean isExceptionFromSameCause(Throwable a, Throwable b) { - if (a == null || b == null) return a == b; // Handle the null case - if (a.getClass() != b.getClass()) return false; // Different classes - if (!similarMessages(a.getMessage(), b.getMessage())) return false; // Different messages. Null is allowed as wildcard - var s1 = a.getStackTrace(); - var s2 = b.getStackTrace(); - if (!sameStackTraceOrigin(s1, s2)) return false; // Different stack trace origins - if (!isExceptionFromSameCause(a.getCause(), b.getCause())) return false; // Different causes - var o1 = a.getSuppressed(); - var o2 = b.getSuppressed(); - if (o1 == null || o2 == null || o1.length != o2.length) return o1 == o2; // Different suppression - for (int i=0; i<o1.length; i++) { - if (!isExceptionFromSameCause(o1[i], o2[i])) return false; // Different suppression - } - return true; - } - - /** - * Parse and optimize using the given worklist seed - */ - public static StopNode parse(String script, long workListSeed) { - var err = System.err; - var out = System.out; - try { - System.setErr(NULL_PRINT_STREAM); - System.setOut(NULL_PRINT_STREAM); - try { - set_MID_ASSERT.invokeExact(false); - } catch (Throwable e) { - throw rethrow(e); - } - var parser = new Parser(script); - WorkRandom.setSeed(workListSeed); - var stop = parser.parse(); - return stop.iterate(); - } finally { - NodeWalkVisit.clear(); - System.setErr(err); - System.setOut(out); - } - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/Reducer.java b/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/Reducer.java deleted file mode 100644 index 3731b40c..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/Reducer.java +++ /dev/null @@ -1,176 +0,0 @@ -package com.seaofnodes.simple.fuzzer; - -import java.util.Arrays; -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * This class is used to reduce test cases created by the fuzzer. - * It applies rewrite rules to the test case and checks that the - * test still produces the same exception. - * This is done in a fixpoint iteration until every rewrite produces - * no or a different exception. - */ -public class Reducer { - - private interface Replacer extends BiConsumer<StringBuilder, Matcher> {} - - /** - * Holder for the rewrite rules - */ - private record Replace(Pattern pattern, boolean iterate, Replacer... replacements) { - Replace(Pattern p, Object... replacements) { - this(p, replacements[0] == Boolean.TRUE, Arrays.stream(replacements).filter(o->!(o instanceof Boolean)).map(Replace::from).toArray(Replacer[]::new)); - } - private static Replacer from(Object o) { - if (o instanceof Replacer r) return r; - if (o instanceof Integer i) return (s, m)->s.append(m.group(i)); - if (o instanceof String r) return (s, m)->s.append(r); - throw new IllegalArgumentException(); - } - } - - /** - * List of rewrite rules. - */ - private static final Replace[] REPLACEMENTS = { - new Replace(Pattern.compile("\\b(?:[^\\W0]|\\w\\w+)\\b"), "0", "1"), - new Replace(Pattern.compile("(?<=\\n|^)[^\\n]+(?=\\n|$)"), true, ""), - new Replace(Pattern.compile("(?<=[+\\-*/<>=(])--"), ""), - new Replace(Pattern.compile("\\b--"), "+"), - new Replace(Pattern.compile("-"), ""), - new Replace(Pattern.compile("\\b\\+-"), "-"), - new Replace(Pattern.compile("(?<![+\\-*/<>=])(?:-|\\*|/|>=|<=|>|<|!=|==)(?![+\\-*/<>=])"), "+"), - new Replace(Pattern.compile("\\{((?:[^{}]|\\{})+)(?:\\n[ \\t]*)?}"), "", "{}", 1), - new Replace(Pattern.compile("(?<=\\n|^)([ \\t]*)\\{\\n(.*?)\\n\\1}", Pattern.DOTALL), 2), - new Replace(Pattern.compile("\\(([^()]+)\\)"), 1), - new Replace(Pattern.compile("\\d+\\+"), ""), - new Replace(Pattern.compile("\\+\\d+"), ""), - new Replace(Pattern.compile("\\n\\n+"), "\n"), - new Replace(Pattern.compile("^\\n+|\\n+$"), ""), - new Replace(Pattern.compile("else *"), ""), - new Replace(Pattern.compile("\\bif\\([^()]+\\) *"), ""), - new Replace(Pattern.compile("\\bwhile\\([^()]+\\) *"), ""), - new Replace(Pattern.compile("\\bstruct \\w+ \\{[^{}]*}"), "") - }; - - /** - * Predicate to test if the reduced script generates the same error. - */ - private final Predicate<String> tester; - - /** - * Create a reducer with a test function. - * @param tester Test function which returns true when the same issue is found in the script. - */ - private Reducer(Predicate<String> tester) { - this.tester = tester; - } - - /** - * Rewrites the script with one rewrite rule. - */ - private String doReplacement(String script, Pattern pattern, Replacer[] replacements) { - var matcher = pattern.matcher(script); - var sb = new StringBuilder(); - var last = 0; - var skip = 0; - outer: - while (matcher.find(last + skip)) { - sb.append(script, last, matcher.start()); - last = matcher.end(); - skip = last == matcher.start() ? 1 : 0; - var pos = sb.length(); - for (var replacement : replacements) { - replacement.accept(sb, matcher); - var tail = sb.length(); - sb.append(script, last, script.length()); - if (tester.test(sb.toString())) { - sb.setLength(tail); - continue outer; - } - sb.setLength(pos); - } - last = matcher.start(); - skip = 1; - } - sb.append(script, last, script.length()); - return sb.toString(); - } - - /** - * Clean up variable names from the random ones generated by the fuzzer. - */ - private String cleanVariables(String script) { - var matcher = Pattern.compile("\\b([0-9a-zA-Z_]+) ([0-9a-zA-Z_]+)").matcher(script); - int[] num = {0, 0}; - while (matcher.find()) { - var type = matcher.group(1); - var var = matcher.group(2); - if (type.equals("new")) continue; - String prefix = "v"; - int t = 0; - if (type.equals("struct")) { - t = 1; - prefix = "s"; - } - if (var.matches(prefix+"\\d+")) continue; - while (script.contains(prefix+num[t])) num[t]++; - var n = script.replaceAll("\\b"+var+"\\b", prefix + num[t]); - if (tester.test(n)) { - script = n; - } - } - return script; - } - - /** - * Run all rewrite rules once. - */ - private String doAllReplacements(String script) { - for (var replace: REPLACEMENTS) { - String old; - do { - old = script; - script = doReplacement(script, replace.pattern, replace.replacements); - } while (replace.iterate && !old.equals(script)); - } - return script; - } - - /** - * Reduce the script to a minimal version which produces the same problem with a test function. - * @param tester Test function which returns true when the same issue is found in the script. - */ - public static String reduce(String script, Predicate<String> tester) { - var reducer = new Reducer(tester); - String old; - do { - old = script; - script = reducer.doAllReplacements(script); - script = reducer.cleanVariables(script); - } while (!script.equals(old)); - return script; - } - - /** - * Reduce the script to a minimal version which produces the same problem with a reproducer. - * @param ex The exception originally caused by the script - * @param reproducer Test function which throws an exception which will be checked against ex. - */ - public static String reduce(String script, Throwable ex, Consumer<String> reproducer) { - return reduce(script, s->{ - Throwable nex = null; - try { - reproducer.accept(s); - } catch (Throwable e) { - nex = e; - } - return FuzzerUtils.isExceptionFromSameCause(nex, ex); - }); - } - -} diff --git a/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/ScriptGenerator.java b/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/ScriptGenerator.java deleted file mode 100644 index 155063ab..00000000 --- a/chapter10b/src/test/java/com/seaofnodes/simple/fuzzer/ScriptGenerator.java +++ /dev/null @@ -1,792 +0,0 @@ -package com.seaofnodes.simple.fuzzer; - -import com.seaofnodes.simple.Parser; -import com.seaofnodes.simple.node.ScopeNode; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Random; -import java.util.function.Predicate; - -/** - * Generate a pseudo random script. - * This generator will generate the same script for two random number generators initialized with the same seed. - * To generate valid code it implements the parser but instead of parsing it emits the statements and expressions. - * It is guaranteed to terminate. - */ -public class ScriptGenerator { - - private static final int MAX_STATEMENTS_PER_BLOCK = 5; - private static final int MAX_BINARY_EXPRESSIONS_PER_EXPRESSION = 10; - private static final int MAX_UNARY_EXPRESSIONS_PER_EXPRESSION = 6; - private static final int MAX_NAME_LENGTH = 10; - private static final int MAX_BLOCK_DEPTH = 4; - private static final int MAX_EXPRESSION_DEPTH = 10; - - /** - * Number of spaces per indentation - */ - private static final int INDENTATION = 4; - /** - * Valid characters for identifiers. The last 10 are not valid for the first character. - */ - private static final String VAR_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789"; - /** - * List of keywords not valid for identifiers. - */ - private static final HashSet<String> KEYWORDS; - - static { - try { - KEYWORDS = FuzzerUtils.getFieldValue(new Parser(""), "KEYWORDS"); - } catch (Throwable e) { - throw new ExceptionInInitializerError(e); - } - } - - /** - * Flag for a statement that it does not pass on control flow to the next statement. - */ - private static final int FLAG_STOP = 0x01; - /** - * Flag for a statement that it contains a final if statement without an else branch. - */ - private static final int FLAG_IF_WITHOUT_ELSE = 0x02; - /** - * Binary operators. - */ - private static final String[] BINARY_OP = {"==", "!=", "<", "<=", ">", ">=", "+", "-", "*", "/"}; - /** - * Unary operators. - */ - private static final String[] UNARY_OP = {"-"}; - - private static class Type { - final String name; - Type(String name) {this.name=name;} - boolean isa(Type other) { return this == other; } - } - - private static class TypeStruct extends Type { - record Field (String name, Type type) {} - final Field[] fields; - final TypeNullable nullable = new TypeNullable(this); - TypeStruct(String name, Field[] fields) { - super(name); - this.fields = fields; - } - boolean isa(Type other) { return this == other || other == nullable; } - } - - private static class TypeNullable extends Type { - - final Type base; - - TypeNullable(Type base) { - super(base.name+"?"); - this.base = base; - } - - } - - private static final Type TYPE_INT = new Type("int"); - - - private static class Variable { - final String name; - final Type declared; - final Variable shadowing; - Type type; - boolean shadowed = false; - - Variable(String name, Type type, Variable var) { - this.name = name; - this.declared = type; - this.type = type; - this.shadowing = var; - } - } - - /** - * The random number generator used for random decisions. - */ - private final Random random; - /** - * Indentation depth. - */ - private int indentation = 0; - /** - * Output string builder - */ - private final StringBuilder sb; - /** - * Number of nested loops - */ - private int loopDepth = 0; - /** - * Current scope start in the variables list. - */ - private int currScopeStart = 0; - /** - * The depth of blocks allowed. - */ - private int depth = MAX_BLOCK_DEPTH; - /** - * The depth of expressions allowed. - */ - private int exprDepth = MAX_EXPRESSION_DEPTH; - /** - * Current variables in scope. - */ - private final ArrayList<Variable> variables = new ArrayList<>(); - /** - * All defined structs. - */ - private final ArrayList<TypeStruct> structs = new ArrayList<>(); - /** - * Allow to declare structs. - */ - private boolean allowStructs = true; - /** - * If this needs to generate valid scripts or is also allowed to generate invalid ones. - */ - private boolean generateValid; - /** - * If this script might be invalid. - */ - private boolean maybeInvalid = false; - - - /** - * - * @param random the random number generator. - * @param sb the script will be written to this string builder. - * @param generateValid if the script should be guaranteed valid or if it is allowed to contain bugs. - */ - public ScriptGenerator(Random random, StringBuilder sb, boolean generateValid) { - this.random = random; - this.sb = sb; - this.generateValid = generateValid; - } - - /** - * Random number with log distribution - * @param max The maximum value - * @return A random number in the range [0, max) with higher numbers being more uncommon. - */ - private int randLog(int max) { - max--; - int n = 1<<max; - var num = random.nextInt(n); - for (int i=max-1; i>=0; i--) { - if ((num & (1<<i))!=0) return max-i-1; - } - return max; - } - - /** - * Helper function to print indentation. - * @return sb for chaining - */ - private StringBuilder printIndentation() { - return sb.repeat(' ', indentation); - } - - /** - * Generate a random name for variables. This might be invalid when it is a keyword. - * @return The random name generated - */ - private StringBuilder getRandomName() { - int len = random.nextInt(MAX_NAME_LENGTH) + 1; - StringBuilder sb = new StringBuilder(len); - sb.append(VAR_CHARS.charAt(random.nextInt(VAR_CHARS.length()-10))); - for (int i=1; i<len; i++) - sb.append(VAR_CHARS.charAt(random.nextInt(VAR_CHARS.length()))); - return sb; - } - - /** - * Should invalid code be generated? - * @return True if invalid code should be generated - */ - private boolean generateInvalid() { - if (generateValid || random.nextInt(1000)>2) return false; - maybeInvalid = true; - return true; - } - - /** - * Lookup a variable by name - * @param name name of the variable - * @return The index of the variable in variables or -1 - */ - private int lookup(String name) { - for (int i=variables.size()-1; i>=0; i--) { - if (variables.get(i).name.equals(name)) return i; - } - return -1; - } - - /** - * Lookup a variable by name - * @param name name of the variable - * @return THe variable of null if not found - */ - private Variable lookupVar(String name) { - int idx = lookup(name); - return idx == -1 ? null : variables.get(idx); - } - - /** - * Add a variable to the current scope - * @param name The name of the variable - * @param type The declared type of the variable - */ - private void addVariable(String name, Type type) { - var old = lookupVar(name); - variables.add(new Variable(name, type, old)); - if (old != null) old.shadowed = true; - } - - /** - * Pop variables to level to - * @param to Level until which variables should be popped - */ - private void popVariables(int to) { - while (variables.size() > to) { - var v = variables.removeLast(); - if (v.shadowing != null) v.shadowing.shadowed = false; - } - } - - /** - * Get a random visible variable patching pred - * @param pred The predicate the variable needs to match - * @return A random visible variable matching pred or null if no variable mached pred. - */ - private Variable findVisibleVariablesMatching(Predicate<Variable> pred) { - int num=0; - for (var v:variables) { - if (!v.shadowed && pred.test(v)) num++; - } - if (num == 0) return null; - num = random.nextInt(num); - for (var v:variables) { - if (!v.shadowed && pred.test(v) && num-- == 0) return v; - } - throw new AssertionError(); - } - - /** - * Get a structure by name - * @param name Name of the structure - * @return The structure of null - */ - private TypeStruct getStruct(String name) { - for (var s:structs) { - if (s.name.equals(name)) return s; - } - return null; - } - - /** - * Generate a variable name. This might be new random name or a name from an outer scope. - * If the program is allowed to be invalid this can return keywords and already used variable names in the current scope. - * @return The variable name. - */ - private String getVarName() { - if (currScopeStart > 0 && random.nextInt(10) > 7) { - // Use a variable outside the current scope. - var v = variables.get(random.nextInt(currScopeStart)); - if (lookup(v.name) < currScopeStart) return v.name; - if (!generateValid) { - maybeInvalid = true; - return v.name; - } - } - // Generate a new random variable name - StringBuilder sb = getRandomName(); - var v = sb.toString(); - if (!generateValid && (KEYWORDS.contains(v) || lookup(v) >= currScopeStart)) { - maybeInvalid = true; - return v; - } - while (KEYWORDS.contains(v) || lookup(v) >= currScopeStart) { - sb.append(VAR_CHARS.charAt(random.nextInt(VAR_CHARS.length()))); - v = sb.toString(); - } - return v; - } - - /** - * Get a random structure name - * @return A random structure name - */ - private String getStructName() { - if (!structs.isEmpty() && generateInvalid()) return structs.get(random.nextInt(structs.size())).name; - // Generate a new random struct name - StringBuilder sb = getRandomName(); - var v = sb.toString(); - if (!generateValid && (KEYWORDS.contains(v) || getStruct(v) != null)) { - maybeInvalid = true; - return v; - } - while (KEYWORDS.contains(v) || getStruct(v) != null) { - sb.append(VAR_CHARS.charAt(random.nextInt(VAR_CHARS.length()))); - v = sb.toString(); - } - return v; - } - - /** - * Get a random type - * @return A random type - */ - private Type getType() { - if (structs.isEmpty() || random.nextBoolean()) return TYPE_INT; - var idx = random.nextInt(structs.size()); - TypeStruct struct = structs.get(idx); - if (random.nextBoolean()) return struct.nullable; - return struct; - } - - /** - * Generates a program and writes it into the string builder supplied in the constructor. - * @return If the program is allowed to be invalid returns if something potentially invalid was generated. - */ - public boolean genProgram() { - var oldGenerateValid = generateValid; - if (!generateValid && random.nextBoolean()) generateValid = true; - this.maybeInvalid = false; - addVariable(ScopeNode.ARG0, TYPE_INT); - currScopeStart = variables.size(); - if ((genStatements() & FLAG_STOP) == 0) { - if (generateValid || random.nextInt(10)<7) { - genReturn(); - } else { - this.maybeInvalid = true; - } - } - generateValid = oldGenerateValid; - return !this.maybeInvalid; - } - - /** - * Generate a list of statements. - * @return flags FLAG_STOP and FLAG_IF_WITHOUT_ELSE for the last statement generated - */ - public int genStatements() { - var num = random.nextInt(MAX_STATEMENTS_PER_BLOCK * (depth+1)); - for (int i=0; i<num; i++) { - printIndentation(); - var stop = genStatement(); - sb.append("\n"); - if ((stop & FLAG_STOP) != 0) return stop; - } - return 0; - } - - /** - * Generate a single statement - * @return flags FLAG_STOP and FLAG_IF_WITHOUT_ELSE for the generated statement - */ - public int genStatement() { - return switch (random.nextInt(12)) { - case 0 -> allowStructs || generateInvalid() ? genStruct() : genAssignment(); - case 1 -> genBlock(); - case 2 -> genIf(); - case 3 -> genCountedLoop(); - case 4 -> genWhile(); - case 5, 6 -> genDecl(); - case 7, 8, 9 -> genAssignment(); - case 10 -> genNullCheck(); - default -> genExit(); - }; - } - - /** - * Generate a new structure - * @return 0 - */ - public int genStruct() { - var name = getStructName(); - var fields = new TypeStruct.Field[generateInvalid() ? 0 : random.nextInt(10)]; - sb.append("struct ").append(name).append(" {\n"); - indentation += INDENTATION; - for (int i=0; i<fields.length; i++) { - var fieldName = getRandomName(); - var type = generateInvalid() ? getType() : TYPE_INT; - printIndentation().append(type.name).append(" ").append(fieldName).append(";\n"); - fields[i] = new TypeStruct.Field(fieldName.toString(), type); - } - indentation -= INDENTATION; - printIndentation().append("}"); - structs.add(new TypeStruct(name, fields)); - return 0; - } - - /** - * Generate a statement for if, else and while blocks. - * This is special since it disallows declarations and prefers to generate blocks. - * @return flags FLAG_STOP and FLAG_IF_WITHOUT_ELSE for the generated statement - */ - public int genStatementBlock() { - var oldAllowStructs = allowStructs; - allowStructs = false; - indentation += INDENTATION; - int res; - if (depth == 0) { - res = random.nextBoolean() ? genAssignment() : genExit(); - } else { - depth--; - res = switch (random.nextInt(12)) { - case 1, 2, 3, 4, 5 -> { - depth++; - indentation -= INDENTATION; - var ret = genBlock(); - indentation += INDENTATION; - depth--; - yield ret; - } - case 6 -> genIf(); - case 7 -> genCountedLoop(); - case 8 -> genWhile(); - case 9 -> genAssignment(); - case 10 -> genNullCheck(); - default -> genExit(); - }; - depth++; - } - indentation -= INDENTATION; - allowStructs = oldAllowStructs; - return res; - } - - /** - * Generate an exit. This can be return or break and continue when in a loop. - * @return FLAG_STOP - */ - public int genExit() { - if (loopDepth == 0 && generateValid) return genReturn(); - return switch (random.nextInt(7)) { - case 0,1,2 -> { - if (loopDepth == 0) maybeInvalid = true; - sb.append("continue;"); - yield FLAG_STOP; - } - case 3,4,5 -> { - if (loopDepth == 0) maybeInvalid = true; - sb.append("break;"); - yield FLAG_STOP; - } - default -> genReturn(); - }; - } - - /** - * Generate a block statement. After a certain depth only empty blocks are generated to ensure termination of the generator. - * @return flag FLAG_STOP for the generated statement - */ - public int genBlock() { - if (depth == 0) { - sb.append("{}"); - return 0; - } - var oldAllowStructs = allowStructs; - var oldCSS = currScopeStart; - allowStructs = false; - currScopeStart = variables.size(); - depth--; - sb.append("{\n"); - indentation += INDENTATION; - var stop = genStatements(); - indentation -= INDENTATION; - printIndentation().append("}"); - popVariables(currScopeStart); - depth++; - currScopeStart = oldCSS; - allowStructs = oldAllowStructs; - return stop & ~FLAG_IF_WITHOUT_ELSE; - } - - /** - * Generate an if statement with an optional else block. - * @return flags FLAG_STOP and FLAG_IF_WITHOUT_ELSE for the generated statement - */ - public int genIf() { - sb.append("if("); - genExpression(TYPE_INT); - sb.append(") "); - var stop = genStatementBlock(); - if ((stop & FLAG_IF_WITHOUT_ELSE) == 0 && random.nextInt(10) > 3) { - sb.append("\n"); - printIndentation().append("else "); - stop &= genStatementBlock(); - } else { - stop = FLAG_IF_WITHOUT_ELSE; - } - return stop; - } - - /** - * Generate a block with a null check - * if (nullable) { handle_nullable_as_non_nullable; } - */ - public int genNullCheck() { - var v = findVisibleVariablesMatching(va->va.declared instanceof TypeNullable); - if (v == null) return genIf(); - var n = (TypeNullable)v.declared; - boolean negate = random.nextBoolean(); - sb.append("if("); - if (negate) sb.append("!"); - sb.append(v.name).append(")"); - if (!negate) v.type = n.base; - var stop = genStatementBlock(); - v.type = n; - if ((stop & FLAG_IF_WITHOUT_ELSE) == 0 && random.nextInt(10) > 3) { - sb.append("\n"); - printIndentation().append("else "); - if (negate) v.type = n.base; - stop &= genStatementBlock(); - v.type = n; - } else { - stop = FLAG_IF_WITHOUT_ELSE; - } - return stop; - } - - /** - * Generate a while loop. - * @return 0 - */ - public int genWhile() { - sb.append("while("); - genExpression(TYPE_INT); - sb.append(") "); - loopDepth++; - genStatementBlock(); - loopDepth--; - return 0; - } - - /** - * Generate a counted loop of the form - * <code> - * { - * int varname = start_expr; - * while (varname < end_expr) loop_body; - * } - * </code> - * @return 0 - */ - public int genCountedLoop() { - if (depth == 0) return genWhile(); - var oldCSS = currScopeStart; - currScopeStart = variables.size(); - sb.append("{\n"); - indentation += INDENTATION; - String name = getVarName(); - printIndentation().append("int ").append(name).append("="); - genExpression(TYPE_INT); - sb.append(";\n"); - addVariable(name, TYPE_INT); - printIndentation().append("while(").append(name).append("<"); - genExpression(TYPE_INT); - sb.append(") {\n"); - indentation += INDENTATION; - depth--; - loopDepth++; - printIndentation().append(name).append("=").append(name).append("+"); - genExpression(TYPE_INT); - sb.append(";\n"); - genStatements(); - loopDepth--; - depth++; - indentation -= INDENTATION; - printIndentation().append("}\n"); - indentation -= INDENTATION; - printIndentation().append("}"); - popVariables(currScopeStart); - currScopeStart = oldCSS; - return 0; - } - - /** - * Generate a declaration statement. - * @return 0 - */ - public int genDecl() { - var type = getType(); - var name = getVarName(); - sb.append(generateInvalid() ? getRandomName() : type.name).append(" ").append(name); - if (!(type instanceof TypeNullable) || random.nextBoolean()) { - sb.append("="); - genExpression(type); - } - sb.append(";"); - addVariable(name, type); - return 0; - } - - /** - * Generate an assignment statement. - * @return 0 - */ - public int genAssignment() { - Type type; - Type declared; - if (generateInvalid()) { - sb.append(getRandomName()); - type = getType(); - declared = type; - } else { - var v = findVisibleVariablesMatching(va->true); - if (v == null) return genDecl(); - sb.append(v.name); - type = v.type; - declared = v.declared; - } - if (generateInvalid()) { - var name = getRandomName(); - sb.append(".").append(name); - declared = getType(); - } else if (type instanceof TypeStruct s && s.fields.length > 0 && random.nextBoolean()) { - var field = s.fields[random.nextInt(s.fields.length)]; - sb.append(".").append(field.name); - declared = field.type; - } - sb.append("="); - genExpression(declared); - sb.append(";"); - return 0; - } - - /** - * Generate a return statement. - * @return FLAG_STOP - */ - public int genReturn() { - var type = getType(); - sb.append("return "); - genExpression(type); - sb.append(";"); - return FLAG_STOP; - } - - /** - * Generate a binary expression. - * This method does not care about operator precedence. - */ - public void genExpression(Type type) { - if (generateInvalid()) type = getType(); - if (type != TYPE_INT) { - genUnary(type); - return; - } - var num = randLog(MAX_BINARY_EXPRESSIONS_PER_EXPRESSION); - while(num-->0) { - genUnary(TYPE_INT); - sb.append(BINARY_OP[random.nextInt(BINARY_OP.length)]); - } - genUnary(TYPE_INT); - } - - /** - * Generate a unary expression. - */ - public void genUnary(Type type) { - if (generateInvalid()) type = getType(); - if (type != TYPE_INT) { - genSuffix(type); - return; - } - var num = randLog(MAX_UNARY_EXPRESSIONS_PER_EXPRESSION); - while(num-->0) { - sb.append(UNARY_OP[random.nextInt(UNARY_OP.length)]); - } - genSuffix(TYPE_INT); - } - - /** - * Generate - */ - public void genSuffix(Type type) { - if (generateInvalid()) type = getType(); - if (type == TYPE_INT && random.nextBoolean()) { - var t = getType(); - if (generateInvalid()) { - var field = getRandomName(); - genPrimary(t); - sb.append(".").append(field); - return; - } else if (t instanceof TypeStruct s && s.fields.length > 0) { - var field = s.fields[random.nextInt(s.fields.length)]; - if (field.type == TYPE_INT) { - genPrimary(t); - sb.append(".").append(field.name); - return; - } - } - } - genPrimary(type); - } - - /** - * Generate a primary expression. - */ - public void genPrimary(Type type) { - if (generateInvalid()) type = getType(); - var rand = random.nextInt(10); - if (rand == 0 && exprDepth != 0) { - sb.append("("); - exprDepth--; - genExpression(type); - exprDepth++; - sb.append(")"); - } else if (rand < 6) { - genVariable(type); - } else { - genConst(type); - } - } - - /** - * Generate a constant. - */ - public void genConst(Type type) { - if (generateInvalid()) type = getType(); - if (type == TYPE_INT) { - var rand = random.nextInt(10); - switch (rand) { - case 0 -> sb.append("true"); - case 1 -> sb.append("false"); - default -> sb.append(random.nextInt(1<<(rand-2))); - } - } else if (type instanceof TypeNullable n) { - if (random.nextBoolean()) { - sb.append("null"); - } else { - sb.append("new ").append(generateInvalid() ? getRandomName() : n.base.name); - } - } else { - sb.append("new ").append(generateInvalid() ? getRandomName() : type.name); - } - } - - /** - * Generate a variable. If there are none generate a number instead. - * If the program is allowed to be invalid a random name can be generated in some cases. - */ - public void genVariable(Type type) { - if (generateInvalid()) { - sb.append(getRandomName()); - return; - } - if (generateInvalid()) type = getType(); - var t = type; - var v = findVisibleVariablesMatching(va->va.type.isa(t)); - if (v == null) genConst(type); - else sb.append(v.name); - } - -} |
