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