1 //==- CoreEngine.h - Path-Sensitive Dataflow Engine ----------------*- C++ -*-//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a generic engine for intraprocedural, path-sensitive,
11 // dataflow analysis via graph reachability.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_GR_COREENGINE
16 #define LLVM_CLANG_GR_COREENGINE
18 #include "clang/AST/Expr.h"
19 #include "clang/Analysis/AnalysisContext.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h"
24 #include "llvm/ADT/OwningPtr.h"
28 class ProgramPointTag;
34 //===----------------------------------------------------------------------===//
35 /// CoreEngine - Implements the core logic of the graph-reachability
36 /// analysis. It traverses the CFG and generates the ExplodedGraph.
37 /// Program "states" are treated as opaque void pointers.
38 /// The template class CoreEngine (which subclasses CoreEngine)
39 /// provides the matching component to the engine that knows the actual types
40 /// for states. Note that this engine only dispatches to transfer functions
41 /// at the statement and block-level. The analyses themselves must implement
42 /// any transfer function logic and the sub-expression level (if any).
44 friend struct NodeBuilderContext;
45 friend class NodeBuilder;
46 friend class ExprEngine;
47 friend class CommonNodeBuilder;
48 friend class IndirectGotoNodeBuilder;
49 friend class SwitchNodeBuilder;
50 friend class EndOfFunctionNodeBuilder;
52 typedef std::vector<std::pair<BlockEdge, const ExplodedNode*> >
55 typedef std::vector<std::pair<const CFGBlock*, const ExplodedNode*> >
62 /// G - The simulation graph. Each node is a (location,state) pair.
63 OwningPtr<ExplodedGraph> G;
65 /// WList - A set of queued nodes that need to be processed by the
66 /// worklist algorithm. It is up to the implementation of WList to decide
67 /// the order that nodes are processed.
68 OwningPtr<WorkList> WList;
70 /// BCounterFactory - A factory object for created BlockCounter objects.
71 /// These are used to record for key nodes in the ExplodedGraph the
72 /// number of times different CFGBlocks have been visited along a path.
73 BlockCounter::Factory BCounterFactory;
75 /// The locations where we stopped doing work because we visited a location
77 BlocksExhausted blocksExhausted;
79 /// The locations where we stopped because the engine aborted analysis,
80 /// usually because it could not reason about something.
81 BlocksAborted blocksAborted;
83 /// The functions which have been analyzed through inlining. This is owned by
84 /// AnalysisConsumer. It can be null.
85 SetOfConstDecls *AnalyzedCallees;
87 /// The information about functions shared by the whole translation unit.
88 /// (This data is owned by AnalysisConsumer.)
89 FunctionSummariesTy *FunctionSummaries;
91 void generateNode(const ProgramPoint &Loc,
92 ProgramStateRef State,
95 void HandleBlockEdge(const BlockEdge &E, ExplodedNode *Pred);
96 void HandleBlockEntrance(const BlockEntrance &E, ExplodedNode *Pred);
97 void HandleBlockExit(const CFGBlock *B, ExplodedNode *Pred);
98 void HandlePostStmt(const CFGBlock *B, unsigned StmtIdx, ExplodedNode *Pred);
100 void HandleBranch(const Stmt *Cond, const Stmt *Term, const CFGBlock *B,
104 CoreEngine(const CoreEngine&); // Do not implement.
105 CoreEngine& operator=(const CoreEngine&);
107 ExplodedNode *generateCallExitBeginNode(ExplodedNode *N);
110 /// Construct a CoreEngine object to analyze the provided CFG.
111 CoreEngine(SubEngine& subengine, SetOfConstDecls *VisitedCallees,
112 FunctionSummariesTy *FS)
113 : SubEng(subengine), G(new ExplodedGraph()),
114 WList(WorkList::makeDFS()),
115 BCounterFactory(G->getAllocator()),
116 AnalyzedCallees(VisitedCallees),
117 FunctionSummaries(FS){}
119 /// getGraph - Returns the exploded graph.
120 ExplodedGraph& getGraph() { return *G.get(); }
122 /// takeGraph - Returns the exploded graph. Ownership of the graph is
123 /// transferred to the caller.
124 ExplodedGraph* takeGraph() { return G.take(); }
126 /// ExecuteWorkList - Run the worklist algorithm for a maximum number of
127 /// steps. Returns true if there is still simulation state on the worklist.
128 bool ExecuteWorkList(const LocationContext *L, unsigned Steps,
129 ProgramStateRef InitState);
130 /// Returns true if there is still simulation state on the worklist.
131 bool ExecuteWorkListWithInitialState(const LocationContext *L,
133 ProgramStateRef InitState,
134 ExplodedNodeSet &Dst);
136 /// Dispatch the work list item based on the given location information.
137 /// Use Pred parameter as the predecessor state.
138 void dispatchWorkItem(ExplodedNode* Pred, ProgramPoint Loc,
139 const WorkListUnit& WU);
141 // Functions for external checking of whether we have unfinished work
142 bool wasBlockAborted() const { return !blocksAborted.empty(); }
143 bool wasBlocksExhausted() const { return !blocksExhausted.empty(); }
144 bool hasWorkRemaining() const { return wasBlocksExhausted() ||
148 /// Inform the CoreEngine that a basic block was aborted because
149 /// it could not be completely analyzed.
150 void addAbortedBlock(const ExplodedNode *node, const CFGBlock *block) {
151 blocksAborted.push_back(std::make_pair(block, node));
154 WorkList *getWorkList() const { return WList.get(); }
156 BlocksExhausted::const_iterator blocks_exhausted_begin() const {
157 return blocksExhausted.begin();
159 BlocksExhausted::const_iterator blocks_exhausted_end() const {
160 return blocksExhausted.end();
162 BlocksAborted::const_iterator blocks_aborted_begin() const {
163 return blocksAborted.begin();
165 BlocksAborted::const_iterator blocks_aborted_end() const {
166 return blocksAborted.end();
169 /// \brief Enqueue the given set of nodes onto the work list.
170 void enqueue(ExplodedNodeSet &Set);
172 /// \brief Enqueue nodes that were created as a result of processing
173 /// a statement onto the work list.
174 void enqueue(ExplodedNodeSet &Set, const CFGBlock *Block, unsigned Idx);
176 /// \brief enqueue the nodes corresponding to the end of function onto the
177 /// end of path / work list.
178 void enqueueEndOfFunction(ExplodedNodeSet &Set);
180 /// \brief Enqueue a single node created as a result of statement processing.
181 void enqueueStmtNode(ExplodedNode *N, const CFGBlock *Block, unsigned Idx);
184 // TODO: Turn into a calss.
185 struct NodeBuilderContext {
186 const CoreEngine &Eng;
187 const CFGBlock *Block;
189 NodeBuilderContext(const CoreEngine &E, const CFGBlock *B, ExplodedNode *N)
190 : Eng(E), Block(B), Pred(N) { assert(B); assert(!N->isSink()); }
192 ExplodedNode *getPred() const { return Pred; }
194 /// \brief Return the CFGBlock associated with this builder.
195 const CFGBlock *getBlock() const { return Block; }
197 /// \brief Returns the number of times the current basic block has been
198 /// visited on the exploded graph path.
199 unsigned getCurrentBlockCount() const {
200 return Eng.WList->getBlockCounter().getNumVisited(
201 Pred->getLocationContext()->getCurrentStackFrame(),
202 Block->getBlockID());
206 /// \class NodeBuilder
207 /// \brief This is the simplest builder which generates nodes in the
210 /// The main benefit of the builder is that it automatically tracks the
211 /// frontier nodes (or destination set). This is the set of nodes which should
212 /// be propagated to the next step / builder. They are the nodes which have been
213 /// added to the builder (either as the input node set or as the newly
214 /// constructed nodes) but did not have any outgoing transitions added.
216 virtual void anchor();
218 const NodeBuilderContext &C;
220 /// Specifies if the builder results have been finalized. For example, if it
221 /// is set to false, autotransitions are yet to be generated.
223 bool HasGeneratedNodes;
224 /// \brief The frontier set - a set of nodes which need to be propagated after
225 /// the builder dies.
226 ExplodedNodeSet &Frontier;
228 /// Checkes if the results are ready.
229 virtual bool checkResults() {
235 bool hasNoSinksInFrontier() {
236 for (iterator I = Frontier.begin(), E = Frontier.end(); I != E; ++I) {
243 /// Allow subclasses to finalize results before result_begin() is executed.
244 virtual void finalizeResults() {}
246 ExplodedNode *generateNodeImpl(const ProgramPoint &PP,
247 ProgramStateRef State,
249 bool MarkAsSink = false);
252 NodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet,
253 const NodeBuilderContext &Ctx, bool F = true)
254 : C(Ctx), Finalized(F), HasGeneratedNodes(false), Frontier(DstSet) {
255 Frontier.Add(SrcNode);
258 NodeBuilder(const ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet,
259 const NodeBuilderContext &Ctx, bool F = true)
260 : C(Ctx), Finalized(F), HasGeneratedNodes(false), Frontier(DstSet) {
261 Frontier.insert(SrcSet);
262 assert(hasNoSinksInFrontier());
265 virtual ~NodeBuilder() {}
267 /// \brief Generates a node in the ExplodedGraph.
269 /// When a node is marked as sink, the exploration from the node is stopped -
270 /// the node becomes the last node on the path.
271 ExplodedNode *generateNode(const ProgramPoint &PP,
272 ProgramStateRef State,
274 bool MarkAsSink = false) {
275 return generateNodeImpl(PP, State, Pred, MarkAsSink);
278 const ExplodedNodeSet &getResults() {
280 assert(checkResults());
284 typedef ExplodedNodeSet::iterator iterator;
285 /// \brief Iterators through the results frontier.
286 inline iterator begin() {
288 assert(checkResults());
289 return Frontier.begin();
291 inline iterator end() {
293 return Frontier.end();
296 const NodeBuilderContext &getContext() { return C; }
297 bool hasGeneratedNodes() { return HasGeneratedNodes; }
299 void takeNodes(const ExplodedNodeSet &S) {
300 for (ExplodedNodeSet::iterator I = S.begin(), E = S.end(); I != E; ++I )
303 void takeNodes(ExplodedNode *N) { Frontier.erase(N); }
304 void addNodes(const ExplodedNodeSet &S) { Frontier.insert(S); }
305 void addNodes(ExplodedNode *N) { Frontier.Add(N); }
308 /// \class NodeBuilderWithSinks
309 /// \brief This node builder keeps track of the generated sink nodes.
310 class NodeBuilderWithSinks: public NodeBuilder {
311 virtual void anchor();
313 SmallVector<ExplodedNode*, 2> sinksGenerated;
314 ProgramPoint &Location;
317 NodeBuilderWithSinks(ExplodedNode *Pred, ExplodedNodeSet &DstSet,
318 const NodeBuilderContext &Ctx, ProgramPoint &L)
319 : NodeBuilder(Pred, DstSet, Ctx), Location(L) {}
320 ExplodedNode *generateNode(ProgramStateRef State,
322 const ProgramPointTag *Tag = 0,
323 bool MarkAsSink = false) {
324 ProgramPoint LocalLoc = (Tag ? Location.withTag(Tag): Location);
326 ExplodedNode *N = generateNodeImpl(LocalLoc, State, Pred, MarkAsSink);
327 if (N && N->isSink())
328 sinksGenerated.push_back(N);
332 const SmallVectorImpl<ExplodedNode*> &getSinks() const {
333 return sinksGenerated;
337 /// \class StmtNodeBuilder
338 /// \brief This builder class is useful for generating nodes that resulted from
339 /// visiting a statement. The main difference from it's parent NodeBuilder is
340 /// that it creates a statement specific ProgramPoint.
341 class StmtNodeBuilder: public NodeBuilder {
342 NodeBuilder *EnclosingBldr;
345 /// \brief Constructs a StmtNodeBuilder. If the builder is going to process
346 /// nodes currently owned by another builder(with larger scope), use
347 /// Enclosing builder to transfer ownership.
348 StmtNodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet,
349 const NodeBuilderContext &Ctx, NodeBuilder *Enclosing = 0)
350 : NodeBuilder(SrcNode, DstSet, Ctx), EnclosingBldr(Enclosing) {
352 EnclosingBldr->takeNodes(SrcNode);
355 StmtNodeBuilder(ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet,
356 const NodeBuilderContext &Ctx, NodeBuilder *Enclosing = 0)
357 : NodeBuilder(SrcSet, DstSet, Ctx), EnclosingBldr(Enclosing) {
359 for (ExplodedNodeSet::iterator I = SrcSet.begin(),
360 E = SrcSet.end(); I != E; ++I )
361 EnclosingBldr->takeNodes(*I);
364 virtual ~StmtNodeBuilder();
366 ExplodedNode *generateNode(const Stmt *S,
369 bool MarkAsSink = false,
370 const ProgramPointTag *tag = 0,
371 ProgramPoint::Kind K = ProgramPoint::PostStmtKind){
372 const ProgramPoint &L = ProgramPoint::getProgramPoint(S, K,
373 Pred->getLocationContext(), tag);
374 return generateNodeImpl(L, St, Pred, MarkAsSink);
377 ExplodedNode *generateNode(const ProgramPoint &PP,
379 ProgramStateRef State,
380 bool MarkAsSink = false) {
381 return generateNodeImpl(PP, State, Pred, MarkAsSink);
385 /// \brief BranchNodeBuilder is responsible for constructing the nodes
386 /// corresponding to the two branches of the if statement - true and false.
387 class BranchNodeBuilder: public NodeBuilder {
388 virtual void anchor();
389 const CFGBlock *DstT;
390 const CFGBlock *DstF;
393 bool InFeasibleFalse;
396 BranchNodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet,
397 const NodeBuilderContext &C,
398 const CFGBlock *dstT, const CFGBlock *dstF)
399 : NodeBuilder(SrcNode, DstSet, C), DstT(dstT), DstF(dstF),
400 InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) {
401 // The branch node builder does not generate autotransitions.
402 // If there are no successors it means that both branches are infeasible.
406 BranchNodeBuilder(const ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet,
407 const NodeBuilderContext &C,
408 const CFGBlock *dstT, const CFGBlock *dstF)
409 : NodeBuilder(SrcSet, DstSet, C), DstT(dstT), DstF(dstF),
410 InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) {
414 ExplodedNode *generateNode(ProgramStateRef State, bool branch,
417 const CFGBlock *getTargetBlock(bool branch) const {
418 return branch ? DstT : DstF;
421 void markInfeasible(bool branch) {
423 InFeasibleTrue = true;
425 InFeasibleFalse = true;
428 bool isFeasible(bool branch) {
429 return branch ? !InFeasibleTrue : !InFeasibleFalse;
433 class IndirectGotoNodeBuilder {
436 const CFGBlock &DispatchBlock;
441 IndirectGotoNodeBuilder(ExplodedNode *pred, const CFGBlock *src,
442 const Expr *e, const CFGBlock *dispatch, CoreEngine* eng)
443 : Eng(*eng), Src(src), DispatchBlock(*dispatch), E(e), Pred(pred) {}
446 CFGBlock::const_succ_iterator I;
448 friend class IndirectGotoNodeBuilder;
449 iterator(CFGBlock::const_succ_iterator i) : I(i) {}
452 iterator &operator++() { ++I; return *this; }
453 bool operator!=(const iterator &X) const { return I != X.I; }
455 const LabelDecl *getLabel() const {
456 return llvm::cast<LabelStmt>((*I)->getLabel())->getDecl();
459 const CFGBlock *getBlock() const {
464 iterator begin() { return iterator(DispatchBlock.succ_begin()); }
465 iterator end() { return iterator(DispatchBlock.succ_end()); }
467 ExplodedNode *generateNode(const iterator &I,
468 ProgramStateRef State,
469 bool isSink = false);
471 const Expr *getTarget() const { return E; }
473 ProgramStateRef getState() const { return Pred->State; }
475 const LocationContext *getLocationContext() const {
476 return Pred->getLocationContext();
480 class SwitchNodeBuilder {
483 const Expr *Condition;
487 SwitchNodeBuilder(ExplodedNode *pred, const CFGBlock *src,
488 const Expr *condition, CoreEngine* eng)
489 : Eng(*eng), Src(src), Condition(condition), Pred(pred) {}
492 CFGBlock::const_succ_reverse_iterator I;
494 friend class SwitchNodeBuilder;
495 iterator(CFGBlock::const_succ_reverse_iterator i) : I(i) {}
498 iterator &operator++() { ++I; return *this; }
499 bool operator!=(const iterator &X) const { return I != X.I; }
500 bool operator==(const iterator &X) const { return I == X.I; }
502 const CaseStmt *getCase() const {
503 return llvm::cast<CaseStmt>((*I)->getLabel());
506 const CFGBlock *getBlock() const {
511 iterator begin() { return iterator(Src->succ_rbegin()+1); }
512 iterator end() { return iterator(Src->succ_rend()); }
514 const SwitchStmt *getSwitch() const {
515 return llvm::cast<SwitchStmt>(Src->getTerminator());
518 ExplodedNode *generateCaseStmtNode(const iterator &I,
519 ProgramStateRef State);
521 ExplodedNode *generateDefaultCaseNode(ProgramStateRef State,
522 bool isSink = false);
524 const Expr *getCondition() const { return Condition; }
526 ProgramStateRef getState() const { return Pred->State; }
528 const LocationContext *getLocationContext() const {
529 return Pred->getLocationContext();
533 } // end ento namespace
534 } // end clang namespace