ExprEngine.h revision b1b5daf30d2597e066936772bd206500232d7d65
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 AnalysisContextManager;
32class ObjCForCollectionStmt;
33
34namespace ento {
35
36class AnalysisManager;
37class CallOrObjCMessage;
38class ObjCMessage;
39
40class ExprEngine : public SubEngine {
41  AnalysisManager &AMgr;
42
43  AnalysisContextManager &AnalysisContexts;
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
73  /// Obj-C Class Identifiers.
74  IdentifierInfo* NSExceptionII;
75
76  /// Obj-C Selectors.
77  Selector* NSExceptionInstanceRaiseSelectors;
78  Selector RaiseSel;
79
80  /// Whether or not GC is enabled in this analysis.
81  bool ObjCGCEnabled;
82
83  /// The BugReporter associated with this engine.  It is important that
84  ///  this object be placed at the very end of member variables so that its
85  ///  destructor is called before the rest of the ExprEngine is destroyed.
86  GRBugReporter BR;
87
88public:
89  ExprEngine(AnalysisManager &mgr, bool gcEnabled);
90
91  ~ExprEngine();
92
93  void ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) {
94    Engine.ExecuteWorkList(L, Steps, 0);
95  }
96
97  /// Execute the work list with an initial state. Nodes that reaches the exit
98  /// of the function are added into the Dst set, which represent the exit
99  /// state of the function call.
100  void ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps,
101                                       const ProgramState *InitState,
102                                       ExplodedNodeSet &Dst) {
103    Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst);
104  }
105
106  /// getContext - Return the ASTContext associated with this analysis.
107  ASTContext &getContext() const { return AMgr.getASTContext(); }
108
109  virtual AnalysisManager &getAnalysisManager() { return AMgr; }
110
111  CheckerManager &getCheckerManager() const {
112    return *AMgr.getCheckerManager();
113  }
114
115  SValBuilder &getSValBuilder() { return svalBuilder; }
116
117  BugReporter& getBugReporter() { return BR; }
118
119  StmtNodeBuilder &getBuilder() { assert(Builder); return *Builder; }
120
121  bool isObjCGCEnabled() { return ObjCGCEnabled; }
122
123  /// ViewGraph - Visualize the ExplodedGraph created by executing the
124  ///  simulation.
125  void ViewGraph(bool trim = false);
126
127  void ViewGraph(ExplodedNode** Beg, ExplodedNode** End);
128
129  /// getInitialState - Return the initial state used for the root vertex
130  ///  in the ExplodedGraph.
131  const ProgramState *getInitialState(const LocationContext *InitLoc);
132
133  ExplodedGraph& getGraph() { return G; }
134  const ExplodedGraph& getGraph() const { return G; }
135
136  /// processCFGElement - Called by CoreEngine. Used to generate new successor
137  ///  nodes by processing the 'effects' of a CFG element.
138  void processCFGElement(const CFGElement E, StmtNodeBuilder& Bldr,
139                         ExplodedNode *Pred);
140
141  void ProcessStmt(const CFGStmt S, StmtNodeBuilder &builder,
142                   ExplodedNode *Pred);
143
144  void ProcessInitializer(const CFGInitializer I, StmtNodeBuilder &Bldr,
145                          ExplodedNode *Pred);
146
147  void ProcessImplicitDtor(const CFGImplicitDtor D, StmtNodeBuilder &builder,
148                           ExplodedNode *Pred);
149
150  void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D,
151                               StmtNodeBuilder &builder, ExplodedNode *Pred);
152  void ProcessBaseDtor(const CFGBaseDtor D, StmtNodeBuilder &builder);
153  void ProcessMemberDtor(const CFGMemberDtor D, StmtNodeBuilder &builder);
154  void ProcessTemporaryDtor(const CFGTemporaryDtor D,
155                            StmtNodeBuilder &builder);
156
157  /// Called by CoreEngine when processing the entrance of a CFGBlock.
158  virtual void processCFGBlockEntrance(ExplodedNodeSet &dstNodes,
159                                GenericNodeBuilder<BlockEntrance> &nodeBuilder);
160
161  /// ProcessBranch - Called by CoreEngine.  Used to generate successor
162  ///  nodes by processing the 'effects' of a branch condition.
163  void processBranch(const Stmt *Condition, const Stmt *Term,
164                     NodeBuilderContext& BuilderCtx,
165                     ExplodedNode *Pred,
166                     const CFGBlock *DstT,
167                     const CFGBlock *DstF);
168
169  /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
170  ///  nodes by processing the 'effects' of a computed goto jump.
171  void processIndirectGoto(IndirectGotoNodeBuilder& builder);
172
173  /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
174  ///  nodes by processing the 'effects' of a switch statement.
175  void processSwitch(SwitchNodeBuilder& builder);
176
177  /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
178  ///  nodes when the control reaches the end of a function.
179  void processEndOfFunction(EndOfFunctionNodeBuilder& builder);
180
181  /// Generate the entry node of the callee.
182  void processCallEnter(CallEnterNodeBuilder &builder);
183
184  /// Generate the first post callsite node.
185  void processCallExit(CallExitNodeBuilder &builder);
186
187  /// Called by CoreEngine when the analysis worklist has terminated.
188  void processEndWorklist(bool hasWorkRemaining);
189
190  /// evalAssume - Callback function invoked by the ConstraintManager when
191  ///  making assumptions about state values.
192  const ProgramState *processAssume(const ProgramState *state, SVal cond,bool assumption);
193
194  /// wantsRegionChangeUpdate - Called by ProgramStateManager to determine if a
195  ///  region change should trigger a processRegionChanges update.
196  bool wantsRegionChangeUpdate(const ProgramState *state);
197
198  /// processRegionChanges - Called by ProgramStateManager whenever a change is made
199  ///  to the store. Used to update checkers that track region values.
200  const ProgramState *
201  processRegionChanges(const ProgramState *state,
202                       const StoreManager::InvalidatedSymbols *invalidated,
203                       ArrayRef<const MemRegion *> ExplicitRegions,
204                       ArrayRef<const MemRegion *> Regions);
205
206  /// printState - Called by ProgramStateManager to print checker-specific data.
207  void printState(raw_ostream &Out, const ProgramState *State,
208                  const char *NL, const char *Sep);
209
210  virtual ProgramStateManager& getStateManager() { return StateMgr; }
211
212  StoreManager& getStoreManager() { return StateMgr.getStoreManager(); }
213
214  ConstraintManager& getConstraintManager() {
215    return StateMgr.getConstraintManager();
216  }
217
218  // FIXME: Remove when we migrate over to just using SValBuilder.
219  BasicValueFactory& getBasicVals() {
220    return StateMgr.getBasicVals();
221  }
222  const BasicValueFactory& getBasicVals() const {
223    return StateMgr.getBasicVals();
224  }
225
226  // FIXME: Remove when we migrate over to just using ValueManager.
227  SymbolManager& getSymbolManager() { return SymMgr; }
228  const SymbolManager& getSymbolManager() const { return SymMgr; }
229
230  // Functions for external checking of whether we have unfinished work
231  bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
232  bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
233  bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); }
234
235  const CoreEngine &getCoreEngine() const { return Engine; }
236
237public:
238  ExplodedNode *MakeNode(ExplodedNodeSet &Dst, const Stmt *S,
239                         ExplodedNode *Pred, const ProgramState *St,
240                         ProgramPoint::Kind K = ProgramPoint::PostStmtKind,
241                         const ProgramPointTag *tag = 0);
242
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  void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
342                        ExplodedNodeSet & Dst);
343
344  void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *expr,
345                                   ExplodedNode *Pred, ExplodedNodeSet &Dst) {
346    VisitCXXConstructExpr(expr, 0, Pred, Dst);
347  }
348
349  void VisitCXXConstructExpr(const CXXConstructExpr *E, const MemRegion *Dest,
350                             ExplodedNode *Pred, ExplodedNodeSet &Dst);
351
352  void VisitCXXDestructor(const CXXDestructorDecl *DD,
353                          const MemRegion *Dest, const Stmt *S,
354                          ExplodedNode *Pred, ExplodedNodeSet &Dst);
355
356  void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
357                       ExplodedNodeSet &Dst);
358
359  void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred,
360                          ExplodedNodeSet &Dst);
361
362  void VisitAggExpr(const Expr *E, const MemRegion *Dest, ExplodedNode *Pred,
363                    ExplodedNodeSet &Dst);
364
365  /// Create a C++ temporary object for an rvalue.
366  void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
367                                ExplodedNode *Pred,
368                                ExplodedNodeSet &Dst);
369
370  /// Synthesize CXXThisRegion.
371  const CXXThisRegion *getCXXThisRegion(const CXXRecordDecl *RD,
372                                        const StackFrameContext *SFC);
373
374  const CXXThisRegion *getCXXThisRegion(const CXXMethodDecl *decl,
375                                        const StackFrameContext *frameCtx);
376
377  /// Evaluate arguments with a work list algorithm.
378  void evalArguments(ConstExprIterator AI, ConstExprIterator AE,
379                     const FunctionProtoType *FnType,
380                     ExplodedNode *Pred, ExplodedNodeSet &Dst,
381                     bool FstArgAsLValue = false);
382
383  /// Evaluate callee expression (for a function call).
384  void evalCallee(const CallExpr *callExpr, const ExplodedNodeSet &src,
385                  ExplodedNodeSet &dest);
386
387  /// evalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic
388  ///  expressions of the form 'x != 0' and generate new nodes (stored in Dst)
389  ///  with those assumptions.
390  void evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
391                         const Expr *Ex);
392
393  std::pair<const ProgramPointTag *, const ProgramPointTag*>
394    getEagerlyAssumeTags();
395
396  SVal evalMinus(SVal X) {
397    return X.isValid() ? svalBuilder.evalMinus(cast<NonLoc>(X)) : X;
398  }
399
400  SVal evalComplement(SVal X) {
401    return X.isValid() ? svalBuilder.evalComplement(cast<NonLoc>(X)) : X;
402  }
403
404public:
405
406  SVal evalBinOp(const ProgramState *state, BinaryOperator::Opcode op,
407                 NonLoc L, NonLoc R, QualType T) {
408    return svalBuilder.evalBinOpNN(state, op, L, R, T);
409  }
410
411  SVal evalBinOp(const ProgramState *state, BinaryOperator::Opcode op,
412                 NonLoc L, SVal R, QualType T) {
413    return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(R), T) : R;
414  }
415
416  SVal evalBinOp(const ProgramState *ST, BinaryOperator::Opcode Op,
417                 SVal LHS, SVal RHS, QualType T) {
418    return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
419  }
420
421protected:
422  void evalObjCMessage(ExplodedNodeSet &Dst, const ObjCMessage &msg,
423                       ExplodedNode *Pred, const ProgramState *state);
424
425  const ProgramState *invalidateArguments(const ProgramState *State,
426                                          const CallOrObjCMessage &Call,
427                                          const LocationContext *LC);
428
429  const ProgramState *MarkBranch(const ProgramState *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                SVal location, SVal Val, bool atDeclInit = false);
436
437public:
438  // FIXME: 'tag' should be removed, and a LocationContext should be used
439  // instead.
440  // FIXME: Comment on the meaning of the arguments, when 'St' may not
441  // be the same as Pred->state, and when 'location' may not be the
442  // same as state->getLValue(Ex).
443  /// Simulate a read of the result of Ex.
444  void evalLoad(ExplodedNodeSet &Dst, const Expr *Ex, ExplodedNode *Pred,
445                const ProgramState *St, SVal location, const ProgramPointTag *tag = 0,
446                QualType LoadTy = QualType());
447
448  // FIXME: 'tag' should be removed, and a LocationContext should be used
449  // instead.
450  void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE,
451                 ExplodedNode *Pred, const ProgramState *St, SVal TargetLV, SVal Val,
452                 const ProgramPointTag *tag = 0);
453private:
454  void evalLoadCommon(ExplodedNodeSet &Dst, const Expr *Ex, ExplodedNode *Pred,
455                      const ProgramState *St, SVal location, const ProgramPointTag *tag,
456                      QualType LoadTy);
457
458  // FIXME: 'tag' should be removed, and a LocationContext should be used
459  // instead.
460  void evalLocation(ExplodedNodeSet &Dst, const Stmt *S, ExplodedNode *Pred,
461                    const ProgramState *St, SVal location,
462                    const ProgramPointTag *tag, bool isLoad);
463
464  bool InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE, ExplodedNode *Pred);
465
466
467public:
468  /// Returns true if calling the specific function or method would possibly
469  /// cause global variables to be invalidated.
470  bool doesInvalidateGlobals(const CallOrObjCMessage &callOrMessage) const;
471
472};
473
474} // end ento namespace
475
476} // end clang namespace
477
478#endif
479