diff --git a/dev/src/driver/toolchain.cpp b/dev/src/driver/toolchain.cpp index d042fa03b..5be3bc61e 100644 --- a/dev/src/driver/toolchain.cpp +++ b/dev/src/driver/toolchain.cpp @@ -325,6 +325,20 @@ void input_language(Invocation& invocation) : Input::Kind::Source; } +uint32_t parse_wasm_stack_size(const std::string& size) +{ + uint64_t bytes = 0; + for (char digit : size) + { + if (digit < '0' || digit > '9' || bytes > 0x7fffffffu / 10) + throw InvocationError("invalid Wasm stack size"); + bytes = bytes * 10 + static_cast(digit - '0'); + } + if (bytes == 0 || bytes > 0x7fffffffu || bytes % 16 != 0) + throw InvocationError("Wasm stack size must be a positive multiple of 16 below 2 GiB"); + return static_cast(bytes); +} + Invocation parse(const std::vector& args, const PreprocessorOptions& base) { Invocation invocation; @@ -373,19 +387,7 @@ Invocation parse(const std::vector& args, const PreprocessorOptions else if (starts_with(arg, "--gcc-install-dir=")) gcc_install_dir = arg.substr(arg.find('=') + 1); else if (starts_with(arg, "-Wl,-z,stack-size=")) - { - const std::string size = arg.substr(18); - uint64_t bytes = 0; - for (char digit : size) - { - if (digit < '0' || digit > '9' || bytes > 0x7fffffffu / 10) - throw InvocationError("invalid Wasm stack size"); - bytes = bytes * 10 + static_cast(digit - '0'); - } - if (bytes == 0 || bytes > 0x7fffffffu || bytes % 16 != 0) - throw InvocationError("Wasm stack size must be a positive multiple of 16 below 2 GiB"); - invocation.wasm_stack_size = static_cast(bytes); - } + invocation.wasm_stack_size = parse_wasm_stack_size(arg.substr(18)); else if (arg == "--sysroot" || starts_with(arg, "--sysroot=") || arg == "-resource-dir" || starts_with(arg, "-resource-dir=")) { diff --git a/dev/src/opt/dead_code.cpp b/dev/src/opt/dead_code.cpp index 5e7f0d20e..57c507dc4 100644 --- a/dev/src/opt/dead_code.cpp +++ b/dev/src/opt/dead_code.cpp @@ -80,6 +80,8 @@ bool remove_dead_code(FunctionContext& context) } if (unknown == 0) return false; + const bool mapped = context.block_of_version == context.version && + context.block_of_size == body.instructions.size(); bool changed = false; for (BlockId b : body.layout) { @@ -90,6 +92,8 @@ bool remove_dead_code(FunctionContext& context) if (live[i] != 1) { unlink_after(body, b, prev, i); + if (mapped) + context.block_of[i] = kNoId; ++context.stats.dead; changed = true; } diff --git a/dev/src/opt/function_ir.cpp b/dev/src/opt/function_ir.cpp index df696f116..8f33ea572 100644 --- a/dev/src/opt/function_ir.cpp +++ b/dev/src/opt/function_ir.cpp @@ -304,6 +304,9 @@ void build_edges(const Program& program, const FunctionBody& body, Cfg& cfg, boo void build_order(const FunctionBody& body, Cfg& cfg) { const uint32_t n = cfg.block_count; + cfg.dfs_index.assign(n, kNoId); + cfg.dfs_vertex.clear(); + cfg.dfs_parent.clear(); if (body.layout.empty()) return; // Iterative DFS: ordinary successors, then handler targets (the @@ -314,6 +317,9 @@ void build_order(const FunctionBody& body, Cfg& cfg) post.clear(); const BlockId entry = body.layout[0]; cfg.flags[entry] |= BF_REACHABLE; + cfg.dfs_index[entry] = 0; + cfg.dfs_vertex.push_back(entry); + cfg.dfs_parent.push_back(kNoId); stack.push_back(std::make_pair(entry, 0u)); while (!stack.empty()) { @@ -331,6 +337,9 @@ void build_order(const FunctionBody& body, Cfg& cfg) if ((cfg.flags[s] & BF_PLACED) != 0 && (cfg.flags[s] & BF_REACHABLE) == 0) { cfg.flags[s] |= BF_REACHABLE; + cfg.dfs_index[s] = static_cast(cfg.dfs_vertex.size()); + cfg.dfs_vertex.push_back(s); + cfg.dfs_parent.push_back(cfg.dfs_index[b]); next = s; } } @@ -426,36 +435,9 @@ void build_dominators(Cfg& cfg) // iterative intersection walk is quadratic on a long chain feeding one // merge): a depth-first preorder over both edge kinds, semidominators // by EVAL over the linked forest, then immediate dominators. - static std::vector number; - static std::vector vertex, parent; - static std::vector> stack; - number.assign(n, kNoId); - vertex.clear(); - parent.clear(); - stack.clear(); - number[entry] = 0; - vertex.push_back(entry); - parent.push_back(kNoId); - stack.push_back(std::make_pair(entry, 0u)); - while (!stack.empty()) - { - const BlockId b = stack.back().first; - const uint32_t k = stack.back().second++; - const uint32_t succs = cfg.succ_first[b + 1] - cfg.succ_first[b]; - const uint32_t total = succs + cfg.handler_first[b + 1] - cfg.handler_first[b]; - if (k >= total) - { - stack.pop_back(); - continue; - } - const BlockId s = k < succs ? cfg.succs[cfg.succ_first[b] + k] : cfg.handlers[cfg.handler_first[b] + k - succs]; - if (!cfg.reachable(s) || number[s] != kNoId) - continue; - number[s] = static_cast(vertex.size()); - vertex.push_back(s); - parent.push_back(number[b]); - stack.push_back(std::make_pair(s, 0u)); - } + const std::vector& number = cfg.dfs_index; + const std::vector& vertex = cfg.dfs_vertex; + const std::vector& parent = cfg.dfs_parent; const uint32_t count = static_cast(vertex.size()); static std::vector semi, label, ancestor, idom, bucket, next, chain; semi.assign(count, 0); diff --git a/dev/src/opt/function_ir.h b/dev/src/opt/function_ir.h index 1d06c49ee..45d04bac3 100644 --- a/dev/src/opt/function_ir.h +++ b/dev/src/opt/function_ir.h @@ -301,6 +301,9 @@ struct Cfg std::vector handler_first, handlers; std::vector flags; std::vector rpo; + // The same DFS supplies RPO and Lengauer-Tarjan preorder/parents. + std::vector dfs_index, dfs_parent; + std::vector dfs_vertex; std::vector rpo_index; // kNoId when unreachable std::vector idom; // kNoId for the entry and unreachable blocks std::vector dom_in, dom_out; diff --git a/dev/src/opt/jump_threading.cpp b/dev/src/opt/jump_threading.cpp index 8a3da473e..660bb82c5 100644 --- a/dev/src/opt/jump_threading.cpp +++ b/dev/src/opt/jump_threading.cpp @@ -734,6 +734,15 @@ void JumpThreading::find_use_dominators() use_dom_[v.index] = b; return; } + // Most additional uses are below the common dominator already + // found. The intervals answer that without climbing the tree again. + if (a == b || cfg_.dominates(a, b)) + return; + if (cfg_.dominates(b, a)) + { + use_dom_[v.index] = b; + return; + } while (a != b) { while (cfg_.rpo_index[a] > cfg_.rpo_index[b]) @@ -783,6 +792,8 @@ void JumpThreading::find_use_dominators() BlockId JumpThreading::successor_holding(BlockId m, TempId t) const { BlockId x = t < use_dom_.size() ? use_dom_[t] : kNoId; + if (x == kNoId || x == m || !cfg_.dominates(m, x)) + return kNoId; while (x != kNoId && x != m && cfg_.idom[x] != m) x = cfg_.idom[x]; return x == kNoId || x == m || cfg_.pred_count(x) != 1 ? kNoId : x; @@ -1305,7 +1316,11 @@ bool JumpThreading::known_compares() // comes between the phis and it is copied for a threaded // predecessor (at most kThreadCopy plain instructions). bool def_here = false; - for (InstId i = first; i != kNoId && i != last && !def_here; i = body_.instructions[i].next) + uint32_t examined = 0; + // Beyond the copy budget this block cannot be threaded, whether + // its compare is here or in another block. + for (InstId i = first; i != kNoId && i != last && !def_here && examined++ <= kThreadCopy; + i = body_.instructions[i].next) def_here = i == def; if (def_here) { @@ -1516,11 +1531,10 @@ bool JumpThreading::known_compares() for (const std::pair& r : redirects) if (bypass(r.first, s, r.second, cresult)) changed = true; - if (!redirects.empty() && changed) - { + if (changed) c_.invalidate_cfg(); - c_.ensure_cfg(); - } + // Demotion may split an edge even if every bypass is rejected. + c_.ensure_cfg(); } counted_ = false; return changed; @@ -2341,12 +2355,10 @@ bool JumpThreading::demote_phis(BlockId s, std::vectorhash >> 26); +} + // A 64-bit mixer (a multiplicative hash, its high half folded down): every // key bit reaches the low bits the tables index by, so names declared in // many scopes spread out. @@ -194,7 +200,9 @@ void NameLookup::reserve(uint32_t names) NameEntry* NameLookup::entry(const Scope* scope, const Identifier* name) { - scope->indexed_names = true; + const uint64_t bit = NameBit(name); + if ((scope->name_bits & bit) == 0) + scope->name_bits |= bit; if ((count_ + 1) * 2 > slots_.size()) grow(); const uint64_t key = key_of(scope, name); @@ -215,7 +223,7 @@ NameEntry* NameLookup::entry(const Scope* scope, const Identifier* name) const NameEntry* NameLookup::find(const Scope* scope, const Identifier* name) const { - if (!scope->indexed_names) + if ((scope->name_bits & NameBit(name)) == 0) return nullptr; const uint64_t key = key_of(scope, name); const uint64_t mask = slot_mask_; diff --git a/dev/src/sema/semantic_graph.h b/dev/src/sema/semantic_graph.h index 18c5b19f6..e66367d75 100644 --- a/dev/src/sema/semantic_graph.h +++ b/dev/src/sema/semantic_graph.h @@ -157,10 +157,6 @@ struct Scope // its concrete class, including bases dependent in the original // template (an explicit member specialization, 14.7.3p16). bool concrete_members : 1; - // Monotonic membership hint for the name index. Setting it through a - // const scope records an index entry, independently of name visibility - // and the printed bindings list (which can omit indexed declarations). - mutable bool indexed_names : 1; // A frozen prefix of a default argument's function parameter clause. // Lookup sees these bindings; declarations (including closures) belong // to the surrounding declaration scope. @@ -173,6 +169,12 @@ struct Scope // scopes already count). uint8_t lists; uint32_t id; + // Monotonic membership hint for the name index: one bit per name hash + // (see NameLookup::entry) of the names indexed here, so a clear bit + // answers a search without probing the index. Setting it through a + // const scope records an index entry, independently of name visibility + // and the printed bindings list (which can omit indexed declarations). + mutable uint64_t name_bits; // Where unqualified lookup continues: the lexical parent, or for an // out-of-class definition the scope of its class or namespace. Scope* parent; diff --git a/dev/src/syntax/name_scopes.cpp b/dev/src/syntax/name_scopes.cpp index 8bd38b97c..db880cfb7 100644 --- a/dev/src/syntax/name_scopes.cpp +++ b/dev/src/syntax/name_scopes.cpp @@ -10,6 +10,12 @@ namespace { const uint64_t kEmptyKey = ~0ull; +// The bit of Scope::name_bits a name sets: six bits of its spelling's hash. +uint64_t NameBit(const Identifier* name) +{ + return uint64_t(1) << (name->hash >> 26); +} + // Orders NameScopes::pending_ as a max-heap by the depth of `at`. bool Shallower(const ScopeEdge* a, const ScopeEdge* b) { @@ -134,6 +140,7 @@ Scope* NameScopes::push(ScopeKind kind, const Identifier* name) scope->fixed_bases = 0; scope->id = next_scope_id_++; scope->specialization_visit = 0; + scope->name_bits = 0; scope->parent = current_; scope->depth = current_ != nullptr ? current_->depth + 1 : 0; scope->name = name; @@ -185,6 +192,7 @@ void NameScopes::declare(Scope* scope, const Identifier* name, NameBinding bindi marks_[name->id] |= kNamespaceTemplateValue; if (member) touch_name(name->id); + scope->name_bits |= NameBit(name); const uint64_t key = key_of(scope, name); uint32_t index = find_slot(key); if (slots_[index].key == kEmptyKey) @@ -553,6 +561,8 @@ void NameScopes::reattach(const std::vector& changes, size_t begin, size NameBinding NameScopes::own(Scope* scope, const Identifier* name) const { + if ((scope->name_bits & NameBit(name)) == 0) + return NameBinding{ NameCategory::None, false, nullptr }; const Slot& slot = slots_[find_slot(key_of(scope, name))]; if (slot.key == kEmptyKey) return NameBinding{ NameCategory::None, false, nullptr }; diff --git a/dev/src/syntax/name_scopes.h b/dev/src/syntax/name_scopes.h index c86002dd3..4e2022191 100644 --- a/dev/src/syntax/name_scopes.h +++ b/dev/src/syntax/name_scopes.h @@ -88,6 +88,9 @@ struct Scope uint32_t id; // A second visit is needed when a lookup first missed without dependent bases. uint32_t specialization_visit; + // One bit per name hash of the names declared here (see + // NameScopes::declare): a clear bit answers a search without the table. + uint64_t name_bits; Scope* parent; const Identifier* name; // Namespace: nominated namespaces (using-directives, inline and unnamed diff --git a/docs/performance/simdjson-compile-20261116.md b/docs/performance/simdjson-compile-20261116.md new file mode 100644 index 000000000..0429faa66 --- /dev/null +++ b/docs/performance/simdjson-compile-20261116.md @@ -0,0 +1,183 @@ +# simdjson compile-time investigation, 2026-11-16 + +The smaller lead over Clang comes mainly from the optimizer, rather than +preprocessing or semantic analysis. Clang also performs well relative to GCC +on this workload. cppgm's frontend advantage is larger than its advantage +once optimized kernel generation is included. + +## Dedicated Intel observations + +The retained v0.9.2 measurement is commit +`2a915cfbfed25b5f95be7b7e5c345dfe87f11666`, Intel Xeon Platinum 8581C, +GCC 15.2 and Clang 21.1.8. These are one-object, single-process compilations +of unmodified simdjson 5.1.1, with the same source and options described in +[the benchmark guide](../../benchmarks/simdjson/README.md). Linking is excluded. + +| Backend | cppgm CPU | Clang CPU | GCC CPU | Paired Clang / cppgm | +|---|---:|---:|---:|---:| +| Scalar | 1.59 s | 2.48 s | 5.34 s | 1.568x | +| SSE | 1.78 s | 3.09 s | 6.385 s | 1.738x | + +CPU values are medians of retained AB observations; the final column is the +original median paired-block ratio, not a ratio of independently rounded +medians. A/A checks showed no calibration variation above 2%. +[CI run and raw artifacts](https://github.com/vishvananda/cppgm/actions/runs/43794025927). + +## Where the advantage goes + +Local diagnostic measurements use the exact v0.9.2 source, built by GCC 15.2 +at O3 with debug symbols, no LTO/PGO, and the same Clang 21.1.8 version. +The host is Xeon E5-2696 v4; its timings are not replacements for the dedicated +Intel measurements. Both compilers use GCC 15's installed C++ headers. +Three local observations per cell give these median CPU times: + +| Backend | cppgm syntax only | Clang syntax only | cppgm O0 | Clang O0 | cppgm O1 | cppgm O3 | Clang O3 | +|---|---:|---:|---:|---:|---:|---:|---:| +| Scalar | 0.29 s | 1.28 s | 0.34 s | 1.52 s | 2.36 s | 2.46 s | 4.89 s | +| SSE | 0.47 s | 2.04 s | 0.54 s | 2.48 s | 2.85 s | 2.71 s | 5.38 s | + +O1 already incurs most of cppgm's optimizer cost; the problem is not confined +to O3-specific loop passes. The small SSE O1/O3 reversal is local timing +variation, not evidence that more optimization is intrinsically cheaper. + +Separate three-repeat hardware instruction counts make the change in work +clearer, without relying on clock frequency: + +| Backend | cppgm O0 | Clang O0 | cppgm O3 | Clang O3 | +|---|---:|---:|---:|---:| +| Scalar | 1.313 billion | 3.910 billion | 9.397 billion | 14.025 billion | +| SSE | 1.915 billion | 5.692 billion | 10.580 billion | 18.024 billion | + +The roughly 3x O0 instruction advantage becomes 1.49x / 1.70x at O3, +close to the dedicated Intel compile ratios. This is not just wall-time noise. +The O3-minus-O0 differences include changes to lowering and code generation; +they are not isolated optimizer timers. + +Cycle-sampling profiles put about 80% of scalar cppgm compilation under +optimization. The frontend is about 12–18% in separate `--stats` runs; +instruction selection is about 120–140 ms and encoding about 7 ms locally. +Clang's time trace also shows substantial optimization and machine-code work. +The final output is only a few dozen functions: cppgm is not simply emitting +thousands of unwanted out-of-line helpers. + +Temporary pass instrumentation isolates the repeated work: + +| Backend | Local function-pipeline visits | Scalar-round invocations | CFG builds | Dominator builds | Jump-threading invocations | +|---|---:|---:|---:|---:|---:| +| Scalar | 683 | 2,790 | 8,032 | 4,245 | 1,145 | +| SSE | 853 | 3,471 | 8,383 | 4,435 | 1,197 | + +These include helpers subsequently inlined or pruned; they are not counts of +final machine functions. The large stage-two parser bodies and their inlined +copies account for much of the work. Inlining invokes local simplification, +and jump threading repeatedly reconstructs graph and dominance facts as it +changes edges. In the scalar instrumented run, jump threading takes about +787 ms, value simplification 354 ms and memory forwarding 329 ms. These timers +include nested work and must not be added to CFG/dominator times again. + +## Retained changes + +The implementation is based on v0.9.4 (`4b05c87802afb837551466590e3eb75c8099ec82`). +Its optimizer differs from the profiled version only by an aggregate-slot +change, so measurements compare immutable v0.9.4 baseline/candidate images. + +- Constant propagation retains a current instruction-to-block map because it + replaces operands without moving instructions. Dead-code removal updates + the entries it unlinks, allowing the next pass to reuse that map too. + `--verify-passes` checks retained analysis after these changed passes. +- Jump threading stops looking for a compare after its existing copy budget + makes the block ineligible. Dominator intervals answer ancestor cases + before a nearest-common-dominator walk, and reject a use outside a candidate + successor's dominance region before walking the tree. +- The driver's Wasm stack-size parser is extracted from argument dispatch. + This reduces `parse` from 243 to 231 code lines, preserving diagnostics and + the 240-line audit limit. + +The initial micro-optimizations reduce instructions by 0.125% for scalar, +0.113% for SSE and 0.104% for the frozen O3 compiler workload. Frozen O0 is +unchanged to within 0.006%. These are small reductions in compiler work; local +wall/CPU timing variation does not establish a material elapsed-time gain. +They do not turn the simdjson comparison into a much larger speedup. + +A broader EH-block cache was rejected: its extra bookkeeping increased scalar +instructions about 0.38%. A narrower redundant-CFG-rebuild prototype also +showed no useful instruction reduction. Neither is in the retained patch. +Larger gains require reducing repeated whole-function optimizer analysis +without losing useful transformations or changing their decisions. + +## CFG and dominator follow-up + +The next investigation uses the initial patch (`989675743`) as its baseline. +Call-chain instrumentation attributes 79.3% / 77.8% of dominator-building time +to jump threading, scalar / SSE. In particular, phi demotion splits edges and +rebuilds the graph, then its caller redirects those edges and rebuilds again. +No CFG facts are read between those two builds. This accounts for 525 / 417 +full rebuilds and 527,640 / 418,662 reachable-block dominator visits. + +Two further changes preserve the same transformation sequence: + +- Phi demotion invalidates after splitting edges; its caller rebuilds after + redirecting them. The caller still rebuilds when edges were split but all + attempted bypasses are rejected. The other caller immediately returns to + cleanup, which also rebuilds before reading graph facts. +- CFG ordering records DFS preorder and parent links in the graph itself. + Lengauer-Tarjan reuses that traversal instead of repeating it. Ordinary + successors and handler edges retain their order; unreachable-block removal + preserves the reachable DFS tree. + +Compared with the initial patch, the combined change gives: + +| Backend | Instructions | Cycles | Paired wall estimate | +|---|---:|---:|---:| +| Scalar O3 | -5.19% | -4.26% | -4.03% | +| SSE O3 | -3.79% | -3.41% | -3.92% | + +Counters use three repeats; wall times use six alternating ABBA/BAAB blocks, +twelve observations per compiler, with A/A checks before and after. No samples +were discarded. A/A changes reach about 4% for scalar and 21% for SSE, including +a four-second scheduling outlier. The wall estimates are consistent with less +compiler work, but their exact size is not established on this active host. +The frozen O3 workload improves only 0.38% in instructions: it exercises the +redundant jump-threading rebuild much less heavily. + +An alternative bounded iterative dominator solver before the existing +Lengauer-Tarjan fallback was rejected. It added work on simdjson, reducing +the deferral-only savings from 4.17% / 2.95% to 1.00% / 0.43%. The existing +large-graph algorithm remains. + +Further gains would require selective updates after real edge changes, or +less full-function processing around those transformations. This needs care: +redirects can change reachability, loop entry and downstream dominance, and +optimizer decisions also depend on traversal order. Simply batching candidates +against stale graph facts or choosing another valid RPO can change output. +The earlier 18–21% profile category includes block maps and use counting; it +is not all removable CFG work. + +## Validation and evidence + +Scalar, SSE and the frozen workload match the baseline object bytes at O0, +O1, O2 and O3. Twelve Wasm stack-size command-line probes match exit status, +stdout and stderr. The final rebuilt candidate's SHA256 matches the immutable +image used in the retained measurements. + +All 467 compiler objects match byte for byte in PA36's full source identity +check. The strict course report passes all 11,314 tests with the pinned Wasm tools +on PATH. +Debug-info tests, PA36 correctness smoke, self-host through PA5 and inception +all pass. Architecture audits, the file audit and formatting with CI's pinned +Clang-format 21.1.8 pass; the file audit retains seven pre-existing header-body +warnings. The final audit uses the same formatter version as CI. + +Raw commands, compiler images, profiles, pass counts, byte comparisons and +counter observations are retained locally under +`/mnt/vizier/cppgm-simdjson-compile-analysis-20261116/`. The retained measurements +are in `prototype-dominance/`; `rejected-eh-cache/` contains the rejected +experiment. `validation-progress.log` records the broader checks. No raw build +artifacts or benchmark input changes are committed with the implementation. + +The CFG follow-up's raw profiles, immutable compiler images, rejected prototype, +object comparisons and paired wall measurements are under +`/mnt/vizier/cppgm-cfg-analysis-20261116/`. Its graph check compares dominance +against independent vertex-removal reachability on 1,000 random graphs, +including handler edges and unreachable blocks, while reusing graph storage. +A 20,000-block chain checks the deep iterative traversal. All pass.