1 //===-- ExprEngine.h - Path-Sensitive Expression-Level Dataflow ---*- 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 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.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CLANG_GR_EXPRENGINE
17 #define LLVM_CLANG_GR_EXPRENGINE
19 #include "clang/Analysis/DomainSpecific/ObjCNoReturn.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
25 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/Type.h"
31 class AnalysisDeclContextManager;
33 class CXXConstructExpr;
36 class CXXTemporaryObjectExpr;
38 class MaterializeTemporaryExpr;
39 class ObjCAtSynchronizedStmt;
40 class ObjCForCollectionStmt;
44 class AnalysisManager;
48 class ExprEngine : public SubEngine {
49 AnalysisManager &AMgr;
51 AnalysisDeclContextManager &AnalysisDeclContexts;
55 /// G - the simulation graph.
58 /// StateMgr - Object that manages the data for all created states.
59 ProgramStateManager StateMgr;
61 /// SymMgr - Object that manages the symbol information.
62 SymbolManager& SymMgr;
64 /// svalBuilder - SValBuilder object that creates SVals from expressions.
65 SValBuilder &svalBuilder;
67 /// EntryNode - The immediate predecessor node.
68 ExplodedNode *EntryNode;
70 /// CleanedState - The state for EntryNode "cleaned" of all dead
71 /// variables and symbols (as determined by a liveness analysis).
72 ProgramStateRef CleanedState;
74 /// currStmt - The current block-level statement.
76 unsigned int currStmtIdx;
77 const NodeBuilderContext *currBldrCtx;
79 /// Helper object to determine if an Objective-C message expression
80 /// implicitly never returns.
81 ObjCNoReturn ObjCNoRet;
83 /// Whether or not GC is enabled in this analysis.
86 /// The BugReporter associated with this engine. It is important that
87 /// this object be placed at the very end of member variables so that its
88 /// destructor is called before the rest of the ExprEngine is destroyed.
91 /// The functions which have been analyzed through inlining. This is owned by
92 /// AnalysisConsumer. It can be null.
93 SetOfConstDecls *VisitedCallees;
96 ExprEngine(AnalysisManager &mgr, bool gcEnabled,
97 SetOfConstDecls *VisitedCalleesIn,
98 FunctionSummariesTy *FS);
102 /// Returns true if there is still simulation state on the worklist.
103 bool ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) {
104 return Engine.ExecuteWorkList(L, Steps, 0);
107 /// Execute the work list with an initial state. Nodes that reaches the exit
108 /// of the function are added into the Dst set, which represent the exit
109 /// state of the function call. Returns true if there is still simulation
110 /// state on the worklist.
111 bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps,
112 ProgramStateRef InitState,
113 ExplodedNodeSet &Dst) {
114 return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst);
117 /// getContext - Return the ASTContext associated with this analysis.
118 ASTContext &getContext() const { return AMgr.getASTContext(); }
120 virtual AnalysisManager &getAnalysisManager() { return AMgr; }
122 CheckerManager &getCheckerManager() const {
123 return *AMgr.getCheckerManager();
126 SValBuilder &getSValBuilder() { return svalBuilder; }
128 BugReporter& getBugReporter() { return BR; }
130 const NodeBuilderContext &getBuilderContext() {
135 bool isObjCGCEnabled() { return ObjCGCEnabled; }
137 const Stmt *getStmt() const;
139 void GenerateAutoTransition(ExplodedNode *N);
140 void enqueueEndOfPath(ExplodedNodeSet &S);
141 void GenerateCallExitNode(ExplodedNode *N);
143 /// ViewGraph - Visualize the ExplodedGraph created by executing the
145 void ViewGraph(bool trim = false);
147 void ViewGraph(ExplodedNode** Beg, ExplodedNode** End);
149 /// getInitialState - Return the initial state used for the root vertex
150 /// in the ExplodedGraph.
151 ProgramStateRef getInitialState(const LocationContext *InitLoc);
153 ExplodedGraph& getGraph() { return G; }
154 const ExplodedGraph& getGraph() const { return G; }
156 /// \brief Run the analyzer's garbage collection - remove dead symbols and
159 /// \param Node - The predecessor node, from which the processing should
161 /// \param Out - The returned set of output nodes.
162 /// \param ReferenceStmt - Run garbage collection using the symbols,
163 /// which are live before the given statement.
164 /// \param LC - The location context of the ReferenceStmt.
165 /// \param DiagnosticStmt - the statement used to associate the diagnostic
166 /// message, if any warnings should occur while removing the dead (leaks
167 /// are usually reported here).
168 /// \param K - In some cases it is possible to use PreStmt kind. (Do
169 /// not use it unless you know what you are doing.)
170 /// If the ReferenceStmt is NULL, everything is this and parent contexts is
172 /// If the stack frame context is NULL, everything on stack is considered
174 void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out,
175 const Stmt *ReferenceStmt, const StackFrameContext *LC,
176 const Stmt *DiagnosticStmt,
177 ProgramPoint::Kind K = ProgramPoint::PreStmtPurgeDeadSymbolsKind);
179 /// processCFGElement - Called by CoreEngine. Used to generate new successor
180 /// nodes by processing the 'effects' of a CFG element.
181 void processCFGElement(const CFGElement E, ExplodedNode *Pred,
182 unsigned StmtIdx, NodeBuilderContext *Ctx);
184 void ProcessStmt(const CFGStmt S, ExplodedNode *Pred);
186 void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred);
188 void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred);
190 void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D,
191 ExplodedNode *Pred, ExplodedNodeSet &Dst);
192 void ProcessBaseDtor(const CFGBaseDtor D,
193 ExplodedNode *Pred, ExplodedNodeSet &Dst);
194 void ProcessMemberDtor(const CFGMemberDtor D,
195 ExplodedNode *Pred, ExplodedNodeSet &Dst);
196 void ProcessTemporaryDtor(const CFGTemporaryDtor D,
197 ExplodedNode *Pred, ExplodedNodeSet &Dst);
199 /// Called by CoreEngine when processing the entrance of a CFGBlock.
200 virtual void processCFGBlockEntrance(const BlockEdge &L,
201 NodeBuilderWithSinks &nodeBuilder,
204 /// ProcessBranch - Called by CoreEngine. Used to generate successor
205 /// nodes by processing the 'effects' of a branch condition.
206 void processBranch(const Stmt *Condition, const Stmt *Term,
207 NodeBuilderContext& BuilderCtx,
209 ExplodedNodeSet &Dst,
210 const CFGBlock *DstT,
211 const CFGBlock *DstF);
213 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
214 /// nodes by processing the 'effects' of a computed goto jump.
215 void processIndirectGoto(IndirectGotoNodeBuilder& builder);
217 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
218 /// nodes by processing the 'effects' of a switch statement.
219 void processSwitch(SwitchNodeBuilder& builder);
221 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
222 /// nodes when the control reaches the end of a function.
223 void processEndOfFunction(NodeBuilderContext& BC,
226 /// Remove dead bindings/symbols before exiting a function.
227 void removeDeadOnEndOfFunction(NodeBuilderContext& BC,
229 ExplodedNodeSet &Dst);
231 /// Generate the entry node of the callee.
232 void processCallEnter(CallEnter CE, ExplodedNode *Pred);
234 /// Generate the sequence of nodes that simulate the call exit and the post
235 /// visit for CallExpr.
236 void processCallExit(ExplodedNode *Pred);
238 /// Called by CoreEngine when the analysis worklist has terminated.
239 void processEndWorklist(bool hasWorkRemaining);
241 /// evalAssume - Callback function invoked by the ConstraintManager when
242 /// making assumptions about state values.
243 ProgramStateRef processAssume(ProgramStateRef state, SVal cond,bool assumption);
245 /// wantsRegionChangeUpdate - Called by ProgramStateManager to determine if a
246 /// region change should trigger a processRegionChanges update.
247 bool wantsRegionChangeUpdate(ProgramStateRef state);
249 /// processRegionChanges - Called by ProgramStateManager whenever a change is made
250 /// to the store. Used to update checkers that track region values.
252 processRegionChanges(ProgramStateRef state,
253 const StoreManager::InvalidatedSymbols *invalidated,
254 ArrayRef<const MemRegion *> ExplicitRegions,
255 ArrayRef<const MemRegion *> Regions,
256 const CallEvent *Call);
258 /// printState - Called by ProgramStateManager to print checker-specific data.
259 void printState(raw_ostream &Out, ProgramStateRef State,
260 const char *NL, const char *Sep);
262 virtual ProgramStateManager& getStateManager() { return StateMgr; }
264 StoreManager& getStoreManager() { return StateMgr.getStoreManager(); }
266 ConstraintManager& getConstraintManager() {
267 return StateMgr.getConstraintManager();
270 // FIXME: Remove when we migrate over to just using SValBuilder.
271 BasicValueFactory& getBasicVals() {
272 return StateMgr.getBasicVals();
275 // FIXME: Remove when we migrate over to just using ValueManager.
276 SymbolManager& getSymbolManager() { return SymMgr; }
277 const SymbolManager& getSymbolManager() const { return SymMgr; }
279 // Functions for external checking of whether we have unfinished work
280 bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
281 bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
282 bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); }
284 const CoreEngine &getCoreEngine() const { return Engine; }
287 /// Visit - Transfer function logic for all statements. Dispatches to
288 /// other functions that handle specific kinds of statements.
289 void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst);
291 /// VisitArraySubscriptExpr - Transfer function for array accesses.
292 void VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *Ex,
294 ExplodedNodeSet &Dst);
296 /// VisitGCCAsmStmt - Transfer function logic for inline asm.
297 void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
298 ExplodedNodeSet &Dst);
300 /// VisitMSAsmStmt - Transfer function logic for MS inline asm.
301 void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
302 ExplodedNodeSet &Dst);
304 /// VisitBlockExpr - Transfer function logic for BlockExprs.
305 void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
306 ExplodedNodeSet &Dst);
308 /// VisitBinaryOperator - Transfer function logic for binary operators.
309 void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred,
310 ExplodedNodeSet &Dst);
313 /// VisitCall - Transfer function for function calls.
314 void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
315 ExplodedNodeSet &Dst);
317 /// VisitCast - Transfer function logic for all casts (implicit and explicit).
318 void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred,
319 ExplodedNodeSet &Dst);
321 /// VisitCompoundLiteralExpr - Transfer function logic for compound literals.
322 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
323 ExplodedNode *Pred, ExplodedNodeSet &Dst);
325 /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
326 void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D,
327 ExplodedNode *Pred, ExplodedNodeSet &Dst);
329 /// VisitDeclStmt - Transfer function logic for DeclStmts.
330 void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
331 ExplodedNodeSet &Dst);
333 /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
334 void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R,
335 ExplodedNode *Pred, ExplodedNodeSet &Dst);
337 void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred,
338 ExplodedNodeSet &Dst);
340 /// VisitLogicalExpr - Transfer function logic for '&&', '||'
341 void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
342 ExplodedNodeSet &Dst);
344 /// VisitMemberExpr - Transfer function for member expressions.
345 void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
346 ExplodedNodeSet &Dst);
348 /// Transfer function logic for ObjCAtSynchronizedStmts.
349 void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
350 ExplodedNode *Pred, ExplodedNodeSet &Dst);
352 /// Transfer function logic for computing the lvalue of an Objective-C ivar.
353 void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred,
354 ExplodedNodeSet &Dst);
356 /// VisitObjCForCollectionStmt - Transfer function logic for
357 /// ObjCForCollectionStmt.
358 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
359 ExplodedNode *Pred, ExplodedNodeSet &Dst);
361 void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred,
362 ExplodedNodeSet &Dst);
364 /// VisitReturnStmt - Transfer function logic for return statements.
365 void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred,
366 ExplodedNodeSet &Dst);
368 /// VisitOffsetOfExpr - Transfer function for offsetof.
369 void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred,
370 ExplodedNodeSet &Dst);
372 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
373 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
374 ExplodedNode *Pred, ExplodedNodeSet &Dst);
376 /// VisitUnaryOperator - Transfer function logic for unary operators.
377 void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred,
378 ExplodedNodeSet &Dst);
380 /// Handle ++ and -- (both pre- and post-increment).
381 void VisitIncrementDecrementOperator(const UnaryOperator* U,
383 ExplodedNodeSet &Dst);
385 void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred,
386 ExplodedNodeSet &Dst);
388 void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
389 ExplodedNodeSet & Dst);
391 void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred,
392 ExplodedNodeSet &Dst);
394 void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest,
395 const Stmt *S, bool IsBaseDtor,
396 ExplodedNode *Pred, ExplodedNodeSet &Dst);
398 void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
399 ExplodedNodeSet &Dst);
401 void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred,
402 ExplodedNodeSet &Dst);
404 /// Create a C++ temporary object for an rvalue.
405 void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
407 ExplodedNodeSet &Dst);
409 /// evalEagerlyAssumeBinOpBifurcation - Given the nodes in 'Src', eagerly assume symbolic
410 /// expressions of the form 'x != 0' and generate new nodes (stored in Dst)
411 /// with those assumptions.
412 void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
415 std::pair<const ProgramPointTag *, const ProgramPointTag*>
416 geteagerlyAssumeBinOpBifurcationTags();
418 SVal evalMinus(SVal X) {
419 return X.isValid() ? svalBuilder.evalMinus(cast<NonLoc>(X)) : X;
422 SVal evalComplement(SVal X) {
423 return X.isValid() ? svalBuilder.evalComplement(cast<NonLoc>(X)) : X;
428 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
429 NonLoc L, NonLoc R, QualType T) {
430 return svalBuilder.evalBinOpNN(state, op, L, R, T);
433 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
434 NonLoc L, SVal R, QualType T) {
435 return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(R), T) : R;
438 SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op,
439 SVal LHS, SVal RHS, QualType T) {
440 return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
444 /// evalBind - Handle the semantics of binding a value to a specific location.
445 /// This method is used by evalStore, VisitDeclStmt, and others.
446 void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred,
447 SVal location, SVal Val, bool atDeclInit = false,
448 const ProgramPoint *PP = 0);
451 // FIXME: 'tag' should be removed, and a LocationContext should be used
453 // FIXME: Comment on the meaning of the arguments, when 'St' may not
454 // be the same as Pred->state, and when 'location' may not be the
455 // same as state->getLValue(Ex).
456 /// Simulate a read of the result of Ex.
457 void evalLoad(ExplodedNodeSet &Dst,
458 const Expr *NodeEx, /* Eventually will be a CFGStmt */
459 const Expr *BoundExpr,
463 const ProgramPointTag *tag = 0,
464 QualType LoadTy = QualType());
466 // FIXME: 'tag' should be removed, and a LocationContext should be used
468 void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE,
469 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val,
470 const ProgramPointTag *tag = 0);
472 /// \brief Create a new state in which the call return value is binded to the
473 /// call origin expression.
474 ProgramStateRef bindReturnValue(const CallEvent &Call,
475 const LocationContext *LCtx,
476 ProgramStateRef State);
478 /// Evaluate a call, running pre- and post-call checks and allowing checkers
479 /// to be responsible for handling the evaluation of the call itself.
480 void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
481 const CallEvent &Call);
483 /// \brief Default implementation of call evaluation.
484 void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred,
485 const CallEvent &Call);
487 void evalLoadCommon(ExplodedNodeSet &Dst,
488 const Expr *NodeEx, /* Eventually will be a CFGStmt */
493 const ProgramPointTag *tag,
496 // FIXME: 'tag' should be removed, and a LocationContext should be used
498 void evalLocation(ExplodedNodeSet &Dst,
499 const Stmt *NodeEx, /* This will eventually be a CFGStmt */
502 ProgramStateRef St, SVal location,
503 const ProgramPointTag *tag, bool isLoad);
505 /// Count the stack depth and determine if the call is recursive.
506 void examineStackFrames(const Decl *D, const LocationContext *LCtx,
507 bool &IsRecursive, unsigned &StackDepth);
509 bool shouldInlineDecl(const Decl *D, ExplodedNode *Pred);
510 bool inlineCall(const CallEvent &Call, const Decl *D, NodeBuilder &Bldr,
511 ExplodedNode *Pred, ProgramStateRef State);
513 /// \brief Conservatively evaluate call by invalidating regions and binding
514 /// a conjured return value.
515 void conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr,
516 ExplodedNode *Pred, ProgramStateRef State);
518 /// \brief Either inline or process the call conservatively (or both), based
519 /// on DynamicDispatchBifurcation data.
520 void BifurcateCall(const MemRegion *BifurReg,
521 const CallEvent &Call, const Decl *D, NodeBuilder &Bldr,
524 bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC);
527 /// Traits for storing the call processing policy inside GDM.
528 /// The GDM stores the corresponding CallExpr pointer.
529 // FIXME: This does not use the nice trait macros because it must be accessible
530 // from multiple translation units.
531 struct ReplayWithoutInlining{};
533 struct ProgramStateTrait<ReplayWithoutInlining> :
534 public ProgramStatePartialTrait<void*> {
535 static void *GDMIndex() { static int index = 0; return &index; }
538 } // end ento namespace
540 } // end clang namespace