clang  7.0.0
ExprEngine.cpp
Go to the documentation of this file.
1 //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
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 GREngine, but provides the boilerplate to execute transfer
12 // functions and build the ExplodedGraph at the expression level.
13 //
14 //===----------------------------------------------------------------------===//
15 
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ParentMap.h"
28 #include "clang/AST/Stmt.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/StmtObjC.h"
31 #include "clang/AST/Type.h"
33 #include "clang/Analysis/CFG.h"
37 #include "clang/Basic/LLVM.h"
42 #include "clang/Basic/Specifiers.h"
63 #include "llvm/ADT/APSInt.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/ImmutableMap.h"
66 #include "llvm/ADT/ImmutableSet.h"
67 #include "llvm/ADT/Optional.h"
68 #include "llvm/ADT/SmallVector.h"
69 #include "llvm/ADT/Statistic.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/DOTGraphTraits.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/GraphWriter.h"
75 #include "llvm/Support/SaveAndRestore.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include <cassert>
78 #include <cstdint>
79 #include <memory>
80 #include <string>
81 #include <tuple>
82 #include <utility>
83 #include <vector>
84 
85 using namespace clang;
86 using namespace ento;
87 
88 #define DEBUG_TYPE "ExprEngine"
89 
90 STATISTIC(NumRemoveDeadBindings,
91  "The # of times RemoveDeadBindings is called");
92 STATISTIC(NumMaxBlockCountReached,
93  "The # of aborted paths due to reaching the maximum block count in "
94  "a top level function");
95 STATISTIC(NumMaxBlockCountReachedInInlined,
96  "The # of aborted paths due to reaching the maximum block count in "
97  "an inlined function");
98 STATISTIC(NumTimesRetriedWithoutInlining,
99  "The # of times we re-evaluated a call without inlining");
100 
101 
102 //===----------------------------------------------------------------------===//
103 // Internal program state traits.
104 //===----------------------------------------------------------------------===//
105 
106 // When modeling a C++ constructor, for a variety of reasons we need to track
107 // the location of the object for the duration of its ConstructionContext.
108 // ObjectsUnderConstruction maps statements within the construction context
109 // to the object's location, so that on every such statement the location
110 // could have been retrieved.
111 
112 /// ConstructedObjectKey is used for being able to find the path-sensitive
113 /// memory region of a freshly constructed object while modeling the AST node
114 /// that syntactically represents the object that is being constructed.
115 /// Semantics of such nodes may sometimes require access to the region that's
116 /// not otherwise present in the program state, or to the very fact that
117 /// the construction context was present and contained references to these
118 /// AST nodes.
120  typedef std::pair<ConstructionContextItem, const LocationContext *>
121  ConstructedObjectKeyImpl;
122 
123  const ConstructedObjectKeyImpl Impl;
124 
125  const void *getAnyASTNodePtr() const {
126  if (const Stmt *S = getItem().getStmtOrNull())
127  return S;
128  else
129  return getItem().getCXXCtorInitializer();
130  }
131 
132 public:
134  const LocationContext *LC)
135  : Impl(Item, LC) {}
136 
137  const ConstructionContextItem &getItem() const { return Impl.first; }
138  const LocationContext *getLocationContext() const { return Impl.second; }
139 
140  void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) {
141  OS << '(' << getLocationContext() << ',' << getAnyASTNodePtr() << ','
142  << getItem().getKindAsString();
144  OS << " #" << getItem().getIndex();
145  OS << ") ";
146  if (const Stmt *S = getItem().getStmtOrNull()) {
147  S->printPretty(OS, Helper, PP);
148  } else {
149  const CXXCtorInitializer *I = getItem().getCXXCtorInitializer();
150  OS << I->getAnyMember()->getNameAsString();
151  }
152  }
153 
154  void Profile(llvm::FoldingSetNodeID &ID) const {
155  ID.Add(Impl.first);
156  ID.AddPointer(Impl.second);
157  }
158 
159  bool operator==(const ConstructedObjectKey &RHS) const {
160  return Impl == RHS.Impl;
161  }
162 
163  bool operator<(const ConstructedObjectKey &RHS) const {
164  return Impl < RHS.Impl;
165  }
166 };
167 
168 typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
170 REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
172 
173 //===----------------------------------------------------------------------===//
174 // Engine construction and deletion.
175 //===----------------------------------------------------------------------===//
176 
177 static const char* TagProviderName = "ExprEngine";
178 
180  AnalysisManager &mgr, bool gcEnabled,
181  SetOfConstDecls *VisitedCalleesIn,
183  InliningModes HowToInlineIn)
184  : CTU(CTU), AMgr(mgr),
185  AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
186  Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()),
187  StateMgr(getContext(), mgr.getStoreManagerCreator(),
188  mgr.getConstraintManagerCreator(), G.getAllocator(),
189  this),
190  SymMgr(StateMgr.getSymbolManager()),
191  svalBuilder(StateMgr.getSValBuilder()), ObjCNoRet(mgr.getASTContext()),
192  ObjCGCEnabled(gcEnabled), BR(mgr, *this),
193  VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
194  unsigned TrimInterval = mgr.options.getGraphTrimInterval();
195  if (TrimInterval != 0) {
196  // Enable eager node reclaimation when constructing the ExplodedGraph.
197  G.enableNodeReclamation(TrimInterval);
198  }
199 }
200 
202  BR.FlushReports();
203 }
204 
205 //===----------------------------------------------------------------------===//
206 // Utility methods.
207 //===----------------------------------------------------------------------===//
208 
210  ProgramStateRef state = StateMgr.getInitialState(InitLoc);
211  const Decl *D = InitLoc->getDecl();
212 
213  // Preconditions.
214  // FIXME: It would be nice if we had a more general mechanism to add
215  // such preconditions. Some day.
216  do {
217  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
218  // Precondition: the first argument of 'main' is an integer guaranteed
219  // to be > 0.
220  const IdentifierInfo *II = FD->getIdentifier();
221  if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
222  break;
223 
224  const ParmVarDecl *PD = FD->getParamDecl(0);
225  QualType T = PD->getType();
226  const auto *BT = dyn_cast<BuiltinType>(T);
227  if (!BT || !BT->isInteger())
228  break;
229 
230  const MemRegion *R = state->getRegion(PD, InitLoc);
231  if (!R)
232  break;
233 
234  SVal V = state->getSVal(loc::MemRegionVal(R));
235  SVal Constraint_untested = evalBinOp(state, BO_GT, V,
236  svalBuilder.makeZeroVal(T),
237  svalBuilder.getConditionType());
238 
239  Optional<DefinedOrUnknownSVal> Constraint =
240  Constraint_untested.getAs<DefinedOrUnknownSVal>();
241 
242  if (!Constraint)
243  break;
244 
245  if (ProgramStateRef newState = state->assume(*Constraint, true))
246  state = newState;
247  }
248  break;
249  }
250  while (false);
251 
252  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
253  // Precondition: 'self' is always non-null upon entry to an Objective-C
254  // method.
255  const ImplicitParamDecl *SelfD = MD->getSelfDecl();
256  const MemRegion *R = state->getRegion(SelfD, InitLoc);
257  SVal V = state->getSVal(loc::MemRegionVal(R));
258 
259  if (Optional<Loc> LV = V.getAs<Loc>()) {
260  // Assume that the pointer value in 'self' is non-null.
261  state = state->assume(*LV, true);
262  assert(state && "'self' cannot be null");
263  }
264  }
265 
266  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
267  if (!MD->isStatic()) {
268  // Precondition: 'this' is always non-null upon entry to the
269  // top-level function. This is our starting assumption for
270  // analyzing an "open" program.
271  const StackFrameContext *SFC = InitLoc->getStackFrame();
272  if (SFC->getParent() == nullptr) {
273  loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
274  SVal V = state->getSVal(L);
275  if (Optional<Loc> LV = V.getAs<Loc>()) {
276  state = state->assume(*LV, true);
277  assert(state && "'this' cannot be null");
278  }
279  }
280  }
281  }
282 
283  return state;
284 }
285 
287 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
288  const LocationContext *LC,
289  const Expr *InitWithAdjustments,
290  const Expr *Result) {
291  // FIXME: This function is a hack that works around the quirky AST
292  // we're often having with respect to C++ temporaries. If only we modelled
293  // the actual execution order of statements properly in the CFG,
294  // all the hassle with adjustments would not be necessary,
295  // and perhaps the whole function would be removed.
296  SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
297  if (!Result) {
298  // If we don't have an explicit result expression, we're in "if needed"
299  // mode. Only create a region if the current value is a NonLoc.
300  if (!InitValWithAdjustments.getAs<NonLoc>())
301  return State;
302  Result = InitWithAdjustments;
303  } else {
304  // We need to create a region no matter what. For sanity, make sure we don't
305  // try to stuff a Loc into a non-pointer temporary region.
306  assert(!InitValWithAdjustments.getAs<Loc>() ||
307  Loc::isLocType(Result->getType()) ||
308  Result->getType()->isMemberPointerType());
309  }
310 
311  ProgramStateManager &StateMgr = State->getStateManager();
312  MemRegionManager &MRMgr = StateMgr.getRegionManager();
313  StoreManager &StoreMgr = StateMgr.getStoreManager();
314 
315  // MaterializeTemporaryExpr may appear out of place, after a few field and
316  // base-class accesses have been made to the object, even though semantically
317  // it is the whole object that gets materialized and lifetime-extended.
318  //
319  // For example:
320  //
321  // `-MaterializeTemporaryExpr
322  // `-MemberExpr
323  // `-CXXTemporaryObjectExpr
324  //
325  // instead of the more natural
326  //
327  // `-MemberExpr
328  // `-MaterializeTemporaryExpr
329  // `-CXXTemporaryObjectExpr
330  //
331  // Use the usual methods for obtaining the expression of the base object,
332  // and record the adjustments that we need to make to obtain the sub-object
333  // that the whole expression 'Ex' refers to. This trick is usual,
334  // in the sense that CodeGen takes a similar route.
335 
338 
339  const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
340  CommaLHSs, Adjustments);
341 
342  // Take the region for Init, i.e. for the whole object. If we do not remember
343  // the region in which the object originally was constructed, come up with
344  // a new temporary region out of thin air and copy the contents of the object
345  // (which are currently present in the Environment, because Init is an rvalue)
346  // into that region. This is not correct, but it is better than nothing.
347  const TypedValueRegion *TR = nullptr;
348  if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
349  if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
350  State = finishObjectConstruction(State, MT, LC);
351  State = State->BindExpr(Result, LC, *V);
352  return State;
353  } else {
354  StorageDuration SD = MT->getStorageDuration();
355  // If this object is bound to a reference with static storage duration, we
356  // put it in a different region to prevent "address leakage" warnings.
357  if (SD == SD_Static || SD == SD_Thread) {
358  TR = MRMgr.getCXXStaticTempObjectRegion(Init);
359  } else {
360  TR = MRMgr.getCXXTempObjectRegion(Init, LC);
361  }
362  }
363  } else {
364  TR = MRMgr.getCXXTempObjectRegion(Init, LC);
365  }
366 
367  SVal Reg = loc::MemRegionVal(TR);
368  SVal BaseReg = Reg;
369 
370  // Make the necessary adjustments to obtain the sub-object.
371  for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
372  const SubobjectAdjustment &Adj = *I;
373  switch (Adj.Kind) {
375  Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
376  break;
378  Reg = StoreMgr.getLValueField(Adj.Field, Reg);
379  break;
381  // FIXME: Unimplemented.
382  State = State->invalidateRegions(Reg, InitWithAdjustments,
383  currBldrCtx->blockCount(), LC, true,
384  nullptr, nullptr, nullptr);
385  return State;
386  }
387  }
388 
389  // What remains is to copy the value of the object to the new region.
390  // FIXME: In other words, what we should always do is copy value of the
391  // Init expression (which corresponds to the bigger object) to the whole
392  // temporary region TR. However, this value is often no longer present
393  // in the Environment. If it has disappeared, we instead invalidate TR.
394  // Still, what we can do is assign the value of expression Ex (which
395  // corresponds to the sub-object) to the TR's sub-region Reg. At least,
396  // values inside Reg would be correct.
397  SVal InitVal = State->getSVal(Init, LC);
398  if (InitVal.isUnknown()) {
399  InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
400  currBldrCtx->blockCount());
401  State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
402 
403  // Then we'd need to take the value that certainly exists and bind it
404  // over.
405  if (InitValWithAdjustments.isUnknown()) {
406  // Try to recover some path sensitivity in case we couldn't
407  // compute the value.
408  InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
409  Result, LC, InitWithAdjustments->getType(),
410  currBldrCtx->blockCount());
411  }
412  State =
413  State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
414  } else {
415  State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
416  }
417 
418  // The result expression would now point to the correct sub-region of the
419  // newly created temporary region. Do this last in order to getSVal of Init
420  // correctly in case (Result == Init).
421  State = State->BindExpr(Result, LC, Reg);
422 
423  // Notify checkers once for two bindLoc()s.
424  State = processRegionChange(State, TR, LC);
425 
426  return State;
427 }
428 
430 ExprEngine::addObjectUnderConstruction(ProgramStateRef State,
431  const ConstructionContextItem &Item,
432  const LocationContext *LC, SVal V) {
433  ConstructedObjectKey Key(Item, LC->getStackFrame());
434  // FIXME: Currently the state might already contain the marker due to
435  // incorrect handling of temporaries bound to default parameters.
436  assert(!State->get<ObjectsUnderConstruction>(Key) ||
437  Key.getItem().getKind() ==
439  return State->set<ObjectsUnderConstruction>(Key, V);
440 }
441 
444  const ConstructionContextItem &Item,
445  const LocationContext *LC) {
446  ConstructedObjectKey Key(Item, LC->getStackFrame());
447  return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
448 }
449 
451 ExprEngine::finishObjectConstruction(ProgramStateRef State,
452  const ConstructionContextItem &Item,
453  const LocationContext *LC) {
454  ConstructedObjectKey Key(Item, LC->getStackFrame());
455  assert(State->contains<ObjectsUnderConstruction>(Key));
456  return State->remove<ObjectsUnderConstruction>(Key);
457 }
458 
459 ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
460  const CXXBindTemporaryExpr *BTE,
461  const LocationContext *LC) {
462  ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
463  // FIXME: Currently the state might already contain the marker due to
464  // incorrect handling of temporaries bound to default parameters.
465  return State->set<ObjectsUnderConstruction>(Key, UnknownVal());
466 }
467 
469 ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
470  const CXXBindTemporaryExpr *BTE,
471  const LocationContext *LC) {
472  ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
473  assert(State->contains<ObjectsUnderConstruction>(Key));
474  return State->remove<ObjectsUnderConstruction>(Key);
475 }
476 
477 bool ExprEngine::isDestructorElided(ProgramStateRef State,
478  const CXXBindTemporaryExpr *BTE,
479  const LocationContext *LC) {
480  ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
481  return State->contains<ObjectsUnderConstruction>(Key);
482 }
483 
484 bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
485  const LocationContext *FromLC,
486  const LocationContext *ToLC) {
487  const LocationContext *LC = FromLC;
488  while (LC != ToLC) {
489  assert(LC && "ToLC must be a parent of FromLC!");
490  for (auto I : State->get<ObjectsUnderConstruction>())
491  if (I.first.getLocationContext() == LC)
492  return false;
493 
494  LC = LC->getParent();
495  }
496  return true;
497 }
498 
499 
500 //===----------------------------------------------------------------------===//
501 // Top-level transfer function logic (Dispatcher).
502 //===----------------------------------------------------------------------===//
503 
504 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
505 /// logic for handling assumptions on symbolic values.
507  SVal cond, bool assumption) {
508  return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
509 }
510 
513  const InvalidatedSymbols *invalidated,
514  ArrayRef<const MemRegion *> Explicits,
516  const LocationContext *LCtx,
517  const CallEvent *Call) {
518  return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
519  Explicits, Regions,
520  LCtx, Call);
521 }
522 
523 static void printObjectsUnderConstructionForContext(raw_ostream &Out,
524  ProgramStateRef State,
525  const char *NL,
526  const char *Sep,
527  const LocationContext *LC) {
528  PrintingPolicy PP =
530  for (auto I : State->get<ObjectsUnderConstruction>()) {
531  ConstructedObjectKey Key = I.first;
532  SVal Value = I.second;
533  if (Key.getLocationContext() != LC)
534  continue;
535  Key.print(Out, nullptr, PP);
536  Out << " : " << Value << NL;
537  }
538 }
539 
540 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
541  const char *NL, const char *Sep,
542  const LocationContext *LCtx) {
543  if (LCtx) {
544  if (!State->get<ObjectsUnderConstruction>().isEmpty()) {
545  Out << Sep << "Objects under construction:" << NL;
546 
547  LCtx->dumpStack(Out, "", NL, Sep, [&](const LocationContext *LC) {
548  printObjectsUnderConstructionForContext(Out, State, NL, Sep, LC);
549  });
550  }
551  }
552 
553  getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
554 }
555 
558 }
559 
561  unsigned StmtIdx, NodeBuilderContext *Ctx) {
563  currStmtIdx = StmtIdx;
564  currBldrCtx = Ctx;
565 
566  switch (E.getKind()) {
570  ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
571  return;
574  return;
577  Pred);
578  return;
585  return;
588  return;
592  return;
593  }
594 }
595 
597  const Stmt *S,
598  const ExplodedNode *Pred,
599  const LocationContext *LC) {
600  // Are we never purging state values?
601  if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
602  return false;
603 
604  // Is this the beginning of a basic block?
605  if (Pred->getLocation().getAs<BlockEntrance>())
606  return true;
607 
608  // Is this on a non-expression?
609  if (!isa<Expr>(S))
610  return true;
611 
612  // Run before processing a call.
613  if (CallEvent::isCallStmt(S))
614  return true;
615 
616  // Is this an expression that is consumed by another expression? If so,
617  // postpone cleaning out the state.
619  return !PM.isConsumedExpr(cast<Expr>(S));
620 }
621 
623  const Stmt *ReferenceStmt,
624  const LocationContext *LC,
625  const Stmt *DiagnosticStmt,
626  ProgramPoint::Kind K) {
628  ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
629  && "PostStmt is not generally supported by the SymbolReaper yet");
630  assert(LC && "Must pass the current (or expiring) LocationContext");
631 
632  if (!DiagnosticStmt) {
633  DiagnosticStmt = ReferenceStmt;
634  assert(DiagnosticStmt && "Required for clearing a LocationContext");
635  }
636 
637  NumRemoveDeadBindings++;
638  ProgramStateRef CleanedState = Pred->getState();
639 
640  // LC is the location context being destroyed, but SymbolReaper wants a
641  // location context that is still live. (If this is the top-level stack
642  // frame, this will be null.)
643  if (!ReferenceStmt) {
645  "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
646  LC = LC->getParent();
647  }
648 
649  const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
650  SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
651 
652  for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
653  if (SymbolRef Sym = I.second.getAsSymbol())
654  SymReaper.markLive(Sym);
655  if (const MemRegion *MR = I.second.getAsRegion())
656  SymReaper.markLive(MR);
657  }
658 
659  getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
660 
661  // Create a state in which dead bindings are removed from the environment
662  // and the store. TODO: The function should just return new env and store,
663  // not a new state.
664  CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
665 
666  // Process any special transfer function for dead symbols.
667  // A tag to track convenience transitions, which can be removed at cleanup.
668  static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
669  if (!SymReaper.hasDeadSymbols()) {
670  // Generate a CleanedNode that has the environment and store cleaned
671  // up. Since no symbols are dead, we can optimize and not clean out
672  // the constraint manager.
673  StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
674  Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
675 
676  } else {
677  // Call checkers with the non-cleaned state so that they could query the
678  // values of the soon to be dead symbols.
679  ExplodedNodeSet CheckedSet;
680  getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
681  DiagnosticStmt, *this, K);
682 
683  // For each node in CheckedSet, generate CleanedNodes that have the
684  // environment, the store, and the constraints cleaned up but have the
685  // user-supplied states as the predecessors.
686  StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
687  for (const auto I : CheckedSet) {
688  ProgramStateRef CheckerState = I->getState();
689 
690  // The constraint manager has not been cleaned up yet, so clean up now.
691  CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
692  SymReaper);
693 
694  assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
695  "Checkers are not allowed to modify the Environment as a part of "
696  "checkDeadSymbols processing.");
697  assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
698  "Checkers are not allowed to modify the Store as a part of "
699  "checkDeadSymbols processing.");
700 
701  // Create a state based on CleanedState with CheckerState GDM and
702  // generate a transition to that state.
703  ProgramStateRef CleanedCheckerSt =
704  StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
705  Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K);
706  }
707  }
708 }
709 
710 void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
711  // Reclaim any unnecessary nodes in the ExplodedGraph.
713 
714  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
715  currStmt->getLocStart(),
716  "Error evaluating statement");
717 
718  // Remove dead bindings and symbols.
719  ExplodedNodeSet CleanedStates;
720  if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
721  Pred->getLocationContext())) {
722  removeDead(Pred, CleanedStates, currStmt,
723  Pred->getLocationContext());
724  } else
725  CleanedStates.Add(Pred);
726 
727  // Visit the statement.
728  ExplodedNodeSet Dst;
729  for (const auto I : CleanedStates) {
730  ExplodedNodeSet DstI;
731  // Visit the statement.
732  Visit(currStmt, I, DstI);
733  Dst.insert(DstI);
734  }
735 
736  // Enqueue the new nodes onto the work list.
737  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
738 }
739 
741  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
742  S->getLocStart(),
743  "Error evaluating end of the loop");
744  ExplodedNodeSet Dst;
745  Dst.Add(Pred);
746  NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
747  ProgramStateRef NewState = Pred->getState();
748 
749  if(AMgr.options.shouldUnrollLoops())
750  NewState = processLoopEnd(S, NewState);
751 
752  LoopExit PP(S, Pred->getLocationContext());
753  Bldr.generateNode(PP, NewState, Pred);
754  // Enqueue the new nodes onto the work list.
755  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
756 }
757 
759  ExplodedNode *Pred) {
760  const CXXCtorInitializer *BMI = CFGInit.getInitializer();
761  const Expr *Init = BMI->getInit()->IgnoreImplicit();
762  const LocationContext *LC = Pred->getLocationContext();
763 
764  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
765  BMI->getSourceLocation(),
766  "Error evaluating initializer");
767 
768  // We don't clean up dead bindings here.
769  const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
770  const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
771 
772  ProgramStateRef State = Pred->getState();
773  SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
774 
775  ExplodedNodeSet Tmp;
776  SVal FieldLoc;
777 
778  // Evaluate the initializer, if necessary
779  if (BMI->isAnyMemberInitializer()) {
780  // Constructors build the object directly in the field,
781  // but non-objects must be copied in from the initializer.
782  if (getObjectUnderConstruction(State, BMI, LC)) {
783  // The field was directly constructed, so there is no need to bind.
784  // But we still need to stop tracking the object under construction.
785  State = finishObjectConstruction(State, BMI, LC);
786  NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
787  PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
788  Bldr.generateNode(PS, State, Pred);
789  } else {
790  const ValueDecl *Field;
791  if (BMI->isIndirectMemberInitializer()) {
792  Field = BMI->getIndirectMember();
793  FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
794  } else {
795  Field = BMI->getMember();
796  FieldLoc = State->getLValue(BMI->getMember(), thisVal);
797  }
798 
799  SVal InitVal;
800  if (Init->getType()->isArrayType()) {
801  // Handle arrays of trivial type. We can represent this with a
802  // primitive load/copy from the base array region.
803  const ArraySubscriptExpr *ASE;
804  while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
805  Init = ASE->getBase()->IgnoreImplicit();
806 
807  SVal LValue = State->getSVal(Init, stackFrame);
808  if (!Field->getType()->isReferenceType())
809  if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
810  InitVal = State->getSVal(*LValueLoc);
811 
812  // If we fail to get the value for some reason, use a symbolic value.
813  if (InitVal.isUnknownOrUndef()) {
814  SValBuilder &SVB = getSValBuilder();
815  InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
816  Field->getType(),
817  currBldrCtx->blockCount());
818  }
819  } else {
820  InitVal = State->getSVal(BMI->getInit(), stackFrame);
821  }
822 
823  PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
824  evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
825  }
826  } else {
827  assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
828  Tmp.insert(Pred);
829  // We already did all the work when visiting the CXXConstructExpr.
830  }
831 
832  // Construct PostInitializer nodes whether the state changed or not,
833  // so that the diagnostics don't get confused.
834  PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
835  ExplodedNodeSet Dst;
836  NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
837  for (const auto I : Tmp) {
838  ProgramStateRef State = I->getState();
839  Bldr.generateNode(PP, State, I);
840  }
841 
842  // Enqueue the new nodes onto the work list.
843  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
844 }
845 
847  ExplodedNode *Pred) {
848  ExplodedNodeSet Dst;
849  switch (D.getKind()) {
852  break;
854  ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
855  break;
857  ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
858  break;
861  break;
863  ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
864  break;
865  default:
866  llvm_unreachable("Unexpected dtor kind.");
867  }
868 
869  // Enqueue the new nodes onto the work list.
870  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
871 }
872 
874  ExplodedNode *Pred) {
875  ExplodedNodeSet Dst;
877  AnalyzerOptions &Opts = AMgr.options;
878  // TODO: We're not evaluating allocators for all cases just yet as
879  // we're not handling the return value correctly, which causes false
880  // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
881  if (Opts.mayInlineCXXAllocator())
882  VisitCXXNewAllocatorCall(NE, Pred, Dst);
883  else {
884  NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
885  const LocationContext *LCtx = Pred->getLocationContext();
886  PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
887  Bldr.generateNode(PP, Pred->getState(), Pred);
888  }
889  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
890 }
891 
893  ExplodedNode *Pred,
894  ExplodedNodeSet &Dst) {
895  const VarDecl *varDecl = Dtor.getVarDecl();
896  QualType varType = varDecl->getType();
897 
898  ProgramStateRef state = Pred->getState();
899  SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
900  const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
901 
902  if (varType->isReferenceType()) {
903  const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
904  if (!ValueRegion) {
905  // FIXME: This should not happen. The language guarantees a presence
906  // of a valid initializer here, so the reference shall not be undefined.
907  // It seems that we're calling destructors over variables that
908  // were not initialized yet.
909  return;
910  }
911  Region = ValueRegion->getBaseRegion();
912  varType = cast<TypedValueRegion>(Region)->getValueType();
913  }
914 
915  // FIXME: We need to run the same destructor on every element of the array.
916  // This workaround will just run the first destructor (which will still
917  // invalidate the entire array).
918  EvalCallOptions CallOpts;
919  Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType,
920  CallOpts.IsArrayCtorOrDtor).getAsRegion();
921 
922  VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
923  Pred, Dst, CallOpts);
924 }
925 
927  ExplodedNode *Pred,
928  ExplodedNodeSet &Dst) {
929  ProgramStateRef State = Pred->getState();
930  const LocationContext *LCtx = Pred->getLocationContext();
931  const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
932  const Stmt *Arg = DE->getArgument();
933  QualType DTy = DE->getDestroyedType();
934  SVal ArgVal = State->getSVal(Arg, LCtx);
935 
936  // If the argument to delete is known to be a null value,
937  // don't run destructor.
938  if (State->isNull(ArgVal).isConstrainedTrue()) {
940  const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
941  const CXXDestructorDecl *Dtor = RD->getDestructor();
942 
943  PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
944  NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
945  Bldr.generateNode(PP, Pred->getState(), Pred);
946  return;
947  }
948 
949  EvalCallOptions CallOpts;
950  const MemRegion *ArgR = ArgVal.getAsRegion();
951  if (DE->isArrayForm()) {
952  // FIXME: We need to run the same destructor on every element of the array.
953  // This workaround will just run the first destructor (which will still
954  // invalidate the entire array).
955  CallOpts.IsArrayCtorOrDtor = true;
956  // Yes, it may even be a multi-dimensional array.
957  while (const auto *AT = getContext().getAsArrayType(DTy))
958  DTy = AT->getElementType();
959  if (ArgR)
960  ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy);
961  }
962 
963  VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
964 }
965 
967  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
968  const LocationContext *LCtx = Pred->getLocationContext();
969 
970  const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
971  Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
972  LCtx->getStackFrame());
973  SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
974 
975  // Create the base object region.
977  QualType BaseTy = Base->getType();
978  SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
979  Base->isVirtual());
980 
982  CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {});
983 }
984 
986  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
987  const FieldDecl *Member = D.getFieldDecl();
988  QualType T = Member->getType();
989  ProgramStateRef State = Pred->getState();
990  const LocationContext *LCtx = Pred->getLocationContext();
991 
992  const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
993  Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
994  LCtx->getStackFrame());
995  SVal FieldVal =
996  State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
997 
998  // FIXME: We need to run the same destructor on every element of the array.
999  // This workaround will just run the first destructor (which will still
1000  // invalidate the entire array).
1001  EvalCallOptions CallOpts;
1002  FieldVal = makeZeroElementRegion(State, FieldVal, T,
1003  CallOpts.IsArrayCtorOrDtor);
1004 
1006  CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts);
1007 }
1008 
1010  ExplodedNode *Pred,
1011  ExplodedNodeSet &Dst) {
1012  const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr();
1013  ProgramStateRef State = Pred->getState();
1014  const LocationContext *LC = Pred->getLocationContext();
1015  const MemRegion *MR = nullptr;
1016 
1017  if (Optional<SVal> V =
1019  Pred->getLocationContext())) {
1020  // FIXME: Currently we insert temporary destructors for default parameters,
1021  // but we don't insert the constructors, so the entry in
1022  // ObjectsUnderConstruction may be missing.
1023  State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
1024  Pred->getLocationContext());
1025  MR = V->getAsRegion();
1026  }
1027 
1028  // If copy elision has occured, and the constructor corresponding to the
1029  // destructor was elided, we need to skip the destructor as well.
1030  if (isDestructorElided(State, BTE, LC)) {
1031  State = cleanupElidedDestructor(State, BTE, LC);
1032  NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1035  Pred->getLocationContext());
1036  Bldr.generateNode(PP, State, Pred);
1037  return;
1038  }
1039 
1040  ExplodedNodeSet CleanDtorState;
1041  StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
1042  StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
1043 
1045  // FIXME: Currently CleanDtorState can be empty here due to temporaries being
1046  // bound to default parameters.
1047  assert(CleanDtorState.size() <= 1);
1048  ExplodedNode *CleanPred =
1049  CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
1050 
1051  EvalCallOptions CallOpts;
1052  CallOpts.IsTemporaryCtorOrDtor = true;
1053  if (!MR) {
1055 
1056  // If we have no MR, we still need to unwrap the array to avoid destroying
1057  // the whole array at once. Regardless, we'd eventually need to model array
1058  // destructors properly, element-by-element.
1059  while (const ArrayType *AT = getContext().getAsArrayType(T)) {
1060  T = AT->getElementType();
1061  CallOpts.IsArrayCtorOrDtor = true;
1062  }
1063  } else {
1064  // We'd eventually need to makeZeroElementRegion() trick here,
1065  // but for now we don't have the respective construction contexts,
1066  // so MR would always be null in this case. Do nothing for now.
1067  }
1069  /*IsBase=*/false, CleanPred, Dst, CallOpts);
1070 }
1071 
1073  NodeBuilderContext &BldCtx,
1074  ExplodedNode *Pred,
1075  ExplodedNodeSet &Dst,
1076  const CFGBlock *DstT,
1077  const CFGBlock *DstF) {
1078  BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
1079  ProgramStateRef State = Pred->getState();
1080  const LocationContext *LC = Pred->getLocationContext();
1081  if (getObjectUnderConstruction(State, BTE, LC)) {
1082  TempDtorBuilder.markInfeasible(false);
1083  TempDtorBuilder.generateNode(State, true, Pred);
1084  } else {
1085  TempDtorBuilder.markInfeasible(true);
1086  TempDtorBuilder.generateNode(State, false, Pred);
1087  }
1088 }
1089 
1091  ExplodedNodeSet &PreVisit,
1092  ExplodedNodeSet &Dst) {
1093  // This is a fallback solution in case we didn't have a construction
1094  // context when we were constructing the temporary. Otherwise the map should
1095  // have been populated there.
1096  if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
1097  // In case we don't have temporary destructors in the CFG, do not mark
1098  // the initialization - we would otherwise never clean it up.
1099  Dst = PreVisit;
1100  return;
1101  }
1102  StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
1103  for (ExplodedNode *Node : PreVisit) {
1104  ProgramStateRef State = Node->getState();
1105  const LocationContext *LC = Node->getLocationContext();
1106  if (!getObjectUnderConstruction(State, BTE, LC)) {
1107  // FIXME: Currently the state might also already contain the marker due to
1108  // incorrect handling of temporaries bound to default parameters; for
1109  // those, we currently skip the CXXBindTemporaryExpr but rely on adding
1110  // temporary destructor nodes.
1111  State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
1112  }
1113  StmtBldr.generateNode(BTE, Node, State);
1114  }
1115 }
1116 
1118  PointerEscapeKind K) const {
1119  class CollectReachableSymbolsCallback final : public SymbolVisitor {
1120  InvalidatedSymbols Symbols;
1121 
1122  public:
1123  explicit CollectReachableSymbolsCallback(ProgramStateRef State) {}
1124 
1125  const InvalidatedSymbols &getSymbols() const { return Symbols; }
1126 
1127  bool VisitSymbol(SymbolRef Sym) override {
1128  Symbols.insert(Sym);
1129  return true;
1130  }
1131  };
1132 
1133  const CollectReachableSymbolsCallback &Scanner =
1134  State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
1136  State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
1137 }
1138 
1139 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
1140  ExplodedNodeSet &DstTop) {
1141  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1142  S->getLocStart(),
1143  "Error evaluating statement");
1144  ExplodedNodeSet Dst;
1145  StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
1146 
1147  assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
1148 
1149  switch (S->getStmtClass()) {
1150  // C++, OpenMP and ARC stuff we don't support yet.
1151  case Expr::ObjCIndirectCopyRestoreExprClass:
1152  case Stmt::CXXDependentScopeMemberExprClass:
1153  case Stmt::CXXInheritedCtorInitExprClass:
1154  case Stmt::CXXTryStmtClass:
1155  case Stmt::CXXTypeidExprClass:
1156  case Stmt::CXXUuidofExprClass:
1157  case Stmt::CXXFoldExprClass:
1158  case Stmt::MSPropertyRefExprClass:
1159  case Stmt::MSPropertySubscriptExprClass:
1160  case Stmt::CXXUnresolvedConstructExprClass:
1161  case Stmt::DependentScopeDeclRefExprClass:
1162  case Stmt::ArrayTypeTraitExprClass:
1163  case Stmt::ExpressionTraitExprClass:
1164  case Stmt::UnresolvedLookupExprClass:
1165  case Stmt::UnresolvedMemberExprClass:
1166  case Stmt::TypoExprClass:
1167  case Stmt::CXXNoexceptExprClass:
1168  case Stmt::PackExpansionExprClass:
1169  case Stmt::SubstNonTypeTemplateParmPackExprClass:
1170  case Stmt::FunctionParmPackExprClass:
1171  case Stmt::CoroutineBodyStmtClass:
1172  case Stmt::CoawaitExprClass:
1173  case Stmt::DependentCoawaitExprClass:
1174  case Stmt::CoreturnStmtClass:
1175  case Stmt::CoyieldExprClass:
1176  case Stmt::SEHTryStmtClass:
1177  case Stmt::SEHExceptStmtClass:
1178  case Stmt::SEHLeaveStmtClass:
1179  case Stmt::SEHFinallyStmtClass:
1180  case Stmt::OMPParallelDirectiveClass:
1181  case Stmt::OMPSimdDirectiveClass:
1182  case Stmt::OMPForDirectiveClass:
1183  case Stmt::OMPForSimdDirectiveClass:
1184  case Stmt::OMPSectionsDirectiveClass:
1185  case Stmt::OMPSectionDirectiveClass:
1186  case Stmt::OMPSingleDirectiveClass:
1187  case Stmt::OMPMasterDirectiveClass:
1188  case Stmt::OMPCriticalDirectiveClass:
1189  case Stmt::OMPParallelForDirectiveClass:
1190  case Stmt::OMPParallelForSimdDirectiveClass:
1191  case Stmt::OMPParallelSectionsDirectiveClass:
1192  case Stmt::OMPTaskDirectiveClass:
1193  case Stmt::OMPTaskyieldDirectiveClass:
1194  case Stmt::OMPBarrierDirectiveClass:
1195  case Stmt::OMPTaskwaitDirectiveClass:
1196  case Stmt::OMPTaskgroupDirectiveClass:
1197  case Stmt::OMPFlushDirectiveClass:
1198  case Stmt::OMPOrderedDirectiveClass:
1199  case Stmt::OMPAtomicDirectiveClass:
1200  case Stmt::OMPTargetDirectiveClass:
1201  case Stmt::OMPTargetDataDirectiveClass:
1202  case Stmt::OMPTargetEnterDataDirectiveClass:
1203  case Stmt::OMPTargetExitDataDirectiveClass:
1204  case Stmt::OMPTargetParallelDirectiveClass:
1205  case Stmt::OMPTargetParallelForDirectiveClass:
1206  case Stmt::OMPTargetUpdateDirectiveClass:
1207  case Stmt::OMPTeamsDirectiveClass:
1208  case Stmt::OMPCancellationPointDirectiveClass:
1209  case Stmt::OMPCancelDirectiveClass:
1210  case Stmt::OMPTaskLoopDirectiveClass:
1211  case Stmt::OMPTaskLoopSimdDirectiveClass:
1212  case Stmt::OMPDistributeDirectiveClass:
1213  case Stmt::OMPDistributeParallelForDirectiveClass:
1214  case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1215  case Stmt::OMPDistributeSimdDirectiveClass:
1216  case Stmt::OMPTargetParallelForSimdDirectiveClass:
1217  case Stmt::OMPTargetSimdDirectiveClass:
1218  case Stmt::OMPTeamsDistributeDirectiveClass:
1219  case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1220  case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1221  case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1222  case Stmt::OMPTargetTeamsDirectiveClass:
1223  case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1224  case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1225  case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1226  case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1227  case Stmt::CapturedStmtClass: {
1228  const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1229  Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1230  break;
1231  }
1232 
1233  case Stmt::ParenExprClass:
1234  llvm_unreachable("ParenExprs already handled.");
1235  case Stmt::GenericSelectionExprClass:
1236  llvm_unreachable("GenericSelectionExprs already handled.");
1237  // Cases that should never be evaluated simply because they shouldn't
1238  // appear in the CFG.
1239  case Stmt::BreakStmtClass:
1240  case Stmt::CaseStmtClass:
1241  case Stmt::CompoundStmtClass:
1242  case Stmt::ContinueStmtClass:
1243  case Stmt::CXXForRangeStmtClass:
1244  case Stmt::DefaultStmtClass:
1245  case Stmt::DoStmtClass:
1246  case Stmt::ForStmtClass:
1247  case Stmt::GotoStmtClass:
1248  case Stmt::IfStmtClass:
1249  case Stmt::IndirectGotoStmtClass:
1250  case Stmt::LabelStmtClass:
1251  case Stmt::NoStmtClass:
1252  case Stmt::NullStmtClass:
1253  case Stmt::SwitchStmtClass:
1254  case Stmt::WhileStmtClass:
1255  case Expr::MSDependentExistsStmtClass:
1256  llvm_unreachable("Stmt should not be in analyzer evaluation loop");
1257 
1258  case Stmt::ObjCSubscriptRefExprClass:
1259  case Stmt::ObjCPropertyRefExprClass:
1260  llvm_unreachable("These are handled by PseudoObjectExpr");
1261 
1262  case Stmt::GNUNullExprClass: {
1263  // GNU __null is a pointer-width integer, not an actual pointer.
1264  ProgramStateRef state = Pred->getState();
1265  state = state->BindExpr(S, Pred->getLocationContext(),
1266  svalBuilder.makeIntValWithPtrWidth(0, false));
1267  Bldr.generateNode(S, Pred, state);
1268  break;
1269  }
1270 
1271  case Stmt::ObjCAtSynchronizedStmtClass:
1272  Bldr.takeNodes(Pred);
1273  VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
1274  Bldr.addNodes(Dst);
1275  break;
1276 
1277  case Stmt::ExprWithCleanupsClass:
1278  // Handled due to fully linearised CFG.
1279  break;
1280 
1281  case Stmt::CXXBindTemporaryExprClass: {
1282  Bldr.takeNodes(Pred);
1283  ExplodedNodeSet PreVisit;
1284  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1285  ExplodedNodeSet Next;
1286  VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
1287  getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
1288  Bldr.addNodes(Dst);
1289  break;
1290  }
1291 
1292  // Cases not handled yet; but will handle some day.
1293  case Stmt::DesignatedInitExprClass:
1294  case Stmt::DesignatedInitUpdateExprClass:
1295  case Stmt::ArrayInitLoopExprClass:
1296  case Stmt::ArrayInitIndexExprClass:
1297  case Stmt::ExtVectorElementExprClass:
1298  case Stmt::ImaginaryLiteralClass:
1299  case Stmt::ObjCAtCatchStmtClass:
1300  case Stmt::ObjCAtFinallyStmtClass:
1301  case Stmt::ObjCAtTryStmtClass:
1302  case Stmt::ObjCAutoreleasePoolStmtClass:
1303  case Stmt::ObjCEncodeExprClass:
1304  case Stmt::ObjCIsaExprClass:
1305  case Stmt::ObjCProtocolExprClass:
1306  case Stmt::ObjCSelectorExprClass:
1307  case Stmt::ParenListExprClass:
1308  case Stmt::ShuffleVectorExprClass:
1309  case Stmt::ConvertVectorExprClass:
1310  case Stmt::VAArgExprClass:
1311  case Stmt::CUDAKernelCallExprClass:
1312  case Stmt::OpaqueValueExprClass:
1313  case Stmt::AsTypeExprClass:
1314  // Fall through.
1315 
1316  // Cases we intentionally don't evaluate, since they don't need
1317  // to be explicitly evaluated.
1318  case Stmt::PredefinedExprClass:
1319  case Stmt::AddrLabelExprClass:
1320  case Stmt::AttributedStmtClass:
1321  case Stmt::IntegerLiteralClass:
1322  case Stmt::FixedPointLiteralClass:
1323  case Stmt::CharacterLiteralClass:
1324  case Stmt::ImplicitValueInitExprClass:
1325  case Stmt::CXXScalarValueInitExprClass:
1326  case Stmt::CXXBoolLiteralExprClass:
1327  case Stmt::ObjCBoolLiteralExprClass:
1328  case Stmt::ObjCAvailabilityCheckExprClass:
1329  case Stmt::FloatingLiteralClass:
1330  case Stmt::NoInitExprClass:
1331  case Stmt::SizeOfPackExprClass:
1332  case Stmt::StringLiteralClass:
1333  case Stmt::ObjCStringLiteralClass:
1334  case Stmt::CXXPseudoDestructorExprClass:
1335  case Stmt::SubstNonTypeTemplateParmExprClass:
1336  case Stmt::CXXNullPtrLiteralExprClass:
1337  case Stmt::OMPArraySectionExprClass:
1338  case Stmt::TypeTraitExprClass: {
1339  Bldr.takeNodes(Pred);
1340  ExplodedNodeSet preVisit;
1341  getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1342  getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
1343  Bldr.addNodes(Dst);
1344  break;
1345  }
1346 
1347  case Stmt::CXXDefaultArgExprClass:
1348  case Stmt::CXXDefaultInitExprClass: {
1349  Bldr.takeNodes(Pred);
1350  ExplodedNodeSet PreVisit;
1351  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1352 
1353  ExplodedNodeSet Tmp;
1354  StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
1355 
1356  const Expr *ArgE;
1357  if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
1358  ArgE = DefE->getExpr();
1359  else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
1360  ArgE = DefE->getExpr();
1361  else
1362  llvm_unreachable("unknown constant wrapper kind");
1363 
1364  bool IsTemporary = false;
1365  if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
1366  ArgE = MTE->GetTemporaryExpr();
1367  IsTemporary = true;
1368  }
1369 
1370  Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
1371  if (!ConstantVal)
1372  ConstantVal = UnknownVal();
1373 
1374  const LocationContext *LCtx = Pred->getLocationContext();
1375  for (const auto I : PreVisit) {
1376  ProgramStateRef State = I->getState();
1377  State = State->BindExpr(S, LCtx, *ConstantVal);
1378  if (IsTemporary)
1379  State = createTemporaryRegionIfNeeded(State, LCtx,
1380  cast<Expr>(S),
1381  cast<Expr>(S));
1382  Bldr2.generateNode(S, I, State);
1383  }
1384 
1385  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1386  Bldr.addNodes(Dst);
1387  break;
1388  }
1389 
1390  // Cases we evaluate as opaque expressions, conjuring a symbol.
1391  case Stmt::CXXStdInitializerListExprClass:
1392  case Expr::ObjCArrayLiteralClass:
1393  case Expr::ObjCDictionaryLiteralClass:
1394  case Expr::ObjCBoxedExprClass: {
1395  Bldr.takeNodes(Pred);
1396 
1397  ExplodedNodeSet preVisit;
1398  getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1399 
1400  ExplodedNodeSet Tmp;
1401  StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
1402 
1403  const auto *Ex = cast<Expr>(S);
1404  QualType resultType = Ex->getType();
1405 
1406  for (const auto N : preVisit) {
1407  const LocationContext *LCtx = N->getLocationContext();
1408  SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1409  resultType,
1410  currBldrCtx->blockCount());
1411  ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
1412 
1413  // Escape pointers passed into the list, unless it's an ObjC boxed
1414  // expression which is not a boxable C structure.
1415  if (!(isa<ObjCBoxedExpr>(Ex) &&
1416  !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
1417  ->getType()->isRecordType()))
1418  for (auto Child : Ex->children()) {
1419  assert(Child);
1420  SVal Val = State->getSVal(Child, LCtx);
1421  State = escapeValue(State, Val, PSK_EscapeOther);
1422  }
1423 
1424  Bldr2.generateNode(S, N, State);
1425  }
1426 
1427  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1428  Bldr.addNodes(Dst);
1429  break;
1430  }
1431 
1432  case Stmt::ArraySubscriptExprClass:
1433  Bldr.takeNodes(Pred);
1434  VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1435  Bldr.addNodes(Dst);
1436  break;
1437 
1438  case Stmt::GCCAsmStmtClass:
1439  Bldr.takeNodes(Pred);
1440  VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1441  Bldr.addNodes(Dst);
1442  break;
1443 
1444  case Stmt::MSAsmStmtClass:
1445  Bldr.takeNodes(Pred);
1446  VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1447  Bldr.addNodes(Dst);
1448  break;
1449 
1450  case Stmt::BlockExprClass:
1451  Bldr.takeNodes(Pred);
1452  VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1453  Bldr.addNodes(Dst);
1454  break;
1455 
1456  case Stmt::LambdaExprClass:
1457  if (AMgr.options.shouldInlineLambdas()) {
1458  Bldr.takeNodes(Pred);
1459  VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1460  Bldr.addNodes(Dst);
1461  } else {
1462  const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1463  Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1464  }
1465  break;
1466 
1467  case Stmt::BinaryOperatorClass: {
1468  const auto *B = cast<BinaryOperator>(S);
1469  if (B->isLogicalOp()) {
1470  Bldr.takeNodes(Pred);
1471  VisitLogicalExpr(B, Pred, Dst);
1472  Bldr.addNodes(Dst);
1473  break;
1474  }
1475  else if (B->getOpcode() == BO_Comma) {
1476  ProgramStateRef state = Pred->getState();
1477  Bldr.generateNode(B, Pred,
1478  state->BindExpr(B, Pred->getLocationContext(),
1479  state->getSVal(B->getRHS(),
1480  Pred->getLocationContext())));
1481  break;
1482  }
1483 
1484  Bldr.takeNodes(Pred);
1485 
1486  if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
1487  (B->isRelationalOp() || B->isEqualityOp())) {
1488  ExplodedNodeSet Tmp;
1489  VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1490  evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1491  }
1492  else
1493  VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1494 
1495  Bldr.addNodes(Dst);
1496  break;
1497  }
1498 
1499  case Stmt::CXXOperatorCallExprClass: {
1500  const auto *OCE = cast<CXXOperatorCallExpr>(S);
1501 
1502  // For instance method operators, make sure the 'this' argument has a
1503  // valid region.
1504  const Decl *Callee = OCE->getCalleeDecl();
1505  if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1506  if (MD->isInstance()) {
1507  ProgramStateRef State = Pred->getState();
1508  const LocationContext *LCtx = Pred->getLocationContext();
1509  ProgramStateRef NewState =
1510  createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1511  if (NewState != State) {
1512  Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1514  // Did we cache out?
1515  if (!Pred)
1516  break;
1517  }
1518  }
1519  }
1520  // FALLTHROUGH
1521  LLVM_FALLTHROUGH;
1522  }
1523 
1524  case Stmt::CallExprClass:
1525  case Stmt::CXXMemberCallExprClass:
1526  case Stmt::UserDefinedLiteralClass:
1527  Bldr.takeNodes(Pred);
1528  VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1529  Bldr.addNodes(Dst);
1530  break;
1531 
1532  case Stmt::CXXCatchStmtClass:
1533  Bldr.takeNodes(Pred);
1534  VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1535  Bldr.addNodes(Dst);
1536  break;
1537 
1538  case Stmt::CXXTemporaryObjectExprClass:
1539  case Stmt::CXXConstructExprClass:
1540  Bldr.takeNodes(Pred);
1541  VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1542  Bldr.addNodes(Dst);
1543  break;
1544 
1545  case Stmt::CXXNewExprClass: {
1546  Bldr.takeNodes(Pred);
1547 
1548  ExplodedNodeSet PreVisit;
1549  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1550 
1551  ExplodedNodeSet PostVisit;
1552  for (const auto i : PreVisit)
1553  VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
1554 
1555  getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1556  Bldr.addNodes(Dst);
1557  break;
1558  }
1559 
1560  case Stmt::CXXDeleteExprClass: {
1561  Bldr.takeNodes(Pred);
1562  ExplodedNodeSet PreVisit;
1563  const auto *CDE = cast<CXXDeleteExpr>(S);
1564  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1565 
1566  for (const auto i : PreVisit)
1567  VisitCXXDeleteExpr(CDE, i, Dst);
1568 
1569  Bldr.addNodes(Dst);
1570  break;
1571  }
1572  // FIXME: ChooseExpr is really a constant. We need to fix
1573  // the CFG do not model them as explicit control-flow.
1574 
1575  case Stmt::ChooseExprClass: { // __builtin_choose_expr
1576  Bldr.takeNodes(Pred);
1577  const auto *C = cast<ChooseExpr>(S);
1578  VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1579  Bldr.addNodes(Dst);
1580  break;
1581  }
1582 
1583  case Stmt::CompoundAssignOperatorClass:
1584  Bldr.takeNodes(Pred);
1585  VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1586  Bldr.addNodes(Dst);
1587  break;
1588 
1589  case Stmt::CompoundLiteralExprClass:
1590  Bldr.takeNodes(Pred);
1591  VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1592  Bldr.addNodes(Dst);
1593  break;
1594 
1595  case Stmt::BinaryConditionalOperatorClass:
1596  case Stmt::ConditionalOperatorClass: { // '?' operator
1597  Bldr.takeNodes(Pred);
1598  const auto *C = cast<AbstractConditionalOperator>(S);
1599  VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1600  Bldr.addNodes(Dst);
1601  break;
1602  }
1603 
1604  case Stmt::CXXThisExprClass:
1605  Bldr.takeNodes(Pred);
1606  VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1607  Bldr.addNodes(Dst);
1608  break;
1609 
1610  case Stmt::DeclRefExprClass: {
1611  Bldr.takeNodes(Pred);
1612  const auto *DE = cast<DeclRefExpr>(S);
1613  VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1614  Bldr.addNodes(Dst);
1615  break;
1616  }
1617 
1618  case Stmt::DeclStmtClass:
1619  Bldr.takeNodes(Pred);
1620  VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1621  Bldr.addNodes(Dst);
1622  break;
1623 
1624  case Stmt::ImplicitCastExprClass:
1625  case Stmt::CStyleCastExprClass:
1626  case Stmt::CXXStaticCastExprClass:
1627  case Stmt::CXXDynamicCastExprClass:
1628  case Stmt::CXXReinterpretCastExprClass:
1629  case Stmt::CXXConstCastExprClass:
1630  case Stmt::CXXFunctionalCastExprClass:
1631  case Stmt::ObjCBridgedCastExprClass: {
1632  Bldr.takeNodes(Pred);
1633  const auto *C = cast<CastExpr>(S);
1634  ExplodedNodeSet dstExpr;
1635  VisitCast(C, C->getSubExpr(), Pred, dstExpr);
1636 
1637  // Handle the postvisit checks.
1638  getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1639  Bldr.addNodes(Dst);
1640  break;
1641  }
1642 
1643  case Expr::MaterializeTemporaryExprClass: {
1644  Bldr.takeNodes(Pred);
1645  const auto *MTE = cast<MaterializeTemporaryExpr>(S);
1646  ExplodedNodeSet dstPrevisit;
1647  getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
1648  ExplodedNodeSet dstExpr;
1649  for (const auto i : dstPrevisit)
1650  CreateCXXTemporaryObject(MTE, i, dstExpr);
1651  getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
1652  Bldr.addNodes(Dst);
1653  break;
1654  }
1655 
1656  case Stmt::InitListExprClass:
1657  Bldr.takeNodes(Pred);
1658  VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1659  Bldr.addNodes(Dst);
1660  break;
1661 
1662  case Stmt::MemberExprClass:
1663  Bldr.takeNodes(Pred);
1664  VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1665  Bldr.addNodes(Dst);
1666  break;
1667 
1668  case Stmt::AtomicExprClass:
1669  Bldr.takeNodes(Pred);
1670  VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
1671  Bldr.addNodes(Dst);
1672  break;
1673 
1674  case Stmt::ObjCIvarRefExprClass:
1675  Bldr.takeNodes(Pred);
1676  VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1677  Bldr.addNodes(Dst);
1678  break;
1679 
1680  case Stmt::ObjCForCollectionStmtClass:
1681  Bldr.takeNodes(Pred);
1682  VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1683  Bldr.addNodes(Dst);
1684  break;
1685 
1686  case Stmt::ObjCMessageExprClass:
1687  Bldr.takeNodes(Pred);
1688  VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1689  Bldr.addNodes(Dst);
1690  break;
1691 
1692  case Stmt::ObjCAtThrowStmtClass:
1693  case Stmt::CXXThrowExprClass:
1694  // FIXME: This is not complete. We basically treat @throw as
1695  // an abort.
1696  Bldr.generateSink(S, Pred, Pred->getState());
1697  break;
1698 
1699  case Stmt::ReturnStmtClass:
1700  Bldr.takeNodes(Pred);
1701  VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1702  Bldr.addNodes(Dst);
1703  break;
1704 
1705  case Stmt::OffsetOfExprClass: {
1706  Bldr.takeNodes(Pred);
1707  ExplodedNodeSet PreVisit;
1708  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1709 
1710  ExplodedNodeSet PostVisit;
1711  for (const auto Node : PreVisit)
1712  VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
1713 
1714  getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1715  Bldr.addNodes(Dst);
1716  break;
1717  }
1718 
1719  case Stmt::UnaryExprOrTypeTraitExprClass:
1720  Bldr.takeNodes(Pred);
1721  VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1722  Pred, Dst);
1723  Bldr.addNodes(Dst);
1724  break;
1725 
1726  case Stmt::StmtExprClass: {
1727  const auto *SE = cast<StmtExpr>(S);
1728 
1729  if (SE->getSubStmt()->body_empty()) {
1730  // Empty statement expression.
1731  assert(SE->getType() == getContext().VoidTy
1732  && "Empty statement expression must have void type.");
1733  break;
1734  }
1735 
1736  if (const auto *LastExpr =
1737  dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1738  ProgramStateRef state = Pred->getState();
1739  Bldr.generateNode(SE, Pred,
1740  state->BindExpr(SE, Pred->getLocationContext(),
1741  state->getSVal(LastExpr,
1742  Pred->getLocationContext())));
1743  }
1744  break;
1745  }
1746 
1747  case Stmt::UnaryOperatorClass: {
1748  Bldr.takeNodes(Pred);
1749  const auto *U = cast<UnaryOperator>(S);
1750  if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1751  ExplodedNodeSet Tmp;
1752  VisitUnaryOperator(U, Pred, Tmp);
1753  evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1754  }
1755  else
1756  VisitUnaryOperator(U, Pred, Dst);
1757  Bldr.addNodes(Dst);
1758  break;
1759  }
1760 
1761  case Stmt::PseudoObjectExprClass: {
1762  Bldr.takeNodes(Pred);
1763  ProgramStateRef state = Pred->getState();
1764  const auto *PE = cast<PseudoObjectExpr>(S);
1765  if (const Expr *Result = PE->getResultExpr()) {
1766  SVal V = state->getSVal(Result, Pred->getLocationContext());
1767  Bldr.generateNode(S, Pred,
1768  state->BindExpr(S, Pred->getLocationContext(), V));
1769  }
1770  else
1771  Bldr.generateNode(S, Pred,
1772  state->BindExpr(S, Pred->getLocationContext(),
1773  UnknownVal()));
1774 
1775  Bldr.addNodes(Dst);
1776  break;
1777  }
1778  }
1779 }
1780 
1781 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1782  const LocationContext *CalleeLC) {
1783  const StackFrameContext *CalleeSF = CalleeLC->getStackFrame();
1784  const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame();
1785  assert(CalleeSF && CallerSF);
1786  ExplodedNode *BeforeProcessingCall = nullptr;
1787  const Stmt *CE = CalleeSF->getCallSite();
1788 
1789  // Find the first node before we started processing the call expression.
1790  while (N) {
1791  ProgramPoint L = N->getLocation();
1792  BeforeProcessingCall = N;
1793  N = N->pred_empty() ? nullptr : *(N->pred_begin());
1794 
1795  // Skip the nodes corresponding to the inlined code.
1796  if (L.getStackFrame() != CallerSF)
1797  continue;
1798  // We reached the caller. Find the node right before we started
1799  // processing the call.
1800  if (L.isPurgeKind())
1801  continue;
1802  if (L.getAs<PreImplicitCall>())
1803  continue;
1804  if (L.getAs<CallEnter>())
1805  continue;
1806  if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1807  if (SP->getStmt() == CE)
1808  continue;
1809  break;
1810  }
1811 
1812  if (!BeforeProcessingCall)
1813  return false;
1814 
1815  // TODO: Clean up the unneeded nodes.
1816 
1817  // Build an Epsilon node from which we will restart the analyzes.
1818  // Note that CE is permitted to be NULL!
1819  ProgramPoint NewNodeLoc =
1820  EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1821  // Add the special flag to GDM to signal retrying with no inlining.
1822  // Note, changing the state ensures that we are not going to cache out.
1823  ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1824  NewNodeState =
1825  NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1826 
1827  // Make the new node a successor of BeforeProcessingCall.
1828  bool IsNew = false;
1829  ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1830  // We cached out at this point. Caching out is common due to us backtracking
1831  // from the inlined function, which might spawn several paths.
1832  if (!IsNew)
1833  return true;
1834 
1835  NewNode->addPredecessor(BeforeProcessingCall, G);
1836 
1837  // Add the new node to the work list.
1838  Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1839  CalleeSF->getIndex());
1840  NumTimesRetriedWithoutInlining++;
1841  return true;
1842 }
1843 
1844 /// Block entrance. (Update counters).
1846  NodeBuilderWithSinks &nodeBuilder,
1847  ExplodedNode *Pred) {
1849  // If we reach a loop which has a known bound (and meets
1850  // other constraints) then consider completely unrolling it.
1851  if(AMgr.options.shouldUnrollLoops()) {
1852  unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
1853  const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1854  if (Term) {
1855  ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
1856  Pred, maxBlockVisitOnPath);
1857  if (NewState != Pred->getState()) {
1858  ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
1859  if (!UpdatedNode)
1860  return;
1861  Pred = UpdatedNode;
1862  }
1863  }
1864  // Is we are inside an unrolled loop then no need the check the counters.
1865  if(isUnrolledState(Pred->getState()))
1866  return;
1867  }
1868 
1869  // If this block is terminated by a loop and it has already been visited the
1870  // maximum number of times, widen the loop.
1871  unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1872  if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1873  AMgr.options.shouldWidenLoops()) {
1874  const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1875  if (!(Term &&
1876  (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1877  return;
1878  // Widen.
1879  const LocationContext *LCtx = Pred->getLocationContext();
1880  ProgramStateRef WidenedState =
1881  getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1882  nodeBuilder.generateNode(WidenedState, Pred);
1883  return;
1884  }
1885 
1886  // FIXME: Refactor this into a checker.
1887  if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1888  static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1889  const ExplodedNode *Sink =
1890  nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1891 
1892  // Check if we stopped at the top level function or not.
1893  // Root node should have the location context of the top most function.
1894  const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1895  const LocationContext *CalleeSF = CalleeLC->getStackFrame();
1896  const LocationContext *RootLC =
1897  (*G.roots_begin())->getLocation().getLocationContext();
1898  if (RootLC->getStackFrame() != CalleeSF) {
1899  Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1900 
1901  // Re-run the call evaluation without inlining it, by storing the
1902  // no-inlining policy in the state and enqueuing the new work item on
1903  // the list. Replay should almost never fail. Use the stats to catch it
1904  // if it does.
1905  if ((!AMgr.options.NoRetryExhausted &&
1906  replayWithoutInlining(Pred, CalleeLC)))
1907  return;
1908  NumMaxBlockCountReachedInInlined++;
1909  } else
1910  NumMaxBlockCountReached++;
1911 
1912  // Make sink nodes as exhausted(for stats) only if retry failed.
1913  Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1914  }
1915 }
1916 
1917 //===----------------------------------------------------------------------===//
1918 // Branch processing.
1919 //===----------------------------------------------------------------------===//
1920 
1921 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1922 /// to try to recover some path-sensitivity for casts of symbolic
1923 /// integers that promote their values (which are currently not tracked well).
1924 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1925 // cast(s) did was sign-extend the original value.
1928  const Stmt *Condition,
1929  const LocationContext *LCtx,
1930  ASTContext &Ctx) {
1931 
1932  const auto *Ex = dyn_cast<Expr>(Condition);
1933  if (!Ex)
1934  return UnknownVal();
1935 
1936  uint64_t bits = 0;
1937  bool bitsInit = false;
1938 
1939  while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
1940  QualType T = CE->getType();
1941 
1942  if (!T->isIntegralOrEnumerationType())
1943  return UnknownVal();
1944 
1945  uint64_t newBits = Ctx.getTypeSize(T);
1946  if (!bitsInit || newBits < bits) {
1947  bitsInit = true;
1948  bits = newBits;
1949  }
1950 
1951  Ex = CE->getSubExpr();
1952  }
1953 
1954  // We reached a non-cast. Is it a symbolic value?
1955  QualType T = Ex->getType();
1956 
1957  if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1958  Ctx.getTypeSize(T) > bits)
1959  return UnknownVal();
1960 
1961  return state->getSVal(Ex, LCtx);
1962 }
1963 
1964 #ifndef NDEBUG
1965 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1966  while (Condition) {
1967  const auto *BO = dyn_cast<BinaryOperator>(Condition);
1968  if (!BO || !BO->isLogicalOp()) {
1969  return Condition;
1970  }
1971  Condition = BO->getRHS()->IgnoreParens();
1972  }
1973  return nullptr;
1974 }
1975 #endif
1976 
1977 // Returns the condition the branch at the end of 'B' depends on and whose value
1978 // has been evaluated within 'B'.
1979 // In most cases, the terminator condition of 'B' will be evaluated fully in
1980 // the last statement of 'B'; in those cases, the resolved condition is the
1981 // given 'Condition'.
1982 // If the condition of the branch is a logical binary operator tree, the CFG is
1983 // optimized: in that case, we know that the expression formed by all but the
1984 // rightmost leaf of the logical binary operator tree must be true, and thus
1985 // the branch condition is at this point equivalent to the truth value of that
1986 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1987 // expression in its final statement. As the full condition in that case was
1988 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1989 // expression to evaluate the truth value of the condition in the current state
1990 // space.
1991 static const Stmt *ResolveCondition(const Stmt *Condition,
1992  const CFGBlock *B) {
1993  if (const auto *Ex = dyn_cast<Expr>(Condition))
1994  Condition = Ex->IgnoreParens();
1995 
1996  const auto *BO = dyn_cast<BinaryOperator>(Condition);
1997  if (!BO || !BO->isLogicalOp())
1998  return Condition;
1999 
2000  assert(!B->getTerminator().isTemporaryDtorsBranch() &&
2001  "Temporary destructor branches handled by processBindTemporary.");
2002 
2003  // For logical operations, we still have the case where some branches
2004  // use the traditional "merge" approach and others sink the branch
2005  // directly into the basic blocks representing the logical operation.
2006  // We need to distinguish between those two cases here.
2007 
2008  // The invariants are still shifting, but it is possible that the
2009  // last element in a CFGBlock is not a CFGStmt. Look for the last
2010  // CFGStmt as the value of the condition.
2011  CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
2012  for (; I != E; ++I) {
2013  CFGElement Elem = *I;
2014  Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
2015  if (!CS)
2016  continue;
2017  const Stmt *LastStmt = CS->getStmt();
2018  assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
2019  return LastStmt;
2020  }
2021  llvm_unreachable("could not resolve condition");
2022 }
2023 
2024 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
2025  NodeBuilderContext& BldCtx,
2026  ExplodedNode *Pred,
2027  ExplodedNodeSet &Dst,
2028  const CFGBlock *DstT,
2029  const CFGBlock *DstF) {
2030  assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
2031  "CXXBindTemporaryExprs are handled by processBindTemporary.");
2032  const LocationContext *LCtx = Pred->getLocationContext();
2033  PrettyStackTraceLocationContext StackCrashInfo(LCtx);
2034  currBldrCtx = &BldCtx;
2035 
2036  // Check for NULL conditions; e.g. "for(;;)"
2037  if (!Condition) {
2038  BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
2039  NullCondBldr.markInfeasible(false);
2040  NullCondBldr.generateNode(Pred->getState(), true, Pred);
2041  return;
2042  }
2043 
2044  if (const auto *Ex = dyn_cast<Expr>(Condition))
2045  Condition = Ex->IgnoreParens();
2046 
2047  Condition = ResolveCondition(Condition, BldCtx.getBlock());
2048  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
2049  Condition->getLocStart(),
2050  "Error evaluating branch");
2051 
2052  ExplodedNodeSet CheckersOutSet;
2053  getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
2054  Pred, *this);
2055  // We generated only sinks.
2056  if (CheckersOutSet.empty())
2057  return;
2058 
2059  BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
2060  for (const auto PredI : CheckersOutSet) {
2061  if (PredI->isSink())
2062  continue;
2063 
2064  ProgramStateRef PrevState = PredI->getState();
2065  SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
2066 
2067  if (X.isUnknownOrUndef()) {
2068  // Give it a chance to recover from unknown.
2069  if (const auto *Ex = dyn_cast<Expr>(Condition)) {
2070  if (Ex->getType()->isIntegralOrEnumerationType()) {
2071  // Try to recover some path-sensitivity. Right now casts of symbolic
2072  // integers that promote their values are currently not tracked well.
2073  // If 'Condition' is such an expression, try and recover the
2074  // underlying value and use that instead.
2076  PrevState, Condition,
2077  PredI->getLocationContext(),
2078  getContext());
2079 
2080  if (!recovered.isUnknown()) {
2081  X = recovered;
2082  }
2083  }
2084  }
2085  }
2086 
2087  // If the condition is still unknown, give up.
2088  if (X.isUnknownOrUndef()) {
2089  builder.generateNode(PrevState, true, PredI);
2090  builder.generateNode(PrevState, false, PredI);
2091  continue;
2092  }
2093 
2094  DefinedSVal V = X.castAs<DefinedSVal>();
2095 
2096  ProgramStateRef StTrue, StFalse;
2097  std::tie(StTrue, StFalse) = PrevState->assume(V);
2098 
2099  // Process the true branch.
2100  if (builder.isFeasible(true)) {
2101  if (StTrue)
2102  builder.generateNode(StTrue, true, PredI);
2103  else
2104  builder.markInfeasible(true);
2105  }
2106 
2107  // Process the false branch.
2108  if (builder.isFeasible(false)) {
2109  if (StFalse)
2110  builder.generateNode(StFalse, false, PredI);
2111  else
2112  builder.markInfeasible(false);
2113  }
2114  }
2115  currBldrCtx = nullptr;
2116 }
2117 
2118 /// The GDM component containing the set of global variables which have been
2119 /// previously initialized with explicit initializers.
2120 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
2121  llvm::ImmutableSet<const VarDecl *>)
2122 
2124  NodeBuilderContext &BuilderCtx,
2125  ExplodedNode *Pred,
2126  ExplodedNodeSet &Dst,
2127  const CFGBlock *DstT,
2128  const CFGBlock *DstF) {
2130  currBldrCtx = &BuilderCtx;
2131 
2132  const auto *VD = cast<VarDecl>(DS->getSingleDecl());
2133  ProgramStateRef state = Pred->getState();
2134  bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
2135  BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
2136 
2137  if (!initHasRun) {
2138  state = state->add<InitializedGlobalsSet>(VD);
2139  }
2140 
2141  builder.generateNode(state, initHasRun, Pred);
2142  builder.markInfeasible(!initHasRun);
2143 
2144  currBldrCtx = nullptr;
2145 }
2146 
2147 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
2148 /// nodes by processing the 'effects' of a computed goto jump.
2150  ProgramStateRef state = builder.getState();
2151  SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
2152 
2153  // Three possibilities:
2154  //
2155  // (1) We know the computed label.
2156  // (2) The label is NULL (or some other constant), or Undefined.
2157  // (3) We have no clue about the label. Dispatch to all targets.
2158  //
2159 
2160  using iterator = IndirectGotoNodeBuilder::iterator;
2161 
2163  const LabelDecl *L = LV->getLabel();
2164 
2165  for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
2166  if (I.getLabel() == L) {
2167  builder.generateNode(I, state);
2168  return;
2169  }
2170  }
2171 
2172  llvm_unreachable("No block with label.");
2173  }
2174 
2175  if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
2176  // Dispatch to the first target and mark it as a sink.
2177  //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
2178  // FIXME: add checker visit.
2179  // UndefBranches.insert(N);
2180  return;
2181  }
2182 
2183  // This is really a catch-all. We don't support symbolics yet.
2184  // FIXME: Implement dispatch for symbolic pointers.
2185 
2186  for (iterator I = builder.begin(), E = builder.end(); I != E; ++I)
2187  builder.generateNode(I, state);
2188 }
2189 
2191  ExplodedNode *Pred,
2192  ExplodedNodeSet &Dst,
2193  const BlockEdge &L) {
2194  SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
2195  getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
2196 }
2197 
2198 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
2199 /// nodes when the control reaches the end of a function.
2201  ExplodedNode *Pred,
2202  const ReturnStmt *RS) {
2203  // FIXME: We currently cannot assert that temporaries are clear, because
2204  // lifetime extended temporaries are not always modelled correctly. In some
2205  // cases when we materialize the temporary, we do
2206  // createTemporaryRegionIfNeeded(), and the region changes, and also the
2207  // respective destructor becomes automatic from temporary. So for now clean up
2208  // the state manually before asserting. Ideally, the code above the assertion
2209  // should go away, but the assertion should remain.
2210  {
2211  ExplodedNodeSet CleanUpObjects;
2212  NodeBuilder Bldr(Pred, CleanUpObjects, BC);
2213  ProgramStateRef State = Pred->getState();
2214  const LocationContext *FromLC = Pred->getLocationContext();
2215  const LocationContext *ToLC = FromLC->getStackFrame()->getParent();
2216  const LocationContext *LC = FromLC;
2217  while (LC != ToLC) {
2218  assert(LC && "ToLC must be a parent of FromLC!");
2219  for (auto I : State->get<ObjectsUnderConstruction>())
2220  if (I.first.getLocationContext() == LC) {
2221  // The comment above only pardons us for not cleaning up a
2222  // temporary destructor. If any other statements are found here,
2223  // it must be a separate problem.
2224  assert(I.first.getItem().getKind() ==
2226  I.first.getItem().getKind() ==
2228  State = State->remove<ObjectsUnderConstruction>(I.first);
2229  }
2230  LC = LC->getParent();
2231  }
2232  if (State != Pred->getState()) {
2233  Pred = Bldr.generateNode(Pred->getLocation(), State, Pred);
2234  if (!Pred) {
2235  // The node with clean temporaries already exists. We might have reached
2236  // it on a path on which we initialize different temporaries.
2237  return;
2238  }
2239  }
2240  }
2241  assert(areAllObjectsFullyConstructed(Pred->getState(),
2242  Pred->getLocationContext(),
2243  Pred->getStackFrame()->getParent()));
2244 
2246  StateMgr.EndPath(Pred->getState());
2247 
2248  ExplodedNodeSet Dst;
2249  if (Pred->getLocationContext()->inTopFrame()) {
2250  // Remove dead symbols.
2251  ExplodedNodeSet AfterRemovedDead;
2252  removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
2253 
2254  // Notify checkers.
2255  for (const auto I : AfterRemovedDead)
2256  getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this, RS);
2257  } else {
2258  getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this, RS);
2259  }
2260 
2261  Engine.enqueueEndOfFunction(Dst, RS);
2262 }
2263 
2264 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
2265 /// nodes by processing the 'effects' of a switch statement.
2267  using iterator = SwitchNodeBuilder::iterator;
2268 
2269  ProgramStateRef state = builder.getState();
2270  const Expr *CondE = builder.getCondition();
2271  SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
2272 
2273  if (CondV_untested.isUndef()) {
2274  //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
2275  // FIXME: add checker
2276  //UndefBranches.insert(N);
2277 
2278  return;
2279  }
2280  DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
2281 
2282  ProgramStateRef DefaultSt = state;
2283 
2284  iterator I = builder.begin(), EI = builder.end();
2285  bool defaultIsFeasible = I == EI;
2286 
2287  for ( ; I != EI; ++I) {
2288  // Successor may be pruned out during CFG construction.
2289  if (!I.getBlock())
2290  continue;
2291 
2292  const CaseStmt *Case = I.getCase();
2293 
2294  // Evaluate the LHS of the case value.
2295  llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
2296  assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
2297 
2298  // Get the RHS of the case, if it exists.
2299  llvm::APSInt V2;
2300  if (const Expr *E = Case->getRHS())
2301  V2 = E->EvaluateKnownConstInt(getContext());
2302  else
2303  V2 = V1;
2304 
2305  ProgramStateRef StateCase;
2306  if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
2307  std::tie(StateCase, DefaultSt) =
2308  DefaultSt->assumeInclusiveRange(*NL, V1, V2);
2309  else // UnknownVal
2310  StateCase = DefaultSt;
2311 
2312  if (StateCase)
2313  builder.generateCaseStmtNode(I, StateCase);
2314 
2315  // Now "assume" that the case doesn't match. Add this state
2316  // to the default state (if it is feasible).
2317  if (DefaultSt)
2318  defaultIsFeasible = true;
2319  else {
2320  defaultIsFeasible = false;
2321  break;
2322  }
2323  }
2324 
2325  if (!defaultIsFeasible)
2326  return;
2327 
2328  // If we have switch(enum value), the default branch is not
2329  // feasible if all of the enum constants not covered by 'case:' statements
2330  // are not feasible values for the switch condition.
2331  //
2332  // Note that this isn't as accurate as it could be. Even if there isn't
2333  // a case for a particular enum value as long as that enum value isn't
2334  // feasible then it shouldn't be considered for making 'default:' reachable.
2335  const SwitchStmt *SS = builder.getSwitch();
2336  const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
2337  if (CondExpr->getType()->getAs<EnumType>()) {
2338  if (SS->isAllEnumCasesCovered())
2339  return;
2340  }
2341 
2342  builder.generateDefaultCaseNode(DefaultSt);
2343 }
2344 
2345 //===----------------------------------------------------------------------===//
2346 // Transfer functions: Loads and stores.
2347 //===----------------------------------------------------------------------===//
2348 
2350  ExplodedNode *Pred,
2351  ExplodedNodeSet &Dst) {
2352  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2353 
2354  ProgramStateRef state = Pred->getState();
2355  const LocationContext *LCtx = Pred->getLocationContext();
2356 
2357  if (const auto *VD = dyn_cast<VarDecl>(D)) {
2358  // C permits "extern void v", and if you cast the address to a valid type,
2359  // you can even do things with it. We simply pretend
2360  assert(Ex->isGLValue() || VD->getType()->isVoidType());
2361  const LocationContext *LocCtxt = Pred->getLocationContext();
2362  const Decl *D = LocCtxt->getDecl();
2363  const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
2364  const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
2366 
2367  if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
2368  DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
2369  MD->getParent()->isLambda()) {
2370  // Lookup the field of the lambda.
2371  const CXXRecordDecl *CXXRec = MD->getParent();
2372  llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
2373  FieldDecl *LambdaThisCaptureField;
2374  CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
2375 
2376  // Sema follows a sequence of complex rules to determine whether the
2377  // variable should be captured.
2378  if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
2379  Loc CXXThis =
2380  svalBuilder.getCXXThis(MD, LocCtxt->getStackFrame());
2381  SVal CXXThisVal = state->getSVal(CXXThis);
2382  VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
2383  }
2384  }
2385 
2386  if (!VInfo)
2387  VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType());
2388 
2389  SVal V = VInfo->first;
2390  bool IsReference = VInfo->second->isReferenceType();
2391 
2392  // For references, the 'lvalue' is the pointer address stored in the
2393  // reference region.
2394  if (IsReference) {
2395  if (const MemRegion *R = V.getAsRegion())
2396  V = state->getSVal(R);
2397  else
2398  V = UnknownVal();
2399  }
2400 
2401  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2403  return;
2404  }
2405  if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
2406  assert(!Ex->isGLValue());
2407  SVal V = svalBuilder.makeIntVal(ED->getInitVal());
2408  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
2409  return;
2410  }
2411  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2412  SVal V = svalBuilder.getFunctionPointer(FD);
2413  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2415  return;
2416  }
2417  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
2418  // FIXME: Compute lvalue of field pointers-to-member.
2419  // Right now we just use a non-null void pointer, so that it gives proper
2420  // results in boolean contexts.
2421  // FIXME: Maybe delegate this to the surrounding operator&.
2422  // Note how this expression is lvalue, however pointer-to-member is NonLoc.
2423  SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
2424  currBldrCtx->blockCount());
2425  state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
2426  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2428  return;
2429  }
2430  if (isa<BindingDecl>(D)) {
2431  // FIXME: proper support for bound declarations.
2432  // For now, let's just prevent crashing.
2433  return;
2434  }
2435 
2436  llvm_unreachable("Support for this Decl not implemented.");
2437 }
2438 
2439 /// VisitArraySubscriptExpr - Transfer function for array accesses
2441  ExplodedNode *Pred,
2442  ExplodedNodeSet &Dst){
2443  const Expr *Base = A->getBase()->IgnoreParens();
2444  const Expr *Idx = A->getIdx()->IgnoreParens();
2445 
2446  ExplodedNodeSet CheckerPreStmt;
2447  getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
2448 
2449  ExplodedNodeSet EvalSet;
2450  StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
2451 
2452  bool IsVectorType = A->getBase()->getType()->isVectorType();
2453 
2454  // The "like" case is for situations where C standard prohibits the type to
2455  // be an lvalue, e.g. taking the address of a subscript of an expression of
2456  // type "void *".
2457  bool IsGLValueLike = A->isGLValue() ||
2458  (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
2459 
2460  for (auto *Node : CheckerPreStmt) {
2461  const LocationContext *LCtx = Node->getLocationContext();
2462  ProgramStateRef state = Node->getState();
2463 
2464  if (IsGLValueLike) {
2465  QualType T = A->getType();
2466 
2467  // One of the forbidden LValue types! We still need to have sensible
2468  // symbolic locations to represent this stuff. Note that arithmetic on
2469  // void pointers is a GCC extension.
2470  if (T->isVoidType())
2471  T = getContext().CharTy;
2472 
2473  SVal V = state->getLValue(T,
2474  state->getSVal(Idx, LCtx),
2475  state->getSVal(Base, LCtx));
2476  Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
2478  } else if (IsVectorType) {
2479  // FIXME: non-glvalue vector reads are not modelled.
2480  Bldr.generateNode(A, Node, state, nullptr);
2481  } else {
2482  llvm_unreachable("Array subscript should be an lValue when not \
2483 a vector and not a forbidden lvalue type");
2484  }
2485  }
2486 
2487  getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
2488 }
2489 
2490 /// VisitMemberExpr - Transfer function for member expressions.
2492  ExplodedNodeSet &Dst) {
2493  // FIXME: Prechecks eventually go in ::Visit().
2494  ExplodedNodeSet CheckedSet;
2495  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
2496 
2497  ExplodedNodeSet EvalSet;
2498  ValueDecl *Member = M->getMemberDecl();
2499 
2500  // Handle static member variables and enum constants accessed via
2501  // member syntax.
2502  if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2503  for (const auto I : CheckedSet)
2504  VisitCommonDeclRefExpr(M, Member, I, EvalSet);
2505  } else {
2506  StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2507  ExplodedNodeSet Tmp;
2508 
2509  for (const auto I : CheckedSet) {
2510  ProgramStateRef state = I->getState();
2511  const LocationContext *LCtx = I->getLocationContext();
2512  Expr *BaseExpr = M->getBase();
2513 
2514  // Handle C++ method calls.
2515  if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
2516  if (MD->isInstance())
2517  state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2518 
2519  SVal MDVal = svalBuilder.getFunctionPointer(MD);
2520  state = state->BindExpr(M, LCtx, MDVal);
2521 
2522  Bldr.generateNode(M, I, state);
2523  continue;
2524  }
2525 
2526  // Handle regular struct fields / member variables.
2527  state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2528  SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
2529 
2530  const auto *field = cast<FieldDecl>(Member);
2531  SVal L = state->getLValue(field, baseExprVal);
2532 
2533  if (M->isGLValue() || M->getType()->isArrayType()) {
2534  // We special-case rvalues of array type because the analyzer cannot
2535  // reason about them, since we expect all regions to be wrapped in Locs.
2536  // We instead treat these as lvalues and assume that they will decay to
2537  // pointers as soon as they are used.
2538  if (!M->isGLValue()) {
2539  assert(M->getType()->isArrayType());
2540  const auto *PE =
2541  dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
2542  if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2543  llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2544  }
2545  }
2546 
2547  if (field->getType()->isReferenceType()) {
2548  if (const MemRegion *R = L.getAsRegion())
2549  L = state->getSVal(R);
2550  else
2551  L = UnknownVal();
2552  }
2553 
2554  Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr,
2556  } else {
2557  Bldr.takeNodes(I);
2558  evalLoad(Tmp, M, M, I, state, L);
2559  Bldr.addNodes(Tmp);
2560  }
2561  }
2562  }
2563 
2564  getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2565 }
2566 
2568  ExplodedNodeSet &Dst) {
2569  ExplodedNodeSet AfterPreSet;
2570  getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
2571 
2572  // For now, treat all the arguments to C11 atomics as escaping.
2573  // FIXME: Ideally we should model the behavior of the atomics precisely here.
2574 
2575  ExplodedNodeSet AfterInvalidateSet;
2576  StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
2577 
2578  for (const auto I : AfterPreSet) {
2579  ProgramStateRef State = I->getState();
2580  const LocationContext *LCtx = I->getLocationContext();
2581 
2582  SmallVector<SVal, 8> ValuesToInvalidate;
2583  for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
2584  const Expr *SubExpr = AE->getSubExprs()[SI];
2585  SVal SubExprVal = State->getSVal(SubExpr, LCtx);
2586  ValuesToInvalidate.push_back(SubExprVal);
2587  }
2588 
2589  State = State->invalidateRegions(ValuesToInvalidate, AE,
2590  currBldrCtx->blockCount(),
2591  LCtx,
2592  /*CausedByPointerEscape*/true,
2593  /*Symbols=*/nullptr);
2594 
2595  SVal ResultVal = UnknownVal();
2596  State = State->BindExpr(AE, LCtx, ResultVal);
2597  Bldr.generateNode(AE, I, State, nullptr,
2599  }
2600 
2601  getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
2602 }
2603 
2604 // A value escapes in three possible cases:
2605 // (1) We are binding to something that is not a memory region.
2606 // (2) We are binding to a MemrRegion that does not have stack storage.
2607 // (3) We are binding to a MemRegion with stack storage that the store
2608 // does not understand.
2610  SVal Loc,
2611  SVal Val,
2612  const LocationContext *LCtx) {
2613  // Are we storing to something that causes the value to "escape"?
2614  bool escapes = true;
2615 
2616  // TODO: Move to StoreManager.
2617  if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2618  escapes = !regionLoc->getRegion()->hasStackStorage();
2619 
2620  if (!escapes) {
2621  // To test (3), generate a new state with the binding added. If it is
2622  // the same state, then it escapes (since the store cannot represent
2623  // the binding).
2624  // Do this only if we know that the store is not supposed to generate the
2625  // same state.
2626  SVal StoredVal = State->getSVal(regionLoc->getRegion());
2627  if (StoredVal != Val)
2628  escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
2629  }
2630  }
2631 
2632  // If our store can represent the binding and we aren't storing to something
2633  // that doesn't have local storage then just return and have the simulation
2634  // state continue as is.
2635  if (!escapes)
2636  return State;
2637 
2638  // Otherwise, find all symbols referenced by 'val' that we are tracking
2639  // and stop tracking them.
2640  State = escapeValue(State, Val, PSK_EscapeOnBind);
2641  return State;
2642 }
2643 
2646  const InvalidatedSymbols *Invalidated,
2647  ArrayRef<const MemRegion *> ExplicitRegions,
2649  const CallEvent *Call,
2651  if (!Invalidated || Invalidated->empty())
2652  return State;
2653 
2654  if (!Call)
2656  *Invalidated,
2657  nullptr,
2659  &ITraits);
2660 
2661  // If the symbols were invalidated by a call, we want to find out which ones
2662  // were invalidated directly due to being arguments to the call.
2663  InvalidatedSymbols SymbolsDirectlyInvalidated;
2664  for (const auto I : ExplicitRegions) {
2665  if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
2666  SymbolsDirectlyInvalidated.insert(R->getSymbol());
2667  }
2668 
2669  InvalidatedSymbols SymbolsIndirectlyInvalidated;
2670  for (const auto &sym : *Invalidated) {
2671  if (SymbolsDirectlyInvalidated.count(sym))
2672  continue;
2673  SymbolsIndirectlyInvalidated.insert(sym);
2674  }
2675 
2676  if (!SymbolsDirectlyInvalidated.empty())
2678  SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2679 
2680  // Notify about the symbols that get indirectly invalidated by the call.
2681  if (!SymbolsIndirectlyInvalidated.empty())
2683  SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2684 
2685  return State;
2686 }
2687 
2688 /// evalBind - Handle the semantics of binding a value to a specific location.
2689 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
2690 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2691  ExplodedNode *Pred,
2692  SVal location, SVal Val,
2693  bool atDeclInit, const ProgramPoint *PP) {
2694  const LocationContext *LC = Pred->getLocationContext();
2695  PostStmt PS(StoreE, LC);
2696  if (!PP)
2697  PP = &PS;
2698 
2699  // Do a previsit of the bind.
2700  ExplodedNodeSet CheckedSet;
2701  getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2702  StoreE, *this, *PP);
2703 
2704  StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2705 
2706  // If the location is not a 'Loc', it will already be handled by
2707  // the checkers. There is nothing left to do.
2708  if (!location.getAs<Loc>()) {
2709  const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2710  /*tag*/nullptr);
2711  ProgramStateRef state = Pred->getState();
2712  state = processPointerEscapedOnBind(state, location, Val, LC);
2713  Bldr.generateNode(L, state, Pred);
2714  return;
2715  }
2716 
2717  for (const auto PredI : CheckedSet) {
2718  ProgramStateRef state = PredI->getState();
2719 
2720  state = processPointerEscapedOnBind(state, location, Val, LC);
2721 
2722  // When binding the value, pass on the hint that this is a initialization.
2723  // For initializations, we do not need to inform clients of region
2724  // changes.
2725  state = state->bindLoc(location.castAs<Loc>(),
2726  Val, LC, /* notifyChanges = */ !atDeclInit);
2727 
2728  const MemRegion *LocReg = nullptr;
2729  if (Optional<loc::MemRegionVal> LocRegVal =
2730  location.getAs<loc::MemRegionVal>()) {
2731  LocReg = LocRegVal->getRegion();
2732  }
2733 
2734  const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2735  Bldr.generateNode(L, state, PredI);
2736  }
2737 }
2738 
2739 /// evalStore - Handle the semantics of a store via an assignment.
2740 /// @param Dst The node set to store generated state nodes
2741 /// @param AssignE The assignment expression if the store happens in an
2742 /// assignment.
2743 /// @param LocationE The location expression that is stored to.
2744 /// @param state The current simulation state
2745 /// @param location The location to store the value
2746 /// @param Val The value to be stored
2747 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2748  const Expr *LocationE,
2749  ExplodedNode *Pred,
2750  ProgramStateRef state, SVal location, SVal Val,
2751  const ProgramPointTag *tag) {
2752  // Proceed with the store. We use AssignE as the anchor for the PostStore
2753  // ProgramPoint if it is non-NULL, and LocationE otherwise.
2754  const Expr *StoreE = AssignE ? AssignE : LocationE;
2755 
2756  // Evaluate the location (checks for bad dereferences).
2757  ExplodedNodeSet Tmp;
2758  evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2759 
2760  if (Tmp.empty())
2761  return;
2762 
2763  if (location.isUndef())
2764  return;
2765 
2766  for (const auto I : Tmp)
2767  evalBind(Dst, StoreE, I, location, Val, false);
2768 }
2769 
2771  const Expr *NodeEx,
2772  const Expr *BoundEx,
2773  ExplodedNode *Pred,
2775  SVal location,
2776  const ProgramPointTag *tag,
2777  QualType LoadTy) {
2778  assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2779  assert(NodeEx);
2780  assert(BoundEx);
2781  // Evaluate the location (checks for bad dereferences).
2782  ExplodedNodeSet Tmp;
2783  evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2784  if (Tmp.empty())
2785  return;
2786 
2787  StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2788  if (location.isUndef())
2789  return;
2790 
2791  // Proceed with the load.
2792  for (const auto I : Tmp) {
2793  state = I->getState();
2794  const LocationContext *LCtx = I->getLocationContext();
2795 
2796  SVal V = UnknownVal();
2797  if (location.isValid()) {
2798  if (LoadTy.isNull())
2799  LoadTy = BoundEx->getType();
2800  V = state->getSVal(location.castAs<Loc>(), LoadTy);
2801  }
2802 
2803  Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
2805  }
2806 }
2807 
2808 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2809  const Stmt *NodeEx,
2810  const Stmt *BoundEx,
2811  ExplodedNode *Pred,
2813  SVal location,
2814  const ProgramPointTag *tag,
2815  bool isLoad) {
2816  StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2817  // Early checks for performance reason.
2818  if (location.isUnknown()) {
2819  return;
2820  }
2821 
2822  ExplodedNodeSet Src;
2823  BldrTop.takeNodes(Pred);
2824  StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2825  if (Pred->getState() != state) {
2826  // Associate this new state with an ExplodedNode.
2827  // FIXME: If I pass null tag, the graph is incorrect, e.g for
2828  // int *p;
2829  // p = 0;
2830  // *p = 0xDEADBEEF;
2831  // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2832  // instead "int *p" is noted as
2833  // "Variable 'p' initialized to a null pointer value"
2834 
2835  static SimpleProgramPointTag tag(TagProviderName, "Location");
2836  Bldr.generateNode(NodeEx, Pred, state, &tag);
2837  }
2838  ExplodedNodeSet Tmp;
2839  getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2840  NodeEx, BoundEx, *this);
2841  BldrTop.addNodes(Tmp);
2842 }
2843 
2844 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2846  static SimpleProgramPointTag
2847  eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2848  "Eagerly Assume True"),
2849  eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2850  "Eagerly Assume False");
2851  return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2852  &eagerlyAssumeBinOpBifurcationFalse);
2853 }
2854 
2856  ExplodedNodeSet &Src,
2857  const Expr *Ex) {
2858  StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2859 
2860  for (const auto Pred : Src) {
2861  // Test if the previous node was as the same expression. This can happen
2862  // when the expression fails to evaluate to anything meaningful and
2863  // (as an optimization) we don't generate a node.
2864  ProgramPoint P = Pred->getLocation();
2865  if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2866  continue;
2867  }
2868 
2869  ProgramStateRef state = Pred->getState();
2870  SVal V = state->getSVal(Ex, Pred->getLocationContext());
2872  if (SEV && SEV->isExpression()) {
2873  const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2875 
2876  ProgramStateRef StateTrue, StateFalse;
2877  std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2878 
2879  // First assume that the condition is true.
2880  if (StateTrue) {
2881  SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2882  StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2883  Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2884  }
2885 
2886  // Next, assume that the condition is false.
2887  if (StateFalse) {
2888  SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2889  StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2890  Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2891  }
2892  }
2893  }
2894 }
2895 
2897  ExplodedNodeSet &Dst) {
2898  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2899  // We have processed both the inputs and the outputs. All of the outputs
2900  // should evaluate to Locs. Nuke all of their values.
2901 
2902  // FIXME: Some day in the future it would be nice to allow a "plug-in"
2903  // which interprets the inline asm and stores proper results in the
2904  // outputs.
2905 
2906  ProgramStateRef state = Pred->getState();
2907 
2908  for (const Expr *O : A->outputs()) {
2909  SVal X = state->getSVal(O, Pred->getLocationContext());
2910  assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2911 
2912  if (Optional<Loc> LV = X.getAs<Loc>())
2913  state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
2914  }
2915 
2916  Bldr.generateNode(A, Pred, state);
2917 }
2918 
2920  ExplodedNodeSet &Dst) {
2921  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2922  Bldr.generateNode(A, Pred, Pred->getState());
2923 }
2924 
2925 //===----------------------------------------------------------------------===//
2926 // Visualization.
2927 //===----------------------------------------------------------------------===//
2928 
2929 #ifndef NDEBUG
2932 
2933 namespace llvm {
2934 
2935 template<>
2936 struct DOTGraphTraits<ExplodedNode*> : public DefaultDOTGraphTraits {
2937  DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2938 
2939  // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2940  // work.
2941  static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2942  return {};
2943  }
2944 
2945  // De-duplicate some source location pretty-printing.
2946  static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2947  if (SLoc.isFileID()) {
2948  Out << "\\lline="
2949  << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2950  << " col="
2951  << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2952  << "\\l";
2953  }
2954  }
2955 
2956  static std::string getNodeLabel(const ExplodedNode *N, void*){
2957  std::string sbuf;
2958  llvm::raw_string_ostream Out(sbuf);
2959 
2960  // Program Location.
2961  ProgramPoint Loc = N->getLocation();
2962 
2963  switch (Loc.getKind()) {
2965  Out << "Block Entrance: B"
2966  << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2967  break;
2968 
2970  assert(false);
2971  break;
2972 
2974  Out << "CallEnter";
2975  break;
2976 
2978  Out << "CallExitBegin";
2979  break;
2980 
2982  Out << "CallExitEnd";
2983  break;
2984 
2986  Out << "PostStmtPurgeDeadSymbols";
2987  break;
2988 
2990  Out << "PreStmtPurgeDeadSymbols";
2991  break;
2992 
2994  Out << "Epsilon Point";
2995  break;
2996 
2998  LoopExit LE = Loc.castAs<LoopExit>();
2999  Out << "LoopExit: " << LE.getLoopStmt()->getStmtClassName();
3000  break;
3001  }
3002 
3005  Out << "PreCall: ";
3006 
3007  // FIXME: Get proper printing options.
3008  PC.getDecl()->print(Out, LangOptions());
3009  printLocation(Out, PC.getLocation());
3010  break;
3011  }
3012 
3015  Out << "PostCall: ";
3016 
3017  // FIXME: Get proper printing options.
3018  PC.getDecl()->print(Out, LangOptions());
3019  printLocation(Out, PC.getLocation());
3020  break;
3021  }
3022 
3024  Out << "PostInitializer: ";
3025  const CXXCtorInitializer *Init =
3026  Loc.castAs<PostInitializer>().getInitializer();
3027  if (const FieldDecl *FD = Init->getAnyMember())
3028  Out << *FD;
3029  else {
3030  QualType Ty = Init->getTypeSourceInfo()->getType();
3031  Ty = Ty.getLocalUnqualifiedType();
3032  LangOptions LO; // FIXME.
3033  Ty.print(Out, LO);
3034  }
3035  break;
3036  }
3037 
3039  const BlockEdge &E = Loc.castAs<BlockEdge>();
3040  Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
3041  << E.getDst()->getBlockID() << ')';
3042 
3043  if (const Stmt *T = E.getSrc()->getTerminator()) {
3044  SourceLocation SLoc = T->getLocStart();
3045 
3046  Out << "\\|Terminator: ";
3047  LangOptions LO; // FIXME.
3048  E.getSrc()->printTerminator(Out, LO);
3049 
3050  if (SLoc.isFileID()) {
3051  Out << "\\lline="
3052  << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
3053  << " col="
3054  << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
3055  }
3056 
3057  if (isa<SwitchStmt>(T)) {
3058  const Stmt *Label = E.getDst()->getLabel();
3059 
3060  if (Label) {
3061  if (const auto *C = dyn_cast<CaseStmt>(Label)) {
3062  Out << "\\lcase ";
3063  LangOptions LO; // FIXME.
3064  if (C->getLHS())
3065  C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
3066 
3067  if (const Stmt *RHS = C->getRHS()) {
3068  Out << " .. ";
3069  RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
3070  }
3071 
3072  Out << ":";
3073  }
3074  else {
3075  assert(isa<DefaultStmt>(Label));
3076  Out << "\\ldefault:";
3077  }
3078  }
3079  else
3080  Out << "\\l(implicit) default:";
3081  }
3082  else if (isa<IndirectGotoStmt>(T)) {
3083  // FIXME
3084  }
3085  else {
3086  Out << "\\lCondition: ";
3087  if (*E.getSrc()->succ_begin() == E.getDst())
3088  Out << "true";
3089  else
3090  Out << "false";
3091  }
3092 
3093  Out << "\\l";
3094  }
3095 
3096  break;
3097  }
3098 
3099  default: {
3100  const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
3101  assert(S != nullptr && "Expecting non-null Stmt");
3102 
3103  Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
3104  LangOptions LO; // FIXME.
3105  S->printPretty(Out, nullptr, PrintingPolicy(LO));
3106  printLocation(Out, S->getLocStart());
3107 
3108  if (Loc.getAs<PreStmt>())
3109  Out << "\\lPreStmt\\l;";
3110  else if (Loc.getAs<PostLoad>())
3111  Out << "\\lPostLoad\\l;";
3112  else if (Loc.getAs<PostStore>())
3113  Out << "\\lPostStore\\l";
3114  else if (Loc.getAs<PostLValue>())
3115  Out << "\\lPostLValue\\l";
3116  else if (Loc.getAs<PostAllocatorCall>())
3117  Out << "\\lPostAllocatorCall\\l";
3118 
3119  break;
3120  }
3121  }
3122 
3123  ProgramStateRef state = N->getState();
3124  Out << "\\|StateID: " << (const void*) state.get()
3125  << " NodeID: " << (const void*) N << "\\|";
3126 
3127  state->printDOT(Out, N->getLocationContext());
3128 
3129  Out << "\\l";
3130 
3131  if (const ProgramPointTag *tag = Loc.getTag()) {
3132  Out << "\\|Tag: " << tag->getTagDescription();
3133  Out << "\\l";
3134  }
3135  return Out.str();
3136  }
3137 };
3138 
3139 } // namespace llvm
3140 #endif
3141 
3142 void ExprEngine::ViewGraph(bool trim) {
3143 #ifndef NDEBUG
3144  if (trim) {
3145  std::vector<const ExplodedNode *> Src;
3146 
3147  // Flush any outstanding reports to make sure we cover all the nodes.
3148  // This does not cause them to get displayed.
3149  for (const auto I : BR)
3150  const_cast<BugType *>(I)->FlushReports(BR);
3151 
3152  // Iterate through the reports and get their nodes.
3154  EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
3155  const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
3156  if (N) Src.push_back(N);
3157  }
3158 
3159  ViewGraph(Src);
3160  }
3161  else {
3162  GraphPrintCheckerState = this;
3163  GraphPrintSourceManager = &getContext().getSourceManager();
3164 
3165  llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
3166 
3167  GraphPrintCheckerState = nullptr;
3168  GraphPrintSourceManager = nullptr;
3169  }
3170 #endif
3171 }
3172 
3174 #ifndef NDEBUG
3175  GraphPrintCheckerState = this;
3176  GraphPrintSourceManager = &getContext().getSourceManager();
3177 
3178  std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
3179 
3180  if (!TrimmedG.get())
3181  llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
3182  else
3183  llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
3184 
3185  GraphPrintCheckerState = nullptr;
3186  GraphPrintSourceManager = nullptr;
3187 #endif
3188 }
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprCXX.h:1272
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition: DeclCXX.h:2318
Defines the clang::ASTContext interface.
Represents C++ allocator call.
Definition: CFG.h:240
This represents a GCC inline-assembly statement extension.
Definition: Stmt.h:1683
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:525
ProgramStateRef processRegionChange(ProgramStateRef state, const MemRegion *MR, const LocationContext *LCtx)
Definition: SubEngine.h:146
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2447
void VisitArraySubscriptExpr(const ArraySubscriptExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitArraySubscriptExpr - Transfer function for array accesses.
void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred)
Definition: ExprEngine.cpp:758
SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast)
Evaluates a chain of derived-to-base casts through the path specified in Cast.
Definition: Store.cpp:248
A (possibly-)qualified type.
Definition: Type.h:655
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:94
Static storage duration.
Definition: Specifiers.h:280
bool isArrayType() const
Definition: Type.h:6162
void markLive(SymbolRef sym)
Unconditionally marks a symbol as live.
bool isMemberPointerType() const
Definition: Type.h:6144
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2596
void markInfeasible(bool branch)
Definition: CoreEngine.h:457
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr *> &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition: Expr.cpp:77
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
Definition: Type.h:998
const Stmt * getStmt() const
Definition: CFG.h:133
bool IsTemporaryCtorOrDtor
This call is a constructor or a destructor of a temporary value.
Definition: ExprEngine.h:106
succ_iterator succ_begin()
Definition: CFG.h:751
ProgramStateRef notifyCheckersOfPointerEscape(ProgramStateRef State, const InvalidatedSymbols *Invalidated, ArrayRef< const MemRegion *> ExplicitRegions, ArrayRef< const MemRegion *> Regions, const CallEvent *Call, RegionAndSymbolInvalidationTraits &ITraits) override
Call PointerEscape callback when a value escapes as a result of region invalidation.
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C...
Definition: Type.h:6069
unsigned blockCount() const
Returns the number of times the current basic block has been visited on the exploded graph path...
Definition: CoreEngine.h:212
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:30
void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCall - Transfer function for function calls.
Stmt - This represents one statement.
Definition: Stmt.h:66
Information about invalidation for a particular region/symbol.
Definition: MemRegion.h:1384
This builder class is useful for generating nodes that resulted from visiting a statement.
Definition: CoreEngine.h:370
void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, ExplodedNodeSet &PreVisit, ExplodedNodeSet &Dst)
bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2)
Definition: ProgramState.h:603
C Language Family Type Representation.
Defines the SourceManager interface.
static const Stmt * getRightmostLeaf(const Stmt *Condition)
Expr * getBase() const
Definition: Expr.h:2590
static void printObjectsUnderConstructionForContext(raw_ostream &Out, ProgramStateRef State, const char *NL, const char *Sep, const LocationContext *LC)
Definition: ExprEngine.cpp:523
unsigned getBlockID() const
Definition: CFG.h:856
const CFGBlock * getSrc() const
Definition: ProgramPoint.h:485
void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitMSAsmStmt - Transfer function logic for MS inline asm.
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Represents a point when we begin processing an inlined call.
Definition: ProgramPoint.h:604
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprCXX.h:2130
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:2015
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:247
StringRef P
const CastExpr * BasePath
Definition: Expr.h:68
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc L, NonLoc R, QualType T)
Definition: ExprEngine.h:568
static ExprEngine * GraphPrintCheckerState
The pointer has been passed to a function indirectly.
void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, NodeBuilderContext &BldCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) override
Called by CoreEngine.
Represents C++ object destructor generated from a call to delete.
Definition: CFG.h:409
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2668
Hints for figuring out of a call should be inlined during evalCall().
Definition: ExprEngine.h:96
Represents a program point just before an implicit call event.
Definition: ProgramPoint.h:557
bool IsArrayCtorOrDtor
This call is a constructor or a destructor for a single element within an array, a part of array cons...
Definition: ExprEngine.h:103
void ProcessMemberDtor(const CFGMemberDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:985
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition: Specifiers.h:276
static std::string getNodeLabel(const ExplodedNode *N, void *)
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type...
Definition: CFG.h:99
const ProgramStateRef & getState() const
ExprEngine(cross_tu::CrossTranslationUnitContext &CTU, AnalysisManager &mgr, bool gcEnabled, SetOfConstDecls *VisitedCalleesIn, FunctionSummariesTy *FS, InliningModes HowToInlineIn)
Definition: ExprEngine.cpp:179
void processCFGBlockEntrance(const BlockEdge &L, NodeBuilderWithSinks &nodeBuilder, ExplodedNode *Pred) override
Called by CoreEngine when processing the entrance of a CFGBlock.
bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2)
Definition: ProgramState.h:599
Represents a point when we exit a loop.
Definition: ProgramPoint.h:687
ProgramStateRef getInitialState(const LocationContext *InitLoc) override
getInitialState - Return the initial state used for the root vertex in the ExplodedGraph.
Definition: ExprEngine.cpp:209
Represents an implicit call event.
Definition: ProgramPoint.h:533
const CXXDestructorDecl * getDestructorDecl(ASTContext &astContext) const
Definition: CFG.cpp:4641
bool isIndirectMemberInitializer() const
Definition: DeclCXX.h:2330
bool isConsumedExpr(Expr *E) const
Definition: ParentMap.cpp:160
void VisitUnaryOperator(const UnaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitUnaryOperator - Transfer function logic for unary operators.
void takeNodes(const ExplodedNodeSet &S)
Definition: CoreEngine.h:321
Represents a variable declaration or definition.
Definition: Decl.h:814
ASTContext & getASTContext() const
REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction, ObjectsUnderConstructionMap) static const char *TagProviderName
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6526
void ProcessDeleteDtor(const CFGDeleteDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:926
loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrameContext *SFC)
Return a memory region for the &#39;this&#39; object reference.
static Optional< SVal > getObjectUnderConstruction(ProgramStateRef State, const ConstructionContextItem &Item, const LocationContext *LC)
By looking at a certain item that may be potentially part of an object&#39;s ConstructionContext, retrieve such object&#39;s location.
Definition: ExprEngine.cpp:443
bool operator<(const ConstructedObjectKey &RHS) const
Definition: ExprEngine.cpp:163
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Definition: Expr.h:741
void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE, ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val, const ProgramPointTag *tag=nullptr)
evalStore - Handle the semantics of a store via an assignment.
bool isUnrolledState(ProgramStateRef State)
Returns if the given State indicates that is inside a completely unrolled loop.
const ElementRegion * GetElementZeroRegion(const SubRegion *R, QualType T)
Definition: Store.cpp:68
void enqueue(ExplodedNodeSet &Set)
Enqueue the given set of nodes onto the work list.
Definition: CoreEngine.cpp:520
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const Stmt * getTriggerStmt() const
Definition: CFG.h:394
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
Defines the Objective-C statement AST node classes.
void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out, const Stmt *ReferenceStmt, const LocationContext *LC, const Stmt *DiagnosticStmt=nullptr, ProgramPoint::Kind K=ProgramPoint::PreStmtPurgeDeadSymbolsKind)
Run the analyzer&#39;s garbage collection - remove dead symbols and bindings from the state...
Definition: ExprEngine.cpp:622
ProgramStateRef removeDeadBindings(ProgramStateRef St, const StackFrameContext *LCtx, SymbolReaper &SymReaper)
Represents a parameter to a function.
Definition: Decl.h:1535
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:894
Defines the clang::Expr interface and subclasses for C++ expressions.
void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
BoundNodesTreeBuilder Nodes
static bool shouldRemoveDeadBindings(AnalysisManager &AMgr, const Stmt *S, const ExplodedNode *Pred, const LocationContext *LC)
Definition: ExprEngine.cpp:596
void ProcessTemporaryDtor(const CFGTemporaryDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void ProcessLoopExit(const Stmt *S, ExplodedNode *Pred)
Definition: ExprEngine.cpp:740
void runCheckersForLocation(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, bool isLoad, const Stmt *NodeEx, const Stmt *BoundEx, ExprEngine &Eng)
Run checkers for load/store of a location.
Symbolic value.
Definition: SymExpr.h:30
const char * getStmtClassName() const
Definition: Stmt.cpp:75
ProgramStateRef runCheckersForPointerEscape(ProgramStateRef State, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ITraits)
Run checkers when pointers escape.
One of these records is kept for each identifier that is lexed.
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
A pointer escapes due to binding its value to a location that the analyzer cannot track...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:150
LineState State
void runCheckersForLiveSymbols(ProgramStateRef state, SymbolReaper &SymReaper)
Run checkers for live symbols.
Represents a member of a struct/union/class.
Definition: Decl.h:2534
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition: DeclCXX.h:2379
void printTerminator(raw_ostream &OS, const LangOptions &LO) const
printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Definition: CFG.cpp:5430
Represents a program point after a store evaluation.
Definition: ProgramPoint.h:405
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Definition: CFG.h:384
const LocationContext * getLocationContext() const
Definition: ExprEngine.cpp:138
ProgramStateRef processLoopEnd(const Stmt *LoopStmt, ProgramStateRef State)
Updates the given ProgramState.
bool isReferenceType() const
Definition: Type.h:6125
void dumpStack(raw_ostream &OS, StringRef Indent={}, const char *NL="\, const char *Sep="", std::function< void(const LocationContext *)> printMoreInfoPerContext=[](const LocationContext *) {}) const
void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred)
Definition: ExprEngine.cpp:846
bool isAllEnumCasesCovered() const
Returns true if the SwitchStmt is a switch of an enum value and all cases have been explicitly covere...
Definition: Stmt.h:1126
void addPredecessor(ExplodedNode *V, ExplodedGraph &G)
addPredeccessor - Adds a predecessor to the current node, and in tandem add this node as a successor ...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
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
const StackFrameContext * getStackFrame() const
Definition: ProgramPoint.h:184
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6440
void enableNodeReclamation(unsigned Interval)
Enable tracking of recently allocated nodes for potential reclamation when calling reclaimRecentlyAll...
static std::string getNodeAttributes(const ExplodedNode *N, void *)
SourceLocation getLocation() const
Definition: ProgramPoint.h:540
ProgramStateRef processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, SVal Val, const LocationContext *LCtx) override
Call PointerEscape callback when a value escapes as a result of bind.
bool isGLValue() const
Definition: Expr.h:252
static bool isLocType(QualType T)
Definition: SVals.h:327
void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitOffsetOfExpr - Transfer function for offsetof.
This is a meta program point, which should be skipped by all the diagnostic reasoning etc...
Definition: ProgramPoint.h:706
ProgramStateRef updateLoopStack(const Stmt *LoopStmt, ASTContext &ASTCtx, ExplodedNode *Pred, unsigned maxVisitOnPath)
Updates the stack of loops contained by the ProgramState.
ExplodedNode * generateSink(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:409
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
STATISTIC(NumRemoveDeadBindings, "The # of times RemoveDeadBindings is called")
const LocationContext * getLocationContext() const
ExplodedNode * generateCaseStmtNode(const iterator &I, ProgramStateRef State)
Definition: CoreEngine.cpp:610
virtual bool inTopFrame() const
Return true if the current LocationContext has no caller context.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:643
static bool isRecordType(QualType T)
const LocationContext * getParent() const
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3143
bool isUnknown() const
Definition: SVals.h:137
const Stmt * getStmt() const
If a crash happens while one of these objects are live, the message is printed out along with the spe...
void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitReturnStmt - Transfer function logic for return statements.
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, const ASTContext *Context=nullptr) const
const VarDecl * getVarDecl() const
Definition: CFG.h:389
bool shouldUnrollLoops()
Returns true if the analysis should try to unroll loops with known bounds.
const CXXBaseSpecifier * getBaseSpecifier() const
Definition: CFG.h:440
bool isAnyMemberInitializer() const
Definition: DeclCXX.h:2326
An adjustment to be made to the temporary created when emitting a reference binding, which accesses a particular subobject of that temporary.
Definition: Expr.h:60
void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred)
Definition: ExprEngine.cpp:873
void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:892
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1245
virtual SVal getLValueField(const FieldDecl *D, SVal Base)
Definition: Store.h:144
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2391
void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitDeclStmt - Transfer function logic for DeclStmts.
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1663
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2385
void runCheckersForEndFunction(NodeBuilderContext &BC, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng, const ReturnStmt *RS)
Run checkers on end of function.
reverse_iterator rend()
Definition: CFG.h:709
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: ExprEngine.cpp:154
void processStaticInitializer(const DeclStmt *DS, NodeBuilderContext &BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) override
Called by CoreEngine.
const CFGBlock * getCallSiteBlock() const
void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred, SVal location, SVal Val, bool atDeclInit=false, const ProgramPoint *PP=nullptr)
evalBind - Handle the semantics of binding a value to a specific location.
CheckerManager & getCheckerManager() const
Definition: ExprEngine.h:186
void VisitLogicalExpr(const BinaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLogicalExpr - Transfer function logic for &#39;&&&#39;, &#39;||&#39;.
bool isArrayForm() const
Definition: ExprCXX.h:2186
CXXCtorInitializer * getInitializer() const
Definition: CFG.h:225
void runCheckersForPrintState(raw_ostream &Out, ProgramStateRef State, const char *NL, const char *Sep)
Run checkers for debug-printing a ProgramState.
void removeDeadOnEndOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Remove dead bindings/symbols before exiting a function.
void runCheckersForBind(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, SVal val, const Stmt *S, ExprEngine &Eng, const ProgramPoint &PP)
Run checkers for binding of a value to a location.
static SourceManager * GraphPrintSourceManager
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1627
const FieldDecl * getFieldDecl() const
Definition: CFG.h:461
const Stmt * getCallSite() const
Expr ** getSubExprs()
Definition: Expr.h:5380
void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
bool isDelegatingInitializer() const
Determine whether this initializer is creating a delegating constructor.
Definition: DeclCXX.h:2346
const CXXBindTemporaryExpr * getBindTemporaryExpr() const
Definition: CFG.h:482
Represents a single basic block in a source-level CFG.
Definition: CFG.h:552
void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
InliningModes
The modes of inlining, which override the default analysis-wide settings.
Definition: ExprEngine.h:87
SymbolicRegion - A special, "non-concrete" region.
Definition: MemRegion.h:759
void runCheckersForPostStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting Stmts.
static void printLocation(raw_ostream &OS, const SourceManager &SM, SourceLocation SLoc)
static unsigned getNumSubExprs(AtomicOp Op)
Determine the number of arguments the specified atomic builtin should have.
Definition: Expr.cpp:4098
void ProcessBaseDtor(const CFGBaseDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:966
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing &#39;0&#39; for the specified type.
Definition: SValBuilder.cpp:53
void processSwitch(SwitchNodeBuilder &builder) override
ProcessSwitch - Called by CoreEngine.
void printState(raw_ostream &Out, ProgramStateRef State, const char *NL, const char *Sep, const LocationContext *LCtx=nullptr) override
printState - Called by ProgramStateManager to print checker-specific data.
Definition: ExprEngine.cpp:540
void processBeginOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred, ExplodedNodeSet &Dst, const BlockEdge &L) override
Called by CoreEngine.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:637
Expr - This represents one expression.
Definition: Expr.h:106
Defines the clang::LangOptions interface.
void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for computing the lvalue of an Objective-C ivar.
std::string Label
void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Kind getKind() const
Definition: ProgramPoint.h:161
const Expr * getCondition() const
Definition: CoreEngine.h:562
void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCast - Transfer function logic for all casts (implicit and explicit).
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2700
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition: CoreEngine.h:228
void Add(ExplodedNode *N)
The pointer has been passed to a function call directly.
struct DTB DerivedToBase
Definition: Expr.h:78
Expr * getRHS()
Definition: Stmt.h:792
virtual StringRef getTagDescription() const =0
QualType getConditionType() const
Definition: SValBuilder.h:161
bool isValid() const
Definition: SVals.h:149
const LocationContext * getLocationContext() const
Definition: CoreEngine.h:566
bool isTemporaryDtorsBranch() const
Definition: CFG.h:513
void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Visit - Transfer function logic for all statements.
void FlushReports()
Generate and flush diagnostics for all bug reports.
const CFGBlock * getDst() const
Definition: ProgramPoint.h:489
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static std::pair< const ProgramPointTag *, const ProgramPointTag * > geteagerlyAssumeBinOpBifurcationTags()
QualType getType() const
Definition: Expr.h:128
The reason for pointer escape is unknown.
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:817
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1343
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:1476
void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitAtomicExpr - Transfer function for builtin atomic expressions.
This represents a Microsoft inline-assembly statement extension.
Definition: Stmt.h:1860
const SwitchStmt * getSwitch() const
Definition: CoreEngine.h:552
void evalLoad(ExplodedNodeSet &Dst, const Expr *NodeEx, const Expr *BoundExpr, ExplodedNode *Pred, ProgramStateRef St, SVal location, const ProgramPointTag *tag=nullptr, QualType LoadTy=QualType())
Simulate a read of the result of Ex.
Represents C++ object destructor implicitly generated for base object in destructor.
Definition: CFG.h:435
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
QualType getDestroyedType() const
Retrieve the type being destroyed.
Definition: ExprCXX.cpp:178
const Expr * getSubExpr() const
Definition: ExprCXX.h:1268
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:720
reverse_iterator rbegin()
Definition: CFG.h:708
virtual ProgramStateRef removeDeadBindings(ProgramStateRef state, SymbolReaper &SymReaper)=0
Scan all symbols referenced by the constraints.
Optional< T > getAs() const
Convert to the specified SVal type, returning None if this SVal is not of the desired type...
Definition: SVals.h:112
const MemRegion * getRegion() const
Get the underlining region.
Definition: SVals.h:605
ExplodedNode * generateNode(const iterator &I, ProgramStateRef State, bool isSink=false)
Definition: CoreEngine.cpp:591
While alive, includes the current analysis stack in a crash trace.
void processEndOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred, const ReturnStmt *RS=nullptr) override
Called by CoreEngine.
Thread storage duration.
Definition: Specifiers.h:279
Expr * getArgument()
Definition: ExprCXX.h:2199
ConstructedObjectKey(const ConstructionContextItem &Item, const LocationContext *LC)
Definition: ExprEngine.cpp:133
static const Stmt * ResolveCondition(const Stmt *Condition, const CFGBlock *B)
CFGTerminator getTerminator()
Definition: CFG.h:840
Kind getKind() const
Definition: CFG.h:119
void processCFGElement(const CFGElement E, ExplodedNode *Pred, unsigned StmtIdx, NodeBuilderContext *Ctx) override
processCFGElement - Called by CoreEngine.
Definition: ExprEngine.cpp:560
bool operator==(const ConstructedObjectKey &RHS) const
Definition: ExprEngine.cpp:159
ProgramStateRef getInitialState(const LocationContext *InitLoc)
const LocationContext * getLocationContext() const
Definition: CoreEngine.h:512
const Stmt * getStmt() const
Definition: ProgramPoint.h:276
void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitGuardedExpr - Transfer function logic for ?, __builtin_choose.
const Stmt * getLoopStmt() const
Definition: ProgramPoint.h:692
ProgramStateRef getWidenedLoopState(ProgramStateRef PrevState, const LocationContext *LCtx, unsigned BlockCount, const Stmt *LoopStmt)
Get the states that result from widening the loop.
Encodes a location in the source.
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, const Expr *expr, const LocationContext *LCtx, unsigned count)
Create a new symbol with a unique &#39;name&#39;.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4161
Stmt * getLabel()
Definition: CFG.h:851
void runCheckersForBranchCondition(const Stmt *condition, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng)
Run checkers for branch condition.
T castAs() const
Convert to the specified ProgramPoint type, asserting that this ProgramPoint is of the desired type...
Definition: ProgramPoint.h:141
static bool isCallStmt(const Stmt *S)
Returns true if this is a statement is a function or method call of some kind.
Definition: CallEvent.cpp:372
ProgramPoints can be "tagged" as representing points specific to a given analysis entity...
Definition: ProgramPoint.h:40
AnalysisManager & getAnalysisManager() override
Definition: ExprEngine.h:184
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:291
void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, const Expr *Ex)
evalEagerlyAssumeBinOpBifurcation - Given the nodes in &#39;Src&#39;, eagerly assume symbolic expressions of ...
const MemRegion * getAsRegion() const
Definition: SVals.cpp:151
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1915
Expr * getLHS()
Definition: Stmt.h:791
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.h:401
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:503
void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCompoundLiteralExpr - Transfer function logic for compound literals.
Represents the declaration of a label.
Definition: Decl.h:468
ExplodedNode * generateNode(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag=nullptr)
Definition: CoreEngine.h:345
static void printLocation(raw_ostream &Out, SourceLocation SLoc)
void processIndirectGoto(IndirectGotoNodeBuilder &builder) override
processIndirectGoto - Called by CoreEngine.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
const CXXTempObjectRegion * getCXXTempObjectRegion(Expr const *Ex, LocationContext const *LC)
Definition: MemRegion.cpp:1015
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprCXX.h:2208
void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void processBranch(const Stmt *Condition, const Stmt *Term, NodeBuilderContext &BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) override
ProcessBranch - Called by CoreEngine.
bool IsCtorOrDtorWithImproperlyModeledTargetRegion
This call is a constructor or a destructor for which we do not currently compute the this-region corr...
Definition: ExprEngine.h:99
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:76
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
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:5313
CanQualType VoidTy
Definition: ASTContext.h:1004
void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
ProgramStateRef runCheckersForEvalAssume(ProgramStateRef state, SVal Cond, bool Assumption)
Run checkers for handling assumptions on symbolic values.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2961
void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitObjCForCollectionStmt - Transfer function logic for ObjCForCollectionStmt.
A class responsible for cleaning up unused symbols.
const Decl * getDecl() const
Definition: ProgramPoint.h:539
void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng)
Run checkers for pre-visiting Stmts.
bool isVectorType() const
Definition: Type.h:6198
ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState, ProgramStateRef GDMState)
void insert(const ExplodedNodeSet &S)
Optional< T > getAs() const
Convert to the specified CFGElement type, returning None if this CFGElement is not of the desired typ...
Definition: CFG.h:110
Defines various enumerations that describe declaration and type specifiers.
StringRef getName() const
Return the actual identifier string.
ast_type_traits::DynTypedNode Node
unsigned getExpansionColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
CanQualType CharTy
Definition: ASTContext.h:1006
void runCheckersForDeadSymbols(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SymbolReaper &SymReaper, const Stmt *S, ExprEngine &Eng, ProgramPoint::Kind K)
Run checkers for dead symbols.
Dataflow Directional Tag Classes.
void ProcessStmt(const Stmt *S, ExplodedNode *Pred)
Definition: ExprEngine.cpp:710
ExplodedNode * generateDefaultCaseNode(ProgramStateRef State, bool isSink=false)
Definition: CoreEngine.cpp:625
SValBuilder & getSValBuilder()
Definition: ExprEngine.h:190
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2145
void addNodes(const ExplodedNodeSet &S)
Definition: CoreEngine.h:327
StoreManager & getStoreManager()
Definition: ExprEngine.h:372
Represents a program point just after an implicit call event.
Definition: ProgramPoint.h:574
ProgramStateRef processRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef< const MemRegion *> ExplicitRegions, ArrayRef< const MemRegion *> Regions, const LocationContext *LCtx, const CallEvent *Call) override
processRegionChanges - Called by ProgramStateManager whenever a change is made to the store...
Definition: ExprEngine.cpp:512
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2225
void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, const Stmt *S, bool IsBaseDtor, ExplodedNode *Pred, ExplodedNodeSet &Dst, const EvalCallOptions &Options)
const NodeBuilderContext & getContext()
Definition: CoreEngine.h:318
unsigned getGraphTrimInterval()
Returns how often nodes in the ExplodedGraph should be recycled to save memory.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
bool hasWorkRemaining() const
Definition: ExprEngine.h:390
This node builder keeps track of the generated sink nodes.
Definition: CoreEngine.h:333
bool isPurgeKind()
Is this a program point corresponding to purge/removal of dead symbols and bindings.
Definition: ProgramPoint.h:172
StmtClass getStmtClass() const
Definition: Stmt.h:391
void reclaimRecentlyAllocatedNodes()
Reclaim "uninteresting" nodes created since the last time this method was called. ...
enum clang::SubobjectAdjustment::@36 Kind
void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLambdaExpr - Transfer function logic for LambdaExprs.
const Decl * getSingleDecl() const
Definition: Stmt.h:520
const ProgramPointTag * getTag() const
Definition: ProgramPoint.h:178
Represents symbolic expression that isn&#39;t a location.
Definition: SVals.h:347
BranchNodeBuilder is responsible for constructing the nodes corresponding to the two branches of the ...
Definition: CoreEngine.h:422
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:165
ProgramStateRef getState() const
Definition: CoreEngine.h:564
const Stmt * getLoopStmt() const
Definition: CFG.h:270
ProgramStateManager & getStateManager() override
Definition: ExprEngine.h:370
This class is used for tools that requires cross translation unit capability.
const Decl * getDecl() const
const CXXDeleteExpr * getDeleteExpr() const
Definition: CFG.h:419
Represents a single point (AST node) in the program that requires attention during construction of an...
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2631
const CXXTempObjectRegion * getCXXStaticTempObjectRegion(const Expr *Ex)
Create a CXXTempObjectRegion for temporaries which are lifetime-extended by static references...
Definition: MemRegion.cpp:939
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
SwitchStmt - This represents a &#39;switch&#39; stmt.
Definition: Stmt.h:1054
unsigned getIntWidth(QualType T) const
void runCheckersForEndAnalysis(ExplodedGraph &G, BugReporter &BR, ExprEngine &Eng)
Run checkers for end of analysis.
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:104
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2226
ExplodedNode * generateSink(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag=nullptr)
Definition: CoreEngine.h:352
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2252
void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for ObjCAtSynchronizedStmts.
IndirectFieldDecl * getIndirectMember() const
Definition: DeclCXX.h:2399
const LocationContext * getLocationContext() const
Definition: ProgramPoint.h:180
void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
const StackFrameContext * getStackFrame() const
llvm::FoldingSet< BugReportEquivClass >::iterator EQClasses_iterator
Iterator over the set of BugReports tracked by the BugReporter.
Definition: BugReporter.h:468
Represents a base class of a C++ class.
Definition: DeclCXX.h:192
void getCaptureFields(llvm::DenseMap< const VarDecl *, FieldDecl *> &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition: DeclCXX.cpp:1360
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2052
SourceManager & getSourceManager()
Definition: ASTContext.h:651
outputs_range outputs()
Definition: Stmt.h:1661
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13820
ExplodedNode * generateNode(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a node in the ExplodedGraph.
Definition: CoreEngine.h:281
const CXXNewExpr * getAllocatorExpr() const
Definition: CFG.h:246
void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitBlockExpr - Transfer function logic for BlockExprs.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2500
Defines the clang::SourceLocation class and associated facilities.
Represents a C++ struct/union/class.
Definition: DeclCXX.h:302
bool isVoidType() const
Definition: Type.h:6340
const ConstructionContextItem & getItem() const
Definition: ExprEngine.cpp:137
Represents C++ object destructor implicitly generated by compiler on various occasions.
Definition: CFG.h:359
ProgramStateRef getState() const
Definition: CoreEngine.h:510
pred_iterator pred_begin()
ExplodedNode * generateNode(ProgramStateRef State, bool branch, ExplodedNode *Pred)
Definition: CoreEngine.cpp:577
Represents a top-level expression in a basic block.
Definition: CFG.h:56
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2250
ProgramStateRef processAssume(ProgramStateRef state, SVal cond, bool assumption) override
evalAssume - Callback function invoked by the ConstraintManager when making assumptions about state v...
Definition: ExprEngine.cpp:506
Represents C++ object destructor implicitly generated for member object in destructor.
Definition: CFG.h:456
const MemRegion * getBaseRegion() const
Definition: MemRegion.cpp:1126
FieldDecl * Field
Definition: Expr.h:79
ExplodedNode * generateNode(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:399
bool isUndef() const
Definition: SVals.h:141
void processEndWorklist(bool hasWorkRemaining) override
Called by CoreEngine when the analysis worklist has terminated.
Definition: ExprEngine.cpp:556
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:930
ProgramStateRef runCheckersForRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef< const MemRegion *> ExplicitRegions, ArrayRef< const MemRegion *> Regions, const LocationContext *LCtx, const CallEvent *Call)
Run checkers for region changes.
void runCheckersForBeginFunction(ExplodedNodeSet &Dst, const BlockEdge &L, ExplodedNode *Pred, ExprEngine &Eng)
Run checkers on beginning of function.
void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:974
Represents C++ base or member initializer from constructor&#39;s initialization list. ...
Definition: CFG.h:220
void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitGCCAsmStmt - Transfer function logic for inline asm.
const StackFrameContext * getStackFrame() const
bool mayInlineCXXAllocator()
Returns whether or not allocator call may be considered for inlining.
void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitMemberExpr - Transfer function for member expressions.
QualType getType() const
Definition: Decl.h:648
ProgramStateRef escapeValue(ProgramStateRef State, SVal V, PointerEscapeKind K) const
A simple wrapper when you only need to notify checkers of pointer-escape of a single value...
AnalysisPurgeMode AnalysisPurgeOpt
llvm::ImmutableMap< ConstructedObjectKey, SVal > ObjectsUnderConstructionMap
Definition: ExprEngine.cpp:169
This represents a decl that may have a name.
Definition: Decl.h:248
void ViewGraph(bool trim=false)
Visualize the ExplodedGraph created by executing the simulation.
Optional< T > getAs() const
Convert to the specified ProgramPoint type, returning None if this ProgramPoint is not of the desired...
Definition: ProgramPoint.h:152
ConstraintManager & getConstraintManager()
Definition: ExprEngine.h:374
void VisitBinaryOperator(const BinaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitBinaryOperator - Transfer function logic for binary operators.
Definition: ExprEngineC.cpp:41
AnalysisDeclContext * getAnalysisDeclContext() const
bool isFeasible(bool branch)
Definition: CoreEngine.h:464
const Expr * getCond() const
Definition: Stmt.h:1092
static SVal RecoverCastedSymbol(ProgramStateManager &StateMgr, ProgramStateRef state, const Stmt *Condition, const LocationContext *LCtx, ASTContext &Ctx)
RecoverCastedSymbol - A helper function for ProcessBranch that is used to try to recover some path-se...
ConstructedObjectKey is used for being able to find the path-sensitive memory region of a freshly con...
Definition: ExprEngine.cpp:119
void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Create a C++ temporary object for an rvalue.
const Expr * getTarget() const
Definition: CoreEngine.h:508
This class handles loading and caching of source files into memory.
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
bool isUnknownOrUndef() const
Definition: SVals.h:145
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:97
void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP)
Definition: ExprEngine.cpp:140
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2513
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:293
Represents the point where a loop ends.
Definition: CFG.h:266