ExprEngine.h revision 422ab7a49a9a4252dbc6350e49d7a5708337b9c7
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/GRState.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/TransferFuncs.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/StmtObjC.h"
29
30namespace clang {
31
32class ObjCForCollectionStmt;
33
34namespace ento {
35
36class AnalysisManager;
37
38class ExprEngine : public SubEngine {
39  AnalysisManager &AMgr;
40
41  CoreEngine Engine;
42
43  /// G - the simulation graph.
44  ExplodedGraph& G;
45
46  /// Builder - The current StmtNodeBuilder which is used when building the
47  ///  nodes for a given statement.
48  StmtNodeBuilder* Builder;
49
50  /// StateMgr - Object that manages the data for all created states.
51  GRStateManager StateMgr;
52
53  /// SymMgr - Object that manages the symbol information.
54  SymbolManager& SymMgr;
55
56  /// svalBuilder - SValBuilder object that creates SVals from expressions.
57  SValBuilder &svalBuilder;
58
59  /// EntryNode - The immediate predecessor node.
60  ExplodedNode* EntryNode;
61
62  /// CleanedState - The state for EntryNode "cleaned" of all dead
63  ///  variables and symbols (as determined by a liveness analysis).
64  const GRState* CleanedState;
65
66  /// currentStmt - The current block-level statement.
67  const Stmt* currentStmt;
68
69  // Obj-C Class Identifiers.
70  IdentifierInfo* NSExceptionII;
71
72  // Obj-C Selectors.
73  Selector* NSExceptionInstanceRaiseSelectors;
74  Selector RaiseSel;
75
76  /// The BugReporter associated with this engine.  It is important that
77  ///  this object be placed at the very end of member variables so that its
78  ///  destructor is called before the rest of the ExprEngine is destroyed.
79  GRBugReporter BR;
80
81  llvm::OwningPtr<TransferFuncs> TF;
82
83public:
84  ExprEngine(AnalysisManager &mgr, TransferFuncs *tf);
85
86  ~ExprEngine();
87
88  void ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) {
89    Engine.ExecuteWorkList(L, Steps, 0);
90  }
91
92  /// Execute the work list with an initial state. Nodes that reaches the exit
93  /// of the function are added into the Dst set, which represent the exit
94  /// state of the function call.
95  void ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps,
96                                       const GRState *InitState,
97                                       ExplodedNodeSet &Dst) {
98    Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst);
99  }
100
101  /// getContext - Return the ASTContext associated with this analysis.
102  ASTContext& getContext() const { return AMgr.getASTContext(); }
103
104  virtual AnalysisManager &getAnalysisManager() { return AMgr; }
105
106  CheckerManager &getCheckerManager() const {
107    return *AMgr.getCheckerManager();
108  }
109
110  SValBuilder &getSValBuilder() { return svalBuilder; }
111
112  TransferFuncs& getTF() { return *TF; }
113
114  BugReporter& getBugReporter() { return BR; }
115
116  StmtNodeBuilder &getBuilder() { assert(Builder); return *Builder; }
117
118  // FIXME: Remove once TransferFuncs is no longer referenced.
119  void setTransferFunction(TransferFuncs* tf);
120
121  /// ViewGraph - Visualize the ExplodedGraph created by executing the
122  ///  simulation.
123  void ViewGraph(bool trim = false);
124
125  void ViewGraph(ExplodedNode** Beg, ExplodedNode** End);
126
127  /// getInitialState - Return the initial state used for the root vertex
128  ///  in the ExplodedGraph.
129  const GRState* getInitialState(const LocationContext *InitLoc);
130
131  ExplodedGraph& getGraph() { return G; }
132  const ExplodedGraph& getGraph() const { return G; }
133
134  /// processCFGElement - Called by CoreEngine. Used to generate new successor
135  ///  nodes by processing the 'effects' of a CFG element.
136  void processCFGElement(const CFGElement E, StmtNodeBuilder& builder);
137
138  void ProcessStmt(const CFGStmt S, StmtNodeBuilder &builder);
139
140  void ProcessInitializer(const CFGInitializer I, StmtNodeBuilder &builder);
141
142  void ProcessImplicitDtor(const CFGImplicitDtor D, StmtNodeBuilder &builder);
143
144  void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D,
145                            StmtNodeBuilder &builder);
146  void ProcessBaseDtor(const CFGBaseDtor D, StmtNodeBuilder &builder);
147  void ProcessMemberDtor(const CFGMemberDtor D, StmtNodeBuilder &builder);
148  void ProcessTemporaryDtor(const CFGTemporaryDtor D,
149                            StmtNodeBuilder &builder);
150
151  /// Called by CoreEngine when processing the entrance of a CFGBlock.
152  virtual void processCFGBlockEntrance(ExplodedNodeSet &dstNodes,
153                                GenericNodeBuilder<BlockEntrance> &nodeBuilder);
154
155  /// ProcessBranch - Called by CoreEngine.  Used to generate successor
156  ///  nodes by processing the 'effects' of a branch condition.
157  void processBranch(const Stmt* Condition, const Stmt* Term,
158                     BranchNodeBuilder& builder);
159
160  /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
161  ///  nodes by processing the 'effects' of a computed goto jump.
162  void processIndirectGoto(IndirectGotoNodeBuilder& builder);
163
164  /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
165  ///  nodes by processing the 'effects' of a switch statement.
166  void processSwitch(SwitchNodeBuilder& builder);
167
168  /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
169  ///  nodes when the control reaches the end of a function.
170  void processEndOfFunction(EndOfFunctionNodeBuilder& builder);
171
172  /// Generate the entry node of the callee.
173  void processCallEnter(CallEnterNodeBuilder &builder);
174
175  /// Generate the first post callsite node.
176  void processCallExit(CallExitNodeBuilder &builder);
177
178  /// Called by CoreEngine when the analysis worklist has terminated.
179  void processEndWorklist(bool hasWorkRemaining);
180
181  /// evalAssume - Callback function invoked by the ConstraintManager when
182  ///  making assumptions about state values.
183  const GRState *processAssume(const GRState *state, SVal cond,bool assumption);
184
185  /// wantsRegionChangeUpdate - Called by GRStateManager to determine if a
186  ///  region change should trigger a processRegionChanges update.
187  bool wantsRegionChangeUpdate(const GRState* state);
188
189  /// processRegionChanges - Called by GRStateManager whenever a change is made
190  ///  to the store. Used to update checkers that track region values.
191  const GRState* processRegionChanges(const GRState *state,
192                                      const MemRegion * const *Begin,
193                                      const MemRegion * const *End);
194
195  virtual GRStateManager& getStateManager() { return StateMgr; }
196
197  StoreManager& getStoreManager() { return StateMgr.getStoreManager(); }
198
199  ConstraintManager& getConstraintManager() {
200    return StateMgr.getConstraintManager();
201  }
202
203  // FIXME: Remove when we migrate over to just using SValBuilder.
204  BasicValueFactory& getBasicVals() {
205    return StateMgr.getBasicVals();
206  }
207  const BasicValueFactory& getBasicVals() const {
208    return StateMgr.getBasicVals();
209  }
210
211  // FIXME: Remove when we migrate over to just using ValueManager.
212  SymbolManager& getSymbolManager() { return SymMgr; }
213  const SymbolManager& getSymbolManager() const { return SymMgr; }
214
215  // Functions for external checking of whether we have unfinished work
216  bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
217  bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
218  bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); }
219
220  const CoreEngine &getCoreEngine() const { return Engine; }
221
222protected:
223  const GRState* GetState(ExplodedNode* N) {
224    return N == EntryNode ? CleanedState : N->getState();
225  }
226
227public:
228  ExplodedNode* MakeNode(ExplodedNodeSet& Dst, const Stmt* S,
229                         ExplodedNode* Pred, const GRState* St,
230                         ProgramPoint::Kind K = ProgramPoint::PostStmtKind,
231                         const void *tag = 0);
232
233  /// Visit - Transfer function logic for all statements.  Dispatches to
234  ///  other functions that handle specific kinds of statements.
235  void Visit(const Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst);
236
237  /// VisitArraySubscriptExpr - Transfer function for array accesses.
238  void VisitLvalArraySubscriptExpr(const ArraySubscriptExpr* Ex,
239                                   ExplodedNode* Pred,
240                                   ExplodedNodeSet& Dst);
241
242  /// VisitAsmStmt - Transfer function logic for inline asm.
243  void VisitAsmStmt(const AsmStmt* A, ExplodedNode* Pred, ExplodedNodeSet& Dst);
244
245  void VisitAsmStmtHelperOutputs(const AsmStmt* A,
246                                 AsmStmt::const_outputs_iterator I,
247                                 AsmStmt::const_outputs_iterator E,
248                                 ExplodedNode* Pred, ExplodedNodeSet& Dst);
249
250  void VisitAsmStmtHelperInputs(const AsmStmt* A,
251                                AsmStmt::const_inputs_iterator I,
252                                AsmStmt::const_inputs_iterator E,
253                                ExplodedNode* Pred, ExplodedNodeSet& Dst);
254
255  /// VisitBlockExpr - Transfer function logic for BlockExprs.
256  void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
257                      ExplodedNodeSet &Dst);
258
259  /// VisitBinaryOperator - Transfer function logic for binary operators.
260  void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode* Pred,
261                           ExplodedNodeSet& Dst);
262
263
264  /// VisitCall - Transfer function for function calls.
265  void VisitCallExpr(const CallExpr* CE, ExplodedNode* Pred,
266                     ExplodedNodeSet& Dst);
267
268  /// VisitCast - Transfer function logic for all casts (implicit and explicit).
269  void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred,
270                ExplodedNodeSet &Dst);
271
272  /// VisitCompoundLiteralExpr - Transfer function logic for compound literals.
273  void VisitCompoundLiteralExpr(const CompoundLiteralExpr* CL,
274                                ExplodedNode* Pred, ExplodedNodeSet& Dst);
275
276  /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
277  void VisitCommonDeclRefExpr(const Expr* DR, const NamedDecl *D,
278                              ExplodedNode* Pred, ExplodedNodeSet& Dst);
279
280  /// VisitDeclStmt - Transfer function logic for DeclStmts.
281  void VisitDeclStmt(const DeclStmt* DS, ExplodedNode* Pred,
282                     ExplodedNodeSet& Dst);
283
284  /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
285  void VisitGuardedExpr(const Expr* Ex, const Expr* L, const Expr* R,
286                        ExplodedNode* Pred, ExplodedNodeSet& Dst);
287
288  /// VisitCondInit - Transfer function for handling the initialization
289  ///  of a condition variable in an IfStmt, SwitchStmt, etc.
290  void VisitCondInit(const VarDecl *VD, const Stmt *S, ExplodedNode *Pred,
291                     ExplodedNodeSet& Dst);
292
293  void VisitInitListExpr(const InitListExpr* E, ExplodedNode* Pred,
294                         ExplodedNodeSet& Dst);
295
296  /// VisitLogicalExpr - Transfer function logic for '&&', '||'
297  void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode* Pred,
298                        ExplodedNodeSet& Dst);
299
300  /// VisitMemberExpr - Transfer function for member expressions.
301  void VisitMemberExpr(const MemberExpr* M, ExplodedNode* Pred,
302                           ExplodedNodeSet& Dst);
303
304  /// Transfer function logic for ObjCAtSynchronizedStmts.
305  void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
306                                   ExplodedNode *Pred, ExplodedNodeSet &Dst);
307
308  void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E,
309                                ExplodedNode *Pred, ExplodedNodeSet &Dst);
310
311  /// Transfer function logic for computing the lvalue of an Objective-C ivar.
312  void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr* DR, ExplodedNode* Pred,
313                                ExplodedNodeSet& Dst);
314
315  /// VisitObjCForCollectionStmt - Transfer function logic for
316  ///  ObjCForCollectionStmt.
317  void VisitObjCForCollectionStmt(const ObjCForCollectionStmt* S,
318                                  ExplodedNode* Pred, ExplodedNodeSet& Dst);
319
320  void VisitObjCForCollectionStmtAux(const ObjCForCollectionStmt* S,
321                                     ExplodedNode* Pred,
322                                     ExplodedNodeSet& Dst, SVal ElementV);
323
324  /// VisitObjCMessageExpr - Transfer function for ObjC message expressions.
325  void VisitObjCMessageExpr(const ObjCMessageExpr* ME, ExplodedNode* Pred,
326                            ExplodedNodeSet& Dst);
327  void VisitObjCMessage(const ObjCMessage &msg, ExplodedNodeSet &Src,
328                        ExplodedNodeSet& Dst);
329
330  /// VisitReturnStmt - Transfer function logic for return statements.
331  void VisitReturnStmt(const ReturnStmt* R, ExplodedNode* Pred,
332                       ExplodedNodeSet& Dst);
333
334  /// VisitOffsetOfExpr - Transfer function for offsetof.
335  void VisitOffsetOfExpr(const OffsetOfExpr* Ex, ExplodedNode* Pred,
336                         ExplodedNodeSet& Dst);
337
338  /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
339  void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr* Ex,
340                              ExplodedNode* Pred, ExplodedNodeSet& Dst);
341
342  /// VisitUnaryOperator - Transfer function logic for unary operators.
343  void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode* Pred,
344                          ExplodedNodeSet& Dst);
345
346  void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
347                        ExplodedNodeSet & Dst);
348
349  void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *expr,
350                                   ExplodedNode *Pred, ExplodedNodeSet &Dst) {
351    VisitCXXConstructExpr(expr, 0, Pred, Dst);
352  }
353
354  void VisitCXXConstructExpr(const CXXConstructExpr *E, const MemRegion *Dest,
355                             ExplodedNode *Pred, ExplodedNodeSet &Dst);
356
357  void VisitCXXDestructor(const CXXDestructorDecl *DD,
358                          const MemRegion *Dest, const Stmt *S,
359                          ExplodedNode *Pred, ExplodedNodeSet &Dst);
360
361  void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
362                       ExplodedNodeSet &Dst);
363
364  void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred,
365                          ExplodedNodeSet &Dst);
366
367  void VisitAggExpr(const Expr *E, const MemRegion *Dest, ExplodedNode *Pred,
368                    ExplodedNodeSet &Dst);
369
370  /// Create a C++ temporary object for an rvalue.
371  void CreateCXXTemporaryObject(const Expr *Ex, ExplodedNode *Pred,
372                                ExplodedNodeSet &Dst);
373
374  /// Synthesize CXXThisRegion.
375  const CXXThisRegion *getCXXThisRegion(const CXXRecordDecl *RD,
376                                        const StackFrameContext *SFC);
377
378  const CXXThisRegion *getCXXThisRegion(const CXXMethodDecl *decl,
379                                        const StackFrameContext *frameCtx);
380
381  /// Evaluate arguments with a work list algorithm.
382  void evalArguments(ConstExprIterator AI, ConstExprIterator AE,
383                     const FunctionProtoType *FnType,
384                     ExplodedNode *Pred, ExplodedNodeSet &Dst,
385                     bool FstArgAsLValue = false);
386
387  /// Evaluate callee expression (for a function call).
388  void evalCallee(const CallExpr *callExpr, const ExplodedNodeSet &src,
389                  ExplodedNodeSet &dest);
390
391  /// evalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic
392  ///  expressions of the form 'x != 0' and generate new nodes (stored in Dst)
393  ///  with those assumptions.
394  void evalEagerlyAssume(ExplodedNodeSet& Dst, ExplodedNodeSet& Src,
395                         const Expr *Ex);
396
397  SVal evalMinus(SVal X) {
398    return X.isValid() ? svalBuilder.evalMinus(cast<NonLoc>(X)) : X;
399  }
400
401  SVal evalComplement(SVal X) {
402    return X.isValid() ? svalBuilder.evalComplement(cast<NonLoc>(X)) : X;
403  }
404
405public:
406
407  SVal evalBinOp(const GRState *state, BinaryOperator::Opcode op,
408                 NonLoc L, NonLoc R, QualType T) {
409    return svalBuilder.evalBinOpNN(state, op, L, R, T);
410  }
411
412  SVal evalBinOp(const GRState *state, BinaryOperator::Opcode op,
413                 NonLoc L, SVal R, QualType T) {
414    return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(R), T) : R;
415  }
416
417  SVal evalBinOp(const GRState *ST, BinaryOperator::Opcode Op,
418                 SVal LHS, SVal RHS, QualType T) {
419    return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
420  }
421
422protected:
423  void evalObjCMessage(ExplodedNodeSet& Dst, const ObjCMessage &msg,
424                       ExplodedNode* Pred, const GRState *state) {
425    assert (Builder && "StmtNodeBuilder must be defined.");
426    getTF().evalObjCMessage(Dst, *this, *Builder, msg, Pred, state);
427  }
428
429  const GRState* MarkBranch(const GRState* St, const Stmt* Terminator,
430                            bool branchTaken);
431
432  /// evalBind - Handle the semantics of binding a value to a specific location.
433  ///  This method is used by evalStore, VisitDeclStmt, and others.
434  void evalBind(ExplodedNodeSet& Dst, const Stmt* StoreE, ExplodedNode* Pred,
435                const GRState* St, SVal location, SVal Val,
436                bool atDeclInit = false);
437
438public:
439  // FIXME: 'tag' should be removed, and a LocationContext should be used
440  // instead.
441  // FIXME: Comment on the meaning of the arguments, when 'St' may not
442  // be the same as Pred->state, and when 'location' may not be the
443  // same as state->getLValue(Ex).
444  /// Simulate a read of the result of Ex.
445  void evalLoad(ExplodedNodeSet& Dst, const Expr* Ex, ExplodedNode* Pred,
446                const GRState* St, SVal location, const void *tag = 0,
447                QualType LoadTy = QualType());
448
449  // FIXME: 'tag' should be removed, and a LocationContext should be used
450  // instead.
451  void evalStore(ExplodedNodeSet& Dst, const Expr* AssignE, const Expr* StoreE,
452                 ExplodedNode* Pred, const GRState* St, SVal TargetLV, SVal Val,
453                 const void *tag = 0);
454private:
455  void evalLoadCommon(ExplodedNodeSet& Dst, const Expr* Ex, ExplodedNode* Pred,
456                      const GRState* St, SVal location, const void *tag,
457                      QualType LoadTy);
458
459  // FIXME: 'tag' should be removed, and a LocationContext should be used
460  // instead.
461  void evalLocation(ExplodedNodeSet &Dst, const Stmt *S, ExplodedNode* Pred,
462                    const GRState* St, SVal location,
463                    const void *tag, bool isLoad);
464
465  bool InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE, ExplodedNode *Pred);
466};
467
468} // end ento namespace
469
470} // end clang namespace
471
472#endif
473