1 //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a meta-engine for path-sensitive dataflow analysis that
11 // is built on GREngine, but provides the boilerplate to execute transfer
12 // functions and build the ExplodedGraph at the expression level.
14 //===----------------------------------------------------------------------===//
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17 #include "PrettyStackTraceLocationContext.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ParentMap.h"
27 #include "clang/AST/PrettyPrinter.h"
28 #include "clang/AST/Stmt.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/StmtObjC.h"
31 #include "clang/AST/Type.h"
32 #include "clang/Analysis/AnalysisDeclContext.h"
33 #include "clang/Analysis/CFG.h"
34 #include "clang/Analysis/ConstructionContext.h"
35 #include "clang/Analysis/ProgramPoint.h"
36 #include "clang/Basic/IdentifierTable.h"
37 #include "clang/Basic/LLVM.h"
38 #include "clang/Basic/LangOptions.h"
39 #include "clang/Basic/PrettyStackTrace.h"
40 #include "clang/Basic/SourceLocation.h"
41 #include "clang/Basic/SourceManager.h"
42 #include "clang/Basic/Specifiers.h"
43 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
44 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
45 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
46 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
47 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
48 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
49 #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
50 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
51 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
52 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
53 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
54 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
55 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
56 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
57 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
58 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
59 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
60 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
61 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
62 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.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"
85 using namespace clang;
88 #define DEBUG_TYPE "ExprEngine"
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");
102 //===----------------------------------------------------------------------===//
103 // Internal program state traits.
104 //===----------------------------------------------------------------------===//
106 // When modeling a C++ constructor, for a variety of reasons we need to track
107 // the location of the object for the duration of its ConstructionContext.
108 // ObjectsUnderConstruction maps statements within the construction context
109 // to the object's location, so that on every such statement the location
110 // could have been retrieved.
112 /// ConstructedObjectKey is used for being able to find the path-sensitive
113 /// memory region of a freshly constructed object while modeling the AST node
114 /// that syntactically represents the object that is being constructed.
115 /// Semantics of such nodes may sometimes require access to the region that's
116 /// not otherwise present in the program state, or to the very fact that
117 /// the construction context was present and contained references to these
119 class ConstructedObjectKey {
121 llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *>,
122 const LocationContext *> ConstructedObjectKeyImpl;
124 ConstructedObjectKeyImpl Impl;
126 const void *getAnyASTNodePtr() const {
127 if (const Stmt *S = getStmt())
130 return getCXXCtorInitializer();
134 ConstructedObjectKey(
135 llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
136 const LocationContext *LC)
138 // This is the full list of statements that require additional actions when
139 // encountered. This list may be expanded when new actions are implemented.
140 assert(getCXXCtorInitializer() || isa<DeclStmt>(getStmt()) ||
141 isa<CXXNewExpr>(getStmt()) || isa<CXXBindTemporaryExpr>(getStmt()) ||
142 isa<MaterializeTemporaryExpr>(getStmt()) ||
143 isa<CXXConstructExpr>(getStmt()));
146 const Stmt *getStmt() const {
147 return Impl.first.dyn_cast<const Stmt *>();
150 const CXXCtorInitializer *getCXXCtorInitializer() const {
151 return Impl.first.dyn_cast<const CXXCtorInitializer *>();
154 const LocationContext *getLocationContext() const {
158 void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) {
159 OS << '(' << getLocationContext() << ',' << getAnyASTNodePtr() << ") ";
160 if (const Stmt *S = getStmt()) {
161 S->printPretty(OS, Helper, PP);
163 const CXXCtorInitializer *I = getCXXCtorInitializer();
164 OS << I->getAnyMember()->getNameAsString();
168 void Profile(llvm::FoldingSetNodeID &ID) const {
169 ID.AddPointer(Impl.first.getOpaqueValue());
170 ID.AddPointer(Impl.second);
173 bool operator==(const ConstructedObjectKey &RHS) const {
174 return Impl == RHS.Impl;
177 bool operator<(const ConstructedObjectKey &RHS) const {
178 return Impl < RHS.Impl;
182 typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
183 ObjectsUnderConstructionMap;
184 REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
185 ObjectsUnderConstructionMap)
187 // Additionally, track a set of destructors that correspond to elided
188 // constructors when copy elision occurs.
189 typedef std::pair<const CXXBindTemporaryExpr *, const LocationContext *>
190 ElidedDestructorItem;
191 typedef llvm::ImmutableSet<ElidedDestructorItem>
193 REGISTER_TRAIT_WITH_PROGRAMSTATE(ElidedDestructors,
196 //===----------------------------------------------------------------------===//
197 // Engine construction and deletion.
198 //===----------------------------------------------------------------------===//
200 static const char* TagProviderName = "ExprEngine";
202 ExprEngine::ExprEngine(cross_tu::CrossTranslationUnitContext &CTU,
203 AnalysisManager &mgr, bool gcEnabled,
204 SetOfConstDecls *VisitedCalleesIn,
205 FunctionSummariesTy *FS,
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(),
213 SymMgr(StateMgr.getSymbolManager()),
214 svalBuilder(StateMgr.getSValBuilder()), ObjCNoRet(mgr.getASTContext()),
215 ObjCGCEnabled(gcEnabled), BR(mgr, *this),
216 VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
217 unsigned TrimInterval = mgr.options.getGraphTrimInterval();
218 if (TrimInterval != 0) {
219 // Enable eager node reclaimation when constructing the ExplodedGraph.
220 G.enableNodeReclamation(TrimInterval);
224 ExprEngine::~ExprEngine() {
228 //===----------------------------------------------------------------------===//
230 //===----------------------------------------------------------------------===//
232 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
233 ProgramStateRef state = StateMgr.getInitialState(InitLoc);
234 const Decl *D = InitLoc->getDecl();
237 // FIXME: It would be nice if we had a more general mechanism to add
238 // such preconditions. Some day.
240 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
241 // Precondition: the first argument of 'main' is an integer guaranteed
243 const IdentifierInfo *II = FD->getIdentifier();
244 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
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())
253 const MemRegion *R = state->getRegion(PD, InitLoc);
257 SVal V = state->getSVal(loc::MemRegionVal(R));
258 SVal Constraint_untested = evalBinOp(state, BO_GT, V,
259 svalBuilder.makeZeroVal(T),
260 svalBuilder.getConditionType());
262 Optional<DefinedOrUnknownSVal> Constraint =
263 Constraint_untested.getAs<DefinedOrUnknownSVal>();
268 if (ProgramStateRef newState = state->assume(*Constraint, true))
275 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
276 // Precondition: 'self' is always non-null upon entry to an Objective-C
278 const ImplicitParamDecl *SelfD = MD->getSelfDecl();
279 const MemRegion *R = state->getRegion(SelfD, InitLoc);
280 SVal V = state->getSVal(loc::MemRegionVal(R));
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");
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");
310 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
311 const LocationContext *LC,
312 const Expr *InitWithAdjustments,
313 const Expr *Result) {
314 // FIXME: This function is a hack that works around the quirky AST
315 // we're often having with respect to C++ temporaries. If only we modelled
316 // the actual execution order of statements properly in the CFG,
317 // all the hassle with adjustments would not be necessary,
318 // and perhaps the whole function would be removed.
319 SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
321 // If we don't have an explicit result expression, we're in "if needed"
322 // mode. Only create a region if the current value is a NonLoc.
323 if (!InitValWithAdjustments.getAs<NonLoc>())
325 Result = InitWithAdjustments;
327 // We need to create a region no matter what. For sanity, make sure we don't
328 // try to stuff a Loc into a non-pointer temporary region.
329 assert(!InitValWithAdjustments.getAs<Loc>() ||
330 Loc::isLocType(Result->getType()) ||
331 Result->getType()->isMemberPointerType());
334 ProgramStateManager &StateMgr = State->getStateManager();
335 MemRegionManager &MRMgr = StateMgr.getRegionManager();
336 StoreManager &StoreMgr = StateMgr.getStoreManager();
338 // MaterializeTemporaryExpr may appear out of place, after a few field and
339 // base-class accesses have been made to the object, even though semantically
340 // it is the whole object that gets materialized and lifetime-extended.
344 // `-MaterializeTemporaryExpr
346 // `-CXXTemporaryObjectExpr
348 // instead of the more natural
351 // `-MaterializeTemporaryExpr
352 // `-CXXTemporaryObjectExpr
354 // Use the usual methods for obtaining the expression of the base object,
355 // and record the adjustments that we need to make to obtain the sub-object
356 // that the whole expression 'Ex' refers to. This trick is usual,
357 // in the sense that CodeGen takes a similar route.
359 SmallVector<const Expr *, 2> CommaLHSs;
360 SmallVector<SubobjectAdjustment, 2> Adjustments;
362 const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
363 CommaLHSs, Adjustments);
365 // Take the region for Init, i.e. for the whole object. If we do not remember
366 // the region in which the object originally was constructed, come up with
367 // a new temporary region out of thin air and copy the contents of the object
368 // (which are currently present in the Environment, because Init is an rvalue)
369 // into that region. This is not correct, but it is better than nothing.
370 const TypedValueRegion *TR = nullptr;
371 if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
372 if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
373 State = finishObjectConstruction(State, MT, LC);
374 State = State->BindExpr(Result, LC, *V);
377 StorageDuration SD = MT->getStorageDuration();
378 // If this object is bound to a reference with static storage duration, we
379 // put it in a different region to prevent "address leakage" warnings.
380 if (SD == SD_Static || SD == SD_Thread) {
381 TR = MRMgr.getCXXStaticTempObjectRegion(Init);
383 TR = MRMgr.getCXXTempObjectRegion(Init, LC);
387 TR = MRMgr.getCXXTempObjectRegion(Init, LC);
390 SVal Reg = loc::MemRegionVal(TR);
393 // Make the necessary adjustments to obtain the sub-object.
394 for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
395 const SubobjectAdjustment &Adj = *I;
397 case SubobjectAdjustment::DerivedToBaseAdjustment:
398 Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
400 case SubobjectAdjustment::FieldAdjustment:
401 Reg = StoreMgr.getLValueField(Adj.Field, Reg);
403 case SubobjectAdjustment::MemberPointerAdjustment:
404 // FIXME: Unimplemented.
405 State = State->invalidateRegions(Reg, InitWithAdjustments,
406 currBldrCtx->blockCount(), LC, true,
407 nullptr, nullptr, nullptr);
412 // What remains is to copy the value of the object to the new region.
413 // FIXME: In other words, what we should always do is copy value of the
414 // Init expression (which corresponds to the bigger object) to the whole
415 // temporary region TR. However, this value is often no longer present
416 // in the Environment. If it has disappeared, we instead invalidate TR.
417 // Still, what we can do is assign the value of expression Ex (which
418 // corresponds to the sub-object) to the TR's sub-region Reg. At least,
419 // values inside Reg would be correct.
420 SVal InitVal = State->getSVal(Init, LC);
421 if (InitVal.isUnknown()) {
422 InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
423 currBldrCtx->blockCount());
424 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
426 // Then we'd need to take the value that certainly exists and bind it
428 if (InitValWithAdjustments.isUnknown()) {
429 // Try to recover some path sensitivity in case we couldn't
430 // compute the value.
431 InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
432 Result, LC, InitWithAdjustments->getType(),
433 currBldrCtx->blockCount());
436 State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
438 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
441 // The result expression would now point to the correct sub-region of the
442 // newly created temporary region. Do this last in order to getSVal of Init
443 // correctly in case (Result == Init).
444 State = State->BindExpr(Result, LC, Reg);
446 // Notify checkers once for two bindLoc()s.
447 State = processRegionChange(State, TR, LC);
452 ProgramStateRef ExprEngine::addObjectUnderConstruction(
453 ProgramStateRef State,
454 llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
455 const LocationContext *LC, SVal V) {
456 ConstructedObjectKey Key(P, LC->getStackFrame());
457 // FIXME: Currently the state might already contain the marker due to
458 // incorrect handling of temporaries bound to default parameters.
459 assert(!State->get<ObjectsUnderConstruction>(Key) ||
460 isa<CXXBindTemporaryExpr>(Key.getStmt()));
461 return State->set<ObjectsUnderConstruction>(Key, V);
464 Optional<SVal> ExprEngine::getObjectUnderConstruction(
465 ProgramStateRef State,
466 llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
467 const LocationContext *LC) {
468 ConstructedObjectKey Key(P, LC->getStackFrame());
469 return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
472 ProgramStateRef ExprEngine::finishObjectConstruction(
473 ProgramStateRef State,
474 llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
475 const LocationContext *LC) {
476 ConstructedObjectKey Key(P, LC->getStackFrame());
477 assert(State->contains<ObjectsUnderConstruction>(Key));
478 return State->remove<ObjectsUnderConstruction>(Key);
481 ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
482 const CXXBindTemporaryExpr *BTE,
483 const LocationContext *LC) {
484 ElidedDestructorItem I(BTE, LC);
485 assert(!State->contains<ElidedDestructors>(I));
486 return State->add<ElidedDestructors>(I);
490 ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
491 const CXXBindTemporaryExpr *BTE,
492 const LocationContext *LC) {
493 ElidedDestructorItem I(BTE, LC);
494 assert(State->contains<ElidedDestructors>(I));
495 return State->remove<ElidedDestructors>(I);
498 bool ExprEngine::isDestructorElided(ProgramStateRef State,
499 const CXXBindTemporaryExpr *BTE,
500 const LocationContext *LC) {
501 ElidedDestructorItem I(BTE, LC);
502 return State->contains<ElidedDestructors>(I);
505 bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
506 const LocationContext *FromLC,
507 const LocationContext *ToLC) {
508 const LocationContext *LC = FromLC;
510 assert(LC && "ToLC must be a parent of FromLC!");
511 for (auto I : State->get<ObjectsUnderConstruction>())
512 if (I.first.getLocationContext() == LC)
515 for (auto I: State->get<ElidedDestructors>())
519 LC = LC->getParent();
525 //===----------------------------------------------------------------------===//
526 // Top-level transfer function logic (Dispatcher).
527 //===----------------------------------------------------------------------===//
529 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
530 /// logic for handling assumptions on symbolic values.
531 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
532 SVal cond, bool assumption) {
533 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
537 ExprEngine::processRegionChanges(ProgramStateRef state,
538 const InvalidatedSymbols *invalidated,
539 ArrayRef<const MemRegion *> Explicits,
540 ArrayRef<const MemRegion *> Regions,
541 const LocationContext *LCtx,
542 const CallEvent *Call) {
543 return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
548 static void printObjectsUnderConstructionForContext(raw_ostream &Out,
549 ProgramStateRef State,
552 const LocationContext *LC) {
554 LC->getAnalysisDeclContext()->getASTContext().getPrintingPolicy();
555 for (auto I : State->get<ObjectsUnderConstruction>()) {
556 ConstructedObjectKey Key = I.first;
557 SVal Value = I.second;
558 if (Key.getLocationContext() != LC)
560 Key.print(Out, nullptr, PP);
561 Out << " : " << Value << NL;
564 for (auto I : State->get<ElidedDestructors>()) {
567 Out << '(' << I.second << ',' << (const void *)I.first << ") ";
568 I.first->printPretty(Out, nullptr, PP);
569 Out << " : (constructor elided)" << NL;
573 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
574 const char *NL, const char *Sep,
575 const LocationContext *LCtx) {
577 if (!State->get<ObjectsUnderConstruction>().isEmpty()) {
578 Out << Sep << "Objects under construction:" << NL;
580 LCtx->dumpStack(Out, "", NL, Sep, [&](const LocationContext *LC) {
581 printObjectsUnderConstructionForContext(Out, State, NL, Sep, LC);
586 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
589 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
590 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
593 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
594 unsigned StmtIdx, NodeBuilderContext *Ctx) {
595 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
596 currStmtIdx = StmtIdx;
599 switch (E.getKind()) {
600 case CFGElement::Statement:
601 case CFGElement::Constructor:
602 case CFGElement::CXXRecordTypedCall:
603 ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
605 case CFGElement::Initializer:
606 ProcessInitializer(E.castAs<CFGInitializer>(), Pred);
608 case CFGElement::NewAllocator:
609 ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
612 case CFGElement::AutomaticObjectDtor:
613 case CFGElement::DeleteDtor:
614 case CFGElement::BaseDtor:
615 case CFGElement::MemberDtor:
616 case CFGElement::TemporaryDtor:
617 ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
619 case CFGElement::LoopExit:
620 ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
622 case CFGElement::LifetimeEnds:
623 case CFGElement::ScopeBegin:
624 case CFGElement::ScopeEnd:
629 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
631 const ExplodedNode *Pred,
632 const LocationContext *LC) {
633 // Are we never purging state values?
634 if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
637 // Is this the beginning of a basic block?
638 if (Pred->getLocation().getAs<BlockEntrance>())
641 // Is this on a non-expression?
645 // Run before processing a call.
646 if (CallEvent::isCallStmt(S))
649 // Is this an expression that is consumed by another expression? If so,
650 // postpone cleaning out the state.
651 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
652 return !PM.isConsumedExpr(cast<Expr>(S));
655 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
656 const Stmt *ReferenceStmt,
657 const LocationContext *LC,
658 const Stmt *DiagnosticStmt,
659 ProgramPoint::Kind K) {
660 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
661 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
662 && "PostStmt is not generally supported by the SymbolReaper yet");
663 assert(LC && "Must pass the current (or expiring) LocationContext");
665 if (!DiagnosticStmt) {
666 DiagnosticStmt = ReferenceStmt;
667 assert(DiagnosticStmt && "Required for clearing a LocationContext");
670 NumRemoveDeadBindings++;
671 ProgramStateRef CleanedState = Pred->getState();
673 // LC is the location context being destroyed, but SymbolReaper wants a
674 // location context that is still live. (If this is the top-level stack
675 // frame, this will be null.)
676 if (!ReferenceStmt) {
677 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
678 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
679 LC = LC->getParent();
682 const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
683 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
685 for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
686 if (SymbolRef Sym = I.second.getAsSymbol())
687 SymReaper.markLive(Sym);
688 if (const MemRegion *MR = I.second.getAsRegion())
689 SymReaper.markLive(MR);
692 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
694 // Create a state in which dead bindings are removed from the environment
695 // and the store. TODO: The function should just return new env and store,
697 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
699 // Process any special transfer function for dead symbols.
700 // A tag to track convenience transitions, which can be removed at cleanup.
701 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
702 if (!SymReaper.hasDeadSymbols()) {
703 // Generate a CleanedNode that has the environment and store cleaned
704 // up. Since no symbols are dead, we can optimize and not clean out
705 // the constraint manager.
706 StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
707 Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
710 // Call checkers with the non-cleaned state so that they could query the
711 // values of the soon to be dead symbols.
712 ExplodedNodeSet CheckedSet;
713 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
714 DiagnosticStmt, *this, K);
716 // For each node in CheckedSet, generate CleanedNodes that have the
717 // environment, the store, and the constraints cleaned up but have the
718 // user-supplied states as the predecessors.
719 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
720 for (const auto I : CheckedSet) {
721 ProgramStateRef CheckerState = I->getState();
723 // The constraint manager has not been cleaned up yet, so clean up now.
724 CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
727 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
728 "Checkers are not allowed to modify the Environment as a part of "
729 "checkDeadSymbols processing.");
730 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
731 "Checkers are not allowed to modify the Store as a part of "
732 "checkDeadSymbols processing.");
734 // Create a state based on CleanedState with CheckerState GDM and
735 // generate a transition to that state.
736 ProgramStateRef CleanedCheckerSt =
737 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
738 Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K);
743 void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
744 // Reclaim any unnecessary nodes in the ExplodedGraph.
745 G.reclaimRecentlyAllocatedNodes();
747 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
748 currStmt->getLocStart(),
749 "Error evaluating statement");
751 // Remove dead bindings and symbols.
752 ExplodedNodeSet CleanedStates;
753 if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
754 Pred->getLocationContext())) {
755 removeDead(Pred, CleanedStates, currStmt,
756 Pred->getLocationContext());
758 CleanedStates.Add(Pred);
760 // Visit the statement.
762 for (const auto I : CleanedStates) {
763 ExplodedNodeSet DstI;
764 // Visit the statement.
765 Visit(currStmt, I, DstI);
769 // Enqueue the new nodes onto the work list.
770 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
773 void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) {
774 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
776 "Error evaluating end of the loop");
779 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
780 ProgramStateRef NewState = Pred->getState();
782 if(AMgr.options.shouldUnrollLoops())
783 NewState = processLoopEnd(S, NewState);
785 LoopExit PP(S, Pred->getLocationContext());
786 Bldr.generateNode(PP, NewState, Pred);
787 // Enqueue the new nodes onto the work list.
788 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
791 void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit,
792 ExplodedNode *Pred) {
793 const CXXCtorInitializer *BMI = CFGInit.getInitializer();
794 const Expr *Init = BMI->getInit()->IgnoreImplicit();
795 const LocationContext *LC = Pred->getLocationContext();
797 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
798 BMI->getSourceLocation(),
799 "Error evaluating initializer");
801 // We don't clean up dead bindings here.
802 const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
803 const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
805 ProgramStateRef State = Pred->getState();
806 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
811 // Evaluate the initializer, if necessary
812 if (BMI->isAnyMemberInitializer()) {
813 // Constructors build the object directly in the field,
814 // but non-objects must be copied in from the initializer.
815 if (getObjectUnderConstruction(State, BMI, LC)) {
816 // The field was directly constructed, so there is no need to bind.
817 // But we still need to stop tracking the object under construction.
818 State = finishObjectConstruction(State, BMI, LC);
819 NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
820 PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
821 Bldr.generateNode(PS, State, Pred);
823 const ValueDecl *Field;
824 if (BMI->isIndirectMemberInitializer()) {
825 Field = BMI->getIndirectMember();
826 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
828 Field = BMI->getMember();
829 FieldLoc = State->getLValue(BMI->getMember(), thisVal);
833 if (Init->getType()->isArrayType()) {
834 // Handle arrays of trivial type. We can represent this with a
835 // primitive load/copy from the base array region.
836 const ArraySubscriptExpr *ASE;
837 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
838 Init = ASE->getBase()->IgnoreImplicit();
840 SVal LValue = State->getSVal(Init, stackFrame);
841 if (!Field->getType()->isReferenceType())
842 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
843 InitVal = State->getSVal(*LValueLoc);
845 // If we fail to get the value for some reason, use a symbolic value.
846 if (InitVal.isUnknownOrUndef()) {
847 SValBuilder &SVB = getSValBuilder();
848 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
850 currBldrCtx->blockCount());
853 InitVal = State->getSVal(BMI->getInit(), stackFrame);
856 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
857 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
860 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
862 // We already did all the work when visiting the CXXConstructExpr.
865 // Construct PostInitializer nodes whether the state changed or not,
866 // so that the diagnostics don't get confused.
867 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
869 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
870 for (const auto I : Tmp) {
871 ProgramStateRef State = I->getState();
872 Bldr.generateNode(PP, State, I);
875 // Enqueue the new nodes onto the work list.
876 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
879 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
880 ExplodedNode *Pred) {
882 switch (D.getKind()) {
883 case CFGElement::AutomaticObjectDtor:
884 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
886 case CFGElement::BaseDtor:
887 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
889 case CFGElement::MemberDtor:
890 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
892 case CFGElement::TemporaryDtor:
893 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
895 case CFGElement::DeleteDtor:
896 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
899 llvm_unreachable("Unexpected dtor kind.");
902 // Enqueue the new nodes onto the work list.
903 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
906 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
907 ExplodedNode *Pred) {
909 AnalysisManager &AMgr = getAnalysisManager();
910 AnalyzerOptions &Opts = AMgr.options;
911 // TODO: We're not evaluating allocators for all cases just yet as
912 // we're not handling the return value correctly, which causes false
913 // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
914 if (Opts.mayInlineCXXAllocator())
915 VisitCXXNewAllocatorCall(NE, Pred, Dst);
917 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
918 const LocationContext *LCtx = Pred->getLocationContext();
919 PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
920 Bldr.generateNode(PP, Pred->getState(), Pred);
922 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
925 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
927 ExplodedNodeSet &Dst) {
928 const VarDecl *varDecl = Dtor.getVarDecl();
929 QualType varType = varDecl->getType();
931 ProgramStateRef state = Pred->getState();
932 SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
933 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
935 if (varType->isReferenceType()) {
936 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
938 // FIXME: This should not happen. The language guarantees a presence
939 // of a valid initializer here, so the reference shall not be undefined.
940 // It seems that we're calling destructors over variables that
941 // were not initialized yet.
944 Region = ValueRegion->getBaseRegion();
945 varType = cast<TypedValueRegion>(Region)->getValueType();
948 // FIXME: We need to run the same destructor on every element of the array.
949 // This workaround will just run the first destructor (which will still
950 // invalidate the entire array).
951 EvalCallOptions CallOpts;
952 Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType,
953 CallOpts.IsArrayCtorOrDtor).getAsRegion();
955 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
956 Pred, Dst, CallOpts);
959 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
961 ExplodedNodeSet &Dst) {
962 ProgramStateRef State = Pred->getState();
963 const LocationContext *LCtx = Pred->getLocationContext();
964 const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
965 const Stmt *Arg = DE->getArgument();
966 QualType DTy = DE->getDestroyedType();
967 SVal ArgVal = State->getSVal(Arg, LCtx);
969 // If the argument to delete is known to be a null value,
970 // don't run destructor.
971 if (State->isNull(ArgVal).isConstrainedTrue()) {
972 QualType BTy = getContext().getBaseElementType(DTy);
973 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
974 const CXXDestructorDecl *Dtor = RD->getDestructor();
976 PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
977 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
978 Bldr.generateNode(PP, Pred->getState(), Pred);
982 EvalCallOptions CallOpts;
983 const MemRegion *ArgR = ArgVal.getAsRegion();
984 if (DE->isArrayForm()) {
985 // FIXME: We need to run the same destructor on every element of the array.
986 // This workaround will just run the first destructor (which will still
987 // invalidate the entire array).
988 CallOpts.IsArrayCtorOrDtor = true;
989 // Yes, it may even be a multi-dimensional array.
990 while (const auto *AT = getContext().getAsArrayType(DTy))
991 DTy = AT->getElementType();
993 ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy);
996 VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
999 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
1000 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1001 const LocationContext *LCtx = Pred->getLocationContext();
1003 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
1004 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
1005 LCtx->getStackFrame());
1006 SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
1008 // Create the base object region.
1009 const CXXBaseSpecifier *Base = D.getBaseSpecifier();
1010 QualType BaseTy = Base->getType();
1011 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
1014 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
1015 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {});
1018 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
1019 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1020 const FieldDecl *Member = D.getFieldDecl();
1021 QualType T = Member->getType();
1022 ProgramStateRef State = Pred->getState();
1023 const LocationContext *LCtx = Pred->getLocationContext();
1025 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
1026 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
1027 LCtx->getStackFrame());
1029 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
1031 // FIXME: We need to run the same destructor on every element of the array.
1032 // This workaround will just run the first destructor (which will still
1033 // invalidate the entire array).
1034 EvalCallOptions CallOpts;
1035 FieldVal = makeZeroElementRegion(State, FieldVal, T,
1036 CallOpts.IsArrayCtorOrDtor);
1038 VisitCXXDestructor(T, FieldVal.castAs<loc::MemRegionVal>().getRegion(),
1039 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts);
1042 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
1044 ExplodedNodeSet &Dst) {
1045 const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr();
1046 ProgramStateRef State = Pred->getState();
1047 const LocationContext *LC = Pred->getLocationContext();
1048 const MemRegion *MR = nullptr;
1050 if (Optional<SVal> V =
1051 getObjectUnderConstruction(State, D.getBindTemporaryExpr(),
1052 Pred->getLocationContext())) {
1053 // FIXME: Currently we insert temporary destructors for default parameters,
1054 // but we don't insert the constructors, so the entry in
1055 // ObjectsUnderConstruction may be missing.
1056 State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
1057 Pred->getLocationContext());
1058 MR = V->getAsRegion();
1061 // If copy elision has occured, and the constructor corresponding to the
1062 // destructor was elided, we need to skip the destructor as well.
1063 if (isDestructorElided(State, BTE, LC)) {
1064 State = cleanupElidedDestructor(State, BTE, LC);
1065 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1066 PostImplicitCall PP(D.getDestructorDecl(getContext()),
1067 D.getBindTemporaryExpr()->getLocStart(),
1068 Pred->getLocationContext());
1069 Bldr.generateNode(PP, State, Pred);
1073 ExplodedNodeSet CleanDtorState;
1074 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
1075 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
1077 QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType();
1078 // FIXME: Currently CleanDtorState can be empty here due to temporaries being
1079 // bound to default parameters.
1080 assert(CleanDtorState.size() <= 1);
1081 ExplodedNode *CleanPred =
1082 CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
1084 EvalCallOptions CallOpts;
1085 CallOpts.IsTemporaryCtorOrDtor = true;
1087 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
1089 // If we have no MR, we still need to unwrap the array to avoid destroying
1090 // the whole array at once. Regardless, we'd eventually need to model array
1091 // destructors properly, element-by-element.
1092 while (const ArrayType *AT = getContext().getAsArrayType(T)) {
1093 T = AT->getElementType();
1094 CallOpts.IsArrayCtorOrDtor = true;
1097 // We'd eventually need to makeZeroElementRegion() trick here,
1098 // but for now we don't have the respective construction contexts,
1099 // so MR would always be null in this case. Do nothing for now.
1101 VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(),
1102 /*IsBase=*/false, CleanPred, Dst, CallOpts);
1105 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
1106 NodeBuilderContext &BldCtx,
1108 ExplodedNodeSet &Dst,
1109 const CFGBlock *DstT,
1110 const CFGBlock *DstF) {
1111 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
1112 ProgramStateRef State = Pred->getState();
1113 const LocationContext *LC = Pred->getLocationContext();
1114 if (getObjectUnderConstruction(State, BTE, LC)) {
1115 TempDtorBuilder.markInfeasible(false);
1116 TempDtorBuilder.generateNode(State, true, Pred);
1118 TempDtorBuilder.markInfeasible(true);
1119 TempDtorBuilder.generateNode(State, false, Pred);
1123 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
1124 ExplodedNodeSet &PreVisit,
1125 ExplodedNodeSet &Dst) {
1126 // This is a fallback solution in case we didn't have a construction
1127 // context when we were constructing the temporary. Otherwise the map should
1128 // have been populated there.
1129 if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
1130 // In case we don't have temporary destructors in the CFG, do not mark
1131 // the initialization - we would otherwise never clean it up.
1135 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
1136 for (ExplodedNode *Node : PreVisit) {
1137 ProgramStateRef State = Node->getState();
1138 const LocationContext *LC = Node->getLocationContext();
1139 if (!getObjectUnderConstruction(State, BTE, LC)) {
1140 // FIXME: Currently the state might also already contain the marker due to
1141 // incorrect handling of temporaries bound to default parameters; for
1142 // those, we currently skip the CXXBindTemporaryExpr but rely on adding
1143 // temporary destructor nodes.
1144 State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
1146 StmtBldr.generateNode(BTE, Node, State);
1150 ProgramStateRef ExprEngine::escapeValue(ProgramStateRef State, SVal V,
1151 PointerEscapeKind K) const {
1152 class CollectReachableSymbolsCallback final : public SymbolVisitor {
1153 InvalidatedSymbols Symbols;
1156 explicit CollectReachableSymbolsCallback(ProgramStateRef State) {}
1158 const InvalidatedSymbols &getSymbols() const { return Symbols; }
1160 bool VisitSymbol(SymbolRef Sym) override {
1161 Symbols.insert(Sym);
1166 const CollectReachableSymbolsCallback &Scanner =
1167 State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
1168 return getCheckerManager().runCheckersForPointerEscape(
1169 State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
1172 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
1173 ExplodedNodeSet &DstTop) {
1174 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1176 "Error evaluating statement");
1177 ExplodedNodeSet Dst;
1178 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
1180 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
1182 switch (S->getStmtClass()) {
1183 // C++, OpenMP and ARC stuff we don't support yet.
1184 case Expr::ObjCIndirectCopyRestoreExprClass:
1185 case Stmt::CXXDependentScopeMemberExprClass:
1186 case Stmt::CXXInheritedCtorInitExprClass:
1187 case Stmt::CXXTryStmtClass:
1188 case Stmt::CXXTypeidExprClass:
1189 case Stmt::CXXUuidofExprClass:
1190 case Stmt::CXXFoldExprClass:
1191 case Stmt::MSPropertyRefExprClass:
1192 case Stmt::MSPropertySubscriptExprClass:
1193 case Stmt::CXXUnresolvedConstructExprClass:
1194 case Stmt::DependentScopeDeclRefExprClass:
1195 case Stmt::ArrayTypeTraitExprClass:
1196 case Stmt::ExpressionTraitExprClass:
1197 case Stmt::UnresolvedLookupExprClass:
1198 case Stmt::UnresolvedMemberExprClass:
1199 case Stmt::TypoExprClass:
1200 case Stmt::CXXNoexceptExprClass:
1201 case Stmt::PackExpansionExprClass:
1202 case Stmt::SubstNonTypeTemplateParmPackExprClass:
1203 case Stmt::FunctionParmPackExprClass:
1204 case Stmt::CoroutineBodyStmtClass:
1205 case Stmt::CoawaitExprClass:
1206 case Stmt::DependentCoawaitExprClass:
1207 case Stmt::CoreturnStmtClass:
1208 case Stmt::CoyieldExprClass:
1209 case Stmt::SEHTryStmtClass:
1210 case Stmt::SEHExceptStmtClass:
1211 case Stmt::SEHLeaveStmtClass:
1212 case Stmt::SEHFinallyStmtClass:
1213 case Stmt::OMPParallelDirectiveClass:
1214 case Stmt::OMPSimdDirectiveClass:
1215 case Stmt::OMPForDirectiveClass:
1216 case Stmt::OMPForSimdDirectiveClass:
1217 case Stmt::OMPSectionsDirectiveClass:
1218 case Stmt::OMPSectionDirectiveClass:
1219 case Stmt::OMPSingleDirectiveClass:
1220 case Stmt::OMPMasterDirectiveClass:
1221 case Stmt::OMPCriticalDirectiveClass:
1222 case Stmt::OMPParallelForDirectiveClass:
1223 case Stmt::OMPParallelForSimdDirectiveClass:
1224 case Stmt::OMPParallelSectionsDirectiveClass:
1225 case Stmt::OMPTaskDirectiveClass:
1226 case Stmt::OMPTaskyieldDirectiveClass:
1227 case Stmt::OMPBarrierDirectiveClass:
1228 case Stmt::OMPTaskwaitDirectiveClass:
1229 case Stmt::OMPTaskgroupDirectiveClass:
1230 case Stmt::OMPFlushDirectiveClass:
1231 case Stmt::OMPOrderedDirectiveClass:
1232 case Stmt::OMPAtomicDirectiveClass:
1233 case Stmt::OMPTargetDirectiveClass:
1234 case Stmt::OMPTargetDataDirectiveClass:
1235 case Stmt::OMPTargetEnterDataDirectiveClass:
1236 case Stmt::OMPTargetExitDataDirectiveClass:
1237 case Stmt::OMPTargetParallelDirectiveClass:
1238 case Stmt::OMPTargetParallelForDirectiveClass:
1239 case Stmt::OMPTargetUpdateDirectiveClass:
1240 case Stmt::OMPTeamsDirectiveClass:
1241 case Stmt::OMPCancellationPointDirectiveClass:
1242 case Stmt::OMPCancelDirectiveClass:
1243 case Stmt::OMPTaskLoopDirectiveClass:
1244 case Stmt::OMPTaskLoopSimdDirectiveClass:
1245 case Stmt::OMPDistributeDirectiveClass:
1246 case Stmt::OMPDistributeParallelForDirectiveClass:
1247 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1248 case Stmt::OMPDistributeSimdDirectiveClass:
1249 case Stmt::OMPTargetParallelForSimdDirectiveClass:
1250 case Stmt::OMPTargetSimdDirectiveClass:
1251 case Stmt::OMPTeamsDistributeDirectiveClass:
1252 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1253 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1254 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1255 case Stmt::OMPTargetTeamsDirectiveClass:
1256 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1257 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1258 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1259 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1260 case Stmt::CapturedStmtClass: {
1261 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1262 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1266 case Stmt::ParenExprClass:
1267 llvm_unreachable("ParenExprs already handled.");
1268 case Stmt::GenericSelectionExprClass:
1269 llvm_unreachable("GenericSelectionExprs already handled.");
1270 // Cases that should never be evaluated simply because they shouldn't
1271 // appear in the CFG.
1272 case Stmt::BreakStmtClass:
1273 case Stmt::CaseStmtClass:
1274 case Stmt::CompoundStmtClass:
1275 case Stmt::ContinueStmtClass:
1276 case Stmt::CXXForRangeStmtClass:
1277 case Stmt::DefaultStmtClass:
1278 case Stmt::DoStmtClass:
1279 case Stmt::ForStmtClass:
1280 case Stmt::GotoStmtClass:
1281 case Stmt::IfStmtClass:
1282 case Stmt::IndirectGotoStmtClass:
1283 case Stmt::LabelStmtClass:
1284 case Stmt::NoStmtClass:
1285 case Stmt::NullStmtClass:
1286 case Stmt::SwitchStmtClass:
1287 case Stmt::WhileStmtClass:
1288 case Expr::MSDependentExistsStmtClass:
1289 llvm_unreachable("Stmt should not be in analyzer evaluation loop");
1291 case Stmt::ObjCSubscriptRefExprClass:
1292 case Stmt::ObjCPropertyRefExprClass:
1293 llvm_unreachable("These are handled by PseudoObjectExpr");
1295 case Stmt::GNUNullExprClass: {
1296 // GNU __null is a pointer-width integer, not an actual pointer.
1297 ProgramStateRef state = Pred->getState();
1298 state = state->BindExpr(S, Pred->getLocationContext(),
1299 svalBuilder.makeIntValWithPtrWidth(0, false));
1300 Bldr.generateNode(S, Pred, state);
1304 case Stmt::ObjCAtSynchronizedStmtClass:
1305 Bldr.takeNodes(Pred);
1306 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
1310 case Stmt::ExprWithCleanupsClass:
1311 // Handled due to fully linearised CFG.
1314 case Stmt::CXXBindTemporaryExprClass: {
1315 Bldr.takeNodes(Pred);
1316 ExplodedNodeSet PreVisit;
1317 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1318 ExplodedNodeSet Next;
1319 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
1320 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
1325 // Cases not handled yet; but will handle some day.
1326 case Stmt::DesignatedInitExprClass:
1327 case Stmt::DesignatedInitUpdateExprClass:
1328 case Stmt::ArrayInitLoopExprClass:
1329 case Stmt::ArrayInitIndexExprClass:
1330 case Stmt::ExtVectorElementExprClass:
1331 case Stmt::ImaginaryLiteralClass:
1332 case Stmt::ObjCAtCatchStmtClass:
1333 case Stmt::ObjCAtFinallyStmtClass:
1334 case Stmt::ObjCAtTryStmtClass:
1335 case Stmt::ObjCAutoreleasePoolStmtClass:
1336 case Stmt::ObjCEncodeExprClass:
1337 case Stmt::ObjCIsaExprClass:
1338 case Stmt::ObjCProtocolExprClass:
1339 case Stmt::ObjCSelectorExprClass:
1340 case Stmt::ParenListExprClass:
1341 case Stmt::ShuffleVectorExprClass:
1342 case Stmt::ConvertVectorExprClass:
1343 case Stmt::VAArgExprClass:
1344 case Stmt::CUDAKernelCallExprClass:
1345 case Stmt::OpaqueValueExprClass:
1346 case Stmt::AsTypeExprClass:
1349 // Cases we intentionally don't evaluate, since they don't need
1350 // to be explicitly evaluated.
1351 case Stmt::PredefinedExprClass:
1352 case Stmt::AddrLabelExprClass:
1353 case Stmt::AttributedStmtClass:
1354 case Stmt::IntegerLiteralClass:
1355 case Stmt::FixedPointLiteralClass:
1356 case Stmt::CharacterLiteralClass:
1357 case Stmt::ImplicitValueInitExprClass:
1358 case Stmt::CXXScalarValueInitExprClass:
1359 case Stmt::CXXBoolLiteralExprClass:
1360 case Stmt::ObjCBoolLiteralExprClass:
1361 case Stmt::ObjCAvailabilityCheckExprClass:
1362 case Stmt::FloatingLiteralClass:
1363 case Stmt::NoInitExprClass:
1364 case Stmt::SizeOfPackExprClass:
1365 case Stmt::StringLiteralClass:
1366 case Stmt::ObjCStringLiteralClass:
1367 case Stmt::CXXPseudoDestructorExprClass:
1368 case Stmt::SubstNonTypeTemplateParmExprClass:
1369 case Stmt::CXXNullPtrLiteralExprClass:
1370 case Stmt::OMPArraySectionExprClass:
1371 case Stmt::TypeTraitExprClass: {
1372 Bldr.takeNodes(Pred);
1373 ExplodedNodeSet preVisit;
1374 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1375 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
1380 case Stmt::CXXDefaultArgExprClass:
1381 case Stmt::CXXDefaultInitExprClass: {
1382 Bldr.takeNodes(Pred);
1383 ExplodedNodeSet PreVisit;
1384 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1386 ExplodedNodeSet Tmp;
1387 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
1390 if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
1391 ArgE = DefE->getExpr();
1392 else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
1393 ArgE = DefE->getExpr();
1395 llvm_unreachable("unknown constant wrapper kind");
1397 bool IsTemporary = false;
1398 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
1399 ArgE = MTE->GetTemporaryExpr();
1403 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
1405 ConstantVal = UnknownVal();
1407 const LocationContext *LCtx = Pred->getLocationContext();
1408 for (const auto I : PreVisit) {
1409 ProgramStateRef State = I->getState();
1410 State = State->BindExpr(S, LCtx, *ConstantVal);
1412 State = createTemporaryRegionIfNeeded(State, LCtx,
1415 Bldr2.generateNode(S, I, State);
1418 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1423 // Cases we evaluate as opaque expressions, conjuring a symbol.
1424 case Stmt::CXXStdInitializerListExprClass:
1425 case Expr::ObjCArrayLiteralClass:
1426 case Expr::ObjCDictionaryLiteralClass:
1427 case Expr::ObjCBoxedExprClass: {
1428 Bldr.takeNodes(Pred);
1430 ExplodedNodeSet preVisit;
1431 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1433 ExplodedNodeSet Tmp;
1434 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
1436 const auto *Ex = cast<Expr>(S);
1437 QualType resultType = Ex->getType();
1439 for (const auto N : preVisit) {
1440 const LocationContext *LCtx = N->getLocationContext();
1441 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1443 currBldrCtx->blockCount());
1444 ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
1446 // Escape pointers passed into the list, unless it's an ObjC boxed
1447 // expression which is not a boxable C structure.
1448 if (!(isa<ObjCBoxedExpr>(Ex) &&
1449 !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
1450 ->getType()->isRecordType()))
1451 for (auto Child : Ex->children()) {
1453 SVal Val = State->getSVal(Child, LCtx);
1454 State = escapeValue(State, Val, PSK_EscapeOther);
1457 Bldr2.generateNode(S, N, State);
1460 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1465 case Stmt::ArraySubscriptExprClass:
1466 Bldr.takeNodes(Pred);
1467 VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1471 case Stmt::GCCAsmStmtClass:
1472 Bldr.takeNodes(Pred);
1473 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1477 case Stmt::MSAsmStmtClass:
1478 Bldr.takeNodes(Pred);
1479 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1483 case Stmt::BlockExprClass:
1484 Bldr.takeNodes(Pred);
1485 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1489 case Stmt::LambdaExprClass:
1490 if (AMgr.options.shouldInlineLambdas()) {
1491 Bldr.takeNodes(Pred);
1492 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1495 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1496 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1500 case Stmt::BinaryOperatorClass: {
1501 const auto *B = cast<BinaryOperator>(S);
1502 if (B->isLogicalOp()) {
1503 Bldr.takeNodes(Pred);
1504 VisitLogicalExpr(B, Pred, Dst);
1508 else if (B->getOpcode() == BO_Comma) {
1509 ProgramStateRef state = Pred->getState();
1510 Bldr.generateNode(B, Pred,
1511 state->BindExpr(B, Pred->getLocationContext(),
1512 state->getSVal(B->getRHS(),
1513 Pred->getLocationContext())));
1517 Bldr.takeNodes(Pred);
1519 if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
1520 (B->isRelationalOp() || B->isEqualityOp())) {
1521 ExplodedNodeSet Tmp;
1522 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1523 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1526 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1532 case Stmt::CXXOperatorCallExprClass: {
1533 const auto *OCE = cast<CXXOperatorCallExpr>(S);
1535 // For instance method operators, make sure the 'this' argument has a
1537 const Decl *Callee = OCE->getCalleeDecl();
1538 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1539 if (MD->isInstance()) {
1540 ProgramStateRef State = Pred->getState();
1541 const LocationContext *LCtx = Pred->getLocationContext();
1542 ProgramStateRef NewState =
1543 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1544 if (NewState != State) {
1545 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1546 ProgramPoint::PreStmtKind);
1547 // Did we cache out?
1557 case Stmt::CallExprClass:
1558 case Stmt::CXXMemberCallExprClass:
1559 case Stmt::UserDefinedLiteralClass:
1560 Bldr.takeNodes(Pred);
1561 VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1565 case Stmt::CXXCatchStmtClass:
1566 Bldr.takeNodes(Pred);
1567 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1571 case Stmt::CXXTemporaryObjectExprClass:
1572 case Stmt::CXXConstructExprClass:
1573 Bldr.takeNodes(Pred);
1574 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1578 case Stmt::CXXNewExprClass: {
1579 Bldr.takeNodes(Pred);
1581 ExplodedNodeSet PreVisit;
1582 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1584 ExplodedNodeSet PostVisit;
1585 for (const auto i : PreVisit)
1586 VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
1588 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1593 case Stmt::CXXDeleteExprClass: {
1594 Bldr.takeNodes(Pred);
1595 ExplodedNodeSet PreVisit;
1596 const auto *CDE = cast<CXXDeleteExpr>(S);
1597 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1599 for (const auto i : PreVisit)
1600 VisitCXXDeleteExpr(CDE, i, Dst);
1605 // FIXME: ChooseExpr is really a constant. We need to fix
1606 // the CFG do not model them as explicit control-flow.
1608 case Stmt::ChooseExprClass: { // __builtin_choose_expr
1609 Bldr.takeNodes(Pred);
1610 const auto *C = cast<ChooseExpr>(S);
1611 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1616 case Stmt::CompoundAssignOperatorClass:
1617 Bldr.takeNodes(Pred);
1618 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1622 case Stmt::CompoundLiteralExprClass:
1623 Bldr.takeNodes(Pred);
1624 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1628 case Stmt::BinaryConditionalOperatorClass:
1629 case Stmt::ConditionalOperatorClass: { // '?' operator
1630 Bldr.takeNodes(Pred);
1631 const auto *C = cast<AbstractConditionalOperator>(S);
1632 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1637 case Stmt::CXXThisExprClass:
1638 Bldr.takeNodes(Pred);
1639 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1643 case Stmt::DeclRefExprClass: {
1644 Bldr.takeNodes(Pred);
1645 const auto *DE = cast<DeclRefExpr>(S);
1646 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1651 case Stmt::DeclStmtClass:
1652 Bldr.takeNodes(Pred);
1653 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1657 case Stmt::ImplicitCastExprClass:
1658 case Stmt::CStyleCastExprClass:
1659 case Stmt::CXXStaticCastExprClass:
1660 case Stmt::CXXDynamicCastExprClass:
1661 case Stmt::CXXReinterpretCastExprClass:
1662 case Stmt::CXXConstCastExprClass:
1663 case Stmt::CXXFunctionalCastExprClass:
1664 case Stmt::ObjCBridgedCastExprClass: {
1665 Bldr.takeNodes(Pred);
1666 const auto *C = cast<CastExpr>(S);
1667 ExplodedNodeSet dstExpr;
1668 VisitCast(C, C->getSubExpr(), Pred, dstExpr);
1670 // Handle the postvisit checks.
1671 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1676 case Expr::MaterializeTemporaryExprClass: {
1677 Bldr.takeNodes(Pred);
1678 const auto *MTE = cast<MaterializeTemporaryExpr>(S);
1679 ExplodedNodeSet dstPrevisit;
1680 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
1681 ExplodedNodeSet dstExpr;
1682 for (const auto i : dstPrevisit)
1683 CreateCXXTemporaryObject(MTE, i, dstExpr);
1684 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
1689 case Stmt::InitListExprClass:
1690 Bldr.takeNodes(Pred);
1691 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1695 case Stmt::MemberExprClass:
1696 Bldr.takeNodes(Pred);
1697 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1701 case Stmt::AtomicExprClass:
1702 Bldr.takeNodes(Pred);
1703 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
1707 case Stmt::ObjCIvarRefExprClass:
1708 Bldr.takeNodes(Pred);
1709 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1713 case Stmt::ObjCForCollectionStmtClass:
1714 Bldr.takeNodes(Pred);
1715 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1719 case Stmt::ObjCMessageExprClass:
1720 Bldr.takeNodes(Pred);
1721 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1725 case Stmt::ObjCAtThrowStmtClass:
1726 case Stmt::CXXThrowExprClass:
1727 // FIXME: This is not complete. We basically treat @throw as
1729 Bldr.generateSink(S, Pred, Pred->getState());
1732 case Stmt::ReturnStmtClass:
1733 Bldr.takeNodes(Pred);
1734 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1738 case Stmt::OffsetOfExprClass: {
1739 Bldr.takeNodes(Pred);
1740 ExplodedNodeSet PreVisit;
1741 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1743 ExplodedNodeSet PostVisit;
1744 for (const auto Node : PreVisit)
1745 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
1747 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1752 case Stmt::UnaryExprOrTypeTraitExprClass:
1753 Bldr.takeNodes(Pred);
1754 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1759 case Stmt::StmtExprClass: {
1760 const auto *SE = cast<StmtExpr>(S);
1762 if (SE->getSubStmt()->body_empty()) {
1763 // Empty statement expression.
1764 assert(SE->getType() == getContext().VoidTy
1765 && "Empty statement expression must have void type.");
1769 if (const auto *LastExpr =
1770 dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1771 ProgramStateRef state = Pred->getState();
1772 Bldr.generateNode(SE, Pred,
1773 state->BindExpr(SE, Pred->getLocationContext(),
1774 state->getSVal(LastExpr,
1775 Pred->getLocationContext())));
1780 case Stmt::UnaryOperatorClass: {
1781 Bldr.takeNodes(Pred);
1782 const auto *U = cast<UnaryOperator>(S);
1783 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1784 ExplodedNodeSet Tmp;
1785 VisitUnaryOperator(U, Pred, Tmp);
1786 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1789 VisitUnaryOperator(U, Pred, Dst);
1794 case Stmt::PseudoObjectExprClass: {
1795 Bldr.takeNodes(Pred);
1796 ProgramStateRef state = Pred->getState();
1797 const auto *PE = cast<PseudoObjectExpr>(S);
1798 if (const Expr *Result = PE->getResultExpr()) {
1799 SVal V = state->getSVal(Result, Pred->getLocationContext());
1800 Bldr.generateNode(S, Pred,
1801 state->BindExpr(S, Pred->getLocationContext(), V));
1804 Bldr.generateNode(S, Pred,
1805 state->BindExpr(S, Pred->getLocationContext(),
1814 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1815 const LocationContext *CalleeLC) {
1816 const StackFrameContext *CalleeSF = CalleeLC->getStackFrame();
1817 const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame();
1818 assert(CalleeSF && CallerSF);
1819 ExplodedNode *BeforeProcessingCall = nullptr;
1820 const Stmt *CE = CalleeSF->getCallSite();
1822 // Find the first node before we started processing the call expression.
1824 ProgramPoint L = N->getLocation();
1825 BeforeProcessingCall = N;
1826 N = N->pred_empty() ? nullptr : *(N->pred_begin());
1828 // Skip the nodes corresponding to the inlined code.
1829 if (L.getStackFrame() != CallerSF)
1831 // We reached the caller. Find the node right before we started
1832 // processing the call.
1833 if (L.isPurgeKind())
1835 if (L.getAs<PreImplicitCall>())
1837 if (L.getAs<CallEnter>())
1839 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1840 if (SP->getStmt() == CE)
1845 if (!BeforeProcessingCall)
1848 // TODO: Clean up the unneeded nodes.
1850 // Build an Epsilon node from which we will restart the analyzes.
1851 // Note that CE is permitted to be NULL!
1852 ProgramPoint NewNodeLoc =
1853 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1854 // Add the special flag to GDM to signal retrying with no inlining.
1855 // Note, changing the state ensures that we are not going to cache out.
1856 ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1858 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1860 // Make the new node a successor of BeforeProcessingCall.
1862 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1863 // We cached out at this point. Caching out is common due to us backtracking
1864 // from the inlined function, which might spawn several paths.
1868 NewNode->addPredecessor(BeforeProcessingCall, G);
1870 // Add the new node to the work list.
1871 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1872 CalleeSF->getIndex());
1873 NumTimesRetriedWithoutInlining++;
1877 /// Block entrance. (Update counters).
1878 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1879 NodeBuilderWithSinks &nodeBuilder,
1880 ExplodedNode *Pred) {
1881 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1882 // If we reach a loop which has a known bound (and meets
1883 // other constraints) then consider completely unrolling it.
1884 if(AMgr.options.shouldUnrollLoops()) {
1885 unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
1886 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1888 ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
1889 Pred, maxBlockVisitOnPath);
1890 if (NewState != Pred->getState()) {
1891 ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
1897 // Is we are inside an unrolled loop then no need the check the counters.
1898 if(isUnrolledState(Pred->getState()))
1902 // If this block is terminated by a loop and it has already been visited the
1903 // maximum number of times, widen the loop.
1904 unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1905 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1906 AMgr.options.shouldWidenLoops()) {
1907 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1909 (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1912 const LocationContext *LCtx = Pred->getLocationContext();
1913 ProgramStateRef WidenedState =
1914 getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1915 nodeBuilder.generateNode(WidenedState, Pred);
1919 // FIXME: Refactor this into a checker.
1920 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1921 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1922 const ExplodedNode *Sink =
1923 nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1925 // Check if we stopped at the top level function or not.
1926 // Root node should have the location context of the top most function.
1927 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1928 const LocationContext *CalleeSF = CalleeLC->getStackFrame();
1929 const LocationContext *RootLC =
1930 (*G.roots_begin())->getLocation().getLocationContext();
1931 if (RootLC->getStackFrame() != CalleeSF) {
1932 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1934 // Re-run the call evaluation without inlining it, by storing the
1935 // no-inlining policy in the state and enqueuing the new work item on
1936 // the list. Replay should almost never fail. Use the stats to catch it
1938 if ((!AMgr.options.NoRetryExhausted &&
1939 replayWithoutInlining(Pred, CalleeLC)))
1941 NumMaxBlockCountReachedInInlined++;
1943 NumMaxBlockCountReached++;
1945 // Make sink nodes as exhausted(for stats) only if retry failed.
1946 Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1950 //===----------------------------------------------------------------------===//
1951 // Branch processing.
1952 //===----------------------------------------------------------------------===//
1954 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1955 /// to try to recover some path-sensitivity for casts of symbolic
1956 /// integers that promote their values (which are currently not tracked well).
1957 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1958 // cast(s) did was sign-extend the original value.
1959 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1960 ProgramStateRef state,
1961 const Stmt *Condition,
1962 const LocationContext *LCtx,
1965 const auto *Ex = dyn_cast<Expr>(Condition);
1967 return UnknownVal();
1970 bool bitsInit = false;
1972 while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
1973 QualType T = CE->getType();
1975 if (!T->isIntegralOrEnumerationType())
1976 return UnknownVal();
1978 uint64_t newBits = Ctx.getTypeSize(T);
1979 if (!bitsInit || newBits < bits) {
1984 Ex = CE->getSubExpr();
1987 // We reached a non-cast. Is it a symbolic value?
1988 QualType T = Ex->getType();
1990 if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1991 Ctx.getTypeSize(T) > bits)
1992 return UnknownVal();
1994 return state->getSVal(Ex, LCtx);
1998 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
2000 const auto *BO = dyn_cast<BinaryOperator>(Condition);
2001 if (!BO || !BO->isLogicalOp()) {
2004 Condition = BO->getRHS()->IgnoreParens();
2010 // Returns the condition the branch at the end of 'B' depends on and whose value
2011 // has been evaluated within 'B'.
2012 // In most cases, the terminator condition of 'B' will be evaluated fully in
2013 // the last statement of 'B'; in those cases, the resolved condition is the
2014 // given 'Condition'.
2015 // If the condition of the branch is a logical binary operator tree, the CFG is
2016 // optimized: in that case, we know that the expression formed by all but the
2017 // rightmost leaf of the logical binary operator tree must be true, and thus
2018 // the branch condition is at this point equivalent to the truth value of that
2019 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
2020 // expression in its final statement. As the full condition in that case was
2021 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
2022 // expression to evaluate the truth value of the condition in the current state
2024 static const Stmt *ResolveCondition(const Stmt *Condition,
2025 const CFGBlock *B) {
2026 if (const auto *Ex = dyn_cast<Expr>(Condition))
2027 Condition = Ex->IgnoreParens();
2029 const auto *BO = dyn_cast<BinaryOperator>(Condition);
2030 if (!BO || !BO->isLogicalOp())
2033 assert(!B->getTerminator().isTemporaryDtorsBranch() &&
2034 "Temporary destructor branches handled by processBindTemporary.");
2036 // For logical operations, we still have the case where some branches
2037 // use the traditional "merge" approach and others sink the branch
2038 // directly into the basic blocks representing the logical operation.
2039 // We need to distinguish between those two cases here.
2041 // The invariants are still shifting, but it is possible that the
2042 // last element in a CFGBlock is not a CFGStmt. Look for the last
2043 // CFGStmt as the value of the condition.
2044 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
2045 for (; I != E; ++I) {
2046 CFGElement Elem = *I;
2047 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
2050 const Stmt *LastStmt = CS->getStmt();
2051 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
2054 llvm_unreachable("could not resolve condition");
2057 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
2058 NodeBuilderContext& BldCtx,
2060 ExplodedNodeSet &Dst,
2061 const CFGBlock *DstT,
2062 const CFGBlock *DstF) {
2063 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
2064 "CXXBindTemporaryExprs are handled by processBindTemporary.");
2065 const LocationContext *LCtx = Pred->getLocationContext();
2066 PrettyStackTraceLocationContext StackCrashInfo(LCtx);
2067 currBldrCtx = &BldCtx;
2069 // Check for NULL conditions; e.g. "for(;;)"
2071 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
2072 NullCondBldr.markInfeasible(false);
2073 NullCondBldr.generateNode(Pred->getState(), true, Pred);
2077 if (const auto *Ex = dyn_cast<Expr>(Condition))
2078 Condition = Ex->IgnoreParens();
2080 Condition = ResolveCondition(Condition, BldCtx.getBlock());
2081 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
2082 Condition->getLocStart(),
2083 "Error evaluating branch");
2085 ExplodedNodeSet CheckersOutSet;
2086 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
2088 // We generated only sinks.
2089 if (CheckersOutSet.empty())
2092 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
2093 for (const auto PredI : CheckersOutSet) {
2094 if (PredI->isSink())
2097 ProgramStateRef PrevState = PredI->getState();
2098 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
2100 if (X.isUnknownOrUndef()) {
2101 // Give it a chance to recover from unknown.
2102 if (const auto *Ex = dyn_cast<Expr>(Condition)) {
2103 if (Ex->getType()->isIntegralOrEnumerationType()) {
2104 // Try to recover some path-sensitivity. Right now casts of symbolic
2105 // integers that promote their values are currently not tracked well.
2106 // If 'Condition' is such an expression, try and recover the
2107 // underlying value and use that instead.
2108 SVal recovered = RecoverCastedSymbol(getStateManager(),
2109 PrevState, Condition,
2110 PredI->getLocationContext(),
2113 if (!recovered.isUnknown()) {
2120 // If the condition is still unknown, give up.
2121 if (X.isUnknownOrUndef()) {
2122 builder.generateNode(PrevState, true, PredI);
2123 builder.generateNode(PrevState, false, PredI);
2127 DefinedSVal V = X.castAs<DefinedSVal>();
2129 ProgramStateRef StTrue, StFalse;
2130 std::tie(StTrue, StFalse) = PrevState->assume(V);
2132 // Process the true branch.
2133 if (builder.isFeasible(true)) {
2135 builder.generateNode(StTrue, true, PredI);
2137 builder.markInfeasible(true);
2140 // Process the false branch.
2141 if (builder.isFeasible(false)) {
2143 builder.generateNode(StFalse, false, PredI);
2145 builder.markInfeasible(false);
2148 currBldrCtx = nullptr;
2151 /// The GDM component containing the set of global variables which have been
2152 /// previously initialized with explicit initializers.
2153 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
2154 llvm::ImmutableSet<const VarDecl *>)
2156 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
2157 NodeBuilderContext &BuilderCtx,
2159 ExplodedNodeSet &Dst,
2160 const CFGBlock *DstT,
2161 const CFGBlock *DstF) {
2162 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
2163 currBldrCtx = &BuilderCtx;
2165 const auto *VD = cast<VarDecl>(DS->getSingleDecl());
2166 ProgramStateRef state = Pred->getState();
2167 bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
2168 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
2171 state = state->add<InitializedGlobalsSet>(VD);
2174 builder.generateNode(state, initHasRun, Pred);
2175 builder.markInfeasible(!initHasRun);
2177 currBldrCtx = nullptr;
2180 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
2181 /// nodes by processing the 'effects' of a computed goto jump.
2182 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
2183 ProgramStateRef state = builder.getState();
2184 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
2186 // Three possibilities:
2188 // (1) We know the computed label.
2189 // (2) The label is NULL (or some other constant), or Undefined.
2190 // (3) We have no clue about the label. Dispatch to all targets.
2193 using iterator = IndirectGotoNodeBuilder::iterator;
2195 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
2196 const LabelDecl *L = LV->getLabel();
2198 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
2199 if (I.getLabel() == L) {
2200 builder.generateNode(I, state);
2205 llvm_unreachable("No block with label.");
2208 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
2209 // Dispatch to the first target and mark it as a sink.
2210 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
2211 // FIXME: add checker visit.
2212 // UndefBranches.insert(N);
2216 // This is really a catch-all. We don't support symbolics yet.
2217 // FIXME: Implement dispatch for symbolic pointers.
2219 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I)
2220 builder.generateNode(I, state);
2223 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
2225 ExplodedNodeSet &Dst,
2226 const BlockEdge &L) {
2227 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
2228 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
2231 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
2232 /// nodes when the control reaches the end of a function.
2233 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
2235 const ReturnStmt *RS) {
2236 // FIXME: We currently cannot assert that temporaries are clear, because
2237 // lifetime extended temporaries are not always modelled correctly. In some
2238 // cases when we materialize the temporary, we do
2239 // createTemporaryRegionIfNeeded(), and the region changes, and also the
2240 // respective destructor becomes automatic from temporary. So for now clean up
2241 // the state manually before asserting. Ideally, the code above the assertion
2242 // should go away, but the assertion should remain.
2244 ExplodedNodeSet CleanUpObjects;
2245 NodeBuilder Bldr(Pred, CleanUpObjects, BC);
2246 ProgramStateRef State = Pred->getState();
2247 const LocationContext *FromLC = Pred->getLocationContext();
2248 const LocationContext *ToLC = FromLC->getStackFrame()->getParent();
2249 const LocationContext *LC = FromLC;
2250 while (LC != ToLC) {
2251 assert(LC && "ToLC must be a parent of FromLC!");
2252 for (auto I : State->get<ObjectsUnderConstruction>())
2253 if (I.first.getLocationContext() == LC) {
2254 // The comment above only pardons us for not cleaning up a
2255 // CXXBindTemporaryExpr. If any other statements are found here,
2256 // it must be a separate problem.
2257 assert(isa<CXXBindTemporaryExpr>(I.first.getStmt()));
2258 State = State->remove<ObjectsUnderConstruction>(I.first);
2259 // Also cleanup the elided destructor info.
2260 ElidedDestructorItem Item(
2261 cast<CXXBindTemporaryExpr>(I.first.getStmt()),
2262 I.first.getLocationContext());
2263 State = State->remove<ElidedDestructors>(Item);
2266 // Also suppress the assertion for elided destructors when temporary
2267 // destructors are not provided at all by the CFG, because there's no
2268 // good place to clean them up.
2269 if (!AMgr.getAnalyzerOptions().includeTemporaryDtorsInCFG())
2270 for (auto I : State->get<ElidedDestructors>())
2272 State = State->remove<ElidedDestructors>(I);
2274 LC = LC->getParent();
2276 if (State != Pred->getState()) {
2277 Pred = Bldr.generateNode(Pred->getLocation(), State, Pred);
2279 // The node with clean temporaries already exists. We might have reached
2280 // it on a path on which we initialize different temporaries.
2285 assert(areAllObjectsFullyConstructed(Pred->getState(),
2286 Pred->getLocationContext(),
2287 Pred->getStackFrame()->getParent()));
2289 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
2290 StateMgr.EndPath(Pred->getState());
2292 ExplodedNodeSet Dst;
2293 if (Pred->getLocationContext()->inTopFrame()) {
2294 // Remove dead symbols.
2295 ExplodedNodeSet AfterRemovedDead;
2296 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
2299 for (const auto I : AfterRemovedDead)
2300 getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this, RS);
2302 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this, RS);
2305 Engine.enqueueEndOfFunction(Dst, RS);
2308 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
2309 /// nodes by processing the 'effects' of a switch statement.
2310 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
2311 using iterator = SwitchNodeBuilder::iterator;
2313 ProgramStateRef state = builder.getState();
2314 const Expr *CondE = builder.getCondition();
2315 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
2317 if (CondV_untested.isUndef()) {
2318 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
2319 // FIXME: add checker
2320 //UndefBranches.insert(N);
2324 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
2326 ProgramStateRef DefaultSt = state;
2328 iterator I = builder.begin(), EI = builder.end();
2329 bool defaultIsFeasible = I == EI;
2331 for ( ; I != EI; ++I) {
2332 // Successor may be pruned out during CFG construction.
2336 const CaseStmt *Case = I.getCase();
2338 // Evaluate the LHS of the case value.
2339 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
2340 assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
2342 // Get the RHS of the case, if it exists.
2344 if (const Expr *E = Case->getRHS())
2345 V2 = E->EvaluateKnownConstInt(getContext());
2349 ProgramStateRef StateCase;
2350 if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
2351 std::tie(StateCase, DefaultSt) =
2352 DefaultSt->assumeInclusiveRange(*NL, V1, V2);
2354 StateCase = DefaultSt;
2357 builder.generateCaseStmtNode(I, StateCase);
2359 // Now "assume" that the case doesn't match. Add this state
2360 // to the default state (if it is feasible).
2362 defaultIsFeasible = true;
2364 defaultIsFeasible = false;
2369 if (!defaultIsFeasible)
2372 // If we have switch(enum value), the default branch is not
2373 // feasible if all of the enum constants not covered by 'case:' statements
2374 // are not feasible values for the switch condition.
2376 // Note that this isn't as accurate as it could be. Even if there isn't
2377 // a case for a particular enum value as long as that enum value isn't
2378 // feasible then it shouldn't be considered for making 'default:' reachable.
2379 const SwitchStmt *SS = builder.getSwitch();
2380 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
2381 if (CondExpr->getType()->getAs<EnumType>()) {
2382 if (SS->isAllEnumCasesCovered())
2386 builder.generateDefaultCaseNode(DefaultSt);
2389 //===----------------------------------------------------------------------===//
2390 // Transfer functions: Loads and stores.
2391 //===----------------------------------------------------------------------===//
2393 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
2395 ExplodedNodeSet &Dst) {
2396 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2398 ProgramStateRef state = Pred->getState();
2399 const LocationContext *LCtx = Pred->getLocationContext();
2401 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2402 // C permits "extern void v", and if you cast the address to a valid type,
2403 // you can even do things with it. We simply pretend
2404 assert(Ex->isGLValue() || VD->getType()->isVoidType());
2405 const LocationContext *LocCtxt = Pred->getLocationContext();
2406 const Decl *D = LocCtxt->getDecl();
2407 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
2408 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
2409 Optional<std::pair<SVal, QualType>> VInfo;
2411 if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
2412 DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
2413 MD->getParent()->isLambda()) {
2414 // Lookup the field of the lambda.
2415 const CXXRecordDecl *CXXRec = MD->getParent();
2416 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
2417 FieldDecl *LambdaThisCaptureField;
2418 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
2420 // Sema follows a sequence of complex rules to determine whether the
2421 // variable should be captured.
2422 if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
2424 svalBuilder.getCXXThis(MD, LocCtxt->getStackFrame());
2425 SVal CXXThisVal = state->getSVal(CXXThis);
2426 VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
2431 VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType());
2433 SVal V = VInfo->first;
2434 bool IsReference = VInfo->second->isReferenceType();
2436 // For references, the 'lvalue' is the pointer address stored in the
2437 // reference region.
2439 if (const MemRegion *R = V.getAsRegion())
2440 V = state->getSVal(R);
2445 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2446 ProgramPoint::PostLValueKind);
2449 if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
2450 assert(!Ex->isGLValue());
2451 SVal V = svalBuilder.makeIntVal(ED->getInitVal());
2452 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
2455 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2456 SVal V = svalBuilder.getFunctionPointer(FD);
2457 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2458 ProgramPoint::PostLValueKind);
2461 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
2462 // FIXME: Compute lvalue of field pointers-to-member.
2463 // Right now we just use a non-null void pointer, so that it gives proper
2464 // results in boolean contexts.
2465 // FIXME: Maybe delegate this to the surrounding operator&.
2466 // Note how this expression is lvalue, however pointer-to-member is NonLoc.
2467 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
2468 currBldrCtx->blockCount());
2469 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
2470 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2471 ProgramPoint::PostLValueKind);
2474 if (isa<BindingDecl>(D)) {
2475 // FIXME: proper support for bound declarations.
2476 // For now, let's just prevent crashing.
2480 llvm_unreachable("Support for this Decl not implemented.");
2483 /// VisitArraySubscriptExpr - Transfer function for array accesses
2484 void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A,
2486 ExplodedNodeSet &Dst){
2487 const Expr *Base = A->getBase()->IgnoreParens();
2488 const Expr *Idx = A->getIdx()->IgnoreParens();
2490 ExplodedNodeSet CheckerPreStmt;
2491 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
2493 ExplodedNodeSet EvalSet;
2494 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
2496 bool IsVectorType = A->getBase()->getType()->isVectorType();
2498 // The "like" case is for situations where C standard prohibits the type to
2499 // be an lvalue, e.g. taking the address of a subscript of an expression of
2501 bool IsGLValueLike = A->isGLValue() ||
2502 (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
2504 for (auto *Node : CheckerPreStmt) {
2505 const LocationContext *LCtx = Node->getLocationContext();
2506 ProgramStateRef state = Node->getState();
2508 if (IsGLValueLike) {
2509 QualType T = A->getType();
2511 // One of the forbidden LValue types! We still need to have sensible
2512 // symbolic locations to represent this stuff. Note that arithmetic on
2513 // void pointers is a GCC extension.
2514 if (T->isVoidType())
2515 T = getContext().CharTy;
2517 SVal V = state->getLValue(T,
2518 state->getSVal(Idx, LCtx),
2519 state->getSVal(Base, LCtx));
2520 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
2521 ProgramPoint::PostLValueKind);
2522 } else if (IsVectorType) {
2523 // FIXME: non-glvalue vector reads are not modelled.
2524 Bldr.generateNode(A, Node, state, nullptr);
2526 llvm_unreachable("Array subscript should be an lValue when not \
2527 a vector and not a forbidden lvalue type");
2531 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
2534 /// VisitMemberExpr - Transfer function for member expressions.
2535 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
2536 ExplodedNodeSet &Dst) {
2537 // FIXME: Prechecks eventually go in ::Visit().
2538 ExplodedNodeSet CheckedSet;
2539 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
2541 ExplodedNodeSet EvalSet;
2542 ValueDecl *Member = M->getMemberDecl();
2544 // Handle static member variables and enum constants accessed via
2546 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2547 for (const auto I : CheckedSet)
2548 VisitCommonDeclRefExpr(M, Member, I, EvalSet);
2550 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2551 ExplodedNodeSet Tmp;
2553 for (const auto I : CheckedSet) {
2554 ProgramStateRef state = I->getState();
2555 const LocationContext *LCtx = I->getLocationContext();
2556 Expr *BaseExpr = M->getBase();
2558 // Handle C++ method calls.
2559 if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
2560 if (MD->isInstance())
2561 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2563 SVal MDVal = svalBuilder.getFunctionPointer(MD);
2564 state = state->BindExpr(M, LCtx, MDVal);
2566 Bldr.generateNode(M, I, state);
2570 // Handle regular struct fields / member variables.
2571 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2572 SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
2574 const auto *field = cast<FieldDecl>(Member);
2575 SVal L = state->getLValue(field, baseExprVal);
2577 if (M->isGLValue() || M->getType()->isArrayType()) {
2578 // We special-case rvalues of array type because the analyzer cannot
2579 // reason about them, since we expect all regions to be wrapped in Locs.
2580 // We instead treat these as lvalues and assume that they will decay to
2581 // pointers as soon as they are used.
2582 if (!M->isGLValue()) {
2583 assert(M->getType()->isArrayType());
2585 dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
2586 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2587 llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2591 if (field->getType()->isReferenceType()) {
2592 if (const MemRegion *R = L.getAsRegion())
2593 L = state->getSVal(R);
2598 Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr,
2599 ProgramPoint::PostLValueKind);
2602 evalLoad(Tmp, M, M, I, state, L);
2608 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2611 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
2612 ExplodedNodeSet &Dst) {
2613 ExplodedNodeSet AfterPreSet;
2614 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
2616 // For now, treat all the arguments to C11 atomics as escaping.
2617 // FIXME: Ideally we should model the behavior of the atomics precisely here.
2619 ExplodedNodeSet AfterInvalidateSet;
2620 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
2622 for (const auto I : AfterPreSet) {
2623 ProgramStateRef State = I->getState();
2624 const LocationContext *LCtx = I->getLocationContext();
2626 SmallVector<SVal, 8> ValuesToInvalidate;
2627 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
2628 const Expr *SubExpr = AE->getSubExprs()[SI];
2629 SVal SubExprVal = State->getSVal(SubExpr, LCtx);
2630 ValuesToInvalidate.push_back(SubExprVal);
2633 State = State->invalidateRegions(ValuesToInvalidate, AE,
2634 currBldrCtx->blockCount(),
2636 /*CausedByPointerEscape*/true,
2637 /*Symbols=*/nullptr);
2639 SVal ResultVal = UnknownVal();
2640 State = State->BindExpr(AE, LCtx, ResultVal);
2641 Bldr.generateNode(AE, I, State, nullptr,
2642 ProgramPoint::PostStmtKind);
2645 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
2648 // A value escapes in three possible cases:
2649 // (1) We are binding to something that is not a memory region.
2650 // (2) We are binding to a MemrRegion that does not have stack storage.
2651 // (3) We are binding to a MemRegion with stack storage that the store
2652 // does not understand.
2653 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2656 const LocationContext *LCtx) {
2657 // Are we storing to something that causes the value to "escape"?
2658 bool escapes = true;
2660 // TODO: Move to StoreManager.
2661 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2662 escapes = !regionLoc->getRegion()->hasStackStorage();
2665 // To test (3), generate a new state with the binding added. If it is
2666 // the same state, then it escapes (since the store cannot represent
2668 // Do this only if we know that the store is not supposed to generate the
2670 SVal StoredVal = State->getSVal(regionLoc->getRegion());
2671 if (StoredVal != Val)
2672 escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
2676 // If our store can represent the binding and we aren't storing to something
2677 // that doesn't have local storage then just return and have the simulation
2678 // state continue as is.
2682 // Otherwise, find all symbols referenced by 'val' that we are tracking
2683 // and stop tracking them.
2684 State = escapeValue(State, Val, PSK_EscapeOnBind);
2689 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2690 const InvalidatedSymbols *Invalidated,
2691 ArrayRef<const MemRegion *> ExplicitRegions,
2692 ArrayRef<const MemRegion *> Regions,
2693 const CallEvent *Call,
2694 RegionAndSymbolInvalidationTraits &ITraits) {
2695 if (!Invalidated || Invalidated->empty())
2699 return getCheckerManager().runCheckersForPointerEscape(State,
2705 // If the symbols were invalidated by a call, we want to find out which ones
2706 // were invalidated directly due to being arguments to the call.
2707 InvalidatedSymbols SymbolsDirectlyInvalidated;
2708 for (const auto I : ExplicitRegions) {
2709 if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
2710 SymbolsDirectlyInvalidated.insert(R->getSymbol());
2713 InvalidatedSymbols SymbolsIndirectlyInvalidated;
2714 for (const auto &sym : *Invalidated) {
2715 if (SymbolsDirectlyInvalidated.count(sym))
2717 SymbolsIndirectlyInvalidated.insert(sym);
2720 if (!SymbolsDirectlyInvalidated.empty())
2721 State = getCheckerManager().runCheckersForPointerEscape(State,
2722 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2724 // Notify about the symbols that get indirectly invalidated by the call.
2725 if (!SymbolsIndirectlyInvalidated.empty())
2726 State = getCheckerManager().runCheckersForPointerEscape(State,
2727 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2732 /// evalBind - Handle the semantics of binding a value to a specific location.
2733 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
2734 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2736 SVal location, SVal Val,
2737 bool atDeclInit, const ProgramPoint *PP) {
2738 const LocationContext *LC = Pred->getLocationContext();
2739 PostStmt PS(StoreE, LC);
2743 // Do a previsit of the bind.
2744 ExplodedNodeSet CheckedSet;
2745 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2746 StoreE, *this, *PP);
2748 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2750 // If the location is not a 'Loc', it will already be handled by
2751 // the checkers. There is nothing left to do.
2752 if (!location.getAs<Loc>()) {
2753 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2755 ProgramStateRef state = Pred->getState();
2756 state = processPointerEscapedOnBind(state, location, Val, LC);
2757 Bldr.generateNode(L, state, Pred);
2761 for (const auto PredI : CheckedSet) {
2762 ProgramStateRef state = PredI->getState();
2764 state = processPointerEscapedOnBind(state, location, Val, LC);
2766 // When binding the value, pass on the hint that this is a initialization.
2767 // For initializations, we do not need to inform clients of region
2769 state = state->bindLoc(location.castAs<Loc>(),
2770 Val, LC, /* notifyChanges = */ !atDeclInit);
2772 const MemRegion *LocReg = nullptr;
2773 if (Optional<loc::MemRegionVal> LocRegVal =
2774 location.getAs<loc::MemRegionVal>()) {
2775 LocReg = LocRegVal->getRegion();
2778 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2779 Bldr.generateNode(L, state, PredI);
2783 /// evalStore - Handle the semantics of a store via an assignment.
2784 /// @param Dst The node set to store generated state nodes
2785 /// @param AssignE The assignment expression if the store happens in an
2787 /// @param LocationE The location expression that is stored to.
2788 /// @param state The current simulation state
2789 /// @param location The location to store the value
2790 /// @param Val The value to be stored
2791 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2792 const Expr *LocationE,
2794 ProgramStateRef state, SVal location, SVal Val,
2795 const ProgramPointTag *tag) {
2796 // Proceed with the store. We use AssignE as the anchor for the PostStore
2797 // ProgramPoint if it is non-NULL, and LocationE otherwise.
2798 const Expr *StoreE = AssignE ? AssignE : LocationE;
2800 // Evaluate the location (checks for bad dereferences).
2801 ExplodedNodeSet Tmp;
2802 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2807 if (location.isUndef())
2810 for (const auto I : Tmp)
2811 evalBind(Dst, StoreE, I, location, Val, false);
2814 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2816 const Expr *BoundEx,
2818 ProgramStateRef state,
2820 const ProgramPointTag *tag,
2822 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2825 // Evaluate the location (checks for bad dereferences).
2826 ExplodedNodeSet Tmp;
2827 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2831 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2832 if (location.isUndef())
2835 // Proceed with the load.
2836 for (const auto I : Tmp) {
2837 state = I->getState();
2838 const LocationContext *LCtx = I->getLocationContext();
2840 SVal V = UnknownVal();
2841 if (location.isValid()) {
2842 if (LoadTy.isNull())
2843 LoadTy = BoundEx->getType();
2844 V = state->getSVal(location.castAs<Loc>(), LoadTy);
2847 Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
2848 ProgramPoint::PostLoadKind);
2852 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2854 const Stmt *BoundEx,
2856 ProgramStateRef state,
2858 const ProgramPointTag *tag,
2860 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2861 // Early checks for performance reason.
2862 if (location.isUnknown()) {
2866 ExplodedNodeSet Src;
2867 BldrTop.takeNodes(Pred);
2868 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2869 if (Pred->getState() != state) {
2870 // Associate this new state with an ExplodedNode.
2871 // FIXME: If I pass null tag, the graph is incorrect, e.g for
2875 // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2876 // instead "int *p" is noted as
2877 // "Variable 'p' initialized to a null pointer value"
2879 static SimpleProgramPointTag tag(TagProviderName, "Location");
2880 Bldr.generateNode(NodeEx, Pred, state, &tag);
2882 ExplodedNodeSet Tmp;
2883 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2884 NodeEx, BoundEx, *this);
2885 BldrTop.addNodes(Tmp);
2888 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2889 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2890 static SimpleProgramPointTag
2891 eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2892 "Eagerly Assume True"),
2893 eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2894 "Eagerly Assume False");
2895 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2896 &eagerlyAssumeBinOpBifurcationFalse);
2899 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2900 ExplodedNodeSet &Src,
2902 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2904 for (const auto Pred : Src) {
2905 // Test if the previous node was as the same expression. This can happen
2906 // when the expression fails to evaluate to anything meaningful and
2907 // (as an optimization) we don't generate a node.
2908 ProgramPoint P = Pred->getLocation();
2909 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2913 ProgramStateRef state = Pred->getState();
2914 SVal V = state->getSVal(Ex, Pred->getLocationContext());
2915 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2916 if (SEV && SEV->isExpression()) {
2917 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2918 geteagerlyAssumeBinOpBifurcationTags();
2920 ProgramStateRef StateTrue, StateFalse;
2921 std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2923 // First assume that the condition is true.
2925 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2926 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2927 Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2930 // Next, assume that the condition is false.
2932 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2933 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2934 Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2940 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2941 ExplodedNodeSet &Dst) {
2942 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2943 // We have processed both the inputs and the outputs. All of the outputs
2944 // should evaluate to Locs. Nuke all of their values.
2946 // FIXME: Some day in the future it would be nice to allow a "plug-in"
2947 // which interprets the inline asm and stores proper results in the
2950 ProgramStateRef state = Pred->getState();
2952 for (const Expr *O : A->outputs()) {
2953 SVal X = state->getSVal(O, Pred->getLocationContext());
2954 assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2956 if (Optional<Loc> LV = X.getAs<Loc>())
2957 state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
2960 Bldr.generateNode(A, Pred, state);
2963 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2964 ExplodedNodeSet &Dst) {
2965 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2966 Bldr.generateNode(A, Pred, Pred->getState());
2969 //===----------------------------------------------------------------------===//
2971 //===----------------------------------------------------------------------===//
2974 static ExprEngine* GraphPrintCheckerState;
2975 static SourceManager* GraphPrintSourceManager;
2980 struct DOTGraphTraits<ExplodedNode*> : public DefaultDOTGraphTraits {
2981 DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2983 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2985 static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2989 // De-duplicate some source location pretty-printing.
2990 static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2991 if (SLoc.isFileID()) {
2993 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2995 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
3000 static std::string getNodeLabel(const ExplodedNode *N, void*){
3002 llvm::raw_string_ostream Out(sbuf);
3004 // Program Location.
3005 ProgramPoint Loc = N->getLocation();
3007 switch (Loc.getKind()) {
3008 case ProgramPoint::BlockEntranceKind:
3009 Out << "Block Entrance: B"
3010 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
3013 case ProgramPoint::BlockExitKind:
3017 case ProgramPoint::CallEnterKind:
3021 case ProgramPoint::CallExitBeginKind:
3022 Out << "CallExitBegin";
3025 case ProgramPoint::CallExitEndKind:
3026 Out << "CallExitEnd";
3029 case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
3030 Out << "PostStmtPurgeDeadSymbols";
3033 case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
3034 Out << "PreStmtPurgeDeadSymbols";
3037 case ProgramPoint::EpsilonKind:
3038 Out << "Epsilon Point";
3041 case ProgramPoint::LoopExitKind: {
3042 LoopExit LE = Loc.castAs<LoopExit>();
3043 Out << "LoopExit: " << LE.getLoopStmt()->getStmtClassName();
3047 case ProgramPoint::PreImplicitCallKind: {
3048 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
3051 // FIXME: Get proper printing options.
3052 PC.getDecl()->print(Out, LangOptions());
3053 printLocation(Out, PC.getLocation());
3057 case ProgramPoint::PostImplicitCallKind: {
3058 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
3059 Out << "PostCall: ";
3061 // FIXME: Get proper printing options.
3062 PC.getDecl()->print(Out, LangOptions());
3063 printLocation(Out, PC.getLocation());
3067 case ProgramPoint::PostInitializerKind: {
3068 Out << "PostInitializer: ";
3069 const CXXCtorInitializer *Init =
3070 Loc.castAs<PostInitializer>().getInitializer();
3071 if (const FieldDecl *FD = Init->getAnyMember())
3074 QualType Ty = Init->getTypeSourceInfo()->getType();
3075 Ty = Ty.getLocalUnqualifiedType();
3076 LangOptions LO; // FIXME.
3082 case ProgramPoint::BlockEdgeKind: {
3083 const BlockEdge &E = Loc.castAs<BlockEdge>();
3084 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
3085 << E.getDst()->getBlockID() << ')';
3087 if (const Stmt *T = E.getSrc()->getTerminator()) {
3088 SourceLocation SLoc = T->getLocStart();
3090 Out << "\\|Terminator: ";
3091 LangOptions LO; // FIXME.
3092 E.getSrc()->printTerminator(Out, LO);
3094 if (SLoc.isFileID()) {
3096 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
3098 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
3101 if (isa<SwitchStmt>(T)) {
3102 const Stmt *Label = E.getDst()->getLabel();
3105 if (const auto *C = dyn_cast<CaseStmt>(Label)) {
3107 LangOptions LO; // FIXME.
3109 C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
3111 if (const Stmt *RHS = C->getRHS()) {
3113 RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
3119 assert(isa<DefaultStmt>(Label));
3120 Out << "\\ldefault:";
3124 Out << "\\l(implicit) default:";
3126 else if (isa<IndirectGotoStmt>(T)) {
3130 Out << "\\lCondition: ";
3131 if (*E.getSrc()->succ_begin() == E.getDst())
3144 const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
3145 assert(S != nullptr && "Expecting non-null Stmt");
3147 Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
3148 LangOptions LO; // FIXME.
3149 S->printPretty(Out, nullptr, PrintingPolicy(LO));
3150 printLocation(Out, S->getLocStart());
3152 if (Loc.getAs<PreStmt>())
3153 Out << "\\lPreStmt\\l;";
3154 else if (Loc.getAs<PostLoad>())
3155 Out << "\\lPostLoad\\l;";
3156 else if (Loc.getAs<PostStore>())
3157 Out << "\\lPostStore\\l";
3158 else if (Loc.getAs<PostLValue>())
3159 Out << "\\lPostLValue\\l";
3160 else if (Loc.getAs<PostAllocatorCall>())
3161 Out << "\\lPostAllocatorCall\\l";
3167 ProgramStateRef state = N->getState();
3168 Out << "\\|StateID: " << (const void*) state.get()
3169 << " NodeID: " << (const void*) N << "\\|";
3171 state->printDOT(Out, N->getLocationContext());
3175 if (const ProgramPointTag *tag = Loc.getTag()) {
3176 Out << "\\|Tag: " << tag->getTagDescription();
3186 void ExprEngine::ViewGraph(bool trim) {
3189 std::vector<const ExplodedNode *> Src;
3191 // Flush any outstanding reports to make sure we cover all the nodes.
3192 // This does not cause them to get displayed.
3193 for (const auto I : BR)
3194 const_cast<BugType *>(I)->FlushReports(BR);
3196 // Iterate through the reports and get their nodes.
3197 for (BugReporter::EQClasses_iterator
3198 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
3199 const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
3200 if (N) Src.push_back(N);
3206 GraphPrintCheckerState = this;
3207 GraphPrintSourceManager = &getContext().getSourceManager();
3209 llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
3211 GraphPrintCheckerState = nullptr;
3212 GraphPrintSourceManager = nullptr;
3217 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
3219 GraphPrintCheckerState = this;
3220 GraphPrintSourceManager = &getContext().getSourceManager();
3222 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
3224 if (!TrimmedG.get())
3225 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
3227 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
3229 GraphPrintCheckerState = nullptr;
3230 GraphPrintSourceManager = nullptr;