1 //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines a meta-engine for path-sensitive dataflow analysis that
10 // is built on GREngine, but provides the boilerplate to execute transfer
11 // functions and build the ExplodedGraph at the expression level.
13 //===----------------------------------------------------------------------===//
15 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
16 #include "PrettyStackTraceLocationContext.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ParentMap.h"
26 #include "clang/AST/PrettyPrinter.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/StmtObjC.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Analysis/AnalysisDeclContext.h"
32 #include "clang/Analysis/CFG.h"
33 #include "clang/Analysis/ConstructionContext.h"
34 #include "clang/Analysis/ProgramPoint.h"
35 #include "clang/Basic/IdentifierTable.h"
36 #include "clang/Basic/JsonSupport.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");
101 //===----------------------------------------------------------------------===//
102 // Internal program state traits.
103 //===----------------------------------------------------------------------===//
107 // When modeling a C++ constructor, for a variety of reasons we need to track
108 // the location of the object for the duration of its ConstructionContext.
109 // ObjectsUnderConstruction maps statements within the construction context
110 // to the object's location, so that on every such statement the location
111 // could have been retrieved.
113 /// ConstructedObjectKey is used for being able to find the path-sensitive
114 /// memory region of a freshly constructed object while modeling the AST node
115 /// that syntactically represents the object that is being constructed.
116 /// Semantics of such nodes may sometimes require access to the region that's
117 /// not otherwise present in the program state, or to the very fact that
118 /// the construction context was present and contained references to these
120 class ConstructedObjectKey {
121 typedef std::pair<ConstructionContextItem, const LocationContext *>
122 ConstructedObjectKeyImpl;
124 const ConstructedObjectKeyImpl Impl;
126 const void *getAnyASTNodePtr() const {
127 if (const Stmt *S = getItem().getStmtOrNull())
130 return getItem().getCXXCtorInitializer();
134 explicit ConstructedObjectKey(const ConstructionContextItem &Item,
135 const LocationContext *LC)
138 const ConstructionContextItem &getItem() const { return Impl.first; }
139 const LocationContext *getLocationContext() const { return Impl.second; }
141 ASTContext &getASTContext() const {
142 return getLocationContext()->getDecl()->getASTContext();
145 void printJson(llvm::raw_ostream &Out, PrinterHelper *Helper,
146 PrintingPolicy &PP) const {
147 const Stmt *S = getItem().getStmtOrNull();
148 const CXXCtorInitializer *I = nullptr;
150 I = getItem().getCXXCtorInitializer();
153 Out << "\"stmt_id\": " << S->getID(getASTContext());
155 Out << "\"init_id\": " << I->getID(getASTContext());
158 Out << ", \"kind\": \"" << getItem().getKindAsString()
159 << "\", \"argument_index\": ";
161 if (getItem().getKind() == ConstructionContextItem::ArgumentKind)
162 Out << getItem().getIndex();
167 Out << ", \"pretty\": ";
170 S->printJson(Out, Helper, PP, /*AddQuotes=*/true);
172 Out << '\"' << I->getAnyMember()->getNameAsString() << '\"';
176 void Profile(llvm::FoldingSetNodeID &ID) const {
178 ID.AddPointer(Impl.second);
181 bool operator==(const ConstructedObjectKey &RHS) const {
182 return Impl == RHS.Impl;
185 bool operator<(const ConstructedObjectKey &RHS) const {
186 return Impl < RHS.Impl;
191 typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
192 ObjectsUnderConstructionMap;
193 REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
194 ObjectsUnderConstructionMap)
196 //===----------------------------------------------------------------------===//
197 // Engine construction and deletion.
198 //===----------------------------------------------------------------------===//
200 static const char* TagProviderName = "ExprEngine";
202 ExprEngine::ExprEngine(cross_tu::CrossTranslationUnitContext &CTU,
203 AnalysisManager &mgr,
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 MRMgr(StateMgr.getRegionManager()),
215 svalBuilder(StateMgr.getSValBuilder()),
216 ObjCNoRet(mgr.getASTContext()),
218 VisitedCallees(VisitedCalleesIn),
219 HowToInline(HowToInlineIn)
221 unsigned TrimInterval = mgr.options.GraphTrimInterval;
222 if (TrimInterval != 0) {
223 // Enable eager node reclamation when constructing the ExplodedGraph.
224 G.enableNodeReclamation(TrimInterval);
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");
309 ProgramStateRef ExprEngine::createTemporaryRegionIfNeeded(
310 ProgramStateRef State, const LocationContext *LC,
311 const Expr *InitWithAdjustments, const Expr *Result,
312 const SubRegion **OutRegionWithAdjustments) {
313 // FIXME: This function is a hack that works around the quirky AST
314 // we're often having with respect to C++ temporaries. If only we modelled
315 // the actual execution order of statements properly in the CFG,
316 // all the hassle with adjustments would not be necessary,
317 // and perhaps the whole function would be removed.
318 SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
320 // If we don't have an explicit result expression, we're in "if needed"
321 // mode. Only create a region if the current value is a NonLoc.
322 if (!InitValWithAdjustments.getAs<NonLoc>()) {
323 if (OutRegionWithAdjustments)
324 *OutRegionWithAdjustments = nullptr;
327 Result = InitWithAdjustments;
329 // We need to create a region no matter what. For sanity, make sure we don't
330 // try to stuff a Loc into a non-pointer temporary region.
331 assert(!InitValWithAdjustments.getAs<Loc>() ||
332 Loc::isLocType(Result->getType()) ||
333 Result->getType()->isMemberPointerType());
336 ProgramStateManager &StateMgr = State->getStateManager();
337 MemRegionManager &MRMgr = StateMgr.getRegionManager();
338 StoreManager &StoreMgr = StateMgr.getStoreManager();
340 // MaterializeTemporaryExpr may appear out of place, after a few field and
341 // base-class accesses have been made to the object, even though semantically
342 // it is the whole object that gets materialized and lifetime-extended.
346 // `-MaterializeTemporaryExpr
348 // `-CXXTemporaryObjectExpr
350 // instead of the more natural
353 // `-MaterializeTemporaryExpr
354 // `-CXXTemporaryObjectExpr
356 // Use the usual methods for obtaining the expression of the base object,
357 // and record the adjustments that we need to make to obtain the sub-object
358 // that the whole expression 'Ex' refers to. This trick is usual,
359 // in the sense that CodeGen takes a similar route.
361 SmallVector<const Expr *, 2> CommaLHSs;
362 SmallVector<SubobjectAdjustment, 2> Adjustments;
364 const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
365 CommaLHSs, Adjustments);
367 // Take the region for Init, i.e. for the whole object. If we do not remember
368 // the region in which the object originally was constructed, come up with
369 // a new temporary region out of thin air and copy the contents of the object
370 // (which are currently present in the Environment, because Init is an rvalue)
371 // into that region. This is not correct, but it is better than nothing.
372 const TypedValueRegion *TR = nullptr;
373 if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
374 if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
375 State = finishObjectConstruction(State, MT, LC);
376 State = State->BindExpr(Result, LC, *V);
379 StorageDuration SD = MT->getStorageDuration();
380 // If this object is bound to a reference with static storage duration, we
381 // put it in a different region to prevent "address leakage" warnings.
382 if (SD == SD_Static || SD == SD_Thread) {
383 TR = MRMgr.getCXXStaticTempObjectRegion(Init);
385 TR = MRMgr.getCXXTempObjectRegion(Init, LC);
389 TR = MRMgr.getCXXTempObjectRegion(Init, LC);
392 SVal Reg = loc::MemRegionVal(TR);
395 // Make the necessary adjustments to obtain the sub-object.
396 for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
397 const SubobjectAdjustment &Adj = *I;
399 case SubobjectAdjustment::DerivedToBaseAdjustment:
400 Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
402 case SubobjectAdjustment::FieldAdjustment:
403 Reg = StoreMgr.getLValueField(Adj.Field, Reg);
405 case SubobjectAdjustment::MemberPointerAdjustment:
406 // FIXME: Unimplemented.
407 State = State->invalidateRegions(Reg, InitWithAdjustments,
408 currBldrCtx->blockCount(), LC, true,
409 nullptr, nullptr, nullptr);
414 // What remains is to copy the value of the object to the new region.
415 // FIXME: In other words, what we should always do is copy value of the
416 // Init expression (which corresponds to the bigger object) to the whole
417 // temporary region TR. However, this value is often no longer present
418 // in the Environment. If it has disappeared, we instead invalidate TR.
419 // Still, what we can do is assign the value of expression Ex (which
420 // corresponds to the sub-object) to the TR's sub-region Reg. At least,
421 // values inside Reg would be correct.
422 SVal InitVal = State->getSVal(Init, LC);
423 if (InitVal.isUnknown()) {
424 InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
425 currBldrCtx->blockCount());
426 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
428 // Then we'd need to take the value that certainly exists and bind it
430 if (InitValWithAdjustments.isUnknown()) {
431 // Try to recover some path sensitivity in case we couldn't
432 // compute the value.
433 InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
434 Result, LC, InitWithAdjustments->getType(),
435 currBldrCtx->blockCount());
438 State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
440 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
443 // The result expression would now point to the correct sub-region of the
444 // newly created temporary region. Do this last in order to getSVal of Init
445 // correctly in case (Result == Init).
446 if (Result->isGLValue()) {
447 State = State->BindExpr(Result, LC, Reg);
449 State = State->BindExpr(Result, LC, InitValWithAdjustments);
452 // Notify checkers once for two bindLoc()s.
453 State = processRegionChange(State, TR, LC);
455 if (OutRegionWithAdjustments)
456 *OutRegionWithAdjustments = cast<SubRegion>(Reg.getAsRegion());
461 ExprEngine::addObjectUnderConstruction(ProgramStateRef State,
462 const ConstructionContextItem &Item,
463 const LocationContext *LC, SVal V) {
464 ConstructedObjectKey Key(Item, LC->getStackFrame());
465 // FIXME: Currently the state might already contain the marker due to
466 // incorrect handling of temporaries bound to default parameters.
467 assert(!State->get<ObjectsUnderConstruction>(Key) ||
468 Key.getItem().getKind() ==
469 ConstructionContextItem::TemporaryDestructorKind);
470 return State->set<ObjectsUnderConstruction>(Key, V);
474 ExprEngine::getObjectUnderConstruction(ProgramStateRef State,
475 const ConstructionContextItem &Item,
476 const LocationContext *LC) {
477 ConstructedObjectKey Key(Item, LC->getStackFrame());
478 return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
482 ExprEngine::finishObjectConstruction(ProgramStateRef State,
483 const ConstructionContextItem &Item,
484 const LocationContext *LC) {
485 ConstructedObjectKey Key(Item, LC->getStackFrame());
486 assert(State->contains<ObjectsUnderConstruction>(Key));
487 return State->remove<ObjectsUnderConstruction>(Key);
490 ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
491 const CXXBindTemporaryExpr *BTE,
492 const LocationContext *LC) {
493 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
494 // FIXME: Currently the state might already contain the marker due to
495 // incorrect handling of temporaries bound to default parameters.
496 return State->set<ObjectsUnderConstruction>(Key, UnknownVal());
500 ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
501 const CXXBindTemporaryExpr *BTE,
502 const LocationContext *LC) {
503 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
504 assert(State->contains<ObjectsUnderConstruction>(Key));
505 return State->remove<ObjectsUnderConstruction>(Key);
508 bool ExprEngine::isDestructorElided(ProgramStateRef State,
509 const CXXBindTemporaryExpr *BTE,
510 const LocationContext *LC) {
511 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
512 return State->contains<ObjectsUnderConstruction>(Key);
515 bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
516 const LocationContext *FromLC,
517 const LocationContext *ToLC) {
518 const LocationContext *LC = FromLC;
520 assert(LC && "ToLC must be a parent of FromLC!");
521 for (auto I : State->get<ObjectsUnderConstruction>())
522 if (I.first.getLocationContext() == LC)
525 LC = LC->getParent();
531 //===----------------------------------------------------------------------===//
532 // Top-level transfer function logic (Dispatcher).
533 //===----------------------------------------------------------------------===//
535 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
536 /// logic for handling assumptions on symbolic values.
537 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
538 SVal cond, bool assumption) {
539 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
543 ExprEngine::processRegionChanges(ProgramStateRef state,
544 const InvalidatedSymbols *invalidated,
545 ArrayRef<const MemRegion *> Explicits,
546 ArrayRef<const MemRegion *> Regions,
547 const LocationContext *LCtx,
548 const CallEvent *Call) {
549 return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
555 printObjectsUnderConstructionJson(raw_ostream &Out, ProgramStateRef State,
556 const char *NL, const LocationContext *LCtx,
557 unsigned int Space = 0, bool IsDot = false) {
559 LCtx->getAnalysisDeclContext()->getASTContext().getPrintingPolicy();
562 bool HasItem = false;
564 // Store the last key.
565 const ConstructedObjectKey *LastKey = nullptr;
566 for (const auto &I : State->get<ObjectsUnderConstruction>()) {
567 const ConstructedObjectKey &Key = I.first;
568 if (Key.getLocationContext() != LCtx)
579 for (const auto &I : State->get<ObjectsUnderConstruction>()) {
580 const ConstructedObjectKey &Key = I.first;
581 SVal Value = I.second;
582 if (Key.getLocationContext() != LCtx)
585 Indent(Out, Space, IsDot) << "{ ";
586 Key.printJson(Out, nullptr, PP);
587 Out << ", \"value\": \"" << Value << "\" }";
595 Indent(Out, --Space, IsDot) << ']'; // End of "location_context".
601 void ExprEngine::printJson(raw_ostream &Out, ProgramStateRef State,
602 const LocationContext *LCtx, const char *NL,
603 unsigned int Space, bool IsDot) const {
604 Indent(Out, Space, IsDot) << "\"constructing_objects\": ";
606 if (LCtx && !State->get<ObjectsUnderConstruction>().isEmpty()) {
609 LCtx->printJson(Out, NL, Space, IsDot, [&](const LocationContext *LC) {
610 printObjectsUnderConstructionJson(Out, State, NL, LC, Space, IsDot);
614 Indent(Out, Space, IsDot) << "]," << NL; // End of "constructing_objects".
616 Out << "null," << NL;
619 getCheckerManager().runCheckersForPrintStateJson(Out, State, NL, Space,
623 void ExprEngine::processEndWorklist() {
624 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
627 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
628 unsigned StmtIdx, NodeBuilderContext *Ctx) {
629 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
630 currStmtIdx = StmtIdx;
633 switch (E.getKind()) {
634 case CFGElement::Statement:
635 case CFGElement::Constructor:
636 case CFGElement::CXXRecordTypedCall:
637 ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
639 case CFGElement::Initializer:
640 ProcessInitializer(E.castAs<CFGInitializer>(), Pred);
642 case CFGElement::NewAllocator:
643 ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
646 case CFGElement::AutomaticObjectDtor:
647 case CFGElement::DeleteDtor:
648 case CFGElement::BaseDtor:
649 case CFGElement::MemberDtor:
650 case CFGElement::TemporaryDtor:
651 ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
653 case CFGElement::LoopExit:
654 ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
656 case CFGElement::LifetimeEnds:
657 case CFGElement::ScopeBegin:
658 case CFGElement::ScopeEnd:
663 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
665 const ExplodedNode *Pred,
666 const LocationContext *LC) {
667 // Are we never purging state values?
668 if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
671 // Is this the beginning of a basic block?
672 if (Pred->getLocation().getAs<BlockEntrance>())
675 // Is this on a non-expression?
679 // Run before processing a call.
680 if (CallEvent::isCallStmt(S))
683 // Is this an expression that is consumed by another expression? If so,
684 // postpone cleaning out the state.
685 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
686 return !PM.isConsumedExpr(cast<Expr>(S));
689 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
690 const Stmt *ReferenceStmt,
691 const LocationContext *LC,
692 const Stmt *DiagnosticStmt,
693 ProgramPoint::Kind K) {
694 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
695 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
696 && "PostStmt is not generally supported by the SymbolReaper yet");
697 assert(LC && "Must pass the current (or expiring) LocationContext");
699 if (!DiagnosticStmt) {
700 DiagnosticStmt = ReferenceStmt;
701 assert(DiagnosticStmt && "Required for clearing a LocationContext");
704 NumRemoveDeadBindings++;
705 ProgramStateRef CleanedState = Pred->getState();
707 // LC is the location context being destroyed, but SymbolReaper wants a
708 // location context that is still live. (If this is the top-level stack
709 // frame, this will be null.)
710 if (!ReferenceStmt) {
711 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
712 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
713 LC = LC->getParent();
716 const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
717 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
719 for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
720 if (SymbolRef Sym = I.second.getAsSymbol())
721 SymReaper.markLive(Sym);
722 if (const MemRegion *MR = I.second.getAsRegion())
723 SymReaper.markLive(MR);
726 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
728 // Create a state in which dead bindings are removed from the environment
729 // and the store. TODO: The function should just return new env and store,
731 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
733 // Process any special transfer function for dead symbols.
734 // A tag to track convenience transitions, which can be removed at cleanup.
735 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
736 // Call checkers with the non-cleaned state so that they could query the
737 // values of the soon to be dead symbols.
738 ExplodedNodeSet CheckedSet;
739 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
740 DiagnosticStmt, *this, K);
742 // For each node in CheckedSet, generate CleanedNodes that have the
743 // environment, the store, and the constraints cleaned up but have the
744 // user-supplied states as the predecessors.
745 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
746 for (const auto I : CheckedSet) {
747 ProgramStateRef CheckerState = I->getState();
749 // The constraint manager has not been cleaned up yet, so clean up now.
751 getConstraintManager().removeDeadBindings(CheckerState, SymReaper);
753 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
754 "Checkers are not allowed to modify the Environment as a part of "
755 "checkDeadSymbols processing.");
756 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
757 "Checkers are not allowed to modify the Store as a part of "
758 "checkDeadSymbols processing.");
760 // Create a state based on CleanedState with CheckerState GDM and
761 // generate a transition to that state.
762 ProgramStateRef CleanedCheckerSt =
763 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
764 Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K);
768 void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
769 // Reclaim any unnecessary nodes in the ExplodedGraph.
770 G.reclaimRecentlyAllocatedNodes();
772 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
773 currStmt->getBeginLoc(),
774 "Error evaluating statement");
776 // Remove dead bindings and symbols.
777 ExplodedNodeSet CleanedStates;
778 if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
779 Pred->getLocationContext())) {
780 removeDead(Pred, CleanedStates, currStmt,
781 Pred->getLocationContext());
783 CleanedStates.Add(Pred);
785 // Visit the statement.
787 for (const auto I : CleanedStates) {
788 ExplodedNodeSet DstI;
789 // Visit the statement.
790 Visit(currStmt, I, DstI);
794 // Enqueue the new nodes onto the work list.
795 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
798 void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) {
799 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
801 "Error evaluating end of the loop");
804 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
805 ProgramStateRef NewState = Pred->getState();
807 if(AMgr.options.ShouldUnrollLoops)
808 NewState = processLoopEnd(S, NewState);
810 LoopExit PP(S, Pred->getLocationContext());
811 Bldr.generateNode(PP, NewState, Pred);
812 // Enqueue the new nodes onto the work list.
813 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
816 void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit,
817 ExplodedNode *Pred) {
818 const CXXCtorInitializer *BMI = CFGInit.getInitializer();
819 const Expr *Init = BMI->getInit()->IgnoreImplicit();
820 const LocationContext *LC = Pred->getLocationContext();
822 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
823 BMI->getSourceLocation(),
824 "Error evaluating initializer");
826 // We don't clean up dead bindings here.
827 const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
828 const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
830 ProgramStateRef State = Pred->getState();
831 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
836 // Evaluate the initializer, if necessary
837 if (BMI->isAnyMemberInitializer()) {
838 // Constructors build the object directly in the field,
839 // but non-objects must be copied in from the initializer.
840 if (getObjectUnderConstruction(State, BMI, LC)) {
841 // The field was directly constructed, so there is no need to bind.
842 // But we still need to stop tracking the object under construction.
843 State = finishObjectConstruction(State, BMI, LC);
844 NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
845 PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
846 Bldr.generateNode(PS, State, Pred);
848 const ValueDecl *Field;
849 if (BMI->isIndirectMemberInitializer()) {
850 Field = BMI->getIndirectMember();
851 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
853 Field = BMI->getMember();
854 FieldLoc = State->getLValue(BMI->getMember(), thisVal);
858 if (Init->getType()->isArrayType()) {
859 // Handle arrays of trivial type. We can represent this with a
860 // primitive load/copy from the base array region.
861 const ArraySubscriptExpr *ASE;
862 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
863 Init = ASE->getBase()->IgnoreImplicit();
865 SVal LValue = State->getSVal(Init, stackFrame);
866 if (!Field->getType()->isReferenceType())
867 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
868 InitVal = State->getSVal(*LValueLoc);
870 // If we fail to get the value for some reason, use a symbolic value.
871 if (InitVal.isUnknownOrUndef()) {
872 SValBuilder &SVB = getSValBuilder();
873 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
875 currBldrCtx->blockCount());
878 InitVal = State->getSVal(BMI->getInit(), stackFrame);
881 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
882 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
885 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
887 // We already did all the work when visiting the CXXConstructExpr.
890 // Construct PostInitializer nodes whether the state changed or not,
891 // so that the diagnostics don't get confused.
892 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
894 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
895 for (const auto I : Tmp) {
896 ProgramStateRef State = I->getState();
897 Bldr.generateNode(PP, State, I);
900 // Enqueue the new nodes onto the work list.
901 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
904 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
905 ExplodedNode *Pred) {
907 switch (D.getKind()) {
908 case CFGElement::AutomaticObjectDtor:
909 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
911 case CFGElement::BaseDtor:
912 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
914 case CFGElement::MemberDtor:
915 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
917 case CFGElement::TemporaryDtor:
918 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
920 case CFGElement::DeleteDtor:
921 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
924 llvm_unreachable("Unexpected dtor kind.");
927 // Enqueue the new nodes onto the work list.
928 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
931 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
932 ExplodedNode *Pred) {
934 AnalysisManager &AMgr = getAnalysisManager();
935 AnalyzerOptions &Opts = AMgr.options;
936 // TODO: We're not evaluating allocators for all cases just yet as
937 // we're not handling the return value correctly, which causes false
938 // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
939 if (Opts.MayInlineCXXAllocator)
940 VisitCXXNewAllocatorCall(NE, Pred, Dst);
942 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
943 const LocationContext *LCtx = Pred->getLocationContext();
944 PostImplicitCall PP(NE->getOperatorNew(), NE->getBeginLoc(), LCtx);
945 Bldr.generateNode(PP, Pred->getState(), Pred);
947 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
950 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
952 ExplodedNodeSet &Dst) {
953 const VarDecl *varDecl = Dtor.getVarDecl();
954 QualType varType = varDecl->getType();
956 ProgramStateRef state = Pred->getState();
957 SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
958 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
960 if (varType->isReferenceType()) {
961 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
963 // FIXME: This should not happen. The language guarantees a presence
964 // of a valid initializer here, so the reference shall not be undefined.
965 // It seems that we're calling destructors over variables that
966 // were not initialized yet.
969 Region = ValueRegion->getBaseRegion();
970 varType = cast<TypedValueRegion>(Region)->getValueType();
973 // FIXME: We need to run the same destructor on every element of the array.
974 // This workaround will just run the first destructor (which will still
975 // invalidate the entire array).
976 EvalCallOptions CallOpts;
977 Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType,
978 CallOpts.IsArrayCtorOrDtor).getAsRegion();
980 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
981 Pred, Dst, CallOpts);
984 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
986 ExplodedNodeSet &Dst) {
987 ProgramStateRef State = Pred->getState();
988 const LocationContext *LCtx = Pred->getLocationContext();
989 const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
990 const Stmt *Arg = DE->getArgument();
991 QualType DTy = DE->getDestroyedType();
992 SVal ArgVal = State->getSVal(Arg, LCtx);
994 // If the argument to delete is known to be a null value,
995 // don't run destructor.
996 if (State->isNull(ArgVal).isConstrainedTrue()) {
997 QualType BTy = getContext().getBaseElementType(DTy);
998 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
999 const CXXDestructorDecl *Dtor = RD->getDestructor();
1001 PostImplicitCall PP(Dtor, DE->getBeginLoc(), LCtx);
1002 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1003 Bldr.generateNode(PP, Pred->getState(), Pred);
1007 EvalCallOptions CallOpts;
1008 const MemRegion *ArgR = ArgVal.getAsRegion();
1009 if (DE->isArrayForm()) {
1010 // FIXME: We need to run the same destructor on every element of the array.
1011 // This workaround will just run the first destructor (which will still
1012 // invalidate the entire array).
1013 CallOpts.IsArrayCtorOrDtor = true;
1014 // Yes, it may even be a multi-dimensional array.
1015 while (const auto *AT = getContext().getAsArrayType(DTy))
1016 DTy = AT->getElementType();
1018 ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy);
1021 VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
1024 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
1025 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1026 const LocationContext *LCtx = Pred->getLocationContext();
1028 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
1029 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
1030 LCtx->getStackFrame());
1031 SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
1033 // Create the base object region.
1034 const CXXBaseSpecifier *Base = D.getBaseSpecifier();
1035 QualType BaseTy = Base->getType();
1036 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
1039 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
1040 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {});
1043 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
1044 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1045 const FieldDecl *Member = D.getFieldDecl();
1046 QualType T = Member->getType();
1047 ProgramStateRef State = Pred->getState();
1048 const LocationContext *LCtx = Pred->getLocationContext();
1050 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
1051 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
1052 LCtx->getStackFrame());
1054 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
1056 // FIXME: We need to run the same destructor on every element of the array.
1057 // This workaround will just run the first destructor (which will still
1058 // invalidate the entire array).
1059 EvalCallOptions CallOpts;
1060 FieldVal = makeZeroElementRegion(State, FieldVal, T,
1061 CallOpts.IsArrayCtorOrDtor);
1063 VisitCXXDestructor(T, FieldVal.castAs<loc::MemRegionVal>().getRegion(),
1064 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts);
1067 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
1069 ExplodedNodeSet &Dst) {
1070 const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr();
1071 ProgramStateRef State = Pred->getState();
1072 const LocationContext *LC = Pred->getLocationContext();
1073 const MemRegion *MR = nullptr;
1075 if (Optional<SVal> V =
1076 getObjectUnderConstruction(State, D.getBindTemporaryExpr(),
1077 Pred->getLocationContext())) {
1078 // FIXME: Currently we insert temporary destructors for default parameters,
1079 // but we don't insert the constructors, so the entry in
1080 // ObjectsUnderConstruction may be missing.
1081 State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
1082 Pred->getLocationContext());
1083 MR = V->getAsRegion();
1086 // If copy elision has occurred, and the constructor corresponding to the
1087 // destructor was elided, we need to skip the destructor as well.
1088 if (isDestructorElided(State, BTE, LC)) {
1089 State = cleanupElidedDestructor(State, BTE, LC);
1090 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1091 PostImplicitCall PP(D.getDestructorDecl(getContext()),
1092 D.getBindTemporaryExpr()->getBeginLoc(),
1093 Pred->getLocationContext());
1094 Bldr.generateNode(PP, State, Pred);
1098 ExplodedNodeSet CleanDtorState;
1099 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
1100 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
1102 QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType();
1103 // FIXME: Currently CleanDtorState can be empty here due to temporaries being
1104 // bound to default parameters.
1105 assert(CleanDtorState.size() <= 1);
1106 ExplodedNode *CleanPred =
1107 CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
1109 EvalCallOptions CallOpts;
1110 CallOpts.IsTemporaryCtorOrDtor = true;
1112 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
1114 // If we have no MR, we still need to unwrap the array to avoid destroying
1115 // the whole array at once. Regardless, we'd eventually need to model array
1116 // destructors properly, element-by-element.
1117 while (const ArrayType *AT = getContext().getAsArrayType(T)) {
1118 T = AT->getElementType();
1119 CallOpts.IsArrayCtorOrDtor = true;
1122 // We'd eventually need to makeZeroElementRegion() trick here,
1123 // but for now we don't have the respective construction contexts,
1124 // so MR would always be null in this case. Do nothing for now.
1126 VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(),
1127 /*IsBase=*/false, CleanPred, Dst, CallOpts);
1130 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
1131 NodeBuilderContext &BldCtx,
1133 ExplodedNodeSet &Dst,
1134 const CFGBlock *DstT,
1135 const CFGBlock *DstF) {
1136 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
1137 ProgramStateRef State = Pred->getState();
1138 const LocationContext *LC = Pred->getLocationContext();
1139 if (getObjectUnderConstruction(State, BTE, LC)) {
1140 TempDtorBuilder.markInfeasible(false);
1141 TempDtorBuilder.generateNode(State, true, Pred);
1143 TempDtorBuilder.markInfeasible(true);
1144 TempDtorBuilder.generateNode(State, false, Pred);
1148 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
1149 ExplodedNodeSet &PreVisit,
1150 ExplodedNodeSet &Dst) {
1151 // This is a fallback solution in case we didn't have a construction
1152 // context when we were constructing the temporary. Otherwise the map should
1153 // have been populated there.
1154 if (!getAnalysisManager().options.ShouldIncludeTemporaryDtorsInCFG) {
1155 // In case we don't have temporary destructors in the CFG, do not mark
1156 // the initialization - we would otherwise never clean it up.
1160 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
1161 for (ExplodedNode *Node : PreVisit) {
1162 ProgramStateRef State = Node->getState();
1163 const LocationContext *LC = Node->getLocationContext();
1164 if (!getObjectUnderConstruction(State, BTE, LC)) {
1165 // FIXME: Currently the state might also already contain the marker due to
1166 // incorrect handling of temporaries bound to default parameters; for
1167 // those, we currently skip the CXXBindTemporaryExpr but rely on adding
1168 // temporary destructor nodes.
1169 State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
1171 StmtBldr.generateNode(BTE, Node, State);
1175 ProgramStateRef ExprEngine::escapeValue(ProgramStateRef State, SVal V,
1176 PointerEscapeKind K) const {
1177 class CollectReachableSymbolsCallback final : public SymbolVisitor {
1178 InvalidatedSymbols Symbols;
1181 explicit CollectReachableSymbolsCallback(ProgramStateRef) {}
1183 const InvalidatedSymbols &getSymbols() const { return Symbols; }
1185 bool VisitSymbol(SymbolRef Sym) override {
1186 Symbols.insert(Sym);
1191 const CollectReachableSymbolsCallback &Scanner =
1192 State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
1193 return getCheckerManager().runCheckersForPointerEscape(
1194 State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
1197 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
1198 ExplodedNodeSet &DstTop) {
1199 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1200 S->getBeginLoc(), "Error evaluating statement");
1201 ExplodedNodeSet Dst;
1202 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
1204 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
1206 switch (S->getStmtClass()) {
1207 // C++, OpenMP and ARC stuff we don't support yet.
1208 case Expr::ObjCIndirectCopyRestoreExprClass:
1209 case Stmt::CXXDependentScopeMemberExprClass:
1210 case Stmt::CXXInheritedCtorInitExprClass:
1211 case Stmt::CXXTryStmtClass:
1212 case Stmt::CXXTypeidExprClass:
1213 case Stmt::CXXUuidofExprClass:
1214 case Stmt::CXXFoldExprClass:
1215 case Stmt::MSPropertyRefExprClass:
1216 case Stmt::MSPropertySubscriptExprClass:
1217 case Stmt::CXXUnresolvedConstructExprClass:
1218 case Stmt::DependentScopeDeclRefExprClass:
1219 case Stmt::ArrayTypeTraitExprClass:
1220 case Stmt::ExpressionTraitExprClass:
1221 case Stmt::UnresolvedLookupExprClass:
1222 case Stmt::UnresolvedMemberExprClass:
1223 case Stmt::TypoExprClass:
1224 case Stmt::CXXNoexceptExprClass:
1225 case Stmt::PackExpansionExprClass:
1226 case Stmt::SubstNonTypeTemplateParmPackExprClass:
1227 case Stmt::FunctionParmPackExprClass:
1228 case Stmt::CoroutineBodyStmtClass:
1229 case Stmt::CoawaitExprClass:
1230 case Stmt::DependentCoawaitExprClass:
1231 case Stmt::CoreturnStmtClass:
1232 case Stmt::CoyieldExprClass:
1233 case Stmt::SEHTryStmtClass:
1234 case Stmt::SEHExceptStmtClass:
1235 case Stmt::SEHLeaveStmtClass:
1236 case Stmt::SEHFinallyStmtClass:
1237 case Stmt::OMPParallelDirectiveClass:
1238 case Stmt::OMPSimdDirectiveClass:
1239 case Stmt::OMPForDirectiveClass:
1240 case Stmt::OMPForSimdDirectiveClass:
1241 case Stmt::OMPSectionsDirectiveClass:
1242 case Stmt::OMPSectionDirectiveClass:
1243 case Stmt::OMPSingleDirectiveClass:
1244 case Stmt::OMPMasterDirectiveClass:
1245 case Stmt::OMPCriticalDirectiveClass:
1246 case Stmt::OMPParallelForDirectiveClass:
1247 case Stmt::OMPParallelForSimdDirectiveClass:
1248 case Stmt::OMPParallelSectionsDirectiveClass:
1249 case Stmt::OMPTaskDirectiveClass:
1250 case Stmt::OMPTaskyieldDirectiveClass:
1251 case Stmt::OMPBarrierDirectiveClass:
1252 case Stmt::OMPTaskwaitDirectiveClass:
1253 case Stmt::OMPTaskgroupDirectiveClass:
1254 case Stmt::OMPFlushDirectiveClass:
1255 case Stmt::OMPOrderedDirectiveClass:
1256 case Stmt::OMPAtomicDirectiveClass:
1257 case Stmt::OMPTargetDirectiveClass:
1258 case Stmt::OMPTargetDataDirectiveClass:
1259 case Stmt::OMPTargetEnterDataDirectiveClass:
1260 case Stmt::OMPTargetExitDataDirectiveClass:
1261 case Stmt::OMPTargetParallelDirectiveClass:
1262 case Stmt::OMPTargetParallelForDirectiveClass:
1263 case Stmt::OMPTargetUpdateDirectiveClass:
1264 case Stmt::OMPTeamsDirectiveClass:
1265 case Stmt::OMPCancellationPointDirectiveClass:
1266 case Stmt::OMPCancelDirectiveClass:
1267 case Stmt::OMPTaskLoopDirectiveClass:
1268 case Stmt::OMPTaskLoopSimdDirectiveClass:
1269 case Stmt::OMPDistributeDirectiveClass:
1270 case Stmt::OMPDistributeParallelForDirectiveClass:
1271 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1272 case Stmt::OMPDistributeSimdDirectiveClass:
1273 case Stmt::OMPTargetParallelForSimdDirectiveClass:
1274 case Stmt::OMPTargetSimdDirectiveClass:
1275 case Stmt::OMPTeamsDistributeDirectiveClass:
1276 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1277 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1278 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1279 case Stmt::OMPTargetTeamsDirectiveClass:
1280 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1281 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1282 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1283 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1284 case Stmt::CapturedStmtClass: {
1285 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1286 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1290 case Stmt::ParenExprClass:
1291 llvm_unreachable("ParenExprs already handled.");
1292 case Stmt::GenericSelectionExprClass:
1293 llvm_unreachable("GenericSelectionExprs already handled.");
1294 // Cases that should never be evaluated simply because they shouldn't
1295 // appear in the CFG.
1296 case Stmt::BreakStmtClass:
1297 case Stmt::CaseStmtClass:
1298 case Stmt::CompoundStmtClass:
1299 case Stmt::ContinueStmtClass:
1300 case Stmt::CXXForRangeStmtClass:
1301 case Stmt::DefaultStmtClass:
1302 case Stmt::DoStmtClass:
1303 case Stmt::ForStmtClass:
1304 case Stmt::GotoStmtClass:
1305 case Stmt::IfStmtClass:
1306 case Stmt::IndirectGotoStmtClass:
1307 case Stmt::LabelStmtClass:
1308 case Stmt::NoStmtClass:
1309 case Stmt::NullStmtClass:
1310 case Stmt::SwitchStmtClass:
1311 case Stmt::WhileStmtClass:
1312 case Expr::MSDependentExistsStmtClass:
1313 llvm_unreachable("Stmt should not be in analyzer evaluation loop");
1315 case Stmt::ObjCSubscriptRefExprClass:
1316 case Stmt::ObjCPropertyRefExprClass:
1317 llvm_unreachable("These are handled by PseudoObjectExpr");
1319 case Stmt::GNUNullExprClass: {
1320 // GNU __null is a pointer-width integer, not an actual pointer.
1321 ProgramStateRef state = Pred->getState();
1322 state = state->BindExpr(S, Pred->getLocationContext(),
1323 svalBuilder.makeIntValWithPtrWidth(0, false));
1324 Bldr.generateNode(S, Pred, state);
1328 case Stmt::ObjCAtSynchronizedStmtClass:
1329 Bldr.takeNodes(Pred);
1330 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
1334 case Expr::ConstantExprClass:
1335 case Stmt::ExprWithCleanupsClass:
1336 // Handled due to fully linearised CFG.
1339 case Stmt::CXXBindTemporaryExprClass: {
1340 Bldr.takeNodes(Pred);
1341 ExplodedNodeSet PreVisit;
1342 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1343 ExplodedNodeSet Next;
1344 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
1345 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
1350 // Cases not handled yet; but will handle some day.
1351 case Stmt::DesignatedInitExprClass:
1352 case Stmt::DesignatedInitUpdateExprClass:
1353 case Stmt::ArrayInitLoopExprClass:
1354 case Stmt::ArrayInitIndexExprClass:
1355 case Stmt::ExtVectorElementExprClass:
1356 case Stmt::ImaginaryLiteralClass:
1357 case Stmt::ObjCAtCatchStmtClass:
1358 case Stmt::ObjCAtFinallyStmtClass:
1359 case Stmt::ObjCAtTryStmtClass:
1360 case Stmt::ObjCAutoreleasePoolStmtClass:
1361 case Stmt::ObjCEncodeExprClass:
1362 case Stmt::ObjCIsaExprClass:
1363 case Stmt::ObjCProtocolExprClass:
1364 case Stmt::ObjCSelectorExprClass:
1365 case Stmt::ParenListExprClass:
1366 case Stmt::ShuffleVectorExprClass:
1367 case Stmt::ConvertVectorExprClass:
1368 case Stmt::VAArgExprClass:
1369 case Stmt::CUDAKernelCallExprClass:
1370 case Stmt::OpaqueValueExprClass:
1371 case Stmt::AsTypeExprClass:
1374 // Cases we intentionally don't evaluate, since they don't need
1375 // to be explicitly evaluated.
1376 case Stmt::PredefinedExprClass:
1377 case Stmt::AddrLabelExprClass:
1378 case Stmt::AttributedStmtClass:
1379 case Stmt::IntegerLiteralClass:
1380 case Stmt::FixedPointLiteralClass:
1381 case Stmt::CharacterLiteralClass:
1382 case Stmt::ImplicitValueInitExprClass:
1383 case Stmt::CXXScalarValueInitExprClass:
1384 case Stmt::CXXBoolLiteralExprClass:
1385 case Stmt::ObjCBoolLiteralExprClass:
1386 case Stmt::ObjCAvailabilityCheckExprClass:
1387 case Stmt::FloatingLiteralClass:
1388 case Stmt::NoInitExprClass:
1389 case Stmt::SizeOfPackExprClass:
1390 case Stmt::StringLiteralClass:
1391 case Stmt::SourceLocExprClass:
1392 case Stmt::ObjCStringLiteralClass:
1393 case Stmt::CXXPseudoDestructorExprClass:
1394 case Stmt::SubstNonTypeTemplateParmExprClass:
1395 case Stmt::CXXNullPtrLiteralExprClass:
1396 case Stmt::OMPArraySectionExprClass:
1397 case Stmt::TypeTraitExprClass: {
1398 Bldr.takeNodes(Pred);
1399 ExplodedNodeSet preVisit;
1400 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1401 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
1406 case Stmt::CXXDefaultArgExprClass:
1407 case Stmt::CXXDefaultInitExprClass: {
1408 Bldr.takeNodes(Pred);
1409 ExplodedNodeSet PreVisit;
1410 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1412 ExplodedNodeSet Tmp;
1413 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
1416 if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
1417 ArgE = DefE->getExpr();
1418 else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
1419 ArgE = DefE->getExpr();
1421 llvm_unreachable("unknown constant wrapper kind");
1423 bool IsTemporary = false;
1424 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
1425 ArgE = MTE->GetTemporaryExpr();
1429 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
1431 ConstantVal = UnknownVal();
1433 const LocationContext *LCtx = Pred->getLocationContext();
1434 for (const auto I : PreVisit) {
1435 ProgramStateRef State = I->getState();
1436 State = State->BindExpr(S, LCtx, *ConstantVal);
1438 State = createTemporaryRegionIfNeeded(State, LCtx,
1441 Bldr2.generateNode(S, I, State);
1444 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1449 // Cases we evaluate as opaque expressions, conjuring a symbol.
1450 case Stmt::CXXStdInitializerListExprClass:
1451 case Expr::ObjCArrayLiteralClass:
1452 case Expr::ObjCDictionaryLiteralClass:
1453 case Expr::ObjCBoxedExprClass: {
1454 Bldr.takeNodes(Pred);
1456 ExplodedNodeSet preVisit;
1457 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1459 ExplodedNodeSet Tmp;
1460 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
1462 const auto *Ex = cast<Expr>(S);
1463 QualType resultType = Ex->getType();
1465 for (const auto N : preVisit) {
1466 const LocationContext *LCtx = N->getLocationContext();
1467 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1469 currBldrCtx->blockCount());
1470 ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
1472 // Escape pointers passed into the list, unless it's an ObjC boxed
1473 // expression which is not a boxable C structure.
1474 if (!(isa<ObjCBoxedExpr>(Ex) &&
1475 !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
1476 ->getType()->isRecordType()))
1477 for (auto Child : Ex->children()) {
1479 SVal Val = State->getSVal(Child, LCtx);
1480 State = escapeValue(State, Val, PSK_EscapeOther);
1483 Bldr2.generateNode(S, N, State);
1486 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1491 case Stmt::ArraySubscriptExprClass:
1492 Bldr.takeNodes(Pred);
1493 VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1497 case Stmt::GCCAsmStmtClass:
1498 Bldr.takeNodes(Pred);
1499 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1503 case Stmt::MSAsmStmtClass:
1504 Bldr.takeNodes(Pred);
1505 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1509 case Stmt::BlockExprClass:
1510 Bldr.takeNodes(Pred);
1511 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1515 case Stmt::LambdaExprClass:
1516 if (AMgr.options.ShouldInlineLambdas) {
1517 Bldr.takeNodes(Pred);
1518 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1521 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1522 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1526 case Stmt::BinaryOperatorClass: {
1527 const auto *B = cast<BinaryOperator>(S);
1528 if (B->isLogicalOp()) {
1529 Bldr.takeNodes(Pred);
1530 VisitLogicalExpr(B, Pred, Dst);
1534 else if (B->getOpcode() == BO_Comma) {
1535 ProgramStateRef state = Pred->getState();
1536 Bldr.generateNode(B, Pred,
1537 state->BindExpr(B, Pred->getLocationContext(),
1538 state->getSVal(B->getRHS(),
1539 Pred->getLocationContext())));
1543 Bldr.takeNodes(Pred);
1545 if (AMgr.options.ShouldEagerlyAssume &&
1546 (B->isRelationalOp() || B->isEqualityOp())) {
1547 ExplodedNodeSet Tmp;
1548 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1549 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1552 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1558 case Stmt::CXXOperatorCallExprClass: {
1559 const auto *OCE = cast<CXXOperatorCallExpr>(S);
1561 // For instance method operators, make sure the 'this' argument has a
1563 const Decl *Callee = OCE->getCalleeDecl();
1564 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1565 if (MD->isInstance()) {
1566 ProgramStateRef State = Pred->getState();
1567 const LocationContext *LCtx = Pred->getLocationContext();
1568 ProgramStateRef NewState =
1569 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1570 if (NewState != State) {
1571 Pred = Bldr.generateNode(OCE, Pred, NewState, /*tag=*/nullptr,
1572 ProgramPoint::PreStmtKind);
1573 // Did we cache out?
1583 case Stmt::CallExprClass:
1584 case Stmt::CXXMemberCallExprClass:
1585 case Stmt::UserDefinedLiteralClass:
1586 Bldr.takeNodes(Pred);
1587 VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1591 case Stmt::CXXCatchStmtClass:
1592 Bldr.takeNodes(Pred);
1593 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1597 case Stmt::CXXTemporaryObjectExprClass:
1598 case Stmt::CXXConstructExprClass:
1599 Bldr.takeNodes(Pred);
1600 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1604 case Stmt::CXXNewExprClass: {
1605 Bldr.takeNodes(Pred);
1607 ExplodedNodeSet PreVisit;
1608 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1610 ExplodedNodeSet PostVisit;
1611 for (const auto i : PreVisit)
1612 VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
1614 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1619 case Stmt::CXXDeleteExprClass: {
1620 Bldr.takeNodes(Pred);
1621 ExplodedNodeSet PreVisit;
1622 const auto *CDE = cast<CXXDeleteExpr>(S);
1623 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1625 for (const auto i : PreVisit)
1626 VisitCXXDeleteExpr(CDE, i, Dst);
1631 // FIXME: ChooseExpr is really a constant. We need to fix
1632 // the CFG do not model them as explicit control-flow.
1634 case Stmt::ChooseExprClass: { // __builtin_choose_expr
1635 Bldr.takeNodes(Pred);
1636 const auto *C = cast<ChooseExpr>(S);
1637 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1642 case Stmt::CompoundAssignOperatorClass:
1643 Bldr.takeNodes(Pred);
1644 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1648 case Stmt::CompoundLiteralExprClass:
1649 Bldr.takeNodes(Pred);
1650 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1654 case Stmt::BinaryConditionalOperatorClass:
1655 case Stmt::ConditionalOperatorClass: { // '?' operator
1656 Bldr.takeNodes(Pred);
1657 const auto *C = cast<AbstractConditionalOperator>(S);
1658 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1663 case Stmt::CXXThisExprClass:
1664 Bldr.takeNodes(Pred);
1665 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1669 case Stmt::DeclRefExprClass: {
1670 Bldr.takeNodes(Pred);
1671 const auto *DE = cast<DeclRefExpr>(S);
1672 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1677 case Stmt::DeclStmtClass:
1678 Bldr.takeNodes(Pred);
1679 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1683 case Stmt::ImplicitCastExprClass:
1684 case Stmt::CStyleCastExprClass:
1685 case Stmt::CXXStaticCastExprClass:
1686 case Stmt::CXXDynamicCastExprClass:
1687 case Stmt::CXXReinterpretCastExprClass:
1688 case Stmt::CXXConstCastExprClass:
1689 case Stmt::CXXFunctionalCastExprClass:
1690 case Stmt::BuiltinBitCastExprClass:
1691 case Stmt::ObjCBridgedCastExprClass: {
1692 Bldr.takeNodes(Pred);
1693 const auto *C = cast<CastExpr>(S);
1694 ExplodedNodeSet dstExpr;
1695 VisitCast(C, C->getSubExpr(), Pred, dstExpr);
1697 // Handle the postvisit checks.
1698 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1703 case Expr::MaterializeTemporaryExprClass: {
1704 Bldr.takeNodes(Pred);
1705 const auto *MTE = cast<MaterializeTemporaryExpr>(S);
1706 ExplodedNodeSet dstPrevisit;
1707 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
1708 ExplodedNodeSet dstExpr;
1709 for (const auto i : dstPrevisit)
1710 CreateCXXTemporaryObject(MTE, i, dstExpr);
1711 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
1716 case Stmt::InitListExprClass:
1717 Bldr.takeNodes(Pred);
1718 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1722 case Stmt::MemberExprClass:
1723 Bldr.takeNodes(Pred);
1724 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1728 case Stmt::AtomicExprClass:
1729 Bldr.takeNodes(Pred);
1730 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
1734 case Stmt::ObjCIvarRefExprClass:
1735 Bldr.takeNodes(Pred);
1736 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1740 case Stmt::ObjCForCollectionStmtClass:
1741 Bldr.takeNodes(Pred);
1742 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1746 case Stmt::ObjCMessageExprClass:
1747 Bldr.takeNodes(Pred);
1748 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1752 case Stmt::ObjCAtThrowStmtClass:
1753 case Stmt::CXXThrowExprClass:
1754 // FIXME: This is not complete. We basically treat @throw as
1756 Bldr.generateSink(S, Pred, Pred->getState());
1759 case Stmt::ReturnStmtClass:
1760 Bldr.takeNodes(Pred);
1761 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1765 case Stmt::OffsetOfExprClass: {
1766 Bldr.takeNodes(Pred);
1767 ExplodedNodeSet PreVisit;
1768 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1770 ExplodedNodeSet PostVisit;
1771 for (const auto Node : PreVisit)
1772 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
1774 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1779 case Stmt::UnaryExprOrTypeTraitExprClass:
1780 Bldr.takeNodes(Pred);
1781 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1786 case Stmt::StmtExprClass: {
1787 const auto *SE = cast<StmtExpr>(S);
1789 if (SE->getSubStmt()->body_empty()) {
1790 // Empty statement expression.
1791 assert(SE->getType() == getContext().VoidTy
1792 && "Empty statement expression must have void type.");
1796 if (const auto *LastExpr =
1797 dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1798 ProgramStateRef state = Pred->getState();
1799 Bldr.generateNode(SE, Pred,
1800 state->BindExpr(SE, Pred->getLocationContext(),
1801 state->getSVal(LastExpr,
1802 Pred->getLocationContext())));
1807 case Stmt::UnaryOperatorClass: {
1808 Bldr.takeNodes(Pred);
1809 const auto *U = cast<UnaryOperator>(S);
1810 if (AMgr.options.ShouldEagerlyAssume && (U->getOpcode() == UO_LNot)) {
1811 ExplodedNodeSet Tmp;
1812 VisitUnaryOperator(U, Pred, Tmp);
1813 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1816 VisitUnaryOperator(U, Pred, Dst);
1821 case Stmt::PseudoObjectExprClass: {
1822 Bldr.takeNodes(Pred);
1823 ProgramStateRef state = Pred->getState();
1824 const auto *PE = cast<PseudoObjectExpr>(S);
1825 if (const Expr *Result = PE->getResultExpr()) {
1826 SVal V = state->getSVal(Result, Pred->getLocationContext());
1827 Bldr.generateNode(S, Pred,
1828 state->BindExpr(S, Pred->getLocationContext(), V));
1831 Bldr.generateNode(S, Pred,
1832 state->BindExpr(S, Pred->getLocationContext(),
1841 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1842 const LocationContext *CalleeLC) {
1843 const StackFrameContext *CalleeSF = CalleeLC->getStackFrame();
1844 const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame();
1845 assert(CalleeSF && CallerSF);
1846 ExplodedNode *BeforeProcessingCall = nullptr;
1847 const Stmt *CE = CalleeSF->getCallSite();
1849 // Find the first node before we started processing the call expression.
1851 ProgramPoint L = N->getLocation();
1852 BeforeProcessingCall = N;
1853 N = N->pred_empty() ? nullptr : *(N->pred_begin());
1855 // Skip the nodes corresponding to the inlined code.
1856 if (L.getStackFrame() != CallerSF)
1858 // We reached the caller. Find the node right before we started
1859 // processing the call.
1860 if (L.isPurgeKind())
1862 if (L.getAs<PreImplicitCall>())
1864 if (L.getAs<CallEnter>())
1866 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1867 if (SP->getStmt() == CE)
1872 if (!BeforeProcessingCall)
1875 // TODO: Clean up the unneeded nodes.
1877 // Build an Epsilon node from which we will restart the analyzes.
1878 // Note that CE is permitted to be NULL!
1879 ProgramPoint NewNodeLoc =
1880 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1881 // Add the special flag to GDM to signal retrying with no inlining.
1882 // Note, changing the state ensures that we are not going to cache out.
1883 ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1885 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1887 // Make the new node a successor of BeforeProcessingCall.
1889 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1890 // We cached out at this point. Caching out is common due to us backtracking
1891 // from the inlined function, which might spawn several paths.
1895 NewNode->addPredecessor(BeforeProcessingCall, G);
1897 // Add the new node to the work list.
1898 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1899 CalleeSF->getIndex());
1900 NumTimesRetriedWithoutInlining++;
1904 /// Block entrance. (Update counters).
1905 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1906 NodeBuilderWithSinks &nodeBuilder,
1907 ExplodedNode *Pred) {
1908 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1909 // If we reach a loop which has a known bound (and meets
1910 // other constraints) then consider completely unrolling it.
1911 if(AMgr.options.ShouldUnrollLoops) {
1912 unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
1913 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt();
1915 ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
1916 Pred, maxBlockVisitOnPath);
1917 if (NewState != Pred->getState()) {
1918 ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
1924 // Is we are inside an unrolled loop then no need the check the counters.
1925 if(isUnrolledState(Pred->getState()))
1929 // If this block is terminated by a loop and it has already been visited the
1930 // maximum number of times, widen the loop.
1931 unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1932 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1933 AMgr.options.ShouldWidenLoops) {
1934 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt();
1936 (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1939 const LocationContext *LCtx = Pred->getLocationContext();
1940 ProgramStateRef WidenedState =
1941 getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1942 nodeBuilder.generateNode(WidenedState, Pred);
1946 // FIXME: Refactor this into a checker.
1947 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1948 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1949 const ExplodedNode *Sink =
1950 nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1952 // Check if we stopped at the top level function or not.
1953 // Root node should have the location context of the top most function.
1954 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1955 const LocationContext *CalleeSF = CalleeLC->getStackFrame();
1956 const LocationContext *RootLC =
1957 (*G.roots_begin())->getLocation().getLocationContext();
1958 if (RootLC->getStackFrame() != CalleeSF) {
1959 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1961 // Re-run the call evaluation without inlining it, by storing the
1962 // no-inlining policy in the state and enqueuing the new work item on
1963 // the list. Replay should almost never fail. Use the stats to catch it
1965 if ((!AMgr.options.NoRetryExhausted &&
1966 replayWithoutInlining(Pred, CalleeLC)))
1968 NumMaxBlockCountReachedInInlined++;
1970 NumMaxBlockCountReached++;
1972 // Make sink nodes as exhausted(for stats) only if retry failed.
1973 Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1977 //===----------------------------------------------------------------------===//
1978 // Branch processing.
1979 //===----------------------------------------------------------------------===//
1981 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1982 /// to try to recover some path-sensitivity for casts of symbolic
1983 /// integers that promote their values (which are currently not tracked well).
1984 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1985 // cast(s) did was sign-extend the original value.
1986 static SVal RecoverCastedSymbol(ProgramStateRef state,
1987 const Stmt *Condition,
1988 const LocationContext *LCtx,
1991 const auto *Ex = dyn_cast<Expr>(Condition);
1993 return UnknownVal();
1996 bool bitsInit = false;
1998 while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
1999 QualType T = CE->getType();
2001 if (!T->isIntegralOrEnumerationType())
2002 return UnknownVal();
2004 uint64_t newBits = Ctx.getTypeSize(T);
2005 if (!bitsInit || newBits < bits) {
2010 Ex = CE->getSubExpr();
2013 // We reached a non-cast. Is it a symbolic value?
2014 QualType T = Ex->getType();
2016 if (!bitsInit || !T->isIntegralOrEnumerationType() ||
2017 Ctx.getTypeSize(T) > bits)
2018 return UnknownVal();
2020 return state->getSVal(Ex, LCtx);
2024 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
2026 const auto *BO = dyn_cast<BinaryOperator>(Condition);
2027 if (!BO || !BO->isLogicalOp()) {
2030 Condition = BO->getRHS()->IgnoreParens();
2036 // Returns the condition the branch at the end of 'B' depends on and whose value
2037 // has been evaluated within 'B'.
2038 // In most cases, the terminator condition of 'B' will be evaluated fully in
2039 // the last statement of 'B'; in those cases, the resolved condition is the
2040 // given 'Condition'.
2041 // If the condition of the branch is a logical binary operator tree, the CFG is
2042 // optimized: in that case, we know that the expression formed by all but the
2043 // rightmost leaf of the logical binary operator tree must be true, and thus
2044 // the branch condition is at this point equivalent to the truth value of that
2045 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
2046 // expression in its final statement. As the full condition in that case was
2047 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
2048 // expression to evaluate the truth value of the condition in the current state
2050 static const Stmt *ResolveCondition(const Stmt *Condition,
2051 const CFGBlock *B) {
2052 if (const auto *Ex = dyn_cast<Expr>(Condition))
2053 Condition = Ex->IgnoreParens();
2055 const auto *BO = dyn_cast<BinaryOperator>(Condition);
2056 if (!BO || !BO->isLogicalOp())
2059 assert(B->getTerminator().isStmtBranch() &&
2060 "Other kinds of branches are handled separately!");
2062 // For logical operations, we still have the case where some branches
2063 // use the traditional "merge" approach and others sink the branch
2064 // directly into the basic blocks representing the logical operation.
2065 // We need to distinguish between those two cases here.
2067 // The invariants are still shifting, but it is possible that the
2068 // last element in a CFGBlock is not a CFGStmt. Look for the last
2069 // CFGStmt as the value of the condition.
2070 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
2071 for (; I != E; ++I) {
2072 CFGElement Elem = *I;
2073 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
2076 const Stmt *LastStmt = CS->getStmt();
2077 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
2080 llvm_unreachable("could not resolve condition");
2083 void ExprEngine::processBranch(const Stmt *Condition,
2084 NodeBuilderContext& BldCtx,
2086 ExplodedNodeSet &Dst,
2087 const CFGBlock *DstT,
2088 const CFGBlock *DstF) {
2089 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
2090 "CXXBindTemporaryExprs are handled by processBindTemporary.");
2091 const LocationContext *LCtx = Pred->getLocationContext();
2092 PrettyStackTraceLocationContext StackCrashInfo(LCtx);
2093 currBldrCtx = &BldCtx;
2095 // Check for NULL conditions; e.g. "for(;;)"
2097 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
2098 NullCondBldr.markInfeasible(false);
2099 NullCondBldr.generateNode(Pred->getState(), true, Pred);
2103 if (const auto *Ex = dyn_cast<Expr>(Condition))
2104 Condition = Ex->IgnoreParens();
2106 Condition = ResolveCondition(Condition, BldCtx.getBlock());
2107 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
2108 Condition->getBeginLoc(),
2109 "Error evaluating branch");
2111 ExplodedNodeSet CheckersOutSet;
2112 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
2114 // We generated only sinks.
2115 if (CheckersOutSet.empty())
2118 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
2119 for (const auto PredI : CheckersOutSet) {
2120 if (PredI->isSink())
2123 ProgramStateRef PrevState = PredI->getState();
2124 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
2126 if (X.isUnknownOrUndef()) {
2127 // Give it a chance to recover from unknown.
2128 if (const auto *Ex = dyn_cast<Expr>(Condition)) {
2129 if (Ex->getType()->isIntegralOrEnumerationType()) {
2130 // Try to recover some path-sensitivity. Right now casts of symbolic
2131 // integers that promote their values are currently not tracked well.
2132 // If 'Condition' is such an expression, try and recover the
2133 // underlying value and use that instead.
2134 SVal recovered = RecoverCastedSymbol(PrevState, Condition,
2135 PredI->getLocationContext(),
2138 if (!recovered.isUnknown()) {
2145 // If the condition is still unknown, give up.
2146 if (X.isUnknownOrUndef()) {
2147 builder.generateNode(PrevState, true, PredI);
2148 builder.generateNode(PrevState, false, PredI);
2152 DefinedSVal V = X.castAs<DefinedSVal>();
2154 ProgramStateRef StTrue, StFalse;
2155 std::tie(StTrue, StFalse) = PrevState->assume(V);
2157 // Process the true branch.
2158 if (builder.isFeasible(true)) {
2160 builder.generateNode(StTrue, true, PredI);
2162 builder.markInfeasible(true);
2165 // Process the false branch.
2166 if (builder.isFeasible(false)) {
2168 builder.generateNode(StFalse, false, PredI);
2170 builder.markInfeasible(false);
2173 currBldrCtx = nullptr;
2176 /// The GDM component containing the set of global variables which have been
2177 /// previously initialized with explicit initializers.
2178 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
2179 llvm::ImmutableSet<const VarDecl *>)
2181 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
2182 NodeBuilderContext &BuilderCtx,
2184 ExplodedNodeSet &Dst,
2185 const CFGBlock *DstT,
2186 const CFGBlock *DstF) {
2187 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
2188 currBldrCtx = &BuilderCtx;
2190 const auto *VD = cast<VarDecl>(DS->getSingleDecl());
2191 ProgramStateRef state = Pred->getState();
2192 bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
2193 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
2196 state = state->add<InitializedGlobalsSet>(VD);
2199 builder.generateNode(state, initHasRun, Pred);
2200 builder.markInfeasible(!initHasRun);
2202 currBldrCtx = nullptr;
2205 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
2206 /// nodes by processing the 'effects' of a computed goto jump.
2207 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
2208 ProgramStateRef state = builder.getState();
2209 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
2211 // Three possibilities:
2213 // (1) We know the computed label.
2214 // (2) The label is NULL (or some other constant), or Undefined.
2215 // (3) We have no clue about the label. Dispatch to all targets.
2218 using iterator = IndirectGotoNodeBuilder::iterator;
2220 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
2221 const LabelDecl *L = LV->getLabel();
2223 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
2224 if (I.getLabel() == L) {
2225 builder.generateNode(I, state);
2230 llvm_unreachable("No block with label.");
2233 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
2234 // Dispatch to the first target and mark it as a sink.
2235 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
2236 // FIXME: add checker visit.
2237 // UndefBranches.insert(N);
2241 // This is really a catch-all. We don't support symbolics yet.
2242 // FIXME: Implement dispatch for symbolic pointers.
2244 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I)
2245 builder.generateNode(I, state);
2248 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
2250 ExplodedNodeSet &Dst,
2251 const BlockEdge &L) {
2252 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
2253 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
2256 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
2257 /// nodes when the control reaches the end of a function.
2258 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
2260 const ReturnStmt *RS) {
2261 ProgramStateRef State = Pred->getState();
2263 if (!Pred->getStackFrame()->inTopFrame())
2264 State = finishArgumentConstruction(
2265 State, *getStateManager().getCallEventManager().getCaller(
2266 Pred->getStackFrame(), Pred->getState()));
2268 // FIXME: We currently cannot assert that temporaries are clear, because
2269 // lifetime extended temporaries are not always modelled correctly. In some
2270 // cases when we materialize the temporary, we do
2271 // createTemporaryRegionIfNeeded(), and the region changes, and also the
2272 // respective destructor becomes automatic from temporary. So for now clean up
2273 // the state manually before asserting. Ideally, this braced block of code
2276 const LocationContext *FromLC = Pred->getLocationContext();
2277 const LocationContext *ToLC = FromLC->getStackFrame()->getParent();
2278 const LocationContext *LC = FromLC;
2279 while (LC != ToLC) {
2280 assert(LC && "ToLC must be a parent of FromLC!");
2281 for (auto I : State->get<ObjectsUnderConstruction>())
2282 if (I.first.getLocationContext() == LC) {
2283 // The comment above only pardons us for not cleaning up a
2284 // temporary destructor. If any other statements are found here,
2285 // it must be a separate problem.
2286 assert(I.first.getItem().getKind() ==
2287 ConstructionContextItem::TemporaryDestructorKind ||
2288 I.first.getItem().getKind() ==
2289 ConstructionContextItem::ElidedDestructorKind);
2290 State = State->remove<ObjectsUnderConstruction>(I.first);
2292 LC = LC->getParent();
2296 // Perform the transition with cleanups.
2297 if (State != Pred->getState()) {
2298 ExplodedNodeSet PostCleanup;
2299 NodeBuilder Bldr(Pred, PostCleanup, BC);
2300 Pred = Bldr.generateNode(Pred->getLocation(), State, Pred);
2302 // The node with clean temporaries already exists. We might have reached
2303 // it on a path on which we initialize different temporaries.
2308 assert(areAllObjectsFullyConstructed(Pred->getState(),
2309 Pred->getLocationContext(),
2310 Pred->getStackFrame()->getParent()));
2312 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
2314 ExplodedNodeSet Dst;
2315 if (Pred->getLocationContext()->inTopFrame()) {
2316 // Remove dead symbols.
2317 ExplodedNodeSet AfterRemovedDead;
2318 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
2321 for (const auto I : AfterRemovedDead)
2322 getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this, RS);
2324 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this, RS);
2327 Engine.enqueueEndOfFunction(Dst, RS);
2330 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
2331 /// nodes by processing the 'effects' of a switch statement.
2332 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
2333 using iterator = SwitchNodeBuilder::iterator;
2335 ProgramStateRef state = builder.getState();
2336 const Expr *CondE = builder.getCondition();
2337 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
2339 if (CondV_untested.isUndef()) {
2340 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
2341 // FIXME: add checker
2342 //UndefBranches.insert(N);
2346 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
2348 ProgramStateRef DefaultSt = state;
2350 iterator I = builder.begin(), EI = builder.end();
2351 bool defaultIsFeasible = I == EI;
2353 for ( ; I != EI; ++I) {
2354 // Successor may be pruned out during CFG construction.
2358 const CaseStmt *Case = I.getCase();
2360 // Evaluate the LHS of the case value.
2361 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
2362 assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
2364 // Get the RHS of the case, if it exists.
2366 if (const Expr *E = Case->getRHS())
2367 V2 = E->EvaluateKnownConstInt(getContext());
2371 ProgramStateRef StateCase;
2372 if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
2373 std::tie(StateCase, DefaultSt) =
2374 DefaultSt->assumeInclusiveRange(*NL, V1, V2);
2376 StateCase = DefaultSt;
2379 builder.generateCaseStmtNode(I, StateCase);
2381 // Now "assume" that the case doesn't match. Add this state
2382 // to the default state (if it is feasible).
2384 defaultIsFeasible = true;
2386 defaultIsFeasible = false;
2391 if (!defaultIsFeasible)
2394 // If we have switch(enum value), the default branch is not
2395 // feasible if all of the enum constants not covered by 'case:' statements
2396 // are not feasible values for the switch condition.
2398 // Note that this isn't as accurate as it could be. Even if there isn't
2399 // a case for a particular enum value as long as that enum value isn't
2400 // feasible then it shouldn't be considered for making 'default:' reachable.
2401 const SwitchStmt *SS = builder.getSwitch();
2402 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
2403 if (CondExpr->getType()->getAs<EnumType>()) {
2404 if (SS->isAllEnumCasesCovered())
2408 builder.generateDefaultCaseNode(DefaultSt);
2411 //===----------------------------------------------------------------------===//
2412 // Transfer functions: Loads and stores.
2413 //===----------------------------------------------------------------------===//
2415 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
2417 ExplodedNodeSet &Dst) {
2418 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2420 ProgramStateRef state = Pred->getState();
2421 const LocationContext *LCtx = Pred->getLocationContext();
2423 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2424 // C permits "extern void v", and if you cast the address to a valid type,
2425 // you can even do things with it. We simply pretend
2426 assert(Ex->isGLValue() || VD->getType()->isVoidType());
2427 const LocationContext *LocCtxt = Pred->getLocationContext();
2428 const Decl *D = LocCtxt->getDecl();
2429 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
2430 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
2431 Optional<std::pair<SVal, QualType>> VInfo;
2433 if (AMgr.options.ShouldInlineLambdas && DeclRefEx &&
2434 DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
2435 MD->getParent()->isLambda()) {
2436 // Lookup the field of the lambda.
2437 const CXXRecordDecl *CXXRec = MD->getParent();
2438 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
2439 FieldDecl *LambdaThisCaptureField;
2440 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
2442 // Sema follows a sequence of complex rules to determine whether the
2443 // variable should be captured.
2444 if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
2446 svalBuilder.getCXXThis(MD, LocCtxt->getStackFrame());
2447 SVal CXXThisVal = state->getSVal(CXXThis);
2448 VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
2453 VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType());
2455 SVal V = VInfo->first;
2456 bool IsReference = VInfo->second->isReferenceType();
2458 // For references, the 'lvalue' is the pointer address stored in the
2459 // reference region.
2461 if (const MemRegion *R = V.getAsRegion())
2462 V = state->getSVal(R);
2467 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2468 ProgramPoint::PostLValueKind);
2471 if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
2472 assert(!Ex->isGLValue());
2473 SVal V = svalBuilder.makeIntVal(ED->getInitVal());
2474 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
2477 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2478 SVal V = svalBuilder.getFunctionPointer(FD);
2479 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2480 ProgramPoint::PostLValueKind);
2483 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
2484 // FIXME: Compute lvalue of field pointers-to-member.
2485 // Right now we just use a non-null void pointer, so that it gives proper
2486 // results in boolean contexts.
2487 // FIXME: Maybe delegate this to the surrounding operator&.
2488 // Note how this expression is lvalue, however pointer-to-member is NonLoc.
2489 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
2490 currBldrCtx->blockCount());
2491 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
2492 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2493 ProgramPoint::PostLValueKind);
2496 if (isa<BindingDecl>(D)) {
2497 // FIXME: proper support for bound declarations.
2498 // For now, let's just prevent crashing.
2502 llvm_unreachable("Support for this Decl not implemented.");
2505 /// VisitArraySubscriptExpr - Transfer function for array accesses
2506 void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A,
2508 ExplodedNodeSet &Dst){
2509 const Expr *Base = A->getBase()->IgnoreParens();
2510 const Expr *Idx = A->getIdx()->IgnoreParens();
2512 ExplodedNodeSet CheckerPreStmt;
2513 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
2515 ExplodedNodeSet EvalSet;
2516 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
2518 bool IsVectorType = A->getBase()->getType()->isVectorType();
2520 // The "like" case is for situations where C standard prohibits the type to
2521 // be an lvalue, e.g. taking the address of a subscript of an expression of
2523 bool IsGLValueLike = A->isGLValue() ||
2524 (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
2526 for (auto *Node : CheckerPreStmt) {
2527 const LocationContext *LCtx = Node->getLocationContext();
2528 ProgramStateRef state = Node->getState();
2530 if (IsGLValueLike) {
2531 QualType T = A->getType();
2533 // One of the forbidden LValue types! We still need to have sensible
2534 // symbolic locations to represent this stuff. Note that arithmetic on
2535 // void pointers is a GCC extension.
2536 if (T->isVoidType())
2537 T = getContext().CharTy;
2539 SVal V = state->getLValue(T,
2540 state->getSVal(Idx, LCtx),
2541 state->getSVal(Base, LCtx));
2542 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
2543 ProgramPoint::PostLValueKind);
2544 } else if (IsVectorType) {
2545 // FIXME: non-glvalue vector reads are not modelled.
2546 Bldr.generateNode(A, Node, state, nullptr);
2548 llvm_unreachable("Array subscript should be an lValue when not \
2549 a vector and not a forbidden lvalue type");
2553 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
2556 /// VisitMemberExpr - Transfer function for member expressions.
2557 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
2558 ExplodedNodeSet &Dst) {
2559 // FIXME: Prechecks eventually go in ::Visit().
2560 ExplodedNodeSet CheckedSet;
2561 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
2563 ExplodedNodeSet EvalSet;
2564 ValueDecl *Member = M->getMemberDecl();
2566 // Handle static member variables and enum constants accessed via
2568 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2569 for (const auto I : CheckedSet)
2570 VisitCommonDeclRefExpr(M, Member, I, EvalSet);
2572 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2573 ExplodedNodeSet Tmp;
2575 for (const auto I : CheckedSet) {
2576 ProgramStateRef state = I->getState();
2577 const LocationContext *LCtx = I->getLocationContext();
2578 Expr *BaseExpr = M->getBase();
2580 // Handle C++ method calls.
2581 if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
2582 if (MD->isInstance())
2583 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2585 SVal MDVal = svalBuilder.getFunctionPointer(MD);
2586 state = state->BindExpr(M, LCtx, MDVal);
2588 Bldr.generateNode(M, I, state);
2592 // Handle regular struct fields / member variables.
2593 const SubRegion *MR = nullptr;
2594 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr,
2596 /*OutRegionWithAdjustments=*/&MR);
2598 MR ? loc::MemRegionVal(MR) : state->getSVal(BaseExpr, LCtx);
2600 const auto *field = cast<FieldDecl>(Member);
2601 SVal L = state->getLValue(field, baseExprVal);
2603 if (M->isGLValue() || M->getType()->isArrayType()) {
2604 // We special-case rvalues of array type because the analyzer cannot
2605 // reason about them, since we expect all regions to be wrapped in Locs.
2606 // We instead treat these as lvalues and assume that they will decay to
2607 // pointers as soon as they are used.
2608 if (!M->isGLValue()) {
2609 assert(M->getType()->isArrayType());
2611 dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
2612 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2613 llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2617 if (field->getType()->isReferenceType()) {
2618 if (const MemRegion *R = L.getAsRegion())
2619 L = state->getSVal(R);
2624 Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr,
2625 ProgramPoint::PostLValueKind);
2628 evalLoad(Tmp, M, M, I, state, L);
2634 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2637 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
2638 ExplodedNodeSet &Dst) {
2639 ExplodedNodeSet AfterPreSet;
2640 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
2642 // For now, treat all the arguments to C11 atomics as escaping.
2643 // FIXME: Ideally we should model the behavior of the atomics precisely here.
2645 ExplodedNodeSet AfterInvalidateSet;
2646 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
2648 for (const auto I : AfterPreSet) {
2649 ProgramStateRef State = I->getState();
2650 const LocationContext *LCtx = I->getLocationContext();
2652 SmallVector<SVal, 8> ValuesToInvalidate;
2653 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
2654 const Expr *SubExpr = AE->getSubExprs()[SI];
2655 SVal SubExprVal = State->getSVal(SubExpr, LCtx);
2656 ValuesToInvalidate.push_back(SubExprVal);
2659 State = State->invalidateRegions(ValuesToInvalidate, AE,
2660 currBldrCtx->blockCount(),
2662 /*CausedByPointerEscape*/true,
2663 /*Symbols=*/nullptr);
2665 SVal ResultVal = UnknownVal();
2666 State = State->BindExpr(AE, LCtx, ResultVal);
2667 Bldr.generateNode(AE, I, State, nullptr,
2668 ProgramPoint::PostStmtKind);
2671 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
2674 // A value escapes in four possible cases:
2675 // (1) We are binding to something that is not a memory region.
2676 // (2) We are binding to a MemRegion that does not have stack storage.
2677 // (3) We are binding to a top-level parameter region with a non-trivial
2678 // destructor. We won't see the destructor during analysis, but it's there.
2679 // (4) We are binding to a MemRegion with stack storage that the store
2680 // does not understand.
2682 ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, SVal Loc,
2683 SVal Val, const LocationContext *LCtx) {
2685 // Cases (1) and (2).
2686 const MemRegion *MR = Loc.getAsRegion();
2687 if (!MR || !MR->hasStackStorage())
2688 return escapeValue(State, Val, PSK_EscapeOnBind);
2691 if (const auto *VR = dyn_cast<VarRegion>(MR->getBaseRegion()))
2692 if (VR->hasStackParametersStorage() && VR->getStackFrame()->inTopFrame())
2693 if (const auto *RD = VR->getValueType()->getAsCXXRecordDecl())
2694 if (!RD->hasTrivialDestructor())
2695 return escapeValue(State, Val, PSK_EscapeOnBind);
2697 // Case (4): in order to test that, generate a new state with the binding
2698 // added. If it is the same state, then it escapes (since the store cannot
2699 // represent the binding).
2700 // Do this only if we know that the store is not supposed to generate the
2702 SVal StoredVal = State->getSVal(MR);
2703 if (StoredVal != Val)
2704 if (State == (State->bindLoc(loc::MemRegionVal(MR), Val, LCtx)))
2705 return escapeValue(State, Val, PSK_EscapeOnBind);
2711 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2712 const InvalidatedSymbols *Invalidated,
2713 ArrayRef<const MemRegion *> ExplicitRegions,
2714 const CallEvent *Call,
2715 RegionAndSymbolInvalidationTraits &ITraits) {
2716 if (!Invalidated || Invalidated->empty())
2720 return getCheckerManager().runCheckersForPointerEscape(State,
2726 // If the symbols were invalidated by a call, we want to find out which ones
2727 // were invalidated directly due to being arguments to the call.
2728 InvalidatedSymbols SymbolsDirectlyInvalidated;
2729 for (const auto I : ExplicitRegions) {
2730 if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
2731 SymbolsDirectlyInvalidated.insert(R->getSymbol());
2734 InvalidatedSymbols SymbolsIndirectlyInvalidated;
2735 for (const auto &sym : *Invalidated) {
2736 if (SymbolsDirectlyInvalidated.count(sym))
2738 SymbolsIndirectlyInvalidated.insert(sym);
2741 if (!SymbolsDirectlyInvalidated.empty())
2742 State = getCheckerManager().runCheckersForPointerEscape(State,
2743 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2745 // Notify about the symbols that get indirectly invalidated by the call.
2746 if (!SymbolsIndirectlyInvalidated.empty())
2747 State = getCheckerManager().runCheckersForPointerEscape(State,
2748 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2753 /// evalBind - Handle the semantics of binding a value to a specific location.
2754 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
2755 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2757 SVal location, SVal Val,
2758 bool atDeclInit, const ProgramPoint *PP) {
2759 const LocationContext *LC = Pred->getLocationContext();
2760 PostStmt PS(StoreE, LC);
2764 // Do a previsit of the bind.
2765 ExplodedNodeSet CheckedSet;
2766 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2767 StoreE, *this, *PP);
2769 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2771 // If the location is not a 'Loc', it will already be handled by
2772 // the checkers. There is nothing left to do.
2773 if (!location.getAs<Loc>()) {
2774 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2776 ProgramStateRef state = Pred->getState();
2777 state = processPointerEscapedOnBind(state, location, Val, LC);
2778 Bldr.generateNode(L, state, Pred);
2782 for (const auto PredI : CheckedSet) {
2783 ProgramStateRef state = PredI->getState();
2785 state = processPointerEscapedOnBind(state, location, Val, LC);
2787 // When binding the value, pass on the hint that this is a initialization.
2788 // For initializations, we do not need to inform clients of region
2790 state = state->bindLoc(location.castAs<Loc>(),
2791 Val, LC, /* notifyChanges = */ !atDeclInit);
2793 const MemRegion *LocReg = nullptr;
2794 if (Optional<loc::MemRegionVal> LocRegVal =
2795 location.getAs<loc::MemRegionVal>()) {
2796 LocReg = LocRegVal->getRegion();
2799 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2800 Bldr.generateNode(L, state, PredI);
2804 /// evalStore - Handle the semantics of a store via an assignment.
2805 /// @param Dst The node set to store generated state nodes
2806 /// @param AssignE The assignment expression if the store happens in an
2808 /// @param LocationE The location expression that is stored to.
2809 /// @param state The current simulation state
2810 /// @param location The location to store the value
2811 /// @param Val The value to be stored
2812 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2813 const Expr *LocationE,
2815 ProgramStateRef state, SVal location, SVal Val,
2816 const ProgramPointTag *tag) {
2817 // Proceed with the store. We use AssignE as the anchor for the PostStore
2818 // ProgramPoint if it is non-NULL, and LocationE otherwise.
2819 const Expr *StoreE = AssignE ? AssignE : LocationE;
2821 // Evaluate the location (checks for bad dereferences).
2822 ExplodedNodeSet Tmp;
2823 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false);
2828 if (location.isUndef())
2831 for (const auto I : Tmp)
2832 evalBind(Dst, StoreE, I, location, Val, false);
2835 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2837 const Expr *BoundEx,
2839 ProgramStateRef state,
2841 const ProgramPointTag *tag,
2843 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2846 // Evaluate the location (checks for bad dereferences).
2847 ExplodedNodeSet Tmp;
2848 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true);
2852 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2853 if (location.isUndef())
2856 // Proceed with the load.
2857 for (const auto I : Tmp) {
2858 state = I->getState();
2859 const LocationContext *LCtx = I->getLocationContext();
2861 SVal V = UnknownVal();
2862 if (location.isValid()) {
2863 if (LoadTy.isNull())
2864 LoadTy = BoundEx->getType();
2865 V = state->getSVal(location.castAs<Loc>(), LoadTy);
2868 Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
2869 ProgramPoint::PostLoadKind);
2873 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2875 const Stmt *BoundEx,
2877 ProgramStateRef state,
2880 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2881 // Early checks for performance reason.
2882 if (location.isUnknown()) {
2886 ExplodedNodeSet Src;
2887 BldrTop.takeNodes(Pred);
2888 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2889 if (Pred->getState() != state) {
2890 // Associate this new state with an ExplodedNode.
2891 // FIXME: If I pass null tag, the graph is incorrect, e.g for
2895 // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2896 // instead "int *p" is noted as
2897 // "Variable 'p' initialized to a null pointer value"
2899 static SimpleProgramPointTag tag(TagProviderName, "Location");
2900 Bldr.generateNode(NodeEx, Pred, state, &tag);
2902 ExplodedNodeSet Tmp;
2903 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2904 NodeEx, BoundEx, *this);
2905 BldrTop.addNodes(Tmp);
2908 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2909 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2910 static SimpleProgramPointTag
2911 eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2912 "Eagerly Assume True"),
2913 eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2914 "Eagerly Assume False");
2915 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2916 &eagerlyAssumeBinOpBifurcationFalse);
2919 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2920 ExplodedNodeSet &Src,
2922 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2924 for (const auto Pred : Src) {
2925 // Test if the previous node was as the same expression. This can happen
2926 // when the expression fails to evaluate to anything meaningful and
2927 // (as an optimization) we don't generate a node.
2928 ProgramPoint P = Pred->getLocation();
2929 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2933 ProgramStateRef state = Pred->getState();
2934 SVal V = state->getSVal(Ex, Pred->getLocationContext());
2935 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2936 if (SEV && SEV->isExpression()) {
2937 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2938 geteagerlyAssumeBinOpBifurcationTags();
2940 ProgramStateRef StateTrue, StateFalse;
2941 std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2943 // First assume that the condition is true.
2945 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2946 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2947 Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2950 // Next, assume that the condition is false.
2952 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2953 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2954 Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2960 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2961 ExplodedNodeSet &Dst) {
2962 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2963 // We have processed both the inputs and the outputs. All of the outputs
2964 // should evaluate to Locs. Nuke all of their values.
2966 // FIXME: Some day in the future it would be nice to allow a "plug-in"
2967 // which interprets the inline asm and stores proper results in the
2970 ProgramStateRef state = Pred->getState();
2972 for (const Expr *O : A->outputs()) {
2973 SVal X = state->getSVal(O, Pred->getLocationContext());
2974 assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2976 if (Optional<Loc> LV = X.getAs<Loc>())
2977 state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
2980 Bldr.generateNode(A, Pred, state);
2983 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2984 ExplodedNodeSet &Dst) {
2985 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2986 Bldr.generateNode(A, Pred, Pred->getState());
2989 //===----------------------------------------------------------------------===//
2991 //===----------------------------------------------------------------------===//
2997 struct DOTGraphTraits<ExplodedGraph*> : public DefaultDOTGraphTraits {
2998 DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3000 static bool nodeHasBugReport(const ExplodedNode *N) {
3001 BugReporter &BR = static_cast<ExprEngine &>(
3002 N->getState()->getStateManager().getOwningEngine()).getBugReporter();
3004 const auto EQClasses =
3005 llvm::make_range(BR.EQClasses_begin(), BR.EQClasses_end());
3007 for (const auto &EQ : EQClasses) {
3008 for (const BugReport &Report : EQ) {
3009 if (Report.getErrorNode()->getState() == N->getState() &&
3010 Report.getErrorNode()->getLocation() == N->getLocation())
3017 /// \p PreCallback: callback before break.
3018 /// \p PostCallback: callback after break.
3019 /// \p Stop: stop iteration if returns {@code true}
3020 /// \return Whether {@code Stop} ever returned {@code true}.
3021 static bool traverseHiddenNodes(
3022 const ExplodedNode *N,
3023 llvm::function_ref<void(const ExplodedNode *)> PreCallback,
3024 llvm::function_ref<void(const ExplodedNode *)> PostCallback,
3025 llvm::function_ref<bool(const ExplodedNode *)> Stop) {
3026 const ExplodedNode *FirstHiddenNode = N;
3027 while (FirstHiddenNode->pred_size() == 1 &&
3028 isNodeHidden(*FirstHiddenNode->pred_begin())) {
3029 FirstHiddenNode = *FirstHiddenNode->pred_begin();
3031 const ExplodedNode *OtherNode = FirstHiddenNode;
3033 PreCallback(OtherNode);
3034 if (Stop(OtherNode))
3039 PostCallback(OtherNode);
3041 OtherNode = *OtherNode->succ_begin();
3046 static bool isNodeHidden(const ExplodedNode *N) {
3047 return N->isTrivial();
3050 static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){
3052 llvm::raw_string_ostream Out(Buf);
3054 const bool IsDot = true;
3055 const unsigned int Space = 1;
3056 ProgramStateRef State = N->getState();
3058 auto Noop = [](const ExplodedNode*){};
3059 bool HasReport = traverseHiddenNodes(
3060 N, Noop, Noop, &nodeHasBugReport);
3061 bool IsSink = traverseHiddenNodes(
3062 N, Noop, Noop, [](const ExplodedNode *N) { return N->isSink(); });
3064 Out << "{ \"node_id\": " << N->getID(G) << ", \"pointer\": \""
3065 << (const void *)N << "\", \"state_id\": " << State->getID()
3066 << ", \"has_report\": " << (HasReport ? "true" : "false")
3067 << ", \"is_sink\": " << (IsSink ? "true" : "false")
3070 Indent(Out, Space, IsDot) << "\"program_points\": [\\l";
3072 // Dump program point for all the previously skipped nodes.
3073 traverseHiddenNodes(
3075 [&](const ExplodedNode *OtherNode) {
3076 Indent(Out, Space + 1, IsDot) << "{ ";
3077 OtherNode->getLocation().printJson(Out, /*NL=*/"\\l");
3078 Out << ", \"tag\": ";
3079 if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag())
3080 Out << '\"' << Tag->getTagDescription() << "\" }";
3084 // Adds a comma and a new-line between each program point.
3085 [&](const ExplodedNode *) { Out << ",\\l"; },
3086 [&](const ExplodedNode *) { return false; });
3088 Out << "\\l"; // Adds a new-line to the last program point.
3089 Indent(Out, Space, IsDot) << "],\\l";
3091 bool SameAsAllPredecessors =
3092 std::all_of(N->pred_begin(), N->pred_end(), [&](const ExplodedNode *P) {
3093 return P->getState() == State;
3096 if (!SameAsAllPredecessors) {
3097 State->printDOT(Out, N->getLocationContext(), Space);
3099 Indent(Out, Space, IsDot) << "\"program_state\": null";
3110 void ExprEngine::ViewGraph(bool trim) {
3112 std::string Filename = DumpGraph(trim);
3113 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
3115 llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
3119 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
3121 std::string Filename = DumpGraph(Nodes);
3122 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
3124 llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
3127 std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) {
3130 std::vector<const ExplodedNode *> Src;
3132 // Iterate through the reports and get their nodes.
3133 for (BugReporter::EQClasses_iterator
3134 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
3135 const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
3136 if (N) Src.push_back(N);
3138 return DumpGraph(Src, Filename);
3140 return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false,
3141 /*Title=*/"Exploded Graph", /*Filename=*/Filename);
3144 llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
3148 std::string ExprEngine::DumpGraph(ArrayRef<const ExplodedNode*> Nodes,
3149 StringRef Filename) {
3151 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
3153 if (!TrimmedG.get()) {
3154 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
3156 return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine",
3157 /*ShortNames=*/false,
3158 /*Title=*/"Trimmed Exploded Graph",
3159 /*Filename=*/Filename);
3162 llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
3166 void *ProgramStateTrait<ReplayWithoutInlining>::GDMIndex() {
3167 static int index = 0;