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