ExprEngine.h revision 0b3ade86a1c60cf0c7b56aa238aff458eb7f5974
1//===-- ExprEngine.h - Path-Sensitive Expression-Level Dataflow ---*- 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 meta-engine for path-sensitive dataflow analysis that 11// is built on CoreEngine, but provides the boilerplate to execute transfer 12// functions and build the ExplodedGraph at the expression level. 13// 14//===----------------------------------------------------------------------===// 15 16#ifndef LLVM_CLANG_GR_EXPRENGINE 17#define LLVM_CLANG_GR_EXPRENGINE 18 19#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 20#include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h" 21#include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h" 22#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 23#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 24#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 25#include "clang/AST/Expr.h" 26#include "clang/AST/Type.h" 27 28namespace clang { 29 30class AnalysisDeclContextManager; 31class CXXCatchStmt; 32class CXXConstructExpr; 33class CXXDeleteExpr; 34class CXXNewExpr; 35class CXXTemporaryObjectExpr; 36class CXXThisExpr; 37class MaterializeTemporaryExpr; 38class ObjCAtSynchronizedStmt; 39class ObjCForCollectionStmt; 40 41namespace ento { 42 43class AnalysisManager; 44class CallOrObjCMessage; 45class ObjCMessage; 46 47class ExprEngine : public SubEngine { 48 AnalysisManager &AMgr; 49 50 AnalysisDeclContextManager &AnalysisDeclContexts; 51 52 CoreEngine Engine; 53 54 /// G - the simulation graph. 55 ExplodedGraph& G; 56 57 /// StateMgr - Object that manages the data for all created states. 58 ProgramStateManager StateMgr; 59 60 /// SymMgr - Object that manages the symbol information. 61 SymbolManager& SymMgr; 62 63 /// svalBuilder - SValBuilder object that creates SVals from expressions. 64 SValBuilder &svalBuilder; 65 66 /// EntryNode - The immediate predecessor node. 67 ExplodedNode *EntryNode; 68 69 /// CleanedState - The state for EntryNode "cleaned" of all dead 70 /// variables and symbols (as determined by a liveness analysis). 71 ProgramStateRef CleanedState; 72 73 /// currentStmt - The current block-level statement. 74 const Stmt *currentStmt; 75 unsigned int currentStmtIdx; 76 const NodeBuilderContext *currentBuilderContext; 77 78 /// Obj-C Class Identifiers. 79 IdentifierInfo* NSExceptionII; 80 81 /// Obj-C Selectors. 82 Selector* NSExceptionInstanceRaiseSelectors; 83 Selector RaiseSel; 84 85 /// Whether or not GC is enabled in this analysis. 86 bool ObjCGCEnabled; 87 88 /// The BugReporter associated with this engine. It is important that 89 /// this object be placed at the very end of member variables so that its 90 /// destructor is called before the rest of the ExprEngine is destroyed. 91 GRBugReporter BR; 92 93public: 94 ExprEngine(AnalysisManager &mgr, bool gcEnabled, 95 SetOfConstDecls *VisitedCallees, 96 FunctionSummariesTy *FS); 97 98 ~ExprEngine(); 99 100 /// Returns true if there is still simulation state on the worklist. 101 bool ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) { 102 return Engine.ExecuteWorkList(L, Steps, 0); 103 } 104 105 /// Execute the work list with an initial state. Nodes that reaches the exit 106 /// of the function are added into the Dst set, which represent the exit 107 /// state of the function call. Returns true if there is still simulation 108 /// state on the worklist. 109 bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps, 110 ProgramStateRef InitState, 111 ExplodedNodeSet &Dst) { 112 return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst); 113 } 114 115 /// getContext - Return the ASTContext associated with this analysis. 116 ASTContext &getContext() const { return AMgr.getASTContext(); } 117 118 virtual AnalysisManager &getAnalysisManager() { return AMgr; } 119 120 CheckerManager &getCheckerManager() const { 121 return *AMgr.getCheckerManager(); 122 } 123 124 SValBuilder &getSValBuilder() { return svalBuilder; } 125 126 BugReporter& getBugReporter() { return BR; } 127 128 const NodeBuilderContext &getBuilderContext() { 129 assert(currentBuilderContext); 130 return *currentBuilderContext; 131 } 132 133 bool isObjCGCEnabled() { return ObjCGCEnabled; } 134 135 const Stmt *getStmt() const; 136 137 void GenerateAutoTransition(ExplodedNode *N); 138 void enqueueEndOfPath(ExplodedNodeSet &S); 139 void GenerateCallExitNode(ExplodedNode *N); 140 141 /// ViewGraph - Visualize the ExplodedGraph created by executing the 142 /// simulation. 143 void ViewGraph(bool trim = false); 144 145 void ViewGraph(ExplodedNode** Beg, ExplodedNode** End); 146 147 /// getInitialState - Return the initial state used for the root vertex 148 /// in the ExplodedGraph. 149 ProgramStateRef getInitialState(const LocationContext *InitLoc); 150 151 ExplodedGraph& getGraph() { return G; } 152 const ExplodedGraph& getGraph() const { return G; } 153 154 /// \brief Run the analyzer's garbage collection - remove dead symbols and 155 /// bindings. 156 /// 157 /// \param Node - The predecessor node, from which the processing should 158 /// start. 159 /// \param Out - The returned set of output nodes. 160 /// \param ReferenceStmt - Run garbage collection using the symbols, 161 /// which are live before the given statement. 162 /// \param LC - The location context of the ReferenceStmt. 163 /// \param DiagnosticStmt - the statement used to associate the diagnostic 164 /// message, if any warnings should occur while removing the dead (leaks 165 /// are usually reported here). 166 /// \param K - In some cases it is possible to use PreStmt kind. (Do 167 /// not use it unless you know what you are doing.) 168 void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out, 169 const Stmt *ReferenceStmt, const LocationContext *LC, 170 const Stmt *DiagnosticStmt, 171 ProgramPoint::Kind K = ProgramPoint::PreStmtPurgeDeadSymbolsKind); 172 173 /// processCFGElement - Called by CoreEngine. Used to generate new successor 174 /// nodes by processing the 'effects' of a CFG element. 175 void processCFGElement(const CFGElement E, ExplodedNode *Pred, 176 unsigned StmtIdx, NodeBuilderContext *Ctx); 177 178 void ProcessStmt(const CFGStmt S, ExplodedNode *Pred); 179 180 void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred); 181 182 void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred); 183 184 void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D, 185 ExplodedNode *Pred, ExplodedNodeSet &Dst); 186 void ProcessBaseDtor(const CFGBaseDtor D, 187 ExplodedNode *Pred, ExplodedNodeSet &Dst); 188 void ProcessMemberDtor(const CFGMemberDtor D, 189 ExplodedNode *Pred, ExplodedNodeSet &Dst); 190 void ProcessTemporaryDtor(const CFGTemporaryDtor D, 191 ExplodedNode *Pred, ExplodedNodeSet &Dst); 192 193 /// Called by CoreEngine when processing the entrance of a CFGBlock. 194 virtual void processCFGBlockEntrance(const BlockEdge &L, 195 NodeBuilderWithSinks &nodeBuilder); 196 197 /// ProcessBranch - Called by CoreEngine. Used to generate successor 198 /// nodes by processing the 'effects' of a branch condition. 199 void processBranch(const Stmt *Condition, const Stmt *Term, 200 NodeBuilderContext& BuilderCtx, 201 ExplodedNode *Pred, 202 ExplodedNodeSet &Dst, 203 const CFGBlock *DstT, 204 const CFGBlock *DstF); 205 206 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 207 /// nodes by processing the 'effects' of a computed goto jump. 208 void processIndirectGoto(IndirectGotoNodeBuilder& builder); 209 210 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 211 /// nodes by processing the 'effects' of a switch statement. 212 void processSwitch(SwitchNodeBuilder& builder); 213 214 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 215 /// nodes when the control reaches the end of a function. 216 void processEndOfFunction(NodeBuilderContext& BC); 217 218 /// Generate the entry node of the callee. 219 void processCallEnter(CallEnter CE, ExplodedNode *Pred); 220 221 /// Generate the sequence of nodes that simulate the call exit and the post 222 /// visit for CallExpr. 223 void processCallExit(ExplodedNode *Pred); 224 225 /// Called by CoreEngine when the analysis worklist has terminated. 226 void processEndWorklist(bool hasWorkRemaining); 227 228 /// evalAssume - Callback function invoked by the ConstraintManager when 229 /// making assumptions about state values. 230 ProgramStateRef processAssume(ProgramStateRef state, SVal cond,bool assumption); 231 232 /// wantsRegionChangeUpdate - Called by ProgramStateManager to determine if a 233 /// region change should trigger a processRegionChanges update. 234 bool wantsRegionChangeUpdate(ProgramStateRef state); 235 236 /// processRegionChanges - Called by ProgramStateManager whenever a change is made 237 /// to the store. Used to update checkers that track region values. 238 ProgramStateRef 239 processRegionChanges(ProgramStateRef state, 240 const StoreManager::InvalidatedSymbols *invalidated, 241 ArrayRef<const MemRegion *> ExplicitRegions, 242 ArrayRef<const MemRegion *> Regions, 243 const CallOrObjCMessage *Call); 244 245 /// printState - Called by ProgramStateManager to print checker-specific data. 246 void printState(raw_ostream &Out, ProgramStateRef State, 247 const char *NL, const char *Sep); 248 249 virtual ProgramStateManager& getStateManager() { return StateMgr; } 250 251 StoreManager& getStoreManager() { return StateMgr.getStoreManager(); } 252 253 ConstraintManager& getConstraintManager() { 254 return StateMgr.getConstraintManager(); 255 } 256 257 // FIXME: Remove when we migrate over to just using SValBuilder. 258 BasicValueFactory& getBasicVals() { 259 return StateMgr.getBasicVals(); 260 } 261 const BasicValueFactory& getBasicVals() const { 262 return StateMgr.getBasicVals(); 263 } 264 265 // FIXME: Remove when we migrate over to just using ValueManager. 266 SymbolManager& getSymbolManager() { return SymMgr; } 267 const SymbolManager& getSymbolManager() const { return SymMgr; } 268 269 // Functions for external checking of whether we have unfinished work 270 bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); } 271 bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); } 272 bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); } 273 274 const CoreEngine &getCoreEngine() const { return Engine; } 275 276public: 277 /// Visit - Transfer function logic for all statements. Dispatches to 278 /// other functions that handle specific kinds of statements. 279 void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst); 280 281 /// VisitArraySubscriptExpr - Transfer function for array accesses. 282 void VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *Ex, 283 ExplodedNode *Pred, 284 ExplodedNodeSet &Dst); 285 286 /// VisitAsmStmt - Transfer function logic for inline asm. 287 void VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst); 288 289 /// VisitBlockExpr - Transfer function logic for BlockExprs. 290 void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 291 ExplodedNodeSet &Dst); 292 293 /// VisitBinaryOperator - Transfer function logic for binary operators. 294 void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred, 295 ExplodedNodeSet &Dst); 296 297 298 /// VisitCall - Transfer function for function calls. 299 void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, 300 ExplodedNodeSet &Dst); 301 302 /// VisitCast - Transfer function logic for all casts (implicit and explicit). 303 void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred, 304 ExplodedNodeSet &Dst); 305 306 /// VisitCompoundLiteralExpr - Transfer function logic for compound literals. 307 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, 308 ExplodedNode *Pred, ExplodedNodeSet &Dst); 309 310 /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs. 311 void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D, 312 ExplodedNode *Pred, ExplodedNodeSet &Dst); 313 314 /// VisitDeclStmt - Transfer function logic for DeclStmts. 315 void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 316 ExplodedNodeSet &Dst); 317 318 /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose 319 void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, 320 ExplodedNode *Pred, ExplodedNodeSet &Dst); 321 322 void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred, 323 ExplodedNodeSet &Dst); 324 325 /// VisitLogicalExpr - Transfer function logic for '&&', '||' 326 void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, 327 ExplodedNodeSet &Dst); 328 329 /// VisitMemberExpr - Transfer function for member expressions. 330 void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 331 ExplodedNodeSet &Dst); 332 333 /// Transfer function logic for ObjCAtSynchronizedStmts. 334 void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, 335 ExplodedNode *Pred, ExplodedNodeSet &Dst); 336 337 /// Transfer function logic for computing the lvalue of an Objective-C ivar. 338 void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, 339 ExplodedNodeSet &Dst); 340 341 /// VisitObjCForCollectionStmt - Transfer function logic for 342 /// ObjCForCollectionStmt. 343 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, 344 ExplodedNode *Pred, ExplodedNodeSet &Dst); 345 346 void VisitObjCMessage(const ObjCMessage &msg, ExplodedNode *Pred, 347 ExplodedNodeSet &Dst); 348 349 /// VisitReturnStmt - Transfer function logic for return statements. 350 void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, 351 ExplodedNodeSet &Dst); 352 353 /// VisitOffsetOfExpr - Transfer function for offsetof. 354 void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, 355 ExplodedNodeSet &Dst); 356 357 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof. 358 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, 359 ExplodedNode *Pred, ExplodedNodeSet &Dst); 360 361 /// VisitUnaryOperator - Transfer function logic for unary operators. 362 void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred, 363 ExplodedNodeSet &Dst); 364 365 /// Handle ++ and -- (both pre- and post-increment). 366 void VisitIncrementDecrementOperator(const UnaryOperator* U, 367 ExplodedNode *Pred, 368 ExplodedNodeSet &Dst); 369 370 void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, 371 ExplodedNodeSet &Dst); 372 373 void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, 374 ExplodedNodeSet & Dst); 375 376 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *expr, 377 ExplodedNode *Pred, ExplodedNodeSet &Dst); 378 379 void VisitCXXConstructExpr(const CXXConstructExpr *E, const MemRegion *Dest, 380 ExplodedNode *Pred, ExplodedNodeSet &Dst); 381 382 void VisitCXXDestructor(const CXXDestructorDecl *DD, 383 const MemRegion *Dest, const Stmt *S, 384 ExplodedNode *Pred, ExplodedNodeSet &Dst); 385 386 void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, 387 ExplodedNodeSet &Dst); 388 389 void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, 390 ExplodedNodeSet &Dst); 391 392 /// Create a C++ temporary object for an rvalue. 393 void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, 394 ExplodedNode *Pred, 395 ExplodedNodeSet &Dst); 396 397 /// Synthesize CXXThisRegion. 398 const CXXThisRegion *getCXXThisRegion(const CXXRecordDecl *RD, 399 const StackFrameContext *SFC); 400 401 const CXXThisRegion *getCXXThisRegion(const CXXMethodDecl *decl, 402 const StackFrameContext *frameCtx); 403 404 /// evalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic 405 /// expressions of the form 'x != 0' and generate new nodes (stored in Dst) 406 /// with those assumptions. 407 void evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, 408 const Expr *Ex); 409 410 std::pair<const ProgramPointTag *, const ProgramPointTag*> 411 getEagerlyAssumeTags(); 412 413 SVal evalMinus(SVal X) { 414 return X.isValid() ? svalBuilder.evalMinus(cast<NonLoc>(X)) : X; 415 } 416 417 SVal evalComplement(SVal X) { 418 return X.isValid() ? svalBuilder.evalComplement(cast<NonLoc>(X)) : X; 419 } 420 421public: 422 423 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, 424 NonLoc L, NonLoc R, QualType T) { 425 return svalBuilder.evalBinOpNN(state, op, L, R, T); 426 } 427 428 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, 429 NonLoc L, SVal R, QualType T) { 430 return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(R), T) : R; 431 } 432 433 SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, 434 SVal LHS, SVal RHS, QualType T) { 435 return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T); 436 } 437 438protected: 439 void evalObjCMessage(StmtNodeBuilder &Bldr, const ObjCMessage &msg, 440 ExplodedNode *Pred, ProgramStateRef state, 441 bool GenSink); 442 443 ProgramStateRef invalidateArguments(ProgramStateRef State, 444 const CallOrObjCMessage &Call, 445 const LocationContext *LC); 446 447 ProgramStateRef MarkBranch(ProgramStateRef state, 448 const Stmt *Terminator, 449 const LocationContext *LCtx, 450 bool branchTaken); 451 452 /// evalBind - Handle the semantics of binding a value to a specific location. 453 /// This method is used by evalStore, VisitDeclStmt, and others. 454 void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred, 455 SVal location, SVal Val, bool atDeclInit = false); 456 457public: 458 // FIXME: 'tag' should be removed, and a LocationContext should be used 459 // instead. 460 // FIXME: Comment on the meaning of the arguments, when 'St' may not 461 // be the same as Pred->state, and when 'location' may not be the 462 // same as state->getLValue(Ex). 463 /// Simulate a read of the result of Ex. 464 void evalLoad(ExplodedNodeSet &Dst, 465 const Expr *NodeEx, /* Eventually will be a CFGStmt */ 466 const Expr *BoundExpr, 467 ExplodedNode *Pred, 468 ProgramStateRef St, 469 SVal location, 470 const ProgramPointTag *tag = 0, 471 QualType LoadTy = QualType()); 472 473 // FIXME: 'tag' should be removed, and a LocationContext should be used 474 // instead. 475 void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE, 476 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val, 477 const ProgramPointTag *tag = 0); 478private: 479 void evalLoadCommon(ExplodedNodeSet &Dst, 480 const Expr *NodeEx, /* Eventually will be a CFGStmt */ 481 const Expr *BoundEx, 482 ExplodedNode *Pred, 483 ProgramStateRef St, 484 SVal location, 485 const ProgramPointTag *tag, 486 QualType LoadTy); 487 488 // FIXME: 'tag' should be removed, and a LocationContext should be used 489 // instead. 490 void evalLocation(ExplodedNodeSet &Dst, 491 const Stmt *NodeEx, /* This will eventually be a CFGStmt */ 492 const Stmt *BoundEx, 493 ExplodedNode *Pred, 494 ProgramStateRef St, SVal location, 495 const ProgramPointTag *tag, bool isLoad); 496 497 bool shouldInlineDecl(const FunctionDecl *FD, ExplodedNode *Pred); 498 bool InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE, ExplodedNode *Pred); 499 500 bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC); 501}; 502 503/// Traits for storing the call processing policy inside GDM. 504/// The GDM stores the corresponding CallExpr pointer. 505struct ReplayWithoutInlining{}; 506template <> 507struct ProgramStateTrait<ReplayWithoutInlining> : 508 public ProgramStatePartialTrait<void*> { 509 static void *GDMIndex() { static int index = 0; return &index; } 510}; 511 512} // end ento namespace 513 514} // end clang namespace 515 516#endif 517