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