32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/FormatVariadic.h"
34#include "llvm/Support/TimeProfiler.h"
44#define DEBUG_TYPE "CoreEngine"
50 "The # of times we reached the max number of steps.");
51STAT_COUNTER(NumPathsExplored,
"The # of paths explored by the analyzer.");
72 llvm_unreachable(
"Unknown AnalyzerOptions::ExplorationStrategyKind");
79 BCounterFactory(G.getAllocator()), FunctionSummaries(FS) {}
82 WList->setBlockCounter(
C);
84 CTUWList->setBlockCounter(
C);
91 assert(!G.getRoot() &&
"empty graph must not have a root node");
96 assert(Entry->
empty() &&
"Entry block must be empty.");
98 assert(Entry->
succ_size() == 1 &&
"Entry block must have 1 successor.");
112 setBlockCounter(BCounterFactory.GetEmptyCounter());
115 InitState = ExprEng.getInitialState(SF);
118 ExplodedNode *Node = G.getNode(StartLoc, InitState.get(),
false, &IsNew);
120 G.designateAsRoot(Node);
122 ExprEng.setCurrStackFrameAndBlock(Node->
getStackFrame(), Succ);
125 ExprEng.processBeginOfFunction(Node, DstBegin, StartLoc);
131 bool UnlimitedSteps = MaxSteps == 0;
135 const unsigned PreReservationCap = 4000000;
137 G.reserve(std::min(MaxSteps, PreReservationCap));
139 auto ProcessWList = [
this, UnlimitedSteps](
unsigned MaxSteps) {
140 unsigned Steps = MaxSteps;
141 while (WList->hasWork()) {
142 if (!UnlimitedSteps) {
144 NumReachedMaxSteps++;
162 return MaxSteps - Steps;
164 const unsigned STUSteps = ProcessWList(MaxSteps);
165 ExploredAllSTUPaths = !WList->hasWork();
168 NumSTUSteps += STUSteps;
169 const unsigned MinCTUSteps =
170 this->ExprEng.getAnalysisManager().options.CTUMaxNodesMin;
172 this->ExprEng.getAnalysisManager().options.CTUMaxNodesPercentage;
173 unsigned MaxCTUSteps = std::max(STUSteps * Pct / 100, MinCTUSteps);
175 WList = std::move(CTUWList);
176 const unsigned CTUSteps = ProcessWList(MaxCTUSteps);
177 NumCTUSteps += CTUSteps;
180 ExprEng.processEndWorklist();
181 return WList->hasWork();
185 if (llvm::timeTraceProfilerEnabled()) {
186 return llvm::formatv(
"dispatchWorkItem {0}",
196 assert(llvm::timeTraceProfilerEnabled());
197 std::string Detail =
"";
199 if (
const Stmt *S = SP->getStmt())
200 Detail = S->getStmtClassName();
202 auto SLoc =
Loc.getSourceLocation();
204 return llvm::TimeTraceMetadata{std::move(Detail),
""};
209 auto Line = SM.getPresumedLineNumber(*SLoc);
210 auto Fname = SM.getFilename(*SLoc);
211 return llvm::TimeTraceMetadata{std::move(Detail), Fname.str(),
212 static_cast<int>(
Line)};
227 ExprEng.resetCurrStackFrameAndBlock();
240 assert(
false &&
"BlockExit location never occur in forward analysis.");
248 ExprEng.processCallExit(Pred);
253 "Assume epsilon has exactly one predecessor by construction");
285 return "Virtual base initialization skipped because "
286 "it has already been handled by the most derived class";
297 if (Blk == &ExitBlk) {
298 assert(ExitBlk.
empty() &&
"EXIT block cannot contain Stmts.");
304 if (std::optional<CFGStmt> LastStmt = LastElement.
getAs<
CFGStmt>()) {
305 RS = dyn_cast<ReturnStmt>(LastStmt->getStmt());
306 }
else if (std::optional<CFGAutomaticObjDtor> AutoDtor =
307 LastElement.
getAs<CFGAutomaticObjDtor>()) {
308 RS = dyn_cast<ReturnStmt>(AutoDtor->getTriggerStmt());
309 }
else if (std::optional<CFGScopeMarker> ScopeMarker =
310 LastElement.
getAs<CFGScopeMarker>()) {
311 RS = dyn_cast<ReturnStmt>(ScopeMarker->getTriggerStmt());
315 ExplodedNodeSet CheckerNodes;
317 ExprEng.runCheckersForBlockEntrance(BE, Pred, CheckerNodes);
320 for (ExplodedNode *P : CheckerNodes) {
321 ExprEng.processEndOfFunction(P, RS);
330 ExplodedNode *Processed = ExprEng.processCFGBlockEntrance(BE, Pred);
332 ExplodedNodeSet CheckerNodes;
335 ExprEng.runCheckersForBlockEntrance(BE, Processed, CheckerNodes);
341void CoreEngine::HandleBlockEntrance(
const BlockEntrance &L,
346 BlockCounter Counter = WList->getBlockCounter();
347 Counter = BCounterFactory.IncrementCount(Counter, SF, BlockId);
348 setBlockCounter(Counter);
353 ExprEng.processCFGElement(*E, Pred, 0);
355 HandleBlockExit(L.
getBlock(), Pred);
358void CoreEngine::HandleBlockExit(
const CFGBlock * B,
ExplodedNode *Pred) {
362 switch (Term->getStmtClass()) {
364 llvm_unreachable(
"Analysis for this terminator not implemented.");
366 case Stmt::CXXBindTemporaryExprClass:
367 HandleCleanupTemporaryBranch(
372 case Stmt::DeclStmtClass:
376 case Stmt::BinaryOperatorClass:
380 case Stmt::BinaryConditionalOperatorClass:
381 case Stmt::ConditionalOperatorClass:
389 case Stmt::ChooseExprClass:
393 case Stmt::CXXTryStmtClass:
396 for (
const CFGBlock *Succ : B->
succs()) {
399 if (ExplodedNode *N =
makeNode(BE, Pred->State.get(), Pred))
405 case Stmt::DoStmtClass:
406 HandleBranch(
cast<DoStmt>(Term)->getCond(), Term, B, Pred);
409 case Stmt::CXXForRangeStmtClass:
413 case Stmt::ForStmtClass:
417 case Stmt::SEHLeaveStmtClass:
418 case Stmt::ContinueStmtClass:
419 case Stmt::BreakStmtClass:
420 case Stmt::GotoStmtClass:
423 case Stmt::IfStmtClass:
424 HandleBranch(
cast<IfStmt>(Term)->getCond(), Term, B, Pred);
427 case Stmt::IndirectGotoStmtClass: {
431 ExprEng.processIndirectGoto(Dst,
438 case Stmt::ObjCForCollectionStmtClass:
449 HandleBranch(Term, Term, B, Pred);
452 case Stmt::SwitchStmtClass: {
460 case Stmt::WhileStmtClass:
464 case Stmt::GCCAsmStmtClass:
465 assert(
cast<GCCAsmStmt>(Term)->isAsmGoto() &&
"Encountered GCCAsmStmt without labels");
472 HandleVirtualBaseBranch(B, Pred);
477 "Blocks with no terminator should have at most 1 successor.");
480 if (ExplodedNode *N =
makeNode(BE, Pred->State.get(), Pred))
484void CoreEngine::HandleCallEnter(
const CallEnter &CE,
ExplodedNode *Pred) {
486 ExprEng.processCallEnter(CE, Pred);
489void CoreEngine::HandleBranch(
const Stmt *Cond,
const Stmt *Term,
493 ExprEng.processBranch(Cond, Pred, Dst, *(B->
succ_begin()),
495 getCompletedIterationCount(B, Pred));
500void CoreEngine::HandleCleanupTemporaryBranch(
const CXXBindTemporaryExpr *BTE,
505 ExprEng.processCleanupTemporaryBranch(BTE, Pred, Dst, *(B->
succ_begin()),
511void CoreEngine::HandleStaticInit(
const DeclStmt *DS,
const CFGBlock *B,
515 ExprEng.processStaticInitializer(DS, Pred, Dst, *(B->
succ_begin()),
521void CoreEngine::HandlePostStmt(
const CFGBlock *B,
unsigned StmtIdx,
527 while (StmtIdx < B->size() &&
532 if (StmtIdx == B->
size())
533 HandleBlockExit(B, Pred);
536 ExprEng.processCFGElement((*B)[StmtIdx], Pred, StmtIdx);
540void CoreEngine::HandleVirtualBaseBranch(
const CFGBlock *B,
543 if (
const auto *CallerCtor =
544 dyn_cast_or_null<CXXConstructExpr>(SF->
getCallSite())) {
545 switch (CallerCtor->getConstructionKind()) {
549 HandleBlockEdge(Loc, Pred);
560 HandleBlockEdge(Loc, Pred);
566 bool IsPO = State->isPosteriorlyOverconstrained();
572 return (IsNew && !IsPO) ? N :
nullptr;
584 WList->enqueue(N,
Block, Idx);
593 WList->enqueue(N,
Block, Idx + 1);
598 WList->enqueue(N,
Block, Idx);
603 WList->enqueue(N,
Block, Idx+1);
614 WList->enqueue(N,
Block, Idx+1);
621 WList->enqueue(Succ,
Block, Idx+1);
624std::optional<unsigned>
625CoreEngine::getCompletedIterationCount(
const CFGBlock *B,
633 assert(BlockCount >= 1 &&
634 "Block count of currently analyzed block must be >= 1");
635 return BlockCount - 1;
648 for (
const auto I :
Set)
661 WList->enqueue(Succ);
664 G.addEndOfPath(Node);
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static std::unique_ptr< WorkList > generateWorkList(AnalyzerOptions &Opts)
ALWAYS_ENABLED_STATISTIC(NumReachedMaxSteps, "The # of times we reached the max number of steps.")
static std::string timeTraceScopeName(const ProgramPoint &Loc)
static llvm::TimeTraceMetadata timeTraceMetadata(const ExplodedNode *Pred, const ProgramPoint &Loc)
static Decl::Kind getKind(const Decl *D)
#define STAT_COUNTER(VARNAME, DESC)
Defines the clang::Expr interface and subclasses for C++ expressions.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the SourceManager interface.
SourceManager & getSourceManager()
ASTContext & getASTContext() const
Stores options for the analyzer from the command line.
ExplorationStrategyKind getExplorationStrategy() const
const CFGBlock * getSrc() const
const CFGBlock * getDst() const
std::optional< CFGElement > getFirstElement() const
const CFGBlock * getBlock() const
Represents a single basic block in a source-level CFG.
CFGTerminator getTerminator() const
succ_iterator succ_begin()
Stmt * getTerminatorStmt()
unsigned getBlockID() const
unsigned succ_size() const
Represents a top-level expression in a basic block.
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type.
std::optional< T > getAs() const
Convert to the specified CFGElement type, returning std::nullopt if this CFGElement is not of the des...
const Stmt * getStmt() const
bool isVirtualBaseBranch() const
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
Represents a point when we begin processing an inlined call.
const CFGBlock * getEntry() const
Returns the entry block in the CFG for the entered function.
Represents a point when we start the call exit sequence (for inlined call).
Represents a point when we finish the call exit sequence (for inlined call).
This is a meta program point, which should be skipped by all the diagnostic reasoning etc.
Represents a point when the lifetime of an automatic object ends.
Represents a point when we exit a loop.
Represents a program point just after an implicit call event.
static StringRef getProgramPointKindName(Kind K)
ProgramPoint withTag(const ProgramPointTag *NewTag) const
Create a new ProgramPoint object that is the same as the original except for using the specified tag ...
const StackFrame * getStackFrame() const
std::optional< T > getAs() const
Convert to the specified ProgramPoint type, returning std::nullopt if this ProgramPoint is not of the...
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
It represents a stack frame of the call stack.
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
const Expr * getCallSite() const
const Decl * getDecl() const
const StackFrame * getParent() const
It might return null.
Stmt - This represents one statement.
An abstract data type used to count the number of times a given block has been visited along a path a...
unsigned getNumVisited(const StackFrame *CallSite, unsigned BlockID) const
CoreEngine(ExprEngine &exprengine, FunctionSummariesTy *FS, AnalyzerOptions &Opts)
Construct a CoreEngine object to analyze the provided CFG.
DataTag::Factory & getDataTags()
void enqueueStmtNode(ExplodedNode *N, const CFGBlock *Block, unsigned Idx)
Enqueue a single node created as a result of statement processing.
void dispatchWorkItem(ExplodedNode *Pred, ProgramPoint Loc, const WorkListUnit &WU)
Dispatch the work list item based on the given location information.
ExplodedNode * makeNode(const ProgramPoint &Loc, const ProgramState *State, ExplodedNode *Pred, bool MarkAsSink=false) const
bool ExecuteWorkList(const StackFrame *SF, unsigned Steps, ProgramStateRef InitState)
ExecuteWorkList - Run the worklist algorithm for a maximum number of steps.
void enqueueEndOfFunction(ExplodedNodeSet &Set, const ReturnStmt *RS)
enqueue the nodes corresponding to the end of function onto the end of path / work list.
void enqueue(ExplodedNodeSet &Set)
Enqueue the given set of nodes onto the work list.
ExplodedNodeSet is a set of ExplodedNode * elements with the invariant that its elements cannot be nu...
const ProgramStateRef & getState() const
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
void addPredecessor(ExplodedNode *V, ExplodedGraph &G)
addPredeccessor - Adds a predecessor to the current node, and in tandem add this node as a successor ...
bool hasSinglePred() const
ExplodedNode * getFirstPred()
const StackFrame * getStackFrame() const
void setCurrStackFrameAndBlock(const StackFrame *SF, const CFGBlock *B)
void markVisitedBasicBlock(unsigned ID, const Decl *D, unsigned TotalIDs)
While alive, includes the current analysis stack in a crash trace.
ProgramState - This class encapsulates:
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
ExplodedNode * getNode() const
Returns the node associated with the worklist unit.
unsigned getIndex() const
Return the index within the CFGBlock for the worklist unit.
const CFGBlock * getBlock() const
Returns the CFGblock associated with the worklist unit.
BlockCounter getBlockCounter() const
Returns the block counter map associated with the worklist unit.
static std::unique_ptr< WorkList > makeUnexploredFirstPriorityLocationQueue()
static std::unique_ptr< WorkList > makeUnexploredFirstPriorityQueue()
static std::unique_ptr< WorkList > makeBFSBlockDFSContents()
static std::unique_ptr< WorkList > makeBFS()
static std::unique_ptr< WorkList > makeDFS()
static std::unique_ptr< WorkList > makeUnexploredFirst()
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
U cast(CodeGen::Address addr)
@ UnexploredFirstLocationQueue