ExprEngine.h revision 17a38e2636a8b1ce473fc6504c4b16cb09db29f4
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/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;
37class CallOrObjCMessage;
38class ObjCMessage;
39
40class ExprEngine : public SubEngine {
41  AnalysisManager &AMgr;
42
43  CoreEngine Engine;
44
45  /// G - the simulation graph.
46  ExplodedGraph& G;
47
48  /// Builder - The current StmtNodeBuilder which is used when building the
49  ///  nodes for a given statement.
50  StmtNodeBuilder* Builder;
51
52  /// StateMgr - Object that manages the data for all created states.
53  ProgramStateManager StateMgr;
54
55  /// SymMgr - Object that manages the symbol information.
56  SymbolManager& SymMgr;
57
58  /// svalBuilder - SValBuilder object that creates SVals from expressions.
59  SValBuilder &svalBuilder;
60
61  /// EntryNode - The immediate predecessor node.
62  ExplodedNode *EntryNode;
63
64  /// CleanedState - The state for EntryNode "cleaned" of all dead
65  ///  variables and symbols (as determined by a liveness analysis).
66  const ProgramState *CleanedState;
67
68  /// currentStmt - The current block-level statement.
69  const Stmt *currentStmt;
70
71  // Obj-C Class Identifiers.
72  IdentifierInfo* NSExceptionII;
73
74  // Obj-C Selectors.
75  Selector* NSExceptionInstanceRaiseSelectors;
76  Selector RaiseSel;
77
78  /// Whether or not GC is enabled in this analysis.
79  bool ObjCGCEnabled;
80
81  /// The BugReporter associated with this engine.  It is important that
82  ///  this object be placed at the very end of member variables so that its
83  ///  destructor is called before the rest of the ExprEngine is destroyed.
84  GRBugReporter BR;
85
86public:
87  ExprEngine(AnalysisManager &mgr, bool gcEnabled);
88
89  ~ExprEngine();
90
91  void ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) {
92    Engine.ExecuteWorkList(L, Steps, 0);
93  }
94
95  /// Execute the work list with an initial state. Nodes that reaches the exit
96  /// of the function are added into the Dst set, which represent the exit
97  /// state of the function call.
98  void ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps,
99                                       const ProgramState *InitState,
100                                       ExplodedNodeSet &Dst) {
101    Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst);
102  }
103
104  /// getContext - Return the ASTContext associated with this analysis.
105  ASTContext &getContext() const { return AMgr.getASTContext(); }
106
107  virtual AnalysisManager &getAnalysisManager() { return AMgr; }
108
109  CheckerManager &getCheckerManager() const {
110    return *AMgr.getCheckerManager();
111  }
112
113  SValBuilder &getSValBuilder() { return svalBuilder; }
114
115  BugReporter& getBugReporter() { return BR; }
116
117  StmtNodeBuilder &getBuilder() { assert(Builder); return *Builder; }
118
119  bool isObjCGCEnabled() { return ObjCGCEnabled; }
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 ProgramState *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 ProgramState *processAssume(const ProgramState *state, SVal cond,bool assumption);
184
185  /// wantsRegionChangeUpdate - Called by ProgramStateManager to determine if a
186  ///  region change should trigger a processRegionChanges update.
187  bool wantsRegionChangeUpdate(const ProgramState *state);
188
189  /// processRegionChanges - Called by ProgramStateManager whenever a change is made
190  ///  to the store. Used to update checkers that track region values.
191  const ProgramState *
192  processRegionChanges(const ProgramState *state,
193                       const StoreManager::InvalidatedSymbols *invalidated,
194                       ArrayRef<const MemRegion *> ExplicitRegions,
195                       ArrayRef<const MemRegion *> Regions);
196
197  /// printState - Called by ProgramStateManager to print checker-specific data.
198  void printState(raw_ostream &Out, const ProgramState *State,
199                  const char *NL, const char *Sep);
200
201  virtual ProgramStateManager& getStateManager() { return StateMgr; }
202
203  StoreManager& getStoreManager() { return StateMgr.getStoreManager(); }
204
205  ConstraintManager& getConstraintManager() {
206    return StateMgr.getConstraintManager();
207  }
208
209  // FIXME: Remove when we migrate over to just using SValBuilder.
210  BasicValueFactory& getBasicVals() {
211    return StateMgr.getBasicVals();
212  }
213  const BasicValueFactory& getBasicVals() const {
214    return StateMgr.getBasicVals();
215  }
216
217  // FIXME: Remove when we migrate over to just using ValueManager.
218  SymbolManager& getSymbolManager() { return SymMgr; }
219  const SymbolManager& getSymbolManager() const { return SymMgr; }
220
221  // Functions for external checking of whether we have unfinished work
222  bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
223  bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
224  bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); }
225
226  const CoreEngine &getCoreEngine() const { return Engine; }
227
228public:
229  ExplodedNode *MakeNode(ExplodedNodeSet &Dst, const Stmt *S,
230                         ExplodedNode *Pred, const ProgramState *St,
231                         ProgramPoint::Kind K = ProgramPoint::PostStmtKind,
232                         const ProgramPointTag *tag = 0);
233
234  /// Visit - Transfer function logic for all statements.  Dispatches to
235  ///  other functions that handle specific kinds of statements.
236  void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst);
237
238  /// VisitArraySubscriptExpr - Transfer function for array accesses.
239  void VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *Ex,
240                                   ExplodedNode *Pred,
241                                   ExplodedNodeSet &Dst);
242
243  /// VisitAsmStmt - Transfer function logic for inline asm.
244  void VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst);
245
246  void VisitAsmStmtHelperOutputs(const AsmStmt *A,
247                                 AsmStmt::const_outputs_iterator I,
248                                 AsmStmt::const_outputs_iterator E,
249                                 ExplodedNode *Pred, ExplodedNodeSet &Dst);
250
251  void VisitAsmStmtHelperInputs(const AsmStmt *A,
252                                AsmStmt::const_inputs_iterator I,
253                                AsmStmt::const_inputs_iterator E,
254                                ExplodedNode *Pred, ExplodedNodeSet &Dst);
255
256  /// VisitBlockExpr - Transfer function logic for BlockExprs.
257  void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
258                      ExplodedNodeSet &Dst);
259
260  /// VisitBinaryOperator - Transfer function logic for binary operators.
261  void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred,
262                           ExplodedNodeSet &Dst);
263
264
265  /// VisitCall - Transfer function for function calls.
266  void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
267                     ExplodedNodeSet &Dst);
268
269  /// VisitCast - Transfer function logic for all casts (implicit and explicit).
270  void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred,
271                ExplodedNodeSet &Dst);
272
273  /// VisitCompoundLiteralExpr - Transfer function logic for compound literals.
274  void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
275                                ExplodedNode *Pred, ExplodedNodeSet &Dst);
276
277  /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
278  void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D,
279                              ExplodedNode *Pred, ExplodedNodeSet &Dst);
280
281  /// VisitDeclStmt - Transfer function logic for DeclStmts.
282  void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
283                     ExplodedNodeSet &Dst);
284
285  /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
286  void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R,
287                        ExplodedNode *Pred, ExplodedNodeSet &Dst);
288
289  void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred,
290                         ExplodedNodeSet &Dst);
291
292  /// VisitLogicalExpr - Transfer function logic for '&&', '||'
293  void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
294                        ExplodedNodeSet &Dst);
295
296  /// VisitMemberExpr - Transfer function for member expressions.
297  void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
298                           ExplodedNodeSet &Dst);
299
300  /// Transfer function logic for ObjCAtSynchronizedStmts.
301  void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
302                                   ExplodedNode *Pred, ExplodedNodeSet &Dst);
303
304  /// Transfer function logic for computing the lvalue of an Objective-C ivar.
305  void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred,
306                                ExplodedNodeSet &Dst);
307
308  /// VisitObjCForCollectionStmt - Transfer function logic for
309  ///  ObjCForCollectionStmt.
310  void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
311                                  ExplodedNode *Pred, ExplodedNodeSet &Dst);
312
313  void VisitObjCMessage(const ObjCMessage &msg, ExplodedNode *Pred,
314                        ExplodedNodeSet &Dst);
315
316  /// VisitReturnStmt - Transfer function logic for return statements.
317  void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred,
318                       ExplodedNodeSet &Dst);
319
320  /// VisitOffsetOfExpr - Transfer function for offsetof.
321  void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred,
322                         ExplodedNodeSet &Dst);
323
324  /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
325  void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
326                              ExplodedNode *Pred, ExplodedNodeSet &Dst);
327
328  /// VisitUnaryOperator - Transfer function logic for unary operators.
329  void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred,
330                          ExplodedNodeSet &Dst);
331
332  void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
333                        ExplodedNodeSet & Dst);
334
335  void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *expr,
336                                   ExplodedNode *Pred, ExplodedNodeSet &Dst) {
337    VisitCXXConstructExpr(expr, 0, Pred, Dst);
338  }
339
340  void VisitCXXConstructExpr(const CXXConstructExpr *E, const MemRegion *Dest,
341                             ExplodedNode *Pred, ExplodedNodeSet &Dst);
342
343  void VisitCXXDestructor(const CXXDestructorDecl *DD,
344                          const MemRegion *Dest, const Stmt *S,
345                          ExplodedNode *Pred, ExplodedNodeSet &Dst);
346
347  void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
348                       ExplodedNodeSet &Dst);
349
350  void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred,
351                          ExplodedNodeSet &Dst);
352
353  void VisitAggExpr(const Expr *E, const MemRegion *Dest, ExplodedNode *Pred,
354                    ExplodedNodeSet &Dst);
355
356  /// Create a C++ temporary object for an rvalue.
357  void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
358                                ExplodedNode *Pred,
359                                ExplodedNodeSet &Dst);
360
361  /// Synthesize CXXThisRegion.
362  const CXXThisRegion *getCXXThisRegion(const CXXRecordDecl *RD,
363                                        const StackFrameContext *SFC);
364
365  const CXXThisRegion *getCXXThisRegion(const CXXMethodDecl *decl,
366                                        const StackFrameContext *frameCtx);
367
368  /// Evaluate arguments with a work list algorithm.
369  void evalArguments(ConstExprIterator AI, ConstExprIterator AE,
370                     const FunctionProtoType *FnType,
371                     ExplodedNode *Pred, ExplodedNodeSet &Dst,
372                     bool FstArgAsLValue = false);
373
374  /// Evaluate callee expression (for a function call).
375  void evalCallee(const CallExpr *callExpr, const ExplodedNodeSet &src,
376                  ExplodedNodeSet &dest);
377
378  /// evalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic
379  ///  expressions of the form 'x != 0' and generate new nodes (stored in Dst)
380  ///  with those assumptions.
381  void evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
382                         const Expr *Ex);
383
384  std::pair<const ProgramPointTag *, const ProgramPointTag*>
385    getEagerlyAssumeTags();
386
387  SVal evalMinus(SVal X) {
388    return X.isValid() ? svalBuilder.evalMinus(cast<NonLoc>(X)) : X;
389  }
390
391  SVal evalComplement(SVal X) {
392    return X.isValid() ? svalBuilder.evalComplement(cast<NonLoc>(X)) : X;
393  }
394
395public:
396
397  SVal evalBinOp(const ProgramState *state, BinaryOperator::Opcode op,
398                 NonLoc L, NonLoc R, QualType T) {
399    return svalBuilder.evalBinOpNN(state, op, L, R, T);
400  }
401
402  SVal evalBinOp(const ProgramState *state, BinaryOperator::Opcode op,
403                 NonLoc L, SVal R, QualType T) {
404    return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(R), T) : R;
405  }
406
407  SVal evalBinOp(const ProgramState *ST, BinaryOperator::Opcode Op,
408                 SVal LHS, SVal RHS, QualType T) {
409    return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
410  }
411
412protected:
413  void evalObjCMessage(ExplodedNodeSet &Dst, const ObjCMessage &msg,
414                       ExplodedNode *Pred, const ProgramState *state);
415
416  const ProgramState *invalidateArguments(const ProgramState *State,
417                                          const CallOrObjCMessage &Call,
418                                          const LocationContext *LC);
419
420  const ProgramState *MarkBranch(const ProgramState *St, const Stmt *Terminator,
421                            bool branchTaken);
422
423  /// evalBind - Handle the semantics of binding a value to a specific location.
424  ///  This method is used by evalStore, VisitDeclStmt, and others.
425  void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred,
426                SVal location, SVal Val, bool atDeclInit = false);
427
428public:
429  // FIXME: 'tag' should be removed, and a LocationContext should be used
430  // instead.
431  // FIXME: Comment on the meaning of the arguments, when 'St' may not
432  // be the same as Pred->state, and when 'location' may not be the
433  // same as state->getLValue(Ex).
434  /// Simulate a read of the result of Ex.
435  void evalLoad(ExplodedNodeSet &Dst, const Expr *Ex, ExplodedNode *Pred,
436                const ProgramState *St, SVal location, const ProgramPointTag *tag = 0,
437                QualType LoadTy = QualType());
438
439  // FIXME: 'tag' should be removed, and a LocationContext should be used
440  // instead.
441  void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE,
442                 ExplodedNode *Pred, const ProgramState *St, SVal TargetLV, SVal Val,
443                 const ProgramPointTag *tag = 0);
444private:
445  void evalLoadCommon(ExplodedNodeSet &Dst, const Expr *Ex, ExplodedNode *Pred,
446                      const ProgramState *St, SVal location, const ProgramPointTag *tag,
447                      QualType LoadTy);
448
449  // FIXME: 'tag' should be removed, and a LocationContext should be used
450  // instead.
451  void evalLocation(ExplodedNodeSet &Dst, const Stmt *S, ExplodedNode *Pred,
452                    const ProgramState *St, SVal location,
453                    const ProgramPointTag *tag, bool isLoad);
454
455  bool InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE, ExplodedNode *Pred);
456
457
458public:
459  /// Returns true if calling the specific function or method would possibly
460  /// cause global variables to be invalidated.
461  bool doesInvalidateGlobals(const CallOrObjCMessage &callOrMessage) const;
462
463};
464
465} // end ento namespace
466
467} // end clang namespace
468
469#endif
470