From dacaf41c33f4aef5ec8c57421b6e509f3419cf4b Mon Sep 17 00:00:00 2001 From: Hugo Date: Thu, 12 Nov 2026 06:56:20 +0100 Subject: [PATCH 01/16] build(deps): pin coretrace-compiler to its per-compilation working directory The pinned commit, from CoreTrace/coretrace-compiler#262, gives each compilation a file system of its own, whose working directory -working-directory moves while the process's stays. The analyzer does not use it yet: it still moves the process around each compilation, under its lock. Refs #271 --- cmake/compiler/coretrace-compiler.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/compiler/coretrace-compiler.cmake b/cmake/compiler/coretrace-compiler.cmake index fb853b9f..70a3bbb0 100644 --- a/cmake/compiler/coretrace-compiler.cmake +++ b/cmake/compiler/coretrace-compiler.cmake @@ -13,7 +13,7 @@ endif() FetchContent_Declare( cc GIT_REPOSITORY https://github.com/CoreTrace/coretrace-compiler.git - GIT_TAG b4ad33638e9020a93f052a7a299e4105bd48f975 # v0.10.0 + GIT_TAG b05bd18b35f5c4c42f3d9b245aecd2c464ccb52b # CoreTrace/coretrace-compiler#262 ) FetchContent_MakeAvailable(cc) From f56e9792ee1011590c8df14ce3df2bd97165dc12 Mon Sep 17 00:00:00 2001 From: Hugo Date: Thu, 12 Nov 2026 06:56:20 +0100 Subject: [PATCH 02/16] perf(input): compile sources in parallel, each in its directory Every compilation held one global lock and moved the whole process to its compile command's directory: the --jobs threads compiled one source at a time. coretrace-compiler now gives each compilation the directory of its -working-directory without moving the process: the analyzer passes the directory that way, and compilations share the lock. Some compilations still hold it alone, since they change state that the whole process shares: those with an option that Clang applies to LLVM's state (-mllvm, -mdebug-pass, -mlimit-float-precision, -ftime-report), and those with -fno-integrated-cc1, whose jobs run as programs, for which coretrace-compiler moves the process. A compile command whose directory does not exist still fails the analysis: coretrace-compiler reports a directory it cannot enter, but compiles to memory all the same, so the analyzer checks the directory itself, with the message it gave before. Refs #271 --- src/analysis/InputPipeline.cpp | 114 +++++++++++++++------------------ 1 file changed, 52 insertions(+), 62 deletions(-) diff --git a/src/analysis/InputPipeline.cpp b/src/analysis/InputPipeline.cpp index 0828f54e..a723665f 100644 --- a/src/analysis/InputPipeline.cpp +++ b/src/analysis/InputPipeline.cpp @@ -14,7 +14,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -40,15 +42,29 @@ namespace ctrace::stack::analysis { namespace { - // compilerlib drives an in-process clang CompilerInstance. clang/LLVM keep global - // mutable state (target registry, cl options, timers); two worker threads compiling - // at once hung intermittently on the first compile of a run. Compilation is - // serialised here; module analysis stays parallel, and the IR cache makes the - // compile step cheap on repeated runs. A compile that needs its compile command's - // directory changes the working directory of the whole process: it holds the same - // lock from before that change until it is undone, so no other compile runs in a - // directory that is not its own, and two changes never interleave. - std::mutex gCompileInvokeMutex; + // coretrace-compiler compiles from several threads at once, each compilation in the + // directory of its -working-directory, without moving the process: compilations share + // this lock. Some change state that the whole process shares, and hold it alone: those + // with an option that Clang applies to LLVM's state, and those with -fno-integrated-cc1, + // whose jobs run as programs, for which coretrace-compiler moves the process to the + // directory. + std::shared_mutex gCompileInvokeMutex; + + bool compilesAlone(const std::vector& args) + { + static constexpr std::string_view kOptionsOfLLVMState[] = { + "-mllvm", "-mdebug-pass", "-mlimit-float-precision", "-ftime-report"}; + return std::any_of(args.begin(), args.end(), + [](const std::string& arg) + { + for (std::string_view option : kOptionsOfLLVMState) + { + if (std::string_view(arg).starts_with(option)) + return true; + } + return arg == "-fno-integrated-cc1"; + }); + } void appendIfMissing(std::vector& args, const std::string& flag) { @@ -745,43 +761,6 @@ namespace ctrace::stack::analysis return true; } - class ScopedCurrentPath - { - public: - explicit ScopedCurrentPath(const std::string& path, std::string& error) - { - if (path.empty()) - return; - std::error_code ec; - previousPath_ = std::filesystem::current_path(ec); - if (ec) - { - error = "Failed to read current working directory"; - return; - } - std::filesystem::current_path(path, ec); - if (ec) - { - error = "Failed to change working directory to: " + path; - return; - } - active_ = true; - } - - ~ScopedCurrentPath() - { - if (!active_) - return; - std::error_code ec; - std::filesystem::current_path(previousPath_, ec); - } - - private: - std::filesystem::path previousPath_; - std::uint64_t active_ : 1 = false; - std::uint64_t reservedFlags_ : 63 = 0; - }; - class ScopedFileCleanup { public: @@ -859,9 +838,7 @@ namespace ctrace::stack::analysis using ctrace::stack::analyzer::ScopedHotspot; ModuleLoadResult result; const ScopedHotspot totalHotspot(config.timing, "input.load_module.total"); - // A relative input resolves from the directory the analysis started in, not from the - // current one: another thread may be compiling from its compile command's directory, - // which the whole process shares meanwhile. + // A relative input resolves from the directory the analysis started in. std::error_code cwdErr; const std::filesystem::path baseDir = config.inputBaseDir.empty() ? std::filesystem::current_path(cwdErr) @@ -923,22 +900,35 @@ namespace ctrace::stack::analysis [&](const std::vector& compileArgs, compilerlib::OutputMode outputMode) -> std::optional { - std::lock_guard compileLock(gCompileInvokeMutex); - if (workingDir.empty()) + std::vector argsInWorkingDir; + argsInWorkingDir.reserve(compileArgs.size() + 2); + if (!workingDir.empty()) { - const ScopedHotspot hotspot(config.timing, "input.compiler.invoke"); - return compilerlib::compile(compileArgs, outputMode); + // coretrace-compiler reports a directory it cannot enter, yet compiles to + // memory all the same: the compilation fails here instead. + std::error_code directoryError; + if (!std::filesystem::is_directory(workingDir, directoryError)) + { + result.error = + "Failed to change working directory to: " + workingDir + "\n"; + return std::nullopt; + } + argsInWorkingDir.push_back("-working-directory"); + argsInWorkingDir.push_back(workingDir); } + argsInWorkingDir.insert(argsInWorkingDir.end(), compileArgs.begin(), + compileArgs.end()); - std::string cwdError; - ScopedCurrentPath cwdGuard(workingDir, cwdError); - if (!cwdError.empty()) - { - result.error = cwdError + "\n"; - return std::nullopt; - } - const ScopedHotspot hotspot(config.timing, "input.compiler.invoke.cwd"); - return compilerlib::compile(compileArgs, outputMode); + std::shared_lock shared(gCompileInvokeMutex, std::defer_lock); + std::unique_lock alone(gCompileInvokeMutex, std::defer_lock); + if (compilesAlone(compileArgs)) + alone.lock(); + else + shared.lock(); + const ScopedHotspot hotspot(config.timing, workingDir.empty() + ? "input.compiler.invoke" + : "input.compiler.invoke.cwd"); + return compilerlib::compile(argsInWorkingDir, outputMode); }; if (cachePaths.enabled) From dd3ba4157309e81dc38c0242cfc601f2268a43b8 Mon Sep 17 00:00:00 2001 From: Hugo Date: Thu, 12 Nov 2026 06:56:20 +0100 Subject: [PATCH 03/16] docs(readme): say that --jobs compiles the sources in parallel Refs #271 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 420cbbdc..236ed64d 100644 --- a/README.md +++ b/README.md @@ -295,7 +295,7 @@ To generate `compile_commands.json` with CMake, configure with If analysis feels slow, `--compdb-fast` disables heavy flags (optimizations, sanitizers, profiling) while keeping include paths and macros. -For multi-file runs, `--jobs=` parallelizes input loading; with cross-TU enabled it also parallelizes summary construction. +For multi-file runs, `--jobs=` parallelizes input loading, compilations included; with cross-TU enabled it also parallelizes summary construction. `--compile-ir-cache-dir=` reuses compiled LLVM IR for unchanged translation units based on source/dependency stamps, which reduces repeated C/C++ frontend cost across runs. IR that another compiler produced (another coretrace-compiler revision or LLVM version) is compiled again. From d6420395fc47013b9106841edf49e0e181b28fd3 Mon Sep 17 00:00:00 2001 From: Hugo Date: Thu, 12 Nov 2026 06:56:20 +0100 Subject: [PATCH 04/16] docs(changelog): announce that sources compile in parallel Refs #271 --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2ad54ff..fe38468c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,12 @@ Notable changes are grouped by release. See [all releases](https://github.com/Co - Added an authors file and linked the repository documents from the README. - SARIF rules carry a title (`shortDescription`) and a description (`fullDescription`) instead of their id, and `describeRule` (`RuleCatalog.hpp`) gives them to programs linking the analyzer. +- With `--jobs` above 1, sources compile in parallel. Each compilation runs in its compile + command's directory through coretrace-compiler's `-working-directory`, instead of moving the + whole process there under a lock that let one source compile at a time. Compilations that pass + `-mllvm`, `-mdebug-pass`, `-mlimit-float-precision`, `-ftime-report` or `-fno-integrated-cc1` + still run one at a time. coretrace-compiler is pinned to a commit of + CoreTrace/coretrace-compiler#262, which gives each compilation a working directory of its own. ## v0.22.0 From e6ae53edbc1d1f92303fc47f4ba83de6de87f347 Mon Sep 17 00:00:00 2001 From: Hugo Date: Thu, 12 Nov 2026 07:14:36 +0100 Subject: [PATCH 05/16] build(deps): pin coretrace-compiler to its fix of the files -MJ writes The newer commit of CoreTrace/coretrace-compiler#262 also writes the fragment of -MJ, the statistics of -save-stats, the graph of -dependency-dot and the module cache in the directory of -working-directory, as the analyzer did when it moved the process there. Refs #271 --- cmake/compiler/coretrace-compiler.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/compiler/coretrace-compiler.cmake b/cmake/compiler/coretrace-compiler.cmake index 70a3bbb0..706a1b56 100644 --- a/cmake/compiler/coretrace-compiler.cmake +++ b/cmake/compiler/coretrace-compiler.cmake @@ -13,7 +13,7 @@ endif() FetchContent_Declare( cc GIT_REPOSITORY https://github.com/CoreTrace/coretrace-compiler.git - GIT_TAG b05bd18b35f5c4c42f3d9b245aecd2c464ccb52b # CoreTrace/coretrace-compiler#262 + GIT_TAG 8a99cf3d7be21dd6e15c1cc8f9523c685fd307ef # CoreTrace/coretrace-compiler#262 ) FetchContent_MakeAvailable(cc) From 18d032f59a144f40e343125822068ef878644bbf Mon Sep 17 00:00:00 2001 From: Hugo Date: Mon, 16 Nov 2026 02:32:51 +0100 Subject: [PATCH 06/16] fix(input): bring the process back after a compilation that moves it With -fno-integrated-cc1, the jobs of a compile command run as programs: coretrace-compiler moves the process to the command's directory and leaves it there. The scoped change of directory that this branch removed used to bring the process back. After a load of such a source, the process stayed in the command's directory, where a relative source without a compile command was no longer found. A compilation that holds the lock alone now puts the process back before it releases the lock. The compilations that share the lock do not move the process, and still run at once. Refs #271 --- src/analysis/InputPipeline.cpp | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/analysis/InputPipeline.cpp b/src/analysis/InputPipeline.cpp index a723665f..a9f5100d 100644 --- a/src/analysis/InputPipeline.cpp +++ b/src/analysis/InputPipeline.cpp @@ -47,9 +47,33 @@ namespace ctrace::stack::analysis // this lock. Some change state that the whole process shares, and hold it alone: those // with an option that Clang applies to LLVM's state, and those with -fno-integrated-cc1, // whose jobs run as programs, for which coretrace-compiler moves the process to the - // directory. + // directory and leaves it there (ProcessDirectoryScope). std::shared_mutex gCompileInvokeMutex; + // Brings the process back to the directory it was in. A compilation that holds + // gCompileInvokeMutex alone ends its scope before it releases the lock: the next + // compilation, and the relative paths of the host, start from that directory again. + class ProcessDirectoryScope + { + public: + ProcessDirectoryScope() : directory_(std::filesystem::current_path(error_)) {} + + ProcessDirectoryScope(const ProcessDirectoryScope&) = delete; + ProcessDirectoryScope& operator=(const ProcessDirectoryScope&) = delete; + + ~ProcessDirectoryScope() + { + if (error_) + return; + std::error_code ignored; + std::filesystem::current_path(directory_, ignored); + } + + private: + std::error_code error_; + std::filesystem::path directory_; + }; + bool compilesAlone(const std::vector& args) { static constexpr std::string_view kOptionsOfLLVMState[] = { @@ -921,8 +945,13 @@ namespace ctrace::stack::analysis std::shared_lock shared(gCompileInvokeMutex, std::defer_lock); std::unique_lock alone(gCompileInvokeMutex, std::defer_lock); + // After the locks: it ends before the one it was taken under is released. + std::optional processDirectory; if (compilesAlone(compileArgs)) + { alone.lock(); + processDirectory.emplace(); + } else shared.lock(); const ScopedHotspot hotspot(config.timing, workingDir.empty() From bbaab08a69bf1562c2806f7da7c0dfdc83671fa5 Mon Sep 17 00:00:00 2001 From: Hugo Date: Mon, 16 Nov 2026 02:32:55 +0100 Subject: [PATCH 07/16] test(unit): check that a load leaves the process in its directory A source whose compile command passes -fno-integrated-cc1 is loaded, then a relative source without a compile command. Before the fix, the process was left in the command's directory and the second load failed. Refs #271 --- test/unit/analyzer_module_unit_tests.cpp | 53 ++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/test/unit/analyzer_module_unit_tests.cpp b/test/unit/analyzer_module_unit_tests.cpp index f1e8ca0f..d32635fe 100644 --- a/test/unit/analyzer_module_unit_tests.cpp +++ b/test/unit/analyzer_module_unit_tests.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #include "StackUsageAnalyzer.hpp" #include "analysis/AnalyzerUtils.hpp" +#include "analysis/CompileCommands.hpp" #include "app/CrossTUSummaryDriver.hpp" #include "app/AnalyzerApp.hpp" #include "cli/ArgParser.hpp" @@ -3472,6 +3473,57 @@ namespace return report.failures == 0; } + /// With -fno-integrated-cc1, the jobs of a compile command run as programs: + /// coretrace-compiler moves the process to the command's directory and leaves it there. The + /// load must bring the process back. A source without a compile command is compiled by its + /// relative path, from the directory the process is in: left in the command's directory, + /// the process no longer finds it. + bool testLoadLeavesTheProcessDirectory(TestReport& report) + { + char rootTemplate[] = "/tmp/ctrace-load-directory-XXXXXX"; + if (mkdtemp(rootTemplate) == nullptr) + { + report.expect(false, "Load directory: no temporary directory"); + return false; + } + std::error_code ec; + const std::filesystem::path start = std::filesystem::current_path(ec); + const std::filesystem::path root = std::filesystem::canonical(rootTemplate, ec); + const std::filesystem::path project = root / "project"; + std::filesystem::create_directories(project, ec); + std::ofstream(project / "unit.c") << "int unit(void) { return 1; }\n"; + std::ofstream(root / "host.c") << "int host(void) { return 2; }\n"; + std::ofstream(project / "compile_commands.json") + << "[{\"directory\": \"" << project.string() << "\", \"file\": \"unit.c\", " + << "\"arguments\": [\"cc\", \"-fno-integrated-cc1\", \"-c\", \"unit.c\"]}]\n"; + + ctrace::stack::AnalysisConfig config; + std::string error; + config.compilationDatabase = ctrace::stack::analysis::CompilationDatabase::loadFromFile( + (project / "compile_commands.json").string(), error); + config.inputBaseDir = root.string(); + const auto loads = [&](const char* source) + { + llvm::LLVMContext context; + llvm::SMDiagnostic err; + return ctrace::stack::analysis::loadModuleForAnalysis(source, config, context, err) + .module != nullptr; + }; + + std::filesystem::current_path(root, ec); + const bool compiled = config.compilationDatabase && loads("project/unit.c"); + const bool stayed = + std::filesystem::equivalent(std::filesystem::current_path(ec), root, ec); + const bool found = loads("host.c"); + std::filesystem::current_path(start, ec); + std::filesystem::remove_all(root, ec); + + report.expect(compiled, "Load directory: a command whose jobs run as programs compiles"); + report.expect(stayed, "Load directory: the process is where it was before that load"); + report.expect(found, "Load directory: a relative source without a command then compiles"); + return compiled && stayed && found; + } + /// A ring of pointer variables with one array source, as -O0 code leaves it: p0 = buf, /// p1 = p0, ..., p0 = p(n-1). Every pointer must find the array, however far from it; the /// order of the accesses must not change the alias paths; and the walk must finish on a @@ -3609,6 +3661,7 @@ int main(int argc, char** argv) (void)testDuplicateIfIndexWidths(repoRoot, report); (void)testStackBufferPhiCycle(repoRoot, report); (void)testStackBufferPointerRing(report); + (void)testLoadLeavesTheProcessDirectory(report); (void)testResourceModelConditions(report); (void)testResourceRuleMatchesFunction(report); (void)testOwnershipFactCollector(repoRoot, report); From 7a50b51cc2f1594f6be81ea784e10616caea188f Mon Sep 17 00:00:00 2001 From: Hugo Date: Tue, 24 Nov 2026 23:53:51 +0100 Subject: [PATCH 08/16] build(deps): update coretrace-compiler to v0.13.0 The branch pinned a commit of CoreTrace/coretrace-compiler#262 while that pull request was open. v0.13.0 (e213053) is the release that holds it. Refs #271 --- cmake/compiler/coretrace-compiler.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/compiler/coretrace-compiler.cmake b/cmake/compiler/coretrace-compiler.cmake index 706a1b56..d1e01a66 100644 --- a/cmake/compiler/coretrace-compiler.cmake +++ b/cmake/compiler/coretrace-compiler.cmake @@ -13,7 +13,7 @@ endif() FetchContent_Declare( cc GIT_REPOSITORY https://github.com/CoreTrace/coretrace-compiler.git - GIT_TAG 8a99cf3d7be21dd6e15c1cc8f9523c685fd307ef # CoreTrace/coretrace-compiler#262 + GIT_TAG e21305389a2e639460b2bf619b3a800c15c94fe1 # v0.13.0 ) FetchContent_MakeAvailable(cc) From 1735f863e3c409b50005a46f5f9ec09f46a8dd6a Mon Sep 17 00:00:00 2001 From: Hugo Date: Tue, 24 Nov 2026 23:54:28 +0100 Subject: [PATCH 09/16] perf(app): load the inputs at once, on two workers or min(N, 4) with --jobs=N Since #285 the inputs of a multi-file run load one after the other: their compilations ran under one lock, so a loading worker only parsed its bitcode in parallel. On this branch the compilations share that lock, and the loading workers compile at once. Each compilation in progress holds its own memory, so the loading takes fewer workers than --jobs allows: two when the count is left to the machine (the default, or --jobs=auto), and min(N, 4) with --jobs=N. The other phases use --jobs as before. Refs #271 --- src/app/AnalyzerApp.cpp | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/app/AnalyzerApp.cpp b/src/app/AnalyzerApp.cpp index 500e329c..9321e94d 100644 --- a/src/app/AnalyzerApp.cpp +++ b/src/app/AnalyzerApp.cpp @@ -107,6 +107,18 @@ static unsigned resolveConfiguredJobs(const AnalysisConfig& cfg) return hw == 0 ? 1u : hw; } +// The inputs of a multi-file run that load at once. Each one compiling holds the memory of a +// compilation, so fewer load than --jobs allows: two when the count is left to the machine, and +// at most four when --jobs gives it. +static constexpr unsigned kAutomaticLoadingJobs = 2; +static constexpr unsigned kMaxLoadingJobs = 4; + +static unsigned resolveLoadingJobs(const AnalysisConfig& cfg) +{ + return std::min(resolveConfiguredJobs(cfg), + cfg.jobsAuto ? kAutomaticLoadingJobs : kMaxLoadingJobs); +} + #if defined(CTRACE_STACK_ANALYZER_HAS_PTHREAD) static std::size_t resolveParallelWorkerStackBytes() { @@ -957,12 +969,11 @@ static AppStatus analyzeWithSharedModuleLoading(const std::vector& loadSucceeded[index] = 1; }; - // One input after the other, on this thread, whatever --jobs. The compilations are serialized - // (InputPipeline.cpp): a loading worker would only parse its bitcode in parallel, while glibc - // would give it an arena of its own and keep there the memory its compilation freed, about one + // The inputs compile at once (InputPipeline.cpp), on fewer workers than --jobs allows + // (resolveLoadingJobs): each compilation in progress holds its own memory, and glibc gives each + // worker an arena of its own, which keeps the memory its compilations freed, about one // compilation per worker for the rest of the run. The cross-TU summaries below still use --jobs. - for (std::size_t index = 0; index < inputFilenames.size(); ++index) - loadSingleModule(index); + runParallelWork(inputFilenames.size(), resolveLoadingJobs(cfg), loadSingleModule); std::vector orderedLoadedModules; orderedLoadedModules.reserve(inputFilenames.size()); From 7199bd46e0d10f7b47b654674e62cc8cd7f029e4 Mon Sep 17 00:00:00 2001 From: Hugo Date: Tue, 24 Nov 2026 23:54:57 +0100 Subject: [PATCH 10/16] perf(app): give back to the system the memory that the loading freed Under glibc, the memory a compilation frees stays in the arena of the thread that ran it, for the rest of the run (#285). Once the inputs are loaded, malloc_trim gives it back. The call is compiled under glibc only. On the Linux measure of this loading (run 44956551908, this repository's 53 C++ sources, medians of 3 runs), the analyzer holds 627 MiB of anonymous memory after loading at one job, where the loading is otherwise main's, against 714 MiB for main with the same compiler; 646 and 641 MiB at 2 and 4 jobs, against 747 and 748 MiB. Refs #271 --- src/app/AnalyzerApp.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/app/AnalyzerApp.cpp b/src/app/AnalyzerApp.cpp index 9321e94d..eb306975 100644 --- a/src/app/AnalyzerApp.cpp +++ b/src/app/AnalyzerApp.cpp @@ -36,6 +36,10 @@ #define CTRACE_STACK_ANALYZER_HAS_PTHREAD 1 #endif +#if defined(__GLIBC__) +#include +#endif + #include #include #include @@ -119,6 +123,15 @@ static unsigned resolveLoadingJobs(const AnalysisConfig& cfg) cfg.jobsAuto ? kAutomaticLoadingJobs : kMaxLoadingJobs); } +// Gives back to the system the memory that the allocator keeps free. glibc keeps what the +// compilations freed, in the arena of the thread that ran them, for the rest of the run (#285). +static void releaseFreedMemory() +{ +#if defined(__GLIBC__) + malloc_trim(0); +#endif +} + #if defined(CTRACE_STACK_ANALYZER_HAS_PTHREAD) static std::size_t resolveParallelWorkerStackBytes() { @@ -972,8 +985,10 @@ static AppStatus analyzeWithSharedModuleLoading(const std::vector& // The inputs compile at once (InputPipeline.cpp), on fewer workers than --jobs allows // (resolveLoadingJobs): each compilation in progress holds its own memory, and glibc gives each // worker an arena of its own, which keeps the memory its compilations freed, about one - // compilation per worker for the rest of the run. The cross-TU summaries below still use --jobs. + // compilation per worker, until it is released here. The cross-TU summaries below still use + // --jobs. runParallelWork(inputFilenames.size(), resolveLoadingJobs(cfg), loadSingleModule); + releaseFreedMemory(); std::vector orderedLoadedModules; orderedLoadedModules.reserve(inputFilenames.size()); From b8ec35470e03380568671ab67e21fbec83c3f44f Mon Sep 17 00:00:00 2001 From: Hugo Date: Tue, 24 Nov 2026 23:56:46 +0100 Subject: [PATCH 11/16] test(app): check how many inputs load at once, by --jobs Twelve C files are loaded without a cache, with --timing. The check counts the inputs whose load has started and is not done, line after line of the log: two at once without --jobs and with --jobs=auto, on a machine of two processors or more, and min(N, 4) with --jobs=N, for 1, 2, 3, 4 and 8. Refs #271 --- run_test.py | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/run_test.py b/run_test.py index fd3ae5b9..6204dea2 100755 --- a/run_test.py +++ b/run_test.py @@ -1744,6 +1744,88 @@ def run_and_capture(fmt: str) -> tuple[bool, str]: return ok +def _write_loading_sources(root: Path, count: int = 12) -> list[Path]: + """ + Write `count` C files for the checks of the loading. Each one reads a global of its own before + any write, which the analyzer reports, calls the next one, and includes three standard + headers, so that its compilation lasts long enough to overlap the others'. + """ + sources = [] + for index in range(count): + callee = f"unit_{index + 1:02d}" if index + 1 < count else None + source = root / f"unit_{index:02d}.c" + source.write_text( + "#include \n#include \n#include \n" + f"int table_{index:02d}[4];\n" + + (f"int {callee}(int i);\n" if callee else "") + + f"int unit_{index:02d}(int i)\n{{\n int s = 0;\n s += table_{index:02d}[i & 3];\n" + + (f" return s + {callee}(i);\n" if callee else " return s;\n") + + "}\n" + ) + sources.append(source) + return sources + + +def _most_loads_at_once(timing_log: str) -> int: + """ + The most inputs loading at once, from the log of --timing: an input logs `Compiling` when its + load starts, and `Bitcode parse done in` once its module is there. + """ + in_flight = most = 0 + for line in timing_log.splitlines(): + if "Compiling " in line: + in_flight += 1 + most = max(most, in_flight) + elif "Bitcode parse done in" in line: + in_flight -= 1 + return most + + +def check_loading_jobs() -> bool: + """ + The inputs of a multi-file run load at once, their sources compiling in parallel, on fewer + workers than --jobs allows, as each compilation in progress holds its own memory: two when + the count is left to the machine (no --jobs, or --jobs=auto), and min(N, 4) with --jobs=N. + """ + print("=== Testing how many inputs load at once ===") + automatic = min(2, os.cpu_count() or 1) + ok = True + with tempfile.TemporaryDirectory(prefix="ct_loading_jobs_") as tmp: + root = Path(tmp) + sources = _write_loading_sources(root) + analyzer = str(Path(RUN_CONFIG.analyzer).resolve()) + for jobs, expected in ( + ([], automatic), + (["--jobs=auto"], automatic), + (["--jobs=1"], 1), + (["--jobs=2"], 2), + (["--jobs=3"], 3), + (["--jobs=4"], 4), + (["--jobs=8"], 4), + ): + label = jobs[0] if jobs else "no --jobs" + try: + result = subprocess.run([analyzer, "--timing", *jobs, *map(str, sources)], cwd=root, + capture_output=True, text=True, + timeout=RUN_CONFIG.analyzer_timeout) + except subprocess.TimeoutExpired: + ok = fail_check(f"{label}: the analyzer timed out") + continue + started = result.stderr.count("Compiling ") + loaded = result.stderr.count("Bitcode parse done in") + if result.returncode != 0 or (started, loaded) != (len(sources), len(sources)): + ok = fail_check(f"{label}: exit code {result.returncode}, {started} loads started and " + f"{loaded} done for {len(sources)} inputs", result.stderr) + continue + most = _most_loads_at_once(result.stderr) + if most != expected: + ok = fail_check(f"{label}: {most} at once, expected {expected}") + continue + print(f" ✅ {label}: {most} at once") + print() + return ok + + def check_pipeline_subscriber_rollout_parity() -> bool: """ Integration check: diagnostics must remain stable when toggling the @@ -5978,6 +6060,7 @@ def record_ok(ok: bool): check_unresolved_call_max_stack, check_cycle_max_stack, check_compile_ir_format_switch, + check_loading_jobs, check_pipeline_subscriber_rollout_parity, check_pipeline_timing_traversal_instrumentation, check_only_func_uninitialized, From bbdbf8ad806c4ae933fc06157368c83275484995 Mon Sep 17 00:00:00 2001 From: Hugo Date: Tue, 24 Nov 2026 23:56:46 +0100 Subject: [PATCH 12/16] test(input): compare the reports of an empty and a filled compile IR cache Twelve C files are analyzed one at a time without a cache, then at once from an empty compile IR cache, which their loads fill together, then from that cache, without --jobs and with --jobs=4. The four runs must give the diagnostics and the functions of the first, the runs on the filled cache must read every input from it, and the others none. Refs #271 --- run_test.py | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/run_test.py b/run_test.py index 6204dea2..052787c2 100755 --- a/run_test.py +++ b/run_test.py @@ -1826,6 +1826,57 @@ def check_loading_jobs() -> bool: return ok +def check_reports_of_an_empty_and_a_filled_compile_ir_cache() -> bool: + """ + A multi-file run gives the diagnostics and the functions of a run that loads its inputs one + at a time without a cache, when its inputs load at once from an empty compile IR cache, which + they fill together, and when they load from the cache they filled. + """ + print("=== Testing the reports of an empty and a filled compile IR cache ===") + ok = True + with tempfile.TemporaryDirectory(prefix="ct_loading_cache_") as tmp: + root = Path(tmp) + sources = _write_loading_sources(root) + analyzer = str(Path(RUN_CONFIG.analyzer).resolve()) + + def run(*args): + try: + result = subprocess.run( + [analyzer, "--timing", "--format=json", *args, *map(str, sources)], cwd=root, + capture_output=True, text=True, timeout=RUN_CONFIG.analyzer_timeout) + payload = json.loads(result.stdout) + except (subprocess.TimeoutExpired, json.JSONDecodeError): + return None, 0 + # A diagnostic's id follows its place in the report, which is not compared. + report = ( + sorted(json.dumps({key: value for key, value in d.items() if key != "id"}, sort_keys=True) + for d in payload.get("diagnostics", [])), + sorted(json.dumps(f, sort_keys=True) for f in payload.get("functions", [])), + ) + return report, result.stderr.count("Compilation cache hit for") + + reference, _ = run("--jobs=1") + if reference is None or not all(reference): + print(" ❌ no diagnostics or no functions without a cache, at --jobs=1") + print() + return False + for index, jobs in enumerate(([], ["--jobs=4"])): + label = jobs[0] if jobs else "no --jobs" + cache = f"--compile-ir-cache-dir={root / f'compile-ir-{index}'}" + for state, expected_hits in (("an empty cache", 0), ("the cache it filled", len(sources))): + report, hits = run(*jobs, cache) + if report == reference and hits == expected_hits: + print(f" ✅ {label}, {state}: the report of a run without a cache, " + f"{hits} of {len(sources)} inputs read from the cache") + else: + ok = False + print(f" ❌ {label}, {state}: the report of a run without a cache: " + f"{report == reference}; {hits} inputs read from the cache, " + f"expected {expected_hits}") + print() + return ok + + def check_pipeline_subscriber_rollout_parity() -> bool: """ Integration check: diagnostics must remain stable when toggling the @@ -6061,6 +6112,7 @@ def record_ok(ok: bool): check_cycle_max_stack, check_compile_ir_format_switch, check_loading_jobs, + check_reports_of_an_empty_and_a_filled_compile_ir_cache, check_pipeline_subscriber_rollout_parity, check_pipeline_timing_traversal_instrumentation, check_only_func_uninitialized, From 6af8a1a123b52fe7610c8be74516b3e17a7c98de Mon Sep 17 00:00:00 2001 From: Hugo Date: Tue, 24 Nov 2026 23:57:23 +0100 Subject: [PATCH 13/16] docs(help): say on how many workers --jobs loads the inputs Refs #271 --- main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/main.cpp b/main.cpp index 80bd4865..3d74e269 100644 --- a/main.cpp +++ b/main.cpp @@ -51,8 +51,8 @@ static void printHelp() << " --compdb-fast Speed up compdb builds (drops heavy flags)\n" << " --include-compdb-deps Include _deps entries when auto-discovering files from " "compile_commands.json\n" - << " --jobs= Parallel jobs for the cross-TU summaries of multi-file runs " - "(default: auto)\n" + << " --jobs= Parallel jobs of multi-file runs: N for the cross-TU " + "summaries, min(N, 4) to load the inputs, or 2 with auto (default: auto)\n" << " If no input files are provided, supported files are loaded\n" << " from compile_commands.json automatically.\n" << " --timing Print compilation/analysis timing to stderr\n" From 3f9717afa4bf510a5b1e43897474460358050ae1 Mon Sep 17 00:00:00 2001 From: Hugo Date: Tue, 24 Nov 2026 23:57:41 +0100 Subject: [PATCH 14/16] docs(readme): say that --jobs loads the inputs in parallel, on bounded workers Refs #271 --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 249ebf76..48ad8c21 100644 --- a/README.md +++ b/README.md @@ -252,7 +252,7 @@ Ready-to-adapt workflow examples: --compdb= alias for --compile-commands --compdb-fast drops heavy build flags for faster analysis --include-compdb-deps includes `_deps` entries when inputs are auto-discovered from compile_commands.json ---jobs= parallel jobs for the cross-TU summaries of multi-file runs (default: auto) +--jobs= parallel jobs of multi-file runs: N for the cross-TU summaries, min(N, 4) to load the inputs, or 2 with auto (default: auto) --escape-model= loads external noescape rules for stack pointer escape analysis (`noescape_arg`) --buffer-model= loads external buffer write rules for copy/string overflow checks (`bounded_write`/`unbounded_write`) --resource-model= loads external acquire/release rules for generic resource lifetime checks @@ -295,7 +295,9 @@ To generate `compile_commands.json` with CMake, configure with If analysis feels slow, `--compdb-fast` disables heavy flags (optimizations, sanitizers, profiling) while keeping include paths and macros. -For multi-file runs, `--jobs=` parallelizes the construction of cross-TU summaries; the inputs are loaded one at a time. +For multi-file runs, `--jobs=` parallelizes the construction of cross-TU summaries and the loading of the inputs, compilations included. +Each compilation in progress holds its own memory, so the loading is bounded apart from the summaries: +it takes `min(N, 4)` workers with `--jobs=N`, and 2 with `auto`, the default. `--compile-ir-cache-dir=` reuses compiled LLVM IR for unchanged translation units based on source/dependency stamps, which reduces repeated C/C++ frontend cost across runs. IR that another compiler produced (another coretrace-compiler revision or LLVM version) is compiled again. @@ -574,7 +576,7 @@ Cross-TU summary behavior: - `--no-resource-cross-tu` forces local-only (single-file) resource reasoning. - `--resource-summary-cache-dir=` controls where per-module summary cache files are stored. - `--resource-summary-cache-memory-only` disables filesystem cache writes and uses an in-process cache only. -- `--jobs=` parallelizes per-module summary extraction during each fixpoint iteration; modules are loaded one at a time. +- `--jobs=` parallelizes per-module summary extraction during each fixpoint iteration; modules are loaded on `min(N, 4)` workers, or on 2 with `--jobs=auto`. - The CLI prints an explicit status line to `stderr` to indicate whether resource inter-procedural analysis is enabled or unavailable/disabled (with reason). - If a local release depends on an unmodeled/external callee and no summary is available, the tool From 460529b0ec6c51596f61e7a7e7a1135b17a603f6 Mon Sep 17 00:00:00 2001 From: Hugo Date: Tue, 24 Nov 2026 23:57:55 +0100 Subject: [PATCH 15/16] docs(changelog): describe the bounded loading and the compiler's update Refs #271 --- CHANGELOG.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b406675c..a17ef122 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,12 +68,16 @@ Notable changes are grouped by release. See [all releases](https://github.com/Co - Added an authors file and linked the repository documents from the README. - SARIF rules carry a title (`shortDescription`) and a description (`fullDescription`) instead of their id, and `describeRule` (`RuleCatalog.hpp`) gives them to programs linking the analyzer. -- With `--jobs` above 1, sources compile in parallel. Each compilation runs in its compile - command's directory through coretrace-compiler's `-working-directory`, instead of moving the - whole process there under a lock that let one source compile at a time. Compilations that pass - `-mllvm`, `-mdebug-pass`, `-mlimit-float-precision`, `-ftime-report` or `-fno-integrated-cc1` - still run one at a time. coretrace-compiler is pinned to a commit of - CoreTrace/coretrace-compiler#262, which gives each compilation a working directory of its own. +- In a multi-file run, the inputs load at once and their sources compile in parallel: on at + most two workers when `--jobs` is left to the machine (the default, or `--jobs=auto`), and on + `min(N, 4)` with `--jobs=N`, as each compilation in progress holds its own memory. The other + phases use `--jobs` as before. Each compilation runs in its compile command's directory through + coretrace-compiler's `-working-directory`, instead of moving the whole process there under a + lock that let one source compile at a time. Compilations that pass `-mllvm`, `-mdebug-pass`, + `-mlimit-float-precision`, `-ftime-report` or `-fno-integrated-cc1` still run one at a time. + Under glibc, the memory the compilations freed is given back to the system once the inputs are + loaded. coretrace-compiler is updated to v0.13.0, which gives each compilation a working + directory of its own. ## v0.22.0 From 3445f89527e6bfe6f2fd3afb5163244717b9af78 Mon Sep 17 00:00:00 2001 From: Hugo Date: Tue, 24 Nov 2026 23:58:38 +0100 Subject: [PATCH 16/16] test(app): check the loading bound without the cross-TU summaries The loading is bounded where a multi-file run loads all its inputs before the analysis, which every multi-file run does today. The check adds a run with --no-resource-cross-tu and --no-uninitialized-cross-tu at --jobs=8, to fail the day such a run loads its inputs another way. Refs #271 --- run_test.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/run_test.py b/run_test.py index 052787c2..2123c2f9 100755 --- a/run_test.py +++ b/run_test.py @@ -1786,6 +1786,8 @@ def check_loading_jobs() -> bool: The inputs of a multi-file run load at once, their sources compiling in parallel, on fewer workers than --jobs allows, as each compilation in progress holds its own memory: two when the count is left to the machine (no --jobs, or --jobs=auto), and min(N, 4) with --jobs=N. + The bound holds without the cross-TU summaries that the options can turn off: every + multi-file run loads its inputs that way. """ print("=== Testing how many inputs load at once ===") automatic = min(2, os.cpu_count() or 1) @@ -1802,8 +1804,9 @@ def check_loading_jobs() -> bool: (["--jobs=3"], 3), (["--jobs=4"], 4), (["--jobs=8"], 4), + (["--jobs=8", "--no-resource-cross-tu", "--no-uninitialized-cross-tu"], 4), ): - label = jobs[0] if jobs else "no --jobs" + label = " ".join(jobs) if jobs else "no --jobs" try: result = subprocess.run([analyzer, "--timing", *jobs, *map(str, sources)], cwd=root, capture_output=True, text=True,