31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/FormatVariadic.h"
33#include "llvm/Support/TimeProfiler.h"
43#define DEBUG_TYPE "CoreEngine"
49 "The # of times we reached the max number of steps.");
50STAT_COUNTER(NumPathsExplored,
"The # of paths explored by the analyzer.");
58 case ExplorationStrategyKind::DFS:
60 case ExplorationStrategyKind::BFS:
62 case ExplorationStrategyKind::BFSBlockDFSContents:
64 case ExplorationStrategyKind::UnexploredFirst:
66 case ExplorationStrategyKind::UnexploredFirstQueue:
68 case ExplorationStrategyKind::UnexploredFirstLocationQueue:
71 llvm_unreachable(
"Unknown AnalyzerOptions::ExplorationStrategyKind");
78 BCounterFactory(G.getAllocator()), FunctionSummaries(FS) {}
81 WList->setBlockCounter(
C);
83 CTUWList->setBlockCounter(
C);
90 assert(!G.
getRoot() &&
"empty graph must not have a root node");
95 assert(Entry->
empty() &&
"Entry block must be empty.");
97 assert(Entry->
succ_size() == 1 &&
"Entry block must have 1 successor.");
130 bool UnlimitedSteps = MaxSteps == 0;
134 const unsigned PreReservationCap = 4000000;
136 G.
reserve(std::min(MaxSteps, PreReservationCap));
138 auto ProcessWList = [
this, UnlimitedSteps](
unsigned MaxSteps) {
139 unsigned Steps = MaxSteps;
140 while (WList->hasWork()) {
141 if (!UnlimitedSteps) {
143 NumReachedMaxSteps++;
161 return MaxSteps - Steps;
163 const unsigned STUSteps = ProcessWList(MaxSteps);
166 NumSTUSteps += STUSteps;
167 const unsigned MinCTUSteps =
171 unsigned MaxCTUSteps = std::max(STUSteps * Pct / 100, MinCTUSteps);
173 WList = std::move(CTUWList);
174 const unsigned CTUSteps = ProcessWList(MaxCTUSteps);
175 NumCTUSteps += CTUSteps;
179 return WList->hasWork();
183 if (llvm::timeTraceProfilerEnabled()) {
184 return llvm::formatv(
"dispatchWorkItem {0}",
194 assert(llvm::timeTraceProfilerEnabled());
195 std::string Detail =
"";
197 if (
const Stmt *S = SP->getStmt())
198 Detail = S->getStmtClassName();
200 auto SLoc =
Loc.getSourceLocation();
202 return llvm::TimeTraceMetadata{std::move(Detail),
""};
207 auto Line =
SM.getPresumedLineNumber(*SLoc);
208 auto Fname =
SM.getFilename(*SLoc);
209 return llvm::TimeTraceMetadata{std::move(Detail), Fname.str(),
210 static_cast<int>(
Line)};
230 assert(
false &&
"BlockExit location never occur in forward analysis.");
243 "Assume epsilon has exactly one predecessor by construction");
278 return "Virtual base initialization skipped because "
279 "it has already been handled by the most derived class";
285 Pred = Bldr.generateNode(
P, Pred->
getState(), Pred);
293 "EXIT block cannot contain Stmts.");
299 if (std::optional<CFGStmt> LastStmt = LastElement.
getAs<
CFGStmt>()) {
300 RS = dyn_cast<ReturnStmt>(LastStmt->getStmt());
301 }
else if (std::optional<CFGAutomaticObjDtor> AutoDtor =
303 RS = dyn_cast<ReturnStmt>(AutoDtor->getTriggerStmt());
332 for (
auto *N : DstNodes) {
348 setBlockCounter(Counter);
355 HandleBlockExit(L.
getBlock(), Pred);
360 switch (Term->getStmtClass()) {
362 llvm_unreachable(
"Analysis for this terminator not implemented.");
364 case Stmt::CXXBindTemporaryExprClass:
365 HandleCleanupTemporaryBranch(
366 cast<CXXBindTemporaryExpr>(Term), B, Pred);
370 case Stmt::DeclStmtClass:
371 HandleStaticInit(cast<DeclStmt>(Term), B, Pred);
374 case Stmt::BinaryOperatorClass:
375 HandleBranch(cast<BinaryOperator>(Term)->getLHS(), Term, B, Pred);
378 case Stmt::BinaryConditionalOperatorClass:
379 case Stmt::ConditionalOperatorClass:
380 HandleBranch(cast<AbstractConditionalOperator>(Term)->getCond(),
387 case Stmt::ChooseExprClass:
388 HandleBranch(cast<ChooseExpr>(Term)->getCond(), Term, B, Pred);
391 case Stmt::CXXTryStmtClass:
395 et = B->
succ_end(); it != et; ++it) {
403 case Stmt::DoStmtClass:
404 HandleBranch(cast<DoStmt>(Term)->getCond(), Term, B, Pred);
407 case Stmt::CXXForRangeStmtClass:
408 HandleBranch(cast<CXXForRangeStmt>(Term)->getCond(), Term, B, Pred);
411 case Stmt::ForStmtClass:
412 HandleBranch(cast<ForStmt>(Term)->getCond(), Term, B, Pred);
415 case Stmt::SEHLeaveStmtClass:
416 case Stmt::ContinueStmtClass:
417 case Stmt::BreakStmtClass:
418 case Stmt::GotoStmtClass:
421 case Stmt::IfStmtClass:
422 HandleBranch(cast<IfStmt>(Term)->getCond(), Term, B, Pred);
425 case Stmt::IndirectGotoStmtClass: {
430 builder(Pred, B, cast<IndirectGotoStmt>(Term)->getTarget(),
437 case Stmt::ObjCForCollectionStmtClass:
448 HandleBranch(Term, Term, B, Pred);
451 case Stmt::SwitchStmtClass: {
459 case Stmt::WhileStmtClass:
460 HandleBranch(cast<WhileStmt>(Term)->getCond(), Term, B, Pred);
463 case Stmt::GCCAsmStmtClass:
464 assert(cast<GCCAsmStmt>(Term)->isAsmGoto() &&
"Encountered GCCAsmStmt without labels");
471 HandleVirtualBaseBranch(B, Pred);
476 "Blocks with no terminator should have at most 1 successor.");
487void CoreEngine::HandleBranch(
const Stmt *Cond,
const Stmt *Term,
494 getCompletedIterationCount(B, Pred));
522void CoreEngine::HandlePostStmt(
const CFGBlock *B,
unsigned StmtIdx,
527 if (StmtIdx == B->
size())
528 HandleBlockExit(B, Pred);
535void CoreEngine::HandleVirtualBaseBranch(
const CFGBlock *B,
538 if (
const auto *CallerCtor = dyn_cast_or_null<CXXConstructExpr>(
540 switch (CallerCtor->getConstructionKind()) {
544 HandleBlockEdge(
Loc, Pred);
555 HandleBlockEdge(
Loc, Pred);
567 Node->addPredecessor(Pred, G);
570 if (IsNew) WList->enqueue(
Node);
582 WList->enqueue(N,
Block, Idx);
590 WList->enqueue(N,
Block, Idx+1);
595 WList->enqueue(N,
Block, Idx);
600 WList->enqueue(N,
Block, Idx+1);
611 WList->enqueue(N,
Block, Idx+1);
620 WList->enqueue(Succ,
Block, Idx+1);
633 Node->addPredecessor(N, G);
634 return isNew ?
Node :
nullptr;
637std::optional<unsigned>
638CoreEngine::getCompletedIterationCount(
const CFGBlock *B,
642 unsigned BlockCount =
646 if (isa<ForStmt, WhileStmt, CXXForRangeStmt>(Term)) {
647 assert(BlockCount >= 1 &&
648 "Block count of currently analyzed block must be >= 1");
649 return BlockCount - 1;
651 if (isa<DoStmt>(Term)) {
662 for (
const auto I :
Set)
668 for (
const auto I :
Set)
673 for (
auto *I :
Set) {
675 if (I->getLocationContext()->getParent()) {
676 I = generateCallExitBeginNode(I, RS);
687void NodeBuilder::anchor() {}
708void NodeBuilderWithSinks::anchor() {}
716void BranchNodeBuilder::anchor() {}
721 const CFGBlock *Dst = Branch ? DstT : DstF;
746 Eng.WList->enqueue(Succ);
762 Eng.WList->enqueue(Succ);
788 Eng.WList->enqueue(Succ);
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.
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 C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Represents a single basic block in a source-level CFG.
succ_reverse_iterator succ_rend()
succ_reverse_iterator succ_rbegin()
CFGTerminator getTerminator() const
succ_iterator succ_begin()
Stmt * getTerminatorStmt()
unsigned getBlockID() const
AdjacentBlocks::const_iterator const_succ_iterator
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 binding an expression to a temporary.
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).
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
This is a meta program point, which should be skipped by all the diagnostic reasoning etc.
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
const Decl * getDecl() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
const StackFrameContext * getStackFrame() const
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 *tag) const
Create a new ProgramPoint object that is the same as the original except for using the specified tag ...
std::optional< T > getAs() const
Convert to the specified ProgramPoint type, returning std::nullopt if this ProgramPoint is not of the...
const LocationContext * getLocationContext() const
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
const Stmt * getCallSite() const
Stmt - This represents one statement.
AnalyzerOptions & options
BlockCounter IncrementCount(BlockCounter BC, const StackFrameContext *CallSite, unsigned BlockID)
BlockCounter GetEmptyCounter()
An abstract data type used to count the number of times a given block has been visited along a path a...
unsigned getNumVisited(const StackFrameContext *CallSite, unsigned BlockID) const
ExplodedNode * generateNode(ProgramStateRef State, bool branch, ExplodedNode *Pred)
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.
bool ExecuteWorkList(const LocationContext *L, 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.
void reserve(unsigned NodeCount)
ExplodedNode * getNode(const ProgramPoint &L, ProgramStateRef State, bool IsSink=false, bool *IsNew=nullptr)
Retrieve the node associated with a (Location, State) pair, where the 'Location' is a ProgramPoint in...
ExplodedNode * getRoot() const
Get the root node of the graph.
void designateAsRoot(ExplodedNode *V)
Mark a node as the root of the graph.
ExplodedNode * addEndOfPath(ExplodedNode *V)
addEndOfPath - Add an untyped node to the set of EOP nodes.
bool erase(ExplodedNode *N)
void Add(ExplodedNode *N)
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
const LocationContext * getLocationContext() const
ExplodedNode * getFirstPred()
void processEndOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred, const ReturnStmt *RS=nullptr)
Called by CoreEngine.
void processCallEnter(NodeBuilderContext &BC, CallEnter CE, ExplodedNode *Pred)
Generate the entry node of the callee.
void processBeginOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred, ExplodedNodeSet &Dst, const BlockEdge &L)
Called by CoreEngine.
ProgramStateRef getInitialState(const LocationContext *InitLoc)
getInitialState - Return the initial state used for the root vertex in the ExplodedGraph.
void processCallExit(ExplodedNode *Pred)
Generate the sequence of nodes that simulate the call exit and the post visit for CallExpr.
void processCFGBlockEntrance(const BlockEdge &L, NodeBuilderWithSinks &nodeBuilder, ExplodedNode *Pred)
Called by CoreEngine when processing the entrance of a CFGBlock.
void processCFGElement(const CFGElement E, ExplodedNode *Pred, unsigned StmtIdx, NodeBuilderContext *Ctx)
processCFGElement - Called by CoreEngine.
void processStaticInitializer(const DeclStmt *DS, NodeBuilderContext &BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF)
Called by CoreEngine.
void processBranch(const Stmt *Condition, NodeBuilderContext &BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF, std::optional< unsigned > IterationsCompletedInLoop)
ProcessBranch - Called by CoreEngine.
void processSwitch(SwitchNodeBuilder &builder)
ProcessSwitch - Called by CoreEngine.
void processEndWorklist()
Called by CoreEngine when the analysis worklist has terminated.
void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, NodeBuilderContext &BldCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF)
Called by CoreEngine.
AnalysisManager & getAnalysisManager()
void runCheckersForBlockEntrance(const NodeBuilderContext &BldCtx, const BlockEntrance &Entrance, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void processIndirectGoto(IndirectGotoNodeBuilder &builder)
processIndirectGoto - Called by CoreEngine.
void markVisitedBasicBlock(unsigned ID, const Decl *D, unsigned TotalIDs)
const CFGBlock * getBlock() const
ExplodedNode * generateNode(const iterator &I, ProgramStateRef State, bool isSink=false)
const CoreEngine & getEngine() const
Return the CoreEngine associated with this builder.
const CFGBlock * getBlock() const
Return the CFGBlock associated with this builder.
This node builder keeps track of the generated sink nodes.
This is the simplest builder which generates nodes in the ExplodedGraph.
const NodeBuilderContext & C
ExplodedNode * generateNode(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a node in the ExplodedGraph.
ExplodedNodeSet & Frontier
The frontier set - a set of nodes which need to be propagated after the builder dies.
void addNodes(const ExplodedNodeSet &S)
ExplodedNode * generateNodeImpl(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred, bool MarkAsSink=false)
While alive, includes the current analysis stack in a crash trace.
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.
~StmtNodeBuilder() override
const CFGBlock * getBlock() const
ExplodedNode * generateDefaultCaseNode(ProgramStateRef State, bool isSink=false)
ExplodedNode * generateCaseStmtNode(const iterator &I, ProgramStateRef State)
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()
The JSON file list parser is used to communicate input to InstallAPI.