ExprEngine.h revision 056c4b46335a3bd2612414735d5749ee159c0165
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/BugReporter/BugReporter.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/StmtObjC.h"
28
29namespace clang {
30
31class AnalysisDeclContextManager;
32class ObjCForCollectionStmt;
33
34namespace ento {
35
36class AnalysisManager;
37class CallOrObjCMessage;
38class ObjCMessage;
39
40class ExprEngine : public SubEngine {
41  AnalysisManager &AMgr;
42
43  AnalysisDeclContextManager &AnalysisDeclContexts;
44
45  CoreEngine Engine;
46
47  /// G - the simulation graph.
48  ExplodedGraph& G;
49
50  /// StateMgr - Object that manages the data for all created states.
51  ProgramStateManager 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 ProgramState *CleanedState;
65
66  /// currentStmt - The current block-level statement.
67  const Stmt *currentStmt;
68  unsigned int currentStmtIdx;
69  const NodeBuilderContext *currentBuilderContext;
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  const NodeBuilderContext &getBuilderContext() {
118    assert(currentBuilderContext);
119    return *currentBuilderContext;
120  }
121
122  bool isObjCGCEnabled() { return ObjCGCEnabled; }
123
124  const Stmt *getStmt() const;
125
126  void GenerateAutoTransition(ExplodedNode *N);
127
128  /// ViewGraph - Visualize the ExplodedGraph created by executing the
129  ///  simulation.
130  void ViewGraph(bool trim = false);
131
132  void ViewGraph(ExplodedNode** Beg, ExplodedNode** End);
133
134  /// getInitialState - Return the initial state used for the root vertex
135  ///  in the ExplodedGraph.
136  const ProgramState *getInitialState(const LocationContext *InitLoc);
137
138  ExplodedGraph& getGraph() { return G; }
139  const ExplodedGraph& getGraph() const { return G; }
140
141  /// processCFGElement - Called by CoreEngine. Used to generate new successor
142  ///  nodes by processing the 'effects' of a CFG element.
143  void processCFGElement(const CFGElement E, ExplodedNode *Pred,
144                         unsigned StmtIdx, NodeBuilderContext *Ctx);
145
146  void ProcessStmt(const CFGStmt S, ExplodedNode *Pred);
147
148  void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred);
149
150  void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred);
151
152  void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D,
153                               ExplodedNode *Pred, ExplodedNodeSet &Dst);
154  void ProcessBaseDtor(const CFGBaseDtor D,
155                       ExplodedNode *Pred, ExplodedNodeSet &Dst);
156  void ProcessMemberDtor(const CFGMemberDtor D,
157                         ExplodedNode *Pred, ExplodedNodeSet &Dst);
158  void ProcessTemporaryDtor(const CFGTemporaryDtor D,
159                            ExplodedNode *Pred, ExplodedNodeSet &Dst);
160
161  /// Called by CoreEngine when processing the entrance of a CFGBlock.
162  virtual void processCFGBlockEntrance(ExplodedNodeSet &dstNodes,
163                                GenericNodeBuilder<BlockEntrance> &nodeBuilder);
164
165  /// ProcessBranch - Called by CoreEngine.  Used to generate successor
166  ///  nodes by processing the 'effects' of a branch condition.
167  void processBranch(const Stmt *Condition, const Stmt *Term,
168                     NodeBuilderContext& BuilderCtx,
169                     ExplodedNode *Pred,
170                     ExplodedNodeSet &Dst,
171                     const CFGBlock *DstT,
172                     const CFGBlock *DstF);
173
174  /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
175  ///  nodes by processing the 'effects' of a computed goto jump.
176  void processIndirectGoto(IndirectGotoNodeBuilder& builder);
177
178  /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
179  ///  nodes by processing the 'effects' of a switch statement.
180  void processSwitch(SwitchNodeBuilder& builder);
181
182  /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
183  ///  nodes when the control reaches the end of a function.
184  void processEndOfFunction(EndOfFunctionNodeBuilder& builder);
185
186  /// Generate the entry node of the callee.
187  void processCallEnter(CallEnterNodeBuilder &builder);
188
189  /// Generate the first post callsite node.
190  void processCallExit(CallExitNodeBuilder &builder);
191
192  /// Called by CoreEngine when the analysis worklist has terminated.
193  void processEndWorklist(bool hasWorkRemaining);
194
195  /// evalAssume - Callback function invoked by the ConstraintManager when
196  ///  making assumptions about state values.
197  const ProgramState *processAssume(const ProgramState *state, SVal cond,bool assumption);
198
199  /// wantsRegionChangeUpdate - Called by ProgramStateManager to determine if a
200  ///  region change should trigger a processRegionChanges update.
201  bool wantsRegionChangeUpdate(const ProgramState *state);
202
203  /// processRegionChanges - Called by ProgramStateManager whenever a change is made
204  ///  to the store. Used to update checkers that track region values.
205  const ProgramState *
206  processRegionChanges(const ProgramState *state,
207                       const StoreManager::InvalidatedSymbols *invalidated,
208                       ArrayRef<const MemRegion *> ExplicitRegions,
209                       ArrayRef<const MemRegion *> Regions);
210
211  /// printState - Called by ProgramStateManager to print checker-specific data.
212  void printState(raw_ostream &Out, const ProgramState *State,
213                  const char *NL, const char *Sep);
214
215  virtual ProgramStateManager& getStateManager() { return StateMgr; }
216
217  StoreManager& getStoreManager() { return StateMgr.getStoreManager(); }
218
219  ConstraintManager& getConstraintManager() {
220    return StateMgr.getConstraintManager();
221  }
222
223  // FIXME: Remove when we migrate over to just using SValBuilder.
224  BasicValueFactory& getBasicVals() {
225    return StateMgr.getBasicVals();
226  }
227  const BasicValueFactory& getBasicVals() const {
228    return StateMgr.getBasicVals();
229  }
230
231  // FIXME: Remove when we migrate over to just using ValueManager.
232  SymbolManager& getSymbolManager() { return SymMgr; }
233  const SymbolManager& getSymbolManager() const { return SymMgr; }
234
235  // Functions for external checking of whether we have unfinished work
236  bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
237  bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
238  bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); }
239
240  const CoreEngine &getCoreEngine() const { return Engine; }
241
242public:
243  /// Visit - Transfer function logic for all statements.  Dispatches to
244  ///  other functions that handle specific kinds of statements.
245  void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst);
246
247  /// VisitArraySubscriptExpr - Transfer function for array accesses.
248  void VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *Ex,
249                                   ExplodedNode *Pred,
250                                   ExplodedNodeSet &Dst);
251
252  /// VisitAsmStmt - Transfer function logic for inline asm.
253  void VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst);
254
255  void VisitAsmStmtHelperOutputs(const AsmStmt *A,
256                                 AsmStmt::const_outputs_iterator I,
257                                 AsmStmt::const_outputs_iterator E,
258                                 ExplodedNode *Pred, ExplodedNodeSet &Dst);
259
260  void VisitAsmStmtHelperInputs(const AsmStmt *A,
261                                AsmStmt::const_inputs_iterator I,
262                                AsmStmt::const_inputs_iterator E,
263                                ExplodedNode *Pred, ExplodedNodeSet &Dst);
264
265  /// VisitBlockExpr - Transfer function logic for BlockExprs.
266  void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
267                      ExplodedNodeSet &Dst);
268
269  /// VisitBinaryOperator - Transfer function logic for binary operators.
270  void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred,
271                           ExplodedNodeSet &Dst);
272
273
274  /// VisitCall - Transfer function for function calls.
275  void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
276                     ExplodedNodeSet &Dst);
277
278  /// VisitCast - Transfer function logic for all casts (implicit and explicit).
279  void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred,
280                ExplodedNodeSet &Dst);
281
282  /// VisitCompoundLiteralExpr - Transfer function logic for compound literals.
283  void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
284                                ExplodedNode *Pred, ExplodedNodeSet &Dst);
285
286  /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
287  void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D,
288                              ExplodedNode *Pred, ExplodedNodeSet &Dst);
289
290  /// VisitDeclStmt - Transfer function logic for DeclStmts.
291  void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
292                     ExplodedNodeSet &Dst);
293
294  /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
295  void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R,
296                        ExplodedNode *Pred, ExplodedNodeSet &Dst);
297
298  void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred,
299                         ExplodedNodeSet &Dst);
300
301  /// VisitLogicalExpr - Transfer function logic for '&&', '||'
302  void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
303                        ExplodedNodeSet &Dst);
304
305  /// VisitMemberExpr - Transfer function for member expressions.
306  void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
307                           ExplodedNodeSet &Dst);
308
309  /// Transfer function logic for ObjCAtSynchronizedStmts.
310  void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
311                                   ExplodedNode *Pred, ExplodedNodeSet &Dst);
312
313  /// Transfer function logic for computing the lvalue of an Objective-C ivar.
314  void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred,
315                                ExplodedNodeSet &Dst);
316
317  /// VisitObjCForCollectionStmt - Transfer function logic for
318  ///  ObjCForCollectionStmt.
319  void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
320                                  ExplodedNode *Pred, ExplodedNodeSet &Dst);
321
322  void VisitObjCMessage(const ObjCMessage &msg, ExplodedNode *Pred,
323                        ExplodedNodeSet &Dst);
324
325  /// VisitReturnStmt - Transfer function logic for return statements.
326  void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred,
327                       ExplodedNodeSet &Dst);
328
329  /// VisitOffsetOfExpr - Transfer function for offsetof.
330  void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred,
331                         ExplodedNodeSet &Dst);
332
333  /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
334  void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
335                              ExplodedNode *Pred, ExplodedNodeSet &Dst);
336
337  /// VisitUnaryOperator - Transfer function logic for unary operators.
338  void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred,
339                          ExplodedNodeSet &Dst);
340
341  /// Handle ++ and -- (both pre- and post-increment).
342  void VisitIncrementDecrementOperator(const UnaryOperator* U,
343                                       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 MaterializeTemporaryExpr *ME,
372                                ExplodedNode *Pred,
373                                ExplodedNodeSet &Dst);
374
375  /// Synthesize CXXThisRegion.
376  const CXXThisRegion *getCXXThisRegion(const CXXRecordDecl *RD,
377                                        const StackFrameContext *SFC);
378
379  const CXXThisRegion *getCXXThisRegion(const CXXMethodDecl *decl,
380                                        const StackFrameContext *frameCtx);
381
382  /// Evaluate arguments with a work list algorithm.
383  void evalArguments(ConstExprIterator AI, ConstExprIterator AE,
384                     const FunctionProtoType *FnType,
385                     ExplodedNode *Pred, ExplodedNodeSet &Dst,
386                     bool FstArgAsLValue = false);
387
388  /// Evaluate callee expression (for a function call).
389  void evalCallee(const CallExpr *callExpr, const ExplodedNodeSet &src,
390                  ExplodedNodeSet &dest);
391
392  /// evalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic
393  ///  expressions of the form 'x != 0' and generate new nodes (stored in Dst)
394  ///  with those assumptions.
395  void evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
396                         const Expr *Ex);
397
398  std::pair<const ProgramPointTag *, const ProgramPointTag*>
399    getEagerlyAssumeTags();
400
401  SVal evalMinus(SVal X) {
402    return X.isValid() ? svalBuilder.evalMinus(cast<NonLoc>(X)) : X;
403  }
404
405  SVal evalComplement(SVal X) {
406    return X.isValid() ? svalBuilder.evalComplement(cast<NonLoc>(X)) : X;
407  }
408
409public:
410
411  SVal evalBinOp(const ProgramState *state, BinaryOperator::Opcode op,
412                 NonLoc L, NonLoc R, QualType T) {
413    return svalBuilder.evalBinOpNN(state, op, L, R, T);
414  }
415
416  SVal evalBinOp(const ProgramState *state, BinaryOperator::Opcode op,
417                 NonLoc L, SVal R, QualType T) {
418    return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(R), T) : R;
419  }
420
421  SVal evalBinOp(const ProgramState *ST, BinaryOperator::Opcode Op,
422                 SVal LHS, SVal RHS, QualType T) {
423    return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
424  }
425
426protected:
427  void evalObjCMessage(PureStmtNodeBuilder &Bldr, const ObjCMessage &msg,
428                       ExplodedNode *Pred, const ProgramState *state,
429                       bool GenSink);
430
431  const ProgramState *invalidateArguments(const ProgramState *State,
432                                          const CallOrObjCMessage &Call,
433                                          const LocationContext *LC);
434
435  const ProgramState *MarkBranch(const ProgramState *St, const Stmt *Terminator,
436                            bool branchTaken);
437
438  /// evalBind - Handle the semantics of binding a value to a specific location.
439  ///  This method is used by evalStore, VisitDeclStmt, and others.
440  void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred,
441                SVal location, SVal Val, bool atDeclInit = false,
442                ProgramPoint::Kind PP = ProgramPoint::PostStmtKind);
443
444public:
445  // FIXME: 'tag' should be removed, and a LocationContext should be used
446  // instead.
447  // FIXME: Comment on the meaning of the arguments, when 'St' may not
448  // be the same as Pred->state, and when 'location' may not be the
449  // same as state->getLValue(Ex).
450  /// Simulate a read of the result of Ex.
451  void evalLoad(ExplodedNodeSet &Dst, const Expr *Ex, ExplodedNode *Pred,
452                const ProgramState *St, SVal location, const ProgramPointTag *tag = 0,
453                QualType LoadTy = QualType());
454
455  // FIXME: 'tag' should be removed, and a LocationContext should be used
456  // instead.
457  void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE,
458                 ExplodedNode *Pred, const ProgramState *St, SVal TargetLV, SVal Val,
459                 const ProgramPointTag *tag = 0);
460private:
461  void evalLoadCommon(ExplodedNodeSet &Dst, const Expr *Ex, ExplodedNode *Pred,
462                      const ProgramState *St, SVal location, const ProgramPointTag *tag,
463                      QualType LoadTy);
464
465  // FIXME: 'tag' should be removed, and a LocationContext should be used
466  // instead.
467  void evalLocation(ExplodedNodeSet &Dst, const Stmt *S, ExplodedNode *Pred,
468                    const ProgramState *St, SVal location,
469                    const ProgramPointTag *tag, bool isLoad);
470
471  bool InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE, ExplodedNode *Pred);
472
473
474public:
475  /// Returns true if calling the specific function or method would possibly
476  /// cause global variables to be invalidated.
477  bool doesInvalidateGlobals(const CallOrObjCMessage &callOrMessage) const;
478
479};
480
481} // end ento namespace
482
483} // end clang namespace
484
485#endif
486