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