ExprEngine.h revision 3682f1ea9c7fddc7dcbc590891158ba40f7fca16
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 CallEvent; 45class SimpleCall; 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 /// currStmt - The current block-level statement. 74 const Stmt *currStmt; 75 unsigned int currStmtIdx; 76 const NodeBuilderContext *currBldrCtx; 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(currBldrCtx); 130 return *currBldrCtx; 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 CallEvent *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 /// VisitGCCAsmStmt - Transfer function logic for inline asm. 287 void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 288 ExplodedNodeSet &Dst); 289 290 /// VisitMSAsmStmt - Transfer function logic for MS inline asm. 291 void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 292 ExplodedNodeSet &Dst); 293 294 /// VisitBlockExpr - Transfer function logic for BlockExprs. 295 void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 296 ExplodedNodeSet &Dst); 297 298 /// VisitBinaryOperator - Transfer function logic for binary operators. 299 void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred, 300 ExplodedNodeSet &Dst); 301 302 303 /// VisitCall - Transfer function for function calls. 304 void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, 305 ExplodedNodeSet &Dst); 306 307 /// VisitCast - Transfer function logic for all casts (implicit and explicit). 308 void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred, 309 ExplodedNodeSet &Dst); 310 311 /// VisitCompoundLiteralExpr - Transfer function logic for compound literals. 312 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, 313 ExplodedNode *Pred, ExplodedNodeSet &Dst); 314 315 /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs. 316 void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D, 317 ExplodedNode *Pred, ExplodedNodeSet &Dst); 318 319 /// VisitDeclStmt - Transfer function logic for DeclStmts. 320 void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 321 ExplodedNodeSet &Dst); 322 323 /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose 324 void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, 325 ExplodedNode *Pred, ExplodedNodeSet &Dst); 326 327 void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred, 328 ExplodedNodeSet &Dst); 329 330 /// VisitLogicalExpr - Transfer function logic for '&&', '||' 331 void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, 332 ExplodedNodeSet &Dst); 333 334 /// VisitMemberExpr - Transfer function for member expressions. 335 void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 336 ExplodedNodeSet &Dst); 337 338 /// Transfer function logic for ObjCAtSynchronizedStmts. 339 void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, 340 ExplodedNode *Pred, ExplodedNodeSet &Dst); 341 342 /// Transfer function logic for computing the lvalue of an Objective-C ivar. 343 void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, 344 ExplodedNodeSet &Dst); 345 346 /// VisitObjCForCollectionStmt - Transfer function logic for 347 /// ObjCForCollectionStmt. 348 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, 349 ExplodedNode *Pred, ExplodedNodeSet &Dst); 350 351 void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, 352 ExplodedNodeSet &Dst); 353 354 /// VisitReturnStmt - Transfer function logic for return statements. 355 void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, 356 ExplodedNodeSet &Dst); 357 358 /// VisitOffsetOfExpr - Transfer function for offsetof. 359 void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, 360 ExplodedNodeSet &Dst); 361 362 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof. 363 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, 364 ExplodedNode *Pred, ExplodedNodeSet &Dst); 365 366 /// VisitUnaryOperator - Transfer function logic for unary operators. 367 void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred, 368 ExplodedNodeSet &Dst); 369 370 /// Handle ++ and -- (both pre- and post-increment). 371 void VisitIncrementDecrementOperator(const UnaryOperator* U, 372 ExplodedNode *Pred, 373 ExplodedNodeSet &Dst); 374 375 void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, 376 ExplodedNodeSet &Dst); 377 378 void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, 379 ExplodedNodeSet & Dst); 380 381 void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, 382 ExplodedNodeSet &Dst); 383 384 void VisitCXXDestructor(QualType ObjectType, 385 const MemRegion *Dest, const Stmt *S, 386 ExplodedNode *Pred, ExplodedNodeSet &Dst); 387 388 void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, 389 ExplodedNodeSet &Dst); 390 391 void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, 392 ExplodedNodeSet &Dst); 393 394 /// Create a C++ temporary object for an rvalue. 395 void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, 396 ExplodedNode *Pred, 397 ExplodedNodeSet &Dst); 398 399 /// evalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic 400 /// expressions of the form 'x != 0' and generate new nodes (stored in Dst) 401 /// with those assumptions. 402 void evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, 403 const Expr *Ex); 404 405 std::pair<const ProgramPointTag *, const ProgramPointTag*> 406 getEagerlyAssumeTags(); 407 408 SVal evalMinus(SVal X) { 409 return X.isValid() ? svalBuilder.evalMinus(cast<NonLoc>(X)) : X; 410 } 411 412 SVal evalComplement(SVal X) { 413 return X.isValid() ? svalBuilder.evalComplement(cast<NonLoc>(X)) : X; 414 } 415 416public: 417 418 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, 419 NonLoc L, NonLoc R, QualType T) { 420 return svalBuilder.evalBinOpNN(state, op, L, R, T); 421 } 422 423 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, 424 NonLoc L, SVal R, QualType T) { 425 return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(R), T) : R; 426 } 427 428 SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, 429 SVal LHS, SVal RHS, QualType T) { 430 return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T); 431 } 432 433protected: 434 /// evalBind - Handle the semantics of binding a value to a specific location. 435 /// This method is used by evalStore, VisitDeclStmt, and others. 436 void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred, 437 SVal location, SVal Val, bool atDeclInit = false, 438 const ProgramPoint *PP = 0); 439 440public: 441 // FIXME: 'tag' should be removed, and a LocationContext should be used 442 // instead. 443 // FIXME: Comment on the meaning of the arguments, when 'St' may not 444 // be the same as Pred->state, and when 'location' may not be the 445 // same as state->getLValue(Ex). 446 /// Simulate a read of the result of Ex. 447 void evalLoad(ExplodedNodeSet &Dst, 448 const Expr *NodeEx, /* Eventually will be a CFGStmt */ 449 const Expr *BoundExpr, 450 ExplodedNode *Pred, 451 ProgramStateRef St, 452 SVal location, 453 const ProgramPointTag *tag = 0, 454 QualType LoadTy = QualType()); 455 456 // FIXME: 'tag' should be removed, and a LocationContext should be used 457 // instead. 458 void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE, 459 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val, 460 const ProgramPointTag *tag = 0); 461 462 /// \brief Create a new state in which the call return value is binded to the 463 /// call origin expression. 464 ProgramStateRef bindReturnValue(const CallEvent &Call, 465 const LocationContext *LCtx, 466 ProgramStateRef State); 467 468 /// Evaluate a call, running pre- and post-call checks and allowing checkers 469 /// to be responsible for handling the evaluation of the call itself. 470 void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, 471 const CallEvent &Call); 472 473 /// \brief Default implementation of call evaluation. 474 void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred, 475 const CallEvent &Call); 476private: 477 void evalLoadCommon(ExplodedNodeSet &Dst, 478 const Expr *NodeEx, /* Eventually will be a CFGStmt */ 479 const Expr *BoundEx, 480 ExplodedNode *Pred, 481 ProgramStateRef St, 482 SVal location, 483 const ProgramPointTag *tag, 484 QualType LoadTy); 485 486 // FIXME: 'tag' should be removed, and a LocationContext should be used 487 // instead. 488 void evalLocation(ExplodedNodeSet &Dst, 489 const Stmt *NodeEx, /* This will eventually be a CFGStmt */ 490 const Stmt *BoundEx, 491 ExplodedNode *Pred, 492 ProgramStateRef St, SVal location, 493 const ProgramPointTag *tag, bool isLoad); 494 495 bool shouldInlineDecl(const Decl *D, ExplodedNode *Pred); 496 bool inlineCall(const CallEvent &Call, const Decl *D, NodeBuilder &Bldr, 497 ExplodedNode *Pred, ProgramStateRef State); 498 499 /// \brief Conservatively evaluate call by invalidating regions and binding 500 /// a conjured return value. 501 void conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr, 502 ExplodedNode *Pred, ProgramStateRef State); 503 504 /// \brief Either inline or process the call conservatively (or both), based 505 /// on DynamicDispatchBifurcation data. 506 void BifurcateCall(const MemRegion *BifurReg, 507 const CallEvent &Call, const Decl *D, NodeBuilder &Bldr, 508 ExplodedNode *Pred); 509 510 bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC); 511}; 512 513/// Traits for storing the call processing policy inside GDM. 514/// The GDM stores the corresponding CallExpr pointer. 515struct ReplayWithoutInlining{}; 516template <> 517struct ProgramStateTrait<ReplayWithoutInlining> : 518 public ProgramStatePartialTrait<void*> { 519 static void *GDMIndex() { static int index = 0; return &index; } 520}; 521 522} // end ento namespace 523 524} // end clang namespace 525 526#endif 527