CoreEngine.h revision 8ff5c41f2bde7ebbe568b4c15e59f14b8befae66
1//==- CoreEngine.h - Path-Sensitive Dataflow Engine ----------------*- C++ -*-// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines a generic engine for intraprocedural, path-sensitive, 11// dataflow analysis via graph reachability. 12// 13//===----------------------------------------------------------------------===// 14 15#ifndef LLVM_CLANG_GR_COREENGINE 16#define LLVM_CLANG_GR_COREENGINE 17 18#include "clang/AST/Expr.h" 19#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h" 20#include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h" 21#include "clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h" 22#include "llvm/ADT/OwningPtr.h" 23 24namespace clang { 25 26class ProgramPointTag; 27 28namespace ento { 29 30class NodeBuilder; 31 32//===----------------------------------------------------------------------===// 33/// CoreEngine - Implements the core logic of the graph-reachability 34/// analysis. It traverses the CFG and generates the ExplodedGraph. 35/// Program "states" are treated as opaque void pointers. 36/// The template class CoreEngine (which subclasses CoreEngine) 37/// provides the matching component to the engine that knows the actual types 38/// for states. Note that this engine only dispatches to transfer functions 39/// at the statement and block-level. The analyses themselves must implement 40/// any transfer function logic and the sub-expression level (if any). 41class CoreEngine { 42 friend class CommonNodeBuilder; 43 friend class NodeBuilder; 44 friend class StmtNodeBuilder; 45 friend class GenericNodeBuilderImpl; 46 friend class BranchNodeBuilder; 47 friend class IndirectGotoNodeBuilder; 48 friend class SwitchNodeBuilder; 49 friend class EndOfFunctionNodeBuilder; 50 friend class CallEnterNodeBuilder; 51 friend class CallExitNodeBuilder; 52 53public: 54 typedef std::vector<std::pair<BlockEdge, const ExplodedNode*> > 55 BlocksExhausted; 56 57 typedef std::vector<std::pair<const CFGBlock*, const ExplodedNode*> > 58 BlocksAborted; 59 60private: 61 62 SubEngine& SubEng; 63 64 /// G - The simulation graph. Each node is a (location,state) pair. 65 llvm::OwningPtr<ExplodedGraph> G; 66 67 /// WList - A set of queued nodes that need to be processed by the 68 /// worklist algorithm. It is up to the implementation of WList to decide 69 /// the order that nodes are processed. 70 WorkList* WList; 71 72 /// BCounterFactory - A factory object for created BlockCounter objects. 73 /// These are used to record for key nodes in the ExplodedGraph the 74 /// number of times different CFGBlocks have been visited along a path. 75 BlockCounter::Factory BCounterFactory; 76 77 /// The locations where we stopped doing work because we visited a location 78 /// too many times. 79 BlocksExhausted blocksExhausted; 80 81 /// The locations where we stopped because the engine aborted analysis, 82 /// usually because it could not reason about something. 83 BlocksAborted blocksAborted; 84 85 void generateNode(const ProgramPoint &Loc, 86 const ProgramState *State, 87 ExplodedNode *Pred); 88 89 void HandleBlockEdge(const BlockEdge &E, ExplodedNode *Pred); 90 void HandleBlockEntrance(const BlockEntrance &E, ExplodedNode *Pred); 91 void HandleBlockExit(const CFGBlock *B, ExplodedNode *Pred); 92 void HandlePostStmt(const CFGBlock *B, unsigned StmtIdx, ExplodedNode *Pred); 93 94 void HandleBranch(const Stmt *Cond, const Stmt *Term, const CFGBlock *B, 95 ExplodedNode *Pred); 96 void HandleCallEnter(const CallEnter &L, const CFGBlock *Block, 97 unsigned Index, ExplodedNode *Pred); 98 void HandleCallExit(const CallExit &L, ExplodedNode *Pred); 99 100private: 101 CoreEngine(const CoreEngine&); // Do not implement. 102 CoreEngine& operator=(const CoreEngine&); 103 104public: 105 /// Construct a CoreEngine object to analyze the provided CFG using 106 /// a DFS exploration of the exploded graph. 107 CoreEngine(SubEngine& subengine) 108 : SubEng(subengine), G(new ExplodedGraph()), 109 WList(WorkList::makeBFS()), 110 BCounterFactory(G->getAllocator()) {} 111 112 /// Construct a CoreEngine object to analyze the provided CFG and to 113 /// use the provided worklist object to execute the worklist algorithm. 114 /// The CoreEngine object assumes ownership of 'wlist'. 115 CoreEngine(WorkList* wlist, SubEngine& subengine) 116 : SubEng(subengine), G(new ExplodedGraph()), WList(wlist), 117 BCounterFactory(G->getAllocator()) {} 118 119 ~CoreEngine() { 120 delete WList; 121 } 122 123 /// getGraph - Returns the exploded graph. 124 ExplodedGraph& getGraph() { return *G.get(); } 125 126 /// takeGraph - Returns the exploded graph. Ownership of the graph is 127 /// transferred to the caller. 128 ExplodedGraph* takeGraph() { return G.take(); } 129 130 /// ExecuteWorkList - Run the worklist algorithm for a maximum number of 131 /// steps. Returns true if there is still simulation state on the worklist. 132 bool ExecuteWorkList(const LocationContext *L, unsigned Steps, 133 const ProgramState *InitState); 134 void ExecuteWorkListWithInitialState(const LocationContext *L, 135 unsigned Steps, 136 const ProgramState *InitState, 137 ExplodedNodeSet &Dst); 138 139 // Functions for external checking of whether we have unfinished work 140 bool wasBlockAborted() const { return !blocksAborted.empty(); } 141 bool wasBlocksExhausted() const { return !blocksExhausted.empty(); } 142 bool hasWorkRemaining() const { return wasBlocksExhausted() || 143 WList->hasWork() || 144 wasBlockAborted(); } 145 146 /// Inform the CoreEngine that a basic block was aborted because 147 /// it could not be completely analyzed. 148 void addAbortedBlock(const ExplodedNode *node, const CFGBlock *block) { 149 blocksAborted.push_back(std::make_pair(block, node)); 150 } 151 152 WorkList *getWorkList() const { return WList; } 153 154 BlocksExhausted::const_iterator blocks_exhausted_begin() const { 155 return blocksExhausted.begin(); 156 } 157 BlocksExhausted::const_iterator blocks_exhausted_end() const { 158 return blocksExhausted.end(); 159 } 160 BlocksAborted::const_iterator blocks_aborted_begin() const { 161 return blocksAborted.begin(); 162 } 163 BlocksAborted::const_iterator blocks_aborted_end() const { 164 return blocksAborted.end(); 165 } 166 167 /// Enqueue the results of the node builder onto the work list. 168 void enqueue(ExplodedNodeSet &NB); 169}; 170 171struct NodeBuilderContext { 172 CoreEngine &Eng; 173 const CFGBlock *Block; 174 ExplodedNode *ContextPred; 175 NodeBuilderContext(CoreEngine &E, const CFGBlock *B, ExplodedNode *N) 176 : Eng(E), Block(B), ContextPred(N) { assert(B); assert(!N->isSink()); } 177}; 178 179/// This is the simplest builder which generates nodes in the ExplodedGraph. 180class NodeBuilder { 181protected: 182 friend class StmtNodeBuilder; 183 184 const NodeBuilderContext &C; 185 186 /// Specifies if the builder results have been finalized. For example, if it 187 /// is set to false, autotransitions are yet to be generated. 188 bool Finalized; 189 190 bool HasGeneratedNodes; 191 192 /// \brief The frontier set - a set of nodes which need to be propagated after 193 /// the builder dies. 194 ExplodedNodeSet &Frontier; 195 196 BlockCounter getBlockCounter() const { return C.Eng.WList->getBlockCounter();} 197 198 /// Checkes if the results are ready. 199 virtual bool checkResults() { 200 if (!Finalized) 201 return false; 202 return true; 203 } 204 205 bool haveNoSinksInFrontier() { 206 for (iterator I = Frontier.begin(), E = Frontier.end(); I != E; ++I) { 207 if ((*I)->isSink()) 208 return false; 209 } 210 return true; 211 } 212 213 /// Allow subclasses to finalize results before result_begin() is executed. 214 virtual void finalizeResults() {} 215 216 ExplodedNode *generateNodeImpl(const ProgramPoint &PP, 217 const ProgramState *State, 218 ExplodedNode *Pred, 219 bool MarkAsSink = false); 220 221public: 222 NodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet, 223 const NodeBuilderContext &Ctx, bool F = true) 224 : C(Ctx), Finalized(F), HasGeneratedNodes(false), Frontier(DstSet) { 225 assert(DstSet.empty()); 226 Frontier.Add(SrcNode); 227 } 228 229 NodeBuilder(const ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet, 230 const NodeBuilderContext &Ctx, bool F = true) 231 : C(Ctx), Finalized(F), HasGeneratedNodes(false), Frontier(DstSet) { 232 assert(DstSet.empty()); 233 //assert(!SrcSet.empty()); 234 235 Frontier.insert(SrcSet); 236 237 assert(haveNoSinksInFrontier()); 238 } 239 240 virtual ~NodeBuilder() {} 241 242 /// \brief Generates a node in the ExplodedGraph. 243 /// 244 /// When a node is marked as sink, the exploration from the node is stopped - 245 /// the node becomes the last node on the path. 246 ExplodedNode *generateNode(const ProgramPoint &PP, 247 const ProgramState *State, 248 ExplodedNode *Pred, 249 bool MarkAsSink = false) { 250 return generateNodeImpl(PP, State, Pred, MarkAsSink); 251 } 252 253 // TODO: will get removed. 254 bool hasGeneratedNodes() const { 255 return HasGeneratedNodes; 256 } 257 258 const ExplodedNodeSet &getResults() { 259 finalizeResults(); 260 assert(checkResults()); 261 return Frontier; 262 } 263 264 typedef ExplodedNodeSet::iterator iterator; 265 /// \brief Iterators through the results frontier. 266 inline iterator begin() { 267 finalizeResults(); 268 assert(checkResults()); 269 return Frontier.begin(); 270 } 271 inline iterator end() { 272 finalizeResults(); 273 return Frontier.end(); 274 } 275 276 /// \brief Return the CFGBlock associated with this builder. 277 const CFGBlock *getBlock() const { return C.Block; } 278 279 const NodeBuilderContext &getContext() { return C; } 280 281 /// \brief Returns the number of times the current basic block has been 282 /// visited on the exploded graph path. 283 unsigned getCurrentBlockCount() const { 284 return getBlockCounter().getNumVisited( 285 C.ContextPred->getLocationContext()->getCurrentStackFrame(), 286 C.Block->getBlockID()); 287 } 288}; 289 290class CommonNodeBuilder { 291protected: 292 ExplodedNode *Pred; 293 CoreEngine& Eng; 294 295 CommonNodeBuilder(CoreEngine* E, ExplodedNode *P) : Pred(P), Eng(*E) {} 296 BlockCounter getBlockCounter() const { return Eng.WList->getBlockCounter(); } 297}; 298 299 300class StmtNodeBuilder: public NodeBuilder { 301 const unsigned Idx; 302 303public: 304 bool PurgingDeadSymbols; 305 bool BuildSinks; 306 // TODO: Remove the flag. We should be able to use the method in the parent. 307 bool hasGeneratedNode; 308 ProgramPoint::Kind PointKind; 309 const ProgramPointTag *Tag; 310 311 void GenerateAutoTransition(ExplodedNode *N); 312 313public: 314 StmtNodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet, 315 unsigned idx, const NodeBuilderContext &Ctx) 316 : NodeBuilder(SrcNode, DstSet, Ctx), Idx(idx), 317 PurgingDeadSymbols(false), BuildSinks(false), hasGeneratedNode(false), 318 PointKind(ProgramPoint::PostStmtKind), Tag(0) {} 319 320 ~StmtNodeBuilder(); 321 322 ExplodedNode *generateNode(const Stmt *S, 323 const ProgramState *St, 324 ExplodedNode *Pred, 325 ProgramPoint::Kind K, 326 const ProgramPointTag *tag = 0, 327 bool MarkAsSink = false) { 328 if (PurgingDeadSymbols) 329 K = ProgramPoint::PostPurgeDeadSymbolsKind; 330 331 const ProgramPoint &L = ProgramPoint::getProgramPoint(S, K, 332 Pred->getLocationContext(), tag ? tag : Tag); 333 return generateNodeImpl(L, St, Pred, MarkAsSink); 334 } 335 336 ExplodedNode *generateNode(const Stmt *S, 337 const ProgramState *St, 338 ExplodedNode *Pred, 339 const ProgramPointTag *tag = 0) { 340 return generateNode(S, St, Pred, PointKind, tag); 341 } 342 343 ExplodedNode *generateNode(const ProgramPoint &PP, 344 const ProgramState *State, 345 ExplodedNode *Pred) { 346 return generateNodeImpl(PP, State, Pred, false); 347 } 348 349 /// getStmt - Return the current block-level expression associated with 350 /// this builder. 351 const Stmt *getStmt() const { 352 const CFGStmt *CS = (*C.Block)[Idx].getAs<CFGStmt>(); 353 return CS ? CS->getStmt() : 0; 354 } 355 356 unsigned getIndex() const { return Idx; } 357 358 ExplodedNode *MakeNode(ExplodedNodeSet &Dst, 359 const Stmt *S, 360 ExplodedNode *Pred, 361 const ProgramState *St) { 362 return MakeNode(Dst, S, Pred, St, PointKind); 363 } 364 365 ExplodedNode *MakeNode(ExplodedNodeSet &Dst, 366 const Stmt *S, 367 ExplodedNode *Pred, 368 const ProgramState *St, 369 ProgramPoint::Kind K); 370 371 ExplodedNode *MakeSinkNode(ExplodedNodeSet &Dst, 372 const Stmt *S, 373 ExplodedNode *Pred, 374 const ProgramState *St) { 375 bool Tmp = BuildSinks; 376 BuildSinks = true; 377 ExplodedNode *N = MakeNode(Dst, S, Pred, St); 378 BuildSinks = Tmp; 379 return N; 380 } 381 382 void takeNodes(const ExplodedNodeSet &S) { 383 for (ExplodedNodeSet::iterator I = S.begin(), E = S.end(); I != E; ++I ) 384 Frontier.erase(*I); 385 } 386 387 void takeNodes(ExplodedNode *N) { 388 Frontier.erase(N); 389 } 390 391 void addNodes(const ExplodedNodeSet &S) { 392 Frontier.insert(S); 393 } 394 395 void addNodes(ExplodedNode *N) { 396 Frontier.Add(N); 397 } 398 399}; 400 401class BranchNodeBuilder: public NodeBuilder { 402 const CFGBlock *DstT; 403 const CFGBlock *DstF; 404 405 bool InFeasibleTrue; 406 bool InFeasibleFalse; 407 408public: 409 BranchNodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet, 410 const NodeBuilderContext &C, 411 const CFGBlock *dstT, const CFGBlock *dstF) 412 : NodeBuilder(SrcNode, DstSet, C), DstT(dstT), DstF(dstF), 413 InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) {} 414 415 BranchNodeBuilder(const ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet, 416 const NodeBuilderContext &C, 417 const CFGBlock *dstT, const CFGBlock *dstF) 418 : NodeBuilder(SrcSet, DstSet, C), DstT(dstT), DstF(dstF), 419 InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) {} 420 421 ExplodedNode *generateNode(const ProgramState *State, bool branch, 422 ExplodedNode *Pred); 423 424 const CFGBlock *getTargetBlock(bool branch) const { 425 return branch ? DstT : DstF; 426 } 427 428 void markInfeasible(bool branch) { 429 if (branch) 430 InFeasibleTrue = true; 431 else 432 InFeasibleFalse = true; 433 } 434 435 bool isFeasible(bool branch) { 436 return branch ? !InFeasibleTrue : !InFeasibleFalse; 437 } 438}; 439 440class IndirectGotoNodeBuilder { 441 CoreEngine& Eng; 442 const CFGBlock *Src; 443 const CFGBlock &DispatchBlock; 444 const Expr *E; 445 ExplodedNode *Pred; 446 447public: 448 IndirectGotoNodeBuilder(ExplodedNode *pred, const CFGBlock *src, 449 const Expr *e, const CFGBlock *dispatch, CoreEngine* eng) 450 : Eng(*eng), Src(src), DispatchBlock(*dispatch), E(e), Pred(pred) {} 451 452 class iterator { 453 CFGBlock::const_succ_iterator I; 454 455 friend class IndirectGotoNodeBuilder; 456 iterator(CFGBlock::const_succ_iterator i) : I(i) {} 457 public: 458 459 iterator &operator++() { ++I; return *this; } 460 bool operator!=(const iterator &X) const { return I != X.I; } 461 462 const LabelDecl *getLabel() const { 463 return llvm::cast<LabelStmt>((*I)->getLabel())->getDecl(); 464 } 465 466 const CFGBlock *getBlock() const { 467 return *I; 468 } 469 }; 470 471 iterator begin() { return iterator(DispatchBlock.succ_begin()); } 472 iterator end() { return iterator(DispatchBlock.succ_end()); } 473 474 ExplodedNode *generateNode(const iterator &I, 475 const ProgramState *State, 476 bool isSink = false); 477 478 const Expr *getTarget() const { return E; } 479 480 const ProgramState *getState() const { return Pred->State; } 481}; 482 483class SwitchNodeBuilder { 484 CoreEngine& Eng; 485 const CFGBlock *Src; 486 const Expr *Condition; 487 ExplodedNode *Pred; 488 489public: 490 SwitchNodeBuilder(ExplodedNode *pred, const CFGBlock *src, 491 const Expr *condition, CoreEngine* eng) 492 : Eng(*eng), Src(src), Condition(condition), Pred(pred) {} 493 494 class iterator { 495 CFGBlock::const_succ_reverse_iterator I; 496 497 friend class SwitchNodeBuilder; 498 iterator(CFGBlock::const_succ_reverse_iterator i) : I(i) {} 499 500 public: 501 iterator &operator++() { ++I; return *this; } 502 bool operator!=(const iterator &X) const { return I != X.I; } 503 bool operator==(const iterator &X) const { return I == X.I; } 504 505 const CaseStmt *getCase() const { 506 return llvm::cast<CaseStmt>((*I)->getLabel()); 507 } 508 509 const CFGBlock *getBlock() const { 510 return *I; 511 } 512 }; 513 514 iterator begin() { return iterator(Src->succ_rbegin()+1); } 515 iterator end() { return iterator(Src->succ_rend()); } 516 517 const SwitchStmt *getSwitch() const { 518 return llvm::cast<SwitchStmt>(Src->getTerminator()); 519 } 520 521 ExplodedNode *generateCaseStmtNode(const iterator &I, 522 const ProgramState *State); 523 524 ExplodedNode *generateDefaultCaseNode(const ProgramState *State, 525 bool isSink = false); 526 527 const Expr *getCondition() const { return Condition; } 528 529 const ProgramState *getState() const { return Pred->State; } 530}; 531 532class GenericNodeBuilderImpl { 533protected: 534 CoreEngine &engine; 535 ExplodedNode *pred; 536 ProgramPoint pp; 537 SmallVector<ExplodedNode*, 2> sinksGenerated; 538 539 ExplodedNode *generateNodeImpl(const ProgramState *state, 540 ExplodedNode *pred, 541 ProgramPoint programPoint, 542 bool asSink); 543 544 GenericNodeBuilderImpl(CoreEngine &eng, ExplodedNode *pr, ProgramPoint p) 545 : engine(eng), pred(pr), pp(p), hasGeneratedNode(false) {} 546 547public: 548 bool hasGeneratedNode; 549 550 WorkList &getWorkList() { return *engine.WList; } 551 552 ExplodedNode *getPredecessor() const { return pred; } 553 554 BlockCounter getBlockCounter() const { 555 return engine.WList->getBlockCounter(); 556 } 557 558 const SmallVectorImpl<ExplodedNode*> &sinks() const { 559 return sinksGenerated; 560 } 561}; 562 563template <typename PP_T> 564class GenericNodeBuilder : public GenericNodeBuilderImpl { 565public: 566 GenericNodeBuilder(CoreEngine &eng, ExplodedNode *pr, const PP_T &p) 567 : GenericNodeBuilderImpl(eng, pr, p) {} 568 569 ExplodedNode *generateNode(const ProgramState *state, ExplodedNode *pred, 570 const ProgramPointTag *tag, bool asSink) { 571 return generateNodeImpl(state, pred, cast<PP_T>(pp).withTag(tag), 572 asSink); 573 } 574 575 const PP_T &getProgramPoint() const { return cast<PP_T>(pp); } 576}; 577 578class EndOfFunctionNodeBuilder : public CommonNodeBuilder { 579 const CFGBlock &B; 580 const ProgramPointTag *Tag; 581 582public: 583 bool hasGeneratedNode; 584 585public: 586 EndOfFunctionNodeBuilder(const CFGBlock *b, ExplodedNode *N, CoreEngine* e, 587 const ProgramPointTag *tag = 0) 588 : CommonNodeBuilder(e, N), B(*b), Tag(tag), hasGeneratedNode(false) {} 589 590 ~EndOfFunctionNodeBuilder(); 591 592 EndOfFunctionNodeBuilder withCheckerTag(const ProgramPointTag *tag) { 593 return EndOfFunctionNodeBuilder(&B, Pred, &Eng, tag); 594 } 595 596 WorkList &getWorkList() { return *Eng.WList; } 597 598 ExplodedNode *getPredecessor() const { return Pred; } 599 600 unsigned getCurrentBlockCount() const { 601 return getBlockCounter().getNumVisited( 602 Pred->getLocationContext()->getCurrentStackFrame(), 603 B.getBlockID()); 604 } 605 606 ExplodedNode *generateNode(const ProgramState *State, 607 ExplodedNode *P = 0, 608 const ProgramPointTag *tag = 0); 609 610 void GenerateCallExitNode(const ProgramState *state); 611 612 const CFGBlock *getBlock() const { return &B; } 613 614 const ProgramState *getState() const { 615 return getPredecessor()->getState(); 616 } 617}; 618 619class CallEnterNodeBuilder { 620 CoreEngine &Eng; 621 622 const ExplodedNode *Pred; 623 624 // The call site. For implicit automatic object dtor, this is the trigger 625 // statement. 626 const Stmt *CE; 627 628 // The context of the callee. 629 const StackFrameContext *CalleeCtx; 630 631 // The parent block of the CallExpr. 632 const CFGBlock *Block; 633 634 // The CFGBlock index of the CallExpr. 635 unsigned Index; 636 637public: 638 CallEnterNodeBuilder(CoreEngine &eng, const ExplodedNode *pred, 639 const Stmt *s, const StackFrameContext *callee, 640 const CFGBlock *blk, unsigned idx) 641 : Eng(eng), Pred(pred), CE(s), CalleeCtx(callee), Block(blk), Index(idx) {} 642 643 const ProgramState *getState() const { return Pred->getState(); } 644 645 const LocationContext *getLocationContext() const { 646 return Pred->getLocationContext(); 647 } 648 649 const Stmt *getCallExpr() const { return CE; } 650 651 const StackFrameContext *getCalleeContext() const { return CalleeCtx; } 652 653 const CFGBlock *getBlock() const { return Block; } 654 655 unsigned getIndex() const { return Index; } 656 657 void generateNode(const ProgramState *state); 658}; 659 660class CallExitNodeBuilder { 661 CoreEngine &Eng; 662 const ExplodedNode *Pred; 663 664public: 665 CallExitNodeBuilder(CoreEngine &eng, const ExplodedNode *pred) 666 : Eng(eng), Pred(pred) {} 667 668 const ExplodedNode *getPredecessor() const { return Pred; } 669 670 const ProgramState *getState() const { return Pred->getState(); } 671 672 void generateNode(const ProgramState *state); 673}; 674 675} // end GR namespace 676 677} // end clang namespace 678 679#endif 680