From 74a0e0182fb50902bf8694e3f4561c3483495f50 Mon Sep 17 00:00:00 2001 From: Hugo Date: Tue, 17 Nov 2026 20:31:22 +0100 Subject: [PATCH 1/2] fix(analysis): take the bytes a counted loop writes as initialized after it An array written element by element by a counted loop was reported as read before initialization after the loop (#224). Each iteration stores at an offset that is not constant in the analyzed IR, so the dataflow adds no write. PromotedValues gets a loopWrites query: on the promoted copy, where the loop counter lives in a register, the bytes a store writes over the whole loop around it. It answers only when the loop leaves from one block after a constant number of iterations, the store runs on each of them, and its address moves from a constant offset by a constant step no larger than the bytes written, so that they are contiguous. The uninitialized-read analysis adds those bytes on the edges that leave the loop, nowhere inside it. A loop that stops before the element read, starts after it, skips elements, writes under a condition, may leave early or has a bound that is not constant keeps its report. --- include/analysis/PromotedValues.hpp | 22 ++++ src/analysis/PromotedValues.cpp | 81 +++++++++++++++ src/analysis/UninitializedVarAnalysis.cpp | 120 +++++++++++++++++++--- 3 files changed, 209 insertions(+), 14 deletions(-) diff --git a/include/analysis/PromotedValues.hpp b/include/analysis/PromotedValues.hpp index 79cdf77a..ac776c4e 100644 --- a/include/analysis/PromotedValues.hpp +++ b/include/analysis/PromotedValues.hpp @@ -4,12 +4,16 @@ #include #include #include +#include +#include namespace llvm { + class BasicBlock; class Function; class Instruction; class Module; + class StoreInst; class Value; } // namespace llvm @@ -35,6 +39,17 @@ namespace ctrace::stack::analysis std::uint32_t reservedFlags : 30 = 0; }; + /// @brief The bytes a store writes over every iteration of the loop around it. + struct LoopWrites + { + std::int64_t begin = 0; ///< First byte written, as an offset from the base. + std::int64_t end = 0; ///< One past the last byte written. + /// The only block the loop leaves from, and its successors outside the loop: every edge + /// from the one to the others leaves the loop with these bytes written. + const llvm::BasicBlock* exiting = nullptr; + std::vector exits; + }; + /// @brief Value queries about the original IR, answered on a copy of the module where /// promotable locals live in registers, so ScalarEvolution sees loop counters. /// @@ -73,6 +88,13 @@ namespace ctrace::stack::analysis [[nodiscard]] bool provesWithin(const llvm::Instruction& access, const llvm::Value& index, std::int64_t lower, std::int64_t upper); + /// Bytes @p store writes from @p base over the loop around it, when the loop leaves from + /// one block after a constant number of iterations, the store runs on each of them, and + /// its address moves by a constant step no larger than what it writes, so that the + /// bytes are contiguous. Both belong to the original IR. + [[nodiscard]] std::optional loopWrites(const llvm::StoreInst& store, + const llvm::Value& base); + private: struct Impl; std::unique_ptr impl_; diff --git a/src/analysis/PromotedValues.cpp b/src/analysis/PromotedValues.cpp index 3fb87149..cc1b1ba4 100644 --- a/src/analysis/PromotedValues.cpp +++ b/src/analysis/PromotedValues.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #include "analysis/PromotedValues.hpp" +#include #include #include #include @@ -19,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -406,4 +408,83 @@ namespace ctrace::stack::analysis scev.isKnownPredicateAt(ICmpInst::ICMP_SLT, indexValue, scev.getConstant(type, upper, /*isSigned=*/true), at); } + + std::optional PromotedValues::loopWrites(const llvm::StoreInst& store, + const llvm::Value& base) + { + PromotedFunction* promoted = impl_->promoted(*store.getFunction()); + const auto* at = dyn_cast_or_null(impl_->copyOf(&store)); + const Value* copiedBase = impl_->copyOf(&base); + if (!promoted || !at || !copiedBase) + return std::nullopt; + + // The store in the loop itself, not in one nested in it. The loop leaves from one block + // and goes back to its header from one latch, which the store runs before. + const BasicBlock* block = at->getParent(); + const Loop* loop = promoted->loops.getLoopFor(block); + const BasicBlock* exiting = loop ? loop->getExitingBlock() : nullptr; + const BasicBlock* latch = loop ? loop->getLoopLatch() : nullptr; + if (!exiting || !latch || !promoted->dominators.dominates(block, latch)) + return std::nullopt; + + // A constant iteration count, and an address that moves by a constant step from a + // constant offset of the base. + ScalarEvolution& scev = promoted->scev; + const auto* count = dyn_cast(scev.getBackedgeTakenCount(loop)); + const auto* offset = dyn_cast( + scev.getMinusSCEV(scev.getSCEV(const_cast(at->getPointerOperand())), + scev.getSCEV(const_cast(copiedBase)))); + if (!count || count->getAPInt().getActiveBits() > 32 || !offset || + offset->getLoop() != loop || !offset->isAffine()) + return std::nullopt; + const auto* start = dyn_cast(offset->getStart()); + const auto* step = dyn_cast(offset->getStepRecurrence(scev)); + const TypeSize size = + promoted->function.getDataLayout().getTypeStoreSize(at->getValueOperand()->getType()); + if (!start || !step || start->getAPInt().getBitWidth() > 64 || size.isScalable()) + return std::nullopt; + + // The store runs on each iteration that goes back to the header, and on the last one + // when it lies on every way to the exit. A step no larger than the bytes written leaves + // no gap between iterations. + const std::int64_t runs = static_cast(count->getAPInt().getZExtValue()) + + (promoted->dominators.dominates(block, exiting) ? 1 : 0); + const std::int64_t stride = step->getAPInt().getSExtValue(); + const auto bytes = static_cast(size.getFixedValue()); + if (runs == 0 || stride > bytes || stride < -bytes) + return std::nullopt; + const std::int64_t first = start->getAPInt().getSExtValue(); + const std::optional span = checkedMul(runs - 1, stride); + const std::optional last = span ? checkedAdd(first, *span) : std::nullopt; + const std::optional end = + last ? checkedAdd(std::max(first, *last), bytes) : std::nullopt; + if (!end) + return std::nullopt; + + // The copy keeps the blocks of the original and the order of their successors. + const BasicBlock* originalExiting = nullptr; + for (const BasicBlock& candidate : *store.getFunction()) + { + if (impl_->copyOf(&candidate) == exiting) + { + originalExiting = &candidate; + break; + } + } + if (!originalExiting) + return std::nullopt; + + LoopWrites out; + out.begin = std::min(first, *last); + out.end = *end; + out.exiting = originalExiting; + const Instruction* copiedTerminator = exiting->getTerminator(); + const Instruction* terminator = originalExiting->getTerminator(); + for (unsigned idx = 0; idx < copiedTerminator->getNumSuccessors(); ++idx) + { + if (!loop->contains(copiedTerminator->getSuccessor(idx))) + out.exits.push_back(terminator->getSuccessor(idx)); + } + return out; + } } // namespace ctrace::stack::analysis diff --git a/src/analysis/UninitializedVarAnalysis.cpp b/src/analysis/UninitializedVarAnalysis.cpp index 42738a42..ea8e5c77 100644 --- a/src/analysis/UninitializedVarAnalysis.cpp +++ b/src/analysis/UninitializedVarAnalysis.cpp @@ -2,6 +2,7 @@ #include "analysis/UninitializedVarAnalysis.hpp" #include "analysis/ParameterDebugBinding.hpp" #include "analysis/AnalyzerUtils.hpp" +#include "analysis/PromotedValues.hpp" #include #include @@ -1125,11 +1126,84 @@ namespace ctrace::stack::analysis } } + // The bytes counted loops write, by edge leaving the loop (#224). The dataflow sees each + // iteration store to an element it cannot name, so it adds nothing; the promoted copy, + // where the loop counter lives in a register, gives the bytes of every iteration. + using LoopExitWrites = + llvm::DenseMap, + llvm::SmallVector>; + + class CountedLoopWrites + { + public: + explicit CountedLoopWrites(const llvm::Module& module) : module_(module) {} + + // Found on the first query of @p F: the summary fixpoint analyzes a function several + // times, its loops once. + const LoopExitWrites& of(const llvm::Function& F, const TrackedObjectContext& tracked, + const llvm::DataLayout& DL) + { + auto [it, inserted] = byFunction_.try_emplace(&F); + if (inserted) + collect(F, tracked, DL, it->second); + return it->second; + } + + private: + void collect(const llvm::Function& F, const TrackedObjectContext& tracked, + const llvm::DataLayout& DL, LoopExitWrites& out) + { + for (const llvm::BasicBlock& BB : F) + { + for (const llvm::Instruction& I : BB) + { + // A store at a constant offset is already a write of the dataflow. + const auto* SI = llvm::dyn_cast(&I); + unsigned objectIdx = 0; + std::uint64_t offset = 0; + bool hasConstOffset = false; + if (!SI || llvm::isa(SI->getValueOperand()) || + !resolveTrackedObjectBase(SI->getPointerOperand(), tracked, DL, + objectIdx, offset, hasConstOffset) || + hasConstOffset) + { + continue; + } + + const TrackedMemoryObject& obj = tracked.objects[objectIdx]; + const llvm::Value* base = obj.alloca; + if (!base) + base = obj.param; + if (!base) + continue; + if (!promoted_) + promoted_.emplace(module_, [](const llvm::Function&) { return true; }); + const std::optional writes = promoted_->loopWrites(*SI, *base); + MemoryAccess access; + access.objectIdx = objectIdx; + if (!writes || writes->begin < 0 || + !clipRangeToObject(obj, static_cast(writes->begin), + static_cast(writes->end), + access.begin, access.end)) + { + continue; + } + for (const llvm::BasicBlock* exit : writes->exits) + out[{writes->exiting, exit}].push_back(access); + } + } + } + + const llvm::Module& module_; + std::optional promoted_; + llvm::DenseMap byFunction_; + }; + static InitRangeState computeInState(const llvm::BasicBlock& BB, const llvm::BasicBlock* entryBlock, const llvm::DenseMap& reachable, const llvm::DenseMap& outState, - const TrackedObjectContext& tracked) + const TrackedObjectContext& tracked, const LoopExitWrites& loopExitWrites) { InitRangeState in = makeBottomState(tracked.objects.size()); if (&BB == entryBlock) @@ -1150,7 +1224,17 @@ namespace ctrace::stack::analysis merged = makeBottomState(tracked.objects.size()); break; } - meetMustState(merged, itOut->second); + auto itLoop = loopExitWrites.find({pred, &BB}); + if (itLoop == loopExitWrites.end()) + { + meetMustState(merged, itOut->second); + continue; + } + // The edge leaves a counted loop: what the loop wrote holds on it. + InitRangeState leaving = itOut->second; + for (const MemoryAccess& access : itLoop->second) + addRange(leaving[access.objectIdx], access.begin, access.end); + meetMustState(merged, leaving); } if (!havePred) @@ -3214,13 +3298,15 @@ namespace ctrace::stack::analysis const FunctionSummaryMap& summaries, const ExternalSummaryMapByName* externalSummariesByName, const CalleeSymbolNameMap* calleeSymbolNames, - unsigned fixpointIterationLimit, FunctionSummary* outSummary, + CountedLoopWrites& loopWrites, unsigned fixpointIterationLimit, + FunctionSummary* outSummary, std::vector* outIssues) { TrackedObjectContext tracked; collectTrackedObjects(F, DL, tracked); if (tracked.objects.empty()) return; + const LoopExitWrites& loopExitWrites = loopWrites.of(F, tracked, DL); const unsigned trackedCount = static_cast(tracked.objects.size()); @@ -3321,8 +3407,8 @@ namespace ctrace::stack::analysis if (!reachable.lookup(&BB)) continue; - InitRangeState newIn = - computeInState(BB, &F.getEntryBlock(), reachable, outState, tracked); + InitRangeState newIn = computeInState(BB, &F.getEntryBlock(), reachable, + outState, tracked, loopExitWrites); InitRangeState state = newIn; if (fuseIssueCollection) @@ -3467,10 +3553,12 @@ namespace ctrace::stack::analysis } } - static FunctionSummaryMap computeFunctionSummaries( - llvm::Module& mod, const std::function& shouldAnalyze, - const ExternalSummaryMapByName* externalSummariesByName, - const CalleeSymbolNameMap* calleeSymbolNames, unsigned fixpointIterationLimit) + static FunctionSummaryMap + computeFunctionSummaries(llvm::Module& mod, + const std::function& shouldAnalyze, + const ExternalSummaryMapByName* externalSummariesByName, + const CalleeSymbolNameMap* calleeSymbolNames, + CountedLoopWrites& loopWrites, unsigned fixpointIterationLimit) { FunctionSummaryMap summaries; llvm::SmallVector analysisFunctions; @@ -3523,7 +3611,8 @@ namespace ctrace::stack::analysis FunctionSummary next = makeEmptySummary(*func); analyzeFunction(*func, mod.getDataLayout(), summaries, externalSummariesByName, - calleeSymbolNames, fixpointIterationLimit, &next, nullptr); + calleeSymbolNames, loopWrites, fixpointIterationLimit, &next, + nullptr); FunctionSummary& cur = summaries[func]; if (!(cur == next)) { @@ -3978,8 +4067,10 @@ namespace ctrace::stack::analysis { externalMap = &preparedExternal->opaque->summariesByName; } - FunctionSummaryMap summaries = computeFunctionSummaries( - mod, shouldSummarize, externalMap, calleeSymbolNames, fixpointIterationLimit); + CountedLoopWrites loopWrites(mod); + FunctionSummaryMap summaries = + computeFunctionSummaries(mod, shouldSummarize, externalMap, calleeSymbolNames, + loopWrites, fixpointIterationLimit); return exportSummaryIndexForModule(mod, summaries); } @@ -4084,9 +4175,10 @@ namespace ctrace::stack::analysis { return summaryScope.find(&F) != summaryScope.end(); }; const CalleeSymbolNameMap calleeSymbolNames = buildCalleeSymbolNameMap(mod, summaryScope); const ExternalSummaryMapByName externalMap = importExternalSummaryMap(externalSummaries); + CountedLoopWrites loopWrites(mod); FunctionSummaryMap summaries = computeFunctionSummaries( mod, shouldSummarize, externalMap.empty() ? nullptr : &externalMap, &calleeSymbolNames, - fixpointIterationLimit); + loopWrites, fixpointIterationLimit); for (const llvm::Function& F : mod) { @@ -4097,7 +4189,7 @@ namespace ctrace::stack::analysis analyzeFunction(F, mod.getDataLayout(), summaries, externalMap.empty() ? nullptr : &externalMap, &calleeSymbolNames, - fixpointIterationLimit, nullptr, &issues); + loopWrites, fixpointIterationLimit, nullptr, &issues); } return issues; From 19145852fbd41071b2bdfac68ce4053cbd8092c5 Mon Sep 17 00:00:00 2001 From: Hugo Date: Wed, 18 Nov 2026 04:00:00 +0100 Subject: [PATCH 2/2] test(uninitialized): a counted loop that fills an array, and loops that leave gaps A new fixture covers #224. A read after a counted loop that writes every element of the array is not reported: increasing, decreasing and do-while loops, and an array passed to a function after the loop. A read of an element the loop may leave unwritten stays reported: a loop that stops before it, starts after it, steps over it, writes under a condition, may break out early or has a bound that is not constant. The strict count admits no other report. In the stb-like fixture, the loop at line 20 writes all 17 elements of 'sizes' before any read of it: its three expected reports were false positives. A negative expectation replaces them. The two reports on 'next_code' stay. --- .../stb-like-next-code-uninitialized.c | 10 +- .../uninitialized-local-counted-loop-array.c | 128 ++++++++++++++++++ 2 files changed, 130 insertions(+), 8 deletions(-) create mode 100644 test/uninitialized-variable/uninitialized-local-counted-loop-array.c diff --git a/test/false-positive-repro/stb-like-next-code-uninitialized.c b/test/false-positive-repro/stb-like-next-code-uninitialized.c index 953be49a..35df0824 100644 --- a/test/false-positive-repro/stb-like-next-code-uninitialized.c +++ b/test/false-positive-repro/stb-like-next-code-uninitialized.c @@ -54,11 +54,5 @@ int fp_stb_like_next_code_uninitialized(Huff* z, const u8* sizelist, int num) // at line 43, column 13 // [ !!Warn ] potential read of uninitialized local variable 'next_code' -// at line 22, column 9 -// [ !!Warn ] potential read of uninitialized local variable 'sizes' - -// at line 30, column 24 -// [ !!Warn ] potential read of uninitialized local variable 'sizes' - -// at line 33, column 14 -// [ !!Warn ] potential read of uninitialized local variable 'sizes' +// The loop at line 20 writes every element of 'sizes' before any read of it (#224). +// not contains: potential read of uninitialized local variable 'sizes' diff --git a/test/uninitialized-variable/uninitialized-local-counted-loop-array.c b/test/uninitialized-variable/uninitialized-local-counted-loop-array.c new file mode 100644 index 00000000..aee2dbcc --- /dev/null +++ b/test/uninitialized-variable/uninitialized-local-counted-loop-array.c @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: Apache-2.0 +// #224: a counted loop that writes every element of an array initializes it, while a loop that +// leaves the element read unwritten does not. + +int read_after_full_loop(void) +{ + int squares[4]; + for (int i = 0; i < 4; i++) + squares[i] = i * i; + return squares[3]; +} + +int read_after_decreasing_loop(void) +{ + int down[4]; + for (int i = 3; i >= 0; i--) + down[i] = i; + return down[0]; +} + +int read_after_do_while(void) +{ + int counted[4]; + int i = 0; + do + { + counted[i] = i; + i++; + } while (i < 4); + return counted[3]; +} + +static int ends_match(const int* values) +{ + return values[0] == values[3]; +} + +int pass_after_full_loop(void) +{ + int filled[4]; + for (int i = 0; i < 4; i++) + filled[i] = i; + return ends_match(filled); +} + +int read_past_loop_end(void) +{ + int short_end[4]; + for (int i = 0; i < 3; i++) + short_end[i] = i; + return short_end[3]; +} + +int read_before_loop_start(void) +{ + int late_start[4]; + for (int i = 1; i < 4; i++) + late_start[i] = i; + return late_start[0]; +} + +int read_skipped_element(void) +{ + int every_other[4]; + for (int i = 0; i < 4; i += 2) + every_other[i] = i; + return every_other[1]; +} + +int read_after_conditional_write(int c) +{ + int some[4]; + for (int i = 0; i < 4; i++) + { + if (c > i) + some[i] = i; + } + return some[3]; +} + +int read_after_loop_with_break(int c) +{ + int cut[4]; + for (int i = 0; i < 4; i++) + { + if (c == i) + break; + cut[i] = i; + } + return cut[3]; +} + +int read_after_variable_bound(int n) +{ + int bounded[4]; + for (int i = 0; i < n; i++) + bounded[i] = i; + return bounded[3]; +} + +// at line 51, column 12 +// [ !!Warn ] potential read of uninitialized local variable 'short_end' +// ↳ this load may execute before any definite initialization on all control-flow paths + +// at line 59, column 12 +// [ !!Warn ] potential read of uninitialized local variable 'late_start' +// ↳ this load may execute before any definite initialization on all control-flow paths + +// at line 67, column 12 +// [ !!Warn ] potential read of uninitialized local variable 'every_other' +// ↳ this load may execute before any definite initialization on all control-flow paths + +// at line 78, column 12 +// [ !!Warn ] potential read of uninitialized local variable 'some' +// ↳ this load may execute before any definite initialization on all control-flow paths + +// at line 90, column 12 +// [ !!Warn ] potential read of uninitialized local variable 'cut' +// ↳ this load may execute before any definite initialization on all control-flow paths + +// at line 98, column 12 +// [ !!Warn ] potential read of uninitialized local variable 'bounded' +// ↳ this load may execute before any definite initialization on all control-flow paths + +// not contains: potential read of uninitialized local variable 'squares' +// not contains: potential read of uninitialized local variable 'down' +// not contains: potential read of uninitialized local variable 'counted' +// not contains: potential read of uninitialized local variable 'filled'