clang  9.0.0svn
ExprEngine.h
Go to the documentation of this file.
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_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
17 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
18 
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/Type.h"
21 #include "clang/Analysis/CFG.h"
24 #include "clang/Basic/LLVM.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include <cassert>
38 #include <utility>
39 
40 namespace clang {
41 
42 class AnalysisDeclContextManager;
43 class AnalyzerOptions;
44 class ASTContext;
45 class ConstructionContext;
46 class CXXBindTemporaryExpr;
47 class CXXCatchStmt;
48 class CXXConstructExpr;
49 class CXXDeleteExpr;
50 class CXXNewExpr;
51 class CXXThisExpr;
52 class Decl;
53 class DeclStmt;
54 class GCCAsmStmt;
55 class LambdaExpr;
56 class LocationContext;
57 class MaterializeTemporaryExpr;
58 class MSAsmStmt;
59 class NamedDecl;
60 class ObjCAtSynchronizedStmt;
61 class ObjCForCollectionStmt;
62 class ObjCIvarRefExpr;
63 class ObjCMessageExpr;
64 class ReturnStmt;
65 class Stmt;
66 
67 namespace cross_tu {
68 
69 class CrossTranslationUnitContext;
70 
71 } // namespace cross_tu
72 
73 namespace ento {
74 
75 class BasicValueFactory;
76 class CallEvent;
77 class CheckerManager;
78 class ConstraintManager;
79 class CXXTempObjectRegion;
80 class MemRegion;
81 class RegionAndSymbolInvalidationTraits;
82 class SymbolManager;
83 
84 class ExprEngine : public SubEngine {
85 public:
86  /// The modes of inlining, which override the default analysis-wide settings.
88  /// Follow the default settings for inlining callees.
89  Inline_Regular = 0,
90 
91  /// Do minimal inlining of callees.
92  Inline_Minimal = 0x1
93  };
94 
95  /// Hints for figuring out of a call should be inlined during evalCall().
96  struct EvalCallOptions {
97  /// This call is a constructor or a destructor for which we do not currently
98  /// compute the this-region correctly.
99  bool IsCtorOrDtorWithImproperlyModeledTargetRegion = false;
100 
101  /// This call is a constructor or a destructor for a single element within
102  /// an array, a part of array construction or destruction.
103  bool IsArrayCtorOrDtor = false;
104 
105  /// This call is a constructor or a destructor of a temporary value.
106  bool IsTemporaryCtorOrDtor = false;
107 
108  /// This call is a constructor for a temporary that is lifetime-extended
109  /// by binding it to a reference-type field within an aggregate,
110  /// for example 'A { const C &c; }; A a = { C() };'
111  bool IsTemporaryLifetimeExtendedViaAggregate = false;
112 
114  };
115 
116 private:
118 
119  AnalysisManager &AMgr;
120 
121  AnalysisDeclContextManager &AnalysisDeclContexts;
122 
123  CoreEngine Engine;
124 
125  /// G - the simulation graph.
126  ExplodedGraph &G;
127 
128  /// StateMgr - Object that manages the data for all created states.
129  ProgramStateManager StateMgr;
130 
131  /// SymMgr - Object that manages the symbol information.
132  SymbolManager &SymMgr;
133 
134  /// MRMgr - MemRegionManager object that creates memory regions.
135  MemRegionManager &MRMgr;
136 
137  /// svalBuilder - SValBuilder object that creates SVals from expressions.
138  SValBuilder &svalBuilder;
139 
140  unsigned int currStmtIdx = 0;
141  const NodeBuilderContext *currBldrCtx = nullptr;
142 
143  /// Helper object to determine if an Objective-C message expression
144  /// implicitly never returns.
145  ObjCNoReturn ObjCNoRet;
146 
147  /// The BugReporter associated with this engine. It is important that
148  /// this object be placed at the very end of member variables so that its
149  /// destructor is called before the rest of the ExprEngine is destroyed.
150  GRBugReporter BR;
151 
152  /// The functions which have been analyzed through inlining. This is owned by
153  /// AnalysisConsumer. It can be null.
154  SetOfConstDecls *VisitedCallees;
155 
156  /// The flag, which specifies the mode of inlining for the engine.
157  InliningModes HowToInline;
158 
159 public:
161  SetOfConstDecls *VisitedCalleesIn,
162  FunctionSummariesTy *FS, InliningModes HowToInlineIn);
163 
164  ~ExprEngine() override;
165 
166  /// Returns true if there is still simulation state on the worklist.
167  bool ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) {
168  return Engine.ExecuteWorkList(L, Steps, nullptr);
169  }
170 
171  /// Execute the work list with an initial state. Nodes that reaches the exit
172  /// of the function are added into the Dst set, which represent the exit
173  /// state of the function call. Returns true if there is still simulation
174  /// state on the worklist.
175  bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps,
176  ProgramStateRef InitState,
177  ExplodedNodeSet &Dst) {
178  return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst);
179  }
180 
181  /// getContext - Return the ASTContext associated with this analysis.
182  ASTContext &getContext() const { return AMgr.getASTContext(); }
183 
184  AnalysisManager &getAnalysisManager() override { return AMgr; }
185 
187  return AMgr.getAnalysisDeclContextManager();
188  }
189 
191  return *AMgr.getCheckerManager();
192  }
193 
194  SValBuilder &getSValBuilder() { return svalBuilder; }
195 
196  BugReporter &getBugReporter() { return BR; }
197 
200  return &CTU;
201  }
202 
204  assert(currBldrCtx);
205  return *currBldrCtx;
206  }
207 
208  const Stmt *getStmt() const;
209 
210  void GenerateAutoTransition(ExplodedNode *N);
211  void enqueueEndOfPath(ExplodedNodeSet &S);
212  void GenerateCallExitNode(ExplodedNode *N);
213 
214 
215  /// Dump graph to the specified filename.
216  /// If filename is empty, generate a temporary one.
217  /// \return The filename the graph is written into.
218  std::string DumpGraph(bool trim = false, StringRef Filename="");
219 
220  /// Dump the graph consisting of the given nodes to a specified filename.
221  /// Generate a temporary filename if it's not provided.
222  /// \return The filename the graph is written into.
223  std::string DumpGraph(ArrayRef<const ExplodedNode *> Nodes,
224  StringRef Filename = "");
225 
226  /// Visualize the ExplodedGraph created by executing the simulation.
227  void ViewGraph(bool trim = false);
228 
229  /// Visualize a trimmed ExplodedGraph that only contains paths to the given
230  /// nodes.
231  void ViewGraph(ArrayRef<const ExplodedNode *> Nodes);
232 
233  /// getInitialState - Return the initial state used for the root vertex
234  /// in the ExplodedGraph.
235  ProgramStateRef getInitialState(const LocationContext *InitLoc) override;
236 
237  ExplodedGraph &getGraph() { return G; }
238  const ExplodedGraph &getGraph() const { return G; }
239 
240  /// Run the analyzer's garbage collection - remove dead symbols and
241  /// bindings from the state.
242  ///
243  /// Checkers can participate in this process with two callbacks:
244  /// \c checkLiveSymbols and \c checkDeadSymbols. See the CheckerDocumentation
245  /// class for more information.
246  ///
247  /// \param Node The predecessor node, from which the processing should start.
248  /// \param Out The returned set of output nodes.
249  /// \param ReferenceStmt The statement which is about to be processed.
250  /// Everything needed for this statement should be considered live.
251  /// A null statement means that everything in child LocationContexts
252  /// is dead.
253  /// \param LC The location context of the \p ReferenceStmt. A null location
254  /// context means that we have reached the end of analysis and that
255  /// all statements and local variables should be considered dead.
256  /// \param DiagnosticStmt Used as a location for any warnings that should
257  /// occur while removing the dead (e.g. leaks). By default, the
258  /// \p ReferenceStmt is used.
259  /// \param K Denotes whether this is a pre- or post-statement purge. This
260  /// must only be ProgramPoint::PostStmtPurgeDeadSymbolsKind if an
261  /// entire location context is being cleared, in which case the
262  /// \p ReferenceStmt must either be a ReturnStmt or \c NULL. Otherwise,
263  /// it must be ProgramPoint::PreStmtPurgeDeadSymbolsKind (the default)
264  /// and \p ReferenceStmt must be valid (non-null).
265  void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out,
266  const Stmt *ReferenceStmt, const LocationContext *LC,
267  const Stmt *DiagnosticStmt = nullptr,
269 
270  /// processCFGElement - Called by CoreEngine. Used to generate new successor
271  /// nodes by processing the 'effects' of a CFG element.
272  void processCFGElement(const CFGElement E, ExplodedNode *Pred,
273  unsigned StmtIdx, NodeBuilderContext *Ctx) override;
274 
275  void ProcessStmt(const Stmt *S, ExplodedNode *Pred);
276 
277  void ProcessLoopExit(const Stmt* S, ExplodedNode *Pred);
278 
279  void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred);
280 
281  void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred);
282 
283  void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred);
284 
285  void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D,
286  ExplodedNode *Pred, ExplodedNodeSet &Dst);
287  void ProcessDeleteDtor(const CFGDeleteDtor D,
288  ExplodedNode *Pred, ExplodedNodeSet &Dst);
289  void ProcessBaseDtor(const CFGBaseDtor D,
290  ExplodedNode *Pred, ExplodedNodeSet &Dst);
291  void ProcessMemberDtor(const CFGMemberDtor D,
292  ExplodedNode *Pred, ExplodedNodeSet &Dst);
293  void ProcessTemporaryDtor(const CFGTemporaryDtor D,
294  ExplodedNode *Pred, ExplodedNodeSet &Dst);
295 
296  /// Called by CoreEngine when processing the entrance of a CFGBlock.
297  void processCFGBlockEntrance(const BlockEdge &L,
298  NodeBuilderWithSinks &nodeBuilder,
299  ExplodedNode *Pred) override;
300 
301  /// ProcessBranch - Called by CoreEngine. Used to generate successor
302  /// nodes by processing the 'effects' of a branch condition.
303  void processBranch(const Stmt *Condition,
304  NodeBuilderContext& BuilderCtx,
305  ExplodedNode *Pred,
306  ExplodedNodeSet &Dst,
307  const CFGBlock *DstT,
308  const CFGBlock *DstF) override;
309 
310  /// Called by CoreEngine.
311  /// Used to generate successor nodes for temporary destructors depending
312  /// on whether the corresponding constructor was visited.
313  void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
314  NodeBuilderContext &BldCtx,
315  ExplodedNode *Pred, ExplodedNodeSet &Dst,
316  const CFGBlock *DstT,
317  const CFGBlock *DstF) override;
318 
319  /// Called by CoreEngine. Used to processing branching behavior
320  /// at static initializers.
321  void processStaticInitializer(const DeclStmt *DS,
322  NodeBuilderContext& BuilderCtx,
323  ExplodedNode *Pred,
324  ExplodedNodeSet &Dst,
325  const CFGBlock *DstT,
326  const CFGBlock *DstF) override;
327 
328  /// processIndirectGoto - Called by CoreEngine. Used to generate successor
329  /// nodes by processing the 'effects' of a computed goto jump.
330  void processIndirectGoto(IndirectGotoNodeBuilder& builder) override;
331 
332  /// ProcessSwitch - Called by CoreEngine. Used to generate successor
333  /// nodes by processing the 'effects' of a switch statement.
334  void processSwitch(SwitchNodeBuilder& builder) override;
335 
336  /// Called by CoreEngine. Used to notify checkers that processing a
337  /// function has begun. Called for both inlined and and top-level functions.
338  void processBeginOfFunction(NodeBuilderContext &BC,
339  ExplodedNode *Pred, ExplodedNodeSet &Dst,
340  const BlockEdge &L) override;
341 
342  /// Called by CoreEngine. Used to notify checkers that processing a
343  /// function has ended. Called for both inlined and and top-level functions.
344  void processEndOfFunction(NodeBuilderContext& BC,
345  ExplodedNode *Pred,
346  const ReturnStmt *RS = nullptr) override;
347 
348  /// Remove dead bindings/symbols before exiting a function.
349  void removeDeadOnEndOfFunction(NodeBuilderContext& BC,
350  ExplodedNode *Pred,
351  ExplodedNodeSet &Dst);
352 
353  /// Generate the entry node of the callee.
354  void processCallEnter(NodeBuilderContext& BC, CallEnter CE,
355  ExplodedNode *Pred) override;
356 
357  /// Generate the sequence of nodes that simulate the call exit and the post
358  /// visit for CallExpr.
359  void processCallExit(ExplodedNode *Pred) override;
360 
361  /// Called by CoreEngine when the analysis worklist has terminated.
362  void processEndWorklist() override;
363 
364  /// evalAssume - Callback function invoked by the ConstraintManager when
365  /// making assumptions about state values.
366  ProgramStateRef processAssume(ProgramStateRef state, SVal cond,
367  bool assumption) override;
368 
369  /// processRegionChanges - Called by ProgramStateManager whenever a change is made
370  /// to the store. Used to update checkers that track region values.
372  processRegionChanges(ProgramStateRef state,
373  const InvalidatedSymbols *invalidated,
374  ArrayRef<const MemRegion *> ExplicitRegions,
376  const LocationContext *LCtx,
377  const CallEvent *Call) override;
378 
379  /// printState - Called by ProgramStateManager to print checker-specific data.
380  void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
381  const char *Sep,
382  const LocationContext *LCtx = nullptr) override;
383 
384  ProgramStateManager &getStateManager() override { return StateMgr; }
385 
386  StoreManager &getStoreManager() { return StateMgr.getStoreManager(); }
387 
389  return StateMgr.getConstraintManager();
390  }
391 
392  // FIXME: Remove when we migrate over to just using SValBuilder.
394  return StateMgr.getBasicVals();
395  }
396 
397  SymbolManager &getSymbolManager() { return SymMgr; }
398  MemRegionManager &getRegionManager() { return MRMgr; }
399 
400 
401  // Functions for external checking of whether we have unfinished work
402  bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
403  bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
404  bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); }
405 
406  const CoreEngine &getCoreEngine() const { return Engine; }
407 
408 public:
409  /// Visit - Transfer function logic for all statements. Dispatches to
410  /// other functions that handle specific kinds of statements.
411  void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst);
412 
413  /// VisitArraySubscriptExpr - Transfer function for array accesses.
414  void VisitArraySubscriptExpr(const ArraySubscriptExpr *Ex,
415  ExplodedNode *Pred,
416  ExplodedNodeSet &Dst);
417 
418  /// VisitGCCAsmStmt - Transfer function logic for inline asm.
419  void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
420  ExplodedNodeSet &Dst);
421 
422  /// VisitMSAsmStmt - Transfer function logic for MS inline asm.
423  void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
424  ExplodedNodeSet &Dst);
425 
426  /// VisitBlockExpr - Transfer function logic for BlockExprs.
427  void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
428  ExplodedNodeSet &Dst);
429 
430  /// VisitLambdaExpr - Transfer function logic for LambdaExprs.
431  void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
432  ExplodedNodeSet &Dst);
433 
434  /// VisitBinaryOperator - Transfer function logic for binary operators.
435  void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred,
436  ExplodedNodeSet &Dst);
437 
438 
439  /// VisitCall - Transfer function for function calls.
440  void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
441  ExplodedNodeSet &Dst);
442 
443  /// VisitCast - Transfer function logic for all casts (implicit and explicit).
444  void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred,
445  ExplodedNodeSet &Dst);
446 
447  /// VisitCompoundLiteralExpr - Transfer function logic for compound literals.
448  void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
449  ExplodedNode *Pred, ExplodedNodeSet &Dst);
450 
451  /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
452  void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D,
453  ExplodedNode *Pred, ExplodedNodeSet &Dst);
454 
455  /// VisitDeclStmt - Transfer function logic for DeclStmts.
456  void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
457  ExplodedNodeSet &Dst);
458 
459  /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
460  void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R,
461  ExplodedNode *Pred, ExplodedNodeSet &Dst);
462 
463  void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred,
464  ExplodedNodeSet &Dst);
465 
466  /// VisitLogicalExpr - Transfer function logic for '&&', '||'
467  void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
468  ExplodedNodeSet &Dst);
469 
470  /// VisitMemberExpr - Transfer function for member expressions.
471  void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
472  ExplodedNodeSet &Dst);
473 
474  /// VisitAtomicExpr - Transfer function for builtin atomic expressions
475  void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred,
476  ExplodedNodeSet &Dst);
477 
478  /// Transfer function logic for ObjCAtSynchronizedStmts.
479  void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
480  ExplodedNode *Pred, ExplodedNodeSet &Dst);
481 
482  /// Transfer function logic for computing the lvalue of an Objective-C ivar.
483  void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred,
484  ExplodedNodeSet &Dst);
485 
486  /// VisitObjCForCollectionStmt - Transfer function logic for
487  /// ObjCForCollectionStmt.
488  void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
489  ExplodedNode *Pred, ExplodedNodeSet &Dst);
490 
491  void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred,
492  ExplodedNodeSet &Dst);
493 
494  /// VisitReturnStmt - Transfer function logic for return statements.
495  void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred,
496  ExplodedNodeSet &Dst);
497 
498  /// VisitOffsetOfExpr - Transfer function for offsetof.
499  void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred,
500  ExplodedNodeSet &Dst);
501 
502  /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
503  void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
504  ExplodedNode *Pred, ExplodedNodeSet &Dst);
505 
506  /// VisitUnaryOperator - Transfer function logic for unary operators.
507  void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred,
508  ExplodedNodeSet &Dst);
509 
510  /// Handle ++ and -- (both pre- and post-increment).
511  void VisitIncrementDecrementOperator(const UnaryOperator* U,
512  ExplodedNode *Pred,
513  ExplodedNodeSet &Dst);
514 
515  void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
516  ExplodedNodeSet &PreVisit,
517  ExplodedNodeSet &Dst);
518 
519  void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred,
520  ExplodedNodeSet &Dst);
521 
522  void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
523  ExplodedNodeSet & Dst);
524 
525  void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred,
526  ExplodedNodeSet &Dst);
527 
528  void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest,
529  const Stmt *S, bool IsBaseDtor,
530  ExplodedNode *Pred, ExplodedNodeSet &Dst,
531  const EvalCallOptions &Options);
532 
533  void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
534  ExplodedNode *Pred,
535  ExplodedNodeSet &Dst);
536 
537  void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
538  ExplodedNodeSet &Dst);
539 
540  void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred,
541  ExplodedNodeSet &Dst);
542 
543  /// Create a C++ temporary object for an rvalue.
544  void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
545  ExplodedNode *Pred,
546  ExplodedNodeSet &Dst);
547 
548  /// evalEagerlyAssumeBinOpBifurcation - Given the nodes in 'Src', eagerly assume symbolic
549  /// expressions of the form 'x != 0' and generate new nodes (stored in Dst)
550  /// with those assumptions.
551  void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
552  const Expr *Ex);
553 
554  static std::pair<const ProgramPointTag *, const ProgramPointTag *>
555  geteagerlyAssumeBinOpBifurcationTags();
556 
558  return X.isValid() ? svalBuilder.evalMinus(X.castAs<NonLoc>()) : X;
559  }
560 
562  return X.isValid() ? svalBuilder.evalComplement(X.castAs<NonLoc>()) : X;
563  }
564 
565  ProgramStateRef handleLValueBitCast(ProgramStateRef state, const Expr *Ex,
566  const LocationContext *LCtx, QualType T,
567  QualType ExTy, const CastExpr *CastE,
568  StmtNodeBuilder &Bldr,
569  ExplodedNode *Pred);
570 
571  ProgramStateRef handleLVectorSplat(ProgramStateRef state,
572  const LocationContext *LCtx,
573  const CastExpr *CastE,
574  StmtNodeBuilder &Bldr,
575  ExplodedNode *Pred);
576 
577  void handleUOExtension(ExplodedNodeSet::iterator I,
578  const UnaryOperator* U,
579  StmtNodeBuilder &Bldr);
580 
581 public:
583  NonLoc L, NonLoc R, QualType T) {
584  return svalBuilder.evalBinOpNN(state, op, L, R, T);
585  }
586 
588  NonLoc L, SVal R, QualType T) {
589  return R.isValid() ? svalBuilder.evalBinOpNN(state, op, L,
590  R.castAs<NonLoc>(), T) : R;
591  }
592 
594  SVal LHS, SVal RHS, QualType T) {
595  return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
596  }
597 
598  /// By looking at a certain item that may be potentially part of an object's
599  /// ConstructionContext, retrieve such object's location. A particular
600  /// statement can be transparently passed as \p Item in most cases.
601  static Optional<SVal>
602  getObjectUnderConstruction(ProgramStateRef State,
603  const ConstructionContextItem &Item,
604  const LocationContext *LC);
605 
606 protected:
607  /// evalBind - Handle the semantics of binding a value to a specific location.
608  /// This method is used by evalStore, VisitDeclStmt, and others.
609  void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred,
610  SVal location, SVal Val, bool atDeclInit = false,
611  const ProgramPoint *PP = nullptr);
612 
613  /// Call PointerEscape callback when a value escapes as a result of bind.
614  ProgramStateRef processPointerEscapedOnBind(ProgramStateRef State,
615  SVal Loc,
616  SVal Val,
617  const LocationContext *LCtx) override;
618  /// Call PointerEscape callback when a value escapes as a result of
619  /// region invalidation.
620  /// \param[in] ITraits Specifies invalidation traits for regions/symbols.
621  ProgramStateRef notifyCheckersOfPointerEscape(
622  ProgramStateRef State,
623  const InvalidatedSymbols *Invalidated,
624  ArrayRef<const MemRegion *> ExplicitRegions,
625  const CallEvent *Call,
626  RegionAndSymbolInvalidationTraits &ITraits) override;
627 
628  /// A simple wrapper when you only need to notify checkers of pointer-escape
629  /// of a single value.
630  ProgramStateRef escapeValue(ProgramStateRef State, SVal V,
631  PointerEscapeKind K) const;
632 
633 public:
634  // FIXME: 'tag' should be removed, and a LocationContext should be used
635  // instead.
636  // FIXME: Comment on the meaning of the arguments, when 'St' may not
637  // be the same as Pred->state, and when 'location' may not be the
638  // same as state->getLValue(Ex).
639  /// Simulate a read of the result of Ex.
640  void evalLoad(ExplodedNodeSet &Dst,
641  const Expr *NodeEx, /* Eventually will be a CFGStmt */
642  const Expr *BoundExpr,
643  ExplodedNode *Pred,
644  ProgramStateRef St,
645  SVal location,
646  const ProgramPointTag *tag = nullptr,
647  QualType LoadTy = QualType());
648 
649  // FIXME: 'tag' should be removed, and a LocationContext should be used
650  // instead.
651  void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE,
652  ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val,
653  const ProgramPointTag *tag = nullptr);
654 
655  /// Return the CFG element corresponding to the worklist element
656  /// that is currently being processed by ExprEngine.
658  return (*currBldrCtx->getBlock())[currStmtIdx];
659  }
660 
661  /// Create a new state in which the call return value is binded to the
662  /// call origin expression.
663  ProgramStateRef bindReturnValue(const CallEvent &Call,
664  const LocationContext *LCtx,
665  ProgramStateRef State);
666 
667  /// Evaluate a call, running pre- and post-call checks and allowing checkers
668  /// to be responsible for handling the evaluation of the call itself.
669  void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
670  const CallEvent &Call);
671 
672  /// Default implementation of call evaluation.
673  void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred,
674  const CallEvent &Call,
675  const EvalCallOptions &CallOpts = {});
676 
677 private:
678  ProgramStateRef finishArgumentConstruction(ProgramStateRef State,
679  const CallEvent &Call);
680  void finishArgumentConstruction(ExplodedNodeSet &Dst, ExplodedNode *Pred,
681  const CallEvent &Call);
682 
683  void evalLoadCommon(ExplodedNodeSet &Dst,
684  const Expr *NodeEx, /* Eventually will be a CFGStmt */
685  const Expr *BoundEx,
686  ExplodedNode *Pred,
687  ProgramStateRef St,
688  SVal location,
689  const ProgramPointTag *tag,
690  QualType LoadTy);
691 
692  void evalLocation(ExplodedNodeSet &Dst,
693  const Stmt *NodeEx, /* This will eventually be a CFGStmt */
694  const Stmt *BoundEx,
695  ExplodedNode *Pred,
696  ProgramStateRef St,
697  SVal location,
698  bool isLoad);
699 
700  /// Count the stack depth and determine if the call is recursive.
701  void examineStackFrames(const Decl *D, const LocationContext *LCtx,
702  bool &IsRecursive, unsigned &StackDepth);
703 
704  enum CallInlinePolicy {
705  CIP_Allowed,
706  CIP_DisallowedOnce,
707  CIP_DisallowedAlways
708  };
709 
710  /// See if a particular call should be inlined, by only looking
711  /// at the call event and the current state of analysis.
712  CallInlinePolicy mayInlineCallKind(const CallEvent &Call,
713  const ExplodedNode *Pred,
714  AnalyzerOptions &Opts,
715  const EvalCallOptions &CallOpts);
716 
717  /// Checks our policies and decides weither the given call should be inlined.
718  bool shouldInlineCall(const CallEvent &Call, const Decl *D,
719  const ExplodedNode *Pred,
720  const EvalCallOptions &CallOpts = {});
721 
722  bool inlineCall(const CallEvent &Call, const Decl *D, NodeBuilder &Bldr,
723  ExplodedNode *Pred, ProgramStateRef State);
724 
725  /// Conservatively evaluate call by invalidating regions and binding
726  /// a conjured return value.
727  void conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr,
728  ExplodedNode *Pred, ProgramStateRef State);
729 
730  /// Either inline or process the call conservatively (or both), based
731  /// on DynamicDispatchBifurcation data.
732  void BifurcateCall(const MemRegion *BifurReg,
733  const CallEvent &Call, const Decl *D, NodeBuilder &Bldr,
734  ExplodedNode *Pred);
735 
736  bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC);
737 
738  /// Models a trivial copy or move constructor or trivial assignment operator
739  /// call with a simple bind.
740  void performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
741  const CallEvent &Call);
742 
743  /// If the value of the given expression \p InitWithAdjustments is a NonLoc,
744  /// copy it into a new temporary object region, and replace the value of the
745  /// expression with that.
746  ///
747  /// If \p Result is provided, the new region will be bound to this expression
748  /// instead of \p InitWithAdjustments.
749  ///
750  /// Returns the temporary region with adjustments into the optional
751  /// OutRegionWithAdjustments out-parameter if a new region was indeed needed,
752  /// otherwise sets it to nullptr.
753  ProgramStateRef createTemporaryRegionIfNeeded(
754  ProgramStateRef State, const LocationContext *LC,
755  const Expr *InitWithAdjustments, const Expr *Result = nullptr,
756  const SubRegion **OutRegionWithAdjustments = nullptr);
757 
758  /// Returns a region representing the first element of a (possibly
759  /// multi-dimensional) array, for the purposes of element construction or
760  /// destruction.
761  ///
762  /// On return, \p Ty will be set to the base type of the array.
763  ///
764  /// If the type is not an array type at all, the original value is returned.
765  /// Otherwise the "IsArray" flag is set.
766  static SVal makeZeroElementRegion(ProgramStateRef State, SVal LValue,
767  QualType &Ty, bool &IsArray);
768 
769  /// For a DeclStmt or CXXInitCtorInitializer, walk backward in the current CFG
770  /// block to find the constructor expression that directly constructed into
771  /// the storage for this statement. Returns null if the constructor for this
772  /// statement created a temporary object region rather than directly
773  /// constructing into an existing region.
774  const CXXConstructExpr *findDirectConstructorForCurrentCFGElement();
775 
776  /// Update the program state with all the path-sensitive information
777  /// that's necessary to perform construction of an object with a given
778  /// syntactic construction context. If the construction context is unavailable
779  /// or unusable for any reason, a dummy temporary region is returned, and the
780  /// IsConstructorWithImproperlyModeledTargetRegion flag is set in \p CallOpts.
781  /// Returns the updated program state and the new object's this-region.
782  std::pair<ProgramStateRef, SVal> prepareForObjectConstruction(
783  const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
784  const ConstructionContext *CC, EvalCallOptions &CallOpts);
785 
786  /// Store the location of a C++ object corresponding to a statement
787  /// until the statement is actually encountered. For example, if a DeclStmt
788  /// has CXXConstructExpr as its initializer, the object would be considered
789  /// to be "under construction" between CXXConstructExpr and DeclStmt.
790  /// This allows, among other things, to keep bindings to variable's fields
791  /// made within the constructor alive until its declaration actually
792  /// goes into scope.
793  static ProgramStateRef
794  addObjectUnderConstruction(ProgramStateRef State,
795  const ConstructionContextItem &Item,
796  const LocationContext *LC, SVal V);
797 
798  /// Mark the object sa fully constructed, cleaning up the state trait
799  /// that tracks objects under construction.
800  static ProgramStateRef
801  finishObjectConstruction(ProgramStateRef State,
802  const ConstructionContextItem &Item,
803  const LocationContext *LC);
804 
805  /// If the given expression corresponds to a temporary that was used for
806  /// passing into an elidable copy/move constructor and that constructor
807  /// was actually elided, track that we also need to elide the destructor.
808  static ProgramStateRef elideDestructor(ProgramStateRef State,
809  const CXXBindTemporaryExpr *BTE,
810  const LocationContext *LC);
811 
812  /// Stop tracking the destructor that corresponds to an elided constructor.
813  static ProgramStateRef
814  cleanupElidedDestructor(ProgramStateRef State,
815  const CXXBindTemporaryExpr *BTE,
816  const LocationContext *LC);
817 
818  /// Returns true if the given expression corresponds to a temporary that
819  /// was constructed for passing into an elidable copy/move constructor
820  /// and that constructor was actually elided.
821  static bool isDestructorElided(ProgramStateRef State,
822  const CXXBindTemporaryExpr *BTE,
823  const LocationContext *LC);
824 
825  /// Check if all objects under construction have been fully constructed
826  /// for the given context range (including FromLC, not including ToLC).
827  /// This is useful for assertions. Also checks if elided destructors
828  /// were cleaned up.
829  static bool areAllObjectsFullyConstructed(ProgramStateRef State,
830  const LocationContext *FromLC,
831  const LocationContext *ToLC);
832 };
833 
834 /// Traits for storing the call processing policy inside GDM.
835 /// The GDM stores the corresponding CallExpr pointer.
836 // FIXME: This does not use the nice trait macros because it must be accessible
837 // from multiple translation units.
839 template <>
841  public ProgramStatePartialTrait<const void*> {
842  static void *GDMIndex();
843 };
844 
845 } // namespace ento
846 
847 } // namespace clang
848 
849 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
MemRegionManager & getRegionManager()
Definition: ExprEngine.h:398
AnalysisDeclContextManager & getAnalysisDeclContextManager()
This represents a GCC inline-assembly statement extension.
Definition: Stmt.h:2675
A (possibly-)qualified type.
Definition: Type.h:638
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:95
CheckerManager * getCheckerManager() const
bool ExecuteWorkList(const LocationContext *L, unsigned Steps, ProgramStateRef InitState)
ExecuteWorkList - Run the worklist algorithm for a maximum number of steps.
Definition: CoreEngine.cpp:81
Stmt - This represents one statement.
Definition: Stmt.h:66
Information about invalidation for a particular region/symbol.
Definition: MemRegion.h:1443
BasicValueFactory & getBasicVals()
Definition: ProgramState.h:538
This builder class is useful for generating nodes that resulted from visiting a statement.
Definition: CoreEngine.h:370
C Language Family Type Representation.
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
Represents a point when we begin processing an inlined call.
Definition: ProgramPoint.h:632
StringRef P
bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps, ProgramStateRef InitState, ExplodedNodeSet &Dst)
Execute the work list with an initial state.
Definition: ExprEngine.h:175
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc L, NonLoc R, QualType T)
Definition: ExprEngine.h:582
Represents C++ object destructor generated from a call to delete.
Definition: CFG.h:409
Hints for figuring out of a call should be inlined during evalCall().
Definition: ExprEngine.h:96
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1262
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4156
cross_tu::CrossTranslationUnitContext * getCrossTranslationUnitContext() override
Definition: ExprEngine.h:199
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2932
const NodeBuilderContext & getBuilderContext()
Definition: ExprEngine.h:203
bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps, ProgramStateRef InitState, ExplodedNodeSet &Dst)
Returns true if there is still simulation state on the worklist.
Definition: CoreEngine.cpp:198
BoundNodesTreeBuilder Nodes
bool hasWorkRemaining() const
Definition: CoreEngine.h:155
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
LineState State
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Definition: CFG.h:384
bool hasEmptyWorkList() const
Definition: ExprEngine.h:403
bool wasBlocksExhausted() const
Definition: ExprEngine.h:402
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
AnalysisDeclContextManager & getAnalysisDeclContextManager()
Definition: ExprEngine.h:186
Describes an C or C++ initializer list.
Definition: Expr.h:4192
BinaryOperatorKind
WorkList * getWorkList() const
Definition: CoreEngine.h:165
CFGElement getCurrentCFGElement()
Return the CFG element corresponding to the worklist element that is currently being processed by Exp...
Definition: ExprEngine.h:657
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3294
const CoreEngine & getCoreEngine() const
Definition: ExprEngine.h:406
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3005
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1217
SVal evalComplement(SVal X)
Definition: ExprEngine.h:561
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1649
ASTContext & getASTContext() override
Represents the this expression in C++.
Definition: ExprCXX.h:976
CheckerManager & getCheckerManager() const
Definition: ExprEngine.h:190
StringRef Filename
Definition: Format.cpp:1629
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:2229
SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, SVal LHS, SVal RHS, QualType T)
Definition: ExprEngine.h:593
Represents a single basic block in a source-level CFG.
Definition: CFG.h:552
InliningModes
The modes of inlining, which override the default analysis-wide settings.
Definition: ExprEngine.h:87
This represents one expression.
Definition: Expr.h:107
virtual SVal evalMinus(NonLoc val)=0
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5184
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition: CoreEngine.h:228
bool isValid() const
Definition: SVals.h:149
Represents Objective-C&#39;s @synchronized statement.
Definition: StmtObjC.h:262
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition: ExprEngine.h:182
Traits for storing the call processing policy inside GDM.
Definition: ExprEngine.h:838
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:2443
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type)
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:904
This represents a Microsoft inline-assembly statement extension.
Definition: Stmt.h:2850
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1903
Represents C++ object destructor implicitly generated for base object in destructor.
Definition: CFG.h:435
SymbolManager & getSymbolManager()
Definition: ExprEngine.h:397
BugReporter is a utility class for generating PathDiagnostics for analysis.
Definition: BugReporter.h:412
ProgramPoints can be "tagged" as representing points specific to a given analysis entity...
Definition: ProgramPoint.h:40
AnalysisManager & getAnalysisManager() override
Definition: ExprEngine.h:184
bool wasBlocksExhausted() const
Definition: CoreEngine.h:154
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1914
virtual bool hasWork() const =0
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:1143
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:76
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>, and corresponding __opencl_atomic_* for OpenCL 2.0.
Definition: Expr.h:5440
BugReporter & getBugReporter()
Definition: ExprEngine.h:196
BasicValueFactory & getBasicVals()
Definition: ExprEngine.h:393
virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy)=0
Create a new value which represents a binary expression with two non- location operands.
bool ExecuteWorkList(const LocationContext *L, unsigned Steps=150000)
Returns true if there is still simulation state on the worklist.
Definition: ExprEngine.h:167
ast_type_traits::DynTypedNode Node
CoreEngine - Implements the core logic of the graph-reachability analysis.
Definition: CoreEngine.h:55
Dataflow Directional Tag Classes.
SValBuilder & getSValBuilder()
Definition: ExprEngine.h:194
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2170
StoreManager & getStoreManager()
Definition: ExprEngine.h:386
bool hasWorkRemaining() const
Definition: ExprEngine.h:404
This node builder keeps track of the generated sink nodes.
Definition: CoreEngine.h:333
const ExplodedGraph & getGraph() const
Definition: ExprEngine.h:238
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:171
ProgramStateManager & getStateManager() override
Definition: ExprEngine.h:384
This class is used for tools that requires cross translation unit capability.
Represents a single point (AST node) in the program that requires attention during construction of an...
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
ConstraintManager & getConstraintManager()
Definition: ProgramState.h:565
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:104
SVal evalMinus(SVal X)
Definition: ExprEngine.h:557
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2319
SubRegion - A region that subsets another larger region.
Definition: MemRegion.h:436
Represents Objective-C&#39;s collection statement.
Definition: StmtObjC.h:24
Stores options for the analyzer from the command line.
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13969
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2689
ConstructionContext&#39;s subclasses describe different ways of constructing an object in C++...
virtual SVal evalComplement(NonLoc val)=0
Represents C++ object destructor implicitly generated by compiler on various occasions.
Definition: CFG.h:359
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc L, SVal R, QualType T)
Definition: ExprEngine.h:587
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:29
Represents a top-level expression in a basic block.
Definition: CFG.h:56
GRBugReporter is used for generating path-sensitive reports.
Definition: BugReporter.h:513
Represents C++ object destructor implicitly generated for member object in destructor.
Definition: CFG.h:456
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2403
Represents C++ base or member initializer from constructor&#39;s initialization list. ...
Definition: CFG.h:220
ExplodedGraph & getGraph()
Definition: ExprEngine.h:237
This represents a decl that may have a name.
Definition: Decl.h:249
ConstraintManager & getConstraintManager()
Definition: ExprEngine.h:388
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type, member-designator).
Definition: Expr.h:2124
Represents C++ object destructor implicitly generated at the end of full expression for temporary obj...
Definition: CFG.h:477
const CFGBlock * getBlock() const
Return the CFGBlock associated with this builder.
Definition: CoreEngine.h:208