aboutsummaryrefslogtreecommitdiff
path: root/src/Zcu/PerThread.zig
diff options
context:
space:
mode:
authormlugg <mlugg@mlugg.co.uk>2025-07-10 09:18:10 +0100
committerMatthew Lugg <mlugg@mlugg.co.uk>2025-08-01 23:48:21 +0100
commitdcc3e6e1dd224f1719b0ad9ef6d8d9dc0ed497ec (patch)
tree470bd1fc20bdbeb6e4212bd4cbbd694401d757e7 /src/Zcu/PerThread.zig
parenta00edbd52d03645366c165e860d9e0ab89caa2fc (diff)
downloadzig-dcc3e6e1dd224f1719b0ad9ef6d8d9dc0ed497ec.tar.gz
zig-dcc3e6e1dd224f1719b0ad9ef6d8d9dc0ed497ec.zip
build system: replace fuzzing UI with build UI, add time report
This commit replaces the "fuzzer" UI, previously accessed with the `--fuzz` and `--port` flags, with a more interesting web UI which allows more interactions with the Zig build system. Most notably, it allows accessing the data emitted by a new "time report" system, which allows users to see which parts of Zig programs take the longest to compile. The option to expose the web UI is `--webui`. By default, it will listen on `[::1]` on a random port, but any IPv6 or IPv4 address can be specified with e.g. `--webui=[::1]:8000` or `--webui=127.0.0.1:8000`. The options `--fuzz` and `--time-report` both imply `--webui` if not given. Currently, `--webui` is incompatible with `--watch`; specifying both will cause `zig build` to exit with a fatal error. When the web UI is enabled, the build runner spawns the web server as soon as the configure phase completes. The frontend code consists of one HTML file, one JavaScript file, two CSS files, and a few Zig source files which are built into a WASM blob on-demand -- this is all very similar to the old fuzzer UI. Also inherited from the fuzzer UI is that the build system communicates with web clients over a WebSocket connection. When the build finishes, if `--webui` was passed (i.e. if the web server is running), the build runner does not terminate; it continues running to serve web requests, allowing interactive control of the build system. In the web interface is an overall "status" indicating whether a build is currently running, and also a list of all steps in this build. There are visual indicators (colors and spinners) for in-progress, succeeded, and failed steps. There is a "Rebuild" button which will cause the build system to reset the state of every step (note that this does not affect caching) and evaluate the step graph again. If `--time-report` is passed to `zig build`, a new section of the interface becomes visible, which associates every build step with a "time report". For most steps, this is just a simple "time taken" value. However, for `Compile` steps, the compiler communicates with the build system to provide it with much more interesting information: time taken for various pipeline phases, with a per-declaration and per-file breakdown, sorted by slowest declarations/files first. This feature is still in its early stages: the data can be a little tricky to understand, and there is no way to, for instance, sort by different properties, or filter to certain files. However, it has already given us some interesting statistics, and can be useful for spotting, for instance, particularly complex and slow compile-time logic. Additionally, if a compilation uses LLVM, its time report includes the "LLVM pass timing" information, which was previously accessible with the (now removed) `-ftime-report` compiler flag. To make time reports more useful, ZIR and compilation caches are ignored by the Zig compiler when they are enabled -- in other words, `Compile` steps *always* run, even if their result should be cached. This means that the flag can be used to analyze a project's compile time without having to repeatedly clear cache directory, for instance. However, when using `-fincremental`, updates other than the first will only show you the statistics for what changed on that particular update. Notably, this gives us a fairly nice way to see exactly which declarations were re-analyzed by an incremental update. If `--fuzz` is passed to `zig build`, another section of the web interface becomes visible, this time exposing the fuzzer. This is quite similar to the fuzzer UI this commit replaces, with only a few cosmetic tweaks. The interface is closer than before to supporting multiple fuzz steps at a time (in line with the overall strategy for this build UI, the goal will be for all of the fuzz steps to be accessible in the same interface), but still doesn't actually support it. The fuzzer UI looks quite different under the hood: as a result, various bugs are fixed, although other bugs remain. For instance, viewing the source code of any file other than the root of the main module is completely broken (as on master) due to some bogus file-to-module assignment logic in the fuzzer UI. Implementation notes: * The `lib/build-web/` directory holds the client side of the web UI. * The general server logic is in `std.Build.WebServer`. * Fuzzing-specific logic is in `std.Build.Fuzz`. * `std.Build.abi` is the new home of `std.Build.Fuzz.abi`, since it now relates to the build system web UI in general. * The build runner now has an **actual** general-purpose allocator, because thanks to `--watch` and `--webui`, the process can be arbitrarily long-lived. The gpa is `std.heap.DebugAllocator`, but the arena remains backed by `std.heap.page_allocator` for efficiency. I fixed several crashes caused by conflation of `gpa` and `arena` in the build runner and `std.Build`, but there may still be some I have missed. * The I/O logic in `std.Build.WebServer` is pretty gnarly; there are a *lot* of threads involved. I anticipate this situation improving significantly once the `std.Io` interface (with concurrency support) is introduced.
Diffstat (limited to 'src/Zcu/PerThread.zig')
-rw-r--r--src/Zcu/PerThread.zig78
1 files changed, 69 insertions, 9 deletions
diff --git a/src/Zcu/PerThread.zig b/src/Zcu/PerThread.zig
index 119b742a89..de4be438f5 100644
--- a/src/Zcu/PerThread.zig
+++ b/src/Zcu/PerThread.zig
@@ -215,12 +215,15 @@ pub fn updateFile(
};
defer cache_file.close();
+ // Under `--time-report`, ignore cache hits; do the work anyway for those juicy numbers.
+ const ignore_hit = comp.time_report != null;
+
const need_update = while (true) {
const result = switch (file.getMode()) {
inline else => |mode| try loadZirZoirCache(zcu, cache_file, stat, file, mode),
};
switch (result) {
- .success => {
+ .success => if (!ignore_hit) {
log.debug("AstGen cached success: {f}", .{file.path.fmt(comp)});
break false;
},
@@ -260,9 +263,16 @@ pub fn updateFile(
file.source = source;
+ var timer = comp.startTimer();
// Any potential AST errors are converted to ZIR errors when we run AstGen/ZonGen.
file.tree = try Ast.parse(gpa, source, file.getMode());
+ if (timer.finish()) |ns_parse| {
+ comp.mutex.lock();
+ defer comp.mutex.unlock();
+ comp.time_report.?.stats.cpu_ns_parse += ns_parse;
+ }
+ timer = comp.startTimer();
switch (file.getMode()) {
.zig => {
file.zir = try AstGen.generate(gpa, file.tree.?);
@@ -282,6 +292,11 @@ pub fn updateFile(
};
},
}
+ if (timer.finish()) |ns_astgen| {
+ comp.mutex.lock();
+ defer comp.mutex.unlock();
+ comp.time_report.?.stats.cpu_ns_astgen += ns_astgen;
+ }
log.debug("AstGen fresh success: {f}", .{file.path.fmt(comp)});
}
@@ -801,8 +816,11 @@ pub fn ensureComptimeUnitUpToDate(pt: Zcu.PerThread, cu_id: InternPool.ComptimeU
info.deps.clearRetainingCapacity();
}
- const unit_prog_node = zcu.startSemaProgNode("comptime");
- defer unit_prog_node.end(zcu);
+ const unit_tracking = zcu.trackUnitSema(
+ "comptime",
+ zcu.intern_pool.getComptimeUnit(cu_id).zir_index,
+ );
+ defer unit_tracking.end(zcu);
return pt.analyzeComptimeUnit(cu_id) catch |err| switch (err) {
error.AnalysisFail => {
@@ -981,8 +999,8 @@ pub fn ensureNavValUpToDate(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zcu
info.deps.clearRetainingCapacity();
}
- const unit_prog_node = zcu.startSemaProgNode(nav.fqn.toSlice(ip));
- defer unit_prog_node.end(zcu);
+ const unit_tracking = zcu.trackUnitSema(nav.fqn.toSlice(ip), nav.srcInst(ip));
+ defer unit_tracking.end(zcu);
const invalidate_value: bool, const new_failed: bool = if (pt.analyzeNavVal(nav_id)) |result| res: {
break :res .{
@@ -1381,8 +1399,8 @@ pub fn ensureNavTypeUpToDate(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zc
info.deps.clearRetainingCapacity();
}
- const unit_prog_node = zcu.startSemaProgNode(nav.fqn.toSlice(ip));
- defer unit_prog_node.end(zcu);
+ const unit_tracking = zcu.trackUnitSema(nav.fqn.toSlice(ip), nav.srcInst(ip));
+ defer unit_tracking.end(zcu);
const invalidate_type: bool, const new_failed: bool = if (pt.analyzeNavType(nav_id)) |result| res: {
break :res .{
@@ -1601,8 +1619,12 @@ pub fn ensureFuncBodyUpToDate(pt: Zcu.PerThread, maybe_coerced_func_index: Inter
info.deps.clearRetainingCapacity();
}
- const func_prog_node = zcu.startSemaProgNode(ip.getNav(func.owner_nav).fqn.toSlice(ip));
- defer func_prog_node.end(zcu);
+ const owner_nav = ip.getNav(func.owner_nav);
+ const unit_tracking = zcu.trackUnitSema(
+ owner_nav.fqn.toSlice(ip),
+ owner_nav.srcInst(ip),
+ );
+ defer unit_tracking.end(zcu);
const ies_outdated, const new_failed = if (pt.analyzeFuncBody(func_index)) |result|
.{ prev_failed or result.ies_outdated, false }
@@ -1847,6 +1869,10 @@ fn semaFile(pt: Zcu.PerThread, file_index: Zcu.File.Index) Zcu.SemaError!void {
});
const struct_ty = try pt.createFileRootStruct(file_index, new_namespace_index, false);
errdefer zcu.intern_pool.remove(pt.tid, struct_ty);
+
+ if (zcu.comp.time_report) |*tr| {
+ tr.stats.n_imported_files += 1;
+ }
}
/// Called by AstGen worker threads when an import is seen. If `new_file` is returned, the caller is
@@ -2520,6 +2546,12 @@ pub fn scanNamespace(
const gpa = zcu.gpa;
const namespace = zcu.namespacePtr(namespace_index);
+ const tracked_unit = zcu.trackUnitSema(
+ Type.fromInterned(namespace.owner_type).containerTypeName(ip).toSlice(ip),
+ null,
+ );
+ defer tracked_unit.end(zcu);
+
// For incremental updates, `scanDecl` wants to look up existing decls by their ZIR index rather
// than their name. We'll build an efficient mapping now, then discard the current `decls`.
// We map to the `AnalUnit`, since not every declaration has a `Nav`.
@@ -2755,6 +2787,12 @@ fn analyzeFnBodyInner(pt: Zcu.PerThread, func_index: InternPool.Index) Zcu.SemaE
func.setResolvedErrorSet(ip, .none);
}
+ if (zcu.comp.time_report) |*tr| {
+ if (func.generic_owner != .none) {
+ tr.stats.n_generic_instances += 1;
+ }
+ }
+
// This is the `Nau` corresponding to the `declaration` instruction which the function or its generic owner originates from.
const decl_nav = ip.getNav(if (func.generic_owner == .none)
func.owner_nav
@@ -4307,6 +4345,9 @@ pub fn addDependency(pt: Zcu.PerThread, unit: AnalUnit, dependee: InternPool.Dep
/// codegen thread, depending on whether the backend supports `Zcu.Feature.separate_thread`.
pub fn runCodegen(pt: Zcu.PerThread, func_index: InternPool.Index, air: *Air, out: *@import("../link.zig").ZcuTask.LinkFunc.SharedMir) void {
const zcu = pt.zcu;
+
+ var timer = zcu.comp.startTimer();
+
const success: bool = if (runCodegenInner(pt, func_index, air)) |mir| success: {
out.value = mir;
break :success true;
@@ -4327,6 +4368,25 @@ pub fn runCodegen(pt: Zcu.PerThread, func_index: InternPool.Index, air: *Air, ou
}
break :success false;
};
+
+ if (timer.finish()) |ns_codegen| report_time: {
+ const ip = &zcu.intern_pool;
+ const nav = ip.indexToKey(func_index).func.owner_nav;
+ const zir_decl = ip.getNav(nav).srcInst(ip);
+ zcu.comp.mutex.lock();
+ defer zcu.comp.mutex.unlock();
+ const tr = &zcu.comp.time_report.?;
+ tr.stats.cpu_ns_codegen += ns_codegen;
+ const gop = tr.decl_codegen_ns.getOrPut(zcu.gpa, zir_decl) catch |err| switch (err) {
+ error.OutOfMemory => {
+ zcu.comp.setAllocFailure();
+ break :report_time;
+ },
+ };
+ if (!gop.found_existing) gop.value_ptr.* = 0;
+ gop.value_ptr.* += ns_codegen;
+ }
+
// release `out.value` with this store; synchronizes with acquire loads in `link`
out.status.store(if (success) .ready else .failed, .release);
zcu.comp.link_task_queue.mirReady(zcu.comp, func_index, out);