diff options
53 files changed, 1179 insertions, 6094 deletions
diff --git a/chapter33/README.ja.md b/chapter33/README.ja.md index 6d1d8c4e..d6ebae8f 100644 --- a/chapter33/README.ja.md +++ b/chapter33/README.ja.md @@ -4,8 +4,10 @@ [前の章:第32章 — コンパイラ内部の高速化](../chapter32/README.ja.md) -この章では自動メモリ管理を検討します。設計は未定で、実装はまだ始めていません。 -完成した第32章のコンパイラから始まります。 +この章では Allocation2 による割り当てサイト単位の points-to 解析を実装しています。 +分離コンパイルへの対応は未完成で、所有権の証明、配置の選択、メモリの再利用は今後の課題です。 +現在の設計と参考文献は[メモリ管理の設計](docs/memory-management.md)、 +可変長配列の構築スコープは[配列の設計](docs/growing-arrays.md)を参照してください(英語)。 コンパイラ、ライブラリ、実行例、テストを含む、独立して実行できるスナップショットです。 高速化の説明と測定結果は[第32章](../chapter32/README.md)にあります。 diff --git a/chapter33/README.md b/chapter33/README.md index b9490d32..5f5b95bc 100644 --- a/chapter33/README.md +++ b/chapter33/README.md @@ -4,340 +4,48 @@ English | [日本語](README.ja.md) [Previous: Chapter 32 — Compiler Internal Speedups](../chapter32/README.md) -This chapter starts automatic memory management with an allocation-lifetime -analysis. It runs after Opto, field-layout finalization, and LoopTree, before TypeCheck. -It reports where storage must live; allocation and machine code still use the -existing runtime. The [design survey](../docs/automatic-memory-management-survey.md) -records the language decisions. Chapter 32's -[speedup measurements](../chapter32/README.md) remain there. +Allocation2 is the only memory-analysis phase. It runs after Opto, field-layout +finalization, and LoopTree, before TypeCheck. It computes allocation-site +points-to sets, reference-field relationships, escapes, and incoming field counts. +Separate-compilation constraints are incomplete. The pass does not yet prove +ownership, choose frame lifetimes, lower a storage policy, or implement recycling. -The [existing-program survey](docs/allocation-survey.md) records what this first -analysis accepts and rejects across `sys` and the games, with small reductions -that separate analysis limitations from storage decisions. -The [growing-array survey](docs/growing-arrays-survey.md) identifies builders that -can finish in one scope, persistent collections, and library API changes needed -for grow-in-place storage. +The [memory-management design](docs/memory-management.md) explains the abstraction, +its precision limits, ownership and lifetime proofs, storage choices, deletion +semantics, and academic references. The [growing-array design](docs/growing-arrays.md) +specifies future construction scopes and illustrates their storage requirements. -## First allocation plans +## Current implementation -Four small examples in [Chapter33Test](src/test/java/com/seaofnodes/simple/Chapter33Test.java) -exercise the first cut: +Each NewNode or static object has a Site. Pointer values and reference fields +have Points containing sets of Sites and an outside-storage flag. Fields use +weak updates; array indices share one field. Registered dependencies requeue +consumers when facts grow. Nullability stays in the type analysis. -| Example | Allocation destination | -|---|---| -| Make a temporary and pass it to a reader | Current function frame | -| Return a Box containing a Thing through two factories | Caller-supplied result storage for both objects | -| Assign a newly allocated Thing to an argument's field | Storage that lives long enough for that argument | -| Call one factory twice and store into different arguments | Separate destinations for the two calls | +Object metadata retains signatures, optimized return states, function names/sizes, +and class-initialization dependencies. It has no independent function-effect or +allocation-contract pass. Bodies remain unloaded until needed. Serialized IR +format is 10 (`C0DA`); older objects must be rebuilt. -The analysis walks the call DAG once. It discovers callees on entry and builds -each function's summary on exit. Within a body it follows control, memory, and -references, skipping arithmetic and offset expressions. Control anchors expose -allocations even when only scalar uses remain; reference uses expose raw-address -conversions without walking the arithmetic that consumes them. Sorting is confined -to the debug dump. Parameters name symbolic storage owners; -returning or storing a fresh reference adds destination requirements. Composing -a call substitutes its actual arguments and keeps its fresh allocations distinct -from other calls to the same factory. Private callee scratch stays in the -callee's summary. +The earlier allocation planner and deletion checker are removed, including +their flags and adapters. Their source remains available in Git history. +Array deletion syntax remains, but ownership proofs and runtime recycling are +unfinished; deletion must not be treated as an implemented no-op. -Within one summary, loads, stores, and call effects converge before a worklist -propagates destination requirements. For example, returning a Box retains its -Thing too. This local closure does not repeat the call-graph traversal. Stores -are conservative weak updates: overwriting a field does not yet release the -earlier value's lifetime constraint. Array elements share one field, regardless -of index. +## Building and inspecting -Pointer-valued loads keep the child's origin separate from the holder: - -```text -get(h) { return h.c; } // returns borrowed origin arg3.c -fill(h) { h.c.d = new Thing; } // new Thing must outlive arg3.c -``` - -At a call, `arg3.c` resolves to the actual holder's possible field values. A -function can build a temporary holder and return its child; only the child -needs result storage. Copying a child between holders likewise retains the -child without retaining its source holder. Call substitution also handles two -arguments referring to the same object. - -The ASCII dump shows function summaries in call-graph reverse postorder (RPO): -callers before callees, starting from the program entry. Other retained functions -(such as constructor bodies whose calls were inlined) follow in a separate RPO -section. Reachability here follows direct calls in the optimized graph. Nested -loop frames stay under their parent, with siblings ordered by node ID. Analysis -still builds summaries in postorder. - -```text -+-- forward_noInline -| call#219 -> make_noInline -| [result] call#219/new#352:Test.Thing (8 bytes) -| [result] call#219/new#381:Test.Box (8 bytes) -| .child --> call#219/new#352:Test.Thing -`-- return -> {call#219/new#381:Test.Box} - -+-- make_noInline -| [result] new#352:Test.Thing (8 bytes) -| [result] new#381:Test.Box (8 bytes) -| .child --> new#352:Test.Thing -`-- return -> {new#381:Test.Box} -``` - -`frame` means scratch for that function; `result` means the caller's result -destination; `static` means program lifetime. `arg3` names storage associated -with argument input 3 (ordinary class functions use input 2 for their hidden -receiver). `arg3.c` names the storage referenced by that argument's `c` field, -not storage inside the holder. `arg3 & arg4` requires a destination satisfying both owners; it does -not arbitrarily pick one. Node numbers help correlate this output with the IR. -These are ownership constraints, not assigned physical stack offsets. -Return origins are a set of alternatives: `{arg3:a | arg4:b}` means the returned -reference may point to either argument. `{}` means no tracked storage is returned. - -Run a poster child and print its plan: - -```sh -make -j8 test CLASS=Chapter33Test METHOD=testAllocationFactoryGraph "TEST_JAVA_OPTS=-XX:ActiveProcessorCount=2 -Dsimple.alloc.dump=true" -``` - -## Iteration storage and winners - -Functions and loop iterations use the same `Summary` and cleanup rule. Each -summary has incoming values, normal exit values, retention effects, and scratch -storage. A loop also has continuation values: its backedge returns these as -arguments to the next iteration. Both loop exits clean up the iteration frame. -The backedge's conceptual pop/push can reuse the same fixed storage without code. - -A loop can have both a surviving result and unrelated scratch. One reference-flow -calculation finds both; placement follows the summary interfaces. For example, -`testAllocationLoopWinnerAndScratch` constructs a Scratch and a candidate Thing -each iteration, tests the candidate, and breaks with the winner: - -```text -| +-- loop#221 frame; parent find_noInline -| | continue refs -> {} -| | return refs -> {call#276/new#424:Test.Thing} -| | [loop#221 iteration] new#484:Test.Scratch (8 bytes) -| `-- cleanup on continue and return -> {new#484:Test.Scratch} -| [result] call#276/new#424:Test.Thing (8 bytes); loop#221 winner -`-- return -> {call#276/new#424:Test.Thing} -``` - -The Thing has fixed result space reserved before entering the loop. Failed -candidates may reuse it because no earlier candidate remains reachable on the -backedge. Scratch belongs to the iteration and can be reclaimed each turn. -Storage prints inside its owning frame, including an inner loop's winner when -the outer iteration owns it. Iteration storage and function `[frame]` storage -are the same logical scratch-storage choice, with different cleanup boundaries. -A winner's referenced objects survive with it. An inner loop's winner can still -belong to the outer loop's iteration storage. Storage exported by a frame is -promoted through enclosing frames until one can own it. Calls substitute -arguments and fresh sites; nested loops already share their function's SSA -vocabulary, so their composition preserves site identities. Private callee -scratch stays in the callee. - -The abbreviated dump above omits the value ports. The full dump names entry, -continuation, and exit values, including scalar and memory values. A scalar -loaded from scratch can cross an exit without retaining the scratch object. -Returning from nested loops exports through each intervening summary; each -frame retains its own cleanup set. These logical storage frames are separate -from machine return-address and spill slots. - -The continuation summary follows reference Phis and memory reaching each backedge, -including helper-call retention. Borrowed references can continue to the next -iteration. Keeping an earlier candidate in a variable, linking -candidates together, or storing them into a pre-existing array rejects the plan. -Publishing through an argument's field only on an exit arm is allowed. For now, -even bounded retention and overwritten memory slots reject: weak updates do not -prove that the old reference died. Collection destinations and more precise -memory liveness remain future work. Floating scalar uses may finish before an -iteration reset; uses constrained outside the loop retain their referenced storage. - -These are still plans: no stack reservations, slot reuse, or reclamation are -emitted yet. Allocation uses each CFG node's tightest containing LoopTree and -the tree's parent links. Simple produces reducible control flow; that is an -asserted invariant, not an allocation rejection. The early LoopTree walk leaves -the IR unchanged. Before scheduling, the tree is rebuilt to account for Lower's -CFG changes, and loops with zero exits receive one synthetic exit. Delaying those -exits preserves nonreturning-function summaries during type checking and serialization. - -That ordering is temporary. Before this chapter closes, the original LoopTree -build must insert NeverExits, Allocation's zero-exit support must be removed, -and Lower must maintain the tree with local edits instead of a full rebuild. -The [roadmap](../docs/roadmap.md#phase-ordering-and-incremental-analysis) tracks -this deferred work, including preserving nonreturning-function semantics. - -Native calls borrow their arguments until the call returns: they must not retain, -hide, or publish those references. Converting an array pointer to an integer now -adds a `KeepAlive(control, value)` at the converting scope's exits. Allocation -traces that value through arithmetic and Phis to its storage. The integer can -travel through memory and Simple wrappers without losing the original endpoint. -The native ABI and pointer representation are unchanged. - -The marker keeps every conversion, including earlier values of reassigned locals. -Returns, breaks, and continues end the scopes they leave; unbraced if/else arms -and loop bodies also have their own borrowing scopes. Conditional expressions -share their enclosing scope. Returning or storing the integer does not extend -that scope: using the address afterwards can access reclaimed storage. - -Markers survive serialization and inlining, then disappear before scheduling; -they require no registers or machine instructions. Zero/null, duplicate adjacent -markers, and unused address expressions fold away. Placement still chooses whole -function/iteration frames, so a lexical endpoint can conservatively retain storage -in a larger frame. Actual stack lowering is still pending. Serialized IR is now -format 4, retaining these endpoints and the deletable-array capability; -older objects must be rebuilt. - -Native results that are Simple pointers also need an explicit origin/allocation -contract; they are not assumed to be borrowed or freshly allocated. - -The first cut also rejects plans for recursive calls, unknown Simple targets, -variable-size stack allocations, and reference origins that it cannot trace. -Weak updates can also invent endlessly longer field paths in -code such as `p.next = p.next.next`; the pass rejects these plans when paths -exceed the body's reads plus the path depths supplied by its callees. Tracking -memory order is future work. A rejected function is printed as `REJECT`, never -as a usable partial plan. Scalar field reads and writes do not themselves -introduce retained references. - -Normal compilation records those rejections and continues with the existing -allocator. `-Dsimple.alloc.check=true` rejects compilation if any function lacks -a supported plan; tests can also require an individual summary to be supported. -The pass does not yet insert hidden destination arguments, stack reservations, -or reclamation. The proposed inline-object and growing-array syntax is not -implemented by this analysis experiment. - -[Allocation.java](src/main/java/com/seaofnodes/simple/codegen/Allocation.java) -contains the walk, one summary class, and one storage-site class. Comments mark -the next work: collection and SCC destinations, memory-ordered field updates, bin packing, -free lists, and parallel growth areas. Allocation contracts are saved beside -function types and effects. They describe argument/field origins, returned and -retained references, and fresh storage sizes and destinations. Imports compose -these contracts without loading implementation bodies. Local scratch and loop -frames stay private to the implementation; rejected plans retain their rejection. - -## Array deletion: first ownership checks - -Explicit array recycling needs stronger guarantees than class-slot recycling: -after `old.del()`, no usable reference to the old array may remain. The source -spelling is `E[^]`, allocated with `new E[^N]` or `new E[^]{...}`. This keeps the -modifier beside the existing array read-only notation `E[~]`, separate from -constructor-parameter `^`. The spelling remains provisional. - -[ArrayDelete.java](src/main/java/com/seaofnodes/simple/codegen/ArrayDelete.java) -checks the intrinsic at its control/memory boundary. `.del()` resolves as an array -member load followed by an ordinary call, including when the receiver's type -becomes known later. Other classes can still define their own `del` methods. -The intended resize pattern is: - -```text -val old = self.buf; -val next = new ...; -copy(next, old, len); -self.buf = next; -old.del(); -``` - -The checker follows memory edges to distinguish an earlier reference from one -that still occupies a field. A definite overwrite kills that field's old value; -branches must kill it on every path. SSA aliases and Phis are followed to their -uses. Borrowing helpers may read references and copy scalar elements, but this -contract excludes pointer-field writes and raw addresses. Returned references -can forward arguments when the allocation contract identifies their origins; -those aliases are checked for surviving uses too. - -The new cases at the end of Chapter33Test cover local buffers, container resize, -and a small hash-table rehash. Saved aliases, retaining fields/helpers, and -one-sided overwrites reject. Copying an object reference out of an array does -not keep the array alive. Incoming buffers report `requires unique entry`: -this becomes a consuming requirement in the function's contract. For example, -`may consume entry(arg2.buf)` requires exclusive access to the buffer held there -on entry. Each caller substitutes its actual owner and incoming memory, then -checks for surviving aliases. A fresh wrapper can satisfy the requirement; -a saved buffer reference used after the call rejects. Sharing the wrapper and -reloading its current field are allowed. Forwarders propagate unmet incoming -requirements, including nested paths, and object files preserve them. - -Calls compose in memory order. A grow's summary can require unique `v.buf` on -entry and guarantee unique `v.buf` on return. The next grow uses that outgoing -version. Other helper stores remain may-stores until a definite overwrite kills -them. Initializers and returned references use this same substitution, including -imported summaries. `testArrayConsumeTwoGrows` is the straight-line debugger case. -A separate input-array parameter can be borrowed while growing; the caller must -prove it is not the buffer being consumed. Passing `v.buf` as that input rejects. - -Repeated grows can pass: a loop backedge carries the wrapper's current buffer, -not a saved copy of its old buffer. The checker stops at that boundary, checks -carried references, and verifies that the callee leaves its field uniquely owned. -Saved locals or fields crossing the backedge reject, including aliases of the -replacement. Breaks and zero-iteration exits keep their separate memory paths. -Loop-entry versions distinguish last iteration's buffer from this iteration's -call results, allowing several grows per iteration. -`testArrayConsumeGrowLoop` is the small debugger example; the imported forwarder -test exercises the same rule using serialized contracts. - -Every surviving source `.del()` now requires a proof during TypeCheck. A `[^]` -type supplies deletion capability, not an unchecked uniqueness promise. -Allocation plans mark these arrays `[buddy]`, accepting dynamic sizes and -keeping their blocks out of function/iteration stack cleanup. Reference-lifetime -tracking and deletion proofs still apply; runtime buddy allocation comes later. -Ordinary array parameters can borrow these arrays; assigning an ordinary -allocation to a `[^]` declaration is rejected. The original checkpoint query, -`Allocation.checkArrayDelete(call,arg)`, remains available for focused tests. -Unresolved reference cycles, array-element ownership slots, raw-address borrows, -and unknown call or class initialization effects reject. Recursive consuming -groups and consuming callbacks without ownership contracts also reject. Recursive -group heads need the same boundary proof once their allocation graphs are built. -General callee may-stores cannot yet prove an alias was definitely cleared, and -loop-carried replacement aliases remain conservative. Buddy allocation and -automatic recycling on overwrite come later. - -Runtime recycling is not implemented. Compile-only checks and object emission -work; generated objects reference `simple_array_delete`, which has no runtime -definition yet. Eval2 reports an explicit unsupported-operation error if that -call executes. It is never silently erased or treated as a successful deletion. - -The [source migration survey](docs/array-delete-survey.md) tries the five production -resize implementations. Migrated `aryi64`, `bitset`, and `Canvas` pass TypeCheck. -The `aryu8` grow/add/append paths, string and integer formatting, and `aryi64.str` -pass their ownership checks; the full migration still rejects native boundaries -in file input, floating formatting, and calendar formatting. Timers reaches the -recursive-consuming-call restriction. Serialized IR format 8 marks effects -outside the field graph, so imported raw/native helpers cannot silently acquire -a no-retention guarantee. - -Imported function summaries now distinguish effects introduced by the function -from memory supplied by its caller: written aliases, possible reference writes, -and escaping identities. Effects propagate through callees, including recursion -and paths that never return. This lets the checker recognize that initializing -`sys.integer` cannot retain an array. It also prevents one imported function from -making unrelated library functions reachable. Library metadata is still loaded -eagerly; unused functions disappear from the optimized graph and allocation dump. -The serialized IR format is now 7; older object files must be rebuilt. - -## Build and use this chapter - -From `chapter33`: +Run from `chapter33`: ```sh make -j8 release -make -j8 sanity -make -j8 tests +make -j8 test CLASS=Chapter33Test +make -j8 test CLASS=Chapter33Test METHOD=testAllocation2SharedFactory "TEST_JAVA_OPTS=-XX:ActiveProcessorCount=2 -Dsimple.alloc2.dump=true" +make -j8 tests_nographics ``` -`sanity` keeps the full lattice checks and focused compiler regressions. -Run the full suite before finishing a change. For a fully headless full run, -use `make -j8 tests_nographics` to disable MiniFB and miniaudio. - -Run one test class, or enable every-step verification for an investigation: - -```sh -make test CLASS=TypeTest -make test CLASS=WorklistTest "TEST_JAVA_OPTS=-XX:ActiveProcessorCount=2 -Dsimple.assert.expensive=1" -``` +`verify()` checks fixed-point stability when requested by tests or assertions. +It does not establish complete boundary handling or ownership. The current tests +include unresolved separate-compilation, escape, and construction cases. -The [grammar and parser map](docs/33-grammar.md) describes this snapshot. -The [examples](docs/examples/README.md) include launch commands for the games. -Library references live with [drawing](src/main/smp/sys/draw/README.md), -[window/input](src/main/smp/sys/gfx.md), [audio](src/main/smp/sys/audio.md), and -[time](src/main/smp/sys/time/README.md). Future projects are in the -[roadmap](../docs/roadmap.md). +See also the [grammar](docs/33-grammar.md), [examples](docs/examples/README.md), +and [roadmap](../docs/roadmap.md). diff --git a/chapter33/docs/AllocationSurvey.java b/chapter33/docs/AllocationSurvey.java deleted file mode 100644 index 108cbfb3..00000000 --- a/chapter33/docs/AllocationSurvey.java +++ /dev/null @@ -1,138 +0,0 @@ -import com.seaofnodes.simple.codegen.*; -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.*; -import com.seaofnodes.simple.util.Ary; -import java.nio.file.*; -import java.lang.reflect.Field; -import java.util.*; - -// Standalone survey, not a test or a compiler option. Run from chapter33. -public class AllocationSurvey { - static Object field(Object object, String name) throws Exception { - Field f=object.getClass().getDeclaredField(name); - f.setAccessible(true); - return f.get(object); - } - static String clean(Object s) { return s==null ? "" : s.toString().replace('\t',' ').replace('\n',' '); } - static String category(String reason) { - if( reason==null ) return "supported"; - if( reason.contains("opaque body") ) return "opaque body"; - if( reason.contains("opaque or indirect") ) return "indirect call"; - if( reason.contains("recursive call") ) return "recursion"; - if( reason.contains("raw address") ) return "raw address"; - if( reason.contains("variable-size") ) return "variable size"; - if( reason.contains("across its backedge") ) return "loop retention"; - if( reason.contains("cyclic field-path") ) return "field paths"; - if( reason.contains("reference origin") ) return "reference origin"; - if( reason.contains("native result storage") ) return "native result"; - return "other"; - } - static String probe(String name) { - return switch(name) { - case "LocalArray" -> """ - val work_noInline={ u32 n -> - val xs=new i64[n]; - for( u32 i=0; i<n; i++ ) xs[i]=i; - return n ? xs[n-1] : 0; - }; - u32 len=arg; - return work_noInline(len); - """; - case "ReturnedArray" -> """ - val make_noInline={ u32 n -> new i64[n]; }; - u32 len=arg; - return make_noInline(len)#; - """; - case "OverwrittenSlot" -> """ - struct Thing { i64 !x; new Thing={i64 n -> x=n;}; }; - struct Holder { Thing? !c=null; }; - val work_noInline={i64 n -> - val h=new Holder; - while(n>0) { h.c=new Thing(n); n--; } - return h.c ? h.c.x : 0; - }; - return work_noInline(arg); - """; - case "ReusedObject" -> """ - struct Thing { i64 !x; new Thing={i64 n -> x=n;}; }; - val read_noInline={Thing t -> t.x;}; - val work_noInline={i64 n -> - val t=new Thing(0); - i64 sum=0; - while(n>0) { t.x=n; sum+=read_noInline(t); n--; } - return sum; - }; - return work_noInline(arg); - """; - default -> throw new IllegalArgumentException(name); - }; - } - @SuppressWarnings("unchecked") - public static void main(String[] args) throws Exception { - String name=args[0], mode=args.length>1 ? args[1] : "source"; - Path out=Path.of("build/allocation-survey",name+"-"+mode); - Files.createDirectories(out); - for( String file : new String[]{"error.txt","dump.txt","functions.tsv","sites.tsv","allocations.tsv","calls.tsv"} ) - Files.deleteIfExists(out.resolve(file)); - String src=mode.equals("probe") ? probe(name) : name.equals("sys") ? null : - name.equals("RuntimeArgs") ? Files.readString(Path.of("src/main/smp/sys/rt/simple_args.smp")) : - Files.readString(Path.of("docs/examples",name+".smp")); - if( src!=null && !name.equals("RuntimeArgs") && mode.equals("source") ) src="val _survey_sys=sys;\n"+src; - String root=mode.equals("source") ? "src/main/smp" : "docs/examples"; - Ary<String> libs=mode.equals("object") ? new Ary<>(new String[]{"build/release/x86_64_v2_win64"}) : null; - CodeGen code=new CodeGen(root,out.resolve("objects").toString(),libs,name,src,456,true,TypeInteger.BOT); - long start=System.nanoTime(); - try { code.driver(CodeGen.Phase.TypeCheck); } - catch(Throwable t) { - StringBuilder error=new StringBuilder(t.toString()+"\nphase="+code._phase+"\n"); - if( t instanceof com.seaofnodes.simple.parser.Parser.ParseException p ) error.append(p.diagnostic()).append('\n'); - for( StackTraceElement frame : t.getStackTrace() ) error.append(frame).append('\n'); - Files.writeString(out.resolve("error.txt"),error); - System.out.println(name+" "+mode+" ERROR "+t); - return; - } - Allocation.Summary[] summaries=(Allocation.Summary[])field(code._allocation,"_summaries"); - Files.writeString(out.resolve("dump.txt"),code._allocation.toString()); - StringBuilder rows=new StringBuilder("program\tmode\tunit\tfunction\tid\tstatus\tcategory\troot_function\troot_id\troot_unit\tnew_user\tnew_class\tvariable\tplaced_user\tplaced_class\tloops\treason\n"); - StringBuilder sites=new StringBuilder("program\tmode\tunit\tfunction\tsite\ttype\tbytes\tdestination\n"); - StringBuilder nodes=new StringBuilder("program\tmode\tunit\tfunction\tnode\tsize\ttype\n"); - StringBuilder calls=new StringBuilder("program\tmode\tunit\tfunction\tnode\ttarget\tsignature\n"); - int total=0,pass=0,allocated=0; - for( Allocation.Summary sum : summaries ) { - if( sum==null ) continue; - FunNode fun=sum._fun; - String unit=fun._compunit==null ? "" : fun._compunit._cname; - Allocation.Summary cause=sum; - HashSet<Allocation.Summary> seen=new HashSet<>(); - while( cause._reject!=null && cause._reject.startsWith("call #") && seen.add(cause) ) { - int id=Integer.parseInt(cause._reject.substring(6,cause._reject.indexOf(' ',6))); - Allocation.Summary next=null; - for( CallNode call : (ArrayList<CallNode>)field(cause,"_calls") ) - if( call._nid==id && call.fptr()._type instanceof TypeFunPtr fp && fp.isConstant() ) next=summaries[fp.fidx()]; - if( next==null ) break; - cause=next; - } - int local=0,clz=0,variable=0,placed=0,placedClz=0; - for( CallNode call : (ArrayList<CallNode>)field(sum,"_calls") ) - calls.append(name).append('\t').append(mode).append('\t').append(clean(unit)).append('\t').append(clean(fun._name)).append('\t').append(call._nid).append('\t').append(clean(call.name())).append('\t').append(clean(call.fptr()._type)).append('\n'); - for( Node n : (ArrayList<Node>)field(sum,"_nodes") ) if( n instanceof NewNode a ) { - if( TypeStruct.startsClzPrefix(a._ts._name) ) clz++; else local++; - if( !(a.size()._type instanceof TypeInteger sz) || !sz.isConstant() ) variable++; - nodes.append(name).append('\t').append(mode).append('\t').append(clean(unit)).append('\t').append(clean(fun._name)).append('\t').append(a._nid).append('\t').append(clean(a.size()._type)).append('\t').append(clean(a._ts._name)).append('\n'); - } - if( sum.supported() ) for( Allocation.Site site : sum._sites ) if( site._allocation!=null ) { - if( TypeStruct.startsClzPrefix(site._allocation._ts._name) ) placedClz++; else placed++; - sites.append(name).append('\t').append(mode).append('\t').append(clean(unit)).append('\t').append(clean(fun._name)).append('\t').append(clean(site._name)).append('\t').append(clean(site._allocation._ts._name)).append('\t').append(site._bytes).append('\t').append(clean(site.destination())).append('\n'); - } - String status=sum.supported() ? "pass" : sum._reject.startsWith("call #") ? "blocked" : "direct"; - rows.append(name).append('\t').append(mode).append('\t').append(clean(unit)).append('\t').append(clean(fun._name)).append('\t').append(fun.sig().fidx()).append('\t').append(status).append('\t').append(category(cause._reject)).append('\t').append(clean(cause._fun._name)).append('\t').append(cause._fun.sig().fidx()).append('\t').append(clean(cause._fun._compunit==null ? null : cause._fun._compunit._cname)).append('\t').append(local).append('\t').append(clz).append('\t').append(variable).append('\t').append(placed).append('\t').append(placedClz).append('\t').append(((IdentityHashMap<?,?>)field(sum,"_loops")).size()).append('\t').append(clean(sum._reject)).append('\n'); - total++; - if( sum.supported() ) { pass++; if( placed>0 ) allocated++; } - } - Files.writeString(out.resolve("functions.tsv"),rows); - Files.writeString(out.resolve("sites.tsv"),sites); - Files.writeString(out.resolve("allocations.tsv"),nodes); - Files.writeString(out.resolve("calls.tsv"),calls); - System.out.println(name+" "+mode+": "+pass+"/"+total+" pass, "+allocated+" with user allocations; "+((System.nanoTime()-start)/1000000)+" ms"); - } -} diff --git a/chapter33/docs/ArrayDeleteSurvey.java b/chapter33/docs/ArrayDeleteSurvey.java deleted file mode 100644 index 7e549048..00000000 --- a/chapter33/docs/ArrayDeleteSurvey.java +++ /dev/null @@ -1,107 +0,0 @@ -import com.seaofnodes.simple.codegen.*; -import com.seaofnodes.simple.parser.Parser; -import com.seaofnodes.simple.type.TypeInteger; -import com.seaofnodes.simple.util.SB; -import java.nio.file.*; -import java.util.ArrayDeque; - -/** Compile-only source migrations. Originals are never changed. Run from chapter33. */ -public class ArrayDeleteSurvey { - private static String change(String src, String from, String to) { - if( !src.contains(from) ) throw new IllegalArgumentException("Survey source changed: "+from); - return src.replace(from,to); - } - - private static String migrate(String name, String src) { - switch(name) { - case "aryu8": - src=change(src,"u8[] !buf;","u8[^] !buf;"); - src=change(src,"new u8[1]","new u8[^1]"); - src=change(src,"u8[] !buf2 = new u8[newlen];","val old = buf;\n u8[^] !buf2 = new u8[^newlen];"); - return change(src,"buf = buf2;","buf = buf2;\n old.del();"); - case "aryi64": - src=change(src,"i64[] !buf;","i64[^] !buf;"); - src=change(src,"i64[] b ->","i64[^] b ->"); - src=change(src,"new i64[","new i64[^"); - src=change(src,"i64[] !buf2 =","val old = buf;\n i64[^] !buf2 ="); - return change(src,"buf = buf2;","buf = buf2;\n old.del();"); - case "bitset": - src=change(src,"i64[] !_bits;","i64[^] !_bits;"); - src=change(src,"new i64[","new i64[^"); - src=change(src,"var bits =","val old = _bits;\n var bits ="); - return change(src,"_bits = bits;","_bits = bits;\n old.del();"); - case "Timers": - src=change(src,"u32[]","u32[^]"); - src=change(src,"i64[]","i64[^]"); - src=change(src,"new u32[","new u32[^"); - src=change(src,"new i64[","new i64[^"); - src=change(src,"val ids =","val oldIds = _ids, oldDue = _due_ms, oldPeriod = _period_ms;\n val ids ="); - return change(src,"_period_ms = periods_ms;","_period_ms = periods_ms;\n oldIds.del(); oldDue.del(); oldPeriod.del();"); - case "Canvas": - src=change(src,"u32[] !pixels;","u32[^] !pixels;"); - src=change(src,"new u32[","new u32[^"); - return change(src,"pixels = new u32[^capacity];", - "val old = pixels;\n pixels = new u32[^capacity];\n old.del();"); - default: throw new IllegalArgumentException(name); - } - } - - private static void copyTree(Path src, Path dst) throws Exception { - ArrayDeque<Path> work=new ArrayDeque<>(); - work.push(src); - while( !work.isEmpty() ) { - Path path=work.pop(), target=dst.resolve(src.relativize(path)); - if( Files.isDirectory(path) ) { - Files.createDirectories(target); - try( DirectoryStream<Path> children=Files.newDirectoryStream(path) ) { - for( Path child : children ) work.push(child); - } - } else Files.copy(path,target); - } - } - - private static String clean(String s) { return s.replace('\t',' ').replace('\n',' ').replace('\r',' '); } - - public static void main(String[] args) throws Exception { - Path build=Path.of("build/array-delete-survey"); - Files.createDirectories(build); - Path run=Files.createTempDirectory(build,"run-"); - SB report=new SB().p("case\tfunction\tstatus\tdetail\n"); - String[] names={"aryu8","aryi64","bitset","Timers","Canvas"}; - String[] files={"sys/aryu8.smp","sys/aryi64.smp","sys/adt/bitset.smp","sys/time/Timers.smp","sys/draw/Canvas.smp"}; - for( int i=0; i<names.length; i++ ) { - String name=names[i]; - Path out=run.resolve(name), src=out.resolve("src"); - copyTree(Path.of("src/main/smp"),src); - Path file=src.resolve(files[i]); - Files.writeString(file,migrate(name,Files.readString(file))); - CodeGen code=new CodeGen(src.toString(),out.resolve("objects").toString(),null,"sys",null,456,true,TypeInteger.BOT); - try { - code.driver(CodeGen.Phase.Allocation); - if( Boolean.getBoolean("simple.delete.graph") ) { - Files.writeString(out.resolve("graph.txt"),code.toString()); - Files.writeString(out.resolve("allocation.txt"),code._allocation.toString()); - } - for( ArrayDelete deletion : code._allocation._deletes ) { - String status=deletion._reject!=null ? "REJECT" : deletion._unique!=null ? "NEEDS UNIQUE ENTRY" : "PASS"; - report.p(name).p('\t').p(deletion._call.fun()._name).p('\t').p(status).p('\t').p(clean(deletion.toString())).p('\n'); - } - if( code._allocation._deletes.isEmpty() ) throw new IllegalStateException("No deletion sites found"); - code.driver(CodeGen.Phase.TypeCheck); - System.out.println(name+": TypeCheck PASS"); - } catch( Parser.ParseException e ) { - Files.writeString(out.resolve("rejection.txt"),e.diagnostic()); - report.p(name).p("\t<TypeCheck>\tREJECT\t").p(clean(e.getMessage())).p('\n'); - System.out.println(name+": REJECT at "+code._phase+": "+e.getMessage()); - } catch( Throwable e ) { - SB stack=new SB().p(e.toString()).p('\n'); - for( StackTraceElement frame : e.getStackTrace() ) stack.p(frame.toString()).p('\n'); - Files.writeString(out.resolve("crash.txt"),stack.toString()); - report.p(name).p("\t<compiler>\tCRASH\t").p(clean(e.toString())).p('\n'); - System.out.println(name+": CRASH at "+code._phase+": "+e); - } - } - Files.writeString(run.resolve("results.tsv"),report.toString()); - System.out.println("Results: "+run.resolve("results.tsv")); - } -} diff --git a/chapter33/docs/allocation-survey-functions.tsv b/chapter33/docs/allocation-survey-functions.tsv deleted file mode 100644 index 80f22547..00000000 --- a/chapter33/docs/allocation-survey-functions.tsv +++ /dev/null @@ -1,262 +0,0 @@ -"program" "mode" "unit" "function" "id" "status" "category" "root_function" "root_id" "root_unit" "new_user" "new_class" "variable" "placed_user" "placed_class" "loops" "reason" -"sys" "source" "sys" "class:sys.<clinit>" "2" "pass" "supported" "class:sys.<clinit>" "2" "sys" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.adt" "class:sys.adt.<clinit>" "3" "pass" "supported" "class:sys.adt.<clinit>" "3" "sys.adt" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.audio" "class:sys.audio.<clinit>" "4" "pass" "supported" "class:sys.audio.<clinit>" "4" "sys.audio" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.audio" "sys.audio.open" "11" "direct" "indirect call" "sys.audio.open" "11" "sys.audio" "0" "0" "0" "0" "0" "0" "opaque or indirect call #257" -"sys" "source" "sys.audio" "sys.audio.load" "12" "direct" "raw address" "sys.audio.load" "12" "sys.audio" "0" "0" "0" "0" "0" "0" "raw address escapes lifetime tracking #274" -"sys" "source" "sys.audio" "sys.audio.play" "13" "direct" "indirect call" "sys.audio.play" "13" "sys.audio" "0" "0" "0" "0" "0" "0" "opaque or indirect call #321" -"sys" "source" "sys.audio" "sys.audio.boop" "14" "direct" "indirect call" "sys.audio.boop" "14" "sys.audio" "0" "0" "0" "0" "0" "0" "opaque or indirect call #361" -"sys" "source" "sys.audio" "sys.audio.win" "15" "direct" "indirect call" "sys.audio.win" "15" "sys.audio" "0" "0" "0" "0" "0" "0" "opaque or indirect call #401" -"sys" "source" "sys.audio" "sys.audio.lose" "16" "direct" "indirect call" "sys.audio.lose" "16" "sys.audio" "0" "0" "0" "0" "0" "0" "opaque or indirect call #441" -"sys" "source" "sys.audio" "sys.audio.stop" "17" "direct" "indirect call" "sys.audio.stop" "17" "sys.audio" "0" "0" "0" "0" "0" "0" "opaque or indirect call #468" -"sys" "source" "sys.audio" "sys.audio.playing" "18" "direct" "indirect call" "sys.audio.playing" "18" "sys.audio" "0" "0" "0" "0" "0" "0" "opaque or indirect call #495" -"sys" "source" "sys.audio" "sys.audio.close" "19" "direct" "indirect call" "sys.audio.close" "19" "sys.audio" "0" "0" "0" "0" "0" "0" "opaque or indirect call #522" -"sys" "source" "sys.ary" "class:sys.ary.<clinit>" "20" "pass" "supported" "class:sys.ary.<clinit>" "20" "sys.ary" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.ary" "sys.ary.capacity" "21" "pass" "supported" "sys.ary.capacity" "21" "sys.ary" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.ary" "sys.ary.copy" "22" "pass" "supported" "sys.ary.copy" "22" "sys.ary" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.ary" "sys.ary.cmp" "23" "pass" "supported" "sys.ary.cmp" "23" "sys.ary" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.aryi64" "class:sys.aryi64.<clinit>" "24" "pass" "supported" "class:sys.aryi64.<clinit>" "24" "sys.aryi64" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.aryi64" "sys.aryi64.<init>" "25" "pass" "supported" "sys.aryi64.<init>" "25" "sys.aryi64" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.aryi64" "sys.aryi64._grow" "26" "direct" "indirect call" "sys.aryi64._grow" "26" "sys.aryi64" "1" "0" "1" "0" "0" "1" "opaque or indirect call #1392" -"sys" "source" "sys.aryi64" "sys.aryi64.add" "27" "blocked" "indirect call" "sys.aryi64._grow" "26" "sys.aryi64" "0" "0" "0" "0" "0" "0" "call #1495 -> sys.aryi64._grow: opaque or indirect call #1392" -"sys" "source" "sys.aryi64" "sys.aryi64.get" "28" "pass" "supported" "sys.aryi64.get" "28" "sys.aryi64" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.aryi64" "sys.aryi64.str" "29" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "2" "0" "0" "0" "0" "1" "call #27695 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.aryi64" "sys.aryi64.swap" "30" "pass" "supported" "sys.aryi64.swap" "30" "sys.aryi64" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.aryi64" "sys.aryi64.<new>" "32" "pass" "supported" "sys.aryi64.<new>" "32" "sys.aryi64" "1" "0" "0" "1" "0" "0" "" -"sys" "source" "sys.aryi64" "sys.aryi64.parseAryI64" "33" "blocked" "indirect call" "sys.aryi64._grow" "26" "sys.aryi64" "3" "0" "0" "0" "0" "6" "call #27372 -> sys.aryi64._grow: opaque or indirect call #1392" -"sys" "source" "sys.aryi64" "sys.aryi64.copy" "34" "pass" "supported" "sys.aryi64.copy" "34" "sys.aryi64" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.aryu8" "class:sys.aryu8.<clinit>" "35" "pass" "supported" "class:sys.aryu8.<clinit>" "35" "sys.aryu8" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.aryu8" "sys.aryu8.<init>" "36" "pass" "supported" "sys.aryu8.<init>" "36" "sys.aryu8" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.aryu8" "sys.aryu8._grow" "37" "direct" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "1" "0" "1" "0" "0" "0" "opaque or indirect call #2466" -"sys" "source" "sys.aryu8" "sys.aryu8.clear" "38" "pass" "supported" "sys.aryu8.clear" "38" "sys.aryu8" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.aryu8" "sys.aryu8.add" "39" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "0" "0" "0" "0" "0" "0" "call #2559 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.aryu8" "sys.aryu8.addAry" "40" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "0" "0" "0" "0" "0" "0" "call #2607 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.aryu8" "sys.aryu8.undo" "41" "pass" "supported" "sys.aryu8.undo" "41" "sys.aryu8" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.aryu8" "sys.aryu8.num" "42" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "0" "0" "0" "0" "0" "0" "call #2705 -> sys.text.integer: call #5950 -> sys.text.string: call #23308 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.aryu8" "sys.aryu8.write" "43" "blocked" "raw address" "sys.io.writeOff" "68" "sys.io" "0" "0" "0" "0" "0" "0" "call #2738 -> sys.io.writeOff: raw address escapes lifetime tracking #4102" -"sys" "source" "sys.aryu8" "sys.aryu8.<new>" "45" "pass" "supported" "sys.aryu8.<new>" "45" "sys.aryu8" "2" "0" "0" "2" "0" "0" "" -"sys" "source" "sys.aryu8" "sys.aryu8.atoi" "46" "pass" "supported" "sys.aryu8.atoi" "46" "sys.aryu8" "0" "0" "0" "0" "0" "2" "" -"sys" "source" "sys.aryu8" "sys.aryu8.str0" "47" "direct" "indirect call" "sys.aryu8.str0" "47" "sys.aryu8" "1" "0" "1" "0" "0" "1" "opaque or indirect call #3085" -"sys" "source" "sys.char" "class:sys.char.<clinit>" "48" "pass" "supported" "class:sys.char.<clinit>" "48" "sys.char" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.char" "sys.char.toupper" "49" "pass" "supported" "sys.char.toupper" "49" "sys.char" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.char" "sys.char.tolower" "50" "pass" "supported" "sys.char.tolower" "50" "sys.char" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.integer" "class:sys.integer.<clinit>" "51" "pass" "supported" "class:sys.integer.<clinit>" "51" "sys.integer" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.math" "class:sys.math.<clinit>" "52" "pass" "supported" "class:sys.math.<clinit>" "52" "sys.math" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.math" "sys.math.max" "60" "pass" "supported" "sys.math.max" "60" "sys.math" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.math" "sys.math.min" "61" "pass" "supported" "sys.math.min" "61" "sys.math" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.io" "class:sys.io.<clinit>" "62" "pass" "supported" "class:sys.io.<clinit>" "62" "sys.io" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.io" "sys.io.p" "63" "blocked" "raw address" "sys.io.writeOff" "68" "sys.io" "0" "0" "0" "0" "0" "0" "call #24576 -> sys.io.writeOff: raw address escapes lifetime tracking #4102" -"sys" "source" "sys.io" "sys.io.p_noInline" "64" "blocked" "raw address" "sys.io.writeOff" "68" "sys.io" "0" "0" "0" "0" "0" "0" "call #23093 -> sys.io.writeOff: raw address escapes lifetime tracking #4102" -"sys" "source" "sys.io" "sys.io.err" "65" "blocked" "raw address" "sys.io.writeOff" "68" "sys.io" "0" "0" "0" "0" "0" "0" "call #27466 -> sys.io.writeOff: raw address escapes lifetime tracking #4102" -"sys" "source" "sys.io" "sys.io.read" "66" "direct" "raw address" "sys.io.read" "66" "sys.io" "4" "0" "1" "0" "0" "1" "raw address escapes lifetime tracking #3695" -"sys" "source" "sys.io" "sys.io.write" "67" "blocked" "raw address" "sys.io.writeOff" "68" "sys.io" "0" "0" "0" "0" "0" "0" "call #4008 -> sys.io.writeOff: raw address escapes lifetime tracking #4102" -"sys" "source" "sys.io" "sys.io.writeOff" "68" "direct" "raw address" "sys.io.writeOff" "68" "sys.io" "0" "0" "0" "0" "0" "1" "raw address escapes lifetime tracking #4102" -"sys" "source" "sys.io" "sys.io.stdin" "69" "blocked" "raw address" "sys.io.read" "66" "sys.io" "0" "0" "0" "0" "0" "0" "call #4301 -> sys.io.read: raw address escapes lifetime tracking #3695" -"sys" "source" "sys.io" "sys.io.getch" "70" "direct" "indirect call" "sys.io.getch" "70" "sys.io" "0" "0" "0" "0" "0" "0" "opaque or indirect call #4326" -"sys" "source" "sys.io" "sys.io.create" "71" "direct" "raw address" "sys.io.create" "71" "sys.io" "0" "0" "0" "0" "0" "0" "raw address escapes lifetime tracking #26751" -"sys" "source" "sys.io" "sys.io.open" "72" "direct" "raw address" "sys.io.open" "72" "sys.io" "0" "0" "0" "0" "0" "0" "raw address escapes lifetime tracking #25971" -"sys" "source" "sys.io" "sys.io.close" "73" "direct" "indirect call" "sys.io.close" "73" "sys.io" "0" "0" "0" "0" "0" "0" "opaque or indirect call #4495" -"sys" "source" "sys.io" "sys.io.remove" "74" "direct" "raw address" "sys.io.remove" "74" "sys.io" "0" "0" "0" "0" "0" "0" "raw address escapes lifetime tracking #26389" -"sys" "source" "sys.gfx" "class:sys.gfx.<clinit>" "75" "pass" "supported" "class:sys.gfx.<clinit>" "75" "sys.gfx" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.gfx" "sys.gfx.open" "88" "direct" "raw address" "sys.gfx.open" "88" "sys.gfx" "0" "0" "0" "0" "0" "0" "raw address escapes lifetime tracking #4719" -"sys" "source" "sys.gfx" "sys.gfx.present" "89" "direct" "raw address" "sys.gfx.present" "89" "sys.gfx" "0" "0" "0" "0" "0" "0" "raw address escapes lifetime tracking #4751" -"sys" "source" "sys.gfx" "sys.gfx.width" "90" "direct" "indirect call" "sys.gfx.width" "90" "sys.gfx" "0" "0" "0" "0" "0" "0" "opaque or indirect call #4796" -"sys" "source" "sys.gfx" "sys.gfx.height" "91" "direct" "indirect call" "sys.gfx.height" "91" "sys.gfx" "0" "0" "0" "0" "0" "0" "opaque or indirect call #4823" -"sys" "source" "sys.gfx" "sys.gfx.presentSize" "92" "direct" "raw address" "sys.gfx.presentSize" "92" "sys.gfx" "0" "0" "0" "0" "0" "0" "raw address escapes lifetime tracking #4990" -"sys" "source" "sys.gfx" "sys.gfx.poll" "93" "direct" "indirect call" "sys.gfx.poll" "93" "sys.gfx" "0" "0" "0" "0" "0" "0" "opaque or indirect call #5042" -"sys" "source" "sys.gfx" "sys.gfx.mouseX" "94" "direct" "indirect call" "sys.gfx.mouseX" "94" "sys.gfx" "0" "0" "0" "0" "0" "0" "opaque or indirect call #5069" -"sys" "source" "sys.gfx" "sys.gfx.mouseY" "95" "direct" "indirect call" "sys.gfx.mouseY" "95" "sys.gfx" "0" "0" "0" "0" "0" "0" "opaque or indirect call #5096" -"sys" "source" "sys.gfx" "sys.gfx.button" "96" "direct" "indirect call" "sys.gfx.button" "96" "sys.gfx" "0" "0" "0" "0" "0" "0" "opaque or indirect call #5125" -"sys" "source" "sys.gfx" "sys.gfx.key" "97" "direct" "indirect call" "sys.gfx.key" "97" "sys.gfx" "0" "0" "0" "0" "0" "0" "opaque or indirect call #5154" -"sys" "source" "sys.gfx" "sys.gfx.close" "98" "direct" "indirect call" "sys.gfx.close" "98" "sys.gfx" "0" "0" "0" "0" "0" "0" "opaque or indirect call #5181" -"sys" "source" "sys.gfx" "sys.gfx.wait" "99" "direct" "indirect call" "sys.gfx.wait" "99" "sys.gfx" "0" "0" "0" "0" "0" "0" "opaque or indirect call #5210" -"sys" "source" "sys.draw" "class:sys.draw.<clinit>" "100" "pass" "supported" "class:sys.draw.<clinit>" "100" "sys.draw" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw" "sys.draw.rgb" "101" "pass" "supported" "sys.draw.rgb" "101" "sys.draw" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.text" "class:sys.text.<clinit>" "102" "pass" "supported" "class:sys.text.<clinit>" "102" "sys.text" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.text" "sys.text.begin" "103" "pass" "supported" "sys.text.begin" "103" "sys.text" "2" "0" "0" "2" "0" "0" "" -"sys" "source" "sys.text" "sys.text.end" "104" "direct" "variable size" "sys.text.end" "104" "sys.text" "1" "0" "1" "0" "0" "1" "variable-size allocation #5612" -"sys" "source" "sys.text" "sys.text._pad" "105" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "0" "0" "0" "0" "0" "1" "call #22342 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.text" "sys.text.string" "106" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "0" "0" "0" "0" "0" "3" "call #23308 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.text" "sys.text.integer" "107" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "1" "0" "0" "0" "0" "8" "call #5950 -> sys.text.string: call #23308 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.text" "sys.text.floating" "109" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "0" "0" "0" "0" "0" "0" "call #23862 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.text" "sys.text.int" "110" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "3" "0" "1" "0" "0" "1" "call #7146 -> sys.text.integer: call #5950 -> sys.text.string: call #23308 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.text" "sys.text.flt" "111" "direct" "indirect call" "sys.text.flt" "111" "sys.text" "3" "0" "1" "0" "0" "1" "opaque or indirect call #23783" -"sys" "source" "sys.text" "sys.text.f32" "112" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "3" "0" "1" "0" "0" "1" "call #24296 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.text" "sys.text.f64" "113" "direct" "indirect call" "sys.text.f64" "113" "sys.text" "3" "0" "1" "0" "0" "1" "opaque or indirect call #22964" -"sys" "source" "sys.text" "sys.text.char" "114" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "3" "0" "1" "0" "0" "1" "call #7450 -> sys.text.integer: call #5950 -> sys.text.string: call #23308 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.text" "sys.text.bool" "115" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "3" "0" "1" "0" "0" "1" "call #7526 -> sys.text.integer: call #5950 -> sys.text.string: call #23308 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.text" "sys.text.hex" "116" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "3" "0" "1" "0" "0" "1" "call #7602 -> sys.text.integer: call #5950 -> sys.text.string: call #23308 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.text" "sys.text.time" "117" "blocked" "raw address" "sys.time.local" "148" "sys.time" "0" "0" "0" "0" "0" "0" "call #27428 -> sys.time._format: call #10394 -> sys.time.local: raw address escapes lifetime tracking #9945" -"sys" "source" "sys.time" "class:sys.time.<clinit>" "118" "pass" "supported" "class:sys.time.<clinit>" "118" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.now" "125" "direct" "indirect call" "sys.time.now" "125" "sys.time" "0" "0" "0" "0" "0" "0" "opaque or indirect call #7965" -"sys" "source" "sys.time" "sys.time.monotonic" "126" "direct" "indirect call" "sys.time.monotonic" "126" "sys.time" "0" "0" "0" "0" "0" "0" "opaque or indirect call #7992" -"sys" "source" "sys.time" "sys.time.nanoTime" "127" "direct" "indirect call" "sys.time.nanoTime" "127" "sys.time" "0" "0" "0" "0" "0" "0" "opaque or indirect call #8019" -"sys" "source" "sys.time" "sys.time.sleep" "128" "direct" "indirect call" "sys.time.sleep" "128" "sys.time" "0" "0" "0" "0" "0" "0" "opaque or indirect call #8049" -"sys" "source" "sys.time" "sys.time.sleepUntil" "129" "direct" "indirect call" "sys.time.sleepUntil" "129" "sys.time" "0" "0" "0" "0" "0" "0" "opaque or indirect call #8079" -"sys" "source" "sys.time" "sys.time._scale" "130" "pass" "supported" "sys.time._scale" "130" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.seconds" "131" "pass" "supported" "sys.time.seconds" "131" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.minutes" "132" "pass" "supported" "sys.time.minutes" "132" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.hours" "133" "pass" "supported" "sys.time.hours" "133" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.days" "134" "pass" "supported" "sys.time.days" "134" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.toSeconds" "135" "pass" "supported" "sys.time.toSeconds" "135" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.toMinutes" "136" "pass" "supported" "sys.time.toMinutes" "136" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.toHours" "137" "pass" "supported" "sys.time.toHours" "137" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.toDays" "138" "pass" "supported" "sys.time.toDays" "138" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.fromNanos" "139" "pass" "supported" "sys.time.fromNanos" "139" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.toNanos" "140" "pass" "supported" "sys.time.toNanos" "140" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.remaining" "141" "pass" "supported" "sys.time.remaining" "141" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.leap" "142" "pass" "supported" "sys.time.leap" "142" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.monthDays" "143" "pass" "supported" "sys.time.monthDays" "143" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time._days" "144" "pass" "supported" "sys.time._days" "144" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.valid" "145" "pass" "supported" "sys.time.valid" "145" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.makeUTC" "146" "pass" "supported" "sys.time.makeUTC" "146" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.utc" "147" "pass" "supported" "sys.time.utc" "147" "sys.time" "1" "0" "0" "1" "0" "0" "" -"sys" "source" "sys.time" "sys.time.local" "148" "direct" "raw address" "sys.time.local" "148" "sys.time" "2" "0" "0" "0" "0" "0" "raw address escapes lifetime tracking #9945" -"sys" "source" "sys.time" "sys.time.zoneName" "149" "direct" "raw address" "sys.time.zoneName" "149" "sys.time" "4" "0" "1" "0" "0" "2" "raw address escapes lifetime tracking #10204" -"sys" "source" "sys.time" "sys.time._digits" "150" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "0" "0" "0" "0" "0" "0" "call #10353 -> sys.text.integer: call #5950 -> sys.text.string: call #23308 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.time" "sys.time._format" "151" "blocked" "raw address" "sys.time.local" "148" "sys.time" "3" "0" "1" "0" "0" "1" "call #10394 -> sys.time.local: raw address escapes lifetime tracking #9945" -"sys" "source" "sys.time" "sys.time.elapsed" "152" "blocked" "indirect call" "sys.aryu8._grow" "37" "sys.aryu8" "3" "0" "1" "0" "0" "1" "call #22941 -> sys.text.integer: call #5950 -> sys.text.string: call #23308 -> sys.aryu8._grow: opaque or indirect call #2466" -"sys" "source" "sys.time" "sys.time.format" "153" "blocked" "raw address" "sys.time.local" "148" "sys.time" "0" "0" "0" "0" "0" "0" "call #11574 -> sys.time._format: call #10394 -> sys.time.local: raw address escapes lifetime tracking #9945" -"sys" "source" "sys.time" "sys.time.formatLocal" "154" "blocked" "raw address" "sys.time.local" "148" "sys.time" "0" "0" "0" "0" "0" "0" "call #11663 -> sys.time._format: call #10394 -> sys.time.local: raw address escapes lifetime tracking #9945" -"sys" "source" "sys.time" "sys.time._number" "155" "pass" "supported" "sys.time._number" "155" "sys.time" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.time" "sys.time._parseZone" "156" "pass" "supported" "sys.time._parseZone" "156" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time" "sys.time.parse" "157" "pass" "supported" "sys.time.parse" "157" "sys.time" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.libc" "class:sys.libc.<clinit>" "158" "pass" "supported" "class:sys.libc.<clinit>" "158" "sys.libc" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.libc" "sys.libc.errno" "167" "direct" "indirect call" "sys.libc.errno" "167" "sys.libc" "0" "0" "0" "0" "0" "0" "opaque or indirect call #13351" -"sys" "source" "sys.libc" "sys.libc.set_errno" "169" "direct" "indirect call" "sys.libc.set_errno" "169" "sys.libc" "0" "0" "0" "0" "0" "0" "opaque or indirect call #13383" -"sys" "source" "sys.rt" "class:sys.rt.<clinit>" "172" "pass" "supported" "class:sys.rt.<clinit>" "172" "sys.rt" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.scan" "class:sys.scan.<clinit>" "173" "pass" "supported" "class:sys.scan.<clinit>" "173" "sys.scan" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.scan" "sys.scan.<init>" "174" "pass" "supported" "sys.scan.<init>" "174" "sys.scan" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.scan" "sys.scan.skip" "175" "pass" "supported" "sys.scan.skip" "175" "sys.scan" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.scan" "sys.scan.match" "176" "pass" "supported" "sys.scan.match" "176" "sys.scan" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.scan" "sys.scan.number" "177" "pass" "supported" "sys.scan.number" "177" "sys.scan" "0" "0" "0" "0" "0" "3" "" -"sys" "source" "sys.scan" "sys.scan.<new>" "179" "pass" "supported" "sys.scan.<new>" "179" "sys.scan" "1" "0" "0" "1" "0" "0" "" -"sys" "source" "sys.adt.bitset" "class:sys.adt.bitset.<clinit>" "180" "pass" "supported" "class:sys.adt.bitset.<clinit>" "180" "sys.adt.bitset" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.adt.bitset" "sys.adt.bitset.<init>" "181" "pass" "supported" "sys.adt.bitset.<init>" "181" "sys.adt.bitset" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.adt.bitset" "sys.adt.bitset.get" "182" "pass" "supported" "sys.adt.bitset.get" "182" "sys.adt.bitset" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.adt.bitset" "sys.adt.bitset._grow" "183" "direct" "variable size" "sys.adt.bitset._grow" "183" "sys.adt.bitset" "1" "0" "1" "0" "0" "2" "variable-size allocation #14313" -"sys" "source" "sys.adt.bitset" "sys.adt.bitset.set" "184" "blocked" "variable size" "sys.adt.bitset._grow" "183" "sys.adt.bitset" "0" "0" "0" "0" "0" "0" "call #14413 -> sys.adt.bitset._grow: variable-size allocation #14313" -"sys" "source" "sys.adt.bitset" "sys.adt.bitset.tset" "185" "blocked" "variable size" "sys.adt.bitset._grow" "183" "sys.adt.bitset" "0" "0" "0" "0" "0" "0" "call #14465 -> sys.adt.bitset._grow: variable-size allocation #14313" -"sys" "source" "sys.adt.bitset" "sys.adt.bitset.clr" "186" "pass" "supported" "sys.adt.bitset.clr" "186" "sys.adt.bitset" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.adt.bitset" "sys.adt.bitset.clear" "187" "pass" "supported" "sys.adt.bitset.clear" "187" "sys.adt.bitset" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.adt.bitset" "sys.adt.bitset.<new>" "189" "pass" "supported" "sys.adt.bitset.<new>" "189" "sys.adt.bitset" "2" "0" "0" "2" "0" "0" "" -"sys" "source" "sys.draw.Canvas" "class:sys.draw.Canvas.<clinit>" "190" "pass" "supported" "class:sys.draw.Canvas.<clinit>" "190" "sys.draw.Canvas" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.<init>" "191" "pass" "supported" "sys.draw.Canvas.<init>" "191" "sys.draw.Canvas" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.resize" "192" "direct" "indirect call" "sys.draw.Canvas.resize" "192" "sys.draw.Canvas" "1" "0" "1" "0" "0" "0" "opaque or indirect call #15078" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.localX" "193" "pass" "supported" "sys.draw.Canvas.localX" "193" "sys.draw.Canvas" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.localY" "194" "pass" "supported" "sys.draw.Canvas.localY" "194" "sys.draw.Canvas" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.clear" "195" "pass" "supported" "sys.draw.Canvas.clear" "195" "sys.draw.Canvas" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.pixel" "196" "pass" "supported" "sys.draw.Canvas.pixel" "196" "sys.draw.Canvas" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.fillRect" "197" "pass" "supported" "sys.draw.Canvas.fillRect" "197" "sys.draw.Canvas" "0" "0" "0" "0" "0" "2" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.rect" "198" "pass" "supported" "sys.draw.Canvas.rect" "198" "sys.draw.Canvas" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.fillCircle" "199" "pass" "supported" "sys.draw.Canvas.fillCircle" "199" "sys.draw.Canvas" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.circle" "200" "pass" "supported" "sys.draw.Canvas.circle" "200" "sys.draw.Canvas" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas._circle" "201" "pass" "supported" "sys.draw.Canvas._circle" "201" "sys.draw.Canvas" "0" "0" "0" "0" "0" "2" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.line" "202" "pass" "supported" "sys.draw.Canvas.line" "202" "sys.draw.Canvas" "0" "0" "0" "0" "0" "2" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.text" "203" "pass" "supported" "sys.draw.Canvas.text" "203" "sys.draw.Canvas" "0" "0" "0" "0" "0" "3" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.Canvas" "204" "direct" "indirect call" "sys.draw.Canvas.Canvas" "204" "sys.draw.Canvas" "1" "0" "1" "0" "0" "0" "opaque or indirect call #17231" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas.<new>" "205" "blocked" "indirect call" "sys.draw.Canvas.Canvas" "204" "sys.draw.Canvas" "1" "0" "0" "0" "0" "0" "call #17399 -> sys.draw.Canvas.Canvas: opaque or indirect call #17231" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas._glyph" "206" "pass" "supported" "sys.draw.Canvas._glyph" "206" "sys.draw.Canvas" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Canvas" "sys.draw.Canvas._onLine" "207" "pass" "supported" "sys.draw.Canvas._onLine" "207" "sys.draw.Canvas" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Button" "class:sys.draw.Button.<clinit>" "208" "pass" "supported" "class:sys.draw.Button.<clinit>" "208" "sys.draw.Button" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Button" "sys.draw.Button.<init>" "209" "pass" "supported" "sys.draw.Button.<init>" "209" "sys.draw.Button" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Button" "sys.draw.Button.contains" "210" "pass" "supported" "sys.draw.Button.contains" "210" "sys.draw.Button" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Button" "sys.draw.Button.update" "211" "pass" "supported" "sys.draw.Button.update" "211" "sys.draw.Button" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Button" "sys.draw.Button.draw" "212" "pass" "supported" "sys.draw.Button.draw" "212" "sys.draw.Button" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.draw.Button" "sys.draw.Button.<new>" "214" "pass" "supported" "sys.draw.Button.<new>" "214" "sys.draw.Button" "1" "0" "0" "1" "0" "0" "" -"sys" "source" "sys.time.DateTime" "class:sys.time.DateTime.<clinit>" "215" "pass" "supported" "class:sys.time.DateTime.<clinit>" "215" "sys.time.DateTime" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time.DateTime" "sys.time.DateTime.<new>" "217" "pass" "supported" "sys.time.DateTime.<new>" "217" "sys.time.DateTime" "1" "0" "0" "1" "0" "0" "" -"sys" "source" "sys.time.DateTime" "sys.time.DateTime.empty" "218" "pass" "supported" "sys.time.DateTime.empty" "218" "sys.time.DateTime" "1" "0" "0" "1" "0" "0" "" -"sys" "source" "sys.time.Timers" "class:sys.time.Timers.<clinit>" "219" "pass" "supported" "class:sys.time.Timers.<clinit>" "219" "sys.time.Timers" "0" "0" "0" "0" "0" "0" "" -"sys" "source" "sys.time.Timers" "sys.time.Timers.<init>" "220" "pass" "supported" "sys.time.Timers.<init>" "220" "sys.time.Timers" "3" "0" "0" "3" "0" "0" "" -"sys" "source" "sys.time.Timers" "sys.time.Timers._add" "221" "direct" "recursion" "sys.time.Timers._add" "221" "sys.time.Timers" "3" "0" "3" "0" "0" "2" "recursive call component" -"sys" "source" "sys.time.Timers" "sys.time.Timers.afterAt" "222" "blocked" "recursion" "sys.time.Timers._add" "221" "sys.time.Timers" "0" "0" "0" "0" "0" "0" "call #20364 -> sys.time.Timers._add: recursive call component" -"sys" "source" "sys.time.Timers" "sys.time.Timers.everyAt" "223" "blocked" "recursion" "sys.time.Timers._add" "221" "sys.time.Timers" "0" "0" "0" "0" "0" "0" "call #20399 -> sys.time.Timers._add: recursive call component" -"sys" "source" "sys.time.Timers" "sys.time.Timers.after" "224" "direct" "indirect call" "sys.time.Timers.after" "224" "sys.time.Timers" "0" "0" "0" "0" "0" "0" "opaque or indirect call #22597" -"sys" "source" "sys.time.Timers" "sys.time.Timers.every" "225" "direct" "indirect call" "sys.time.Timers.every" "225" "sys.time.Timers" "0" "0" "0" "0" "0" "0" "opaque or indirect call #23115" -"sys" "source" "sys.time.Timers" "sys.time.Timers.cancel" "226" "pass" "supported" "sys.time.Timers.cancel" "226" "sys.time.Timers" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.time.Timers" "sys.time.Timers.nextDeadline" "227" "pass" "supported" "sys.time.Timers.nextDeadline" "227" "sys.time.Timers" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.time.Timers" "sys.time.Timers.poll" "228" "pass" "supported" "sys.time.Timers.poll" "228" "sys.time.Timers" "0" "0" "0" "0" "0" "1" "" -"sys" "source" "sys.time.Timers" "sys.time.Timers.<new>" "229" "pass" "supported" "sys.time.Timers.<new>" "229" "sys.time.Timers" "1" "0" "0" "4" "0" "0" "" -"RuntimeArgs" "source" "RuntimeArgs" "class:RuntimeArgs.<clinit>" "2" "pass" "supported" "class:RuntimeArgs.<clinit>" "2" "RuntimeArgs" "0" "0" "0" "0" "0" "0" "" -"RuntimeArgs" "source" "RuntimeArgs" "simple_args" "6" "direct" "raw address" "simple_args" "6" "RuntimeArgs" "2" "0" "2" "0" "0" "1" "raw address escapes lifetime tracking #248" -"A_helloWorld" "object" "A_helloWorld" "class:A_helloWorld.<clinit>" "2" "blocked" "raw address" "sys.io.writeOff" "95" "sys.io" "0" "0" "0" "0" "0" "0" "call #4079 -> sys.io.writeOff: raw address escapes lifetime tracking #3733" -"BubbleSort" "object" "BubbleSort" "class:BubbleSort.<clinit>" "2" "pass" "supported" "class:BubbleSort.<clinit>" "2" "BubbleSort" "0" "0" "0" "0" "0" "0" "" -"BubbleSort" "object" "BubbleSort" "sort" "202" "pass" "supported" "sort" "202" "BubbleSort" "0" "0" "0" "0" "0" "2" "" -"BubbleSort" "object" "BubbleSort" "main" "203" "blocked" "raw address" "sys.io.writeOff" "95" "sys.io" "0" "0" "0" "0" "0" "0" "call #5100 -> sys.io.writeOff: raw address escapes lifetime tracking #4714" -"BubbleSort" "object" "BubbleSort" "usage" "204" "blocked" "raw address" "sys.io.writeOff" "95" "sys.io" "0" "0" "0" "0" "0" "0" "call #5978 -> sys.io.writeOff: raw address escapes lifetime tracking #4714" -"Capitalize" "object" "Capitalize" "class:Capitalize.<clinit>" "2" "pass" "supported" "class:Capitalize.<clinit>" "2" "Capitalize" "0" "0" "0" "0" "0" "0" "" -"Capitalize" "object" "Capitalize" "main" "3" "blocked" "raw address" "sys.io.writeOff" "96" "sys.io" "1" "0" "1" "0" "0" "0" "call #4536 -> sys.io.writeOff: raw address escapes lifetime tracking #4076" -"FileIO" "object" "FileIO" "class:FileIO.<clinit>" "2" "pass" "supported" "class:FileIO.<clinit>" "2" "FileIO" "0" "0" "0" "0" "0" "0" "" -"FileIO" "object" "FileIO" "main" "3" "direct" "raw address" "main" "3" "FileIO" "2" "0" "0" "0" "0" "0" "raw address escapes lifetime tracking #6573" -"FileIO" "object" "FileIO" "_error2" "203" "direct" "raw address" "_error2" "203" "FileIO" "2" "0" "0" "0" "0" "0" "raw address escapes lifetime tracking #6670" -"FileIO" "object" "FileIO" "_error" "204" "direct" "indirect call" "_error" "204" "FileIO" "0" "0" "0" "0" "0" "0" "opaque or indirect call #6874" -"Dijkstra" "object" "Dijkstra" "class:Dijkstra.<clinit>" "2" "pass" "supported" "class:Dijkstra.<clinit>" "2" "Dijkstra" "0" "0" "0" "0" "0" "0" "" -"Dijkstra" "object" "Dijkstra" "shortestPath" "202" "blocked" "variable size" "sys.adt.bitset._grow" "48" "sys.adt.bitset" "3" "0" "1" "0" "0" "4" "call #7543 -> sys.adt.bitset._grow: variable-size allocation #6202" -"Dijkstra" "object" "Dijkstra" "usage" "203" "blocked" "raw address" "sys.io.writeOff" "95" "sys.io" "0" "0" "0" "0" "0" "0" "call #7528 -> sys.io.writeOff: raw address escapes lifetime tracking #6699" -"Dijkstra" "object" "Dijkstra" "main" "204" "blocked" "raw address" "sys.io.writeOff" "95" "sys.io" "2" "0" "0" "0" "0" "2" "call #7568 -> sys.io.writeOff: raw address escapes lifetime tracking #6699" -"Graphics" "object" "Graphics" "class:Graphics.<clinit>" "2" "pass" "supported" "class:Graphics.<clinit>" "2" "Graphics" "0" "0" "0" "0" "0" "0" "" -"Graphics" "object" "Graphics" "main" "3" "direct" "raw address" "main" "3" "Graphics" "1" "0" "0" "0" "0" "3" "raw address escapes lifetime tracking #6220" -"Clock" "object" "Clock" "class:Clock.<clinit>" "2" "pass" "supported" "class:Clock.<clinit>" "2" "Clock" "0" "0" "0" "0" "0" "0" "" -"Clock" "object" "Clock" "main" "3" "direct" "raw address" "main" "3" "Clock" "3" "0" "0" "0" "0" "1" "raw address escapes lifetime tracking #11014" -"Clock" "object" "Clock" "_draw" "203" "blocked" "raw address" "sys.time.local" "185" "sys.time" "3" "0" "1" "0" "0" "2" "call #1002 -> sys.time.local: raw address escapes lifetime tracking #12253" -"Clock" "object" "Clock" "_digit" "208" "pass" "supported" "_digit" "208" "Clock" "0" "0" "0" "0" "0" "1" "" -"Clock" "object" "Clock" "_digital" "209" "pass" "supported" "_digital" "209" "Clock" "0" "0" "0" "0" "0" "1" "" -"Clock" "object" "Clock" "_hand" "210" "direct" "indirect call" "_hand" "210" "Clock" "0" "0" "0" "0" "0" "0" "opaque or indirect call #2302" -"Clock" "object" "Clock" "_analog" "211" "direct" "indirect call" "_analog" "211" "Clock" "0" "0" "0" "0" "0" "1" "opaque or indirect call #2540" -"Breakout" "object" "Breakout" "class:Breakout.<clinit>" "2" "pass" "supported" "class:Breakout.<clinit>" "2" "Breakout" "1" "0" "0" "1" "0" "0" "" -"Breakout" "object" "Breakout" "Breakout.Game.<init>" "3" "pass" "supported" "Breakout.Game.<init>" "3" "Breakout" "1" "0" "0" "1" "0" "1" "" -"Breakout" "object" "Breakout" "_tick" "4" "pass" "supported" "_tick" "4" "Breakout" "0" "0" "0" "0" "0" "3" "" -"Breakout" "object" "Breakout" "_cue" "5" "pass" "supported" "_cue" "5" "Breakout" "0" "0" "0" "0" "0" "0" "" -"Breakout" "object" "Breakout" "_speed" "6" "pass" "supported" "_speed" "6" "Breakout" "0" "0" "0" "0" "0" "0" "" -"Breakout" "object" "Breakout" "_paddle" "7" "pass" "supported" "_paddle" "7" "Breakout" "0" "0" "0" "0" "0" "0" "" -"Breakout" "object" "Breakout" "_rebound" "8" "pass" "supported" "_rebound" "8" "Breakout" "0" "0" "0" "0" "0" "1" "" -"Breakout" "object" "Breakout" "_brick" "9" "pass" "supported" "_brick" "9" "Breakout" "0" "0" "0" "0" "0" "0" "" -"Breakout" "object" "Breakout" "_lostBall" "10" "pass" "supported" "_lostBall" "10" "Breakout" "0" "0" "0" "0" "0" "0" "" -"Breakout" "object" "Breakout" "_reset" "11" "pass" "supported" "_reset" "11" "Breakout" "0" "0" "0" "0" "0" "1" "" -"Breakout" "object" "Breakout" "_hud" "211" "pass" "supported" "_hud" "211" "Breakout" "0" "0" "0" "0" "0" "4" "" -"Breakout" "object" "Breakout" "_bricks" "212" "pass" "supported" "_bricks" "212" "Breakout" "0" "0" "0" "0" "0" "1" "" -"Breakout" "object" "Breakout" "_overlay" "213" "pass" "supported" "_overlay" "213" "Breakout" "0" "0" "0" "0" "0" "0" "" -"Breakout" "object" "Breakout" "_draw" "214" "pass" "supported" "_draw" "214" "Breakout" "0" "0" "0" "0" "0" "1" "" -"Breakout" "object" "Breakout" "_input" "215" "direct" "indirect call" "_input" "215" "Breakout" "0" "0" "0" "0" "0" "0" "opaque or indirect call #18288" -"Breakout" "object" "Breakout" "debounce" "216" "direct" "indirect call" "debounce" "216" "Breakout" "0" "0" "0" "0" "0" "0" "opaque or indirect call #6273" -"Breakout" "object" "Breakout" "_serve" "217" "pass" "supported" "_serve" "217" "Breakout" "0" "0" "0" "0" "0" "1" "" -"Breakout" "object" "Breakout" "" "218" "direct" "indirect call" "" "218" "Breakout" "0" "0" "0" "0" "0" "0" "opaque or indirect call #18379" -"Breakout" "object" "Breakout" "" "219" "pass" "supported" "" "219" "Breakout" "0" "0" "0" "0" "0" "0" "" -"Breakout" "object" "Breakout" "Breakout.Game.<new>" "220" "pass" "supported" "Breakout.Game.<new>" "220" "Breakout" "1" "0" "0" "2" "0" "0" "" -"Breakout" "object" "Breakout" "_number" "221" "pass" "supported" "_number" "221" "Breakout" "0" "0" "0" "0" "0" "1" "" -"Breakout" "object" "Breakout" "_tone" "222" "direct" "raw address" "_tone" "222" "Breakout" "1" "0" "0" "0" "0" "1" "raw address escapes lifetime tracking #18921" -"Breakout" "object" "Breakout" "_sqrt" "223" "pass" "supported" "_sqrt" "223" "Breakout" "0" "0" "0" "0" "0" "1" "" -"Breakout" "object" "Breakout" "main" "224" "direct" "raw address" "main" "224" "Breakout" "4" "0" "1" "0" "0" "3" "raw address escapes lifetime tracking #19167" -"TicTacToe" "object" "TicTacToe" "class:TicTacToe.<clinit>" "2" "pass" "supported" "class:TicTacToe.<clinit>" "2" "TicTacToe" "0" "0" "0" "0" "0" "0" "" -"TicTacToe" "object" "TicTacToe" "main" "3" "blocked" "raw address" "sys.io.writeOff" "96" "sys.io" "4" "0" "1" "0" "0" "3" "call #9529 -> sys.io.writeOff: raw address escapes lifetime tracking #7910" -"TicTacToe" "object" "TicTacToe" "_validMove" "207" "direct" "indirect call" "_validMove" "207" "TicTacToe" "3" "0" "1" "0" "0" "2" "opaque or indirect call #9266" -"TicTacToe" "object" "TicTacToe" "_winner" "208" "pass" "supported" "_winner" "208" "TicTacToe" "0" "0" "0" "0" "0" "1" "" -"TicTacToe" "object" "TicTacToe" "_finished" "209" "blocked" "raw address" "sys.io.writeOff" "96" "sys.io" "0" "0" "0" "0" "0" "1" "call #9491 -> sys.io.writeOff: raw address escapes lifetime tracking #7910" -"TicTacToe" "object" "TicTacToe" "_threat" "210" "pass" "supported" "_threat" "210" "TicTacToe" "0" "0" "0" "0" "0" "1" "" -"TicTacToe" "object" "TicTacToe" "_cpu" "211" "pass" "supported" "_cpu" "211" "TicTacToe" "0" "0" "0" "0" "0" "2" "" -"TicTacToe" "object" "TicTacToe" "_draw" "212" "blocked" "opaque body" "sys.ary.capacity" "64" "sys.ary" "2" "0" "0" "0" "0" "2" "call #8785 -> sys.aryu8._grow: call #8389 -> sys.ary.capacity: opaque body: allocation contract unavailable" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "class:TicTacToeGraphical.<clinit>" "2" "pass" "supported" "class:TicTacToeGraphical.<clinit>" "2" "TicTacToeGraphical" "0" "0" "0" "0" "0" "0" "" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "main" "3" "direct" "raw address" "main" "3" "TicTacToeGraphical" "2" "0" "0" "0" "0" "4" "raw address escapes lifetime tracking #9861" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "_sound" "203" "pass" "supported" "_sound" "203" "TicTacToeGraphical" "0" "0" "0" "0" "0" "0" "" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "_reset" "204" "pass" "supported" "_reset" "204" "TicTacToeGraphical" "0" "0" "0" "0" "0" "1" "" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "_square" "205" "pass" "supported" "_square" "205" "TicTacToeGraphical" "0" "0" "0" "0" "0" "0" "" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "_move" "206" "pass" "supported" "_move" "206" "TicTacToeGraphical" "0" "0" "0" "0" "0" "2" "" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "_finished" "207" "pass" "supported" "_finished" "207" "TicTacToeGraphical" "0" "0" "0" "0" "0" "1" "" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "_winningLine" "208" "pass" "supported" "_winningLine" "208" "TicTacToeGraphical" "0" "0" "0" "0" "0" "1" "" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "_winner" "209" "pass" "supported" "_winner" "209" "TicTacToeGraphical" "0" "0" "0" "0" "0" "0" "" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "_threat" "210" "pass" "supported" "_threat" "210" "TicTacToeGraphical" "0" "0" "0" "0" "0" "1" "" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "_cpu" "211" "pass" "supported" "_cpu" "211" "TicTacToeGraphical" "0" "0" "0" "0" "0" "2" "" -"TicTacToeGraphical" "object" "TicTacToeGraphical" "_draw" "212" "pass" "supported" "_draw" "212" "TicTacToeGraphical" "0" "0" "0" "0" "0" "4" "" -"LocalArray" "probe" "LocalArray" "class:LocalArray.<clinit>" "2" "blocked" "variable size" "work_noInline" "3" "LocalArray" "0" "0" "0" "0" "0" "0" "call #111 -> work_noInline: variable-size allocation #36" -"LocalArray" "probe" "LocalArray" "work_noInline" "3" "direct" "variable size" "work_noInline" "3" "LocalArray" "1" "0" "1" "0" "0" "1" "variable-size allocation #36" -"ReturnedArray" "probe" "ReturnedArray" "class:ReturnedArray.<clinit>" "2" "blocked" "variable size" "make_noInline" "3" "ReturnedArray" "0" "0" "0" "0" "0" "0" "call #53 -> make_noInline: variable-size allocation #36" -"ReturnedArray" "probe" "ReturnedArray" "make_noInline" "3" "direct" "variable size" "make_noInline" "3" "ReturnedArray" "1" "0" "1" "0" "0" "0" "variable-size allocation #36" -"OverwrittenSlot" "probe" "OverwrittenSlot" "class:OverwrittenSlot.<clinit>" "2" "blocked" "loop retention" "work_noInline" "8" "OverwrittenSlot" "0" "0" "0" "0" "0" "0" "call #206 -> work_noInline: loop#148 carries new#277:OverwrittenSlot.Thing across its backedge; collection/overlap destinations not implemented" -"OverwrittenSlot" "probe" "OverwrittenSlot" "OverwrittenSlot.Thing.<new>" "5" "pass" "supported" "OverwrittenSlot.Thing.<new>" "5" "OverwrittenSlot" "1" "0" "0" "1" "0" "0" "" -"OverwrittenSlot" "probe" "OverwrittenSlot" "OverwrittenSlot.Holder.<new>" "7" "pass" "supported" "OverwrittenSlot.Holder.<new>" "7" "OverwrittenSlot" "1" "0" "0" "1" "0" "0" "" -"OverwrittenSlot" "probe" "OverwrittenSlot" "work_noInline" "8" "direct" "loop retention" "work_noInline" "8" "OverwrittenSlot" "2" "0" "0" "0" "0" "1" "loop#148 carries new#277:OverwrittenSlot.Thing across its backedge; collection/overlap destinations not implemented" -"ReusedObject" "probe" "ReusedObject" "class:ReusedObject.<clinit>" "2" "pass" "supported" "class:ReusedObject.<clinit>" "2" "ReusedObject" "0" "0" "0" "0" "0" "0" "" -"ReusedObject" "probe" "ReusedObject" "ReusedObject.Thing.<new>" "5" "pass" "supported" "ReusedObject.Thing.<new>" "5" "ReusedObject" "1" "0" "0" "1" "0" "0" "" -"ReusedObject" "probe" "ReusedObject" "read_noInline" "6" "pass" "supported" "read_noInline" "6" "ReusedObject" "0" "0" "0" "0" "0" "0" "" -"ReusedObject" "probe" "ReusedObject" "work_noInline" "7" "pass" "supported" "work_noInline" "7" "ReusedObject" "1" "0" "0" "1" "0" "1" "" diff --git a/chapter33/docs/allocation-survey.md b/chapter33/docs/allocation-survey.md deleted file mode 100644 index eb803c78..00000000 --- a/chapter33/docs/allocation-survey.md +++ /dev/null @@ -1,256 +0,0 @@ -# Allocation survey: existing Simple programs - -Measured 2026-11-21, at TypeCheck with assertions enabled. This surveys the -current analysis; it does not implement or validate stack allocation at runtime. - -The fixed-size plans handle useful object graphs and native borrowing. -Variable-sized storage is now the broadest limitation; the original baseline -below records the earlier native-call and raw-address blockers. - -## Update: lexical KeepAlive - -The parser now retains converted addresses through their lexical scope exits. -This admits integer arguments forwarded through Simple wrappers and addresses -stored and reloaded within that scope. Conditional conversions, overwritten -locals, return/break/continue paths, implicit branch scopes, forward calls, and -imported bodies are covered by the chapter tests. A returned integer does not -promote its backing storage into the caller's lifetime. - -The large-program totals remain 134/179 accepted for `sys` source and -52/68 for the examples' own functions. Those programs had already passed -the simpler borrowing checks or encountered another blocker first. - -The current first-cause breakdown for the 45 rejected `sys` functions is: - -| Cause | Direct | Blocked callers | -|---|---:|---:| -| Variable-size allocation | 7 | 32 | -| Recursion | 1 | 4 | -| Native pointer result without an allocation contract | 1 | 0 | - -First-cause counts can change with optimization order when a function has several -blockers. The native-result requirement remains; this is not permission to assume -that a native-produced pointer is borrowed. The examples' remaining failures -are eleven missing imported bodies, four variable-size plans, and one indirect -callback. - -The next substantial gains need variable-size plans and allocation contracts -for imported bodies. Recursion and Breakout's indirect callback remain separate -work. `_exit` still needs the agreed nonreturning handling. KeepAlive is erased -before scheduling; storage placement still uses function/iteration frames and -does not yet change runtime allocation. - -## Update: native borrowing - -After adopting the native non-retention rule and tracking pointer-derived -integer SSA values through calls, the same cohorts improve as follows. The -remaining sections preserve the original survey and its baseline snapshot. - -| Cohort | Accepted before | Accepted now | With user allocations now | -|---|---:|---:|---:| -| `sys` source, 179 functions | 98 | 134 | 12 | -| Examples' own 68 functions | 43 | 52 | 4 | - -Hello world's executable initializer now gets a supported plan. Clock's `_hand` -and `_analog` pass. Breakout improves from 19/24 to 22/24; its `_tone` buffer is -now accepted as scratch. `sys.time.local` now accepts the DateTime result and -its temporary native buffer. - -Of the remaining 45 `sys` rejections, 38 stop at variable-sized allocation -(seven direct, 31 callers), five at recursion (one direct, four callers), and -two at native-produced Simple pointers without allocation contracts. No call -or raw-address rejection remains the first cause in that source cohort. -Precompiled-library examples still expose missing imported summaries, such as -`sys.ary.capacity`, `sys.ary.copy`, and `sys.aryu8.str0`. Breakout's `debounce` -also contains a genuinely indirect callback. - -This change is analysis-only. `_exit` is accepted under the native borrowing -rule, but is not yet a nonreturning intrinsic. The ABI, allocation lowering, -and default runtime allocation behavior are unchanged. - -## Original baseline - -| Cohort | Function summaries | Accepted | Accepted with user allocations | -|---|---:|---:|---:| -| `sys`, compiled from source | 179 | 98 | 11 | -| Ten examples, their own functions only | 68 | 43 | 3 | -| Native argument conversion, compiled separately | 2 | 1 | 0 | - -These counts include retained/exported functions and class initializers, not -just functions reachable by direct calls from an entry point. Native declarations -without a Simple body are not separate function summaries. A passing function -can still call other passing functions that allocate. The last column counts -fresh storage represented in that function's plan, including imported callee -sites; it excludes compiler class objects. It is not a count of dynamic objects. -All 87 other accepted `sys` functions have no remaining allocation sites. - -## What passes - -The accepted `sys` plans include 19 user-storage sites: 16 with result destinations -and three retained through constructor receiver `arg2`. - -- `sys.time.utc` builds and returns a DateTime: a real fixed-size factory, with - calendar computation and conditional paths. -- `sys.time.Timers.<new>` returns a timer object and its three fixed initial - arrays. The initializer puts the arrays in the receiver's lifetime; the factory - composes that into the returned graph. -- `sys.aryu8.<new>` and `sys.text.begin` return a byte-vector object plus its - initial backing array. Growing that array is a separate, rejected operation. -- Bitset construction, Button construction, and scanner construction pass. -- All six `sys.scan` summaries and all six `sys.draw.Button` summaries pass. - Canvas has 15 passing summaries out of 18: the drawing operations work on - borrowed storage; construction and resizing encounter allocation/call barriers. -- Breakout's Game factory returns the Game and its 192-element brick array. - Its initializer correctly gives the array the receiver's lifetime. Most game - logic and drawing routines pass too. - -The accepted `sys` functions contain 26 loop summaries. Ordinary loops over -existing storage are not the main obstacle. - -## Where the library stops - -The pass records the first rejection in a function. A caller can then inherit -that rejection. Following those call chains gives: - -| First underlying reason | Directly rejected functions | Blocked callers | Total | -|---|---:|---:|---:| -| Opaque or indirect call | 35 | 18 | 53 | -| Raw-address conversion | 11 | 10 | 21 | -| Variable-size allocation | 2 | 2 | 4 | -| Recursion | 1 | 2 | 3 | -| Total | 49 | 32 | 81 | - -These are first-cause counts, not independent fixes or predicted acceptance -after removing a barrier. For example, `sys.aryu8._grow` accounts for 16 rejected -summaries including itself. Its first rejection is the `_exit(1)` call used for -overflow failure, but it also allocates a variable-sized array. Accepting that -call alone would not make growth work. - -Independent inspection of the collected IR finds 21 variable-sized NewNodes -across 19 `sys` functions. Only two functions currently report that as their -first direct failure: `sys.text.end` and `sys.adt.bitset._grow`. - -There were no first-reported loop-retention, cyclic-field-path, or unmapped-origin -failures in this library cohort. Earlier rejection barriers can hide them. - -## The examples - -These use the normal precompiled `sys` library. Counts include only each -example's own functions, avoiding repeated counts of imported library exports. -The compiler may load and inline imported bodies; some others remain opaque. - -| Example | Accepted / total | Accepted with allocations | Representative failure | -|---|---:|---:|---| -| Hello world | 0 / 1 | 0 | String address passed to output | -| BubbleSort | 2 / 4 | 0 | Output; sorting itself passes | -| Capitalize | 1 / 2 | 0 | Output; main also has a variable-sized array | -| FileIO | 1 / 4 | 0 | Native I/O and raw addresses | -| Dijkstra | 1 / 4 | 0 | Bitset growth; output | -| Graphics | 1 / 2 | 0 | Raw address passed to graphics | -| Clock | 3 / 7 | 0 | Graphics/time pointers; scalar libm calls | -| Breakout | 19 / 24 | 3 | Input/audio/graphics calls | -| TicTacToe | 4 / 8 | 0 | I/O, growth, an opaque imported `sys.ary.capacity` | -| TicTacToeGraphical | 11 / 12 | 0 | Main's graphics boundary | - -No example's `main` receives a complete supported plan; hello world's executable -class initializer is rejected too. High per-function acceptance is not yet a -working automatically managed program. - -## Analysis improvements versus storage decisions - -| Case | What is missing | Likely action | -|---|---|---| -| Clock's `sin`/`cos`, clocks, input polling, `_exit` | Known native behavior is treated as opaque | Targeted native contracts/recognition; no application rewrite should be needed | -| Array passed to synchronous I/O or copying audio loader | Lifetime/provenance is lost at conversion to `i64` | Wrapper contract and provenance tracking through the native call | -| Opaque imported Simple function | No serialized allocation summary | Export/import lifetime summaries; avoid changing source merely to force inlining | -| Runtime-sized local scratch array | Immediate rejection of nonconstant size | Keep the lifetime result and represent a runtime size; later lower a local reservation | -| Finished variable-sized result, such as `sys.text.end` | Caller needs storage whose size the callee discovers | Destination/buffer/region choice under the agreed design; possibly a small library rewrite | -| Replaced vector/Canvas backing array | Dynamic sizing plus proof that old aliases are no longer usable | Analysis for reclaiming old buffers; explicit storage policy where proof fails | -| Fixed-size object repeatedly replacing `Holder.c` | Weak updates never kill the old reference | Overwrite/liveness analysis; this is not inherently unbounded storage | -| `Timers._add` retries recursively after growing | SCC support, plus three variable-sized arrays | Defer SCCs; changing the retry to a loop alone would not solve storage | - -Native scalar signatures must not be accepted indiscriminately: an `i64` may -carry a raw pointer. Contracts must describe the actual wrapper, including -whether it retains a passed address or creates returned storage. - -One concrete native allocation requires attention: -[`simple_text_float`](../src/main/c/simple_crt.c) uses `malloc` to create a -Simple-format byte array and returns it. There is no Simple NewNode for that -allocation. A non-retaining-call annotation is insufficient: the result needs -an allocation/ownership contract, or the wrapper should write into caller-provided -storage. This is a useful first native-interface design case. - -The separately compiled [`simple_args`](../src/main/smp/sys/rt/simple_args.smp) -has two variable-sized allocation sites: an outer reference array and byte -arrays created inside its initializer loop. Its first rejection is the raw -destination passed to `memcpy`. Beyond that contract, it exercises the planned -collection destination and variable-sized returned graph. - -## Small reductions - -The survey probe also compiles four isolated cases, without native calls: - -| Probe | Result | -|---|---| -| Allocate `i64[n]`, fill/read it, return a scalar | Rejected: variable-size allocation | -| Return a freshly allocated `i64[n]` | Rejected for the same reason, despite a different storage problem | -| Repeatedly replace `h.c` with a fresh fixed-size Thing, then read the last one | Rejected: Thing survives the backedge | -| Allocate one mutable Thing before the loop, overwrite its scalar field, borrow it each iteration | Accepted: one Thing in the function frame | - -The overwrite reduction has no saved reference to an older Thing. It needs an -analysis improvement, not a language prohibition. Reusing one mutable object -is a possible rewrite for that particular program, not a general replacement -for allocations with distinct observable identities. - -## Suggested next work - -First, admit a small audited set of scalar native calls and specify borrowing -for the common array wrappers. Preserve those contracts across imported calls. -That removes the largest observational barrier without tackling SCCs. - -Then distinguish local variable-sized scratch from returned/growing storage, -and tackle the fixed-size overwrite proof. Re-run this survey after those steps; -the first-cause distribution should become much more informative. - -For an initial lowering implementation, the passing Game, Timers, byte-vector, -and DateTime factories already supply useful fixed-size object graphs. Use them -alongside the existing scratch/winner poster children. Do not wait for every -library operation to pass before validating real storage placement. - -## Reproduction and limitations - -[`AllocationSurvey.java`](AllocationSurvey.java) is a standalone observational -probe. It reads private analysis collections by reflection rather than adding -production compiler APIs. It does not change contracts, suppress rejections, -link native code, run games, or lower allocation plans. -The [function-level snapshot](allocation-survey-functions.tsv) contains the -cohorts above and the four reductions, with first-cause chains and site counts. -Full dumps, allocation sites, and call lists are written under -`build/allocation-survey/<name>-<mode>/`. - -From `chapter33`, after building the Java compiler and the normal `sys` objects: - -```powershell -javac -cp build/classes/main -d build/allocation-survey docs/AllocationSurvey.java -java -ea -Xss16m -Xmx2g -XX:ActiveProcessorCount=2 -cp 'build/classes/main;build/allocation-survey' AllocationSurvey sys source -java -ea -Xss16m -Xmx2g -XX:ActiveProcessorCount=2 -cp 'build/classes/main;build/allocation-survey' AllocationSurvey Clock object -java -ea -Xss16m -Xmx2g -XX:ActiveProcessorCount=2 -cp 'build/classes/main;build/allocation-survey' AllocationSurvey OverwrittenSlot probe -``` - -Use each example's filename without `.smp`; modes are `source` and `object`. -`RuntimeArgs source` compiles the native-startup helper. Probe names are -`LocalArray`, `ReturnedArray`, `OverwrittenSlot`, and `ReusedObject`. -On bash use `:` instead of `;` in the classpath. - -The auxiliary all-source run succeeds for hello world, BubbleSort, Capitalize, -and Breakout. Breakout's own 19/24 result is unchanged with library source visible. -The other six examples stop in Parse on qualified `sys` types, before Allocation; -they are not counted as lifetime failures. The source-mode probe prepends a -private `sys` binding to request library discovery; that does not resolve those -type-name failures. A first all-source Breakout run exhausted the default Java -stack in `Node._walk`; all reported runs use `-Xss16m`. - -Counts use seed 456 and optimized IR, so inlining and dead-code removal affect -which sites and functions remain. They measure the current conservative analysis, -not runtime allocation frequency, memory saved, or proof that future lowering is -correct. Existing compiler files were not changed for this survey. diff --git a/chapter33/docs/array-delete-survey.md b/chapter33/docs/array-delete-survey.md deleted file mode 100644 index 82303acb..00000000 --- a/chapter33/docs/array-delete-survey.md +++ /dev/null @@ -1,141 +0,0 @@ -# Deletable-array source survey - -2026-11-23. Five production resize implementations, seven source deletion sites. -The compiler now accepts `E[^]`, `new E[^N]`, and `.del()` and requires an ownership -proof at TypeCheck. Runtime recycling remains unimplemented. - -| Source | Local deletion check | Full TypeCheck | -|---|---|---| -| [aryu8._grow](../src/main/smp/sys/aryu8.smp) | Grow/add/append, string/integer formatting, and `aryi64.str` compose | Reject: native boundaries in file input, floating formatting, and calendar formatting | -| [aryi64._grow](../src/main/smp/sys/aryi64.smp) | Initializer and repeated `add` calls compose | Pass, including `parseAryI64` | -| [bitset._grow](../src/main/smp/sys/adt/bitset.smp) | Contract propagates through `set` and `tset` | Pass | -| [Timers._add](../src/main/smp/sys/time/Timers.smp) | Consuming recursion not supported | Reject | -| [Canvas.resize](../src/main/smp/sys/draw/Canvas.smp) | Consuming `self.pixels` contract inferred | Pass | - -No compiler crashes remain in the final sweep. Initially four cases asserted on -an array `.del` field offset: the receiver became an array only after parsing. -Deferred member resolution now folds that load to the intrinsic. The added -generic receiver signature also exposed an abstract-pointer type-upgrade bug; -abstract struct bounds now remain bounds instead of being looked up as classes. - -The source-level poster children in Chapter33Test pass: local arrays, replacement -of a locally constructed owner's buffer, borrowing helpers, list/generator -initializers, and serialized/imported deletion bodies. Saved aliases and -double deletion reject. Extracting an element reference does not retain its -backing array. Incoming ownership becomes a checked function requirement; callers -must discharge it or propagate it in their own contract. A library can therefore -pass TypeCheck while retaining requirements for future callers. - -## What the failures tell us - -Known native `_exit` calls now retain normal call control but return `TypeMem.TOP` -memory and `TypeScalar.TOP` values. The machine call remains; mixed or unknown -targets remain conservative. This removes `_exit` from the merged memory effects -without adding an exceptional CFG edge. - -The earlier reduced case's redundant `Test.$init` guard is handled: loads recover -the initialized flag through whole-memory parameters when every live incoming -path proves it. Variable-sized `[^]` allocations are planned as buddy storage. - -Its replacement, `testArrayDeleteAryu8IntegerInit`, reads `sys.integer.MAX_U32` -directly and imports the release library, isolating remote initialization from -`ary.capacity` and `ary.copy`. The saved summary now records the function's own -written aliases, reference-write flag, and escaping identities. Incoming memory -and unrelated functions' escapes are not part of that contract. Effects compose -through calls, including recursive and nonreturning paths. The initializer has -no reference writes. The local proof produces a consuming requirement, and the -fresh-wrapper caller discharges it; the test now passes TypeCheck. - -This removes `sys.ary.capacity` and `sys.integer` as blockers in the production -sweep. Allocation contracts now survive serialization too: `ary.copy` returns -its `dst` argument, allocates no storage, and writes no references. The deletion -checker follows returned argument aliases, allowing this copy while still -rejecting uses of an old array through a returned alias after deletion. -`testArrayDeleteAryu8Copy` exercises the actual imported contract without loading -the copy implementation; its fresh-wrapper caller now passes too. Caller checks -use the buffer's entry identity: saved aliases reject, but a reload of the -replaced field is valid. Requirements survive forwarding and serialization. - -The repeated-checkpoint restriction is now removed. `testArrayConsumeGrowLoop` -passes, as do nested loops, breaks, fresh allocation/deletion per iteration, and -loops calling an imported forwarder. The backedge check rejects saved array -references and verifies the callee preserves an exclusive owning field. A helper -that publishes an alias of its replacement cannot satisfy that proof. -Copies of the replacement crossing the backedge are conservatively rejected, -even when the next iteration could use and discard them before its next grow. - -The two-grow example now passes (`testArrayConsumeTwoGrows`). The checker follows -memory SSA; it substitutes each call's field stores and returned origins at that -call's memory output. A proven unique outgoing field provides a new ownership -version, even on a no-growth path. Loop heads provide iteration-entry versions, -so several grows per iteration do not confuse prior and current buffers. The -initializer-specific proof was replaced by this general call substitution. - -String formatting needs both a writable builder and a borrowed input array. -Its unique-buffer requirement excludes an alias in that input parameter; callers -check their actual arguments. Passing the builder's own buffer rejects. Distinct -wrapper parameters are still allowed to alias, so their field paths cannot gain -this disjointness assumption merely by having different names. - -## Checkpoint for design review - -The latest sweep passes the complete `aryi64`, `bitset`, and `Canvas` migrations. -Within the `aryu8` migration, `_grow`, `add`, `addAry`, `num`, padding, string and -integer formatting, `aryi64.str`, and elapsed-time formatting pass their checks. -The remaining failures are: - -| Boundary | Current rejection | -|---|---| -| `sys.io.read` | Native `read` has no usable pointer-memory effect contract | -| Floating formatting | `simple_text_float` returns storage with unknown origin | -| Calendar formatting | `sys.time.local` carries unmodeled native effects | -| Timers | Recursive consuming groups lack allocation/ownership contracts | - -The storage graph is still flow-insensitive. It supplies conservative may-stores -and the proof of unique outgoing fields; the deletion checker applies those -facts in memory order. Arbitrary callee overwrites do not yet prove an alias was -cleared. Other conservative limits remain: replacement aliases carried across -iterations, cyclic reference queries, multiple incoming ownership paths, and -array-element ownership slots requiring index proofs. These are useful targets -for the architecture review rather than more library-specific exceptions. - -IR format 8 records whether raw/native/initialization effects are absent from -the field graph. Such summaries remain opaque to ownership composition, also -after serialization. Tests cover unsafe saved aliases, helper retention, actual -argument aliasing, multiple grows per iteration, imported forwarders, and an -imported raw-address store. The headless test suite passes. No compiler crashes -occurred in the sweep. Runtime recycling remains unimplemented. - -## Reproducing the sweep - -[ArrayDeleteSurvey.java](ArrayDeleteSurvey.java) copies `src/main/smp` into a fresh -directory under `build/array-delete-survey`, changes one library per case, then -compiles the whole source `sys`. It does not alter production files or run Simple -code. Each migration marks backing arrays and their allocations `[^]`, saves the -old references, publishes replacements, and calls `.del()` on the old buffers. -For aryi64 it also changes the owning constructor parameter and its factory's -initial allocation; arbitrary caller arrays cannot simply acquire the capability. - -From chapter33, compile the runner: - -```text -javac -cp build/classes/main -d build/array-delete-survey docs/ArrayDeleteSurvey.java -``` - -PowerShell or cmd: - -```text -java -ea -Xss16m -Xmx2g -XX:ActiveProcessorCount=2 -cp "build/classes/main;build/array-delete-survey" ArrayDeleteSurvey -``` - -Bash on Unix: - -```sh -java -ea -Xss16m -Xmx2g -XX:ActiveProcessorCount=2 -cp 'build/classes/main:build/array-delete-survey' ArrayDeleteSurvey -``` - -The runner prints the output directory. It contains migrated sources, a -`results.tsv` with every deletion result, and source diagnostics for rejected -compilations. Java exceptions/assertions are recorded separately as crashes. -Adding `-Dsimple.delete.graph=true` also saves the IR and allocation dump for each -case. Quote that option in PowerShell. diff --git a/chapter33/docs/examples/Breakout.smp b/chapter33/docs/examples/Breakout.smp index d60894ac..ecb7fc26 100644 --- a/chapter33/docs/examples/Breakout.smp +++ b/chapter33/docs/examples/Breakout.smp @@ -246,12 +246,12 @@ struct Game { int mouse = c.localX(gfx.mouseX()); // Restart requested - restartHeld = debounce( restart, restartHeld, { -> _reset(); sys.audio.stop(); } ); + restartHeld = _debounce( restart, restartHeld, { -> _reset(); sys.audio.stop(); } ); // Playing or ready to play game? if( phase == READY || phase == PLAY ) { // Flip pause state - pauseHeld = debounce( pause, pauseHeld, { -> paused = !paused; } ); + pauseHeld = _debounce( pause, pauseHeld, { -> paused = !paused; } ); // If no key and mouse moved, set paddle to mouse if( mouse >= 0 && mouse != lastMouse && direction == 0 && !paused ) { @@ -264,13 +264,13 @@ struct Game { } // Serve requested - serveHeld = debounce( serve, serveHeld, _serve ); + serveHeld = _debounce( serve, serveHeld, _serve ); // Return key direction, so the tick tracking can slide paddle smoothly return direction; }; - val debounce = { bool b, bool bHeld, { int } action -> + val _debounce = { bool b, bool bHeld, { int } action -> if( b && !bHeld ) // Action requested and repeating action(); // Do action b; // Dont action again, until 'b' is released diff --git a/chapter33/docs/growing-arrays-survey.md b/chapter33/docs/growing-arrays-survey.md deleted file mode 100644 index 13fd93d0..00000000 --- a/chapter33/docs/growing-arrays-survey.md +++ /dev/null @@ -1,230 +0,0 @@ -# Growing arrays: where grow-in-place fits - -Surveyed 2026-11-21. Most current byte builders have a single construction -phase and could finish as ordinary arrays. The persistent counterexamples are -bitsets, timers, and canvas buffers. The choice belongs to a use of a collection, -not to every instance of `aryu8` or `aryi64`. - -This is a source survey, not an implemented placement proof or a runtime profile. -It covers chapter33's Simple library, examples, Simple programs embedded in Java -tests, and retained regression workloads. Earlier chapter copies are not counted -again. Compiler Java collections appear separately as future Simple-in-Simple -requirements. No language or library behavior changed during the survey. -The [first source rewrites](growing-array-rewrites.md) show BrainFuck and direct -block reads using scope-ended growth and a proposed writable array length. - -## Construction that finishes - -“Candidate” below means growth has a recognizable end. It does not yet prove -that the physical allocation end is free, or solve returning variable-sized data. - -| Code | Observed growth and subsequent use | Grow-in-place assessment | -|---|---|---| -| [Interpolation](../src/main/java/com/seaofnodes/simple/parser/Strings.java), [text.integer/string](../src/main/smp/sys/text.smp) | Parser creates one builder, appends literal pieces and formatted expressions, then calls `end`. Integer formatting uses a fixed 22-byte digit scratch array. | Strong candidate. Fixed scratch needs placement before/beside the growing storage; formatting helpers need to borrow the active builder. Arbitrary interpolation expressions can introduce nested allocation. | -| [text.floating/time](../src/main/smp/sys/text.smp) | Both obtain a temporary string and append it to the outer builder. `floating` gets a native allocation; `time` calls another Simple formatter. | Candidate after arranging temporary storage or changing to destination-writing helpers. Not automatically one free growing end; see below. | -| [aryi64.str](../src/main/smp/sys/aryi64.smp) | Appends brackets, numbers, and separators, removes the final separator, then returns the builder. [BubbleSort](examples/BubbleSort.smp) and [StreamIOTest](../src/test/java/com/seaofnodes/simple/StreamIOTest.java) append a newline afterwards. | Construction is localized, but its present API returns a still-growable value. Prefer an append-into-destination formatter, with the caller adding the newline before finishing. | -| [parseAryI64](../src/main/smp/sys/aryi64.smp) | One scanner and one result vector; append parsed numbers, validate closing syntax, return. BubbleSort sorts the result; Dijkstra only reads it. Neither appends more numbers. | Strong candidate for a finished mutable `i64[]`. Freeze length, not element stores. Returned variable-sized storage still needs a destination. | -| [io.read](../src/main/smp/sys/io.smp) | Allocates an 8 KiB scratch chunk before starting the builder. Reads until EOF, appends each received prefix, then copies to an exact-length result. Errors discard the partial result. | Strong candidate. The scratch buffer is already separate from the growing output. Finish could avoid the final copy if the result's lifetime and placement permit it. Keep short-read/EINTR/error behavior. | -| [BrainFuckTest](../src/test/java/com/seaofnodes/simple/BrainFuckTest.java) | One output builder, one fixed 100-byte tape, no other growing collection in the interpreter. Output is consumed only after execution finishes. | Strong candidate. Place the fixed tape before the growing output, or in reserved fixed storage. Finish at interpreter exit; the current wrapper-return API needs changing or an explicit result destination. | -| [TicTacToe._draw](examples/TicTacToe.smp) | Builds one board rendering and immediately writes it. No builder escapes. | Simplest local candidate. This particular rendering is exactly 60 bytes, so a fixed array also suffices. | -| [FileIO](examples/FileIO.smp), [Dijkstra's diagnostic output](examples/Dijkstra.smp) | FileIO builds its message before opening/writing/reading the file, then compares it with the readback. Diagnostics build and write once. | Finish FileIO's message before later I/O allocations; its storage remains live for comparison. The literal message can also be sized exactly. Diagnostics are local builders. | -| [time._format/elapsed/zoneName](../src/main/smp/sys/time.smp) | Formatters build and finish one result. `zoneName` first fills a fixed 128-byte buffer, learns `n`, then builds another buffer and copies again in `text.end`. | `_format`/`elapsed` are localized builders. `zoneName` needs no growing array: after the native call, allocate exactly `n` bytes and copy once. All returned results retain the destination question. | - -The [original BrainFuck workload](../src/test/java/com/seaofnodes/simple/spill/BrainFuckTest-testBrainFuck.smp) -does `new u8[output# + 1]` and copies the old output on every `.` command. -For N emitted bytes that copies N(N-1)/2 old bytes, in addition to writing the -N new bytes. It is the clearest avoidable-copy example. The aryu8 version already -uses geometric growth. Keep the historical workload if its purpose remains -cross-target compiler comparison; add a new builder version alongside it. - -## Growth interleaved with continued use - -The production Simple library has five implementations that replace backing -arrays to increase capacity: `aryu8`, `aryi64`, `bitset`, `Timers`, and `Canvas`. -Timers replaces three arrays together. The first two support the construction -cases above; the other three illustrate why we still need another storage choice. - -| Code | Why a single temporary construction scope is insufficient | Suitable direction | -|---|---|---| -| [adt.bitset](../src/main/smp/sys/adt/bitset.smp) | Random indexed `set`/`tset` can increase capacity between reads, clears, and other work. | General instance: retain a replaceable backing array or use chunks. [Dijkstra](examples/Dijkstra.smp) knows the bit universe from `nodes`, so reserve `(nodes+63)/64` words before its loop instead. | -| [time.Timers](../src/main/smp/sys/time/Timers.smp) | IDs, deadlines, and periods grow together; registration, cancellation, and polling interleave. [TimeTest](../src/test/java/com/seaofnodes/simple/TimeTest.java) forces growth past eight slots. Clock itself registers only one timer. | A mini-arena owned by the Timers instance can hold replacement arrays. Alternatively, fixed chunks of inline timer entries would avoid copying and exercise value objects; that is a representation change, not just append syntax. Three independent arrays cannot all own one contiguous growing end. | -| [draw.Canvas.resize](../src/main/smp/sys/draw/Canvas.smp) | Capacity increases across window events, interleaved with drawing, timers, and text formatting. Smaller sizes reuse capacity. On growth the old pixels are discarded, not copied. | Retain replacement-buffer behavior in the Canvas lifetime group. A deliberately reserved non-moving region is plausible for a small number of windows, but should be an explicit choice. Chunking pixels directly would change the contiguous graphics interface. | - -The generic aryu8 API also permits `clear`, `undo`, reads, and later appends. -[StreamIOTest](../src/test/java/com/seaofnodes/simple/StreamIOTest.java) exercises -that mutable-container behavior. The small `_Vec` in -[Chapter21Test.testArmVectorGrowth](../src/test/java/com/seaofnodes/simple/Chapter21Test.java) -is another explicit doubling/copy implementation outside sys. Its particular -caller builds five integers in one expression; the generic type allows later -growth. The frozen BubbleSort and seed-reproduction sources contain older copies -of the same byte/integer vector pattern. - -## Two constraints exposed by the survey - -### Explicit containers for interleaved growth - -Discussion direction: infer one active growing end, with properly nested -temporary work allowed. If multiple live arrays need interleaved extension at -that end, reject with a concrete rewrite path. Do not automatically synthesize -independent regions or a general collector to preserve the source representation. - -A proposed diagnostic at the failed extension: - -```text -Cannot extend 'ids' here: live storage for 'due_ms' follows it. - 'ids' starts growing at ... - 'due_ms' is allocated at ... and is still needed at ... -Use one array of inline timer entries, or explicit resizable containers -such as aryu32 and aryi64 for independently growing buffers. -``` - -This diagnoses unavailable tail space while growth is still permitted. Trying -to grow an array whose constructor has already ended instead reports that its -length is fixed, with the constructor boundary and the attempted growth shown. - -For Timers the programmer can choose either representation: - -- Array of inline Timer entries containing id, due, and period, with explicit - resize logic. Under the previously agreed notation this is `new *Timer[8]` - (with appropriate element initialization), rather than an array of Timer - references. No per-entry object allocation or pointer chase is required; - padding and field-scan locality can still differ from struct-of-arrays. -- Keep the struct-of-arrays layout, using three explicit container instances: - one aryu32 and two aryi64 collections. These containers need not own the - shared stack's growing end. - -Agreed allocator direction: growable containers use power-of-two backing arrays -and deleted backing arrays are recycled through a buddy allocator. Resize obtains -a larger chunk, copies the used elements, publishes the replacement, and calls -`old.del()` to retire the old backing allocation. This moving representation -does not promise stable -direct interior references through resize. Container/index handles and copied -primitive/reference values remain useful interfaces. - -Agreed safety rule: a deletable array has a different type from an ordinary -array; its provisional modifier is `^`. It disallows interior references and -requires unique access and no escaping aliases. Deletion consumes the owning -access, with no outstanding borrows or other usable aliases surviving it. -The compiler checks this rule; it is not an unchecked promise by the library. -Copied primitive elements and copied object references are not references into -the backing storage. Container/index handles can resolve through the current -buffer without retaining the retired one. - -In resize, replacing the container's backing field removes that owning access -to the old buffer; the local `old` then supplies the access consumed by delete. -If another usable alias remains, diagnose that alias and the attempted deletion. -Ordinary arrays retain their automatic-lifetime behavior and cannot be deleted. -Raw-address borrowing must also respect the no-surviving-use requirement. - -This differs from deletable class slots, whose stale references remain type-safe. -Buddy splitting/coalescing can change the array extent and layout. An old array -header can become element data after reuse, so even bounds checks can read the -wrong length. Merely preserving the element type is not enough to inherit the -class-slot post-delete guarantees. The agreed uniqueness rule excludes those -stale accesses, allowing the buddy allocator to recycle the whole block. -Moving the length field out of the allocation is therefore not needed for this -safety argument; it remains a separate, useful layout optimization. -The same buddy allocator can serve every element type and keep metadata inside -freed blocks. Automatic deletion on a proven last-reference overwrite is deferred; -the first interface uses explicit `.del()`. The -[first ownership experiment](../README.md#array-deletion-first-ownership-checks) -now accepts source `E[^]` and `.del()` and checks local aliases and field kills. -The [migration survey](array-delete-survey.md) records which real resize bodies -pass these local checks and which proof obligations remain. The runtime -intrinsic is not implemented yet. - -`text.begin()` currently returns a newly created builder. For the proposed -scope-owned growing array, interpolation should establish that storage in the -expression's owning scope, then let helpers borrow it. Keeping `begin()` unchanged -and hoping the inliner erases its call would make a language lifetime rule depend -on optimization. The same issue applies to factories returning fresh growable -wrappers; it is separate from a helper appending to an existing destination. - -One logical builder does not imply one free physical end. For example, -[Clock._draw](examples/Clock.smp) interpolates `sys.time.formatLocal(...)` into -an outer string. The outer builder is started before that expression is evaluated. -The inner formatter returns its finished array, then the outer builder grows -while reading that array. With both on the same growing end, the inner result -still occupies the space the outer wants. This is not the easy nested case where -the child has unwound before the parent resumes growing. - -Agreed follow-up: append time formatting directly into a supplied destination. -For floating formatting, pre-grow the destination by a sufficient bound, pass -the writable tail and its capacity to the C helper, and receive the actual byte -count. Trim the unused tail afterwards. The helper fills the destination directly; -it does not allocate a returned string or copy from an intermediate output array. -The bound must account for the value, format, width, precision, and any terminating -NUL needed by the C implementation. The NUL is not part of the final string length. -The existing [simple_text_float](../src/main/c/simple_crt.c) still allocates; -changing it to this interface remains implementation work. - -Arbitrary interpolation expressions follow the ordinary rules for code executing -inside any growable-array constructor. Their allocation/lifetime plan must leave -the required growing end free when extension resumes. If no legal plan exists, -the normal allocation analysis rejects the program. There is no separate -interpolation allocation rule. Helpers growing a caller's destination likewise -use the general call-frame placement rules. - -The agreed return destination is now a separate growable data stack. `io.read`, -parsed number arrays, formatted strings, and BrainFuck results finish growth -before returning; their bytes survive the callee's control frame. The hidden -data-stack top is updated on return, and the owning lifetime later restores its -mark. This supplies contiguous non-moving storage without a final copy; lowering -and the calling convention remain implementation work. - -## Aliases and future inline elements - -Backing-array references are already observable, even without interior pointers: - -- `aryi64` accepts a caller-provided backing array; it need not own the only reference. -- `buf`/`pixels` are exposed. StreamIOTest saves `b.buf`; DrawTest saves old and - grown pixel arrays and checks reuse when resizing within capacity. -- `text.end(b)` currently copies into a read-only array and leaves `b` usable. - A consuming finish operation changes that contract. Existing callers that are - done with `b` can migrate; the general API cannot silently change meaning. -- `aryi64.str()` callers demonstrably continue growing the returned value. - -A mini-arena makes its allocated blocks stationary. It does not make a vector -stationary if the vector later copies its contents into a larger block. An -array of future inline objects can promise stable direct interior references -only with the non-moving choice; those references also inherit the backing -storage's lifetime. Movable containers can expose values or `(container,index)` -handles instead. Truncating/clearing and reusing inline slots will need its own -reference-validity rule, even when the storage address stays fixed. - -Old backing arrays cannot be recycled merely because the wrapper now points to -a new array: another reference may still name the old one. Retaining all blocks -until the lifetime group unwinds is the simple safe policy. Earlier recycling -needs proof that those references are gone. Allocator chunk recycling here is -distinct from the language's explicit `delete` and its weaker post-delete rules. - -## Compiler collections: future Simple-in-Simple cases - -| Existing Java use | Storage implication | -|---|---| -| [Node inputs/outputs](../src/main/java/com/seaofnodes/simple/node/Node.java), backed by [Ary](../src/main/java/com/seaofnodes/simple/util/Ary.java) | Many independently growing collections, mutated throughout optimization. Embedded small vectors plus overflow storage fit; one reserved growing region per Node does not. Entries currently hold references, not inline Nodes. | -| [CodeGen linker/call/CFG lists](../src/main/java/com/seaofnodes/simple/codegen/CodeGen.java) | Broad lifetimes, but several lists grow interleaved. Being long-lived does not alone make their ends free. Separate explicit areas or a common chunk allocator are options. | -| [Serialize.write](../src/main/java/com/seaofnodes/simple/codegen/Serialize.java), [Lexer.stringPart](../src/main/java/com/seaofnodes/simple/parser/Lexer.java) | Local output accumulation followed by a completed byte result. Candidates for finishable builders, subject to helper temporaries and the return destination. | -| [Encoding](../src/main/java/com/seaofnodes/simple/codegen/Encoding.java), [BAOS](../src/main/java/com/seaofnodes/simple/util/BAOS.java) | Instruction bytes, constant data, and writable data have separate buffers; emission also creates metadata, patches earlier bytes, and can replace the instruction buffer during compaction. This needs an explicit layout plan or independent buffers, not blanket conversion of BAOS. | -| [IntHashMap](../src/main/java/com/seaofnodes/simple/util/IntHashMap.java) | Growth rehashes entries. Reserving more address space does not remove that semantic relocation. A future inline-entry reference cannot promise stability through rehash. | - -The native MiniFB adapter has a separate resizable repaint buffer in -[simple_minifb.c](../src/main/c/simple_minifb.c). It copies the Simple pixels; -the retained native buffer is not a retained pointer into the Simple array. - -## Suggested first cases - -1. BrainFuck output: one unknown-length append stream, fixed scratch, finish; - first consume it within the same activation to isolate growth from return placement. -2. `io.read`: chunked input, error unwind, and a finished variable-sized result. -3. Integer/string interpolation, then nested time formatting: borrowed builder - helpers, fixed scratch, and the first real competing-temporary case. -4. Timers: persistent growth and three coupled arrays; compare grouped replacement - buffers with chunks of inline entries rather than forcing it into the first case. - -Some current variable-size failures are not growing arrays at all: `str0`, -`Canvas` construction, and `text.end` know their length when they allocate. -Supporting runtime-sized fixed arrays is independently useful. This survey does -not predict a new accepted-function count: the current pass also rejects loop -retention, returned variable-sized storage, and recursive Timers._add before -these proposed storage representations exist. diff --git a/chapter33/docs/growing-array-rewrites.md b/chapter33/docs/growing-arrays.md index cd9257d3..4a0d5046 100644 --- a/chapter33/docs/growing-array-rewrites.md +++ b/chapter33/docs/growing-arrays.md @@ -1,11 +1,11 @@ -# Growing arrays: first source rewrites +# Scope-owned growing arrays -Design notes, 2026-11-21. Writable array length and the constructor return rules -below are agreed; the parser and allocator do not implement these examples yet. -They follow the -[growing-array survey](growing-arrays-survey.md). +This is the selected language and storage design, with illustrative source +examples. Writable array length, whole-array construction scopes, and growable +data-stack lowering are not implemented. See [memory management](memory-management.md) +for the analysis and storage-policy boundary. -The proposed rule is: `new E[]` creates an initially empty array whose growth +The selected rule is: `new E[]` creates an initially empty array whose growth belongs to the allocating lexical scope. Leaving that scope ends growth, including returning the array. Its storage can outlive that scope; its permission to grow cannot. Element mutation remains allowed. Returning from a helper that @@ -108,24 +108,13 @@ state remain. Cleanup must preserve errno. References into abandoned storage must not survive its reclamation; the lifetime check includes the failure edge. -### Other exit spellings considered - -- `self = null` with an implicit exit hides control flow in assignment; rejected. -- `self = null; break` separates the failure marker from the exit, makes self - nullable inside the body, and normally breaks only the innermost loop. Avoid it. -- `self# = -1; break` violates the valid-length invariant and overloads an unsigned - length with an error sentinel. Negative lengths remain invalid. -- `break null` could be part of a general value-producing loop/block design, but - here it needs a new target rule: does it exit the loop or the constructor? - A labeled value-break could disambiguate it, at the cost of more syntax. - -The chosen forms are `return self` / `return null`, ordinary loop breaks, and implicit -successful completion at the constructor's closing brace. No magic assignment, -negative-length sentinel, or dedicated finish keyword is required. +Explicit returns keep completion distinct from mutation: assigning null to self +would hide control flow, a negative length would violate the length invariant, +and an ordinary break belongs to the nearest loop. No finish keyword is needed. ## Growing and trimming with `#` -Try extending the existing length notation rather than adding a finish keyword: +Extend the existing length notation during construction: | Expression | Proposed meaning during construction | |---|---| @@ -224,7 +213,7 @@ than the old implementation's possible full extra chunk. No regular read chunk and no final copy remain. Physical alignment or mapped-page slack can remain after trimming; the logical result length is exactly `used`. -## What these examples settle, and what they do not +## Placement and borrowing constraints Floating formatting uses the same extend/fill/trim pattern as direct I/O: remember the current length, extend by enough space for the requested format, @@ -257,3 +246,27 @@ different: references into the removed tail must be gone before that storage is reclaimed or reused. For these byte programs there are no typed interior references, and the native borrow ends before the final trim. Future inline objects need that restriction; non-moving alone does not make shrinking safe. + +## Persistent containers + +Finishable builders and persistent resizable containers have different needs. +A byte stream, rendered string, or parsed number array can end growth at a +lexical boundary. Timers, bitsets, and Canvas pixel buffers grow between unrelated +operations and need an explicit container/storage policy. Consolidating coupled +timer arrays into entries can simplify placement; it does not remove other live +growth at the same stack tip. The storage heuristic may choose another growth +stack, replacement buffers, or report an unsupported layout. + +Backing-array aliases are observable. Replacing `v.buf` or `Canvas.pixels` does +not by itself authorize recycling the old array. An `E[^]` deletable array needs +proof that no usable aliases or raw-address borrows survive deletion. Ordinary +arrays retain their automatic-lifetime behavior. Buddy allocation can reuse the +array header only after this proof; type-compatible element storage alone cannot +make a stale length field safe. These ownership proofs and runtime recycling +remain unimplemented. + +Time formatting should append into a supplied destination. Floating formatting +can use the extend/fill/trim protocol above, with a bounded native helper writing +directly into the destination. Arbitrary interpolation expressions obey ordinary +lifetime and growth-placement rules: a retained inner result can obstruct the +outer array's next extension. diff --git a/chapter33/docs/memory-management.md b/chapter33/docs/memory-management.md new file mode 100644 index 00000000..29461b99 --- /dev/null +++ b/chapter33/docs/memory-management.md @@ -0,0 +1,368 @@ +# Points-to, ownership, and storage + +## Scope and architecture + +Allocation2 computes allocation-site points-to facts after Opto, FinalizeIR, and +LoopTree, before TypeCheck. It is the only allocation-analysis phase. It does +not prove ownership, select storage, insert deletion, or implement recycling. +Separate-compilation analysis is incomplete; its results must not authorize +reclamation yet. + +The design separates three jobs: + +1. Analyze references, ownership/borrows, lifetime boundaries, multiplicity, + object sizes, and interference. +2. Choose storage with a heuristic. Every outcome is a concrete plan or an + explicit unsupported diagnostic. +3. Lower the plan into frame slots, allocations, resets, and reclamation. + +This separation keeps policy changes independent of the safety facts they use. +A may-points-to set records possible aliases; it cannot by itself prove that an +overwrite removed the last usable reference. Temporal proofs need memory order +and reference liveness. Ownership additionally needs relationships between +concrete objects represented by the same allocation site. + +## (1) Points-to analysis + +### Object abstraction and precision + +Each optimized NewNode denotes one abstract Site, potentially representing many +runtime objects. Static constant objects have separate Sites. Distinct NewNodes +of the same class stay distinct. TypeStruct supplies the layout; each Site owns +its reference-field facts, indexed in TypeStruct field order and looked up by +field alias. Array indices share the `[]` field. + +The analysis is interprocedural and context-insensitive over the remaining IR. +Parameters merge live actuals and calls share their callee's result facts. +Earlier inlining supplies context precision by cloning code. There are no +per-call analysis copies. A shared factory therefore has one abstract allocation +even when two calls produce different concrete objects. + +This gives a small finite abstraction with ordinary monotone constraints. The +cost is loss of call-site correlation, array-index precision, and temporal field +contents. A set containing one Site is not proof of one concrete object. +Bounded repetition belongs to earlier optimization: unrolling four allocations +gives four NewNodes; this pass does not add exact-count analysis. + +Recursion is deferred for lifetime placement. Cyclic points-to constraints have +a finite domain, but convergence does not prove a recursive storage policy. +The intended later model treats a recursive call SCC as a loop-like unit. +[Recency abstraction][recency], distinguishing the newest object from older +summary objects, is an optional future precision improvement. + +### Facts and worklist + +```text +P(pointer SSA node) -> set of Sites, plus an outside-storage flag +H(Site, reference field) -> set of Sites, plus an outside-storage flag +Escapes -> local Sites accessible outside, plus outside storage +``` + +Points stores a HashSet of Sites. Null adds no Site; nullability belongs to the +type analysis. The `_unknown` flag denotes storage outside the local collection; +compatible local escapees are separate explicit Sites. An empty local set is +therefore different from an unknown external reference. + +| Operation | Constraint | +|---|---| +| New and its pointer projection | Seed the allocation Site | +| Static object constant | Seed its static Site | +| Pointer Phi / formal parameter | Union live input facts | +| Guard, readonly, construction/init view | Forward pointer facts | +| `p.f = q` | Union P(q) into each possible base Site's field | +| `q = p.f` | Union the corresponding fields of possible base Sites | +| Known loaded call | Actual-to-Parm links; Return-to-call-result links | +| External argument or result | Relate outside storage and compatible escapees; incomplete | + +Stores are weak updates: a Site can represent many concrete objects. Conversely, +multiple aliases to a proven concrete singleton would not prevent a strong +update, because all those aliases observe the same cell. Set cardinality, +number of pointer names, and concrete multiplicity are distinct facts. + +Reading a Points registers the consuming Node. Growing a fact requeues its +readers on util.WorkList; loads and stores discover field dependencies as their +bases grow. Node-keyed tables use identity rather than Node.hashCode, which +participates in GVN locking. The solver uses graph walks for initialization and +dependency-driven propagation thereafter. `verify()` explicitly re-evaluates +constraints and is called by assertions/tests; it is not a second production +analysis pass. Convergence checking is not a soundness proof. + +After solving, reverse field-edge counts identify candidate owning fields. +These counts exclude local SSA aliases and do not prove concrete ownership. +`simple.alloc2.dump` prints Sites, fields, escapes, and pointer facts. + +This is an inclusion-based, field-sensitive analysis with flow-insensitive field +facts. Its finite monotone domain supports worklist solving; broad sets and field +cross-products can still be expensive. Cornell's [alias-analysis lesson][cornell] +provides the standard terminology. + +### Separate compilation and escapes + +FunctionSummary is metadata for an unloaded SummaryNode: signature, optimized +return state, name, size, and class-initialization dependencies. Serialized format +10 (`C0DA`) contains no allocation destinations, consume contracts, or separate +function-write analysis. A body loads when needed for inlining or evaluation. + +An internal call does not publish its callee's FIDX. Class-init dependency edges +serve cycle checking and must not grant unknown callers access. Hidden private +construction memory defaults to unknown contents with empty escape sets; actual +calls still carry initialized field values under the broad declared signature. +Publication of one field uses that field's value, rather than unrelated escapes +from the entire private object. Final singleton-memory constants refresh their +escape sets after recursive type closure has completed. + +Boundary handling still needs work: imported pointer results must include +returned local arguments; escape closure must observe later field growth; +outside writes, raw addresses, and intrinsic calls need explicit treatment. +The current implementation and regression tests expose these gaps. Neither an +unknown result nor a low incoming-edge count permits a lifetime decision. + +Cofinite imported escape sets also need a defined receiving universe. Renaming +only their finite exclusions admits caller-private FIDXs into the infinite tail. +Preserve membership of known remote identities while excluding local identities +from the anonymous remote remainder. Actual local escapes enter through the +caller's escape flow. Today type-table loading occurs during parsing, before all +local identities exist, although SummaryNodes are installed after parsing. +Import ordering and universe rebasing are pending work; ordinary universal type +bounds must retain their meaning. + +### Normalized exits + +LoopTree inserts Never exits before Allocation2 and TypeCheck. FunNode preserves +the semantic return state before adding synthetic control flow, so diagnostics +and serialized summaries do not claim a nonreturning function returns. Rebuilding +the loop tree for scheduling retains existing synthetic exits. Unloaded summary +wrappers remain dispatch metadata and are detached from scheduling roots. + +## (2) Ownership: candidates first, per-instance proofs next + +Reverse field-edge counts fall directly out of points-to. If only abstract +`A.buf` points to B, record the single source as an ownership candidate. Counts +exclude local SSA aliases and must not silently ignore unknown external edges +when someone eventually consumes them as evidence. + +The tempting inference "one reverse edge, therefore A owns B" is unsound for +summary objects. Both heaps below have `A.buf -> {B}`: + +```text +a1.buf = b1; a2.buf = b2; // separate pairings +a1.buf = b1; a2.buf = b1; // shared child +``` + +The missing fact is relational: for every concrete a, a.buf belongs to that a, +and distinct As do not retain the same owned B. Establish this at construction, +then show every write +to the owning field restores it. Temporary aliases are borrows whose usable +lifetimes end before reclamation. Copying the owner pointer is fine; both copies +name the same owning field. Copying the child creates a separate borrow to track. + +For hand-over-hand replacement: + +| Step | Old B | New B | +|---|---|---| +| Entry | retained by v.buf | absent | +| `old = v.buf` | v.buf and old | absent | +| Allocate next, copy | v.buf and old | next | +| `v.buf = next` | old | v.buf and next | +| Last use of next | old | v.buf | +| Last usable reference to old ends | reclaimable | v.buf | + +The straight-line case is deliberately modest. Every reachable mutation, +constructor/helper, and call must preserve the invariant or invalidate the +candidate. A no-growth path can retain the incoming B. A new summary/version +name must not assert a physically new object on that path. Outstanding aliases +such as `saved = v.buf` across grow block old-buffer reclamation; loading v.buf +after grow refers to the current child instead. + +This does not require runtime reference counting. [Alias burying][burying] +explains why temporary aliases need not prevent later uniqueness. Preconditions, +postconditions, and frame reasoning from [separation logic][seplogic] are useful +without adopting a general theorem prover. + +### From one-step ownership to aggregates + +Prove immediate owner edges first. If A owns B and B owns C, ownership composes; +an owner tree plus ancestry queries suffices, without enumerating every pair. +This is not ordinary reachability: + +```text +A.b -> B; A.c -> C; B.c -> C +``` + +A may own B and C, but B does not own C because A.c bypasses B. Detaching B does +not authorize reclaiming C. [Owners-as-dominators][ownership] concerns the +object graph, not the control-flow dominator tree or frame containment tree. + +The next generalization permits internal sharing/cycles within a representation +while controlling access crossing its boundary, as in [external uniqueness][external]. +The ownership hierarchy may be a tree even though heap pointers form a graph. +Whole-aggregate lifetime resembles [region reference counting][regions-rc], but +we are not committing to runtime counts or one arena per owner. + +Examples: v owns its current buffer; Canvas owns its current pixel array; Game +can own its bricks. Breakout's Game and Canvas are separate roots in main; a +drawing helper borrowing Canvas does not transfer ownership. Keeping every +historical buffer in the owner's arena defeats prompt reclamation, so an owned +child must be detachable after its boundary borrows end. + +Pros: a uniform rule for wrappers, canvases, and nested representations, with +cheap transitive composition. Cons: proving the first edge requires temporal +and relational information absent from raw may-points-to sets. Internal sharing +requires a wider boundary proof. Start with paired fields; do not solve general +heap shape merely to handle a resize. + +## (3) Lifetime boundaries and reclamation proofs + +The proposed "frame idom" is a containing allocation-frame relation: function +activation, loop iteration, or suitable single-entry/single-exit region. For +`main: p=make(); use(p);`, make and use are siblings under main; the object can +be allocated in main's frame. Ordinary immediate CFG dominance alone does not +give that lifetime. Calling this a frame LCA avoids conflating the structures. + +Find a common enclosing frame for the allocation and all usable accesses, +including indirect access through fields, returns, and retained aliases. Model +cleanup boundaries, including loop continuation and exits. A call-DAG walk can +propagate these requirements; do not expand the dynamic activation tree. +Interprocedural paths must respect matched calls/returns, not connect a shared +callee return to arbitrary callers. [Realizable-path analysis][realizable] +explains that distinction. Context-insensitive may results may conservatively +include infeasible paths; lifetime reasoning must preserve call/return meaning. + +Multiplicity is relative to the selected frame. A site may need one slot per +iteration yet accumulate many retained objects in the enclosing function: + +```text +head = null; +while (...) head = new Cell(head); +use(head); +``` + +The tiny graph `head -> A; A.next -> A` represents a potentially large list. +The common frame is outside the loop, requiring growth. A known object size +does not prove bounded total demand. "Many/unknown" is conservative, not a proof +that demand is mathematically unbounded. A repeatedly executed site may still +reuse one slot when each previous object's lifetime ends before the next. + +Memory-SSA walks can establish borrow ends through overwrites, calls, and +loop backedges. Propagate checked contracts on the call DAG. Automatic deletion +also needs a selected endpoint; conservative checkpoints suffice initially. +These proofs are not implemented in Allocation2. + +"No usable future reference" is the reclamation condition. It is weaker than +"no pointer bits anywhere": an unused local or a field overwritten before its +next read need not keep storage alive. Mere lexical scope exit is insufficient +if a stored/returned alias remains usable. + +Pros: use memory-SSA reasoning and keep lifetime separate from alias +possibility. Cons: still must connect per-instance ownership and temporal facts +without rebuilding the old parallel reference machinery. The frame tree and +its SESE/cleanup representation remain to be implemented in Allocation2. + +## (4) Storage selection is a separate heuristic + +There need not be a safety theorem saying "stack allocation has become +impossible." Retaining everything in a growing outermost region can often be +safe but wasteful. Lifetime safety and useful bounded-space behavior differ. +Ownership transfer exposes earlier reclamation opportunities; policy decides +whether to exploit them. [Region inference][regions] supplies a lifetime model, +without deciding every allocator tradeoff for us. + +Use an explicit decision tree, initially conservative: + +| Candidate decision | Required facts / tradeoff | +|---|---| +| Fixed slot in the LCA frame | Known size, singleton relative to that frame, sufficient lifetime; simple and cheap | +| Grow at an available open tip | Dynamic size or overlapping instances; allocate at definition, reclaim at owning-frame end; may retain dead intermediates | +| Another growth stack | Competing live growth obstructs one tip; extra stack/metadata cost; fixed-size repetitions are useful candidates, not a hard restriction | +| Free-list/buddy allocation | Hand-over-hand or other proven reuse endpoints; unordered deaths/variable sizes; allocator overhead | +| Unsupported, request rewrite | No plan justified by available facts and policy | + +The policy can improve later. It needs neither an optimal answer nor elaborate +theory up front. All leaves report a decision and reason. Analysis supplies +lifetime bounds, size, multiplicity, ownership/borrow facts, safe reuse points, +and interference. Open-tip availability also depends on prior layout choices, +so the heuristic combines these facts with its current plan. It must never +manufacture a missing lifetime or deletion proof. + +Lowering subsequently reserves slots, passes region destinations where needed, +inserts allocation/reset/drop operations, and handles every exit. Separating it +from analysis makes policy changes and debugging easier. + +## (5) Deletion semantics: zero first, optimize later + +The selected design changes deletion to clear ALL fields, references and +scalars, including final fields. References stored in deletable objects must +admit null. Final means immutable during the live-object protocol; reset of dead +storage is permitted. Bulk zeroing is a natural initial implementation. +Removing redundant clearing is a later optimization with an observability proof. + +Between deletion and reuse, a stale non-array reference sees zeroed fields; +after reuse its backing slot must still have a type-compatible representation. Zeroing eliminates +references discoverable by rereading the deleted object, but cannot revoke +references copied out before deletion. Those retain their own lifetime duties. + +StoreNode's existing `_init` permission bypasses final/readonly store checks, +which is relevant to reset lowering. It is not by itself a complete solution: +load folding, field type bounds, final-field assumptions, and memory ordering +must agree that dead/reset memory can contain zeros. Consider an explicit raw +storage/reset meaning for that permission. Numeric nonzero bounds and array +headers need the same care as reference nullability. + +Non-array stale aliases remain type-safe and readable, so deletion does not by +itself end the backing slot's lifetime. Reusing a readable field as an arbitrary +allocator link is not justified. Arrays instead require proof of no usable +stale access before physical recycling; then the allocator may reuse the old +header, including the length field, as metadata. Auto-inserted deletion likewise +needs the no-remaining-usable-reference proof, not just a one-edge candidate. + +Pros: predictable reset semantics; stale object paths no longer expose the whole +former representation; initially simple bulk clearing. Cons: observable writes, +final/type optimizer changes, and restrictions on reuse with stale aliases. +Keep the chain "prove alias death -> permit header reuse -> buddy allocation" +visible and revisit alternatives if expensive. These semantic and runtime +changes are not implemented by the points-to slice. + +## Remaining implementation + +Complete and review separate-compilation points-to constraints before using +them for lifetime proofs. Then implement paired ownership and borrow endpoints, +containing-frame lifetime and multiplicity facts, the storage decision heuristic, +and reset/reclamation lowering. Native-effect precision and consuming recursion +are separate follow-ups, not prerequisites for choosing this analysis structure. + +Use small semantic assertions as well as fixed-point checks. In particular, +exercise shared factories, weak field stores, loops, pointer arrays, imported +identity functions, escaping object graphs, and callbacks. Keep failing semantic +regressions visible until the corresponding behavior is implemented. + +The [growing-array design](growing-arrays.md) gives scope, return-destination, +and direct-I/O examples for the later storage stage. + +## References + +- [Cornell, Alias Analysis][cornell]: constraints, heap abstraction, sensitivity. + Also the original [pointer-analysis notes][notes]. +- [Tofte and Talpin, Region-Based Memory Management][regions]: lifetime/regions. +- [Balakrishnan and Reps, Recency-Abstraction for Heap-Allocated Storage][recency]: + most-recent versus summary objects; optional precision. +- [Reynolds, Separation Logic][seplogic]: local heap reasoning and contracts. +- [Boyland, Alias Burying][burying]: uniqueness after temporary aliases. +- [Clarke and Wrigstad, External Uniqueness Is Unique Enough][external]: + aggregate boundaries despite internal sharing. +- [Gay and Aiken, Memory Management with Explicit Regions][regions-rc]: + region reference counting; motivation, not a selected runtime scheme. +- [Clarke et al., Ownership Types: A Survey][ownership]: owners-as-dominators + and ownership variants/inference. +- [Reps, Horwitz, and Sagiv, Precise Interprocedural Dataflow Analysis via Graph + Reachability][realizable]: valid call/return paths. + +[cornell]: https://www.cs.cornell.edu/courses/cs6120/2023fa/lesson/10/ +[notes]: https://www.cs.cornell.edu/courses/cs4120/2026sp/notes.html?id=pointer +[regions]: https://ropas.snu.ac.kr/lib/dock/ToTa1997.pdf +[recency]: https://research.cs.wisc.edu/wpis/papers/sas06-recency.pdf +[seplogic]: https://www.cs.cmu.edu/~jcr/seplogic.pdf +[burying]: https://onlinelibrary.wiley.com/doi/abs/10.1002/spe.370 +[external]: https://ics-archive.science.uu.nl/research/techreps/repo/CS-2002/2002-048.pdf +[regions-rc]: https://theory.stanford.edu/~aiken/publications/papers/pldi98a.pdf +[ownership]: https://ilyasergey.net/papers/ownership-survey.pdf +[realizable]: https://www.cs.tufts.edu/comp/150CMP/papers/reps95reachability.pdf diff --git a/chapter33/docs/ownership-analysis-architecture-review.md b/chapter33/docs/ownership-analysis-architecture-review.md deleted file mode 100644 index e804d4b0..00000000 --- a/chapter33/docs/ownership-analysis-architecture-review.md +++ /dev/null @@ -1,79 +0,0 @@ -# Ownership analysis architecture review - -2026-11-23. - -I agree with the broad assessment. Native effects and the Timer rewrite can wait; neither needs to drive this redesign. - -After reading the implementation, I think the main problem is that we discard information in one analysis and reconstruct it in another. Better terminology would help expose that, but we also need clearer boundaries between the questions being answered. - -I would describe the task as: points-to analysis and reference liveness, feeding region inference and checks for safe storage reuse. Alias analysis supplies much of the evidence, but cannot by itself determine when storage can be reclaimed. - -Your solution space looks right, with these additional proof obligations: - -| Storage choice | What must be established | -|---|---| -| Fixed storage reserved in the current or an enclosing frame | Size, sufficient slots for simultaneously needed objects, and a frame lifetime covering every permitted access | -| Dynamically sized storage at a growing stack tip | Lifetime compatibility and an allocation order compatible with contiguous growth and stack reclamation | -| Recycled non-array object slots | Type-safe reuse while old aliases remain valid; backing storage must still outlive those aliases | -| Recycled arrays | No usable access to the old array survives deletion | -| Require a rewrite | The available analysis cannot establish a supported storage arrangement | - -Two additions matter here. Fixed object size does not imply fixed storage demand: one allocation site can produce arbitrarily many simultaneously needed objects. And dynamically sized storage need not have a compile-time size bound, but growth still has ordering constraints—a retained inner allocation can obstruct an outer growing array. - -The first two choices fit the established subject of region inference: infer storage regions and prove that their reclamation respects accesses. Tofte and Talpin give a formal foundation for that separation between lifetime reasoning and runtime regions. [Region-Based Memory Management](https://ropas.snu.ac.kr/lib/dock/ToTa1997.pdf) - -The terminology I would use for our current machinery is: - -| Current concept | Established terminology | -|---|---| -| Possible reference “origins” | Points-to sets over abstract objects | -| `arg3.c` | An access path rooted at a formal parameter | -| Union of everything stored into a field | A flow-insensitive may-points-to relation | -| Following field contents at a memory version | Flow-sensitive points-to analysis | -| Forgetting a field’s previous contents after a definite overwrite | Strong update | -| Retaining both previous and newly stored possibilities | Weak update | -| Substituting arguments and allocations at a call | Instantiation of a procedure summary | -| Proving no usable alias survives | A lifetime/deallocation proof using alias and liveness information | - -These distinctions are standard in pointer analysis; in particular, flow sensitivity determines whether facts distinguish program points. [Cornell’s pointer-analysis notes](https://www.cs.cornell.edu/courses/cs4120/2026sp/notes.html?id=pointer) - -One especially important distinction: strong updates do not require that an object have only one pointer to it. They require that the analysis establish which concrete storage cell is overwritten. Several aliases can all observe that same overwrite. Conversely, a points-to set containing one abstract allocation-site node may represent many concrete objects, so “set size one” alone does not justify a strong update. This is exactly the problem addressed by work on allocation-site abstractions and recency abstractions. [Balakrishnan and Reps](https://research.cs.wisc.edu/wpis/papers/sas06-recency.pdf) - -That distinction should help us avoid making “unique” stand for several different properties. - -The clearest architectural issue is visible in a tiny example: - -```text -old = v.buf; -v.buf = next; -old.del(); -``` - -`Allocation` accumulates both buffers in the field’s possible contents. `ArrayDelete` then follows memory SSA to recover that the field no longer contains `old`. Calls and loops require additional machinery because their summaries have also merged facts from different times. - -The code currently has two reference representations, `Site` and `Ref`, two reference-resolution mechanisms, and two forms of call substitution. Their purposes differ, but the overlap is substantial. `arrayOwned`, outgoing call versions, and loop-entry versions bridge the difference between the representations. - -My inference is that this mismatch accounts for a substantial part of the special cases. - -I would move toward one account of how references and memory change, with separate consumers for placement and deletion. A procedure summary should describe a transformation from incoming memory to outgoing memory, including: - -- Possible returned references and newly allocated objects. -- Fields that may change, and fields definitely overwritten. -- Storage that may be consumed. -- Preconditions and guarantees needed for those operations. - -For `grow(v)`, the useful contract is approximately: the incoming buffer may be consumed; the outgoing buffer is valid; aliases that could access a consumed buffer must not remain usable. The outgoing buffer may be the incoming buffer on the no-growth path. Giving it a new analysis name must not imply that it is a physically distinct allocation. - -That is also where ideas from separation logic are useful: explicit preconditions, postconditions, and reasoning about the portion of memory a procedure affects. We need not adopt a full separation-logic prover to benefit from those distinctions. [Reynolds](https://www.cs.cmu.edu/~jcr/seplogic.pdf) - -A second addition to your assessment is that “no aliases” is stronger than the property we ultimately need. An unused local can still contain the old pointer. A field can contain it if the field is definitely overwritten before any subsequent read. The safety question is whether a future execution can use that reference to access reclaimed storage. - -That introduces reference liveness alongside points-to information. A conservative first implementation can reject whenever it finds a surviving reference, but the architecture should make clear that this is an approximation. Otherwise every improvement in recognizing dead aliases becomes another ownership exception. - -The non-array deletion semantics deserve a separate, explicit rule. Because old references remain usable, deleting an object does not end the lifetime of its backing slot. It makes the slot eligible for reuse under the language’s historical-value rules. References recoverable from those permitted historical values also retain lifetime obligations. Arrays instead require the proof that old access has ended before recycling. Both can use the same alias information, but their reuse conditions are fundamentally different. - -Finally, loops need a stated abstraction for repeated allocations. One abstract object per allocation site conflates successive objects. Our loop versions are already attempting to recover that distinction. Recency abstraction—separating the most recent object from older objects—is a relevant established option, though we should evaluate whether it fits our cases rather than adopt it automatically. - -I would start the redesign with a small abstract semantics: what an abstract object denotes, what information a memory state contains, the rules for loads/stores/calls/joins, and the exact conditions for reclamation and reuse. Then work the existing two-grow and loop-winner examples through those rules by hand. - -The simplification target is that initializers, ordinary helpers, consecutive grows, and loop iterations follow those same rules. That would give us a theoretical explanation for accepted programs, and a precise description of where our chosen approximation requires the user to rewrite. diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java deleted file mode 100644 index 2c0d4664..00000000 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java +++ /dev/null @@ -1,1147 +0,0 @@ -package com.seaofnodes.simple.codegen; - -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.*; -import com.seaofnodes.simple.util.SB; -import com.seaofnodes.simple.util.BAOS; -import com.seaofnodes.simple.parser.Parser; -import java.util.*; - -/** First allocation-lifetime experiment. Builds plans, not machine allocations. - * One DFS of the call DAG: discover callees on entry, compose their symbolic - * summaries on exit. No call-tree expansion, caller rewalk, or IR mutation. - * Within a summary, reference edges propagate destination requirements with a - * small worklist. A rejected summary is never a usable allocation plan. - */ -public final class Allocation { - private final Summary[] _summaries; - private final Summary _entrySummary; - private final ArrayList<Summary> _postorder = new ArrayList<>(); - public final ArrayList<ArrayDelete> _deletes = new ArrayList<>(); - - // Destination bits: result, static storage, Call/Parm input indices, then - // borrowed field paths. A child's storage need not share its holder's owner. - private static final int RESULT=0, STATIC=1; - - /** One abstract storage object. Imported allocations are distinct per call - * site; a parameter denotes borrowed storage, not an allocation to move. */ - public static final class Site { - public final NewNode _allocation; // null for borrowed/static storage or unloaded allocations - public final int _arg; // >=2: Parm index, -1: static, 0: fresh/path - public final String _name; - public final long _bytes; // snapshot before later IR rewrites - public final boolean _fresh; // also true for allocations in unloaded bodies - private final boolean _buddy; - public final BitSet _owners = new BitSet(); - public final HashMap<String,HashSet<Site>> _fields = new HashMap<>(); - public Summary _frame; // activation creating this object - public Summary _scope; // scratch frame, null for an external destination - private CFGNode _birth; // allocation control, or importing call - private final ArrayList<String> _destinations; - private final HashMap<String,Site> _loads = new HashMap<>(); - Site _base; // borrowed field origin, e.g. arg3.c - String _field; - private int _depth; - - private Site(Summary sum, NewNode allocation, int arg, String name) { - this(sum,allocation,arg,name, - allocation!=null && allocation.size()._type instanceof TypeInteger size && size.isConstant() ? size.value() : -1, - allocation!=null,allocation!=null && allocation._deletable); - } - private Site(Summary sum, NewNode allocation, int arg, String name, long bytes, boolean fresh, boolean buddy) { - _allocation=allocation; _arg=arg; _name=name; - _destinations=sum._destinations; - _bytes=bytes; _fresh=fresh; _buddy=buddy; - if( arg>=2 ) _owners.set(arg); - if( arg==-1 ) _owners.set(STATIC); - } - - public String destination() { - if( buddy() ) return "buddy"; - if( _owners.isEmpty() ) return _scope==null || _scope._loop==null ? "frame" : _scope.name()+" iteration"; - SB sb = new SB(); - if( _owners.get(RESULT) ) sb.p("result & "); - if( _owners.get(STATIC) ) sb.p("static & "); - ArrayList<String> names = new ArrayList<>(); - for( int i=_owners.nextSetBit(2); i>=0; i=_owners.nextSetBit(i+1) ) - names.add(_destinations.get(i)); - Collections.sort(names); // Paths are discovered in arbitrary order. - for( String name : names ) sb.p(name).p(" & "); - return sb.unchar(3).toString(); - } - - public boolean buddy() { return _buddy; } - } - - /** Symbolic summary, with separate destinations for separate arguments. - * Object fields are weak updates: all stored references remain possible. - * Borrowed field paths describe incoming contents separately from stores. */ - - // An activation summary: a function or one loop iteration. Loops share their - // enclosing function's SSA/Site vocabulary, so composition needs no cloning - // or argument substitution. Calls substitute that vocabulary in compose(). - public static final class Summary { - public final FunNode _fun; // owning function, also for loop frames - public final LoopNode _loop; // null for a function activation - public Summary _parent; - public final ArrayList<Summary> _frames = new ArrayList<>(); - public final ArrayList<Site> _sites = new ArrayList<>(); - // Ports map formal/output identity to its value. Loop Phis are entry - // and continuation ports; captured SSA values name themselves. Memory - // ports are included; their retention effects are summarized below. - public final IdentityHashMap<Node,Node> _entry = new IdentityHashMap<>(); - public final IdentityHashMap<Node,Node> _exit = new IdentityHashMap<>(); - public final IdentityHashMap<Node,Node> _next = new IdentityHashMap<>(); - public final HashSet<Site> _returns = new HashSet<>(); - public final HashSet<Site> _retained = new HashSet<>(); - public final HashSet<Site> _continues = new HashSet<>(); - public final HashSet<Site> _scratch = new HashSet<>(); - public final ArrayList<ArrayDelete.Consume> _consumes = new ArrayList<>(); - boolean _opaqueEffects; // raw/native effects absent from the field graph - private final HashSet<Site> _escapes = new HashSet<>(); - public String _reject; - private byte _state; // 0 pre/unseen, 1 mid/active DFS, 2 post/complete - private byte _ownershipState; - private boolean _ownershipCycle; - // All allocation-interesting Nodes; Calls, Stores, News, Ptr ops - private final ArrayList<Node> _nodes = new ArrayList<>(); - // Just the Calls - private final ArrayList<CallNode> _calls = new ArrayList<>(); - // Pointer expression -> possible storage objects, in this function's vocabulary. - private final IdentityHashMap< Node,HashSet<Site>> _values; - // Call -> returned storage after substituting actuals and closing effects. - private final IdentityHashMap<CallNode,HashSet<Site>> _results; - private final BitSet _resolved; - private final BitSet _raw; // Scalar expressions feeding lexical lifetime endpoints - private final IdentityHashMap<LoopNode,Summary> _loops = new IdentityHashMap<>(); - private final ArrayList<String> _destinations; - private Site _static; - private int _pathLimit; // own reads plus the path depths imported at calls - private boolean _changed; - - private Summary(FunNode fun) { - _fun=fun; _loop=null; - _values=new IdentityHashMap<>(); - _results=new IdentityHashMap<>(); - _resolved=new BitSet(); - _raw=new BitSet(); - _destinations=new ArrayList<>(List.of("result","static")); - _static=new Site(this,null,-1,"static"); - } - private Summary(Summary fun, LoopNode loop) { - _fun=fun._fun; _loop=loop; - _values=fun._values; _results=fun._results; _resolved=fun._resolved; - _raw=fun._raw; - _destinations=fun._destinations; _static=fun._static; - } - public String name() { return _loop!=null ? "loop#"+_loop._nid : _fun==null ? "saved contract" : _fun.label(); } - // Hit the end of summary findings with no errors. - public boolean supported() { return _state==2 && _reject==null; } - // Throw or return valid summary - public Summary requireSupported() { - if( !supported() ) throw new IllegalStateException("Allocation "+name()+": "+_reject); - return this; - } - // Collect first rejection - private void reject(String why) { if( _reject==null ) _reject=why; } - } - - public Allocation(CodeGen code) { - _summaries = new Summary[code._linker._len]; - Summary entry=null; - for( FunNode fun : code._linker ) - if( fun!=null && !fun.isDead() && !fun._type.isHigh() ) { - Summary sum=new Summary(fun); - _summaries[fun.sig().fidx()] = sum; - if( code.entryClinitName().equals(fun._name) ) entry=sum; - } - _entrySummary=entry; - for( Summary sum : _summaries ) - if( sum!=null ) - visit(sum); - // Callees precede callers. Discharged requirements disappear; incoming - // ones become the caller's own contract. This is separate from placement. - for( Summary sum : _postorder ) ownership(sum); - } - - private void ownership(Summary sum) { - if( sum._ownershipState==2 ) return; - if( sum._ownershipState==1 ) { sum._ownershipCycle=true; return; } - sum._ownershipState=1; - for( CallNode call : sum._calls ) { - if( call.fptr()._type instanceof TypeFunPtr fp && !XInt.isHigh(fp.fidxs()) ) - for( int fidx=XInt.next(fp.fidxs(),0); fidx>=0; fidx=XInt.next(fp.fidxs(),fidx) ) { - Summary callee=fidx<_summaries.length ? _summaries[fidx] : null; - if( callee!=null ) { ownership(callee); sum._ownershipCycle |= callee._ownershipCycle; } - } - } - for( CallNode call : sum._calls ) { - if( Intrinsic.arrayDelete(call) && Intrinsic.arrayDeleteType(call.tfp()) && call.nargs()==1 ) - consume(sum,new ArrayDelete(this,sum._nodes,call,2)); - else if( call.fptr()._type instanceof TypeFunPtr fp && !XInt.isHigh(fp.fidxs()) ) - for( int fidx=XInt.next(fp.fidxs(),0); fidx>=0; fidx=XInt.next(fp.fidxs(),fidx) ) { - Summary callee=fidx<_summaries.length ? _summaries[fidx] : null; - if( callee!=null ) - for( ArrayDelete.Consume requirement : new ArrayList<>(callee._consumes) ) - consume(sum,new ArrayDelete(this,sum._nodes,call,requirement)); - } - } - sum._ownershipState=2; - } - - private void consume(Summary sum, ArrayDelete check) { - // Recursive SCC heads need the same entry/outgoing ownership boundary - // as loop heads. Their allocation graphs are not built yet; do not - // assume a consuming requirement also proves a unique outgoing field. - if( sum._ownershipCycle ) check._reject="recursive consuming contracts are not supported"; - _deletes.add(check); - if( check._reject==null && check._requirement!=null && !sum._consumes.contains(check._requirement) ) - sum._consumes.add(check._requirement); - } - - void checkOwnership() { - // A first-class callback type does not yet carry consuming paths. - // Do not let it erase a requirement established on a concrete function. - for( Summary sum : _postorder ) for( CallNode call : sum._calls ) { - TypeFunPtr target=call.fptr()._type instanceof TypeFunPtr fp ? fp : null; - int first=target!=null && target.nargs()>0 && target.arg(0)==TypePtr.PTR ? 3 : 2; - for( int i=first; i<call.nIns()-1; i++ ) { - Type arg=call.arg(i)._type; - int[] callbacks=arg instanceof TypeFunPtr fp ? fp.fidxs() : - nativeCall(call) && arg instanceof TypeMemPtr ? TypeMem.START.escapesFrom(arg)._escFs : XInt.EMPTY; - if( callbacks!=XInt.EMPTY ) for( Summary callee : _summaries ) - if( callee!=null && !callee._consumes.isEmpty() && XInt.bit(callbacks,callee._fun.sig().fidx()) ) - throw Parser.error("Consuming callback requires an explicit ownership contract",call._loc); - if( (target==null || XInt.isHigh(target.fidxs())) && deletableStorage(arg,new HashSet<>()) ) - throw Parser.error("Unknown call cannot verify ownership of deletable storage",call._loc); - } - } - } - - private static boolean deletableStorage(Type t, HashSet<Type> seen) { - if( !seen.add(t) || !(t instanceof TypeMemPtr ptr) ) return false; - if( ptr._del ) return true; - if( ptr._obj._fields!=null ) - for( Field field : ptr._obj._fields ) if( deletableStorage(field._t,seen) ) return true; - return false; - } - - public Summary summary(String name) { - for( Summary sum : _summaries ) - if( sum!=null && name.equals(sum._fun._name) ) return sum; - throw new IllegalArgumentException("No allocation summary for "+name); - } - - Summary summary(FunNode fun) { return _summaries[fun.sig().fidx()]; } - - // Boundary contracts contain symbolic storage, never graph node IDs or - // implementation frames. Site zero is static storage. Local scratch is - // omitted; only external destinations and their reference graph survive. - static void write(BAOS out, Summary sum) { - assert sum._state==2; - out.packed4(sum._consumes.size()); - for( ArrayDelete.Consume consume : sum._consumes ) { - out.packed4(consume.arg()); out.packed4(consume.path().size()); - for( String field : consume.path() ) out.packedS(field); - } - out.packed1(sum._opaqueEffects ? 1 : 0); - out.packedS(sum._reject==null ? "" : sum._reject); - if( !sum.supported() ) return; - out.packed4(sum._destinations.size()); - for( String name : sum._destinations ) out.packedS(name); - ArrayList<Site> sites=new ArrayList<>(); - HashMap<Site,Integer> ids=new HashMap<>(); - ids.put(sum._static,0); - sites.add(sum._static); - for( Site site : sum._sites ) - if( site!=sum._static && !site._owners.isEmpty() ) { - ids.put(site,sites.size()); sites.add(site); - } - // Include field/path dependencies even when they have no destination - // of their own. Assign IDs before writing so cycles need no recursion. - for( int i=0; i<sites.size(); i++ ) { - Site site=sites.get(i); - if( site._base!=null && !ids.containsKey(site._base) ) { - ids.put(site._base,sites.size()); sites.add(site._base); - } - for( HashSet<Site> values : site._fields.values() ) - for( Site child : values ) if( !ids.containsKey(child) ) { - ids.put(child,sites.size()); sites.add(child); - } - } - out.packed4(sites.size()); - for( Site site : sites ) { - out.packed4(site._arg); out.packedS(site._name); - out.packed8(site._bytes); - out.packed1((site._fresh ? 1 : 0) | (site.buddy() ? 2 : 0)); - out.packed4(site._owners.cardinality()); - for( int bit=site._owners.nextSetBit(0); bit>=0; bit=site._owners.nextSetBit(bit+1) ) out.packed4(bit); - } - for( Site site : sites ) { - out.packed4(site._base==null ? -1 : ids.get(site._base)); - if( site._base!=null ) out.packedS(site._field); - out.packed4(site._depth); - out.packed4(site._fields.size()); - for( var field : site._fields.entrySet() ) { - out.packedS(field.getKey()); out.packed4(field.getValue().size()); - for( Site child : field.getValue() ) out.packed4(ids.get(child)); - } - } - out.packed4(sum._returns.size()); - for( Site site : sum._returns ) out.packed4(ids.get(site)); - } - - static Summary read(BAOS in) { - Summary sum=new Summary((FunNode)null); - sum._state=2; - int consumes=in.packed4(); - for( int i=0; i<consumes; i++ ) { - int arg=in.packed4(), count=in.packed4(); - ArrayList<String> path=new ArrayList<>(); - for( int j=0; j<count; j++ ) path.add(in.packedS()); - sum._consumes.add(new ArrayDelete.Consume(arg,path)); - } - sum._opaqueEffects=in.packed1()!=0; - String reject=in.packedS(); - if( !reject.isEmpty() ) { sum.reject(reject); return sum; } - sum._destinations.clear(); - int names=in.packed4(); - for( int i=0; i<names; i++ ) sum._destinations.add(in.packedS()); - int count=in.packed4(); - for( int i=0; i<count; i++ ) { - int arg=in.packed4(); String name=in.packedS(); - long bytes=in.packed8(); int flags=in.packed1(); - Site site=new Site(sum,null,arg,name,bytes,(flags&1)!=0,(flags&2)!=0); - site._owners.clear(); - int owners=in.packed4(); - for( int j=0; j<owners; j++ ) site._owners.set(in.packed4()); - sum._sites.add(site); - } - sum._static=sum._sites.get(0); - for( Site site : sum._sites ) { - int base=in.packed4(); - if( base>=0 ) { - site._base=sum._sites.get(base); site._field=in.packedS(); - site._base._loads.put(site._field,site); - } - site._depth=in.packed4(); - int fields=in.packed4(); - for( int j=0; j<fields; j++ ) { - String field=in.packedS(); int size=in.packed4(); - HashSet<Site> values=new HashSet<>(); - for( int k=0; k<size; k++ ) values.add(sum._sites.get(in.packed4())); - site._fields.put(field,values); - } - } - int returns=in.packed4(); - for( int i=0; i<returns; i++ ) sum._returns.add(sum._sites.get(in.packed4())); - // Retention is represented by stores through incoming/static sites. - for( Site site : sum._sites ) if( !site._fresh ) - for( HashSet<Site> children : site._fields.values() ) sum._retained.addAll(children); - return sum; - } - - public void requireSupported() { - for( Summary sum : _postorder ) - sum.requireSupported(); - } - - /** Analysis-only deletion checkpoint. No storage is freed. A proof about - * incoming storage also reports the unique-entry contract still required. */ - public ArrayDelete checkArrayDelete(CallNode call, int arg) { - for( Summary sum : _postorder ) - if( sum._calls.contains(call) ) return new ArrayDelete(this,sum._nodes,call,arg); - throw new IllegalArgumentException("Deletion checkpoint is not in an analyzed body"); - } - - // A deliberately narrow helper contract: pointer fields are not changed, - // and the result is scalar or forwards known arguments. Scalar element - // copies, including loops, qualify. Scalar results need only effects; - // reference results also require an allocation contract for their origins. - boolean arrayBorrow(CallNode call) { - // A nonreturning call contributes no retained references to its caller. - if( call.cend()._type instanceof TypeTuple tt && tt.mem()==TypeMem.TOP ) return true; - if( nativeCall(call) ) return false; // No pointer-memory effect contract yet. - Summary sum=target(call); - if( sum==null || sum._fun._extern ) return false; - Type ret=sum._fun.ret().expr()._type; - if( !(ret instanceof TypeInteger || ret instanceof TypeFloat) && arrayResult(call)==null ) return false; - return noReferenceEffects(sum._fun); - } - - // Direct argument forwarding is enough for copy/identity helpers. Field - // paths and fresh return storage are serialized too, but their deletion - // proofs need richer memory-origin queries before allowing these borrows. - ArrayList<Node> arrayResult(CallNode call) { - Summary sum=target(call); - if( sum==null || !sum.supported() ) return null; - ArrayList<Node> args=new ArrayList<>(); - for( Site site : sum._returns ) { - if( site._arg<2 || site._arg>=call.nIns()-1 ) return null; - args.add(call.arg(site._arg)); - } - return args; - } - - // Repeated consumption also needs an exclusive outgoing slot. Consuming - // the entry value alone does not promise that: a helper could publish its - // replacement into a second field before returning. The existing boundary - // graph (including imported graphs) suffices for this narrow proof. - boolean arrayOwned(CallNode call, ArrayDelete.Consume consume) { - return arrayOwned(target(call),consume); - } - - private static boolean arrayOwned(Summary sum, ArrayDelete.Consume consume) { - if( sum==null || !sum.supported() || sum._opaqueEffects || consume.path().isEmpty() ) return false; - Site owner=null; - for( Site site : sum._sites ) if( site._arg==consume.arg() ) owner=site; - if( owner==null ) return false; - for( int i=0; i<consume.path().size()-1; i++ ) { - String field=consume.path().get(i); - Set<Site> stored=owner._fields.get(field); - Site incoming=owner._loads.get(field); - if( stored!=null && !stored.isEmpty() ) { - if( stored.size()!=1 || incoming!=null && !stored.contains(incoming) ) return false; - owner=stored.iterator().next(); - } else owner=incoming; - if( owner==null ) return false; - } - String field=consume.path().getLast(); - HashSet<Site> values=new HashSet<>(); - Set<Site> stored=owner._fields.get(field); - if( stored!=null ) values.addAll(stored); - Site incoming=owner._loads.get(field); - if( incoming!=null ) values.add(incoming); - for( Site value : values ) { - if( value!=incoming && !value._fresh || sum._returns.contains(value) ) return false; - for( Site site : sum._sites ) for( var edge : site._fields.entrySet() ) - if( edge.getValue().contains(value) && (site!=owner || !edge.getKey().equals(field)) ) return false; - } - return true; - } - - boolean arrayBorrow(CLInitNode init) { - return init.bypass() || noReferenceEffects(CodeGen.CODE.link(init.cu())); - } - - private static boolean noReferenceEffects(FunNode fun) { - FunctionEffects effects=CodeGen.CODE._effects.get(fun); - return effects!=null && !effects._referenceWrites; - } - - private void visit(Summary sum) { - if( sum._state==2 ) return; // Post-order, done - // Mid-visit, so found a Call Graph cycle, i.e. recursion - if( sum._state==1 ) { - // Recursive SCC/mega-call work goes here; do not expand a call tree. - sum.reject("recursive call component"); - return; - } - // Was pre-order, now mid-order - sum._state=1; - if( sum._fun.summary()!=null && sum._fun.summary()._allocation!=null ) { - Summary contract=sum._fun.summary()._allocation; - sum._reject=contract._reject; - sum._destinations.clear(); sum._destinations.addAll(contract._destinations); - sum._static=contract._static; - sum._sites.addAll(contract._sites); - sum._returns.addAll(contract._returns); - sum._retained.addAll(contract._retained); - sum._consumes.addAll(contract._consumes); - sum._opaqueEffects=contract._opaqueEffects; - } else if( sum._fun._extern || sum._fun.summary()!=null ) { - sum.reject("opaque body: allocation contract unavailable"); - } else { - // Collection interesting function body and call sites - collect(sum); - for( Node n : sum._nodes ) - if( n instanceof PtrToIntNode || n instanceof CLInitNode init && !arrayBorrow(init) ) sum._opaqueEffects=true; - for( CallNode call : sum._calls ) { - if( nativeCall(call) ) { - if( !Intrinsic.pure(call) && !Intrinsic.arrayDelete(call) && - !(call.cend()._type instanceof TypeTuple tt && tt.mem()==TypeMem.TOP) ) sum._opaqueEffects=true; - // Native code borrows its arguments for this call only. - // Returned storage still needs an explicit origin contract. - Type ret=call.tfp().ret(); - if( !(ret instanceof TypeInteger || ret instanceof TypeFloat) ) - sum.reject("native result storage has no allocation contract at call #"+call._nid); - continue; - } - Summary callee = target(call); - if( callee==null ) sum.reject("opaque or indirect call #"+call._nid); - else { - // Recursive walk Call Graph DAG - visit(callee); - sum._opaqueEffects |= callee._opaqueEffects; - // If some callee is rejected, so is this caller - if( callee._reject!=null ) - sum.reject("call #"+call._nid+" -> "+callee._fun.label()+": "+callee._reject); - } - } - if( sum._reject==null ) - build(sum); - } - // Postder - sum._state=2; - _postorder.add(sum); - } - - Summary target(CallNode call) { - if( !(call.fptr()._type instanceof TypeFunPtr fp) || !fp.isConstant() ) return null; - int idx=fp.fidx(); - return idx>=0 && idx<_summaries.length ? _summaries[idx] : null; - } - - // Unlike external(), this excludes unknown targets and mixed Simple/native - // target sets. Every possible target must obey the native borrowing rule. - private static boolean nativeCall(CallNode call) { - if( !(call.fptr()._type instanceof TypeFunPtr fp) || XInt.isHigh(fp.fidxs()) || fp.nfcns()==0 ) return false; - for( int idx=XInt.next(fp.fidxs(),-1); idx>=0; idx=XInt.next(fp.fidxs(),idx) ) - if( CodeGen.CODE.externFunc(idx)==null ) return false; - return true; - } - - // Follow control, memory, and references, not arithmetic/offset expressions. - // Find allocations at control anchors too: their only remaining use might - // be a scalar load or a raw address buried under arithmetic. Don't walk into - // other functions, so no following linked Calls or Parms. - private void collect(Summary sum) { - BitSet seen = new BitSet(); - ArrayDeque<Node> work = new ArrayDeque<>(); - // Start at both ends: zero-exit loops cannot be reached from Return. - work.push(sum._fun.ret()); - work.push(sum._fun); - // Repeat until entire function is walked - while( !work.isEmpty() ) { - Node n = work.pop(); - if( seen.get(n._nid) ) continue; // Been there, done that - seen.set(n._nid); - // Add to function body - sum._nodes.add(n); - if( n instanceof CFGNode cfg && !(cfg instanceof ReturnNode) && - (cfg==sum._fun || !cfg.isFunLeaf()) ) - for( Node use : cfg._outputs ) - if( use instanceof CFGNode next && !cfg.skip(next) ) work.push(next); - if( n instanceof CFGNode ) - for( Node use : n._outputs ) - if( use instanceof NewNode alloc && alloc.ctrl()==n || - use instanceof ParmNode parm && parm.fun()==sum._fun ) - work.push(use); - // Reference uses stay within this function; Parm call links and - // constant/global anchors are boundaries. In particular, find raw - // conversions without following their scalar arithmetic users. - if( !n.isFunLeaf() || n instanceof ParmNode ) - for( Node use : n._outputs ) - if( use instanceof PtrToIntNode || pointer(use) && !use.isFunLeaf() ) - work.push(use); - if( n.isFunLeaf() ) continue; - if( n instanceof CallNode call ) sum._calls.add(call); - if( n instanceof LoopNode loop ) sum._loops.put(loop,new Summary(sum,loop)); - - // CLInit accesses static state, not caller parameters. Its body is - // analyzed separately; stores publishing local objects to static - // state already give those objects the static destination. Do not - // mistake an own-class initialization guard for recursive calling. - if( n instanceof CallEndNode cend ) { work.push(cend.call()); continue; } - - // Walk selected edges. We can skip pure-data ops, but need to - // walk both control and memory at least. - for( Node in : n._inputs ) - if( in!=null && (in instanceof CFGNode || in.isMem() || - in._type instanceof TypeMem || pointer(in) || in instanceof NewNode) ) - work.push(in); - } - keepOrigins(sum,seen); - } - - // Follow the scope endpoint backwards, not all uses of an integer address. - // Memory round trips and wrapper calls need no provenance: the original - // conversion is kept here until its own lexical scope ends. - private static void keepOrigins(Summary sum, BitSet seen) { - ArrayDeque<Node> work=new ArrayDeque<>(); - for( Node n : sum._nodes ) if( n instanceof KeepAliveNode ) work.push(n.in(1)); - while( !work.isEmpty() ) { - Node n=work.pop(); - if( pointer(n) || n instanceof ConstantNode || n instanceof CFGNode || - n instanceof LoadNode || n.isFunLeaf() || - n instanceof ProjNode || sum._raw.get(n._nid) ) continue; - sum._raw.set(n._nid); - if( !seen.get(n._nid) ) { seen.set(n._nid); sum._nodes.add(n); } - for( Node in : n._inputs ) if( in!=null ) work.push(in); - } - } - // Post-order work during the Call Graph visit - private void build(Summary sum) { - loopFrames(sum); - for( Node n : sum._nodes ) { - // Gather allocation sites - if( n instanceof NewNode alloc ) { - if( !alloc._deletable && (!(alloc.size()._type instanceof TypeInteger size) || !size.isConstant()) ) - sum.reject("variable-size allocation #"+alloc._nid); - Site site = new Site(sum,alloc,0,"new#"+alloc._nid+":"+alloc._ts._name); - site._birth=(CFGNode)alloc.ctrl(); - if( TypeStruct.startsClzPrefix(alloc._ts._name) ) site._owners.set(STATIC); - sum._sites.add(site); - sum._values.put(alloc,set(site)); - } - if( n instanceof ParmNode parm && pointer(parm) ) { - if( parm.fun()!=sum._fun ) sum.reject("foreign parameter #"+parm._nid); - while( sum._destinations.size()<=parm._idx ) - sum._destinations.add("arg"+sum._destinations.size()); - Site site = new Site(sum,null,parm._idx,"arg"+parm._idx+":"+parm.label()); - sum._sites.add(site); - sum._values.put(parm,set(site)); - } - if( n instanceof LoadNode && pointer(n) ) sum._pathLimit++; - } - // Import fresh storage once per call, even though its reference edges - // may need several local rounds. No repeated walk of a callee's IR. - IdentityHashMap<CallNode,IdentityHashMap<Site,HashSet<Site>>> imports=new IdentityHashMap<>(); - for( CallNode call : sum._calls ) { - if( nativeCall(call) ) continue; - Summary callee=target(call); - IdentityHashMap<Site,HashSet<Site>> map=new IdentityHashMap<>(); - imports.put(call,map); - sum._results.put(call,new HashSet<>()); - map.put(callee._static,set(sum._static)); - int depth=0; - for( Site site : callee._sites ) { - depth=Math.max(depth,site._depth); - if( site==callee._static ) continue; - HashSet<Site> values=new HashSet<>(); - if( site._fresh && !site._owners.isEmpty() ) { - Site copy=new Site(sum,site._allocation,0,"call#"+call._nid+"/"+site._name,site._bytes,true,site.buddy()); - copy._birth=call; - if( site._owners.get(STATIC) ) copy._owners.set(STATIC); - sum._sites.add(copy); - values.add(copy); - } - map.put(site,values); - } - sum._pathLimit+=depth; - } - - // Loads, stores, and call effects depend on each other. Solve their weak - // unions before assigning owners: caching an early empty load would lose - // a later-discovered store. Targets, fields, and call results grow - // monotonically, including cyclic loop Phis. Each expression is visited - // once per round; a cycle uses the targets discovered so far. - do { - sum._changed=false; - sum._resolved.clear(); - for( CallNode call : sum._calls ) if( !nativeCall(call) ) compose(sum,call,imports.get(call)); - for( Node n : sum._nodes ) { - if( pointer(n) || sum._raw.get(n._nid) ) refs(sum,n); - if( n instanceof StoreNode store && pointer(store.val()) ) - if( edge(refs(sum,store.ptr()),store._name,refs(sum,store.val())) ) sum._changed=true; - } - if( pointer(sum._fun.ret().expr()) && sum._returns.addAll(refs(sum,sum._fun.ret().expr())) ) sum._changed=true; - } while( sum._changed && sum._reject==null ); - for( Site site : sum._returns ) site._owners.set(RESULT); - if( !sum._static._fields.isEmpty() ) sum._sites.add(sum._static); - - // Local closure only: an object retained in a destination retains its - // referenced objects there too. Cyclic object graphs need no DAG rewalk. - ArrayDeque<Site> work=new ArrayDeque<>(sum._sites); - while( !work.isEmpty() ) { - Site src = work.pop(); - for( Set<Site> values : src._fields.values() ) - for( Site dst : values ) { - int before = dst._owners.cardinality(); - dst._owners.or(src._owners); // Union owners set - if( dst._owners.cardinality() != before ) work.push(dst); - } - } - if( sum._reject==null ) { - frameBoundaries(sum); - summarizeFrame(sum,sum,imports); - if( sum._reject==null ) placeFrames(sum); - } - // Bin packing goes here: fixed destinations become caller landing zones. - // Free-list work goes here: only after checking remaining usable aliases. - // Parallel growing tips go here: one owner may need several storage areas. - } - - // n has pointer type - private static boolean pointer(Node n) { - return n!=null && (n._type instanceof TypeMemPtr || n._type instanceof TypePtr); - } - - // LoopTree already establishes reducible nesting and each CFG's tightest - // containing loop. Allocation only supplies the corresponding frame summaries. - private static void loopFrames(Summary sum) { - for( Summary frame : sum._loops.values() ) { - CFGNode.LoopTree tree=frame._loop._ltree; - assert tree!=null && tree._head==frame._loop && tree._par!=null; - frame._parent=tree._par._head instanceof StartNode ? sum : sum._loops.get(tree._par._head); - assert frame._parent!=null : "Missing enclosing loop summary"; - frame._parent._frames.add(frame); - } - } - - // Everything reachable through stored references. Used both for backedge - // safety and for retaining a winner's entire object graph on loop exit. - private static HashSet<Site> reachable(HashSet<Site> roots) { - HashSet<Site> seen=new HashSet<>(roots); - ArrayDeque<Site> work=new ArrayDeque<>(roots); - while( !work.isEmpty() ) - for( HashSet<Site> children : work.pop()._fields.values() ) - for( Site child : children ) - if( seen.add(child) ) work.push(child); - return seen; - } - - // A store to storage not born in this iteration can carry its value into - // the next iteration. Stores within an iteration's private graph are fine; - // a surviving root will bring that entire graph into reachable() instead. - private static void retained(HashSet<Site> dst, HashSet<Site> src, - HashSet<Site> born, HashSet<Site> carried) { - for( Site base : dst ) - if( !born.contains(base) ) { carried.addAll(src); return; } - } - - // Memory reaching the backedge exposes stores that a pointer-Phi check alone - // misses, e.g. an array allocated before the loop collecting each candidate. - // Stop at this header: entry memory and exit-only stores do not execute on - // the repeated path. Weak updates deliberately do not kill earlier stores. - private static ArrayList<Node> backMemory(LoopNode loop) { - ArrayList<Node> nodes=new ArrayList<>(); - BitSet seen=new BitSet(); - ArrayDeque<Node> work=new ArrayDeque<>(); - for( Node use : loop._outputs ) - if( use instanceof PhiNode phi && phi.region()==loop && phi._type instanceof TypeMem ) - work.push(phi.in(2)); - while( !work.isEmpty() ) { - Node n=work.pop(); - if( seen.get(n._nid) ) continue; - seen.set(n._nid); - if( n instanceof PhiNode phi && phi.region()==loop ) continue; - if( n instanceof ParmNode || n.isFunLeaf() ) continue; - nodes.add(n); - if( n instanceof ProjNode proj ) work.push(proj.in(0)); - else if( n instanceof CallEndNode end ) work.push(end.call()); - else for( Node in : n._inputs ) - if( in!=null && in._type instanceof TypeMem ) work.push(in); - } - return nodes; - } - - private static Summary enclosing(Summary sum, CFGNode ctrl) { - if( ctrl==null || ctrl._type.isHigh() ) return sum; - assert ctrl._ltree!=null : "Missing LoopTree for CFG #"+ctrl._nid; - if( ctrl._ltree._head instanceof StartNode ) return sum; - Summary frame=sum._loops.get(ctrl._ltree._head); - assert frame!=null : "Missing loop summary for CFG #"+ctrl._nid; - return frame; - } - - // Earliest control for a boundary value/use, without scheduling or changing - // the IR. New's pointer AND private-memory projections inherit its control. - // Floating scalar calculations can finish before returning from a frame; - // only their scalar result then crosses the boundary. - static CFGNode control(Node n, IdentityHashMap<Node,CFGNode> cache, BitSet active) { - if( n instanceof CFGNode cfg ) return cfg; - if( n instanceof PhiNode phi ) return phi.region(); - if( n.isFunLeaf() ) return null; - if( cache.containsKey(n) ) return cache.get(n); - if( active.get(n._nid) ) return CFGNode.safeCFG(n); - active.set(n._nid); - CFGNode ctrl=null; - for( Node in : n._inputs ) - if( in!=null ) ctrl=CFGNode.deepest(ctrl,control(in,cache,active)); - active.clear(n._nid); - cache.put(n,ctrl); - return ctrl; - } - - // Export a value from its producing activation to the common ancestor, - // then capture it down to the consuming activation. These explicit ports, - // not a later placement scan of uses, define what must survive cleanup. - private static void crossing(Node value, Summary from, Summary to) { - Summary common=from; - while( true ) { - Summary up=to; - while( up!=null && up!=common ) up=up._parent; - if( up!=null ) break; - common=common._parent; - } - for( Summary frame=from; frame!=common; frame=frame._parent ) frame._exit.put(value,value); - for( Summary frame=to; frame!=common; frame=frame._parent ) frame._entry.put(value,value); - } - - // Build the function/iteration interfaces in the existing SSA vocabulary. - // A loop's backedge is a return into its next activation, with Phi inputs - // supplying the arguments. Breaks/fallout export through the normal interface. - private void frameBoundaries(Summary sum) { - IdentityHashMap<Node,CFGNode> controls=new IdentityHashMap<>(); - BitSet active=new BitSet(); - for( Site site : sum._sites ) if( site._birth!=null ) { - site._frame=enclosing(sum,site._birth); - for( Summary frame=site._frame; frame!=sum; frame=frame._parent ) frame._sites.add(site); - } - for( Summary frame : sum._loops.values() ) - for( Node use : frame._loop._outputs ) - if( use instanceof PhiNode phi && phi.region()==frame._loop ) { - frame._entry.put(phi,phi.in(1)); - frame._next.put(phi,phi.in(2)); - } - sum._exit.put(sum._fun.ret(),sum._fun.ret().expr()); - sum._exit.put(sum._fun.ret().mem(),sum._fun.ret().mem()); - for( Node n : sum._nodes ) if( n instanceof ParmNode ) sum._entry.put(n,n); - if( sum._loops.isEmpty() ) return; - for( Node n : sum._nodes ) { - boundaryInputs(sum,n,controls,active); - // collect() skips scalar arithmetic. Merge Phis still define exit - // ports, including scalar results loaded from reclaimed scratch. - if( n instanceof CFGNode ) - for( Node use : n._outputs ) - if( use instanceof PhiNode phi && phi.region()==n ) boundaryInputs(sum,phi,controls,active); - } - // Scalar users were deliberately omitted by collect(). Their pointer - // operands still need boundary ports (e.g. a load after an outside call). - for( var value : sum._values.entrySet() ) { - Node n=value.getKey(); - if( !pointer(n) || n instanceof ConstantNode ) continue; - Summary producer=enclosing(sum,control(n,controls,active)); - for( Node use : n._outputs ) { - if( use.isFunLeaf() || use instanceof PhiNode phi && phi.region() instanceof LoopNode ) continue; - crossing(n,producer,enclosing(sum,control(use,controls,active))); - } - } - } - - private static void boundaryInputs(Summary sum, Node n, IdentityHashMap<Node,CFGNode> controls, BitSet active) { - if( n.isFunLeaf() || n instanceof PhiNode phi && phi.region() instanceof LoopNode ) return; - Summary consumer=enclosing(sum,control(n,controls,active)); - for( Node in : n._inputs ) { - if( in==null || in instanceof ConstantNode || in instanceof CFGNode ) continue; - // Ordinary integer users do not extend the borrowing scope. Only - // the endpoint and its expression carry raw-address obligations. - if( sum._raw.get(in._nid) && - !(n instanceof KeepAliveNode) && !sum._raw.get(n._nid) ) continue; - crossing(in,enclosing(sum,control(in,controls,active)),consumer); - } - } - - // The same summary closure for function returns and loop exits. Effects on - // incoming storage escape the frame even without a returned pointer. Loops - // additionally describe the continuation's values and memory effects. - private void summarizeFrame(Summary sum, Summary frame, - IdentityHashMap<CallNode,IdentityHashMap<Site,HashSet<Site>>> imports) { - frame._state=1; - for( Summary child : frame._frames ) { - summarizeFrame(sum,child,imports); - if( child._reject!=null ) frame.reject(child._reject); - } - HashSet<Site> born=new HashSet<>(); - for( Site site : frame._sites ) if( site._fresh ) born.add(site); - for( Node value : frame._exit.values() ) - if( frame._loop!=null || pointer(value) ) frame._returns.addAll(refs(sum,value)); - for( Site site : sum._sites ) - if( !born.contains(site) ) - for( HashSet<Site> children : site._fields.values() ) frame._retained.addAll(children); - frame._escapes.addAll(frame._returns); - frame._escapes.addAll(frame._retained); - // Static allocations retain their absolute lifetime across substitution. - for( Site site : born ) if( site._owners.get(STATIC) ) frame._escapes.add(site); - frame._escapes.addAll(reachable(frame._escapes)); - if( frame._loop!=null ) { - for( var port : frame._next.entrySet() ) - if( pointer(port.getKey()) || sum._raw.get(port.getKey()._nid) ) - frame._continues.addAll(refs(sum,port.getValue())); - for( Node n : backMemory(frame._loop) ) { - if( n instanceof StoreNode store && pointer(store.val()) ) - retained(refs(sum,store.ptr()),refs(sum,store.val()),born,frame._continues); - if( n instanceof CallNode call && !nativeCall(call) ) { - var map=imports.get(call); - for( Site site : target(call)._sites ) - for( HashSet<Site> children : site._fields.values() ) - for( Site child : children ) retained(map.get(site),map.get(child),born,frame._continues); - } - } - frame._continues.addAll(reachable(frame._continues)); - for( Site site : frame._continues ) - if( born.contains(site) && !site.buddy() ) { - frame.reject(frame.name()+" carries "+site._name+" across its backedge; collection/overlap destinations not implemented"); - break; - } - } - frame._state=2; - } - - // Function and iteration cleanup use the same rule. Promote escaped storage - // to the enclosing frame until its interface no longer exports that storage. - // A function's external results already have symbolic owner requirements. - // No RSP adjustment or actual reclamation is emitted by this planning pass. - private static void placeFrames(Summary sum) { - for( Site site : sum._sites ) if( site._frame!=null ) { - // Buddy blocks are independent allocations, released by .del(). - // Keep tracking their references, but never put them in stack cleanup. - if( site.buddy() ) { site._scope=site._frame; continue; } - Summary scope=site._frame; - while( scope!=null && scope._escapes.contains(site) ) scope=scope._parent; - site._scope=scope; - if( scope!=null ) scope._scratch.add(site); - } - } - - // One element Set of Site - private static HashSet<Site> set(Site site) { - HashSet<Site> set = new HashSet<>(); set.add(site); return set; - } - - private static boolean edge(HashSet<Site> dst, String field, HashSet<Site> src) { - if( src.isEmpty() ) return false; - boolean changed=false; - for( Site site : dst ) - changed |= site._fields.computeIfAbsent(field,k -> new HashSet<>()).addAll(src); - return changed; - } - - // Select a field's possible values, not its containing object's storage. - // Fresh objects have only the stores we see. Borrowed objects also have an - // incoming value, named by a path. That path is a separate borrowed Site, - // substituted against the actual object's fields at each call. - private HashSet<Site> field(Summary sum, HashSet<Site> bases, String name) { - HashSet<Site> values=new HashSet<>(); - for( Site base : bases ) { - if( !base._fresh ) { - Site child=base._loads.get(name); - if( child==null ) { - // Weak updates can invent an unbounded path even in straight - // line code: p.next=p.next.next. Stop at the body's finite - // read count rather than silently truncate possible origins. - // Memory-ordered field updates go here. - if( base._depth>=sum._pathLimit ) { - sum.reject("cyclic field-path expansion at "+base._name+"."+name); - continue; - } - String path=(base._arg>=2 ? "arg"+base._arg : base._name)+"."+name; - child=new Site(sum,null,0,path); - child._base=base; child._field=name; child._depth=base._depth+1; - if( base==sum._static || base._owners.get(STATIC) ) child._owners.set(STATIC); - else { - child._owners.set(sum._destinations.size()); - sum._destinations.add(path); - } - base._loads.put(name,child); - sum._sites.add(child); - sum._changed=true; - } - values.add(child); - } - Set<Site> stored=base._fields.get(name); - if( stored!=null ) values.addAll(stored); - } - return values; - } - - // Which storage objects can this pointer expression denote? This resolves - // pointer VALUE flow, not the fields reachable through the pointer. A Phi - // unions possible targets; casts/views preserve targets; a call result uses - // compose's caller-side targets; a load selects one field's targets. - // New/Parm targets were seeded by build. - // Example: refs(cond ? a : b) = {site(a), site(b)}. - // build() uses these sets to add Store edges, then propagates owner requirements - // through that separate object graph. Cyclic SSA values use the prior known - // targets; the next local round propagates any newly discovered ones. - private HashSet<Site> refs(Summary sum, Node n) { - if( n==null || !(pointer(n) || sum._raw.get(n._nid)) ) return new HashSet<>(); - HashSet<Site> old = sum._values.computeIfAbsent(n,k -> new HashSet<>()); - if( n instanceof ParmNode || sum._resolved.get(n._nid) ) return old; - sum._resolved.set(n._nid); - HashSet<Site> values = new HashSet<>(); - if( n instanceof ConstantNode ) { - // Zero/null carries no storage obligation. Other constant objects - // have static backing; field() handles their incoming contents. - if( n._type!=Type.NIL && n._type!=TypeInteger.ZERO ) values.add(sum._static); - } else if( n instanceof ProjNode proj && proj.in(0) instanceof NewNode alloc && proj._idx==0 ) { - Set<Site> sites = sum._values.get(alloc); - if( sites==null ) sum.reject("foreign allocation #"+alloc._nid); - else values.addAll(sites); - } else if( n instanceof ProjNode proj && proj.in(0) instanceof CallEndNode end && proj._idx==2 ) { - Set<Site> result=sum._results.get(end.call()); - if( result==null ) sum.reject("foreign call #"+end.call()._nid); - else values.addAll(result); - } else if( n instanceof LoadNode load ) { - values.addAll(field(sum,refs(sum,load.ptr()),load._name)); - } else if( n instanceof PhiNode phi && !(phi instanceof ParmNode) ) { - for( int i=1; i<n.nIns(); i++ ) - if( !phi.region().in(i)._type.isHigh() ) values.addAll(refs(sum,n.in(i))); - } else if( n instanceof ReadOnlyNode || n instanceof GuardNode || - n instanceof ConstructNode || n instanceof InitViewNode || n instanceof ConvertNode ) { - values.addAll(refs(sum,n.in(1))); - } else if( n instanceof ArrayInitNode ) { - values.addAll(refs(sum,n.in(2))); - } else if( sum._raw.get(n._nid) ) { - for( Node in : n._inputs ) values.addAll(refs(sum,in)); - } else { - sum.reject("reference origin "+n.getClass().getSimpleName()+" #"+n._nid); - } - if( old.addAll(values) ) sum._changed=true; - return old; - } - - // Apply an already-built callee summary to this particular call. Translate - // callee Sites into caller Sites: formal -> refs(actual), static -> static, - // borrowed field -> actual field targets. Fresh Sites were imported once by - // build, tagged with this call. Private callee scratch stays in the callee. - // A second call gets distinct Sites for its fresh allocations. - // Then translate field edges and returned targets through the same map. - // For helper(h) { h.c = new Thing; }, calling helper(a) adds a.c -> call/new. - // The map values are SETS because an actual may select several objects. - // Callee result/argument owner bits are relative to its signature; do not - // copy them into the caller. build's closure derives the caller's owners - // from the translated edges and uses of the result. Only static is absolute. - private void compose(Summary sum, CallNode call, IdentityHashMap<Site,HashSet<Site>> map) { - Summary callee=target(call); - // Grow substitutions before transferring edges. A later local round - // resolves forward references and aliasing actuals. For example, after - // f(a,b) { a.c=new Thing; return b.c; }, f(h,h) returns that new Thing too. - for( Site site : callee._sites ) { - if( site._arg>=2 ) { - if( site._arg>=call.nIns()-1 ) - sum.reject("missing argument at call #"+call._nid); - else if( map.get(site).addAll(refs(sum,call.arg(site._arg))) ) sum._changed=true; - } else if( site._base!=null ) - if( map.get(site).addAll(field(sum,map.get(site._base),site._field)) ) sum._changed=true; - } - // Retention effects exist even when the function returns a scalar. - for( Site site : callee._sites ) { - HashSet<Site> dst=map.get(site); - if( dst.isEmpty() ) continue; - for( var field : site._fields.entrySet() ) for( Site child : field.getValue() ) { - HashSet<Site> src=map.get(child); - if( src==null ) sum.reject("unmapped retained storage at call #"+call._nid); - else sum._changed |= edge(dst,field.getKey(),src); - } - } - for( Site site : callee._returns ) { - Set<Site> returned=map.get(site); - if( returned==null ) sum.reject("unmapped returned storage at call #"+call._nid); - else sum._changed |= sum._results.get(call).addAll(returned); - } - } - - // Printing has its own rooted traversal: reversing the analysis's entire - // forest would put disconnected bodies (e.g. inlined constructors) first. - private void printPostorder(Summary sum, BitSet seen, ArrayList<Summary> post) { - if( sum==null || seen.get(sum._fun._nid) ) return; - seen.set(sum._fun._nid); - ArrayList<CallNode> calls=new ArrayList<>(sum._calls); - calls.sort(Comparator.comparingInt(n -> n._nid)); - for( CallNode call : calls ) printPostorder(target(call),seen,post); - post.add(sum); - } - - @Override public String toString() { - StringBuilder out = new StringBuilder("Allocation destinations (analysis only; no stack lowering)\n"); - BitSet seen=new BitSet(); - ArrayList<Summary> order=new ArrayList<>(); - printPostorder(_entrySummary,seen,order); - Collections.reverse(order); - int reachable=order.size(); - ArrayList<Summary> other=new ArrayList<>(); - for( Summary sum : _summaries ) printPostorder(sum,seen,other); - Collections.reverse(other); - order.addAll(other); - for( int i=0; i<order.size(); i++ ) { - if( i==reachable && _entrySummary!=null ) - out.append("\nOther retained functions (not reachable by direct calls from entry):\n"); - Summary sum=order.get(i); - out.append("\n+-- ").append(sum._fun.label()).append("\n"); - for( ArrayDelete.Consume consume : sum._consumes ) { - out.append("| may consume entry(").append(consume).append("); requires unique access"); - if( arrayOwned(sum,consume) ) out.append("; returns unique ").append(consume); - out.append('\n'); - } - ArrayList<CallNode> calls=new ArrayList<>(sum._calls); - calls.sort(Comparator.comparingInt(n -> n._nid)); - for( CallNode call : calls ) { - Summary callee=target(call); - out.append("| call#").append(call._nid).append(" -> ") - .append(callee==null ? nativeCall(call) ? "native (borrow; no retain)" : "?" : callee._fun.label()).append("\n"); - } - if( !sum.supported() ) { - out.append("`-- REJECT: ").append(sum._reject).append("\n"); - continue; // Do not display a partial plan as a safe placement. - } - printFrames(out,sum,"| "); - printStorage(out,sum,"| "); - printSites(out,"| cleanup on return -> ",sum._scratch); - printSites(out,"`-- return -> ",sum._returns," | "); - } - return out.toString(); - } - - // Show storage in its owning frame, which may enclose its allocation site. - // Borrowed/external destinations remain at function level. - private static void printStorage(StringBuilder out, Summary frame, String indent) { - ArrayList<Site> sites=new ArrayList<>(); - for( Site site : frame._sites ) - if( site._scope==frame || (frame._loop==null && site._scope==null) ) sites.add(site); - sites.sort(Comparator.comparing(s -> s._name)); - for( Site site : sites ) { - out.append(indent).append('[').append(site.destination()).append("] ").append(site._name); - if( site._fresh ) { - out.append(" ("); - if( site._bytes<0 ) out.append("dynamic size"); - else out.append(site._bytes).append(" bytes"); - out.append(')'); - } - if( site._frame!=null && site._frame._loop!=null && site._scope!=site._frame ) - out.append("; ").append(site._frame.name()).append(" winner"); - out.append('\n'); - ArrayList<String> edges=new ArrayList<>(); - for( var field : site._fields.entrySet() ) for( Site child : field.getValue() ) - edges.add(indent+" ."+field.getKey()+" --> "+child._name+"\n"); - Collections.sort(edges); - for( String edge : edges ) out.append(edge); - } - } - - private static void printSites(StringBuilder out, String label, HashSet<Site> sites) { - printSites(out,label,sites,", "); - } - private static void printSites(StringBuilder out, String label, HashSet<Site> sites, String separator) { - out.append(label).append('{'); - ArrayList<String> names=new ArrayList<>(); - for( Site site : sites ) names.add(site._name); - Collections.sort(names); - for( int i=0; i<names.size(); i++ ) { - if( i>0 ) out.append(separator); - out.append(names.get(i)); - } - out.append("}\n"); - } - - private static void printPorts(StringBuilder out, String label, IdentityHashMap<Node,Node> ports) { - out.append(label).append('{'); - ArrayList<Node> keys=new ArrayList<>(ports.keySet()); - keys.sort(Comparator.comparingInt(n -> n._nid)); - for( int i=0; i<keys.size(); i++ ) { - Node port=keys.get(i), value=ports.get(port); - if( i>0 ) out.append(", "); - out.append(port.label()).append('#').append(port._nid); - if( port!=value ) out.append(" <- ").append(value.label()).append('#').append(value._nid); - } - out.append("}\n"); - } - - private static void printFrames(StringBuilder out, Summary parent, String indent) { - ArrayList<Summary> frames=new ArrayList<>(parent._frames); - frames.sort(Comparator.comparingInt(s -> s._loop._nid)); - for( Summary frame : frames ) { - out.append(indent).append("+-- ").append(frame.name()).append(" frame; parent ").append(parent.name()).append('\n'); - printPorts(out,indent+"| entry -> ",frame._entry); - printPorts(out,indent+"| continue values -> ",frame._next); - printSites(out,indent+"| continue refs -> ",frame._continues); - printPorts(out,indent+"| exit values -> ",frame._exit); - printSites(out,indent+"| return refs -> ",frame._returns); - printSites(out,indent+"| retain -> ",frame._retained); - printStorage(out,frame,indent+"| "); - printFrames(out,frame,indent+"| "); - printSites(out,indent+"`-- cleanup on continue and return -> ",frame._scratch); - } - } -} diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java index 42490961..7a0fa4e2 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java @@ -4,7 +4,6 @@ import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.type.*; import com.seaofnodes.simple.util.*; -import java.awt.*; import java.util.*; /** Allocation-site points-to analysis of the optimized graph. One object per @@ -13,14 +12,16 @@ import java.util.*; * <p></p> * Facts only grow. Reading a fact registers a dependency; changing it * schedules its readers. Loads/stores discover field dependencies as their - * bases grow. Unknown means arbitrary storage, not an empty points-to set. + * bases grow. Unknown denotes storage outside the local Site collection. + * Separate-compilation boundaries are incomplete; these facts must not yet + * authorize storage reclamation. */ public final class Allocation2 { private final CodeGen _code; // --------------------------------- // Things that can be pointed-at; a NewNode allocation or a static pre- - // initialized Constant (basically a NewNode moved to program genysis). + // initialized Constant (basically a NewNode moved to program startup). public static final class Site { public final Node _node; // NewNode or static ConstantNode // Each field has its own set of things it points to. This array is @@ -74,14 +75,6 @@ public final class Allocation2 { return field; } - // Transitively escape - void escapes( HashSet<Site> escapes ) { - if( _byFld != null ) - for( Points fld : _byFld ) - if( fld != null ) - throw Utils.TODO(); - } - @Override public String toString() { return str(new SB()).toString(); } public SB str( SB sb ) { TypeStruct ts = type(); @@ -137,7 +130,7 @@ public final class Allocation2 { // // Have a Point, merge the Point._unknown and all Point._sites. // Have a HashSet<Site> instead. - // Have a Type, filer by Type. + // Have a Type, filter by Type. // Have a WorkList, add changes if progress. // Merge Site into our existing Sites, return true if progress @@ -164,13 +157,20 @@ public final class Allocation2 { changed(work); } + // TODO: Track field growth after a site first escapes, including fields + // which are still empty. Visiting each site once is not a lifetime proof. boolean mergeTransitive( Points p ) { boolean progress = false; for( Site site : p._sites ) if( _sites.add(site) ) { progress = true; - if( site._byFld != null ) - throw Utils.TODO("transitive"); + if( site._byFld != null ) { + for( int i=0; i<site._byFld.length; i++ ) { + Points field = site._byFld[i]; + if( field != null ) + mergeTransitive(field); + } + } } return progress; } @@ -182,8 +182,7 @@ public final class Allocation2 { } public boolean contains(Site site) { - // Unknown sites are none of these, so it never contains one - //if( _unknown ) throw Utils.TODO(); + // Unknown sites are outside this collection. return _sites.contains(site); } @@ -250,10 +249,13 @@ public final class Allocation2 { points(_work.push(n)); // ConstantNodes imply some memory was pre-allocated at // start time (unlike NewNodes, which make new every time) - if( n instanceof ConstantNode con && n._type.isConstant() ) + if( n instanceof ConstantNode && n._type.isConstant() ) getPts(n).merge(site(n)); - } else if( n instanceof StoreNode st && st.val()._type instanceof TypeMemPtr ) { + } else if( n instanceof CallEndNode || n instanceof SummaryNode || + n instanceof StoreNode st && st.val()._type instanceof TypeMemPtr ) { + // Includes Calls and Summaries that call external functions + // and escape all arguments, even if they do not return a reference. _work.push(n); } @@ -271,15 +273,9 @@ public final class Allocation2 { // Solve the points-to private void solve() { - int steps=0; // Steps to solve; nice binary search for solver crashes - // Pass work to be done in backdoor _reader, to avoid having to pass it - // everywhere - // Current worklist element being worked on Node n; - while( (n = _work.pop()) != null ) { - steps++; + while( (n = _work.pop()) != null ) transfer( n ); - } } private Points read(Node node, Node dep) { @@ -296,30 +292,28 @@ public final class Allocation2 { if( field!=null ) field.merge(src,_work); } - // Storing local values into unknown sites if( bases._unknown && _escapes.mergeTransitive(src) ) _escapes.changed(_work); } - //case CLInitNode init when !init.bypass() -> { - // FunNode fun = _code.link(init.cu()); - // if( fun==null || fun.summary()!=null ) effects(n,fun); - //} case CallEndNode cend -> cend(cend); + case SummaryNode sum -> escapeCallArgs(sum,sum.in(0),n); case ReturnNode ret -> { - if( reference(ret.expr()._type) ) points(n).merge(read(ret.expr(),n), _work); + if( reference(ret.expr()._type) ) { + Points result = read(ret.expr(),n); + points(n).merge(result, _work); + if( ret.fun().in(1) instanceof StartNode && + _escapes.mergeTransitive(result) ) + _escapes.changed(_work); + } } - //case PtrToIntNode raw -> { - // int[] writes=XInt.EMPTY; - // if( raw.in(1)._type instanceof TypeMemPtr ptr && ptr._obj._fields!=null ) { - // if( ptr._obj.isAry() ) writes=XInt.make(ptr._obj.field("[]")._alias); - // else for( Field field : ptr._obj._fields ) writes=XInt.make(writes,field._alias); - // } else writes=XInt.FULL; - // opaque(n,writes,"raw-address access"); - //} - //case NewNode alloc -> {} // Seeded before solving. case ConstantNode con -> { // Constant static memory already handled assert n._type instanceof TypeMemPtr; + // Constant non-constants are the default argument from an unknown + // caller; means any escaped allocation of the correct type might + // come in here + if( !n._type.isConstant() && points(n).merge(_escapes.addDep(n),((TypeMemPtr)n._type)._obj) ) + points(n).changed(_work); } case PhiNode phi -> { @@ -329,11 +323,13 @@ public final class Allocation2 { assert !phi.region().in(i)._type.isHigh(); if( phi.in(i)._type==Type.NIL ) continue; // null does not point to anything if( phi.in(i)._type.isHigh() ) continue; // Never-exit as a TOP here + // TODO: TypeCheck runs later; malformed programs can still + // supply non-reference actual arguments here. assert reference(phi.in(i)._type); progress |= dst.merge(read(phi.in(i),n)); // If getting from the unknown caller, might get all the escapes if( phi instanceof ParmNode && i==1 && phi.region().in(i) instanceof StartNode ) - progress |= dst.merge(_escapes.addDep(phi),phi._type); + progress |= dst.merge(_escapes.addDep(phi),((TypeMemPtr)phi._type)._obj); } if( progress ) dst.changed(_work); } @@ -365,7 +361,9 @@ public final class Allocation2 { case GuardNode guard -> forward(guard); case ConstructNode con -> forward(con); case InitViewNode view -> forward(view); - //case ConvertNode conv -> forward(conv ,nonNull); + case ConvertNode conv -> { + if( reference(conv.in(1)._type) ) forward(conv); + } case ArrayInitNode init -> points(n).merge(read(init.in(2),n),_work); default -> throw Utils.TODO("transfer: "+n.getClass().getSimpleName()); @@ -378,37 +376,58 @@ public final class Allocation2 { } private void cend(CallEndNode cend) { - assert reference(cend._type); // Only here for calls returning pointers CallNode call = cend.call(); if( Intrinsic.arrayDelete(call) || Intrinsic.pure(call) ) - throw Utils.TODO("untested");//return; + throw Utils.TODO("Allocation2 intrinsic call transfer"); if( !(call.fptr()._type instanceof TypeFunPtr fp) ) throw Utils.TODO("why weak tfp"); - assert !XInt.isHigh(fp.fidxs()); // Again, why any dead calls here? + // Calls unknown functions? + int firstArg = XInt.isHigh(fp.fidxs()) ? 2 : 0; if( !(cend._type instanceof TypeTuple state) ) throw Utils.TODO("why weak return"); Type result = state.ret(); - Points p = points(cend); + // Can be here for Calls returning non-references, but to escaping functions + Points p = reference(result) ? points(cend) : null; boolean progress = false; // Walk target functions for( int fidx = XInt.next(fp.fidxs(),0); fidx>=0; fidx = XInt.next(fp.fidxs(),fidx) ) { FunNode fun = _code.link(fidx); - if( fun==null || fun._extern || fun.summary()!=null ) { - // Might return some unknown allocation - progress |= p.merge(_escapes.addDep(cend), ((TypeMemPtr)result)._obj); - // All arguments escape as well - for( int i=3; i<call.nIns(); i++ ) - if( reference(call.in(i)._type) ) - throw Utils.TODO(""); - } else { + if( fun==null || fun._extern || fun.summary() !=null ) { + int x = SummaryNode.firstArgument(fun); + if( firstArg==0 ) firstArg = x; + else assert firstArg==x; + } else if( p!=null ) { progress |= p.merge(read(fun.ret(),cend)); } } + + if( firstArg != 0 ) { + // Might return some unknown allocation + if( p != null ) + progress |= p.merge(_escapes.addDep(cend), ((TypeMemPtr)result)._obj); + // All arguments escape as well + escapeCallArgs(call,firstArg,cend); + } if( progress ) p.changed(_work); } + // Calling an unknown function escapes the call's args + void escapeCallArgs(Node call, Node fun, Node dep) { + int first = SummaryNode.firstArgument(fun); + escapeCallArgs(call,first,dep); + } + + void escapeCallArgs(Node call, int first, Node dep) { + // Skip the class arg + for( int i=first; i<call.nIns()-1; i++ ) + if( reference(call.in(i)._type) && + _escapes.mergeTransitive(read(call.in(i),dep)) ) + _escapes.changed(_work); + } + + // Count incoming edges; mark special a single incoming ptr private void incoming() { for( Site base : _sites.values() ) @@ -423,13 +442,12 @@ public final class Allocation2 { // --------------------------------- - /** Re-evaluate every constraint after convergence. Used by the review - * sweep and focused tests, not the production hot path. Includes facts - * without readers. */ + /** Re-evaluate every constraint after convergence. Used by assertions and + * explicit tests, including facts without readers. */ public boolean verify() { String before = toString(); _code._start.walk( n -> { - if( reference(n._type) || + if( reference(n._type) || n instanceof CallEndNode || n instanceof SummaryNode || (n instanceof StoreNode st && st.val()._type instanceof TypeMemPtr) ) _work.push(n); return null; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ArrayDelete.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ArrayDelete.java deleted file mode 100644 index 1d22a3b6..00000000 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ArrayDelete.java +++ /dev/null @@ -1,538 +0,0 @@ -package com.seaofnodes.simple.codegen; - -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.*; -import com.seaofnodes.simple.util.SB; -import java.util.*; - -/** Demand-driven ownership at a deletion checkpoint. Field queries follow - * memory SSA. Call summaries supply may-stores, returned origins, and exclusive - * outgoing fields at that call's memory output, never at all calls at once. - * Runtime recycling remains separate from these proofs. */ -public final class ArrayDelete { - public record Consume(int arg, List<String> path) { - public Consume { path=List.copyOf(path); } - @Override public String toString() { - SB sb=new SB().p("arg").p(arg); - for( String field : path ) sb.p('.').p(field); - return sb.toString(); - } - } - - // An origin is a local Node, an incoming base.field, a callee allocation, - // or a call's exclusive outgoing base.field. Interned inside this check. - // Node equality/hashing must be identity: Node.hashCode participates in GVN. - private record Ref(Node node, Ref base, String field, Allocation.Site site) { - @Override public int hashCode() { - return System.identityHashCode(node)+31*System.identityHashCode(base)+ - 17*System.identityHashCode(site)+Objects.hashCode(field); - } - @Override public boolean equals(Object o) { - return o instanceof Ref r && node==r.node && base==r.base && site==r.site && Objects.equals(field,r.field); - } - boolean fresh() { return node instanceof NewNode || node instanceof CallNode || node instanceof LoopNode && base!=null; } - } - private static final class Effects { - final IdentityHashMap<Allocation.Site,HashSet<Ref>> values=new IdentityHashMap<>(); - final HashMap<Ref,HashMap<String,HashSet<Ref>>> stores=new HashMap<>(); - final HashSet<Ref> returns=new HashSet<>(); - boolean building=true; - } - - public final CallNode _call; - public String _reject; - public Node _unique; - public Consume _requirement; - private Ref _owner; - private String _field; - private int _alias; - private final Allocation _allocation; - private final HashMap<Ref,Ref> _origins=new HashMap<>(); - private final IdentityHashMap<Node,HashSet<Ref>> _refs=new IdentityHashMap<>(); - private final IdentityHashMap<CallNode,Effects> _effects=new IdentityHashMap<>(); - private final IdentityHashMap<CallNode,HashSet<Ref>> _owned=new IdentityHashMap<>(); - private final HashMap<Ref,HashSet<Ref>> _loopEntries=new HashMap<>(); - private final IdentityHashMap<Node,Boolean> _borrows=new IdentityHashMap<>(); - private final BitSet _active=new BitSet(), _after=new BitSet(); - private final ArrayList<LoopNode> _backedges=new ArrayList<>(); - private HashSet<Ref> _old; - private HashSet<Ref> _next; - private String _arrayType; - private boolean _deletable; - - ArrayDelete(Allocation allocation, List<Node> nodes, CallNode call, int arg) { - this(allocation,nodes,call,new Consume(arg,List.of()),false); - } - ArrayDelete(Allocation allocation, List<Node> nodes, CallNode call, Consume consume) { - this(allocation,nodes,call,consume,true); - } - private ArrayDelete(Allocation allocation, List<Node> nodes, CallNode call, Consume consume, boolean atCaller) { - _allocation=allocation; _call=call; - if( consume.arg()<2 || consume.arg()>=call.nIns()-1 ) throw new IllegalArgumentException("Not a call argument"); - Node value=call.arg(consume.arg()); - Type type=value._type; - HashSet<Ref> roots=refs(value); - for( String name : consume.path() ) { - if( roots.size()!=1 || !(type instanceof TypeMemPtr ptr) ) { - reject("ambiguous consuming owner for "+consume); return; - } - Field field=ptr._obj.field(name); - if( field==null ) { reject("missing consuming field ."+name); return; } - _owner=roots.iterator().next(); _field=name; _alias=field._alias; - roots=contents(call.in(1),_owner,name,_alias); - // This checkpoint's next ownership version belongs to the next - // iteration; the entry and other preceding versions are checked here. - roots.remove(ref(call,_owner,name,null)); - type=field._t; - } - if( !(type instanceof TypeMemPtr ptr) || !ptr._obj.isAry() || ptr.nullable() ) { - reject("requires a non-null array"); return; - } - _arrayType=ptr._obj._name; - _deletable=ptr._del; - if( _reject!=null ) return; - if( roots.isEmpty() ) { reject("array has no known origin"); return; } - _old=new HashSet<>(roots); - ArrayDeque<Ref> entries=new ArrayDeque<>(roots); - while( !entries.isEmpty() ) { - HashSet<Ref> entry=_loopEntries.get(entries.pop()); - if( entry!=null ) for( Ref r : entry ) if( _old.add(r) ) entries.push(r); - } - for( Ref root : _old ) if( !root.fresh() ) { - Consume incoming=entryPath(root); - if( incoming==null ) { reject("cannot express incoming ownership as an argument field path"); return; } - if( _requirement!=null && !_requirement.equals(incoming) ) { - reject("array has multiple incoming ownership paths"); return; - } - _requirement=incoming; _unique=value; - } - after(call); - // Merges reached after this checkpoint exclude paths that bypassed it. - _refs.clear(); _effects.clear(); _owned.clear(); - - // A unique-entry requirement excludes aliases in the other arguments. - // Callees may rely on this; check the actuals at each consuming caller. - if( atCaller ) for( int i=2; i<call.nIns()-1; i++ ) - if( i!=consume.arg() && pointer(call.arg(i)) && contains(call.arg(i)) ) - reject("argument #"+(i-2)+" aliases the array at deletion"); - - // Check explicit stores and substituted callee stores by the same rule: - // any alias must be killed at the checkpoint's incoming memory version. - for( Ref root : roots ) if( root.node==null && root.base!=null ) slot(root.base,root.field); - for( Node n : nodes ) { - if( _reject!=null ) return; - if( n instanceof StoreNode st && pointer(st.val()) && contains(st.val()) ) { - if( later(st) ) reject("store #"+st._nid+" uses the array after deletion"); - else for( Ref base : refs(st.ptr()) ) slot(base,st._name); - } - if( n instanceof CallNode other && other!=call && !borrow(other) && !unborn(other) ) { - Effects effect=effects(other); - if( effect==null ) { reject("call #"+other._nid+" ("+target(other)+") has unknown reference effects before deletion"); continue; } - for( var base : effect.stores.entrySet() ) for( var field : base.getValue().entrySet() ) - if( contains(field.getValue()) ) { - if( later(other) ) reject("call #"+other._nid+" stores the array after deletion"); - else slot(base.getKey(),field.getKey()); - } - } - if( n instanceof CLInitNode init && !_allocation.arrayBorrow(init) && !later(init) && !unborn(init) ) - reject("class initialization #"+init._nid+" has unknown reference effects before deletion"); - } - for( Node n : nodes ) { - if( _reject!=null ) return; - if( pointer(n) && contains(n) ) for( Node use : n._outputs ) { - if( _reject!=null ) return; - use(n,use); - } - } - if( _reject==null && !_backedges.isEmpty() ) { - if( atCaller && !consume.path().isEmpty() && !_allocation.arrayOwned(call,consume) ) - reject("callee does not preserve unique field ownership across deletion backedge"); - else backedges(nodes); - } - } - - public boolean proven() { return _reject==null && _unique==null; } - private void reject(String why) { if( _reject==null ) _reject=why; } - private Ref ref(Node n, Ref base, String field, Allocation.Site site) { - Ref r=new Ref(n,base,field,site); - Ref old=_origins.putIfAbsent(r,r); - return old==null ? r : old; - } - private Ref ref(Node n) { return ref(n,null,null,null); } - private static HashSet<Ref> set(Ref r) { HashSet<Ref> s=new HashSet<>(); s.add(r); return s; } - private static boolean pointer(Node n) { return n!=null && (n._type instanceof TypeMemPtr || n._type instanceof TypePtr); } - private Type type(Ref r) { - if( r.base!=null && type(r.base) instanceof TypeMemPtr p ) { - Field field=p._obj.field(r.field); - if( field!=null ) return field._t; - } - Type t=r.site!=null && r.site._allocation!=null ? r.site._allocation._type : r.node==null ? TypePtr.PTR : r.node._type; - return t instanceof TypeTuple tt && (r.node instanceof NewNode || r.site!=null && r.site._allocation!=null) ? tt.at(0) : t; - } - private int alias(Ref base, String name) { - if( type(base) instanceof TypeMemPtr p ) { - Field field=p._obj.field(name); - if( field!=null ) return field._alias; - } - return 1; // Unknown base: query the whole-memory slice conservatively. - } - private static Consume entryPath(Ref r) { - if( r.node instanceof ParmNode parm ) return new Consume(parm._idx,List.of()); - if( r.node!=null || r.base==null ) return null; - Consume parent=entryPath(r.base); - if( parent==null ) return null; - ArrayList<String> path=new ArrayList<>(parent.path()); path.add(r.field); - return new Consume(parent.arg(),path); - } - private boolean contains(Node n) { - if( n._type instanceof TypeMemPtr p && p._obj!=TypeStruct.BOT && !p._obj._name.equals(_arrayType) ) return false; - return contains(refs(n)); - } - private boolean contains(HashSet<Ref> refs) { - for( Ref old : _old ) if( mayAlias(refs,old) ) return true; - return false; - } - private boolean updated(HashSet<Ref> refs) { - if( _next!=null ) for( Ref r : _next ) if( mayAlias(refs,r) ) return true; - return false; - } - private boolean mayAlias(HashSet<Ref> refs, Ref base) { - for( Ref r : refs ) { - if( r==base ) return true; - if( r.fresh() || base.fresh() ) continue; - // Literal/static arrays cannot inhabit a deletable array slot. - if( _deletable && r.node instanceof ConstantNode && type(r) instanceof TypeMemPtr p && - p._obj.isAry() && !p._del ) continue; - // A separate array parameter is disjoint under the propagated - // unique-entry requirement, checked against actuals at callers. - // Do not infer that different owner paths are disjoint: two - // wrapper parameters might denote the same wrapper. - if( _requirement!=null && _old!=null && _old.contains(base) && - entryPath(base)!=null && r.node instanceof ParmNode ) continue; - if( type(r) instanceof TypeMemPtr x && type(base) instanceof TypeMemPtr y && - x._obj!=TypeStruct.BOT && y._obj!=TypeStruct.BOT && !x._obj._name.equals(y._obj._name) ) continue; - return true; - } - return false; - } - private boolean unborn(CFGNode effect) { - for( Ref root : _old ) { - CFGNode birth=root.node instanceof NewNode alloc ? (CFGNode)alloc.ctrl() : - root.node instanceof CallNode call ? call : null; - if( birth==null || effect==birth || !effect.dominates(birth,null) ) return false; - } - return true; - } - private HashSet<Ref> refs(Node n) { - HashSet<Ref> known=_refs.get(n); - if( known!=null ) return known; - HashSet<Ref> result=new HashSet<>(); - if( _reject!=null ) return result; - if( _active.get(n._nid) ) { reject("cyclic reference at #"+n._nid); return result; } - _active.set(n._nid); - if( n._type==Type.NIL || n._type.isHigh() ) { - } else if( n instanceof NewNode || n instanceof ParmNode || n instanceof ConstantNode ) result.add(ref(n)); - else if( n instanceof ProjNode proj && proj._idx==0 && proj.in(0) instanceof NewNode ) result.add(ref(proj.in(0))); - else if( n instanceof GuardNode || n instanceof ReadOnlyNode || n instanceof ConstructNode || n instanceof InitViewNode ) - result.addAll(refs(n.in(1))); - else if( n instanceof ArrayInitNode ) result.addAll(refs(n.in(2))); - else if( n instanceof PhiNode phi ) { - for( int i=1; i<phi.nIns(); i++ ) if( liveInput(phi,i) ) result.addAll(refs(phi.in(i))); - } else if( n instanceof LoadNode load ) { - HashSet<Ref> bases=refs(load.ptr()); - if( bases.size()!=1 ) reject("ambiguous owner of field ."+load._name+" at #"+load._nid); - else result.addAll(contents(load.mem(),bases.iterator().next(),load._name,load._alias)); - } else if( n instanceof ProjNode proj && proj._idx==2 && proj.in(0) instanceof CallEndNode end ) { - // Forwarded arguments need no field substitution, including calls - // which also update memory. Their stores are checked separately. - ArrayList<Node> args=_allocation.arrayResult(end.call()); - if( args!=null ) for( Node arg : args ) result.addAll(refs(arg)); - else { - Effects effect=effects(end.call()); - if( effect==null ) reject("untracked returned reference at call #"+end.call()._nid); - else result.addAll(effect.returns); - } - } else reject("untracked reference #"+n._nid+" ("+n.label()+")"); - _active.clear(n._nid); _refs.put(n,result); - return result; - } - - // Unique entry -> unique exit is a strong ownership transfer, even when - // the implementation takes its no-growth path. May-stores remain weak. - private HashSet<Ref> owned(CallNode call) { - HashSet<Ref> slots=_owned.get(call); - if( slots!=null ) return slots; - slots=new HashSet<>(); _owned.put(call,slots); - Allocation.Summary sum=_allocation.target(call); - if( sum!=null ) for( Consume consume : sum._consumes ) - if( _allocation.arrayOwned(call,consume) ) { - HashSet<Ref> bases=refs(call.arg(consume.arg())); - for( int i=0; i<consume.path().size()-1; i++ ) { - String field=consume.path().get(i); - HashSet<Ref> next=new HashSet<>(); - for( Ref base : bases ) next.addAll(contents(call.in(1),base,field,alias(base,field))); - bases=next; - } - if( bases.size()==1 ) slots.add(ref(null,bases.iterator().next(),consume.path().getLast(),null)); - } - return slots; - } - - private HashSet<Ref> substitute(CallNode call, Allocation.Site site, Effects effect) { - HashSet<Ref> known=effect.values.get(site); - if( known!=null ) return known; - HashSet<Ref> values=new HashSet<>(); effect.values.put(site,values); - if( site._arg>=2 ) values.addAll(refs(call.arg(site._arg))); - else if( site._arg==-1 ) values.add(ref(CodeGen.CODE._start)); - else if( site._fresh ) values.add(ref(call,null,null,site)); - else if( site._base!=null ) - for( Ref base : substitute(call,site._base,effect) ) - values.addAll(contents(call.in(1),base,site._field,alias(base,site._field))); - else reject("unmapped call storage at #"+call._nid); - return values; - } - - private Effects effects(CallNode call) { - Effects known=_effects.get(call); - if( known!=null ) { - if( known.building ) { reject("cyclic call-field effects at #"+call._nid); return null; } - return known; - } - Allocation.Summary sum=_allocation.target(call); - if( sum==null || !sum.supported() || sum._opaqueEffects || sum._fun._extern ) return null; - Effects effect=new Effects(); _effects.put(call,effect); - HashSet<Ref> owned=owned(call); - for( Allocation.Site site : sum._sites ) if( !site._fields.isEmpty() ) - for( Ref base : substitute(call,site,effect) ) for( var field : site._fields.entrySet() ) { - HashSet<Ref> values=effect.stores.computeIfAbsent(base,k -> new HashMap<>()) - .computeIfAbsent(field.getKey(),k -> new HashSet<>()); - if( owned.contains(ref(null,base,field.getKey(),null)) ) values.add(ref(call,base,field.getKey(),null)); - else for( Allocation.Site value : field.getValue() ) values.addAll(substitute(call,value,effect)); - } - for( Allocation.Site site : sum._returns ) effect.returns.addAll(substitute(call,site,effect)); - effect.building=false; - return effect; - } - - private HashSet<Ref> contents(Node mem, Ref base, String field, int alias) { - return contents(mem,base,field,alias,new BitSet()); - } - private HashSet<Ref> contents(Node mem, Ref base, String field, int alias, BitSet seen) { - HashSet<Ref> result=new HashSet<>(); - if( _reject!=null || mem._type.isHigh() || seen.get(mem._nid) ) return result; - // A field query is reachability through memory definitions, with strong - // stores cutting edges. A loop revisit adds no new reachable definition. - seen.set(mem._nid); - if( mem instanceof MemMergeNode merge ) { - if( alias==1 ) { - for( Node slice : merge._inputs ) if( slice!=null ) result.addAll(contents(slice,base,field,alias,seen)); - } else { - Node slice=merge.explicitAlias(alias); - result.addAll(contents(slice==null ? merge.in(1) : slice,base,field,alias,seen)); - } - } else if( mem instanceof StoreNode st ) { - HashSet<Ref> bases=refs(st.ptr()); - boolean same=(st._alias==alias || st._alias==1 || alias==1) && st._name.equals(field); - boolean exact=same && bases.size()==1 && bases.contains(base); - if( same && mayAlias(bases,base) ) { - if( "[]".equals(field) ) reject("array-element ownership needs an index proof"); - else result.addAll(refs(st.val())); - } - if( !exact ) result.addAll(contents(st.mem(),base,field,alias,seen)); - } else if( mem instanceof EscapeNode esc ) { - HashSet<Ref> bases=refs(esc.self()); - boolean same=esc.fld()._alias==alias || alias==1; - if( same && mayAlias(bases,base) ) result.addAll(contents(esc.priv(),base,field,alias,seen)); - if( !same || bases.size()!=1 || !bases.contains(base) ) result.addAll(contents(esc.pub(),base,field,alias,seen)); - } else if( mem instanceof PhiNode phi && !(mem instanceof ParmNode) ) { - if( phi.region() instanceof LoopNode loop && inside(_call,loop) && base==_owner && - field.equals(_field) && alias==_alias && type(ref(null,base,field,null)) instanceof TypeMemPtr p && p._obj.isAry() ) { - // A loop header is an ownership boundary, just like a call. - // Keep its entry version distinct from calls on the backedge. - Ref entry=ref(loop,base,field,null); - if( !_loopEntries.containsKey(entry) ) { - _loopEntries.put(entry,new HashSet<>()); - _loopEntries.get(entry).addAll(contents(phi.in(1),base,field,alias,seen)); - } - result.add(entry); - } else for( int i=1; i<phi.nIns(); i++ ) if( liveInput(phi,i) ) result.addAll(contents(phi.in(i),base,field,alias,seen)); - } else if( mem instanceof ProjNode proj && proj.in(0) instanceof CallEndNode end ) { - CallNode call=end.call(); - if( call==_call && base==_owner && field.equals(_field) && alias==_alias || - owned(call).contains(ref(null,base,field,null)) ) result.add(ref(call,base,field,null)); - else if( call==_call || Intrinsic.arrayDelete(call) || borrow(call) ) - result.addAll(contents(call.in(1),base,field,alias,seen)); - else { - Effects effect=effects(call); - if( effect==null ) reject("unknown reference effects at call #"+call._nid+" ("+target(call)+")"); - else { - for( var store : effect.stores.entrySet() ) if( mayAlias(set(store.getKey()),base) ) { - Set<Ref> values=store.getValue().get(field); - if( values!=null ) result.addAll(values); - } - result.addAll(contents(call.in(1),base,field,alias,seen)); - } - } - } else if( mem instanceof ProjNode proj && proj.in(0) instanceof NewNode ) { - } else if( mem instanceof ProjNode proj && proj.in(0) instanceof CLInitNode init && _allocation.arrayBorrow(init) ) { - result.addAll(contents(init.mem(),base,field,alias,seen)); - } else if( mem instanceof ParmNode || mem instanceof ConstantNode || mem instanceof ProjNode proj && proj.in(0) instanceof StartNode ) { - if( !base.fresh() ) result.add(ref(null,base,field,null)); - } else reject("unknown memory #"+mem._nid+" ("+mem.getClass().getSimpleName()+") for ."+field); - return result; - } - - private boolean liveInput(PhiNode phi, int i) { - Node ctrl=phi.region().in(i); - return !ctrl._type.isHigh() && (!_after.get(phi.region()._nid) || _after.get(ctrl._nid)); - } - private void slot(Ref base, String field) { - if( base==_owner && field.equals(_field) ) return; - if( contains(contents(_call.in(1),base,field,alias(base,field))) ) - reject("field ."+field+" still holds the array at deletion"); - } - private boolean borrow(CallNode call) { - Boolean known=_borrows.get(call); - if( known!=null ) return known; - boolean result=Intrinsic.arrayDelete(call) || _allocation.arrayBorrow(call); - _borrows.put(call,result); return result; - } - private static String target(CallNode call) { - return call.fptr()._type instanceof TypeFunPtr fp && fp.isConstant() ? CodeGen.CODE.funcName(fp.fidx()) : "indirect"; - } - private void use(Node value, Node use) { - if( use==null ) { reject("unclassified kept reference #"+value._nid); return; } - if( use==_call ) return; - if( use instanceof PtrToIntNode ) { reject("raw-address borrow of the array at #"+use._nid); return; } - if( use instanceof CallNode call ) { - if( later(call) ) reject("call #"+call._nid+" uses the array after deletion"); - else if( !borrow(call) && effects(call)==null ) reject("call #"+call._nid+" has no borrowing-only contract"); - return; - } - if( use instanceof StoreNode store && store.val()==value ) return; - if( use instanceof EscapeNode || use instanceof NewNode || use instanceof ArrayInitNode ) return; - if( pointer(use) && (use instanceof PhiNode || use instanceof GuardNode || use instanceof ReadOnlyNode || - use instanceof ConstructNode || use instanceof InitViewNode) ) return; - if( use.isFunLeaf() && !(use instanceof ReturnNode) ) return; - if( later(use) ) reject("use #"+use._nid+" ("+use.label()+") survives deletion"); - } - - private void after(CallNode call) { - if( call.cend()==null ) { reject("checkpoint has no continuation"); return; } - ArrayDeque<CFGNode> work=new ArrayDeque<>(); - work.push(call.cend()); - while( !work.isEmpty() ) { - CFGNode n=work.pop(); - if( _after.get(n._nid) || n._type.isHigh() ) continue; - _after.set(n._nid); - if( n instanceof ReturnNode ) continue; - for( Node use : n._outputs ) - if( use instanceof CFGNode next && !n.skip(next) ) { - if( next instanceof LoopNode loop && n==loop.back() && inside(call,loop) ) { - if( !_backedges.contains(loop) ) _backedges.add(loop); - } else work.push(next); - } - } - assert !_after.get(call._nid); - } - - private static boolean inside(CFGNode ctrl, LoopNode loop) { - for( CFGNode.LoopTree tree=ctrl._ltree; tree!=null; tree=tree._par ) - if( tree._head==loop ) return true; - return false; - } - - // The backedge is a call to the next iteration. The wrapper passes its - // current field, not a saved copy of its old field. Check explicit Phi - // arguments and invariant references used again, as well as stored copies - // of the replacement. This last check is deliberately conservative: a - // later iteration might kill a stored alias before growing, but we do not - // yet infer that ordering as part of an iteration's entry contract. - private void backedges(List<Node> nodes) { - IdentityHashMap<Node,CFGNode> controls=new IdentityHashMap<>(); - BitSet active=new BitSet(); - for( LoopNode loop : _backedges ) { - _next=new HashSet<>(); - if( _owner!=null ) for( Node use : loop._outputs ) - if( use instanceof PhiNode phi && phi.region()==loop && phi._type instanceof TypeMem mem && - (mem._alias==_alias || mem._alias==1) ) - _next.addAll(contents(phi.in(2),_owner,_field,_alias)); - // Include eventual exits as well as the next body. An invariant - // saved pointer returned after the loop also crosses this boundary. - BitSet next=new BitSet(); - ArrayDeque<CFGNode> work=new ArrayDeque<>(); - work.push(loop); - while( !work.isEmpty() ) { - CFGNode ctrl=work.pop(); - if( next.get(ctrl._nid) || ctrl._type.isHigh() ) continue; - next.set(ctrl._nid); - if( ctrl instanceof ReturnNode ) continue; - for( Node use : ctrl._outputs ) - if( use instanceof CFGNode cfg && !ctrl.skip(cfg) ) work.push(cfg); - } - for( Node n : nodes ) { - if( _reject!=null ) return; - // A helper after grow can retain the replacement through the - // wrapper. That effect precedes the NEXT grow, even though it - // does not precede this iteration's checkpoint. - if( n instanceof CallNode call && call!=_call && later(call) && inside(call,loop) && !borrow(call) ) { - Effects effect=effects(call); - if( effect==null ) reject("call #"+call._nid+" has unknown reference effects across deletion backedge"); - else for( var base : effect.stores.entrySet() ) for( var field : base.getValue().entrySet() ) - if( updated(field.getValue()) && !(base.getKey()==_owner && field.getKey().equals(_field)) ) - reject("replacement array alias stored across deletion backedge at call #"+call._nid); - } - if( n instanceof PhiNode phi && phi.region()==loop && pointer(phi) ) { - HashSet<Ref> carried=refs(phi.in(2)); - if( contains(phi.in(2)) || updated(carried) ) - reject("array reference crosses deletion backedge at Phi #"+phi._nid); - } - if( n instanceof StoreNode st && pointer(st.val()) && updated(refs(st.val())) ) { - CFGNode ctrl=Allocation.control(st,controls,active); - if( ctrl!=null && inside(ctrl,loop) && - !(refs(st.ptr()).equals(set(_owner)) && st._name.equals(_field)) ) - reject("replacement array alias stored across deletion backedge at #"+st._nid); - } - if( !pointer(n) || !contains(n) ) continue; - CFGNode birth=Allocation.control(n,controls,active); - if( birth!=null && next.get(birth._nid) ) continue; - for( Node use : n._outputs ) { - if( use==null || use.isFunLeaf() ) continue; - CFGNode ctrl=Allocation.control(use,controls,active); - if( ctrl!=null && next.get(ctrl._nid) ) - reject("array reference reused across deletion backedge at #"+use._nid); - } - } - } - _next=null; - } - - // Follow data/memory definitions to their controls. A floating load on - // pre-delete memory may run before delete; a pointer returned afterwards - // is itself a post-delete use. No scheduling or graph mutation is needed. - private boolean later(Node node) { - BitSet seen=new BitSet(); - ArrayDeque<Node> work=new ArrayDeque<>(); - work.push(node); - while( !work.isEmpty() ) { - Node n=work.pop(); - if( seen.get(n._nid) ) continue; - seen.set(n._nid); - if( n instanceof CFGNode ) { - if( _after.get(n._nid) ) return true; - continue; - } - if( n instanceof PhiNode phi ) { work.push(phi.region()); continue; } - if( n.isFunLeaf() ) continue; - for( Node in : n._inputs ) if( in!=null ) work.push(in); - } - return false; - } - - @Override public String toString() { - SB sb=new SB().p("delete at call #").p(_call._nid).p(": "); - if( _reject!=null ) return sb.p("REJECT: ").p(_reject).toString(); - if( _unique!=null ) sb.p("requires unique entry ").p(_requirement.toString()).p("; "); - return sb.p("no surviving array access").toString(); - } -} diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java index 302f1491..0585f888 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java @@ -29,7 +29,7 @@ public class CodeGen { IterPostOpto, // Peepholes and inlining using SCCP results FinalizeIR, // Field layout, offset cleanup, function/CU roots LoopTree, // Containing loops for allocation analysis - Allocation, // Symbolic allocation destinations; analysis only + Allocation2, // Allocation-site points-to analysis TypeCheck, // Last check for bad programs Serialize, // Save ideal IR, including opaque class initialization Lower, // Expand checked class initialization to ordinary IR @@ -200,7 +200,7 @@ public class CodeGen { // Field layouts; field symbols become constant offsets step(target, Phase.FinalizeIR, this::finalizeIR, dump); step(target, Phase.LoopTree, this::loopTree, dump); - step(target, Phase.Allocation, this::allocation, dump); + step(target, Phase.Allocation2, this::allocation2, dump); // Final error check - bad programs fail here step(target, Phase.TypeCheck, this::typeCheck, dump); // Save reloadable ideal IR for a later seperate compilation @@ -432,9 +432,6 @@ public class CodeGen { public CodeGen opto() { return phase(Phase.Opto, _phase==Phase.Iter, () -> Opto.opto(this)); } public CodeGen iterPostOpto() { return phase(Phase.IterPostOpto, _phase==Phase.Opto, () -> { - // The call graph is settled. Peepholes can now ask which aliases a - // call preserves; later inlining only removes possible effects. - _effects=FunctionEffects.analyze(this); _iter.iterate(this); }); } @@ -528,21 +525,19 @@ public class CodeGen { // --------------------------- // Last check for bad programs - public Allocation _allocation; - public IdentityHashMap<FunNode,FunctionEffects> _effects; - public CodeGen allocation() { + public Allocation2 _allocation2; + public CodeGen typeCheck() { + if( _phase==Phase.FinalizeIR || _phase==Phase.LoopTree ) allocation2(); + return phase(Phase.TypeCheck, _phase==Phase.Allocation2, () -> TypeCheck.run(this)); + } + public CodeGen allocation2() { if( _phase==Phase.FinalizeIR ) loopTree(); - return phase(Phase.Allocation, _phase==Phase.LoopTree, () -> { - _effects = FunctionEffects.analyze(this); - _allocation = new Allocation(this); - if( Boolean.getBoolean("simple.alloc.dump") ) System.out.print(_allocation); - if( Boolean.getBoolean("simple.alloc.check") ) _allocation.requireSupported(); + return phase(Phase.Allocation2, _phase==Phase.LoopTree, () -> { + _allocation2 = new Allocation2(this); + if( Boolean.getBoolean("simple.alloc2.dump") ) + System.out.print(_allocation2); }); } - public CodeGen typeCheck() { - if( _phase==Phase.FinalizeIR || _phase==Phase.LoopTree ) allocation(); - return phase(Phase.TypeCheck, _phase==Phase.Allocation, () -> TypeCheck.run(this)); - } // --------------------------- // TypeCheck queued surviving CLInits during its existing error walk. @@ -551,11 +546,10 @@ public class CodeGen { } // --------------------------- - // Build containing loops without changing control flow before TypeCheck - // and serialization. Scheduling adds exits to zero-exit loops later. + // Normalize loops, including synthetic exits, before allocation analysis. public CodeGen loopTree() { return phase(Phase.LoopTree, _phase==Phase.FinalizeIR, - () -> _start.buildLoopTree(_linker,_stop,false)); + () -> _start.buildLoopTree(_linker,_stop)); } // --------------------------- @@ -598,8 +592,8 @@ public class CodeGen { private void unlink(boolean removeImports) { phase(Phase.Unlink, (_phase==Phase.Lower || _phase==Phase.TypeCheck || _phase==Phase.Serialize), () -> { KeepAliveNode.erase(_start); - // Lower can change CFG membership. Rebuild for scheduling, now - // including synthetic exits for loops with no exits at all. + // Lower can change CFG membership. Rebuild for scheduling; + // already-normalized loops keep their existing synthetic exits. _start.rebuildLoopTree(_linker,_stop); _start.setDef(2,null); // Releases the compiler-only escape analysis. if( removeImports ) Unlink.run(this,true); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FinalizeIR.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FinalizeIR.java index 69e0104d..bff0b0ba 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FinalizeIR.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FinalizeIR.java @@ -3,7 +3,7 @@ package com.seaofnodes.simple.codegen; import com.seaofnodes.simple.node.*; import java.util.Arrays; -// Comnpute field layouts only after SCCP and its peepholes converge. +// Compute field layouts after SCCP settles. // Keep surviving functions rooted without introducing unknown callers. abstract class FinalizeIR { static void run(CodeGen code) { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionEffects.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionEffects.java deleted file mode 100644 index 9094f635..00000000 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionEffects.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.seaofnodes.simple.codegen; - -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.*; -import java.util.*; - -/** Effects introduced by a function, independent of its incoming memory. - * Scan each body once, then union effects along call edges to a fixed point. - * This includes recursion and paths which never reach Return. */ -public final class FunctionEffects { - public int[] _writes; - public boolean _referenceWrites; - public TypeMem _escapes; - private final ArrayList<FunNode> _callees = new ArrayList<>(); - - public FunctionEffects(int[] writes, boolean referenceWrites, TypeMem escapes) { - _writes=writes; _referenceWrites=referenceWrites; _escapes=escapes; - } - private FunctionEffects() { this(XInt.EMPTY,false,TypeMem.START); } - - public static IdentityHashMap<FunNode,FunctionEffects> analyze(CodeGen code) { - IdentityHashMap<FunNode,FunctionEffects> effects=new IdentityHashMap<>(); - for( FunNode fun : code._linker ) - if( fun!=null && !fun.isDead() && !fun._type.isHigh() ) { - FunctionEffects effect=fun.summary()==null ? new FunctionEffects() : fun.summary()._effects; - effects.put(fun,effect); - if( fun.summary()==null ) effect.collect(fun); - } - // Sets only grow. Recursive components need no special fallback and - // cannot accidentally prove themselves effect-free before convergence. - boolean changed; - do { - changed=false; - for( FunctionEffects effect : effects.values() ) - for( FunNode callee : effect._callees ) { - FunctionEffects child=effects.get(callee); - changed |= effect.merge(child); - } - } while( changed ); - return effects; - } - - private boolean merge(FunctionEffects other) { - int[] writes=other==null ? XInt.FULL : XInt.meet(_writes,other._writes); - boolean refs=other==null || _referenceWrites || other._referenceWrites; - TypeMem escapes=other==null ? TypeMem.BOT : _escapes.escapes(other._escapes); - boolean changed=writes!=_writes || refs!=_referenceWrites || escapes!=_escapes; - _writes=writes; _referenceWrites=refs; _escapes=escapes; - return changed; - } - - private void collect(FunNode fun) { - BitSet seen=new BitSet(); - ArrayDeque<Node> work=new ArrayDeque<>(); - work.push(fun); work.push(fun.ret()); - while( !work.isEmpty() ) { - Node n=work.pop(); - if( seen.get(n._nid) ) continue; - seen.set(n._nid); - if( n instanceof CFGNode cfg && !(cfg instanceof ReturnNode) && - (cfg==fun || !cfg.isFunLeaf()) ) - for( Node use : cfg._outputs ) - if( use instanceof CFGNode next && !cfg.skip(next) && !next._type.isHigh() ) work.push(next); - if( n.isFunLeaf() ) continue; - // Replacing the effect table can enable an alias-preservation peep - // even though no graph type changed. Wake its consumers explicitly. - if( n instanceof LoadNode load && "$init".equals(load._name) ) CodeGen.CODE.add(load); - // Raw addresses can hide a reference in an otherwise scalar store. - // Until raw effects have their own contract, they block ownership proofs. - if( n instanceof PtrToIntNode ) _referenceWrites=true; - if( n instanceof StoreNode st ) { - int alias=st._alias; - if( alias==1 && st.ptr()._type instanceof TypeMemPtr ptr ) { - Field field=ptr._obj.field(st._name); - if( field!=null ) alias=field._alias; - } - _writes=alias==1 ? XInt.FULL : XInt.make(_writes,alias); - if( reference(st.val()._type) ) { - _referenceWrites=true; - expose(st.val()); - } - } - if( n instanceof EscapeNode esc && !esc._borrow ) { - _writes=XInt.make(_writes,esc.fld()._alias); - _referenceWrites |= reference(esc.fld()._t); - } - if( n instanceof CLInitNode init && !init.bypass() ) { - FunNode target=CodeGen.CODE.link(init.cu()); - if( target==null ) merge(null); - else _callees.add(target); - } - if( n instanceof CallNode call ) call(call); - if( n instanceof CallEndNode end ) { work.push(end.call()); continue; } - // Memory walks find even unpinned Stores. Stop at incoming Parms, - // constants, and interprocedural return edges, not their cached types. - for( Node in : n._inputs ) if( in!=null ) work.push(in); - } - } - - private static boolean reference(Type t) { - return !(t instanceof TypeInteger || t instanceof TypeFloat) && !t.isHigh() && t!=Type.NIL; - } - - private void expose(Node value) { - // Incoming references are supplied at each imported call, not frozen - // into a library-wide set of possible callbacks. All reference arguments - // still conservatively escape when applying the summary. - if( value instanceof ParmNode parm && !(parm._idx==2 && parm.fun().isClz()) ) return; - _escapes=_escapes.escapesFrom(value._type); - } - - private void call(CallNode call) { - if( Intrinsic.pure(call) ) return; - // The terminating native has no returning memory effects. - boolean exits=call.cend()._type instanceof TypeTuple tt && tt.mem()==TypeMem.TOP; - TypeFunPtr fp=call.fptr()._type instanceof TypeFunPtr f ? f : null; - boolean unknown=fp==null || XInt.isHigh(fp.fidxs()); - boolean external=unknown; - if( !unknown ) - for( int idx=XInt.next(fp.fidxs(),0); idx>=0; idx=XInt.next(fp.fidxs(),idx) ) { - FunNode target=CodeGen.CODE.link(idx); - if( target==null ) external=true; - else _callees.add(target); - } - if( external && !exits ) { _writes=XInt.FULL; _referenceWrites=true; } - // Simple callees can retain parameters too. Using their actuals keeps - // this conservative without importing the caller's entire memory state. - int first=fp!=null && fp.nargs()>0 && fp.arg(0)==TypePtr.PTR ? 3 : 2; - for( int i=first; i<call.nIns()-1; i++ ) expose(call.in(i)); - } -} diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java index c6bf483d..31c71d27 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java @@ -4,19 +4,18 @@ import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.type.*; // The small, eagerly readable part of a function's serialized implementation. -record FunctionSummary(TypeFunPtr sig, TypeTuple state, String name, int size, int[] classDependencyFIDXs, - FunctionEffects effects, Allocation.Summary allocation) { +record FunctionSummary(TypeFunPtr sig, TypeTuple state, String name, int size, int[] classDependencyFIDXs) { void install(CodeGen code, CompUnit cu) { FunNode fun = new FunNode(null,sig,name,cu,null,cu._start); fun._approxUIDs=size; fun.init(); // First user stays in output slot zero until the summary is removed. - SummaryNode body = new SummaryNode(state,classDependencyFIDXs,effects,allocation,fun); + SummaryNode body = new SummaryNode(state,classDependencyFIDXs,fun); ParmNode rpc = new ParmNode("$rpc",0,TypeRPC.BOT,fun,code.con(TypeRPC.BOT)).init(); ParmNode mem = new ParmNode("$mem",1,TypeMem.BOT,fun,cu._start.proj(1)).init(); body.addDef(mem); for( int i = 0; i<sig.nargs(); i++ ) - body.addDef(new ParmNode("arg"+i,i+2,sig.arg(i),fun,code.con(sig.arg(i))).init()); + body.addDef(new ParmNode("arg"+i,i+2,sig.arg(i),fun,code.con(fun.defaultArg(i))).init()); body.init(); Node ctrl = new CProjNode(body,0,"ctrl").init(); Node memory = new ProjNode(body,1,"mem").init(); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java index 83c0677d..d7837c43 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java @@ -1,6 +1,6 @@ package com.seaofnodes.simple.codegen; -import com.seaofnodes.simple.codegen.IterPeeps.WorkList; +import com.seaofnodes.simple.util.WorkList; import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.type.*; import com.seaofnodes.simple.util.Ary; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java index fe935a69..54ccef09 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java @@ -3,11 +3,10 @@ package com.seaofnodes.simple.codegen; import com.seaofnodes.simple.type.Type; import com.seaofnodes.simple.type.TypeInteger; import com.seaofnodes.simple.util.Ary; +import com.seaofnodes.simple.util.WorkList; import com.seaofnodes.simple.node.*; -import java.util.Arrays; import java.util.BitSet; import java.util.IdentityHashMap; -import java.util.Random; /** * The IterPeeps runs after parsing. It iterates the peepholes to a fixed point @@ -111,8 +110,7 @@ public class IterPeeps { Node x = n.peepholeOpt(); if( n instanceof CallEndNode cend ) _workInline.push(cend); - if( x != null ) { - assert !x.isDead(); // Peepholes return alive answers + if( x != null && !x.isDead() ) { // 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 @@ -275,84 +273,4 @@ public class IterPeeps { return cfg==null ? "null" : cfg.getClass().getSimpleName()+"#"+cfg._nid+" "+cfg; } - /** - * Classic WorkList, with a fast add/remove, dup removal, random pull. - * The Node's nid is used to check membership in the worklist. - */ - @SuppressWarnings("unchecked") - 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; - - public 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( Ary<E> ary ) { - for( E n : ary ) - push(n); - } - public void addAll( E[] es ) { - for( E n : es ) - push(n); - } - - - /** - * True if Node is on the WorkList - */ - public boolean on( E x ) { return _on.get(x._nid); } - - /** - * Removes a random Node from the WorkList; null if WorkList is empty - */ - public E pop() { - if( _len == 0 ) return null; - int idx = _R.nextInt(_len); - E x = (E)_es[idx]; - _es[idx] = _es[--_len]; // Compress array - _es[_len] = null; - _on.clear(x._nid); - return x; - } - - public boolean isEmpty() { return _len==0; } - public void clear() { - Arrays.fill(_es,0,_len,null); - _len = 0; - _on.clear(); - _R.setSeed(_seed); - _totalWork = 0; - } - } } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java index f90d8d4e..cdd09c1a 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java @@ -1,6 +1,6 @@ package com.seaofnodes.simple.codegen; -import com.seaofnodes.simple.codegen.IterPeeps.WorkList; +import com.seaofnodes.simple.util.WorkList; import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.type.*; import com.seaofnodes.simple.util.Ary; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java index 6d653835..4d6fb84d 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java @@ -2,7 +2,7 @@ package com.seaofnodes.simple.codegen; import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.parser.Parser; -import com.seaofnodes.simple.codegen.IterPeeps.WorkList; +import com.seaofnodes.simple.util.WorkList; import com.seaofnodes.simple.type.*; import com.seaofnodes.simple.util.Ary; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java index c3ae2566..49c11e8c 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java @@ -104,15 +104,8 @@ public class Serialize { BAOS baos = new BAOS(); // A - Print the C0DE header; last byte is the version number. - // Format 2: gradual packed ints, UTF-8 strings, sparse MemMerge edges, - // and wider singleton function IDs. Reject old cached objects clearly. - // Format 3 retains lexical raw-address lifetime endpoints in bodies. - // Format 4 adds the deletable-array capability and allocation flag. - // Format 5 stores per-function effects, not the unit's incoming memory. - // Format 6 adds symbolic allocation contracts beside function effects. - // Format 7 carries consuming argument/field requirements. - // Format 8 marks effects not represented by the allocation field graph. - baos.write('C').write('0').write('D').write('8'); + // Format 10 removes the retired allocation/effect contracts. + baos.write('C').write('0').write('D').write('A'); // Count unique Types var types = new HashMap<Type,Integer>(); @@ -132,13 +125,7 @@ public class Serialize { if( n instanceof CallEndNode cend ) cend._rpc.gather(types); if( n instanceof FunNode fun ) { fun.sig().gather(types); - TypeTuple state = (TypeTuple)fun.ret()._type; - TypeMem mem = (TypeMem)state.mem(); - // Only effects introduced by this function and its callees. - // Incoming memory and unrelated exported functions are not effects. - TypeMem escaped = CodeGen.CODE._effects.get(fun)._escapes; - mem=mem.makeFrom(escaped._escFs,escaped._escAs); - state=state.makeFrom(1,mem); + TypeTuple state = fun.returnState(); summaries.put(fun,state); state.gather(types); } @@ -257,14 +244,6 @@ public class Serialize { int[] edges = _init._edgess[fun.sig().fidx()]; baos.packed4(edges==null ? 0 : edges.length); if( edges!=null ) for( int edge : edges ) baos.packed4(edge); - FunctionEffects effect=CodeGen.CODE._effects.get(fun); - baos.packed1(effect._referenceWrites ? 1 : 0); - if( effect._writes==XInt.FULL ) baos.packed4(-1); - else { - baos.packed4(XInt.bitCount(effect._writes)); - for( int alias=XInt.next(effect._writes,0); alias>=0; alias=XInt.next(effect._writes,alias) ) baos.packed4(alias); - } - Allocation.write(baos,CodeGen.CODE._allocation.summary(fun)); } // D - Write the nodes. Since this is expected to be the bulk of the @@ -349,7 +328,7 @@ public class Serialize { Type.TAGOFFS(); // A - Read a header - if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='8' ) + if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='A' ) throw new IllegalArgumentException("Unsupported serialized IR format; rebuild the object file"); // B - Packed read of #strings, then strings @@ -382,7 +361,7 @@ public class Serialize { String[] strs = elf._strs; if( strs == null ) { // A - Read a header - if( bais.read() != 'C' || bais.read() != '0' || bais.read() != 'D' || bais.read() != '8' ) + if( bais.read() != 'C' || bais.read() != '0' || bais.read() != 'D' || bais.read() != 'A' ) throw new IllegalArgumentException( "Unsupported serialized IR format; rebuild the object file" ); // B - Packed read of #strings, then strings @@ -458,12 +437,7 @@ public class Serialize { int size = bais.packed4(); int[] edges = new int[bais.packed4()]; for( int j = 0; j<edges.length; j++ ) edges[j]=fidxs.map(fileFidxs,bais.packed4()); - boolean refs=bais.packed1()!=0; - int count=bais.packed4(); - int[] writes=count<0 ? XInt.FULL : XInt.EMPTY; - for( int j=0; j<count; j++ ) writes=XInt.make(writes,aliases.map(fileAliases,bais.packed4())); - elf._functions[i]=new FunctionSummary(sig,state,name.isEmpty() ? fidxs.symbol(sig.fidx()) : name,size,edges, - new FunctionEffects(writes,refs,state.mem()),Allocation.read(bais)); + elf._functions[i]=new FunctionSummary(sig,state,name.isEmpty() ? fidxs.symbol(sig.fidx()) : name,size,edges); } return elf._types = new TypeRead(types,strs,fileAliases,fileFidxs,fileRpcs); } @@ -511,6 +485,10 @@ public class Serialize { if( n instanceof FunNode fun ) { assert cu != null; fun._compunit = cu; + for( FunctionSummary summary : elf._functions ) if( summary.sig().fidx()==fun.sig().fidx() ) { + if( summary.state().ctl()==Type.XCONTROL ) fun._semanticReturn=summary.state(); + break; + } if( fun._name==null || fun._name.isEmpty() ) fun._name=fidxs.symbol(fun.sig().fidx()); } if( n instanceof ExternNode ext && ext._con instanceof TypeFunPtr tfp && tfp.isConstant() ) { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java index c1773ece..dc2c4e4e 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java @@ -58,13 +58,6 @@ abstract class TypeCheck { if( code._obs != null ) code._obs.error(min, min.err().getMessage()); throw min.err(); } - // Incoming requirements are part of the function's checked contract; - // Allocation has substituted and checked them at each concrete caller. - for( ArrayDelete deletion : code._allocation._deletes ) { - if( deletion._reject!=null || (!deletion.proven() && deletion._requirement==null) ) - throw Parser.error(deletion.toString(),deletion._call._loc); - } - code._allocation.checkOwnership(); // Checked construction boundaries and views have no runtime behavior. Gathered // above during the existing error walk; no separate graph pass/solve. diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java index bd876a01..5a170a75 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java @@ -38,7 +38,7 @@ abstract class Unlink { } code.releaseUnlinkedNodes(); for( Node n : nodes ) - if( n instanceof StartCUNode unitStart ) detachEmptyStart(unitStart); + if( n instanceof StartCUNode unitStart ) detachUnscheduledStart(unitStart); // A summary is a dispatch target, not a schedulable implementation. // Retain its own wrapper graph without including it in this schedule. for( int i = 0; i<stop.nIns(); i++ ) { @@ -143,7 +143,7 @@ abstract class Unlink { } code.releaseUnlinkedNodes(); for( CompUnit cu : code._compunits.values() ) - if( cu._start!=null && !cu._start.isDead() ) detachEmptyStart(cu._start); + if( cu._start!=null && !cu._start.isDead() ) detachUnscheduledStart(cu._start); code._stop.walk(n -> { if( n instanceof CallEndNode cend ) @@ -156,10 +156,17 @@ abstract class Unlink { }); } - private static void detachEmptyStart(StartCUNode start) { - // An unused unit can lose its outer Stop edge during optimization. - // Detach its empty wrapper from the scheduling root as well. - if( start.in(1) instanceof StopCUNode stop && stop.nIns()==0 ) start.setDef(0,null); + private static void detachUnscheduledStart(StartCUNode start) { + // Empty units and unloaded summaries have no body to schedule. An + // internal imported callee can retain its summary wrapper even after + // losing the outer Stop edge; detach its Start edge as well. + if( !(start.in(1) instanceof StopCUNode stop) ) return; + for( Node n : stop._inputs ) + if( ((ReturnNode)n).fun().summary()==null ) return; + start.setDef(0,null); + for( Node use : stop._outputs.asAry() ) + if( use instanceof StopNode outer ) + outer.delDef(outer._inputs.find(stop)); } private static void restoreRPC(FunNode fun) { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java index 7cbf3f9b..ebcec43a 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java @@ -224,10 +224,6 @@ public abstract class CFGNode extends Node { } public void buildLoopTree( Ary<FunNode> funs, StopNode stop) { - buildLoopTree(funs,stop,true); - } - - public void buildLoopTree( Ary<FunNode> funs, StopNode stop, boolean forceExits) { _ltree = stop._ltree = CodeGen.CODE.XCTRL._ltree = new LoopTree((StartNode)this); Ary<FunNode> work = new Ary<>(FunNode.class); @@ -248,11 +244,11 @@ public abstract class CFGNode extends Node { } for( int i=0; i<work._len; i++ ) - pre = work.at(i)._bltWalk(pre,work.at(i),stop, post, work,forceExits); + pre = work.at(i)._bltWalk(pre,work.at(i),stop, post, work); post.clear(); } - int _bltWalk( int pre, FunNode fun, StopNode stop, BitSet post, Ary<FunNode> work, boolean forceExits ) { + int _bltWalk( int pre, FunNode fun, StopNode stop, BitSet post, Ary<FunNode> work ) { // Pre-walked? if( _pre!=0 ) return pre; _pre = pre++; @@ -274,7 +270,7 @@ public abstract class CFGNode extends Node { if( skip( usecfg ) ) { if( usecfg._pre==0 && usecfg instanceof FunNode fun2 && fun2.summary()==null ) work.add( fun2 ); } else - pre = usecfg._bltWalk( pre, use instanceof FunNode fuse ? fuse : fun, stop, post, work,forceExits ); + pre = usecfg._bltWalk( pre, use instanceof FunNode fuse ? fuse : fun, stop, post, work ); } // Post-order work: find innermost loop @@ -298,9 +294,7 @@ public abstract class CFGNode extends Node { if( ltree._par == null ) { // This loop never had an If test choose to take its // exit, i.e. it is a no-exit infinite loop. - // Analysis needs its nesting, but a synthetic exit - // must not change nonreturning summaries in .simple. - if( forceExits ) ltree._head.forceExit(fun,stop); + ltree._head.forceExit(fun,stop); ltree._par = fun._ltree; } ltree = ltree._par; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java index a8a6151c..c7dcb128 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java @@ -66,8 +66,8 @@ public class EscapeNode extends TypeNode { public Type compute() { // A static constant array has no private heap writes to publish. // This depends on its type, regardless of which node produced it. - if( self()!=null && self()._type instanceof TypeMemPtr ptr && - ptr.isConstant() && ptr._obj.isConAry() ) return pub()._type; + if( self()!=null && self()._type instanceof TypeMemPtr ptr && ptr.isConstant() && ptr._obj.isConAry() ) + return pub()._type; if( priv()._type.isHigh() ) return TypeMem.TOP; if( pub ()._type.isHigh() ) return TypeMem.TOP; TypeMem mpriv = (TypeMem)priv()._type; @@ -83,24 +83,31 @@ public class EscapeNode extends TypeNode { assert !(mpub._t instanceof TypeStruct); // Never expect this, but if it starts to happen, need to optimize Type tpub = mpub._t; + // A partially complete object + if( _borrow ) { + Type bound = fld._t; + if( bound instanceof TypeMemPtr ptr && TypeMemPtr.mayBePartial(tpriv) ) + bound = ptr.withPartial(true).partialBound(); + // t is meet of pub & priv. Pub memory can be very weak (e.g. alias 1) + // and we're no worse than the declared field type + Type t = tpriv.meet(tpub).join(bound); + // Lending memory to a local read-only partial argument is an ordering + // edge, not publication to unknown callers. Keep the public escape sets. + return TypeMem.make(fld._alias,t,false,false,false,mpub._escFs,mpub._escAs); + } + // t is meet of pub & priv. Pub memory can be very weak (e.g. alias 1) // and we're no worse than the declared field type - Type bound = fld._t; - if( _borrow && bound instanceof TypeMemPtr ptr && TypeMemPtr.mayBePartial(tpriv) ) - bound = ptr.withPartial(true).partialBound(); - Type t = tpriv.meet(tpub).join(bound); - // Lending memory to a local read-only partial argument is an ordering - // edge, not publication to unknown callers. Keep the public escape sets. - if( _borrow ) - return TypeMem.make(fld._alias,t,false,false,false,mpub._escFs,mpub._escAs); - int[] fidxes = XInt.meet(mpriv._escFs, mpub._escFs); - int[] aliases = XInt.meet(mpriv._escAs, mpub._escAs); - // Keep escapes from the actual private value before narrowing it to - // the declaration. Selecting its Store from a MemMerge must preserve - // this result, including Scalar.BOT's unknown pointer escapes. - TypeMem defaults = CodeGen.CODE._phase.ordinal()<CodeGen.Phase.Opto.ordinal() ? TypeMem.BOT : mpub; - return TypeMem.make(fld._alias, t, false, false, fld._final, fidxes, aliases) - .escapesFrom(tpriv,defaults).escapesFrom(t,defaults); + Type t = tpriv.meet(tpub).join(fld._t); + + // Opaque contents can expose identities already in public memory. + if( TypeMem.opaque(t) ) { + return TypeMem.make(fld._alias,t,false,false,fld._final,mpub._escFs,mpub._escAs); + } + // Escape pub memory, plus 't' + return TypeMem.make(fld._alias,t,false,false,fld._final,mpub._escFs,mpub._escAs) + .escapesFrom(t,mpub); + } @Override public Node idealize() { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java index e49162f4..93f2baf9 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java @@ -31,7 +31,7 @@ public class FldOffNode extends TypeNode { } @Override public Type compute() { - return Type.BOTTOM; + return TypeInteger.BOT; } @Override public Node idealize() { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java index 632b5fb4..c2604d35 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java @@ -28,6 +28,11 @@ public class FunNode extends RegionNode { public CompUnit _compunit; // Defined in source file public final boolean _extern; // External function; no code, name only + // Return state before Never adds structural exits. Export/diagnostics must + // not mistake a synthetic exit for an execution which returns normally. + public TypeTuple _semanticReturn; + public TypeTuple returnState() { return _semanticReturn==null ? (TypeTuple)ret()._type : _semanticReturn; } + private FunNode( Lexer loc, Node[] nodes, TypeFunPtr sig, String name, CompUnit compunit, boolean ext ) { super(loc,nodes); _name = name; @@ -42,6 +47,7 @@ public class FunNode extends RegionNode { _name = fun._name; _compunit = fun._compunit; _extern = fun._extern; + _semanticReturn = fun._semanticReturn; } @Override public Tag serialTag() { return Tag.Fun; } @Override public void packed(BAOS baos, HashMap<String,Integer> strs, HashMap<Type,Integer> types, IdentityHashMap<Node,Integer> anodes ) { @@ -104,8 +110,15 @@ public class FunNode extends RegionNode { // uniform call syntax, including callbacks forwarded by another class. public Type defaultArg(int idx) { Type t = sig().arg(idx); + // Default private construction memory publishes no identities. Keep + // its unknown contents and the broad signature for actual callers. + if( t instanceof TypeMem mem && mem._one ) + return mem.makeFrom(XInt.EMPTY,XInt.EMPTY); + // Partial objects have stronger constraints if( t instanceof TypeMemPtr ptr && ptr._partial && - !(idx==0 && sig().nargs()>1 && sig().arg(1) instanceof TypeMem) ) return ptr.partialBound(); + !(idx==0 && sig().nargs()>1 && sig().arg(1) instanceof TypeMem) ) + return ptr.partialBound(); + // Normal default args just use the signature if( idx!=0 || t!=TypePtr.PTR ) return t; TypeStruct clz = (TypeStruct)Parser.TYPES.get(TypeStruct.addClzPrefix(_compunit._cname)); assert clz!=null; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/GlobalEscapeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/GlobalEscapeNode.java index 740b0895..9ef20c77 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/GlobalEscapeNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/GlobalEscapeNode.java @@ -18,18 +18,13 @@ public class GlobalEscapeNode extends Node { @Override public TypeMem compute() { TypeMem xmem = TypeMem.START; for( CallNode call : CodeGen.CODE._calls ) - if( !call.isDead() ) { + if( !call.isDead() ) xmem = xmem.escapes(call.exposed(this)); - } for( FunNode fun : CodeGen.CODE._linker ) - if( fun!=null && fun.summary()!=null && !fun.summary().isDead() ) { + if( fun!=null && fun.summary()!=null && !fun.summary().isDead() ) xmem = xmem.escapes(fun.summary().exposed(this)); - // A reachable unloaded body can call these targets, including - // private initializers. Its arguments are unavailable here. - if( fun._type==Type.CONTROL ) - for( int fidx : fun.summary()._classDependencyFIDXs ) - if( fidx!=0 ) xmem = xmem.makeFrom(XInt.meet(xmem._escFs,XInt.make(fidx)),xmem._escAs); - } + // Do not follow class-init dependencies; class A might trigger class B + // to init, but this does not escape class B directly. return xmem; } } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/InitViewNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/InitViewNode.java index 46988a99..877eb48d 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/InitViewNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/InitViewNode.java @@ -15,7 +15,7 @@ public class InitViewNode extends TypeNode { if( ptr.isHigh() || mem.isHigh() ) return Type.TOP; if( !(ptr instanceof TypeMemPtr p) ) return ptr; TypeStruct state = mem instanceof TypeMem m && m._one && m._t instanceof TypeStruct ts - ? ts : p._obj.makeInit(); + ? ts : p._obj.makeInit(false); // An earlier alias can have fewer initialized slots. The declaration // supplies field types; this program point's memory supplies the proof. return p.makeFrom(((TypeMemPtr)_con)._obj).withPartial(true).initialized(state); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java index 7db31fe3..f9263fc7 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java @@ -7,7 +7,7 @@ import java.util.BitSet; import java.util.ArrayDeque; /** A lexical lifetime endpoint. This is a control use, not a machine operand. - * Kept values may be raw addresses; Allocation follows them back to storage. + * Kept values may be raw addresses; their storage remains reachable through the conversion. * Retained in .simple and through inlining; erased before scheduling. */ public class KeepAliveNode extends CFGNode { public KeepAliveNode(Node ctrl, Node value) { super(ctrl,value); } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java index 52dbfa8e..287ae8c8 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java @@ -260,30 +260,6 @@ public class LoadNode extends MemOpNode { boolean ready=false; if( mem instanceof MemMergeNode merge ) ready=classInitialized(merge.alias(_alias),active); - else if( mem instanceof ProjNode proj && proj._idx==1 && proj.in(0) instanceof CLInitNode init ) { - addDep(init); - FunNode target=CodeGen.CODE.link(init.cu()); - if( target!=null ) { - addDep(target); - SummaryNode summary=target.summary(); - if( summary!=null && !XInt.bit(summary._effects._writes,_alias) ) - ready=classInitialized(init.mem(),active); - } - } - else if( mem instanceof ProjNode proj && proj._idx==1 && proj.in(0) instanceof CallEndNode end ) { - addDep(end); - if( end.in(0) instanceof CallNode call ) { - Type ftype=addDep(call.fptr())._type; - FunNode target=ftype instanceof TypeFunPtr fp && fp.isConstant() ? CodeGen.CODE.link(fp.fidx()) : null; - var effects=CodeGen.CODE._effects; - if( target!=null && effects!=null ) { - addDep(target); - var effect=effects.get(target); - if( effect!=null && !XInt.bit(effect._writes,_alias) ) - ready=classInitialized(call.mem(),active); - } - } - } else if( mem instanceof StoreNode st ) { if( st._alias==_alias ) ready=addDep(st.val())._type==TypeInteger.TRUE; else if( st._alias>1 ) ready=classInitialized(st.mem(),active); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java index 2ab76429..1f821246 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java @@ -51,6 +51,7 @@ public class LoopNode extends RegionNode { CProjNode f = new CProjNode(iff,1,"False").init(); setDef(2,t); // True continues loop, False (never) exits loop ReturnNode ret = fun.ret(); + if( fun._semanticReturn==null ) fun._semanticReturn=fun.returnState(); iff._ltree = t._ltree = _ltree; ret._ltree = f._ltree = fun._ltree; @@ -60,6 +61,7 @@ public class LoopNode extends RegionNode { // executing. Keep synthetic nodes local; do not GVN into that graph. Node top = ConstantNode.raw(Type.TOP); top.setDef(0,fun); + top.init(); MemMergeNode memout = new MemMergeNode(); memout.addDef(f); // placeholder for control memout.addDef(top); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java index a077e14b..d79473c7 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java @@ -131,7 +131,6 @@ public class MemMergeNode extends Node { } } return TypeMem.makePrivate(ts); - } // Normal public memory; meet across escaped inputs diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java index 88a1242a..8ce9d6e2 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java @@ -44,12 +44,13 @@ public class NewNode extends Node implements MultiNode { @Override public TypeTuple compute() { if( ctrl()._type.isHigh() ) return TypeTuple.DEAD_NEW; - TypeStruct ts = _ts.isAry() ? _ts : _ts.makeInit(); + boolean opto = CodeGen.CODE._phase.ordinal() >= CodeGen.Phase.Opto.ordinal(); + TypeStruct ts = _ts.isAry() ? _ts : _ts.makeInit(opto); + // Arrays get pre-zeroed by constructor. Object fields start at + // Scalar.BOT during parsing, Scalar.TOP during Opto; declaration + // defaults are explicit Stores. This is + // private memory, so no aliases escape yet. return TypeTuple.make(TypeMemPtr.make(_ts).withDelete(_deletable), - // Arrays get pre-zeroed by constructor. - // Object fields start at Scalar.BOT; declaration - // defaults are explicit Stores. This is private - // memory, so no aliases escape yet. TypeMem.make(1,ts,true,false,false,null,null)); } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java index f2972c91..d76aa201 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java @@ -71,6 +71,7 @@ public class ReturnNode extends CFGNode { } @Override public Parser.ParseException err() { + if( _fun._semanticReturn!=null && _fun._semanticReturn.ctl()==Type.XCONTROL ) return null; if( ctrl()._type == Type.CONTROL && expr()._type == Type.TOP ) return Parser.error("No defined return type",null); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java index ea2bdf03..4ebdd156 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java @@ -9,22 +9,12 @@ import java.util.HashMap; public class SummaryNode extends CFGNode implements MultiNode { public TypeTuple _state; - public final FunctionEffects _effects; - public final Allocation.Summary _allocation; // Callees and touched class initializers, by FIDX, for class-init cycle checks. public final int[] _classDependencyFIDXs; public SummaryNode(TypeTuple state, int[] classDependencyFIDXs, Node... inputs) { - this(state,classDependencyFIDXs,new FunctionEffects(XInt.FULL,true,state.mem()),inputs); - } - public SummaryNode(TypeTuple state, int[] classDependencyFIDXs, FunctionEffects effects, Node... inputs) { - this(state,classDependencyFIDXs,effects,null,inputs); - } - public SummaryNode(TypeTuple state, int[] classDependencyFIDXs, FunctionEffects effects, Allocation.Summary allocation, Node... inputs) { super(inputs); _state = state; - _effects = effects; - _allocation = allocation; _classDependencyFIDXs = classDependencyFIDXs; CodeGen.CODE.add(CodeGen.CODE._globalEscapes); } @@ -36,10 +26,8 @@ public class SummaryNode extends CFGNode implements MultiNode { if( in(0)._type.isHigh() ) return TypeTuple.STATE.dual(); // A library summary does not forget escapes already present in the caller. TypeMem mem = in(1)._type instanceof TypeMem m ? m : in(1)._type.isHigh() ? TypeMem.TOP : TypeMem.BOT; - if( _effects._writes!=XInt.EMPTY || _state.mem()._one ) - mem = (TypeMem)mem.meet(_state.mem()); - else mem = mem.escapes(_state.mem()); - for( int i = firstArgument(); i<nIns(); i++ ) { + mem = (TypeMem)mem.meet(_state.mem()); + for( int i = firstArgument(in(0)); i<nIns(); i++ ) { Type arg = in(i)._type; // Only opaque arguments can hide identities supplied by outside code. TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(this) : TypeMem.BOT; @@ -52,7 +40,7 @@ public class SummaryNode extends CFGNode implements MultiNode { dep.addDepForwards(this); if( dep.addDepForwards(in(0))._type.isHigh() ) return TypeMem.START; TypeMem mem = (TypeMem)_state.mem(); - for( int i = firstArgument(); i<nIns(); i++ ) { + for( int i = firstArgument(in(0)); i<nIns(); i++ ) { Type arg = dep.addDepForwards(in(i))._type; TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(dep) : TypeMem.BOT; mem = mem.escapesFrom(arg,outside); @@ -61,10 +49,11 @@ public class SummaryNode extends CFGNode implements MultiNode { } // A class receiver is supplied by the callee, not exposed by its caller. // Actual uses which publish self are already represented in _state. - private int firstArgument() { - if( !(in(0) instanceof FunNode fun) ) return 2; + public static int firstArgument(Node f) { + if( f==null ) return 3; // Extern calls ignore the passed clz ptr + FunNode fun = (FunNode)f; // Must be a FunNode TypeFunPtr sig = fun.sig(); - return fun.isClz() || sig.nargs()>0 && sig.arg(0)==TypePtr.PTR ? 3 : 2; + return fun.isClz() || (sig.nargs()>0 && sig.arg(0)==TypePtr.PTR) ? 3 : 2; } @Override boolean _upgradeType(HashMap<String,Type> types) { TypeTuple state = (TypeTuple)_state.upgradeType(types); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java index 8dad94ec..0ddd3a31 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java @@ -16,13 +16,8 @@ final class Allocations { Node parseNew() { P._lexer.skipWhiteSpace(); Lexer site=P.loc(); - Type t = P.types.parseType(); - if( t==null ) { - String tname = P._lexer.matchId(); - if( tname==null || Parser.KEYWORDS.contains(tname) ) - throw Parser.error("Expected a type after 'new'",site); - t = P.types.forwardRefType(tname); - } + Type t = P.types.parseType(true); + if( t==null ) throw Parser.error("Expected a type after 'new'",site); // Parse ary[ length_expr ] if( P.match("[") ) { boolean readonly = P.match("~"); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java index 5064c479..00ea624c 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java @@ -119,7 +119,7 @@ final class Functions { Type t = P.types.parseType(); // Arg type if( t==null ) break; P._lexer.skipWhiteSpace(); - Lexer qualifier=P.loc(); + Lexer qualifier = P.loc(); if( P.match("^") ) { if( !(t instanceof TypeMemPtr ptr) || ptr._obj.isAry() ) throw Parser.error("'^' requires a struct parameter",qualifier); @@ -128,7 +128,7 @@ final class Functions { } finals.set(ids.size(),P.declarations.bindingFinal(t)); P._lexer.skipWhiteSpace(); - Lexer nameLoc=P.loc(); + Lexer nameLoc = P.loc(); String id = P.requireId(); // Older free functions may explicitly name a source argument // "self". It shadows the implicit class receiver, not its ABI slot. diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java index f4103fe6..1f896f03 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java @@ -34,7 +34,7 @@ final class References { P.ctrl(),P.mem(),receiver,P.fldoff(receiver,name))); } - // Resolve a primary name, retaining its use site before speculative type lookup. + // Resolve a primary name, retaining its use site before class lookup. Node parseName(String id, int pre, int pos, int pos2) { Lexer site=P.loc(); site._position=pos; @@ -42,29 +42,16 @@ final class References { // Attempt a local var lookup first Var var = P._scope.lookup(id); if( var==null ) { - // Not a local var, try again as a type name - P.pos(pos); - Lexer nameLoc = P.loc(); - Type t = P.types.parseType(); - if( t!=null ) { - // Static <clinit> typename lookup - if( P.peek('.') ) // type.fld, which is really a field lookup in the class object - return P.expressions.parsePostfix(P.con(t)); - // Direct reference to a <clinit> type. Convert the instance - // type to a class type name - if( !(t instanceof TypeMemPtr tmp) ) { - //return new FRefNode(addClzPrefix(tmp._obj._name), loc()).peephole(); - // Not a local var, but yes a bare type... disallow a local - // FREF and return null, not-a-primary parse. - P.pos(pos); - return null; - } - } + // A class name is a value here. Resolve only this identifier; + // every following dot is a Load, never part of a type parse. + String name = P.types.knownTypeName(id); + Type clz0 = name==null ? null : Parser.TYPES.get(TypeStruct.addClzPrefix(name)); // Insert FREF outside enclosing Kind.Func scope. P.pos(pos2); - t = FRefNode.FREF_TYPE; + Type t = FRefNode.FREF_TYPE; // Check if this is a class. + // Even a known module needs an FRef so ParseAll records its dependency. CompUnit cu = ParseAll.findCompUnit(P._code,P._ref,id); if( cu!=null ) { // Must be a final class-type @@ -73,9 +60,10 @@ final class References { if( clz == null ) Parser.TYPES.put(clzName,clz = TypeStruct.make(clzName,true)); t = TypeMemPtr.make((byte)2,clz,true); - } + } else if( clz0 instanceof TypeStruct clz ) + return P.expressions.parsePostfix(P.con(TypeMemPtr.make((byte)2,clz,true))); // Define the FRef - var = P._scope.defineFRef(id,t,true,nameLoc); + var = P._scope.defineFRef(id,t,true,site); P.references._frefs.push((FRefNode)P._scope.in(var)); } @@ -187,7 +175,7 @@ final class References { } } - boolean arrayMethod="del".equals(name) && (ts==null || ts.isAry()); + boolean arrayMethod = "del".equals(name) && (ts==null || ts.isAry()); Field fld = ts==null ? null : ts.field(name); if( fld==null && ts!=null && !TypeStruct.startsClzPrefix(ts._name) ) { Type clz0 = Parser.TYPES.get(TypeStruct.addClzPrefix(ts._name)); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java index 92117531..48383a48 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java @@ -21,7 +21,11 @@ final class Types { // Will also match external names like "sys.io" or "externModule.subtype.subtype" - Type parseType() { + Type parseType() { return parseType(false); } + + // After new, a type needs no following binding. In a declaration/parameter + // an unknown name is only a type when followed by a binding name. + Type parseType(boolean allocation) { if( P.peek('{') ) return parseFunctionType(); int old1 = P.pos(); @@ -30,19 +34,14 @@ final class Types { String tname = P._lexer.matchId(); if( tname==null ) return P.posT(old1); + Ary<String> forwards = new Ary<>(String.class); Type t0 = Parser.TYPES.get(tname); if( Parser.KEYWORDS.contains(tname) ) { if( t0==null ) return P.posT(old1); } else { if( t0==Type.BOTTOM || t0==Type.TOP ) return t0; // var/val - tname = typeName(tname).intern(); + tname = typeName(tname,forwards).intern(); t0 = Parser.TYPES.get(tname); - // Bare forward types use the same file-relative name as `new`. - // A later sibling declaration must complete this very type. - if( t0 == null && tname.indexOf('.') == -1 ) { - tname = fullTypeName(tname); - t0 = Parser.TYPES.get(tname); - } } Type t1 = t0==null ? TypeStruct.forward(tname) : t0; @@ -78,36 +77,31 @@ final class Types { break; } - // Check no forward ref - if( t0 != null ) return t2; // Check valid forward ref, after parsing all the type extra bits. // Cannot check earlier, because cannot find required 'id' until after "[]?" syntax - int old2 = P.pos(); - P.match("^"); // Constructor parameter qualifier; parsed by Functions. - if( !P.match("!") ) P.match("~"); - String id = P._lexer.matchId(); - if( !(P.peek(',') || P.peek(';') || P.peek('=') || P.match("->")) || id==null ) - return P.posT(old1); // Reset lexer to reparse - P.pos(old2); // Reset lexer to reparse - // Yes a forward ref, so declare it - forwardRefType(tname,(TypeStruct)((TypeMemPtr)t1)._obj); + if( t0==null && !allocation ) { + int old2 = P.pos(); + P.match("^"); // Constructor parameter qualifier; parsed by Functions. + if( !P.match("!") ) P.match("~"); + String id = P._lexer.matchId(); + if( !(P.peek(',') || P.peek(';') || P.peek('=') || P.match("->")) || id==null ) + return P.posT(old1); // Reset lexer to reparse + P.pos(old2); // Reset lexer to reparse + } + // Commit only after recognizing a type, never during expression lookahead. + for( String name : forwards ) + forwardRefType(name,TypeStruct.forward(name)); // Return the (array, final) type return t2; } - TypeMemPtr forwardRefType( String tname, TypeStruct tself ) { + private void forwardRefType( String tname, TypeStruct tself ) { Parser.TYPES.put(tname,tself); String clzName = TypeStruct.addClzPrefix( tname ); // Only a struct declaration publishes an instance initializer. A // forward type may name a file with just <clinit>, so do not invent // a constructor field (or overwrite an already parsed class). Parser.TYPES.putIfAbsent(clzName,TypeStruct.make(clzName,true)); - return TypeMemPtr.make(tself); - } - - TypeMemPtr forwardRefType( String tname ) { - tname = fullTypeName(tname); - return forwardRefType(tname,TypeStruct.forward(tname)); } String fullTypeName( String tname ) { @@ -197,57 +191,52 @@ final class Types { return fld; } - // typeName: walk known local types first, then enclosing namespaces, then - // file modules. A missing suffix of a known type belongs to field parsing. - private String typeName(String name) { - if( Parser.TYPES.containsKey(name) ) return dottedName(name,false); + // TODO: Backport qualified-name parsing to Chapters 28a-32. + // Resolve only the first component. Expression lookup uses this without + // consuming member access; type lookup then consumes the qualified tail. + String knownTypeName(String name) { + if( Parser.TYPES.containsKey(name) || Parser.TYPES.containsKey(TypeStruct.addClzPrefix(name)) ) return name; String root = P._nestedType; int dot = root.indexOf('.'); if( dot!=-1 ) root = root.substring(0,dot); - if( name.equals(root) ) return rootedName(name); + if( name.equals(root) ) return name; for( String nest = P._nestedType; ; ) { String full = nest+"."+name; - if( Parser.TYPES.containsKey(full) ) return dottedName(full,false); + if( Parser.TYPES.containsKey(full) || Parser.TYPES.containsKey(TypeStruct.addClzPrefix(full)) ) return full; int idx = nest.lastIndexOf('.'); if( idx==-1 ) break; nest = nest.substring(0,idx); } - CompUnit cu = ParseAll.findCompUnit(P._code,P._ref,name); - return dottedName(cu==null ? name : cu._cname,true); + return null; } - private String dottedName(String name, boolean forward) { + private String typeName(String id, Ary<String> forwards) { + String name = knownTypeName(id); + if( name==null ) { + CompUnit cu = ParseAll.findCompUnit(P._code,P._ref,id); + name = cu==null ? fullTypeName(id) : cu._cname; + } + if( !Parser.TYPES.containsKey(name) ) forwards.push(name.intern()); while( true ) { int old = P.pos(); if( !P.match(".") ) return name; String part = P.matchId(); - if( part==null || (!forward && !Parser.TYPES.containsKey(name+"."+part)) ) { + if( part==null ) { P.pos(old); return name; } - name += "."+part; - } - } - - // A root-qualified name may introduce an as-yet-undeclared nested type - // inside the current lexical namespace. Once forward, keep its full tail. - private String rootedName(String name) { - boolean forward = false; - while( true ) { - int old = P.pos(); - if( !P.match(".") ) return name; - String part = P.matchId(); - if( part==null ) { P.pos(old); return name; } String full = name+"."+part; - boolean known = Parser.TYPES.containsKey(full); - if( !known && !forward && - !(P._nestedType.equals(name) || P._nestedType.startsWith(name+".")) ) { + Type parent = Parser.TYPES.get(name); + // Closed types can still be followed by an allocation's member + // access, e.g. new Counter.step(). Open types admit nested names, + // whether they are forward refs or definitions still being parsed. + if( !Parser.TYPES.containsKey(full) && parent instanceof TypeStruct ts && !ts._open ) { P.pos(old); return name; } - name = full; - forward |= !known; + name = full.intern(); + if( !Parser.TYPES.containsKey(name) ) forwards.push(name); } } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java index 1c83ddd7..05fd1795 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java @@ -97,7 +97,7 @@ public class TypeMem extends Type { } // Existing escapes plus `t` escapes public TypeMem escapesFrom(Type t) { - return make(_alias,_t,_one,_clz,_final, escapeFIDX(_escFs,t), escapeAlias(_escAs,t)); + return escapes(t); } // An opaque external object can expose the public interface and whatever // private values have already escaped. It cannot invent access to other @@ -184,6 +184,17 @@ public class TypeMem extends Type { @Override Type _upgradeType(HashMap<String,Type> TYPES) { return make(_alias,_t._upgradeType(TYPES),_one,_clz,_final,_escFs,_escAs); } + @Override public TypeMem upgradeType(HashMap<String,Type> TYPES) { + TypeMem mem = (TypeMem)super.upgradeType(TYPES); + Type t = mem._t; + // The recursive upgrade has finished; reset the escape set from FULL + // to what can be locally seen now + if( mem._one && mem._clz && mem._final && mem._alias!=1 && t.isConstant() && !opaque(t) ) + return make(mem._alias,t,mem._one,mem._clz,mem._final, + escapeFIDX (XInt.EMPTY,t), + escapeAlias(XInt.EMPTY,t)); + return mem; + } @Override int hash() { return 9876543 + _alias + _t.hashCode() + (_one ? 8196 : 0) + (_clz ? 4098 : 0) + (_final ? 16392 : 0) + XInt.hash(_escFs) + XInt.hash(_escAs); } @@ -270,7 +281,7 @@ public class TypeMem extends Type { case TypeFunPtr tfp -> XInt.meet(xs,tfp.fidxs()); case TypeMem mem -> XInt.meet(xs,mem._escFs); // An abstract pointer or scalar can refine to a concrete escaped - // object or function. Until then it must allow all of their bits. + // object or function. Until then, it must allow all of their bits. case TypePtr ptr -> ptr.isHigh() ? xs : XInt.FULL; case Type tt -> tt == BOTTOM || tt == TypeScalar.BOT ? XInt.FULL : xs; }; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java index 02d26a1e..6695bc81 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java @@ -101,7 +101,7 @@ public class TypeMemPtr extends TypeNil { // A partial declaration promises no initialized slots. Actual callers may // supply a sharper shape; the declaration must not manufacture those facts. - public TypeMemPtr partialBound() { return _partial ? makeFrom(_obj.makeInit()) : this; } + public TypeMemPtr partialBound() { return _partial ? makeFrom(_obj.makeInit(false)) : this; } // Project field initialization onto declared field types, not stored // constants. A pointer field being set does not complete its referent. diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java index d1586547..2a6bb203 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java @@ -149,11 +149,10 @@ public class TypeStruct extends Type { Field.make("[]" ,con ,bodyAlias,true)); } - public TypeStruct makeInit() { + public TypeStruct makeInit(boolean opto) { Field[] fs = new Field[_fields.length]; for( int i=0; i<_fields.length; i++ ) { - if( _fields[i]._extern ) { fs[i] = _fields[i]; continue; } - fs[i] = _fields[i].makeFrom(TypeScalar.BOT); + fs[i] = _fields[i]._extern ? _fields[i] : _fields[i].makeFrom(opto ? TypeScalar.TOP : TypeScalar.BOT); } return make(_name,_open,_fref,fs); } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/util/WorkList.java b/chapter33/src/main/java/com/seaofnodes/simple/util/WorkList.java new file mode 100644 index 00000000..a4330df7 --- /dev/null +++ b/chapter33/src/main/java/com/seaofnodes/simple/util/WorkList.java @@ -0,0 +1,78 @@ +package com.seaofnodes.simple.util; + +import com.seaofnodes.simple.node.Node; +import java.util.Arrays; +import java.util.BitSet; +import java.util.Random; + +/** Deduplicated node worklist with seeded random removal. Membership uses + * Node IDs, never Node.hashCode (which participates in GVN). + * Use pop() for iterative solvers and popOnce() for graph traversals. */ +public class WorkList<E extends Node> { + private Node[] _es; + private int _len; + private final BitSet _on; // Queued nodes, plus visited nodes with popOnce(). + private final Random _R; + private final long _seed; + private long _totalWork = 0; + + public WorkList() { this(123); } + public WorkList(long seed) { + _es = new Node[1]; + _on = new BitSet(); + _seed = seed; + _R = new Random(seed); + } + + /** Add a node unless already marked. Null is ignored. */ + 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(Ary<E> ary) { + for( E n : ary ) push(n); + } + public void addAll(E[] es) { + for( E n : es ) push(n); + } + + /** Queued membership; popOnce() also retains already-visited membership. */ + public boolean on(E x) { return _on.get(x._nid); } + + /** Remove a random node and allow it to be queued again. Null when empty. */ + public E pop() { + E x = popOnce(); + if( x!=null ) _on.clear(x._nid); + return x; + } + + /** Remove a random node, retaining its mark to prevent revisits in cyclic + * graph walks. clear() starts a fresh traversal. Null when empty. */ + @SuppressWarnings("unchecked") + public E popOnce() { + if( _len==0 ) return null; + int idx = _R.nextInt(_len); + E x = (E)_es[idx]; + _es[idx] = _es[--_len]; + _es[_len] = null; + return x; + } + + public boolean isEmpty() { return _len==0; } + public void clear() { + Arrays.fill(_es,0,_len,null); + _len = 0; + _on.clear(); + _R.setSeed(_seed); + _totalWork = 0; + } +} diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java index 9cb5dacc..b86d83c0 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java @@ -21,15 +21,17 @@ public class Chapter18Test { "int x=0; while(arg) { if(arg==2) while(1) { x++; } x++; arg--; } return x;" }; for( String src : sources ) { - CodeGen code = new CodeGen(src).driver(CodeGen.Phase.TypeCheck); + CodeGen code = new CodeGen(src).driver(CodeGen.Phase.Allocation2); + int[] earlyNevers = {0}; code._stop.walk(n -> { - assertFalse("Analysis must not insert synthetic exits",n instanceof NeverNode); + if( n instanceof NeverNode ) earlyNevers[0]++; if( n instanceof LoopNode loop && !(loop instanceof StartNode) ) { assertSame(loop,loop._ltree._head); assertNotNull(loop._ltree._par); } return null; }); + assertTrue("Normalize exits before allocation analysis",earlyNevers[0]>0); code.driver(CodeGen.Phase.Unlink); int[] nevers = {0}; code._stop.walk(n -> { @@ -54,6 +56,7 @@ public class Chapter18Test { return null; }); assertTrue("Exercise a synthetic exit",nevers[0]>0); + assertEquals("Rebuilding must not duplicate synthetic exits",earlyNevers[0],nevers[0]); } } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java index 226425ca..664d5a77 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java @@ -31,13 +31,15 @@ public class Chapter20Test { for( String src : sources ) { CodeGen code = new CodeGen(src).driver(CodeGen.Phase.RegAlloc,target,"SystemV"); com.seaofnodes.simple.codegen.RegAllocTestSupport.checkRegisters(code); - assertNotNull(code._stop.walk(n -> { + // Early normalization lets peepholes erase redundant TOP inputs. + // Any which survive must still require no register or split. + code._stop.walk(n -> { if( n._type!=com.seaofnodes.simple.type.Type.TOP ) return null; assertEquals(-1,code._regAlloc.regnum(n)); for( var use : n.outs() ) assertFalse(use instanceof com.seaofnodes.simple.node.SplitNode); - return n; - })); + return null; + }); code.encode(); } } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java index fa52d09f..f28eed00 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java @@ -2,25 +2,56 @@ package com.seaofnodes.simple; import com.seaofnodes.simple.codegen.*; import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.TypeInteger; -import com.seaofnodes.simple.type.TypeFunPtr; -import com.seaofnodes.simple.type.TypeMemPtr; -import com.seaofnodes.simple.type.Type; -import com.seaofnodes.simple.type.TypeMem; -import com.seaofnodes.simple.type.TypeScalar; -import com.seaofnodes.simple.type.TypeTuple; +import com.seaofnodes.simple.type.*; import com.seaofnodes.simple.util.Ary; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import org.junit.Test; import static org.junit.Assert.*; -/** Small allocation poster children. Keep calls visible: this tests summaries, - * not whether an inliner happens to put the allocations in the right function. */ +/** Points-to and conservative separate-compilation boundaries. */ public class Chapter33Test { + @Test public void testSummaryCallDependencyDoesNotEscape() { + CodeGen code = new CodeGen("return 0;").parse(); + code._phase = CodeGen.Phase.Opto; + TypeFunPtr sig = TypeFunPtr.make1((byte)2,true,TypeFunPtr.TEMPTY,TypeInteger.BOT,100); + FunNode fun = new FunNode(null,sig,"summaryOwner",code.compunit(),code._start); + fun._type = Type.CONTROL; + TypeTuple state = TypeTuple.make(Type.CONTROL, + TypeMem.START.makeFrom(XInt.make(9),XInt.EMPTY),TypeInteger.BOT); + SummaryNode summary = new SummaryNode(state,new int[]{7},fun,code.con(TypeMem.START)).init(); + code.link(fun); + assertSame(summary,fun.summary()); + TypeMem exposed = new GlobalEscapeNode().compute(); + assertTrue("Published function pointers escape",XInt.bit(exposed._escFs,9)); + assertFalse("Internal call dependencies do not escape",XInt.bit(exposed._escFs,7)); + } + + @Test public void testPrivateMemoryDefaultDoesNotEscape() { + CodeGen code = new CodeGen(""" + struct Box { int n; new Box = { int x -> n=x; }; }; + return new Box(((arg<<32)>>32)).n; + """).parse(); + int helpers = 0; + for( FunNode fun : code._linker ) + if( fun!=null && fun.sig().nargs()>1 && fun.sig().arg(1) instanceof TypeMem bound ) { + helpers++; + TypeMem def = (TypeMem)fun.defaultArg(1); + assertTrue(def._one); + assertSame(Type.BOTTOM,def._t); + assertSame(XInt.EMPTY,def._escFs); + assertSame(XInt.EMPTY,def._escAs); + assertTrue("Actual initialized memory must still fit the signature",bound._one); + assertSame(XInt.FULL,bound._escFs); + assertSame(XInt.FULL,bound._escAs); + } + assertTrue(helpers>0); + code.driver(CodeGen.Phase.TypeCheck); + assertEquals("42",Eval2.eval(code,42)); + } + private static final String THING = """ struct Thing { i64 x; @@ -33,915 +64,12 @@ public class Chapter33Test { return new CodeGen(source).driver(CodeGen.Phase.TypeCheck); } - private static List<Allocation.Site> allocations(Allocation.Summary sum, String type) { - sum.requireSupported(); - var sites = new ArrayList<Allocation.Site>(); - for( var site : sum._sites ) - if( site._allocation!=null && site._allocation._ts._name.endsWith("."+type) ) - sites.add(site); - return sites; - } - - // 1. A call borrows a temporary. The caller can reclaim it on return. - @Test public void testAllocationLocalFrame() { - CodeGen code = compile(THING+""" - val work_noInline = { i64 n -> - val t=new Thing(n); - return read_noInline(t); - }; - return work_noInline(arg); - """); - var sites = allocations(code._allocation.summary("work_noInline"),"Thing"); - assertEquals(1,sites.size()); - assertEquals("frame",sites.get(0).destination()); - assertEquals("17",Eval2.eval(code,17)); - } - - // 2. A factory returns a graph through another factory. Both objects need - // result destinations, but the final consuming caller owns them locally. - @Test public void testAllocationFactoryGraph() { - CodeGen code=compile(THING+""" - struct Box { - Thing child; - new Box = { Thing child -> self.child=child; }; - }; - val make_noInline = { i64 n -> new Box(new Thing(n)); }; - val forward_noInline = { i64 n -> make_noInline(n); }; - val use_noInline = { Box b -> b.child.x; }; - val work_noInline = { i64 n -> use_noInline(forward_noInline(n)); }; - return work_noInline(arg); - """); - for( String name : new String[]{"make_noInline","forward_noInline"} ) { - var sum = code._allocation.summary(name); - assertEquals("result",allocations(sum,"Box" ).get(0).destination()); - assertEquals("result",allocations(sum,"Thing").get(0).destination()); - } - var work = code._allocation.summary("work_noInline"); - assertEquals("frame",allocations(work,"Box" ).get(0).destination()); - assertEquals("frame",allocations(work,"Thing").get(0).destination()); - assertEquals("23",Eval2.eval(code,23)); - } - - private static final String HOLDER = """ - struct Holder { Thing !c = new Thing(0); }; - """; - - // 3. A fresh reference escapes through a parameter, not the return value. - @Test public void testAllocationStoreThroughArgument() { - CodeGen code=compile(THING+HOLDER+""" - val fill_noInline = { !Holder h, i64 n -> h.c = new Thing(n); return n; }; - val work_noInline = { i64 n -> - val h = new Holder; - fill_noInline(h,n); - return h.c.x; - }; - return work_noInline(arg); - """); - var fill = allocations(code._allocation.summary("fill_noInline"),"Thing"); - assertEquals(1,fill.size()); - assertEquals("arg3",fill.get(0).destination()); // arg2 is the class receiver - for( var site : allocations(code._allocation.summary("work_noInline"),"Thing") ) - assertEquals("frame",site.destination()); - assertEquals("31",Eval2.eval(code,31)); - } - - // 4. One shared factory, two call sites, two unrelated destinations. - @Test public void testAllocationSeparateDestinations() { - CodeGen code=compile(THING+HOLDER+""" - val make_noInline = { i64 n -> new Thing(n); }; - val fill_noInline = { !Holder a, !Holder b, i64 n -> - a.c = make_noInline(n); - b.c = make_noInline(n+1); - return n; - }; - val a = new Holder, b = new Holder; - fill_noInline(a,b,arg); - return a.c.x*10+b.c.x; - """); - var sites=allocations(code._allocation.summary("fill_noInline"),"Thing"); - assertEquals(2,sites.size()); - assertNotEquals(sites.get(0)._name,sites.get(1)._name); - var destinations=new ArrayList<String>(); - for( var site : sites ) destinations.add(site.destination()); - Collections.sort(destinations); - assertEquals(List.of("arg3","arg4"),destinations); - assertEquals("45",Eval2.eval(code,4)); - String dump=code._allocation.toString(); - assertTrue(dump.contains("[arg3]")); - assertTrue(dump.contains(".c -->")); - assertTrue(dump.indexOf("+-- fill_noInline\n") < dump.indexOf("+-- make_noInline\n")); - } - - // A join requires BOTH possible owners; it must not pick whichever input - // happens to be visited first. Alias actual arguments at a call as well. - @Test public void testAllocationConditionalAndAliasedOwners() { - CodeGen code=compile(THING+HOLDER+""" - val fill_noInline = { !Holder a, !Holder b, i64 n -> - val h=n ? a : b; - h.c=new Thing(n); - return n; - }; - val a=new Holder, b=new Holder; - fill_noInline(a,b,arg); - fill_noInline(a,a,arg+1); - return a.c.x; - """); - var sites=allocations(code._allocation.summary("fill_noInline"),"Thing"); - assertEquals(1,sites.size()); - assertEquals("arg3 & arg4",sites.get(0).destination()); - assertEquals("8",Eval2.eval(code,7)); - } - - @Test public void testAllocationBorrowAndObjectCycle() { - CodeGen borrow=compile(THING+""" - val choose_noInline={ Thing a, Thing b, i64 n -> n ? a : b; }; - return read_noInline(choose_noInline(new Thing(arg),new Thing(arg+1),arg)); - """); - var choose=borrow._allocation.summary("choose_noInline").requireSupported(); - assertEquals(2,choose._returns.size()); - var destinations=new ArrayList<String>(); - for( var site : choose._returns ) { - assertNull(site._allocation); - destinations.add(site.destination()); - } - Collections.sort(destinations); - assertEquals(List.of("result & arg3","result & arg4"),destinations); - assertEquals("1",Eval2.eval(borrow,0)); - assertTrue(borrow.toString().contains("choose_noInline")); - - CodeGen cycle=compile(""" - struct Link { Link? !next; i64 x; new Link={ i64 n -> x=n; }; }; - val cycle_noInline={ i64 n -> - val a=new Link(n), b=new Link(n+1); - a.next=b; - b.next=a; - return a; - }; - return cycle_noInline(arg).x; - """); - var sites=allocations(cycle._allocation.summary("cycle_noInline"),"Link"); - assertEquals(2,sites.size()); - for( var site : sites ) assertEquals("result",site.destination()); - assertEquals("9",Eval2.eval(cycle,9)); - assertTrue(cycle.toString().contains("cycle_noInline")); - // Compiling cycle reset and recycled borrow's types. Its debugger string - // must neither crash on cleared types nor print their reused contents. - assertEquals("IR unavailable: shared types were reset after this compilation.",borrow.toString()); - } - - // Scalar results must not hide allocations when arithmetic is skipped. - @Test public void testAllocationScalarArrayUse() { - CodeGen code=compile(""" - val work_noInline={ i64 n -> - val a=new i64[2]; - a[0]=n; - return a[n&1]+n*n; - }; - return work_noInline(arg); - """); - var sum=code._allocation.summary("work_noInline").requireSupported(); - int arrays=0; - for( var site : sum._sites ) - if( site._allocation!=null && site._allocation._ts.isAry() ) { - arrays++; - assertEquals("frame",site.destination()); - } - assertEquals(1,arrays); - assertEquals("25",Eval2.eval(code,5)); - assertEquals("20",Eval2.eval(code,4)); - } - - // Make unsupported plans explicit, without replacing existing TypeCheck - // diagnostics or changing the allocator used by older chapter tests. - @Test public void testAllocationRejectedPlans() { - String[] sources={ - "val bad_noInline={ i64 n -> n ? bad_noInline(n-1) : 0; }; return bad_noInline(arg);", - "val bad_noInline={ i64 n -> new int[n]; }; return bad_noInline(arg);", - "{ i64 -> int[] } native=\"C\"; val bad_noInline={ i64 n -> native(n); }; return bad_noInline(arg);" - }; - String[] reasons={"recursive", "variable-size", "native result"}; - for( int i=0; i<sources.length; i++ ) { - CodeGen code=compile(sources[i]); - var sum=code._allocation.summary("bad_noInline"); - assertFalse(sum.supported()); - assertTrue(sum._reject,sum._reject.contains(reasons[i])); - try { sum.requireSupported(); fail("Rejected plan was usable"); } - catch( IllegalStateException expected ) { - assertTrue(expected.getMessage().contains(reasons[i])); - } - assertTrue(code._allocation.toString().contains("REJECT:")); - } - } - - // A borrowed child is a separate origin. Returning it through helpers must - // retain the Thing, not the temporary Holder used to reach it. - @Test public void testAllocationReturnField() { - CodeGen code=compile(THING+HOLDER+""" - val get_noInline = { Holder h -> h.c; }; - val forward_noInline = { Holder h -> get_noInline(h); }; - val work_noInline={ i64 n -> - val h = new Holder; - h.c = new Thing(n); - return forward_noInline(h); - }; - return read_noInline(work_noInline(arg)); - """); - for( String name : new String[]{"get_noInline","forward_noInline"} ) { - var sum=code._allocation.summary(name).requireSupported(); - assertEquals(1,sum._returns.size()); - var child=sum._returns.iterator().next(); - assertEquals("arg3.c",child._name); - assertEquals("result & arg3.c",child.destination()); - for( var site : sum._sites ) - if( site._arg==3 ) assertEquals("arg3",site.destination()); - } - var work=code._allocation.summary("work_noInline"); - assertEquals("frame",allocations(work,"Holder").get(0).destination()); - assertEquals(2,allocations(work,"Thing").size()); // weak update retains the default too - for( var site : allocations(work,"Thing") ) assertEquals("result",site.destination()); - assertEquals("17",Eval2.eval(code,17)); - } - - // Retention through a loaded reference composes across a wrapper. The - // source holder stays local even though its child escapes to the argument. - @Test public void testAllocationCopyField() { - CodeGen code=compile(THING+HOLDER+""" - val copy_noInline={ !Holder dst, Holder src -> dst.c=src.c; return 0; }; - val forward_noInline={ !Holder dst, Holder src -> copy_noInline(dst,src); }; - val work_noInline={ !Holder dst, i64 n -> - val src=new Holder; - src.c=new Thing(n); - return forward_noInline(dst,src); - }; - val dst=new Holder; - work_noInline(dst,arg); - return dst.c.x; - """); - for( String name : new String[]{"copy_noInline","forward_noInline"} ) { - var sum=code._allocation.summary(name).requireSupported(); - boolean found=false; - for( var site : sum._sites ) { - if( site._name.equals("arg4.c") ) { - found=true; - assertEquals("arg3 & arg4.c",site.destination()); - } - if( site._arg==4 ) assertEquals("arg4",site.destination()); - } - assertTrue(found); - } - var work=code._allocation.summary("work_noInline"); - assertEquals("frame",allocations(work,"Holder").get(0).destination()); - assertEquals(2,allocations(work,"Thing").size()); - for( var site : allocations(work,"Thing") ) assertEquals("arg3",site.destination()); - assertEquals("23",Eval2.eval(code,23)); - } - - // An argument's child can itself receive allocations. Its lifetime is a - // distinct destination, resolved to the actual Holder at the next call. - @Test public void testAllocationStoreThroughField() { - CodeGen code=compile(THING+HOLDER+""" - struct Outer { !Holder h=new Holder; }; - val fill_noInline={ !Outer o, i64 n -> o.h.c=new Thing(n); return n; }; - val get_noInline={ Outer o -> o.h.c; }; - val work_noInline={ i64 n -> - val o=new Outer; - fill_noInline(o,n); - return get_noInline(o); - }; - return read_noInline(work_noInline(arg)); - """); - var fill=allocations(code._allocation.summary("fill_noInline"),"Thing"); - assertEquals(1,fill.size()); - assertEquals("arg3.h",fill.get(0).destination()); - var get=code._allocation.summary("get_noInline").requireSupported(); - assertEquals("arg3.h.c",get._returns.iterator().next()._name); - var work=code._allocation.summary("work_noInline"); - assertEquals("frame",allocations(work,"Outer").get(0).destination()); - assertEquals("frame",allocations(work,"Holder").get(0).destination()); - assertEquals(2,allocations(work,"Thing").size()); - for( var site : allocations(work,"Thing") ) assertEquals("result",site.destination()); - assertEquals("31",Eval2.eval(code,31)); - } - - // A store through one formal must reach a load through another when actuals - // alias. Keeping all fields as weak unions also covers a load before a store. - @Test public void testAllocationAliasedFieldLoad() { - CodeGen code=compile(THING+HOLDER+""" - val fill_noInline={ !Holder a, Holder b, i64 n -> a.c=new Thing(n); return b.c; }; - val same_noInline={ i64 n -> - val h=new Holder; - return fill_noInline(h,h,n); - }; - val different_noInline={ i64 n -> - val a=new Holder, b=new Holder; - return fill_noInline(a,b,n); - }; - return read_noInline(same_noInline(arg))+read_noInline(different_noInline(arg)); - """); - for( String name : new String[]{"same_noInline","different_noInline"} ) { - var sum=code._allocation.summary(name); - for( var site : allocations(sum,"Holder") ) assertEquals("frame",site.destination()); - int returned=0; - for( var site : allocations(sum,"Thing") ) - if( site.destination().equals("result") ) returned++; - assertEquals(name.equals("same_noInline") ? 2 : 1,returned); - } - assertEquals("41",Eval2.eval(code,41)); - } - - // Weak updates can create fictitious repeated reads. Reject this case - // instead of building infinite p.next.next... paths or silently dropping one. - @Test public void testAllocationCyclicFieldPaths() { - CodeGen code=compile(""" - struct Link { Link? !next; i64 x; new Link={ i64 n -> x=n; }; }; - val skip_noInline={ !Link p -> - val a=p.next; - if( a ) p.next=a.next; - return p; - }; - val a=new Link(arg), b=new Link(arg+1); - a.next=b; - return skip_noInline(a).x; - """); - var sum=code._allocation.summary("skip_noInline"); - assertFalse(sum.supported()); - assertTrue(sum._reject,sum._reject.contains("cyclic field-path expansion")); - assertEquals("5",Eval2.eval(code,5)); - } - - // Array indices share one conservative field. Both possible children need - // result storage; the fixed-size backing array itself remains temporary. - @Test public void testAllocationArrayElementOrigins() { - CodeGen code=compile(THING+""" - val get_noInline={ Thing?[] ts, i64 n -> ts[n&1]; }; - val work_noInline={ i64 n -> - val ts=new Thing?[2]; - ts[0]=new Thing(n); - ts[1]=new Thing(n+1); - return get_noInline(ts,n); - }; - val t=work_noInline(arg); - return t ? t.x : -1; - """); - var work=code._allocation.summary("work_noInline").requireSupported(); - assertEquals(2,allocations(work,"Thing").size()); - for( var site : allocations(work,"Thing") ) assertEquals("result",site.destination()); - int arrays=0; - for( var site : work._sites ) - if( site._allocation!=null && site._allocation._ts.isAry() ) { - arrays++; - assertEquals("frame",site.destination()); - } - assertEquals(1,arrays); - assertEquals("8",Eval2.eval(code,7)); - assertEquals("6",Eval2.eval(code,6)); - } - - // One temporary per iteration, including allocations imported from a helper. - @Test public void testAllocationLoopTemporary() { - CodeGen code=compile(THING+""" - val make_noInline={ i64 n -> new Thing(n); }; - val work_noInline={ i64 n -> - i64 s=0; - while( n>0 ) { - val t=make_noInline(n); - s+=read_noInline(t); - n--; - } - return s; - }; - return work_noInline(arg); - """); - var sites=allocations(code._allocation.summary("work_noInline"),"Thing"); - assertEquals(1,sites.size()); - var temp=sites.get(0); - assertNotNull(temp._frame._loop); - assertSame(temp._frame,temp._scope); - assertEquals(temp._frame.name()+" iteration",temp.destination()); - assertTrue(temp._frame._scratch.contains(temp)); - assertFalse(temp._frame._continues.contains(temp)); - assertFalse(temp._frame._returns.contains(temp)); - assertEquals("15",Eval2.eval(code,5)); - assertEquals("0",Eval2.eval(code,0)); - } - - // A loop can retain a winner while reclaiming unrelated scratch every turn. - // The winner is built by a factory, so its destination crosses a call too. - @Test public void testAllocationLoopWinnerAndScratch() { - CodeGen code=compile(THING+""" - struct Scratch { i64 x; new Scratch={ i64 n -> x=n; }; }; - val readScratch_noInline={ Scratch s -> s.x; }; - val make_noInline={ i64 n -> new Thing(n); }; - val find_noInline={ i64 n -> - Thing? !winner=null; - while( n>0 ) { - val scratch=new Scratch(n); - val candidate=make_noInline(readScratch_noInline(scratch)); - if( read_noInline(candidate)==3 ) { winner=candidate; break; } - n--; - } - return winner; - }; - Thing? t=find_noInline(arg); - return t ? t.x : -1; - """); - var sum=code._allocation.summary("find_noInline").requireSupported(); - var winner=allocations(sum,"Thing").get(0); - var scratch=allocations(sum,"Scratch").get(0); - assertNotNull(winner._frame._loop); - assertSame(winner._frame,scratch._frame); - assertEquals("result",winner.destination()); - assertNull(winner._scope); - assertSame(scratch._frame,scratch._scope); - assertEquals(scratch._frame.name()+" iteration",scratch.destination()); - var frame=winner._frame.requireSupported(); - assertSame(sum,frame._parent); - assertTrue(sum._frames.contains(frame)); - assertTrue(frame._returns.contains(winner)); - assertFalse(frame._continues.contains(winner)); - assertFalse(frame._scratch.contains(winner)); - assertTrue(frame._scratch.contains(scratch)); - assertFalse(frame._entry.isEmpty()); - assertFalse(frame._next.isEmpty()); - assertFalse(frame._exit.isEmpty()); - String dump=code._allocation.toString(); - assertTrue(dump.contains(frame.name()+" winner")); - assertEquals(dump.indexOf("\n+-- "),dump.indexOf("\n+-- class:Test.<clinit>\n")); - int others=dump.indexOf("Other retained functions"); - assertTrue(dump.indexOf("\n+-- find_noInline\n") < others); - assertTrue(dump.indexOf("\n+-- make_noInline\n") < others); - assertTrue(dump.indexOf("\n+-- Test.Scratch.<new>\n") > others); - assertEquals("3",Eval2.eval(code,5)); - assertEquals("-1",Eval2.eval(code,2)); - assertEquals("-1",Eval2.eval(code,0)); - } - - // A collection needs multiple generations of an allocation site. Neither a - // loop-carried pointer nor a pointer hidden in pre-existing memory is a winner. - @Test public void testAllocationLoopRetainedCandidates() { - String[] sources={ - """ - struct Link { Link? next; i64 x; new Link={ Link? p, i64 n -> next=p; x=n; }; }; - val work_noInline={ i64 n -> - Link? !head=null; - while( n>0 ) { head=new Link(head,n); n--; } - return head; - }; - val t=work_noInline(arg); - return t ? t.x : -1; - """, - THING+""" - val work_noInline={ i64 n -> - val ts=new Thing?[2]; - while( n>0 ) { ts[n&1]=new Thing(n); n--; } - return ts; - }; - val ts=work_noInline(arg); - val t=ts[1]; - return t ? t.x : -1; - """, - THING+HOLDER+""" - val fill_noInline={ !Holder h, i64 n -> h.c=new Thing(n); return n; }; - val work_noInline={ i64 n -> - val h=new Holder; - while( n>0 ) { fill_noInline(h,n); n--; } - return h; - }; - return work_noInline(arg).c.x; - """ - }; - for( String source : sources ) { - CodeGen code=compile(source); - var sum=code._allocation.summary("work_noInline"); - assertFalse(sum.supported()); - assertTrue(sum._reject,sum._reject.contains("across its backedge")); - assertEquals("1",Eval2.eval(code,3)); - } - } - - // Publishing on the exit arm is allowed. Publishing on the backedge was - // rejected above; both cases write through a pre-existing holder. - @Test public void testAllocationLoopWinnerStore() { - CodeGen code=compile(THING+HOLDER+""" - val fill_noInline={ !Holder h, i64 n -> - while( n>0 ) { - val t=new Thing(n); - if( read_noInline(t)==3 ) { h.c=t; break; } - n--; - } - return n; - }; - val h=new Holder; - fill_noInline(h,arg); - return h.c.x; - """); - var sites=allocations(code._allocation.summary("fill_noInline"),"Thing"); - assertEquals(1,sites.size()); - assertEquals("arg3",sites.get(0).destination()); - assertNotNull(sites.get(0)._frame._loop); - assertNull(sites.get(0)._scope); - assertTrue(sites.get(0)._frame._retained.contains(sites.get(0))); - assertEquals("3",Eval2.eval(code,5)); - assertEquals("0",Eval2.eval(code,2)); - } - - // An inner winner can still be temporary in the enclosing iteration. - @Test public void testAllocationNestedLoopWinner() { - CodeGen code=compile(THING+""" - val work_noInline={ i64 n -> - i64 s=0; - while( n>0 ) { - Thing? !winner=null; - i64 i=3; - while( i>0 ) { - val t=new Thing(n+i); - if( read_noInline(t)==n+2 ) { winner=t; break; } - i--; - } - if( winner ) s+=read_noInline(winner); - n--; - } - return s; - }; - return work_noInline(arg); - """); - var sites=allocations(code._allocation.summary("work_noInline"),"Thing"); - assertEquals(1,sites.size()); - var site=sites.get(0); - assertNotNull(site._frame._loop); - assertNotNull(site._scope); - assertSame(site._frame._parent,site._scope); - assertEquals(site._scope.name()+" iteration",site.destination()); - assertTrue(site._frame._returns.contains(site)); - assertFalse(site._frame._scratch.contains(site)); - assertTrue(site._scope._scratch.contains(site)); - assertEquals("12",Eval2.eval(code,3)); - } - - // The candidate's graph survives together, but the caller can consume that - // result locally. The helper's winner layout must not leak into its caller. - @Test public void testAllocationLoopWinnerGraph() { - CodeGen code=compile(THING+""" - struct Box { Thing child; new Box={ Thing t -> child=t; }; }; - val use_noInline={ Box b -> b.child.x; }; - val find_noInline={ i64 n -> - while( true ) { - val b=new Box(new Thing(n)); - if( use_noInline(b)==3 ) return b; - n--; - } - }; - val work_noInline={ i64 n -> use_noInline(find_noInline(n)); }; - return work_noInline(arg); - """); - var find=code._allocation.summary("find_noInline").requireSupported(); - for( String type : new String[]{"Thing","Box"} ) { - var winner=allocations(find,type).get(0); - assertEquals("result",winner.destination()); - assertNotNull(winner._frame._loop); - assertNull(winner._scope); - var caller=allocations(code._allocation.summary("work_noInline"),type).get(0); - assertEquals("frame",caller.destination()); - assertSame(code._allocation.summary("work_noInline"),caller._frame); - assertSame(caller._frame,caller._scope); - assertTrue(caller._frame._scratch.contains(caller)); - } - assertEquals("3",Eval2.eval(code,5)); - } - - // Continuation ports can return borrowed references into the next activation. - // They do not require retaining any storage created by the iteration. - @Test public void testAllocationBorrowedContinuation() { - CodeGen code=compile(THING+""" - val work_noInline={ Thing a, Thing b, i64 n -> - Thing !p=a; - i64 s=0; - while( n>0 ) { - s+=read_noInline(p); - p=(n&1) ? a : b; - n--; - } - return s+read_noInline(p); - }; - return work_noInline(new Thing(10),new Thing(20),arg); - """); - var fun=code._allocation.summary("work_noInline").requireSupported(); - assertEquals(1,fun._frames.size()); - var loop=fun._frames.get(0).requireSupported(); - assertEquals(2,loop._continues.size()); - for( var site : loop._continues ) { - assertNull(site._allocation); - assertTrue(site._arg==3 || site._arg==4); - assertTrue(loop._returns.contains(site)); - } - assertTrue(loop._scratch.isEmpty()); - assertEquals("50",Eval2.eval(code,3)); - assertEquals("10",Eval2.eval(code,0)); - } - - // Both exits clean the same scratch. The normal result here is a scalar, - // loaded before cleanup; returning it does not retain the temporary object. - @Test public void testAllocationScalarLoopExit() { - CodeGen code=compile(THING+""" - val work_noInline={ i64 n -> - i64 result=-1; - while( n>0 ) { - val t=new Thing(n); - val x=read_noInline(t); - if( n==3 ) { result=x; break; } - n--; - } - return result; - }; - return work_noInline(arg); - """); - var fun=code._allocation.summary("work_noInline").requireSupported(); - var temp=allocations(fun,"Thing").get(0); - var loop=temp._frame.requireSupported(); - assertSame(loop,temp._scope); - assertTrue(loop._scratch.contains(temp)); - assertTrue(loop._returns.isEmpty()); - assertTrue(loop._continues.isEmpty()); - boolean scalar=false; - for( var value : loop._exit.values() ) - if( value._type instanceof com.seaofnodes.simple.type.TypeInteger ) scalar=true; - assertTrue(scalar); - assertEquals("3",Eval2.eval(code,5)); - assertEquals("-1",Eval2.eval(code,2)); - } - - // Returning from an inner loop exports through both enclosing interfaces; - // each exited frame has its own cleanup obligations. - @Test public void testAllocationNestedFrameReturn() { - CodeGen code=compile(THING+""" - struct Scratch { i64 x; new Scratch={ i64 n -> x=n; }; }; - val readScratch_noInline={ Scratch s -> s.x; }; - val find_noInline={ i64 n -> - while( n>0 ) { - val scratch=new Scratch(n); - i64 i=readScratch_noInline(scratch); - while( i>0 ) { - val candidate=new Thing(i); - if( read_noInline(candidate)==3 ) return candidate; - i--; - } - n--; - } - return null; - }; - Thing? t=find_noInline(arg); - return t ? t.x : -1; - """); - var fun=code._allocation.summary("find_noInline").requireSupported(); - var winner=allocations(fun,"Thing").get(0); - var scratch=allocations(fun,"Scratch").get(0); - var inner=winner._frame; - var outer=scratch._frame; - assertSame(outer,inner._parent); - assertSame(fun,outer._parent); - assertTrue(inner._returns.contains(winner)); - assertTrue(outer._returns.contains(winner)); - assertTrue(fun._returns.contains(winner)); - assertNull(winner._scope); - assertSame(outer,scratch._scope); - assertTrue(outer._scratch.contains(scratch)); - assertFalse(inner._scratch.contains(scratch)); - assertEquals("3",Eval2.eval(code,5)); - assertEquals("-1",Eval2.eval(code,2)); - } - - @Test public void testAllocationExitlessLoop() { - CodeGen code=compile(THING+""" - val spin_noInline={ i64 n -> - while( true ) { - val t=new Thing(n); - n=read_noInline(t)+1; - } - return 7; - }; - spin_noInline(arg); - return 7; - """); - var fun=code._allocation.summary("spin_noInline").requireSupported(); - assertEquals(1,fun._frames.size()); - var loop=fun._frames.get(0).requireSupported(); - assertNotNull(loop._loop); - assertSame(loop._loop,loop._loop._ltree._head); - assertSame(fun,loop._parent); - var temp=allocations(fun,"Thing").get(0); - assertSame(loop,temp._scope); - assertTrue(loop._scratch.contains(temp)); - assertTrue(loop._returns.isEmpty()); - assertTrue(loop._continues.isEmpty()); - // No synthetic return before TypeCheck or serialization; scheduling - // supplies the exit later. The evaluator still cannot return. - assertSame(com.seaofnodes.simple.type.Type.XCONTROL,fun._fun.ret().ctrl()._type); - assertNull(Eval2.eval(code,0,10)); - } - - @Test public void testAllocationNativeBorrow() { - CodeGen code=compile(""" - { i64 i64 -> i64 } native="C"; - val work_noInline={i64 n -> - val a=new u8[16], b=new u8[16]; - i64 pa=a, pb=b; - i64 p=n ? pa : pb; - return native(p+2,8); - }; - return work_noInline(arg); - """); - var fun=code._allocation.summary("work_noInline").requireSupported(); - int count=0; - for( var site : fun._sites ) if( site._allocation!=null ) { - count++; - assertSame(fun,site._scope); - assertTrue(fun._scratch.contains(site)); - assertFalse(fun._returns.contains(site)); - } - assertEquals(2,count); - assertTrue(code._allocation.toString().contains("native (borrow; no retain)")); - } - - @Test public void testAllocationNativeLoopBorrow() { - CodeGen code=compile(""" - { i64 i64 -> i64 } native="C"; - val borrow_noInline={u8[] bytes -> - i64 p=bytes; - return native(p,bytes#); - }; - val work_noInline={i64 n -> - i64 total=0; - while(n>0) { - val bytes=new u8[16]; - total+=borrow_noInline(bytes); - i64 p=bytes; - total+=native(p+1,8); - n--; - } - return total; - }; - return work_noInline(arg); - """); - code._allocation.summary("borrow_noInline").requireSupported(); - var fun=code._allocation.summary("work_noInline").requireSupported(); - int count=0; - for( var site : fun._sites ) if( site._allocation!=null ) { - count++; - assertNotNull(site._frame._loop); - assertSame(site._frame,site._scope); - assertTrue(site._scope._scratch.contains(site)); - assertFalse(site._scope._continues.contains(site)); - } - assertEquals(1,count); - } - - @Test public void testAllocationRawAddressBoundaries() { - String[] bodies={ - """ - i64 p=0; - while(n>0) { - if(p) native(p); - val bytes=new u8[16]; - p=bytes; - n--; - } - return 0; - """, - "val bytes=new u8[16]; i64 p=bytes; addresses[0]=p; return native(addresses[0]);" - }; - for( int i=0; i<bodies.length; i++ ) { - CodeGen code=compile("{ i64 -> i64 } native=\"C\"; val addresses=new i64[1]; "+ - "val work_noInline={i64 n -> "+bodies[i]+"}; return work_noInline(arg);"); - var fun=code._allocation.summary("work_noInline").requireSupported(); - for( var site : fun._sites ) if( site._allocation!=null ) { - // Carrying the integer across iterations does not carry its - // backing storage. The first program uses a stale raw address. - assertSame(site._frame,site._scope); - assertTrue(site._scope._scratch.contains(site)); - } - } - } - private static List<KeepAliveNode> keeps(CodeGen code) { var keeps=new ArrayList<KeepAliveNode>(); code._start.walk(n -> { if( n instanceof KeepAliveNode k ) keeps.add(k); return null; }); return keeps; } - @Test public void testKeepAliveWrappersAndReplacement() { - CodeGen code=compile(""" - { i64 -> i64 } native="C"; - val forward_noInline={ i64 p -> native(p); }; - val wrapper_noInline={ i64 p -> forward_noInline(p); }; - val addresses=new i64[2]; - val work_noInline={ i64 n -> - i64 raw=new u8[16]; - addresses[0]=raw; - raw=new u8[32]; - addresses[1]=raw; - return wrapper_noInline(addresses[n&1]); - }; - return work_noInline(arg); - """); - var fun=code._allocation.summary("work_noInline").requireSupported(); - int count=0; - for( var site : fun._sites ) if( site._allocation!=null ) { - count++; - assertSame(fun,site._scope); - assertTrue(fun._scratch.contains(site)); - } - assertEquals(2,count); - assertEquals(1,keeps(code).size()); - KeepAliveNode keep=keeps(code).get(0); - assertTrue(keep.in(1) instanceof KeepAliveNode.Values); - assertSame(keep,fun._fun.ret().ctrl()); - assertTrue(keep.in(0) instanceof CProjNode); - } - - @Test public void testKeepAliveConditionalAndErasure() { - CodeGen code=compile(""" - { i64 -> i64 } native="C"; - val work_noInline={ i64 n -> - i64 raw=0; - n && ((raw=new u8[16])!=null); - return native(raw); - }; - return work_noInline(arg); - """); - var fun=code._allocation.summary("work_noInline").requireSupported(); - assertEquals(1,keeps(code).size()); - KeepAliveNode keep=keeps(code).get(0); - assertTrue(keep.in(1) instanceof PhiNode); - assertSame(keep,fun._fun.ret().ctrl()); - CallNode call=((CallEndNode)keep.in(0).in(0)).call(); - Node raw=call.arg(3); - KeepAliveNode.erase(code._start); - assertTrue(keeps(code).isEmpty()); - assertSame(raw,call.arg(3)); // Shared ordinary Phi must survive erasure. - assertFalse(raw.isDead()); - } - - @Test public void testKeepAliveLoopExits() { - CodeGen code=compile(""" - { i64 -> i64 } native="C"; - val work_noInline={ i64 n -> - i64 total=0; - while(n>0) { - i64 raw=new u8[16]; - total+=native(raw); - if(n==1) return total; - if(n==2) break; - n--; - if(n==3) continue; - total++; - } - return total; - }; - return work_noInline(arg); - """); - var fun=code._allocation.summary("work_noInline").requireSupported(); - assertFalse(keeps(code).isEmpty()); - for( var site : fun._sites ) if( site._allocation!=null ) { - assertNotNull(site._frame._loop); - assertFalse(site._frame._continues.contains(site)); - assertNotNull(site._scope); - } - } - - @Test public void testKeepAliveOuterLoopScope() { - CodeGen code=compile(""" - { i64 -> i64 } native="C"; - val work_noInline={ i64 n -> - i64 raw=0; - while((raw=new u8[16]) && native(raw) && n-->0) { } - return n; - }; - return work_noInline(arg); - """); - var fun=code._allocation.summary("work_noInline"); - // Predicate conversions belong to the enclosing scope; every iteration - // adds storage to that scope, unlike a conversion in the loop body. - assertFalse(fun.supported()); - assertTrue(fun._reject,fun._reject.contains("across its backedge")); - } - - @Test public void testKeepAliveRawReturnAndUnused() { - CodeGen code=compile(""" - val work_noInline={ -> - i64 raw=new u8[16]; - return raw+17; - }; - return work_noInline(); - """); - var fun=code._allocation.summary("work_noInline").requireSupported(); - assertTrue(fun._returns.isEmpty()); // Returned integer has no lifetime contract. - assertFalse(fun._scratch.isEmpty()); - assertEquals(1,keeps(code).size()); - code=compile("val work_noInline={ -> val a=new u8[16]; i64 unused=a; return 1; }; return work_noInline();"); - assertTrue(keeps(code).isEmpty()); - assertEquals("1",Eval2.eval(code,0)); - } - @Test public void testKeepAliveImportedBody() throws Exception { Path build=Path.of("build/objs/separate"); Files.createDirectories(build); @@ -959,361 +87,6 @@ public class Chapter33Test { assertTrue(keeps(code).isEmpty()); } - @Test public void testKeepAliveForwardConversion() { - CodeGen code=compile(""" - { i64 -> i64 } native="C"; - val work_noInline={ -> i64 raw=make_noInline(); return native(raw); }; - val make_noInline={ -> new u8[16]; }; - return work_noInline(); - """); - var fun=code._allocation.summary("work_noInline").requireSupported(); - assertEquals(1,keeps(code).size()); - assertFalse(fun._scratch.isEmpty()); - assertTrue(fun._returns.isEmpty()); - } - - @Test public void testKeepAliveImplicitScopes() { - CodeGen code=compile(""" - { i64 -> i64 } native="C"; - val work_noInline={ i64 n -> - i64 raw=0; - if(n) raw=new u8[16]; else raw=new u8[32]; - return native(raw); - }; - return work_noInline(arg); - """); - code._allocation.summary("work_noInline").requireSupported(); - // Each unbraced arm ends its own borrowing scope. The subsequent call - // deliberately uses stale integers; it must not move these endpoints. - assertEquals(2,keeps(code).size()); - for( KeepAliveNode keep : keeps(code) ) { - assertTrue(keep.in(0) instanceof CProjNode); - assertTrue(keep.in(0).in(0) instanceof IfNode); - boolean merges=false; - for( Node use : keep._outputs ) if( use instanceof RegionNode ) merges=true; - assertTrue(merges); - } - } - - @Test public void testKeepAliveNestedFunction() { - CodeGen code=compile(""" - { i64 -> i64 } native="C"; - val work_noInline={ i64 n -> - i64 raw=new u8[16]; - val helper_noInline={i64 k -> while(k>0) k--; return k;}; - helper_noInline(n); - return native(raw); - }; - return work_noInline(arg); - """); - var fun=code._allocation.summary("work_noInline").requireSupported(); - assertEquals(1,keeps(code).size()); - assertSame(keeps(code).get(0),fun._fun.ret().ctrl()); - assertFalse(fun._scratch.isEmpty()); - } - - // Until ^ and .del() have a checked source contract, a native call supplies - // the real control/memory boundary at which we ask the ownership question. - // These programs are analyzed only: retire is not linked or executed. - private static ArrayDelete deletion(CodeGen code) { - var calls=new ArrayList<CallNode>(); - code._start.walk(n -> { if( n instanceof CallNode call ) calls.add(call); return null; }); - CallNode checkpoint=null; - for( CallNode call : calls ) - if( call.external() ) { - assertNull("Expected one deletion checkpoint",checkpoint); - checkpoint=call; - } - assertNotNull("Missing deletion checkpoint",checkpoint); - return code._allocation.checkArrayDelete(checkpoint,3); - } - - @Test public void testArrayDeleteLocalAndBorrow() { - CodeGen code=compile(""" - val work_noInline={i64 n -> - { u8[] -> i64 } retire="C"; - val copy_noInline={u8[] dst, u8[] src, i64 len -> - for(i64 i=0; i<len; i++) dst[i]=src[i]; - return len; - }; - val old=new u8[n], next=new u8[n*2]; - copy_noInline(next,old,n); - retire(old); - return next[0]; - }; - return work_noInline(arg); - """); - ArrayDelete check=deletion(code); - assertTrue(check.toString(),check.proven()); - } - - private static final String BUFFER = "struct Buffer { u8[] !buf=new u8[8]; };\n"; - - @Test public void testArrayDeleteFieldReplacement() { - CodeGen code=compile(BUFFER+""" - val resize_noInline={!Buffer b, i64 n -> - { u8[] -> i64 } retire="C"; - val copy_noInline={u8[] dst, u8[] src, i64 len -> - for(i64 i=0; i<len; i++) dst[i]=src[i]; - return len; - }; - val old=b.buf; - val next=new u8[n]; - copy_noInline(next,old,old#); - b.buf=next; - retire(old); - return b.buf[0]; - }; - return resize_noInline(new Buffer,arg); - """); - ArrayDelete check=deletion(code); - assertNull(check.toString(),check._reject); - // Local kills are proved, caller uniqueness is NOT silently assumed. - assertNotNull(check._unique); - assertFalse(check.proven()); - assertTrue(check.toString().contains("requires unique entry")); - } - - @Test public void testArrayDeleteSurvivingAlias() { - for( String alias : new String[]{"old", "n ? old : new u8[8]"} ) { - CodeGen code=compile(""" - val work_noInline={i64 n -> - { u8[] -> i64 } retire="C"; - val old=new u8[n]; - val saved= - """+alias+";"+""" - retire(old); - return saved[0]; - }; - return work_noInline(arg); - """); - ArrayDelete check=deletion(code); - assertNotNull(check.toString(),check._reject); - assertTrue(check.toString(),check._reject.contains("survives deletion")); - } - } - - @Test public void testArrayDeleteConditionalKill() { - for( boolean both : new boolean[]{false,true} ) { - CodeGen code=compile(BUFFER+""" - val resize_noInline={!Buffer b, i64 n -> - { u8[] -> i64 } retire="C"; - val old=b.buf; - if(n) b.buf=new u8[16]; - """+(both ? "else b.buf=new u8[32];" : "")+""" - retire(old); - return b.buf[0]; - }; - return resize_noInline(new Buffer,arg); - """); - ArrayDelete check=deletion(code); - if( both ) assertNull(check.toString(),check._reject); - else { - assertNotNull(check.toString(),check._reject); - assertTrue(check.toString(),check._reject.contains("still holds the array")); - } - } - } - - @Test public void testArrayDeleteFreshOwnerAndStoredAlias() { - for( boolean saved : new boolean[]{false,true} ) { - CodeGen code=compile(""" - struct Buffer { u8[] !buf=new u8[8]; u8[]? !saved=null; }; - val work_noInline={i64 n -> - { u8[] -> i64 } retire="C"; - val b=new Buffer; - val old=new u8[n]; - b.buf=old; - """+(saved ? "b.saved=old;" : "")+""" - b.buf=new u8[n*2]; - retire(old); - return b; - }; - return work_noInline(arg); - """); - ArrayDelete check=deletion(code); - if( !saved ) assertTrue(check.toString(),check.proven()); - else { - assertNotNull(check.toString(),check._reject); - assertTrue(check.toString(),check._reject.contains("still holds the array")); - } - } - } - - @Test public void testArrayDeleteAliasedOwner() { - CodeGen code=compile(BUFFER+""" - val resize_noInline={!Buffer b, !Buffer other, i64 n -> - { u8[] -> i64 } retire="C"; - val old=b.buf; - val saved=other.buf; - b.buf=new u8[n]; - retire(old); - return saved[0]; - }; - val b=new Buffer; - return resize_noInline(b,b,arg); - """); - ArrayDelete check=deletion(code); - assertNotNull(check.toString(),check._reject); - assertTrue(check.toString(),check._reject.contains("survives deletion")); - } - - @Test public void testArrayDeleteRetainingHelper() { - CodeGen code=compile(""" - struct Buffer { u8[] !buf=new u8[8]; u8[]? !saved=null; }; - val work_noInline={i64 n -> - { u8[] -> i64 } retire="C"; - val retain_noInline={!Buffer b -> b.saved=b.buf; return 0; }; - val b=new Buffer; - val old=new u8[n]; - b.buf=old; - retain_noInline(b); - b.buf=new u8[n*2]; - retire(old); - return b; - }; - return work_noInline(arg); - """); - ArrayDelete check=deletion(code); - assertNotNull(check.toString(),check._reject); - assertTrue(check.toString(),check._reject.contains("field .saved still holds the array")); - } - - @Test public void testArrayDeleteRawBorrowAndRepeatedDelete() { - CodeGen code=compile(""" - val work_noInline={i64 n -> - { u8[] -> i64 } retire="C"; - val old=new u8[n]; - i64 address=old; - retire(old); - return address; - }; - return work_noInline(arg); - """); - ArrayDelete check=deletion(code); - assertNotNull(check.toString(),check._reject); - assertTrue(check.toString(),check._reject.contains("raw-address borrow")); - - code=compile(""" - val work_noInline={i64 n -> - { u8[] -> i64 } retire="C"; - val old=new u8[8]; - while(n>0) { retire(old); n--; } - return n; - }; - return work_noInline(arg); - """); - check=deletion(code); - assertNotNull(check.toString(),check._reject); - assertTrue(check.toString(),check._reject.contains("backedge")); - } - - @Test public void testArrayDeleteRehash() { - CodeGen code=compile(""" - struct Table { i64[] !keys=new i64[8]; }; - val rehash_noInline={!Table table -> - { i64[] -> i64 } retire="C"; - val old=table.keys; - val next=new i64[old#*2]; - for(i64 i=0; i<old#; i++) { - val key=old[i]; - if(key) { - i64 j=key & (next#-1); - while(next[j]) j=(j+1) & (next#-1); - next[j]=key; - } - } - table.keys=next; - retire(old); - return table.keys#; - }; - return rehash_noInline(new Table); - """); - ArrayDelete check=deletion(code); - assertNull(check.toString(),check._reject); - assertNotNull(check._unique); - assertFalse(check.proven()); - } - - @Test public void testArrayDeleteCopiedElementReference() { - CodeGen code=compile(""" - struct Item { i64 x=42; }; - val work_noInline={i64 n -> - { Item?[] -> i64 } retire="C"; - val item=new Item; - val old=new Item?[n]; - old[0]=item; - val saved=old[0]; - retire(old); - return saved ? saved.x : 0; - }; - return work_noInline(arg); - """); - ArrayDelete check=deletion(code); - assertTrue(check.toString(),check.proven()); - } - - @Test public void testArrayDeleteConstructorRetention() { - CodeGen code=compile(""" - struct Box { - u8[] buf; - new Box={u8[] buf -> self.buf=buf;}; - }; - val work_noInline={i64 n -> - { u8[] -> i64 } retire="C"; - val old=new u8[n]; - val box=new Box(old); - retire(old); - return box; - }; - return work_noInline(arg); - """); - ArrayDelete check=deletion(code); - assertNotNull(check.toString(),check._reject); - assertFalse(check.proven()); - } - - @Test public void testArrayDeleteSourceSyntax() { - for( String allocation : new String[]{"new u8[^arg]", "new u8[^]{1,2,3}", "new u8[^8]{int i -> i;}"} ) { - CodeGen code=compile("{ u8[^] a="+allocation+"; a.del(); return 42; }"); - code._allocation.requireSupported(); - assertEquals(1,code._allocation._deletes.size()); - assertTrue(code._allocation._deletes.get(0).toString(),code._allocation._deletes.get(0).proven()); - } - CodeGen code=compile(""" - val work_noInline={i64 n -> - val read_noInline={u8[~] a -> a[0];}; - val a=new u8[^n]; - val answer=read_noInline(a); - a.del(); - return answer; - }; - return work_noInline(arg); - """); - assertTrue(code._allocation._deletes.get(0).toString(),code._allocation._deletes.get(0).proven()); - code._allocation.summary("work_noInline").requireSupported(); - } - - private static void deleteError(String source, String message) { - try { compile("{"+source+"}"); fail("Expected deletion rejection"); } - catch( com.seaofnodes.simple.parser.Parser.ParseException e ) { - assertTrue(e.getMessage(),e.getMessage().contains(message)); - } - } - - @Test public void testArrayDeleteSourceErrors() { - deleteError("val a=new u8[8]; a.del(); return 0;","requires a non-null [^]"); - deleteError("u8[^] a=new u8[8]; return a#;","not of declared type"); - deleteError("val a=new u8[^8]; a.del(); return a[0];","survives deletion"); - deleteError("val a=new u8[^8]; a.del(); a.del(); return 0;","after deletion"); - deleteError("val a=new u8[^8]; return a.del;","must be called directly"); - deleteError("val a=new u8[^8]; a.del=0; return 0;","not a writable field"); - compile(""" - val consume_noInline={u8[^] a -> a.del(); return 0;}; - return consume_noInline(new u8[^8]); - """); - } - @Test public void testArrayDeleteExecutionNotImplemented() { CodeGen code=compile("{ val a=new u8[^8]; a.del(); return 0; }"); try { Eval2.eval(code,0); fail("Deletion must not silently become a no-op"); } @@ -1322,117 +95,6 @@ public class Chapter33Test { } } - @Test public void testArrayDeleteSerializedBody() throws Exception { - Path build=Path.of("build/objs/separate"); - Files.createDirectories(build); - Path lib=Files.createTempDirectory(build,"array-delete-"); - new CodeGen(null,lib.toString(),null,"DeleteLib",""" - val work={i64 n -> val a=new u8[^n]; a.del(); return n;}; - """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); - var paths=new Ary<>(new String[]{lib.toString()}); - CodeGen code=new CodeGen(null,lib.toString(),paths,"DeleteClient", - "return DeleteLib.work(arg);",123,true,TypeInteger.BOT) - .driver(CodeGen.Phase.TypeCheck); - assertFalse(code._allocation._deletes.isEmpty()); - for( ArrayDelete deletion : code._allocation._deletes ) assertTrue(deletion.toString(),deletion.proven()); - } - - @Test public void testArrayDeleteSourceField() { - CodeGen code=compile(""" - struct Buffer { u8[^] !buf=new u8[^8]; }; - val work_noInline={i64 n -> - val b=new Buffer; - val old=b.buf; - b.buf=new u8[^n]; - old.del(); - return b; - }; - return work_noInline(arg); - """); - assertEquals(1,code._allocation._deletes.size()); - assertTrue(code._allocation._deletes.get(0).toString(),code._allocation._deletes.get(0).proven()); - } - - @Test public void testArrayDeleteForwardMember() { - CodeGen code=compile(""" - val work_noInline={ -> val b=make(); val old=b.buf; b.buf=new u8[^16]; old.del(); return b; }; - struct Buffer { u8[^] !buf=new u8[^8]; }; - val make={ -> new Buffer; }; - return work_noInline(); - """); - assertFalse(code._allocation._deletes.isEmpty()); - for( ArrayDelete deletion : code._allocation._deletes ) assertTrue(deletion.toString(),deletion.proven()); - // A forward receiver with a user-defined del is an ordinary method. - code=compile(""" - val work_noInline={ -> make().del(); }; - struct Thing { val del={ -> 17; }; }; - val make={ -> new Thing; }; - return work_noInline(); - """); - assertTrue(code._allocation._deletes.isEmpty()); - assertEquals("17",Eval2.eval(code,0)); - } - - // Read the same remote bound as ary.capacity, without that helper or - // ary.copy obscuring the initializer's effect on the deletion proof. - @Test public void testArrayDeleteAryu8IntegerInit() { - var paths=new Ary<>(new String[]{TestC.RELEASE_SYS_DIR}); - CodeGen code=new CodeGen(null,null,paths,"Test",""" - { i32 -> i64 } _exit="C"; - struct aryu8 { - u32 !len = 0; - u8[^] !buf = new u8[^1]; - val _grow_noInline = { u32 len2 -> - if( len+len2 <= buf# ) return self; - i64 newlen = buf#*2; - // Triggers <clinit> for sys.integer - if( newlen > sys.integer.MAX_U32 ) _exit(1); - val old = buf; - val next = new u8[^newlen]; - for(u32 i=0; i<len; i++) next[i] = old[i]; - buf = next; - old.del(); - return self; - }; - }; - u32 extra=arg; - return new aryu8()._grow_noInline(extra); - """,126,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation); - assertEquals(2,code._allocation._deletes.size()); - ArrayDelete deletion=code._allocation._deletes.get(0); - assertTrue(code._allocation._deletes.get(1).toString(),code._allocation._deletes.get(1).proven()); - FunNode integerInit=code.link(code._compunits.get("sys/integer")); - SummaryNode summary=integerInit.summary(); - // Break here to inspect the imported summary and the deletion memory. - assertNotNull("Exercise a loaded summary, not a parsed initializer body",summary); - assertFalse(summary._effects._referenceWrites); - assertNotSame(TypeMem.BOT,summary._state.mem()); - assertNull(deletion.toString(),deletion._reject); - assertNotNull(deletion.toString(),deletion._unique); - for( FunNode fun : code._linker ) - assertTrue("Unreferenced DateTime must not survive Opto", - fun==null || fun.isDead() || fun._name==null || !fun._name.contains("sys.time.DateTime")); - var grow=code._allocation.summary("_grow_noInline").requireSupported(); - boolean dynamic=false; - for( Allocation.Site site : grow._sites ) - if( site._allocation!=null && site._bytes<0 ) { - assertEquals("buddy",site.destination()); - assertFalse(grow._scratch.contains(site)); - dynamic=true; - } - assertTrue(dynamic); - var inits=new ArrayList<CLInitNode>(); - code._start.walk(n -> { if( n instanceof CLInitNode init ) inits.add(init); return null; }); - boolean found=false; - for( CLInitNode init : inits ) - if( init.cu()==integerInit._compunit ) { - assertFalse(init.bypass()); - found=true; - } - assertTrue("The remote initialization guard must remain",found); - code.driver(CodeGen.Phase.TypeCheck); - } - @Test public void testExitCallEnd() { CodeGen code=compile(""" { i32 -> i64 } _exit="C"; @@ -1468,654 +130,330 @@ public class Chapter33Test { assertEquals("18",Eval2.eval(code,17)); } - @Test public void testAllocationBuddyLoop() { - // Two iterations' blocks may coexist; neither occupies iteration scratch. - CodeGen code=compile(""" - val work_noInline={i64 n -> - u8[^] !last=new u8[^1]; - i64 total=0; - while(n>0) { - val next=new u8[^n]; - total+=last#; - last=next; - n--; - } - return total+last#; - }; - return work_noInline(arg); - """); - var sum=code._allocation.summary("work_noInline").requireSupported(); - boolean carried=false; - for( Allocation.Summary loop : sum._frames ) - for( Allocation.Site site : loop._continues ) - if( site._allocation!=null && site._frame==loop ) { - assertTrue(site.buddy()); - assertFalse(loop._scratch.contains(site)); - carried=true; - } - assertTrue(carried); + private static Allocation2 points2(String source) { + CodeGen code=new CodeGen(source).driver(CodeGen.Phase.Allocation2); + assertTrue(code._allocation2.verify()); + return code._allocation2; } - @Test public void testSummaryOwnEffects() throws Exception { - Path base=Files.createDirectories(Path.of("build/objs/summary-effects")); - Path lib=Files.createTempDirectory(base,"own-"); - new CodeGen(null,lib.toString(),null,"Effects",""" - u8[] !saved=new u8[0]; - val retain_noInline={u8[] xs -> saved=xs; return 0;}; - val _callback_noInline={i64 n -> n+1;}; - val _unused_noInline={i64 n -> n+2;}; - val clean_noInline={i64 n -> n+3;}; - val publish_noInline={ -> - { {i64 -> i64} -> i64 } publish="C"; - publish(_callback_noInline); - while(true) {} - }; - """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); - var paths=new Ary<>(new String[]{lib.toString()}); - CodeGen code=new CodeGen(null,null,paths,"Clean", - "return Effects.clean_noInline(arg);",123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck); - for( FunNode fun : code._linker ) - if( fun!=null && !fun.isDead() && fun._name!=null ) { - assertFalse(fun._name,fun._name.contains("publish_noInline")); - assertFalse(fun._name,fun._name.contains("_callback_noInline")); - assertFalse(fun._name,fun._name.contains("_unused_noInline")); - if( fun._name.endsWith("clean_noInline") ) { - assertNotNull(fun.summary()); - assertSame(com.seaofnodes.simple.type.XInt.EMPTY,fun.summary()._effects._writes); - } - } - assertEquals("20",Eval2.eval(code,17)); - - code=new CodeGen(null,null,paths,"Retain", - "Effects.retain_noInline(new u8[3]); return Effects.saved#;",123,true,TypeInteger.BOT) - .driver(CodeGen.Phase.TypeCheck); - boolean retained=false; - for( FunNode fun : code._linker ) - if( fun!=null && !fun.isDead() && fun._name!=null && fun._name.endsWith("retain_noInline") ) { - assertNotNull(fun.summary()); - assertTrue(fun.summary()._effects._referenceWrites); - assertNotSame(com.seaofnodes.simple.type.XInt.EMPTY,fun.summary()._effects._writes); - retained=true; - } - assertTrue(retained); - assertEquals("3",Eval2.eval(code,0)); - - // Retention on a nonreturning path must survive saving/loading too. - code=new CodeGen(null,null,paths,"Publish", - "if(arg) Effects.publish_noInline(); return 7;",123,true,TypeInteger.BOT) - .driver(CodeGen.Phase.TypeCheck); - boolean callback=false; - for( FunNode fun : code._linker ) - if( fun!=null && !fun.isDead() && fun._name!=null && fun._name.endsWith("_callback_noInline") ) { - assertTrue(fun.unknownCallers()); - callback=true; - } - assertTrue("The native can retain the callback before the infinite loop",callback); - } - - @Test public void testArrayDeleteAryu8Copy() { - var paths=new Ary<>(new String[]{TestC.RELEASE_SYS_DIR}); - CodeGen code=new CodeGen(null,null,paths,"Test",""" - struct aryu8 { - u32 !len = 0; - u8[^] !buf = new u8[^1]; - val _grow_noInline = { u32 len2 -> - if( len2 <= buf# ) return self; - val old = buf; - val next = new u8[^len2]; - sys.ary.copy(next,0,old,0,len); - buf = next; - old.del(); - return self; - }; - }; - u32 extra=arg; - return new aryu8()._grow_noInline(extra); - """,126,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation); - assertEquals(2,code._allocation._deletes.size()); - ArrayDelete deletion=code._allocation._deletes.get(0); - assertTrue(code._allocation._deletes.get(1).toString(),code._allocation._deletes.get(1).proven()); - FunNode copy=null; - for( FunNode fun : code._linker ) - if( fun!=null && !fun.isDead() && "sys.ary.copy".equals(fun._name) ) copy=fun; - assertNotNull(copy); - CallNode copyCall=null; - for( CallNode call : code._calls ) - if( !call.isDead() && call.fptr()._type instanceof TypeFunPtr fp && - fp.isConstant() && fp.fidx()==copy.sig().fidx() ) copyCall=call; - assertNotNull(copyCall); - var effects=code._effects.get(copy); - var contract=code._allocation.summary("sys.ary.copy").requireSupported(); - // Break here: the unloaded copy's contract returns arg3 (dst). - assertNotNull(copy.summary()); - assertNotNull(copy.summary()._allocation); - assertEquals(1,contract._returns.size()); - assertEquals(3,contract._returns.iterator().next()._arg); - assertFalse(effects._referenceWrites); - assertTrue(copy.ret().expr()._type instanceof TypeMemPtr); - assertNull(deletion.toString(),deletion._reject); - assertNotNull(deletion._unique); - code.driver(CodeGen.Phase.TypeCheck); - } - - @Test public void testAllocationSerializedContracts() throws Exception { - Path base=Files.createDirectories(Path.of("build/objs/allocation-contracts")); - Path lib=Files.createTempDirectory(base,"graph-"); - var paths=new Ary<>(new String[]{lib.toString()}); - new CodeGen(null,lib.toString(),null,"Contracts",THING+HOLDER+""" - val make_noInline={i64 n -> new Thing(n);}; - val holder_noInline={ -> new Holder;}; - val field_noInline={Holder h -> h.c;}; - val put_noInline={ !Holder h, Thing t -> h.c=t; return 0;}; - val choose_noInline={Thing a, Thing b, i64 n -> n ? a : b;}; - struct Link { Link? !next; i64 x; new Link={i64 n -> x=n;}; }; - val cycle_noInline={i64 n -> - val a=new Link(n), b=new Link(n+1); - a.next=b; b.next=a; return a; - }; - val unsupported_noInline={u32 n -> new u8[n];}; - val buddy_noInline={u32 n -> new u8[^n];}; - """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); - CodeGen code=new CodeGen(null,null,paths,"Use",""" - val work_noInline={i64 n -> - val h=Contracts.holder_noInline(); - val a=Contracts.make_noInline(n), b=Contracts.make_noInline(n+1); - Contracts.put_noInline(h,a); - return Contracts.choose_noInline(Contracts.field_noInline(h),b,n); - }; - return work_noInline(arg).x + Contracts.cycle_noInline(arg).x; - """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck); - for( String name : new String[]{"make_noInline","field_noInline","put_noInline","choose_noInline","cycle_noInline"} ) { - var sum=code._allocation.summary(name).requireSupported(); - assertNotNull("Contract must work without loading "+name,sum._fun.summary()); - } - var make=code._allocation.summary("make_noInline"); - var made=make._returns.iterator().next(); - assertTrue(made._fresh); - assertNull(made._allocation); - assertTrue(made._bytes>0); - assertEquals("arg3.c",code._allocation.summary("field_noInline")._returns.iterator().next()._name); - assertEquals(2,code._allocation.summary("choose_noInline")._returns.size()); - assertEquals(4,code._allocation.summary("put_noInline")._retained.iterator().next()._arg); - var cycle=code._allocation.summary("cycle_noInline"); - var a=cycle._returns.iterator().next(); - var b=a._fields.get("next").iterator().next(); - assertTrue(b._fields.get("next").contains(a)); - var work=code._allocation.summary("work_noInline").requireSupported(); - int copies=0; - for( Allocation.Site site : work._sites ) - if( site._fresh && site._name.endsWith("/"+made._name) ) { - assertTrue(work._returns.contains(site)); - copies++; + private static ArrayList<Allocation2.Site> sites2(Allocation2 analysis, String type) { + var sites = new ArrayList<Allocation2.Site>(); + for( var site : analysis._sites.values() ) + if( site._node instanceof NewNode && + !com.seaofnodes.simple.type.TypeStruct.startsClzPrefix(site.type()._name) && + site.type()._name.endsWith("."+type) ) { + FunNode fun = ((NewNode)site._node).cfg0().fun(); + // Inspect inlined allocations, excluding the retained constructor body. + if( !fun._name.endsWith(".<new>") ) + sites.add(site); } - assertEquals("Each call imports distinct fresh storage",2,copies); - assertEquals("34",Eval2.eval(code,17)); - - // Contracts composed from imported contracts survive another export. - new CodeGen(null,lib.toString(),paths,"Bridge", - "val forward_noInline={i64 n -> Contracts.make_noInline(n);};",123,true,TypeInteger.BOT) - .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); - code=new CodeGen(null,null,paths,"UseBridge","return Bridge.forward_noInline(arg).x;",123,true,TypeInteger.BOT) - .driver(CodeGen.Phase.TypeCheck); - var forward=code._allocation.summary("forward_noInline").requireSupported(); - assertNotNull(forward._fun.summary()); - assertTrue(forward._returns.iterator().next()._fresh); - assertEquals(made._bytes,forward._returns.iterator().next()._bytes); - assertEquals("19",Eval2.eval(code,19)); - - code=new CodeGen(null,null,paths,"Unsupported","u32 n=arg; return Contracts.unsupported_noInline(n)#;",123,true,TypeInteger.BOT) - .driver(CodeGen.Phase.Allocation); - var unsupported=code._allocation.summary("unsupported_noInline"); - assertNotNull(unsupported._fun.summary()); - assertFalse(unsupported.supported()); - assertTrue(unsupported._reject,unsupported._reject.contains("variable-size allocation")); - - code=new CodeGen(null,null,paths,"Buddy","u32 n=arg; return Contracts.buddy_noInline(n)#;",123,true,TypeInteger.BOT) - .driver(CodeGen.Phase.TypeCheck); - var buddy=code._allocation.summary("buddy_noInline").requireSupported(); - assertNotNull(buddy._fun.summary()); - var block=buddy._returns.iterator().next(); - assertTrue(block._fresh); - assertTrue(block.buddy()); - assertEquals(-1,block._bytes); + return sites; } - @Test public void testArrayDeleteImportedReturnedAlias() throws Exception { - Path base=Files.createDirectories(Path.of("build/objs/allocation-contracts")); - Path lib=Files.createTempDirectory(base,"borrow-"); - var paths=new Ary<>(new String[]{lib.toString()}); - new CodeGen(null,lib.toString(),null,"Borrow","val identity_noInline={u8[] xs -> xs;};",123,true,TypeInteger.BOT) - .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); - for( boolean after : new boolean[]{false,true} ) { - String source="{ val a=new u8[^8]; val b=Borrow.identity_noInline(a); "+ - (after ? "a.del(); return b[0]; }" : "val x=b[0]; a.del(); return x; }"); - CodeGen code=new CodeGen(null,null,paths,"Use",source,123,true,TypeInteger.BOT) - .driver(CodeGen.Phase.Allocation); - var contract=code._allocation.summary("identity_noInline").requireSupported(); - assertNotNull(contract._fun.summary()); - ArrayDelete deletion=code._allocation._deletes.get(0); - if( after ) { - assertNotNull(deletion.toString(),deletion._reject); - assertTrue(deletion._reject,deletion._reject.contains("survives deletion")); - } else { - assertTrue(deletion.toString(),deletion.proven()); - code.driver(CodeGen.Phase.TypeCheck); + @Test public void testAllocation2SharedFactory() { + Allocation2 a = points2(THING+""" + val make_noInline={i64 x -> new Thing(x);}; + val first=make_noInline(arg); + val second=make_noInline(arg+1); + return read_noInline(first)+read_noInline(second); + """); + var things = sites2(a,"Thing"); + assertEquals("A shared factory has one abstract NewNode, not a copy per call",1,things.size()); + int[] calls={0}; + CodeGen.CODE._start.walk(n -> { + if( n instanceof CallEndNode cend && "make_noInline".equals(cend.call().name()) ) { + assertFalse(a.getPts(cend)._unknown); + assertEquals(1,a.getPts(cend)._sites.size()); + assertTrue(a.getPts(cend).contains(things.get(0))); + calls[0]++; + } + return null; + }); + assertEquals(2,calls[0]); + } + + @Test public void testAllocation2SeparateObjectsAndWeakStores() { + Allocation2 a=points2(THING+""" + struct Box { Thing? !child=null; }; + val get_noInline = { Box b -> b.child ? read_noInline(b.child) : 0;}; + val b = new Box; + val c = new Box; + b.child = new Thing(arg); + c.child = new Thing(arg+1); + int result=get_noInline(b)+get_noInline(c); + b.child = new Thing(arg+2); + return result+get_noInline(b); + """); + var boxes = sites2(a,"Box"); + var things= sites2(a,"Thing"); + assertEquals(2,boxes.size()); + assertEquals(3,things.size()); + var b = boxes.get(0).field("child"); + var c = boxes.get(1).field("child"); + assertFalse(b._unknown); assertFalse(c._unknown); + assertEquals(3,b._sites.size()+c._sites.size()); + assertTrue("One field remembers both pre- and post-overwrite values", + b._sites.size()==2 || c._sites.size()==2); + for( var site : b._sites ) + assertFalse("Fields belong to sites, not the shared TypeStruct",c.contains(site)); + for( var site : c._sites ) + assertFalse("Fields belong to sites, not the shared TypeStruct",b.contains(site)); + for( var thing : things ) assertEquals(1,thing._incoming); + } + + @Test public void testAllocation2LoopAndPhi() { + Allocation2 a = points2(""" + struct Cell { Cell? next; i64 x; new Cell = { Cell? n, i64 x -> next=n; self.x=x;}; }; + val read_noInline = { Cell? c -> c ? c.x : 0;}; + Cell? !head = null; + for(int i=0;i<arg;i++) head = new Cell(head,i); + return read_noInline(head); + """); + var cells = sites2(a,"Cell"); + assertEquals(1,cells.size()); + var cell = cells.get(0); + assertFalse(cell.field("next")._unknown); + assertTrue("A summary self edge represents distinct list cells",cell.field("next").contains(cell)); + for( Node n : a._points.keySet() ) + if( n instanceof PhiNode && !(n instanceof ParmNode) ) + assertTrue( a.getPts(n).contains(cell) ); + } + + @Test public void testAllocation2PointerArrays() { + Allocation2 a=points2(THING+""" + val readArray_noInline={Thing?[] xs,u32 i -> xs[i] ? read_noInline(xs[i]) : 0;}; + val xs=new Thing?[2]; + xs[0]=new Thing(arg); + xs[1]=new Thing(arg+1); + return readArray_noInline(xs,0)+readArray_noInline(xs,1); + """); + var things = sites2(a,"Thing"); + assertEquals(2,things.size()); + int arrays=0; + for( var site : a._sites.values() ) { + var elements = site.field("[]"); + if( elements!=null ) { + assertFalse(elements._unknown); + assertEquals(2,elements._sites.size()); + for( var thing : things ) assertTrue(elements.contains(thing)); + arrays++; } } + assertEquals(1,arrays); } - private static final String OWNED_BUFFER=""" - struct Buffer { - u8[^] !buf = new u8[^1]; - val grow_noInline = { u32 n -> - if( n <= buf# ) return 0; - val old = buf; - buf = new u8[^n]; - old.del(); - return 0; - }; - }; - """; - - @Test public void testArrayConsumeCallers() { - compile(OWNED_BUFFER.replace("return 0;","return self;")+""" - { val v=new Buffer; return v.grow_noInline(8).buf#; } - """); - for( String body : new String[]{ - "val v=new Buffer; v.grow_noInline(8); return v.buf#;", - "val v=new Buffer; val w=v; v.grow_noInline(8); return w.buf#;", - "val v=new Buffer; val saved=v.buf; val x=saved[0]; v.grow_noInline(8); return x;"} ) { - CodeGen code=compile(OWNED_BUFFER+"{"+body+"}"); - boolean required=false, checked=false; - for( ArrayDelete deletion : code._allocation._deletes ) { - assertNull(deletion.toString(),deletion._reject); - if( deletion._requirement!=null ) { - assertEquals("arg2.buf",deletion._requirement.toString()); required=true; - } else { assertTrue(deletion.proven()); checked=true; } - } - assertTrue(required); assertTrue(checked); - } - for( String body : new String[]{ - "val v=new Buffer; val saved=v.buf; v.grow_noInline(8); return saved[0];", - "val v=new Buffer; val saved=v.buf; v.grow_noInline(8); return saved#;", - "val v=new Buffer; val saved=v.buf; v.grow_noInline(8); saved[0]=1; return 0;"} ) - deleteError(OWNED_BUFFER+"{"+body+"}","deletion"); + @Test public void testAllocation2UnknownBoundary() { + Allocation2 a = points2(""" + {i64 -> u8[]} native="C"; + val get_noInline={i64 n -> native(n);}; + return get_noInline(arg)#; + """); + int cnt=0; + for( Node n : a._points.keySet() ) + if( n instanceof CallEndNode cend && + "get_noInline".equals(cend.call().name()) ) { + assertTrue("An external result is unknown",a.getPts(cend)._unknown); + cnt++; + } + assertEquals(1,cnt); + } + + @Test public void testAllocation2ExternalParameters() { + CodeGen code=new CodeGen(null,null,null,"External", + THING+"val borrow_noInline = { Thing t -> read_noInline(t); };", + 123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation2); + Allocation2 a = code._allocation2; + int cnt = 0; + for( Node n : a._points.keySet() ) + if( n instanceof ParmNode p && p._idx==3 && "borrow_noInline".equals(p.fun()._name) ) { + assertTrue("Start's memory input denotes an external pointer, even with no known escaping objects",a.getPts(p)._unknown); + cnt++; + } + assertEquals(1,cnt); + assertTrue(a.verify()); + } + + @Test public void testAllocation2ImportedSignatureAndRefinedReturn() { + var paths = new Ary<>(new String[]{"build/release/"+TestC.CPU_PORT+"_"+TestC.CALL_CONVENTION}); + CodeGen code = new CodeGen(null,null,paths,"Use",""" + val main = { u8[~][] args -> + val nums = sys.aryi64.parseAryI64(args[0]); + val dst = new u8[8]; + sys.ary.copy(dst,0,args[0],0,1); + return nums ? nums.len+dst# : 0; + }; + """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation2); + Allocation2 a = code._allocation2; + boolean[] found={false,false}; + code._start.walk(n -> { + if( n._type.isHigh() ) return null; + if( n instanceof CallEndNode end && "sys.aryi64.parseAryI64".equals(end.call().name()) ) { + var pts=a.getPts(end); + assertNotNull(pts); + assertTrue(pts._unknown || !pts._sites.isEmpty()); + found[0]=true; + } + if( n instanceof SummaryNode ) found[1]=true; + return null; + }); + assertTrue(found[0]); assertTrue(found[1]); + assertTrue(a.verify()); + } + + // Reduced from Clock: the preceding qualified new used to leave only + // a sys placeholder, causing the parameter to stop at the first dot. + @Test public void testSourceQualifiedCanvasParameter() throws Exception { + Path out=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs")),"canvas-source-"); + CodeGen code=new CodeGen("src/main/smp",out.toString(),null,"Clock",""" + val _survey_sys = sys; + val main = { -> new sys.draw.Canvas(320,240); }; + val _draw = { sys.draw.Canvas screen -> screen.width; }; + return 0; + """,456,true,TypeInteger.BOT); + code.driver(CodeGen.Phase.Parse); } - @Test public void testArrayConsumeForwarding() { - CodeGen code=compile(OWNED_BUFFER+""" - val forward_noInline={ !Buffer v,u32 n -> v.grow_noInline(n);}; - { val v=new Buffer; forward_noInline(v,8); return v.buf#; } + @Test public void testQualifiedForwardTypeChain() { + CodeGen code=compile(""" + val make={ -> new A.B.C.D(); }; + val read={ A.B.C.D d -> d.x; }; + A.B.C.D? saved=null; + struct A { struct B { struct C { struct D { int x=42; }; }; }; }; + return read(make()); """); - assertEquals(List.of(new ArrayDelete.Consume(3,List.of("buf"))), - code._allocation.summary("forward_noInline")._consumes); - deleteError(OWNED_BUFFER+""" - val forward_noInline={ !Buffer v,u32 n -> v.grow_noInline(n);}; - { val v=new Buffer; val saved=v.buf; forward_noInline(v,8); return saved[0]; } - ""","deletion"); - String nested=OWNED_BUFFER+""" - struct Outer {!Buffer !b; new Outer={!Buffer b -> self.b=b;};}; - val nested_noInline={ !Outer o -> o.b.grow_noInline(8);}; - """; - code=compile(nested+"{val v=new Buffer; val o=new Outer(v); nested_noInline(o); return o.b.buf#;}"); - assertEquals(List.of(new ArrayDelete.Consume(3,List.of("b","buf"))), - code._allocation.summary("nested_noInline")._consumes); - deleteError(nested+"{val v=new Buffer; val o=new Outer(v); val saved=v.buf; nested_noInline(o); return saved[0];}","deletion"); - - String redirected=OWNED_BUFFER+""" - struct Outer {!Buffer !b; new Outer={!Buffer b -> self.b=b;};}; - val redirect_noInline={ !Outer o,!Buffer b -> o.b=b; o.b.grow_noInline(8);}; - """; - code=compile(redirected+"{val a=new Buffer,b=new Buffer; val o=new Outer(a); redirect_noInline(o,b); return o.b.buf#;}"); - assertEquals(List.of(new ArrayDelete.Consume(4,List.of("buf"))), - code._allocation.summary("redirect_noInline")._consumes); - deleteError(redirected+"{val a=new Buffer,b=new Buffer; val o=new Outer(a); val saved=b.buf; redirect_noInline(o,b); return saved[0];}","deletion"); + assertEquals("42",Eval2.eval(code,0)); } - @Test public void testArrayConsumeStoredAliases() { - String saved="struct Saved {u8[]? !a;};"; - deleteError(OWNED_BUFFER+saved+""" - { val v=new Buffer; val saved=new Saved; saved.a=v.buf; - v.grow_noInline(8); return saved.a==null; } - ""","still holds the array"); - deleteError(OWNED_BUFFER+saved+""" - { val v=new Buffer; val saved=new Saved; saved.a=v.buf; - if(arg) saved.a=null; - v.grow_noInline(8); return saved.a==null; } - ""","still holds the array"); - compile(OWNED_BUFFER+saved+""" - { val v=new Buffer; val saved=new Saved; saved.a=v.buf; - saved.a=null; v.grow_noInline(8); return v.buf#; } + @Test public void testQualifiedTypeThroughOpenDefinition() { + CodeGen code=compile(""" + struct A { + val make={ -> new A.B.C.D(); }; + struct B { struct C { struct D { int x=42; }; }; }; + }; + return new A.make().x; """); - // Aliasing two formal parameters must not evade the callee's check. - deleteError(OWNED_BUFFER+""" - val bad_noInline={ !Buffer v,u8[] saved -> v.grow_noInline(8); return saved[0];}; - { val v=new Buffer; return bad_noInline(v,v.buf); } - ""","deletion"); - deleteError(OWNED_BUFFER+""" - val consume_noInline={u8[^] a -> a.del(); return 0;}; - { val v=new Buffer; consume_noInline(v.buf); return v.buf#; } - ""","still holds the array"); - } - - @Test public void testArrayConsumeIndirect() { - String functions=""" - val consume_noInline={u8[^] a -> a.del(); return 0;}; - val leave_noInline={u8[^] a -> a#;}; - """; - compile(functions+"{val a=new u8[^8]; return (arg ? consume_noInline : leave_noInline)(a);}"); - deleteError(functions+""" - {val a=new u8[^8]; (arg ? consume_noInline : leave_noInline)(a); return a[0];} - ""","deletion"); - deleteError(""" - val recurse_noInline={u8[^] a,i64 n -> if(n) return recurse_noInline(a,n-1); a.del(); return 0;}; - return recurse_noInline(new u8[^8],arg); - ""","recursive consuming"); - deleteError(functions+""" - val invoke_noInline={ {u8[^] -> i64} f,u8[^] a -> f(a);}; - return invoke_noInline(consume_noInline,new u8[^8]); - ""","ownership contract"); - deleteError(functions+""" - struct Handler { val f=consume_noInline; }; - { {Handler -> i64} invoke="C"; - return invoke(new Handler); } - ""","Consuming callback"); + assertEquals("42",Eval2.eval(code,0)); } - @Test public void testArrayConsumeImported() throws Exception { - Path base=Files.createDirectories(Path.of("build/objs/ownership")); - Path lib=Files.createTempDirectory(base,"consume-"); - var paths=new Ary<>(new String[]{lib.toString()}); - new CodeGen(null,lib.toString(),null,"Types","struct Buffer {u8[^] !buf=new u8[^1];};",123,true,TypeInteger.BOT) + @Test public void testQualifiedExpressionIsMemberAccess() throws Exception { + Path root=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs")),"qualified-expr-"); + Files.createDirectories(root.resolve("sys/draw")); + Files.writeString(root.resolve("sys.smp"),"val draw=draw;"); + Files.writeString(root.resolve("sys/draw.smp"),"val Canvas=Canvas;"); + Files.writeString(root.resolve("sys/draw/Canvas.smp"),"int foo=42;"); + CodeGen code=new CodeGen(root.toString(),root.resolve("obj").toString(),null,"Clock",""" + val keep=sys; + sys.draw.Canvas.foo; + if( sys.draw.Canvas.foo ) return sys.draw.Canvas.foo; + return 0; + """,456,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck); + assertEquals("42",Eval2.eval(code,0)); + for( String name : com.seaofnodes.simple.parser.Parser.TYPES.keySet() ) + assertFalse("Expression lookahead created a type: "+name,name.endsWith(".foo")); + } + + @Test public void testAllocation2ImportedParameterConstants() { + var paths=new Ary<>(new String[]{"build/release/"+TestC.CPU_PORT+"_"+TestC.CALL_CONVENTION}); + CodeGen code=new CodeGen(null,null,paths,"Copy",""" + val main={u8[~][] args -> + val dst=new u8[8]; + sys.ary.copy(dst,0,args[0],0,1); + return dst[0]; + }; + """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation2); + Allocation2 a=code._allocation2; + int[] receivers={0}; + code._start.walk(n -> { + if( n instanceof ParmNode parm && parm._idx==2 && "sys.ary.copy".equals(parm.fun()._name) ) { + // The hidden TypePtr receiver is not a memory reference. + assertNull(a.getPts(parm)); + receivers[0]++; + } + return null; + }); + assertEquals(1,receivers[0]); + assertTrue(a.verify()); + } + + // A newly escaped byte array must requeue the unknown call's result. + @Test public void testAllocation2EscapeCallProgress() { + CodeGen code=new CodeGen(""" + {i64 -> u8[]?[]} get="C"; + {i64 -> u8[]} take="C"; + { val sink=get(0); sink[0]=new u8[8]; return take(0)#; } + """).driver(CodeGen.Phase.Allocation2); + assertTrue(code._allocation2.verify()); + } + + // The load and its guard likewise need to refire when escapes grow. + @Test public void testAllocation2EscapeLoadProgress() { + CodeGen code=new CodeGen(""" + struct Sink { u8[]? !a=null; }; + {i64 -> !Sink} get="C"; + { val sink=get(0); sink.a=new u8[8]; + val other=get(1); return other.a ? other.a# : 0; } + """).driver(CodeGen.Phase.Allocation2); + assertTrue(code._allocation2.verify()); + } + + @Test public void testAllocation2ImportedPointerIdentity() throws Exception { + Path lib=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs")),"points-import-"); + new CodeGen(null,lib.toString(),null,"Identity","val echo_noInline={u8[] a -> a;};",123,true,TypeInteger.BOT) .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); - new CodeGen(null,lib.toString(),paths,"Grow",""" - val grow_noInline={ !Types.Buffer v,u32 n -> - if(n<=v.buf#) return 0; - val old=v.buf; v.buf=new u8[^n]; old.del(); return 0; - }; - """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); - new CodeGen(null,lib.toString(),paths,"Forward",""" - val forward_noInline={ !Types.Buffer v,u32 n -> Grow.grow_noInline(v,n);}; - """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); - for( int variant=0; variant<4; variant++ ) { - boolean alias=variant==1; - String grow=variant==3 ? "Forward.forward_noInline(v,8); Forward.forward_noInline(v,16);" : - variant==2 ? "for(u32 i=2; i<arg; i++) Forward.forward_noInline(v,i);" : - "Forward.forward_noInline(v,8);"; - CodeGen code=new CodeGen(null,null,paths,"Use",""" - { val v=new Types.Buffer; - """+(alias ? "val saved=v.buf;" : "")+grow+" return "+ - (alias ? "saved[0];}" : "v.buf#;}"),123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation); - var sum=code._allocation.summary("forward_noInline"); - assertNotNull("Use the serialized requirement without loading the body",sum._fun.summary()); - assertEquals(List.of(new ArrayDelete.Consume(3,List.of("buf"))),sum._consumes); - if( alias ) { - try { code.driver(CodeGen.Phase.TypeCheck); fail("Saved alias must reject"); } - catch( com.seaofnodes.simple.parser.Parser.ParseException e ) { - assertTrue(e.getMessage(),e.getMessage().contains("deletion")); - } - } else { - for( ArrayDelete check : code._allocation._deletes ) assertTrue(check.toString(),check.proven()); - code.driver(CodeGen.Phase.TypeCheck); - } + var paths=new Ary<>(new String[]{lib.toString()}); + CodeGen code=new CodeGen(null,null,paths,"UseIdentity",""" + { val a=new u8[arg]; return Identity.echo_noInline(a)#; } + """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation2); + Allocation2 a=code._allocation2; + Allocation2.Site local=null; + for( var site : a._sites.values() ) if( site._node instanceof NewNode ) local=site; + assertNotNull(local); + assertTrue(a._escapes.contains(local)); + int summaries=0; + for( Node n : a._points.keySet() ) + if( n instanceof SummaryNode ) { + assertTrue(a.getPts(n)._unknown); + assertTrue("A returned argument remains a possible local target",a.getPts(n).contains(local)); + summaries++; + } + assertEquals(1,summaries); + assertTrue(a.verify()); + } + + @Test public void testAllocation2OpaqueScalarCallEscapesGraph() { + CodeGen code=new CodeGen(""" + struct Box { u8[] !child=new u8[8]; }; + {!Box -> i64} native="C"; + { val b=new Box; return native(b); } + """).driver(CodeGen.Phase.Allocation2); + Allocation2 a=code._allocation2; + int roots=0; + for( var box : sites2(a,"Box") ) { + assertTrue(a._escapes.contains(box)); + assertNotNull(box.field("child")); + assertFalse(box.field("child")._sites.isEmpty()); + for( var child : box.field("child")._sites ) assertTrue(a._escapes.contains(child)); + roots++; } + assertEquals(1,roots); + assertTrue(a.verify()); } - @Test public void testArrayConsumeGrowLoop() { - // Reduced from parseAryI64: nums.add(...) repeatedly calls _grow, - // which may replace/delete the backing buffer on each iteration. - CodeGen code=new CodeGen(OWNED_BUFFER+""" - { - val v=new Buffer; - u32 n=arg; - for(u32 i=2; i<n; i++) v.grow_noInline(i); - return v.buf#; - } - """).driver(CodeGen.Phase.Allocation); - ArrayDelete repeated=null; - for( ArrayDelete check : code._allocation._deletes ) - if( !Intrinsic.arrayDelete(check._call) ) repeated=check; - assertNotNull("Exercise the repeated consuming call",repeated); - CallNode growCall=repeated._call; - FunNode grow=code.link((TypeFunPtr)growCall.fptr()._type); - var contract=code._allocation.summary(grow._name); - // Break here: code, repeated, growCall, grow, and contract are available. - assertEquals(List.of(new ArrayDelete.Consume(2,List.of("buf"))),contract._consumes); - assertTrue(repeated.toString(),repeated.proven()); - code.driver(CodeGen.Phase.TypeCheck); + // Return escape growth must requeue unknown-caller constants and parameters. + @Test public void testAllocation2ReturnEscapeProgress() { + CodeGen code=new CodeGen(null,null,null,"Progress",""" + val make_noInline={i64 n -> new u8[n];}; + val read_noInline={u8[] a -> a#;}; + """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation2); + assertTrue(code._allocation2.verify()); } - @Test public void testArrayConsumeLoopBackedges() { - compile(OWNED_BUFFER+""" - val many_noInline={ !Buffer v,u32 n -> - val same=v; - for(u32 i=2; i<n; i++) same.grow_noInline(i); - return v.buf#; - }; - u32 n=arg; - return many_noInline(new Buffer,n); - """); - compile(OWNED_BUFFER+""" - { val v=new Buffer; - u32 n=arg; - for(u32 i=2; i<n; i++) { - val before=v.buf#; - v.grow_noInline(i); - if(before>4) break; - } - return v.buf#; - } - """); - compile(OWNED_BUFFER+""" - { val v=new Buffer; - u32 n=arg; - for(u32 i=2; i<n; i++) - for(u32 j=2; j<i; j++) v.grow_noInline(j); - return v.buf#; - } - """); - // Each iteration gets its own allocation. Repeating delete on one - // allocation instead must fail, even without any other array accesses. - compile("{ for(int i=0; i<arg; i++) { val a=new u8[^8]; a.del(); } return 0; }"); - deleteError("val a=new u8[^8]; for(int i=0; i<arg; i++) a.del(); return 0;","backedge"); - - deleteError(OWNED_BUFFER+""" - val v=new Buffer; - val saved=v.buf; - u32 n=arg; - for(u32 i=2; i<n; i++) v.grow_noInline(i); - return saved; - ""","backedge"); - deleteError(OWNED_BUFFER+""" - val v=new Buffer; - val saved=v.buf; - u32 n=arg; - int sum=0; - for(u32 i=2; i<n; i++) { - sum+=saved[0]; - v.grow_noInline(i); - } - return sum; - ""","backedge"); - // A previous iteration's local is still an alias, not a fresh reload. - deleteError(OWNED_BUFFER+""" - val v=new Buffer; - u8[^]? !saved=null; - u32 n=arg; - int sum=0; - for(u32 i=2; i<n; i++) { - if(saved) sum+=saved[0]; - saved=v.buf; - v.grow_noInline(i); - } - return sum; - ""","backedge"); - // Conservatively reject copies of the replacement across the boundary. - // The SSA case could pass with a proof that its last use precedes the - // next grow; that ordering is not yet an iteration-entry contract. - deleteError(OWNED_BUFFER+""" - val v=new Buffer; - u8[^]? !saved=null; - u32 n=arg; - int sum=0; - for(u32 i=2; i<n; i++) { - if(saved) sum+=saved[0]; - v.grow_noInline(i); - saved=v.buf; - } - return sum; - ""","backedge"); - deleteError(OWNED_BUFFER+""" - struct Saved { u8[^]? !a=null; }; - val v=new Buffer; - val saved=new Saved; - u32 n=arg; - for(u32 i=2; i<n; i++) { - v.grow_noInline(i); - saved.a=v.buf; - } - return saved.a ? saved.a# : 0; - ""","backedge"); - deleteError(OWNED_BUFFER+""" - struct Saved { u8[^]? !a=null; }; - val save_noInline={ !Saved saved,!Buffer v -> saved.a=v.buf; return 0; }; - val v=new Buffer; - val saved=new Saved; - u32 n=arg; - for(u32 i=2; i<n; i++) { - v.grow_noInline(i); - save_noInline(saved,v); - } - return saved.a ? saved.a# : 0; - ""","backedge"); - // A consuming contract describes the entry buffer. It must not hide - // the callee publishing a new alias of its replacement before return. - deleteError(OWNED_BUFFER.replace("u8[^] !buf = new u8[^1];", - "u8[^] !buf = new u8[^1]; u8[^]? !saved=null;") - .replace("old.del();","old.del(); saved=buf;")+""" - val v=new Buffer; - u32 n=arg; - for(u32 i=2; i<n; i++) v.grow_noInline(i); - return v.saved ? v.saved# : 0; - ""","backedge"); - } - @Test public void testArrayConsumeTwoGrows() { - // Reduced from text.string's padding, text, and trailing-padding grows. - CodeGen code=new CodeGen(OWNED_BUFFER+""" - { - val v=new Buffer; - v.grow_noInline(8); - v.grow_noInline(16); - return v.buf#; - } - """).driver(CodeGen.Phase.Allocation); - ArrayDelete first=null, second=null; - for( ArrayDelete check : code._allocation._deletes ) { - if( Intrinsic.arrayDelete(check._call) ) continue; - if( first==null ) first=check; - else if( check._call.dominates(first._call,null) ) { second=first; first=check; } - else second=check; - } - assertNotNull(first); - assertNotNull(second); - // Break here: code, first, and second expose both caller checkpoints. - assertTrue(first.toString(),first.proven()); - assertTrue(second.toString(),second.proven()); - code.driver(CodeGen.Phase.TypeCheck); - } - - @Test public void testArrayConsumeComposedCalls() { - compile(OWNED_BUFFER+""" - { val v=new Buffer; - if(arg) v.grow_noInline(8); - v.grow_noInline(16); - return v.buf#; - } - """); - compile(OWNED_BUFFER+""" - { val v=new Buffer; u32 n=arg; - for(u32 i=2; i<n; i++) { - v.grow_noInline(i); - v.grow_noInline(n); - } - return v.buf#; - } - """); - compile(OWNED_BUFFER.replace("u8[^] !buf = new u8[^1];",""" - u8[^] !buf; - new Buffer={u8[^] initial -> buf=initial;}; - """)+""" - { val v=new Buffer(new u8[^1]); - v.grow_noInline(8); v.grow_noInline(16); return v.buf#; - } - """); - String append=OWNED_BUFFER+""" - val append_noInline={ !Buffer v,u8[~] xs -> - v.grow_noInline(8); return xs[0]+v.buf#; - }; - """; - compile(append+"{val v=new Buffer; return append_noInline(v,\"hello\");}"); - deleteError(append+"{val v=new Buffer; return append_noInline(v,v.buf);}","aliases the array"); - // Distinct wrapper formals can still name the same wrapper. A saved - // field load cannot inherit the direct-array-parameter disjointness. - deleteError(OWNED_BUFFER+""" - val peek_noInline={ !Buffer a,!Buffer b -> - val saved=a.buf; b.grow_noInline(8); return saved[0]; - }; - { val v=new Buffer; return peek_noInline(v,v); } - ""","deletion"); - for( boolean between : new boolean[]{false,true} ) - deleteError(OWNED_BUFFER+"{val v=new Buffer;"+ - (between ? "v.grow_noInline(8); val saved=v.buf;" : "val saved=v.buf; v.grow_noInline(8);")+ - "v.grow_noInline(16); return saved[0];}","deletion"); - deleteError(OWNED_BUFFER+""" - struct Saved {u8[^]? !a=null;}; - { val v=new Buffer; val s=new Saved; u32 n=arg; - for(u32 i=2; i<n; i++) { - v.grow_noInline(i); v.grow_noInline(n); s.a=v.buf; - } - return s.a ? s.a# : 0; - } - ""","backedge"); - compile(""" - struct Saved {u8[^]? !a=null;}; - val save_noInline={ !Saved s,u8[^] a -> s.a=a; return 0;}; - { val s=new Saved; val a=new u8[^8]; - save_noInline(s,a); s.a=null; a.del(); return 0; - } - """); - try { - compile(""" - u8[^]? !saved=null; - val save_noInline={u8[^] a -> saved=a; return 0;}; - {val a=new u8[^8]; save_noInline(a); a.del(); return saved ? saved# : 0;} - """); - fail("Global retained alias must reject"); - } catch( com.seaofnodes.simple.parser.Parser.ParseException e ) { - // The helper's global initialization remains an opaque effect. - assertTrue(e.getMessage(),e.getMessage().contains("unknown reference effects")); - } - } - - @Test public void testArrayConsumeImportedOpaqueEffects() throws Exception { - Path base=Files.createDirectories(Path.of("build/objs/ownership")); - Path lib=Files.createTempDirectory(base,"opaque-"); - var paths=new Ary<>(new String[]{lib.toString()}); - new CodeGen(null,lib.toString(),null,"Types","struct Saved {i64 !address=0;};",123,true,TypeInteger.BOT) - .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); - new CodeGen(null,lib.toString(),paths,"Opaque",""" - val save_noInline={ !Types.Saved s,u8[] a -> s.address=a; return 0;}; - """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); - CodeGen code=new CodeGen(null,null,paths,"Use",""" - { val s=new Types.Saved; val a=new u8[^8]; - Opaque.save_noInline(s,a); a.del(); return s.address; - } - """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation); - assertNotNull(code._allocation.summary("save_noInline")._fun.summary()); - try { code.driver(CodeGen.Phase.TypeCheck); fail("Raw store must remain opaque after loading its summary"); } - catch( com.seaofnodes.simple.parser.Parser.ParseException e ) { - assertTrue(e.getMessage(),e.getMessage().contains("unknown reference effects")); - } + @Test public void testAllocation2ReturnEscapeProgressEscapeDraw() { + var paths = new Ary<>(new String[]{"build/release/"+TestC.CPU_PORT+"_"+TestC.CALL_CONVENTION}); + CodeGen code = new CodeGen(null,null,paths,"Use", + "val _draw={i64 x -> x+1;}; val main={ -> sys.math.max(1,2);};", + 123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation2); + assertTrue(code._allocation2.verify()); } } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java b/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java index 2794fca9..8bce0891 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java @@ -27,7 +27,7 @@ public class PhaseTest { code.driver(Phase.TypeCheck); // A repeated request does not rerun anything. assertEquals("45",Eval2.eval(code,10)); code.driver(Phase.LocalSched); - assertEquals("Parse Iter Opto IterPostOpto FinalizeIR LoopTree Allocation TypeCheck Unlink Schedule LocalSched", + assertEquals("Parse Iter Opto IterPostOpto FinalizeIR LoopTree Allocation2 TypeCheck Unlink Schedule LocalSched", String.join(" ",phases)); assertNull(code._serial); assertNull(code._mach); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java b/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java index 4e590d2e..971d6811 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java @@ -224,7 +224,9 @@ public class SelectiveLoadingTest { "if(arg==0) return -1; return Lib.api.p_noInline(((arg<<32)>>32));",123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck); assertNotNull(function(code,"Lib.Api.p_noInline").summary()); assertNotNull(function(code,"Lib.Work.write_noInline").summary()); - assertAbsent(code,"Lib.Unused.f"); + // Conservative type summaries may expose another declaration. They + // must still leave its implementation unloaded. + assertNotLoaded(code,"Lib.Unused.f"); assertEquals("-1",Eval2.eval(code,0)); assertNotNull("An untaken branch does not load its target",function(code,"Lib.Api.p_noInline").summary()); assertEquals("42",Eval2.eval(code,41)); @@ -238,7 +240,7 @@ public class SelectiveLoadingTest { .driver(CodeGen.Phase.TypeCheck); assertNull("p requested Api's implementation",function(code,"Lib.Api.p").summary()); assertNotNull("The remaining call needs a signature, not a body",function(code,"Lib.Work.write_noInline").summary()); - assertAbsent(code,"Lib.Unused.f"); + assertNotLoaded(code,"Lib.Unused.f"); code.driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); Path driver = app.resolve("driver.c"); Files.writeString(driver,""" @@ -266,6 +268,12 @@ public class SelectiveLoadingTest { assertTrue(name,fun==null || fun.isDead() || !name.equals(fun._name)); } + private static void assertNotLoaded(CodeGen code, String name) { + for( FunNode fun : code._linker ) + if( fun!=null && !fun.isDead() && name.equals(fun._name) ) + assertNotNull(name,fun.summary()); + } + private static FunNode function(CodeGen code, String name) { for( FunNode fun : code._linker ) if( fun!=null && name.equals(fun._name) ) return fun; throw new AssertionError("Missing function "+name); diff --git a/skills/chapter25-codex-notes.md b/skills/chapter25-codex-notes.md index 7a0face8..8d4ec57d 100644 --- a/skills/chapter25-codex-notes.md +++ b/skills/chapter25-codex-notes.md @@ -33,309 +33,37 @@ field shapes, existing Iter/SCCP propagates them, and TypeCheck checks and erase the views. Borrowed partials can read proven fields but cannot write; unknown callers promise no initialized fields. No new passes or backward demand walks. -## Current checkpoint before reset (2026-11-23) - -Cliff requested another attempt at normal array-wrapper ownership composition, -then intends to review/commit and step back to assess the architecture. That -attempt is finished and validated. The next conversation should start from -[the survey's review checkpoint](../chapter33/docs/array-delete-survey.md#checkpoint-for-design-review), -not automatically continue adding exceptions or implementing recycling. - -Workspace: `C:/Users/cliffc/Desktop/Simple`, PowerShell, branch `ch33`; HEAD when -saved was `96f150b0` (Simple loops, loop escapes and loop scratch). The large dirty -workspace includes several earlier turns' work. Nothing was committed or pushed. -Preserve it all, including untracked `ArrayDelete.java`, `FunctionEffects.java`, -`docs/ArrayDeleteSurvey.java`, and `docs/array-delete-survey.md` under chapter33. - -The latest change is mainly ArrayDelete's per-call field substitution. The -allocation graph remains flow-insensitive; deletion checks follow memory SSA. -Interned Ref identities distinguish incoming fields, callee allocations, and -exclusive outgoing call/loop versions. Effects maps callee may-stores and return -origins into the caller. Initializers use this machinery too. `arrayOwned` proves -exclusive outgoing fields from the boundary graph; dumps now print that guarantee. -Loop versions distinguish previous-iteration call results, and backedge checks -cover explicit stores AND helper-retained aliases. The longer design/invariants -entry below describes this and the separate, still-unfixed verifier reproducer. - -Serialized IR is now format 8. `_opaqueEffects` prevents raw/native/initialization -effects missing from the field graph from being treated as no-retention. The -release sys library was rebuilt. Previous library caches were moved, not deleted, -to `chapter33/build/array-delete-format3` through `array-delete-format7`. - -Debugger cases at the end of `Chapter33Test.java`: - -- `testArrayConsumeTwoGrows` (near line 2003) now PASSES; breakpoint comment exposes - `code`, `first`, and `second` caller checkpoints. It used to assert rejection. -- `testArrayConsumeGrowLoop` (near line 1864) is the single-grow loop example. -- `testArrayConsumeComposedCalls` covers branches, multiple grows per iteration, - buffer-taking initializers, borrowed input arrays, saved aliases, and helper stores. -- `testArrayConsumeImportedOpaqueEffects` proves the raw-effect marker survives - serialization. Keep the class in a separate module from the helper so loading - its constructor does not restore the helper's body and defeat this test. - -Validation: `make -j8 tests_nographics` PASSED; log is -`chapter33/build/compose-full.log`. `git diff --check` passed. Latest source survey: -`chapter33/build/array-delete-survey/run-10730582824125651151/results.tsv`, with -console output in `chapter33/build/compose-survey.log`. Full migrations pass for -aryi64, bitset, and Canvas. aryu8's ordinary grow/add/append, string/integer -formatting, aryi64.str, and elapsed formatting checks pass; the whole aryu8 -migration still rejects native read, floating-result origins, and time.local's -native effects. Timers still rejects consuming recursion. No survey crashes. -Runtime array recycling is NOT implemented. - -The survey runner accepts `-Dsimple.delete.graph=true` to save graph.txt and -allocation.txt per case (quote this option in PowerShell). Run from chapter33; -the survey document gives javac/java commands. Temporary probes and backups in -build are debugging artifacts. In particular, DO NOT rerun -`build/compose-array-delete.py`: it generated an intermediate implementation and -would overwrite subsequent fixes. Current source files are authoritative. - -User preferences: no bold in terminal responses; no streams/StringJoiner; -append new tests to Chapter33Test rather than separate test classes; use -j8; -keep debugger examples small. No subagents unless explicitly requested. - -## Chapter 33: restart guidance (2026-11-16) - -Cliff closed Chapter 32 and requested `ch32` rebased onto `main`, then a new -complete snapshot on branch `ch33`. Continue in `chapter33/`. Cliff selected -automatic memory management as the next topic. On 2026-11-19 Cliff requested -the first analysis pass after Opto and before TypeCheck, few new classes, -ASCII debugging, conservative rejections, and 3-4 poster children. The agreed decisions and remaining -questions are in [the survey's base design](../docs/automatic-memory-management-survey.md#agreed-base-design--2026-11-17). -The initial implementation is `codegen/Allocation.java`, after FinalizeIR and -LoopTree, before TypeCheck. One call-DAG DFS composes symbolic summaries in postorder; -local reference-edge closure uses a worklist. Four poster children and boundary -checks live in Chapter33Test. The phase is analysis-only: existing allocation -lowering is unchanged. `simple.alloc.dump` prints ASCII, `simple.alloc.check` -requires all plans to be supported; otherwise unsupported summaries record a -rejection without blocking the existing allocator. SCCs, variable sizes, -opaque calls, and raw addresses are deferred. Pointer-valued loads now select -field targets; borrowed paths such as arg3.c have their own destination identity. -Local weak-union closure covers loads, stores, and call substitutions before -owner propagation. Actual aliases are resolved at calls; array indices share -one field. Fresh sites are imported once per call. Incoming borrowed paths are -separate from store edges: returning a child must not retain its holder. Weak -updates that expand paths beyond the body's reads plus imported path depths -reject instead of truncating; memory-ordered updates remain future work. -Loop Phis now join the same local monotone reference calculation. Allocation -uses CFG `_ltree` membership and LoopTree parent links, without rediscovering -loop bodies. Reducibility is asserted by LoopTree. The early tree build does -not insert synthetic exits: doing so would change nonreturning summaries before -serialization. Unlink rebuilds the tree after Lower's CFG changes and inserts -one synthetic exit only for loops with zero exits. Any fresh -allocation reachable across a backedge rejects the plan, via pointer Phis or -memory retention (including helper effects). Collection starts from both the -function entry and Return, so zero-exit bodies are analyzed without synthetic -exits. Exit-only winners get fixed storage -before the loop; unrelated scratch uses iteration storage. Inner-loop winners -can live in the outer iteration. Bound exemptions and overwrite/liveness proofs -are not implemented yet. Functions and loop iterations now use the same Summary -class, with entry/normal-exit/continuation ports, retention effects, and scratch -cleanup sets. One function-wide reference closure shares SSA/Site identities -with nested loop summaries; calls substitute those identities. Summary interfaces -drive promotion through parent frames, replacing the separate loop placement -scan. Continuation cleanup and normal-exit cleanup use the same scratch set. -Borrowed continuation references are supported. Tests include scalar exit values, -nested returns, mixed winner/scratch, helper allocations, exit-only stores, winner -graphs, and rejected linked/array/helper retention. No stack lowering is emitted. -Serialized lifetime summaries were added on 2026-11-23; see the update below. -Update 2026-11-21: Cliff requires the temporary LoopTree ordering above to be -replaced before closing Chapter 33, but explicitly deferred implementation. -Insert NeverExits in the original LoopTree build, then remove Allocation's -zero-exit-body support and its extra forward CFG traversal. Resolve the -nonreturning-summary issue rather than delaying synthetic exits. Lower should -maintain LoopTree with minor local edits, eliminating the full rebuild before -scheduling. Track completion in the roadmap's phase-ordering section. -The 2026-11-21 [allocation survey](../chapter33/docs/allocation-survey.md) -measures `sys` (98/179 supported summaries, 11 with user-storage sites) and ten -examples (43/68 own summaries, three with user-storage sites). First-cause -rejections are mostly native/opaque calls and raw addresses; they mask dynamic -arrays and potentially later failures. Scalar libm/clock calls need targeted -contracts; do not interpret arbitrary i64 arguments as pointer-free. The native -`simple_text_float` allocates its returned Simple byte array with malloc, outside -NewNode analysis, so needs an allocation contract or a caller-buffer interface. -Local variable-sized scratch and returned variable-sized arrays both reject; -fixed-size Holder overwrites reject while explicit object reuse passes. These -are survey findings, not authorization to change contracts or allocation lowering. -The standalone probe and function-level snapshot live beside the report. -Update 2026-11-21, native borrowing: Cliff authorized Plan A: native calls borrow -references through the call and do not hide, publish, or retain them. Allocation -now recognizes finite all-native target sets via externFunc, accepts scalar -results, and follows PtrToInt provenance through SSA arithmetic/Phis. Raw returns, -memory stores, and Simple integer-argument forwarding still reject; typed-pointer -wrappers work. Native Simple-pointer results still require origin contracts. -No ABI or runtime allocator changes. Scope lifetime is the documented upper -bound; brace-level scopes are absent here, so current plans use function/iteration -frames. Tests cover raw Phis/offsets, loop scratch, typed wrappers, and backedge -and memory escape rejection. Update 2026-11-22: known native `_exit` calls keep -ordinary live CallEnd control, with TypeMem.TOP memory and TypeScalar.TOP result. -The concrete machine call remains. Mixed/unknown targets stay conservative; -there is no exception edge or dead-control rewrite. -Update 2026-11-19: Cliff accepted the entire -[embedded-object design](../docs/automatic-memory-management-survey.md#agreed-design-embedded-objects-values-and-references), -including `*T` object values, `&` interior references, and `*(T[4])` embedded -fixed buffers. Length and element storage are separate layout components; -length widths may be smaller than four bytes. Each array representation has a -known maximum element count; preventing length wrap follows from enforcing -that maximum, rather than being the primary semantic rule. Removing constant length fields -is future work, not an implementation request. A uniform struct with fixed -named fields and a growing final array tail is also selected; exact tail and -length-width syntax remains open. The tail grows until scope-based finishing. -Placement uses `new(destination) T(args)`; `region` declarations are top-level -only and denote program-lifetime storage with no language-level size bound. -Labeled scopes supply lexical destinations. Free lists from delete are compiler -internals, not user-visible pools. These distinctions supersede older pool -terminology below. `new E[]` begins growth, `es += e` appends, and the creating -scope's end finishes growth without necessarily ending storage lifetime. -Update 2026-11-21: ordinary arrays remain non-deletable. Cliff approved a distinct -deletable-array type with provisional modifier `^` and explicit `.del()`. It -disallows interior pointers and requires proof that no usable aliases or borrows -survive deletion. Blocks may then share a type-independent buddy allocator with -internal metadata. Automatic deletion on overwrite is deferred. ArrayDelete is -also an opt-in checkpoint query; old native-call fixtures are not executable -deletes. It follows memory-ordered field kills and SSA uses, with narrow borrowing -helper contracts. Incoming ownership is reported as an unmet unique-entry -requirement, not silently assumed. Source syntax is now `E[^]`, `new E[^N]`, and -`.del()`: a deferred member Load folds to a memory-effecting intrinsic call. -TypeCheck requires every deletion proof. Caller contract checking and runtime -recycling are still pending. TypeMemPtr._del is an AND/dual capability coordinate; -ordinary array parameters accept borrowed deletable arrays. NewNode preserves -the allocation flag through cloning and serialization; IR format is now 4. -The five-library migration survey has no crashes; bitset discharges local kills, -aryu8/aryi64 now hit sys.ary.capacity's effects, Timers/Canvas hit class-init effects. All incoming cases -still reject without checked caller uniqueness. Tests end Chapter33Test. -Update 2026-11-22: the reduced aryu8 case's Test.$init load now folds by proving -the flag on every incoming memory path, including across Parm nodes. It reaches -the unique-entry requirement. Nonreturning TOP memory contributes no retained -references to deletion checks. Allocation plans mark ^ arrays as buddy storage, -allow dynamic sizes and overlapping loop allocations, and exclude these blocks -from stack cleanup. Ownership/reference tracking remains; runtime buddy lowering -is not implemented. -Update 2026-11-22, function effects: FunctionEffects scans each live body and -unions written aliases, reference-write flags, and introduced escapes along -call edges to a fixed point. Serialize saves those per-function effects, never -StopCU's compilation-wide escape set; IR format is now 5. Imported initializer -dependencies do not expose their incidental return value. Late body loading -restores only its summary dependency closure and repairs types after reattaching -the graph. The integer-init regression no longer retains unrelated DateTime -functions and reaches the unique-entry requirement. Production aryi64, bitset, -and Canvas pass local deletion checks; aryu8 needs ary.copy's reference-result -contract. Timers' first buffer passes locally; subsequent buffers hit preceding -deletions' unknown effects. All incoming ownership still needs caller checks. -Update 2026-11-23: IR format 6 saves Allocation boundary contracts in function -metadata. Allocation.write/read preserve symbolic argument and field origins, -return sets, reference-store edges (including cycles), ownership destinations, -fresh allocation sizes and buddy flags, and unsupported-plan diagnostics. Local -scratch/loop frames are not exported. No IR nodes are needed to load or compose -these contracts. Site._fresh distinguishes unloaded fresh storage from borrowed -storage even when _allocation is null. Callers import fresh sites separately for -each call. Returned-argument borrowing now handles ary.copy and tracks the result -alias through deletion checks. aryu8 joins aryi64/bitset/Canvas at the incoming -uniqueness requirement. Timers still needs preceding deletion effects handled. -Tests at the end of Chapter33Test cover the copy debugger case, imported field -paths/retention, fresh and cyclic graphs, re-export, unsupported plans, buddy -sizes, and rejection of surviving returned aliases. Runtime recycling remains -unimplemented. -Update 2026-11-23, consuming ownership: Summary._consumes holds argument/field -entry paths (ArrayDelete.Consume), serialized even for unsupported allocation -plans in IR format 8 (format 7 introduced the consuming paths). A separate ownership DAG walk uses the already-collected -calls/nodes, including finite indirect targets; it discharges fresh caller -storage or propagates requirements outward. ArrayDelete checks both direct -deletion and consuming calls. The selected owner's post-call field reload is -valid; saved aliases, retained other slots, and conditional kills reject. -Nested paths follow preceding stores: o.b=b; grow(o.b) requires b.buf, not the -old o.b.buf. Non-inlined initializers now use the same call-field substitution -as other helpers; the former initializedArrays special case is removed. -Recursive consuming groups and callbacks without ownership contracts reject; -call field effects compose at their memory outputs. ArrayDelete interns Ref -identities for local nodes, incoming fields, callee allocations, and call/loop -ownership versions. Node identity hashes avoid touching GVN. Effects substitutes -the existing summary graph's may-stores and result origins; a proven unique -outgoing field is a strong ownership transfer. Unknown raw/native/CLInit effects -set Summary._opaqueEffects, propagated and serialized in format 8. Do not infer -no-retention merely because a partial field graph has no reference stores. -Loop backedges now end the current deletion checkpoint's CFG walk. Pointer Phis, -invariant references reused by the next iteration, and stored replacement aliases -are checked at that boundary. The updated owner field has a distinct ownership -version; ArrayDelete must not mistake it for a saved copy of the entry array. -Loop-entry versions separate previous-iteration call results from current ones; -the check includes preheader origins and aliases of the backedge's current value. -Allocation.arrayOwned additionally checks the callee's existing boundary graph -for aliases of the outgoing field (also works on imported summaries). A consume -requirement alone does NOT prove unique outgoing ownership. Merge queries after -the checkpoint exclude arms that bypassed it, including zero-iteration exits. -Recursive SCC heads need this same boundary check when their graphs are built. -Reduced aryu8 copy/integer tests pass caller checks. The source survey passes -aryi64 (including parseAryI64), bitset, and Canvas. aryu8's normal grow/add/append, -string/integer formatting, aryi64.str, and elapsed formatting checks pass. Its -remaining blockers are native read, floating result origins, and time.local's -native effects; Timers still stops on consuming recursion. Separate array -parameters may rely on the propagated unique-entry requirement; callers reject -actual aliases. Do not extend that assumption to arbitrary owner field paths: -two wrapper parameters can name the same wrapper. -Tests at Chapter33Test's end cover wrapper sharing, saved -reads/lengths/writes, stored aliases, forwarding/redirection, finite indirect -calls, rejected callbacks/recursion, imported/re-exported requirements, repeated -grows (testArrayConsumeGrowLoop is the debugger example), nested loops/breaks, -and stale or replacement aliases crossing a backedge. Scratch field copies -across iterations remain conservative even if a later iteration would kill them. -Separate verifier follow-up found during ownership tests: a constructor-supplied -callback can fail EscapeNode monotonicity in IterPostOpto, before Allocation runs. -Reproducer (wrap in a block, use new CodeGen(source).driver(TypeCheck), assertions on): -`val consume_noInline={u8[^] a -> a.del(); return 0;};` -`val leave_noInline={u8[^] a -> a#;};` -`struct Handler { {u8[^] -> i64} f; new Handler={ {u8[^] -> i64} f -> self.f=f;}; };` -`{ {Handler -> i64} invoke="C"; return invoke(new Handler(consume_noInline)); }` -Observed Esc#5 at node119 widens escaped aliases from a restricted outside set -to FULL. This is not fixed by the consuming pass. The native-callback ownership -regression uses a direct `val f=consume_noInline` field and rejects correctly. -Classes opt into deletion/recycling; stale reads remain type-safe but can see -historical field values, including finals. Incomplete references cannot be -stored into deletable objects, including during construction. The older ban on -array deletion is superseded only by the distinct, strictly checked array type -above; class-slot stale-reference semantics do not apply to arrays. Deletable -constructors use ordinary aliasable memory from entry, while non-deletable -constructors retain private memory. Keep initialization obligations separate -from storage privacy; withholding TMP._one is a suggested implementation route -to audit, not a verified sufficient change. Preserve these decisions; older -discussion in the survey includes superseded assumptions. -Do not treat other roadmap sketches as chosen mechanisms. -Pools have global or shorter lexical lifetimes (2026-11-18 decision), rather -than transferred/object-owned lifetimes. Global pools retain their storage. -Pool reclamation requires proving all usable references gone, including stale -references after object delete and reachable historical pointer values. Object -delete never waives the region-lifetime proof. Analysis design remains deferred. -Function lifetime contracts infer borrowing, result origins/destinations, and -retention for ordinary definitions; opaque callback interfaces default to -borrowing arguments for the call, with retention explicit and implementations -checked. Result contracts remain necessary. Specializing functions by argument -treatment is an optional optimization, never a condition of language legality. -Native functions use the same external lifetime contracts: their written Simple -FFI type supplies trusted promises that the native implementation must honor. -No separate native lifetime mechanism is needed; mismatches are binding or -implementation bugs. -Returned-borrow syntax agreed 2026-11-19: function result `T from arg`, or -`T from (a | b)` for alternative origins. Only arguments mentioned in `from` -need names in the function type; other parameters may remain unnamed. `T` is -a struct reference, while `*T` is an object value. Bodies infer contracts or -are checked against written ones; annotations do not silently extend storage. -For now FFI cannot directly return borrowed interior references into Simple -objects. Native array adapters return indices/ranges and Simple constructs -checked interior references. Field-reference FFI returns are deferred. -Apparent unbounded growth under inferred lifetimes must be an error, never a -warning or merely a report. The user fixes it with a cheap explicit choice of -the default stack destination or an appropriate pool. Neither annotation waives -lifetime safety. Growth-check repetition means an unknown loop bound, a known -upper bound greater than 10, or recursion; small bounded loops are exempt on -that account. Support make-and-test loops retaining only the winner, where -failed candidates provably do not escape. Syntax and implementation remain open. -Preserve Chapter 32's compiler and performance narrative. -The test commands and invariants below also apply to Chapter 33. - -The initial Chapter 33 snapshot passed `make -j8 tests` (819 executions) and -`make -j8 release`. Subsequent edits only update documentation and the Maven -display name. The chapter cut and roadmap cleanup remain uncommitted; check -Git status on restart. No push was requested. +## Chapter 33: memory analysis + +Work in chapter33. Allocation2 is the only allocation-analysis phase; the old +Allocation, ArrayDelete, FunctionEffects, contracts, and option flags are removed. +Do not restore them from an old handoff. Git retains previous implementations. +The [memory-management design](../chapter33/docs/memory-management.md) records the +current abstraction, ownership/lifetime decisions, tradeoffs, and paper references. +The [growing-array design](../chapter33/docs/growing-arrays.md) retains the selected +construction-scope and return-storage rules. Other language proposals remain in +the [roadmap](../docs/roadmap.md) and +[language design](../docs/automatic-memory-management-survey.md); use the current +Chapter33 design where older deletion and allocator assumptions conflict. + +Allocation2 uses one Site per optimized NewNode/static object, weak field facts, +and dependency-driven WorkList propagation. Earlier inlining supplies context +precision. Ownership, storage selection, and recycling remain future work. +Separate-compilation boundary handling is incomplete. Internal call dependencies +do not publish FIDXs; imported cofinite escape sets must not invent caller-private +escapes. Import ordering and universe rebasing are pending work. + +Never exits are inserted before Allocation2/TypeCheck; preserve semantic returns +for nonreturning functions. Serialized format is C0DA. Rebuild old objects. +Tests pay for verification and inspection; production should not retain extra +graph collections or run analyses solely to support tests. + +Use -j8, add regressions to Chapter33Test, and keep debugger examples small. +No streams/StringJoiner, no bold terminal responses, and no subagents unless +explicitly requested. Keep live failing regressions visible; a checkpoint commit +does not imply the suite passes. Temporary probes and logs belong under build, +not in chapter documentation. Preserve final decisions and supporting examples, +not chronological investigation transcripts or archived source copies. ## Chapter 32: completed snapshot (2026-11-15 guidance) |
