1 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-=
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a meta-engine for path-sensitive dataflow analysis that
11 // is built on GREngine, but provides the boilerplate to execute transfer
12 // functions and build the ExplodedGraph at the expression level.
14 //===----------------------------------------------------------------------===//
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17 #include "PrettyStackTraceLocationContext.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ParentMap.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/PrettyStackTrace.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
26 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Support/SaveAndRestore.h"
32 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/GraphWriter.h"
38 using namespace clang;
42 #define DEBUG_TYPE "ExprEngine"
44 STATISTIC(NumRemoveDeadBindings,
45 "The # of times RemoveDeadBindings is called");
46 STATISTIC(NumMaxBlockCountReached,
47 "The # of aborted paths due to reaching the maximum block count in "
48 "a top level function");
49 STATISTIC(NumMaxBlockCountReachedInInlined,
50 "The # of aborted paths due to reaching the maximum block count in "
51 "an inlined function");
52 STATISTIC(NumTimesRetriedWithoutInlining,
53 "The # of times we re-evaluated a call without inlining");
55 typedef std::pair<const CXXBindTemporaryExpr *, const StackFrameContext *>
56 CXXBindTemporaryContext;
58 // Keeps track of whether CXXBindTemporaryExpr nodes have been evaluated.
59 // The StackFrameContext assures that nested calls due to inlined recursive
60 // functions do not interfere.
61 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedTemporariesSet,
62 llvm::ImmutableSet<CXXBindTemporaryContext>)
64 //===----------------------------------------------------------------------===//
65 // Engine construction and deletion.
66 //===----------------------------------------------------------------------===//
68 static const char* TagProviderName = "ExprEngine";
70 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
71 SetOfConstDecls *VisitedCalleesIn,
72 FunctionSummariesTy *FS,
73 InliningModes HowToInlineIn)
75 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
78 StateMgr(getContext(), mgr.getStoreManagerCreator(),
79 mgr.getConstraintManagerCreator(), G.getAllocator(),
81 SymMgr(StateMgr.getSymbolManager()),
82 svalBuilder(StateMgr.getSValBuilder()),
83 currStmtIdx(0), currBldrCtx(nullptr),
84 ObjCNoRet(mgr.getASTContext()),
85 ObjCGCEnabled(gcEnabled), BR(mgr, *this),
86 VisitedCallees(VisitedCalleesIn),
87 HowToInline(HowToInlineIn)
89 unsigned TrimInterval = mgr.options.getGraphTrimInterval();
90 if (TrimInterval != 0) {
91 // Enable eager node reclaimation when constructing the ExplodedGraph.
92 G.enableNodeReclamation(TrimInterval);
96 ExprEngine::~ExprEngine() {
100 //===----------------------------------------------------------------------===//
102 //===----------------------------------------------------------------------===//
104 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
105 ProgramStateRef state = StateMgr.getInitialState(InitLoc);
106 const Decl *D = InitLoc->getDecl();
109 // FIXME: It would be nice if we had a more general mechanism to add
110 // such preconditions. Some day.
113 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
114 // Precondition: the first argument of 'main' is an integer guaranteed
116 const IdentifierInfo *II = FD->getIdentifier();
117 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
120 const ParmVarDecl *PD = FD->getParamDecl(0);
121 QualType T = PD->getType();
122 const BuiltinType *BT = dyn_cast<BuiltinType>(T);
123 if (!BT || !BT->isInteger())
126 const MemRegion *R = state->getRegion(PD, InitLoc);
130 SVal V = state->getSVal(loc::MemRegionVal(R));
131 SVal Constraint_untested = evalBinOp(state, BO_GT, V,
132 svalBuilder.makeZeroVal(T),
133 svalBuilder.getConditionType());
135 Optional<DefinedOrUnknownSVal> Constraint =
136 Constraint_untested.getAs<DefinedOrUnknownSVal>();
141 if (ProgramStateRef newState = state->assume(*Constraint, true))
148 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
149 // Precondition: 'self' is always non-null upon entry to an Objective-C
151 const ImplicitParamDecl *SelfD = MD->getSelfDecl();
152 const MemRegion *R = state->getRegion(SelfD, InitLoc);
153 SVal V = state->getSVal(loc::MemRegionVal(R));
155 if (Optional<Loc> LV = V.getAs<Loc>()) {
156 // Assume that the pointer value in 'self' is non-null.
157 state = state->assume(*LV, true);
158 assert(state && "'self' cannot be null");
162 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
163 if (!MD->isStatic()) {
164 // Precondition: 'this' is always non-null upon entry to the
165 // top-level function. This is our starting assumption for
166 // analyzing an "open" program.
167 const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
168 if (SFC->getParent() == nullptr) {
169 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
170 SVal V = state->getSVal(L);
171 if (Optional<Loc> LV = V.getAs<Loc>()) {
172 state = state->assume(*LV, true);
173 assert(state && "'this' cannot be null");
183 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
184 const LocationContext *LC,
185 const Expr *InitWithAdjustments,
186 const Expr *Result) {
187 // FIXME: This function is a hack that works around the quirky AST
188 // we're often having with respect to C++ temporaries. If only we modelled
189 // the actual execution order of statements properly in the CFG,
190 // all the hassle with adjustments would not be necessary,
191 // and perhaps the whole function would be removed.
192 SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
194 // If we don't have an explicit result expression, we're in "if needed"
195 // mode. Only create a region if the current value is a NonLoc.
196 if (!InitValWithAdjustments.getAs<NonLoc>())
198 Result = InitWithAdjustments;
200 // We need to create a region no matter what. For sanity, make sure we don't
201 // try to stuff a Loc into a non-pointer temporary region.
202 assert(!InitValWithAdjustments.getAs<Loc>() ||
203 Loc::isLocType(Result->getType()) ||
204 Result->getType()->isMemberPointerType());
207 ProgramStateManager &StateMgr = State->getStateManager();
208 MemRegionManager &MRMgr = StateMgr.getRegionManager();
209 StoreManager &StoreMgr = StateMgr.getStoreManager();
211 // MaterializeTemporaryExpr may appear out of place, after a few field and
212 // base-class accesses have been made to the object, even though semantically
213 // it is the whole object that gets materialized and lifetime-extended.
217 // `-MaterializeTemporaryExpr
219 // `-CXXTemporaryObjectExpr
221 // instead of the more natural
224 // `-MaterializeTemporaryExpr
225 // `-CXXTemporaryObjectExpr
227 // Use the usual methods for obtaining the expression of the base object,
228 // and record the adjustments that we need to make to obtain the sub-object
229 // that the whole expression 'Ex' refers to. This trick is usual,
230 // in the sense that CodeGen takes a similar route.
232 SmallVector<const Expr *, 2> CommaLHSs;
233 SmallVector<SubobjectAdjustment, 2> Adjustments;
235 const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
236 CommaLHSs, Adjustments);
238 const TypedValueRegion *TR = nullptr;
239 if (const MaterializeTemporaryExpr *MT =
240 dyn_cast<MaterializeTemporaryExpr>(Result)) {
241 StorageDuration SD = MT->getStorageDuration();
242 // If this object is bound to a reference with static storage duration, we
243 // put it in a different region to prevent "address leakage" warnings.
244 if (SD == SD_Static || SD == SD_Thread)
245 TR = MRMgr.getCXXStaticTempObjectRegion(Init);
248 TR = MRMgr.getCXXTempObjectRegion(Init, LC);
250 SVal Reg = loc::MemRegionVal(TR);
253 // Make the necessary adjustments to obtain the sub-object.
254 for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
255 const SubobjectAdjustment &Adj = *I;
257 case SubobjectAdjustment::DerivedToBaseAdjustment:
258 Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
260 case SubobjectAdjustment::FieldAdjustment:
261 Reg = StoreMgr.getLValueField(Adj.Field, Reg);
263 case SubobjectAdjustment::MemberPointerAdjustment:
264 // FIXME: Unimplemented.
265 State = State->bindDefault(Reg, UnknownVal(), LC);
270 // What remains is to copy the value of the object to the new region.
271 // FIXME: In other words, what we should always do is copy value of the
272 // Init expression (which corresponds to the bigger object) to the whole
273 // temporary region TR. However, this value is often no longer present
274 // in the Environment. If it has disappeared, we instead invalidate TR.
275 // Still, what we can do is assign the value of expression Ex (which
276 // corresponds to the sub-object) to the TR's sub-region Reg. At least,
277 // values inside Reg would be correct.
278 SVal InitVal = State->getSVal(Init, LC);
279 if (InitVal.isUnknown()) {
280 InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
281 currBldrCtx->blockCount());
282 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
284 // Then we'd need to take the value that certainly exists and bind it over.
285 if (InitValWithAdjustments.isUnknown()) {
286 // Try to recover some path sensitivity in case we couldn't
287 // compute the value.
288 InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
289 Result, LC, InitWithAdjustments->getType(),
290 currBldrCtx->blockCount());
293 State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
295 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
298 // The result expression would now point to the correct sub-region of the
299 // newly created temporary region. Do this last in order to getSVal of Init
300 // correctly in case (Result == Init).
301 State = State->BindExpr(Result, LC, Reg);
303 // Notify checkers once for two bindLoc()s.
304 State = processRegionChange(State, TR, LC);
309 //===----------------------------------------------------------------------===//
310 // Top-level transfer function logic (Dispatcher).
311 //===----------------------------------------------------------------------===//
313 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
314 /// logic for handling assumptions on symbolic values.
315 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
316 SVal cond, bool assumption) {
317 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
321 ExprEngine::processRegionChanges(ProgramStateRef state,
322 const InvalidatedSymbols *invalidated,
323 ArrayRef<const MemRegion *> Explicits,
324 ArrayRef<const MemRegion *> Regions,
325 const LocationContext *LCtx,
326 const CallEvent *Call) {
327 return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
332 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
333 const char *NL, const char *Sep) {
334 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
337 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
338 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
341 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
342 unsigned StmtIdx, NodeBuilderContext *Ctx) {
343 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
344 currStmtIdx = StmtIdx;
347 switch (E.getKind()) {
348 case CFGElement::Statement:
349 ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred);
351 case CFGElement::Initializer:
352 ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred);
354 case CFGElement::NewAllocator:
355 ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
358 case CFGElement::AutomaticObjectDtor:
359 case CFGElement::DeleteDtor:
360 case CFGElement::BaseDtor:
361 case CFGElement::MemberDtor:
362 case CFGElement::TemporaryDtor:
363 ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
365 case CFGElement::LifetimeEnds:
370 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
372 const ExplodedNode *Pred,
373 const LocationContext *LC) {
375 // Are we never purging state values?
376 if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
379 // Is this the beginning of a basic block?
380 if (Pred->getLocation().getAs<BlockEntrance>())
383 // Is this on a non-expression?
384 if (!isa<Expr>(S.getStmt()))
387 // Run before processing a call.
388 if (CallEvent::isCallStmt(S.getStmt()))
391 // Is this an expression that is consumed by another expression? If so,
392 // postpone cleaning out the state.
393 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
394 return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
397 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
398 const Stmt *ReferenceStmt,
399 const LocationContext *LC,
400 const Stmt *DiagnosticStmt,
401 ProgramPoint::Kind K) {
402 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
403 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
404 && "PostStmt is not generally supported by the SymbolReaper yet");
405 assert(LC && "Must pass the current (or expiring) LocationContext");
407 if (!DiagnosticStmt) {
408 DiagnosticStmt = ReferenceStmt;
409 assert(DiagnosticStmt && "Required for clearing a LocationContext");
412 NumRemoveDeadBindings++;
413 ProgramStateRef CleanedState = Pred->getState();
415 // LC is the location context being destroyed, but SymbolReaper wants a
416 // location context that is still live. (If this is the top-level stack
417 // frame, this will be null.)
418 if (!ReferenceStmt) {
419 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
420 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
421 LC = LC->getParent();
424 const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : nullptr;
425 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
427 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
429 // Create a state in which dead bindings are removed from the environment
430 // and the store. TODO: The function should just return new env and store,
432 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
434 // Process any special transfer function for dead symbols.
435 // A tag to track convenience transitions, which can be removed at cleanup.
436 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
437 if (!SymReaper.hasDeadSymbols()) {
438 // Generate a CleanedNode that has the environment and store cleaned
439 // up. Since no symbols are dead, we can optimize and not clean out
440 // the constraint manager.
441 StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
442 Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
445 // Call checkers with the non-cleaned state so that they could query the
446 // values of the soon to be dead symbols.
447 ExplodedNodeSet CheckedSet;
448 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
449 DiagnosticStmt, *this, K);
451 // For each node in CheckedSet, generate CleanedNodes that have the
452 // environment, the store, and the constraints cleaned up but have the
453 // user-supplied states as the predecessors.
454 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
455 for (ExplodedNodeSet::const_iterator
456 I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
457 ProgramStateRef CheckerState = (*I)->getState();
459 // The constraint manager has not been cleaned up yet, so clean up now.
460 CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
463 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
464 "Checkers are not allowed to modify the Environment as a part of "
465 "checkDeadSymbols processing.");
466 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
467 "Checkers are not allowed to modify the Store as a part of "
468 "checkDeadSymbols processing.");
470 // Create a state based on CleanedState with CheckerState GDM and
471 // generate a transition to that state.
472 ProgramStateRef CleanedCheckerSt =
473 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
474 Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
479 void ExprEngine::ProcessStmt(const CFGStmt S,
480 ExplodedNode *Pred) {
481 // Reclaim any unnecessary nodes in the ExplodedGraph.
482 G.reclaimRecentlyAllocatedNodes();
484 const Stmt *currStmt = S.getStmt();
485 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
486 currStmt->getLocStart(),
487 "Error evaluating statement");
489 // Remove dead bindings and symbols.
490 ExplodedNodeSet CleanedStates;
491 if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
492 removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
494 CleanedStates.Add(Pred);
496 // Visit the statement.
498 for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
499 E = CleanedStates.end(); I != E; ++I) {
500 ExplodedNodeSet DstI;
501 // Visit the statement.
502 Visit(currStmt, *I, DstI);
506 // Enqueue the new nodes onto the work list.
507 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
510 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
511 ExplodedNode *Pred) {
512 const CXXCtorInitializer *BMI = Init.getInitializer();
514 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
515 BMI->getSourceLocation(),
516 "Error evaluating initializer");
518 // We don't clean up dead bindings here.
519 const StackFrameContext *stackFrame =
520 cast<StackFrameContext>(Pred->getLocationContext());
521 const CXXConstructorDecl *decl =
522 cast<CXXConstructorDecl>(stackFrame->getDecl());
524 ProgramStateRef State = Pred->getState();
525 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
527 ExplodedNodeSet Tmp(Pred);
530 // Evaluate the initializer, if necessary
531 if (BMI->isAnyMemberInitializer()) {
532 // Constructors build the object directly in the field,
533 // but non-objects must be copied in from the initializer.
534 if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) {
535 assert(BMI->getInit()->IgnoreImplicit() == CtorExpr);
537 // The field was directly constructed, so there is no need to bind.
539 const Expr *Init = BMI->getInit()->IgnoreImplicit();
540 const ValueDecl *Field;
541 if (BMI->isIndirectMemberInitializer()) {
542 Field = BMI->getIndirectMember();
543 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
545 Field = BMI->getMember();
546 FieldLoc = State->getLValue(BMI->getMember(), thisVal);
550 if (Init->getType()->isArrayType()) {
551 // Handle arrays of trivial type. We can represent this with a
552 // primitive load/copy from the base array region.
553 const ArraySubscriptExpr *ASE;
554 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
555 Init = ASE->getBase()->IgnoreImplicit();
557 SVal LValue = State->getSVal(Init, stackFrame);
558 if (!Field->getType()->isReferenceType())
559 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
560 InitVal = State->getSVal(*LValueLoc);
562 // If we fail to get the value for some reason, use a symbolic value.
563 if (InitVal.isUnknownOrUndef()) {
564 SValBuilder &SVB = getSValBuilder();
565 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
567 currBldrCtx->blockCount());
570 InitVal = State->getSVal(BMI->getInit(), stackFrame);
573 assert(Tmp.size() == 1 && "have not generated any new nodes yet");
574 assert(*Tmp.begin() == Pred && "have not generated any new nodes yet");
577 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
578 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
581 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
582 // We already did all the work when visiting the CXXConstructExpr.
585 // Construct PostInitializer nodes whether the state changed or not,
586 // so that the diagnostics don't get confused.
587 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
589 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
590 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
591 ExplodedNode *N = *I;
592 Bldr.generateNode(PP, N->getState(), N);
595 // Enqueue the new nodes onto the work list.
596 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
599 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
600 ExplodedNode *Pred) {
602 switch (D.getKind()) {
603 case CFGElement::AutomaticObjectDtor:
604 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
606 case CFGElement::BaseDtor:
607 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
609 case CFGElement::MemberDtor:
610 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
612 case CFGElement::TemporaryDtor:
613 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
615 case CFGElement::DeleteDtor:
616 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
619 llvm_unreachable("Unexpected dtor kind.");
622 // Enqueue the new nodes onto the work list.
623 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
626 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
627 ExplodedNode *Pred) {
629 AnalysisManager &AMgr = getAnalysisManager();
630 AnalyzerOptions &Opts = AMgr.options;
631 // TODO: We're not evaluating allocators for all cases just yet as
632 // we're not handling the return value correctly, which causes false
633 // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
634 if (Opts.mayInlineCXXAllocator())
635 VisitCXXNewAllocatorCall(NE, Pred, Dst);
637 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
638 const LocationContext *LCtx = Pred->getLocationContext();
639 PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
640 Bldr.generateNode(PP, Pred->getState(), Pred);
642 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
645 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
647 ExplodedNodeSet &Dst) {
648 const VarDecl *varDecl = Dtor.getVarDecl();
649 QualType varType = varDecl->getType();
651 ProgramStateRef state = Pred->getState();
652 SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
653 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
655 if (varType->isReferenceType()) {
656 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
658 // FIXME: This should not happen. The language guarantees a presence
659 // of a valid initializer here, so the reference shall not be undefined.
660 // It seems that we're calling destructors over variables that
661 // were not initialized yet.
664 Region = ValueRegion->getBaseRegion();
665 varType = cast<TypedValueRegion>(Region)->getValueType();
668 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
672 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
674 ExplodedNodeSet &Dst) {
675 ProgramStateRef State = Pred->getState();
676 const LocationContext *LCtx = Pred->getLocationContext();
677 const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
678 const Stmt *Arg = DE->getArgument();
679 SVal ArgVal = State->getSVal(Arg, LCtx);
681 // If the argument to delete is known to be a null value,
682 // don't run destructor.
683 if (State->isNull(ArgVal).isConstrainedTrue()) {
684 QualType DTy = DE->getDestroyedType();
685 QualType BTy = getContext().getBaseElementType(DTy);
686 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
687 const CXXDestructorDecl *Dtor = RD->getDestructor();
689 PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
690 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
691 Bldr.generateNode(PP, Pred->getState(), Pred);
695 VisitCXXDestructor(DE->getDestroyedType(),
696 ArgVal.getAsRegion(),
697 DE, /*IsBase=*/ false,
701 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
702 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
703 const LocationContext *LCtx = Pred->getLocationContext();
705 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
706 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
707 LCtx->getCurrentStackFrame());
708 SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
710 // Create the base object region.
711 const CXXBaseSpecifier *Base = D.getBaseSpecifier();
712 QualType BaseTy = Base->getType();
713 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
716 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
717 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst);
720 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
721 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
722 const FieldDecl *Member = D.getFieldDecl();
723 ProgramStateRef State = Pred->getState();
724 const LocationContext *LCtx = Pred->getLocationContext();
726 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
727 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
728 LCtx->getCurrentStackFrame());
730 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
732 VisitCXXDestructor(Member->getType(),
733 FieldVal.castAs<loc::MemRegionVal>().getRegion(),
734 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
737 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
739 ExplodedNodeSet &Dst) {
740 ExplodedNodeSet CleanDtorState;
741 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
742 ProgramStateRef State = Pred->getState();
743 if (State->contains<InitializedTemporariesSet>(
744 std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()))) {
745 // FIXME: Currently we insert temporary destructors for default parameters,
746 // but we don't insert the constructors.
747 State = State->remove<InitializedTemporariesSet>(
748 std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()));
750 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
752 QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType();
753 // FIXME: Currently CleanDtorState can be empty here due to temporaries being
754 // bound to default parameters.
755 assert(CleanDtorState.size() <= 1);
756 ExplodedNode *CleanPred =
757 CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
758 // FIXME: Inlining of temporary destructors is not supported yet anyway, so
759 // we just put a NULL region for now. This will need to be changed later.
760 VisitCXXDestructor(varType, nullptr, D.getBindTemporaryExpr(),
761 /*IsBase=*/false, CleanPred, Dst);
764 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
765 NodeBuilderContext &BldCtx,
767 ExplodedNodeSet &Dst,
768 const CFGBlock *DstT,
769 const CFGBlock *DstF) {
770 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
771 if (Pred->getState()->contains<InitializedTemporariesSet>(
772 std::make_pair(BTE, Pred->getStackFrame()))) {
773 TempDtorBuilder.markInfeasible(false);
774 TempDtorBuilder.generateNode(Pred->getState(), true, Pred);
776 TempDtorBuilder.markInfeasible(true);
777 TempDtorBuilder.generateNode(Pred->getState(), false, Pred);
781 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
782 ExplodedNodeSet &PreVisit,
783 ExplodedNodeSet &Dst) {
784 if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
785 // In case we don't have temporary destructors in the CFG, do not mark
786 // the initialization - we would otherwise never clean it up.
790 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
791 for (ExplodedNode *Node : PreVisit) {
792 ProgramStateRef State = Node->getState();
794 if (!State->contains<InitializedTemporariesSet>(
795 std::make_pair(BTE, Node->getStackFrame()))) {
796 // FIXME: Currently the state might already contain the marker due to
797 // incorrect handling of temporaries bound to default parameters; for
798 // those, we currently skip the CXXBindTemporaryExpr but rely on adding
799 // temporary destructor nodes.
800 State = State->add<InitializedTemporariesSet>(
801 std::make_pair(BTE, Node->getStackFrame()));
803 StmtBldr.generateNode(BTE, Node, State);
807 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
808 ExplodedNodeSet &DstTop) {
809 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
811 "Error evaluating statement");
813 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
815 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
817 switch (S->getStmtClass()) {
818 // C++, OpenMP and ARC stuff we don't support yet.
819 case Expr::ObjCIndirectCopyRestoreExprClass:
820 case Stmt::CXXDependentScopeMemberExprClass:
821 case Stmt::CXXInheritedCtorInitExprClass:
822 case Stmt::CXXTryStmtClass:
823 case Stmt::CXXTypeidExprClass:
824 case Stmt::CXXUuidofExprClass:
825 case Stmt::CXXFoldExprClass:
826 case Stmt::MSPropertyRefExprClass:
827 case Stmt::MSPropertySubscriptExprClass:
828 case Stmt::CXXUnresolvedConstructExprClass:
829 case Stmt::DependentScopeDeclRefExprClass:
830 case Stmt::ArrayTypeTraitExprClass:
831 case Stmt::ExpressionTraitExprClass:
832 case Stmt::UnresolvedLookupExprClass:
833 case Stmt::UnresolvedMemberExprClass:
834 case Stmt::TypoExprClass:
835 case Stmt::CXXNoexceptExprClass:
836 case Stmt::PackExpansionExprClass:
837 case Stmt::SubstNonTypeTemplateParmPackExprClass:
838 case Stmt::FunctionParmPackExprClass:
839 case Stmt::CoroutineBodyStmtClass:
840 case Stmt::CoawaitExprClass:
841 case Stmt::DependentCoawaitExprClass:
842 case Stmt::CoreturnStmtClass:
843 case Stmt::CoyieldExprClass:
844 case Stmt::SEHTryStmtClass:
845 case Stmt::SEHExceptStmtClass:
846 case Stmt::SEHLeaveStmtClass:
847 case Stmt::SEHFinallyStmtClass:
848 case Stmt::OMPParallelDirectiveClass:
849 case Stmt::OMPSimdDirectiveClass:
850 case Stmt::OMPForDirectiveClass:
851 case Stmt::OMPForSimdDirectiveClass:
852 case Stmt::OMPSectionsDirectiveClass:
853 case Stmt::OMPSectionDirectiveClass:
854 case Stmt::OMPSingleDirectiveClass:
855 case Stmt::OMPMasterDirectiveClass:
856 case Stmt::OMPCriticalDirectiveClass:
857 case Stmt::OMPParallelForDirectiveClass:
858 case Stmt::OMPParallelForSimdDirectiveClass:
859 case Stmt::OMPParallelSectionsDirectiveClass:
860 case Stmt::OMPTaskDirectiveClass:
861 case Stmt::OMPTaskyieldDirectiveClass:
862 case Stmt::OMPBarrierDirectiveClass:
863 case Stmt::OMPTaskwaitDirectiveClass:
864 case Stmt::OMPTaskgroupDirectiveClass:
865 case Stmt::OMPFlushDirectiveClass:
866 case Stmt::OMPOrderedDirectiveClass:
867 case Stmt::OMPAtomicDirectiveClass:
868 case Stmt::OMPTargetDirectiveClass:
869 case Stmt::OMPTargetDataDirectiveClass:
870 case Stmt::OMPTargetEnterDataDirectiveClass:
871 case Stmt::OMPTargetExitDataDirectiveClass:
872 case Stmt::OMPTargetParallelDirectiveClass:
873 case Stmt::OMPTargetParallelForDirectiveClass:
874 case Stmt::OMPTargetUpdateDirectiveClass:
875 case Stmt::OMPTeamsDirectiveClass:
876 case Stmt::OMPCancellationPointDirectiveClass:
877 case Stmt::OMPCancelDirectiveClass:
878 case Stmt::OMPTaskLoopDirectiveClass:
879 case Stmt::OMPTaskLoopSimdDirectiveClass:
880 case Stmt::OMPDistributeDirectiveClass:
881 case Stmt::OMPDistributeParallelForDirectiveClass:
882 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
883 case Stmt::OMPDistributeSimdDirectiveClass:
884 case Stmt::OMPTargetParallelForSimdDirectiveClass:
885 case Stmt::OMPTargetSimdDirectiveClass:
886 case Stmt::OMPTeamsDistributeDirectiveClass:
887 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
888 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
889 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
890 case Stmt::OMPTargetTeamsDirectiveClass:
891 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
892 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
893 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
894 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
895 case Stmt::CapturedStmtClass:
897 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
898 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
902 case Stmt::ParenExprClass:
903 llvm_unreachable("ParenExprs already handled.");
904 case Stmt::GenericSelectionExprClass:
905 llvm_unreachable("GenericSelectionExprs already handled.");
906 // Cases that should never be evaluated simply because they shouldn't
907 // appear in the CFG.
908 case Stmt::BreakStmtClass:
909 case Stmt::CaseStmtClass:
910 case Stmt::CompoundStmtClass:
911 case Stmt::ContinueStmtClass:
912 case Stmt::CXXForRangeStmtClass:
913 case Stmt::DefaultStmtClass:
914 case Stmt::DoStmtClass:
915 case Stmt::ForStmtClass:
916 case Stmt::GotoStmtClass:
917 case Stmt::IfStmtClass:
918 case Stmt::IndirectGotoStmtClass:
919 case Stmt::LabelStmtClass:
920 case Stmt::NoStmtClass:
921 case Stmt::NullStmtClass:
922 case Stmt::SwitchStmtClass:
923 case Stmt::WhileStmtClass:
924 case Expr::MSDependentExistsStmtClass:
925 llvm_unreachable("Stmt should not be in analyzer evaluation loop");
927 case Stmt::ObjCSubscriptRefExprClass:
928 case Stmt::ObjCPropertyRefExprClass:
929 llvm_unreachable("These are handled by PseudoObjectExpr");
931 case Stmt::GNUNullExprClass: {
932 // GNU __null is a pointer-width integer, not an actual pointer.
933 ProgramStateRef state = Pred->getState();
934 state = state->BindExpr(S, Pred->getLocationContext(),
935 svalBuilder.makeIntValWithPtrWidth(0, false));
936 Bldr.generateNode(S, Pred, state);
940 case Stmt::ObjCAtSynchronizedStmtClass:
941 Bldr.takeNodes(Pred);
942 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
946 case Stmt::ExprWithCleanupsClass:
947 // Handled due to fully linearised CFG.
950 case Stmt::CXXBindTemporaryExprClass: {
951 Bldr.takeNodes(Pred);
952 ExplodedNodeSet PreVisit;
953 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
954 ExplodedNodeSet Next;
955 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
956 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
961 // Cases not handled yet; but will handle some day.
962 case Stmt::DesignatedInitExprClass:
963 case Stmt::DesignatedInitUpdateExprClass:
964 case Stmt::ArrayInitLoopExprClass:
965 case Stmt::ArrayInitIndexExprClass:
966 case Stmt::ExtVectorElementExprClass:
967 case Stmt::ImaginaryLiteralClass:
968 case Stmt::ObjCAtCatchStmtClass:
969 case Stmt::ObjCAtFinallyStmtClass:
970 case Stmt::ObjCAtTryStmtClass:
971 case Stmt::ObjCAutoreleasePoolStmtClass:
972 case Stmt::ObjCEncodeExprClass:
973 case Stmt::ObjCIsaExprClass:
974 case Stmt::ObjCProtocolExprClass:
975 case Stmt::ObjCSelectorExprClass:
976 case Stmt::ParenListExprClass:
977 case Stmt::ShuffleVectorExprClass:
978 case Stmt::ConvertVectorExprClass:
979 case Stmt::VAArgExprClass:
980 case Stmt::CUDAKernelCallExprClass:
981 case Stmt::OpaqueValueExprClass:
982 case Stmt::AsTypeExprClass:
985 // Cases we intentionally don't evaluate, since they don't need
986 // to be explicitly evaluated.
987 case Stmt::PredefinedExprClass:
988 case Stmt::AddrLabelExprClass:
989 case Stmt::AttributedStmtClass:
990 case Stmt::IntegerLiteralClass:
991 case Stmt::CharacterLiteralClass:
992 case Stmt::ImplicitValueInitExprClass:
993 case Stmt::CXXScalarValueInitExprClass:
994 case Stmt::CXXBoolLiteralExprClass:
995 case Stmt::ObjCBoolLiteralExprClass:
996 case Stmt::ObjCAvailabilityCheckExprClass:
997 case Stmt::FloatingLiteralClass:
998 case Stmt::NoInitExprClass:
999 case Stmt::SizeOfPackExprClass:
1000 case Stmt::StringLiteralClass:
1001 case Stmt::ObjCStringLiteralClass:
1002 case Stmt::CXXPseudoDestructorExprClass:
1003 case Stmt::SubstNonTypeTemplateParmExprClass:
1004 case Stmt::CXXNullPtrLiteralExprClass:
1005 case Stmt::OMPArraySectionExprClass:
1006 case Stmt::TypeTraitExprClass: {
1007 Bldr.takeNodes(Pred);
1008 ExplodedNodeSet preVisit;
1009 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1010 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
1015 case Stmt::CXXDefaultArgExprClass:
1016 case Stmt::CXXDefaultInitExprClass: {
1017 Bldr.takeNodes(Pred);
1018 ExplodedNodeSet PreVisit;
1019 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1021 ExplodedNodeSet Tmp;
1022 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
1025 if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
1026 ArgE = DefE->getExpr();
1027 else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
1028 ArgE = DefE->getExpr();
1030 llvm_unreachable("unknown constant wrapper kind");
1032 bool IsTemporary = false;
1033 if (const MaterializeTemporaryExpr *MTE =
1034 dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
1035 ArgE = MTE->GetTemporaryExpr();
1039 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
1041 ConstantVal = UnknownVal();
1043 const LocationContext *LCtx = Pred->getLocationContext();
1044 for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
1046 ProgramStateRef State = (*I)->getState();
1047 State = State->BindExpr(S, LCtx, *ConstantVal);
1049 State = createTemporaryRegionIfNeeded(State, LCtx,
1052 Bldr2.generateNode(S, *I, State);
1055 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1060 // Cases we evaluate as opaque expressions, conjuring a symbol.
1061 case Stmt::CXXStdInitializerListExprClass:
1062 case Expr::ObjCArrayLiteralClass:
1063 case Expr::ObjCDictionaryLiteralClass:
1064 case Expr::ObjCBoxedExprClass: {
1065 Bldr.takeNodes(Pred);
1067 ExplodedNodeSet preVisit;
1068 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1070 ExplodedNodeSet Tmp;
1071 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
1073 const Expr *Ex = cast<Expr>(S);
1074 QualType resultType = Ex->getType();
1076 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
1078 ExplodedNode *N = *it;
1079 const LocationContext *LCtx = N->getLocationContext();
1080 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1082 currBldrCtx->blockCount());
1083 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
1084 Bldr2.generateNode(S, N, state);
1087 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1092 case Stmt::ArraySubscriptExprClass:
1093 Bldr.takeNodes(Pred);
1094 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1098 case Stmt::GCCAsmStmtClass:
1099 Bldr.takeNodes(Pred);
1100 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1104 case Stmt::MSAsmStmtClass:
1105 Bldr.takeNodes(Pred);
1106 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1110 case Stmt::BlockExprClass:
1111 Bldr.takeNodes(Pred);
1112 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1116 case Stmt::LambdaExprClass:
1117 if (AMgr.options.shouldInlineLambdas()) {
1118 Bldr.takeNodes(Pred);
1119 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1122 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1123 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1127 case Stmt::BinaryOperatorClass: {
1128 const BinaryOperator* B = cast<BinaryOperator>(S);
1129 if (B->isLogicalOp()) {
1130 Bldr.takeNodes(Pred);
1131 VisitLogicalExpr(B, Pred, Dst);
1135 else if (B->getOpcode() == BO_Comma) {
1136 ProgramStateRef state = Pred->getState();
1137 Bldr.generateNode(B, Pred,
1138 state->BindExpr(B, Pred->getLocationContext(),
1139 state->getSVal(B->getRHS(),
1140 Pred->getLocationContext())));
1144 Bldr.takeNodes(Pred);
1146 if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
1147 (B->isRelationalOp() || B->isEqualityOp())) {
1148 ExplodedNodeSet Tmp;
1149 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1150 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1153 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1159 case Stmt::CXXOperatorCallExprClass: {
1160 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
1162 // For instance method operators, make sure the 'this' argument has a
1164 const Decl *Callee = OCE->getCalleeDecl();
1165 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1166 if (MD->isInstance()) {
1167 ProgramStateRef State = Pred->getState();
1168 const LocationContext *LCtx = Pred->getLocationContext();
1169 ProgramStateRef NewState =
1170 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1171 if (NewState != State) {
1172 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1173 ProgramPoint::PreStmtKind);
1174 // Did we cache out?
1183 case Stmt::CallExprClass:
1184 case Stmt::CXXMemberCallExprClass:
1185 case Stmt::UserDefinedLiteralClass: {
1186 Bldr.takeNodes(Pred);
1187 VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1192 case Stmt::CXXCatchStmtClass: {
1193 Bldr.takeNodes(Pred);
1194 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1199 case Stmt::CXXTemporaryObjectExprClass:
1200 case Stmt::CXXConstructExprClass: {
1201 Bldr.takeNodes(Pred);
1202 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1207 case Stmt::CXXNewExprClass: {
1208 Bldr.takeNodes(Pred);
1209 ExplodedNodeSet PostVisit;
1210 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
1211 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1216 case Stmt::CXXDeleteExprClass: {
1217 Bldr.takeNodes(Pred);
1218 ExplodedNodeSet PreVisit;
1219 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
1220 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1222 for (ExplodedNodeSet::iterator i = PreVisit.begin(),
1223 e = PreVisit.end(); i != e ; ++i)
1224 VisitCXXDeleteExpr(CDE, *i, Dst);
1229 // FIXME: ChooseExpr is really a constant. We need to fix
1230 // the CFG do not model them as explicit control-flow.
1232 case Stmt::ChooseExprClass: { // __builtin_choose_expr
1233 Bldr.takeNodes(Pred);
1234 const ChooseExpr *C = cast<ChooseExpr>(S);
1235 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1240 case Stmt::CompoundAssignOperatorClass:
1241 Bldr.takeNodes(Pred);
1242 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1246 case Stmt::CompoundLiteralExprClass:
1247 Bldr.takeNodes(Pred);
1248 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1252 case Stmt::BinaryConditionalOperatorClass:
1253 case Stmt::ConditionalOperatorClass: { // '?' operator
1254 Bldr.takeNodes(Pred);
1255 const AbstractConditionalOperator *C
1256 = cast<AbstractConditionalOperator>(S);
1257 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1262 case Stmt::CXXThisExprClass:
1263 Bldr.takeNodes(Pred);
1264 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1268 case Stmt::DeclRefExprClass: {
1269 Bldr.takeNodes(Pred);
1270 const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1271 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1276 case Stmt::DeclStmtClass:
1277 Bldr.takeNodes(Pred);
1278 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1282 case Stmt::ImplicitCastExprClass:
1283 case Stmt::CStyleCastExprClass:
1284 case Stmt::CXXStaticCastExprClass:
1285 case Stmt::CXXDynamicCastExprClass:
1286 case Stmt::CXXReinterpretCastExprClass:
1287 case Stmt::CXXConstCastExprClass:
1288 case Stmt::CXXFunctionalCastExprClass:
1289 case Stmt::ObjCBridgedCastExprClass: {
1290 Bldr.takeNodes(Pred);
1291 const CastExpr *C = cast<CastExpr>(S);
1292 ExplodedNodeSet dstExpr;
1293 VisitCast(C, C->getSubExpr(), Pred, dstExpr);
1295 // Handle the postvisit checks.
1296 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1301 case Expr::MaterializeTemporaryExprClass: {
1302 Bldr.takeNodes(Pred);
1303 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1304 ExplodedNodeSet dstPrevisit;
1305 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
1306 ExplodedNodeSet dstExpr;
1307 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1308 e = dstPrevisit.end(); i != e ; ++i) {
1309 CreateCXXTemporaryObject(MTE, *i, dstExpr);
1311 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
1316 case Stmt::InitListExprClass:
1317 Bldr.takeNodes(Pred);
1318 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1322 case Stmt::MemberExprClass:
1323 Bldr.takeNodes(Pred);
1324 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1328 case Stmt::AtomicExprClass:
1329 Bldr.takeNodes(Pred);
1330 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
1334 case Stmt::ObjCIvarRefExprClass:
1335 Bldr.takeNodes(Pred);
1336 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1340 case Stmt::ObjCForCollectionStmtClass:
1341 Bldr.takeNodes(Pred);
1342 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1346 case Stmt::ObjCMessageExprClass:
1347 Bldr.takeNodes(Pred);
1348 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1352 case Stmt::ObjCAtThrowStmtClass:
1353 case Stmt::CXXThrowExprClass:
1354 // FIXME: This is not complete. We basically treat @throw as
1356 Bldr.generateSink(S, Pred, Pred->getState());
1359 case Stmt::ReturnStmtClass:
1360 Bldr.takeNodes(Pred);
1361 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1365 case Stmt::OffsetOfExprClass:
1366 Bldr.takeNodes(Pred);
1367 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1371 case Stmt::UnaryExprOrTypeTraitExprClass:
1372 Bldr.takeNodes(Pred);
1373 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1378 case Stmt::StmtExprClass: {
1379 const StmtExpr *SE = cast<StmtExpr>(S);
1381 if (SE->getSubStmt()->body_empty()) {
1382 // Empty statement expression.
1383 assert(SE->getType() == getContext().VoidTy
1384 && "Empty statement expression must have void type.");
1388 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1389 ProgramStateRef state = Pred->getState();
1390 Bldr.generateNode(SE, Pred,
1391 state->BindExpr(SE, Pred->getLocationContext(),
1392 state->getSVal(LastExpr,
1393 Pred->getLocationContext())));
1398 case Stmt::UnaryOperatorClass: {
1399 Bldr.takeNodes(Pred);
1400 const UnaryOperator *U = cast<UnaryOperator>(S);
1401 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1402 ExplodedNodeSet Tmp;
1403 VisitUnaryOperator(U, Pred, Tmp);
1404 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1407 VisitUnaryOperator(U, Pred, Dst);
1412 case Stmt::PseudoObjectExprClass: {
1413 Bldr.takeNodes(Pred);
1414 ProgramStateRef state = Pred->getState();
1415 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1416 if (const Expr *Result = PE->getResultExpr()) {
1417 SVal V = state->getSVal(Result, Pred->getLocationContext());
1418 Bldr.generateNode(S, Pred,
1419 state->BindExpr(S, Pred->getLocationContext(), V));
1422 Bldr.generateNode(S, Pred,
1423 state->BindExpr(S, Pred->getLocationContext(),
1432 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1433 const LocationContext *CalleeLC) {
1434 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1435 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1436 assert(CalleeSF && CallerSF);
1437 ExplodedNode *BeforeProcessingCall = nullptr;
1438 const Stmt *CE = CalleeSF->getCallSite();
1440 // Find the first node before we started processing the call expression.
1442 ProgramPoint L = N->getLocation();
1443 BeforeProcessingCall = N;
1444 N = N->pred_empty() ? nullptr : *(N->pred_begin());
1446 // Skip the nodes corresponding to the inlined code.
1447 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1449 // We reached the caller. Find the node right before we started
1450 // processing the call.
1451 if (L.isPurgeKind())
1453 if (L.getAs<PreImplicitCall>())
1455 if (L.getAs<CallEnter>())
1457 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1458 if (SP->getStmt() == CE)
1463 if (!BeforeProcessingCall)
1466 // TODO: Clean up the unneeded nodes.
1468 // Build an Epsilon node from which we will restart the analyzes.
1469 // Note that CE is permitted to be NULL!
1470 ProgramPoint NewNodeLoc =
1471 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1472 // Add the special flag to GDM to signal retrying with no inlining.
1473 // Note, changing the state ensures that we are not going to cache out.
1474 ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1476 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1478 // Make the new node a successor of BeforeProcessingCall.
1480 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1481 // We cached out at this point. Caching out is common due to us backtracking
1482 // from the inlined function, which might spawn several paths.
1486 NewNode->addPredecessor(BeforeProcessingCall, G);
1488 // Add the new node to the work list.
1489 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1490 CalleeSF->getIndex());
1491 NumTimesRetriedWithoutInlining++;
1495 /// Block entrance. (Update counters).
1496 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1497 NodeBuilderWithSinks &nodeBuilder,
1498 ExplodedNode *Pred) {
1499 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1501 // If this block is terminated by a loop and it has already been visited the
1502 // maximum number of times, widen the loop.
1503 unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1504 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1505 AMgr.options.shouldWidenLoops()) {
1506 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1508 (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1511 const LocationContext *LCtx = Pred->getLocationContext();
1512 ProgramStateRef WidenedState =
1513 getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1514 nodeBuilder.generateNode(WidenedState, Pred);
1518 // FIXME: Refactor this into a checker.
1519 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1520 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1521 const ExplodedNode *Sink =
1522 nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1524 // Check if we stopped at the top level function or not.
1525 // Root node should have the location context of the top most function.
1526 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1527 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1528 const LocationContext *RootLC =
1529 (*G.roots_begin())->getLocation().getLocationContext();
1530 if (RootLC->getCurrentStackFrame() != CalleeSF) {
1531 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1533 // Re-run the call evaluation without inlining it, by storing the
1534 // no-inlining policy in the state and enqueuing the new work item on
1535 // the list. Replay should almost never fail. Use the stats to catch it
1537 if ((!AMgr.options.NoRetryExhausted &&
1538 replayWithoutInlining(Pred, CalleeLC)))
1540 NumMaxBlockCountReachedInInlined++;
1542 NumMaxBlockCountReached++;
1544 // Make sink nodes as exhausted(for stats) only if retry failed.
1545 Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1549 //===----------------------------------------------------------------------===//
1550 // Branch processing.
1551 //===----------------------------------------------------------------------===//
1553 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1554 /// to try to recover some path-sensitivity for casts of symbolic
1555 /// integers that promote their values (which are currently not tracked well).
1556 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1557 // cast(s) did was sign-extend the original value.
1558 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1559 ProgramStateRef state,
1560 const Stmt *Condition,
1561 const LocationContext *LCtx,
1564 const Expr *Ex = dyn_cast<Expr>(Condition);
1566 return UnknownVal();
1569 bool bitsInit = false;
1571 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1572 QualType T = CE->getType();
1574 if (!T->isIntegralOrEnumerationType())
1575 return UnknownVal();
1577 uint64_t newBits = Ctx.getTypeSize(T);
1578 if (!bitsInit || newBits < bits) {
1583 Ex = CE->getSubExpr();
1586 // We reached a non-cast. Is it a symbolic value?
1587 QualType T = Ex->getType();
1589 if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1590 Ctx.getTypeSize(T) > bits)
1591 return UnknownVal();
1593 return state->getSVal(Ex, LCtx);
1597 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1599 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1600 if (!BO || !BO->isLogicalOp()) {
1603 Condition = BO->getRHS()->IgnoreParens();
1609 // Returns the condition the branch at the end of 'B' depends on and whose value
1610 // has been evaluated within 'B'.
1611 // In most cases, the terminator condition of 'B' will be evaluated fully in
1612 // the last statement of 'B'; in those cases, the resolved condition is the
1613 // given 'Condition'.
1614 // If the condition of the branch is a logical binary operator tree, the CFG is
1615 // optimized: in that case, we know that the expression formed by all but the
1616 // rightmost leaf of the logical binary operator tree must be true, and thus
1617 // the branch condition is at this point equivalent to the truth value of that
1618 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1619 // expression in its final statement. As the full condition in that case was
1620 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1621 // expression to evaluate the truth value of the condition in the current state
1623 static const Stmt *ResolveCondition(const Stmt *Condition,
1624 const CFGBlock *B) {
1625 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1626 Condition = Ex->IgnoreParens();
1628 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1629 if (!BO || !BO->isLogicalOp())
1632 assert(!B->getTerminator().isTemporaryDtorsBranch() &&
1633 "Temporary destructor branches handled by processBindTemporary.");
1635 // For logical operations, we still have the case where some branches
1636 // use the traditional "merge" approach and others sink the branch
1637 // directly into the basic blocks representing the logical operation.
1638 // We need to distinguish between those two cases here.
1640 // The invariants are still shifting, but it is possible that the
1641 // last element in a CFGBlock is not a CFGStmt. Look for the last
1642 // CFGStmt as the value of the condition.
1643 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1644 for (; I != E; ++I) {
1645 CFGElement Elem = *I;
1646 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1649 const Stmt *LastStmt = CS->getStmt();
1650 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
1653 llvm_unreachable("could not resolve condition");
1656 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1657 NodeBuilderContext& BldCtx,
1659 ExplodedNodeSet &Dst,
1660 const CFGBlock *DstT,
1661 const CFGBlock *DstF) {
1662 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
1663 "CXXBindTemporaryExprs are handled by processBindTemporary.");
1664 const LocationContext *LCtx = Pred->getLocationContext();
1665 PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1666 currBldrCtx = &BldCtx;
1668 // Check for NULL conditions; e.g. "for(;;)"
1670 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1671 NullCondBldr.markInfeasible(false);
1672 NullCondBldr.generateNode(Pred->getState(), true, Pred);
1676 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1677 Condition = Ex->IgnoreParens();
1679 Condition = ResolveCondition(Condition, BldCtx.getBlock());
1680 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1681 Condition->getLocStart(),
1682 "Error evaluating branch");
1684 ExplodedNodeSet CheckersOutSet;
1685 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1687 // We generated only sinks.
1688 if (CheckersOutSet.empty())
1691 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1692 for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1693 E = CheckersOutSet.end(); E != I; ++I) {
1694 ExplodedNode *PredI = *I;
1696 if (PredI->isSink())
1699 ProgramStateRef PrevState = PredI->getState();
1700 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1702 if (X.isUnknownOrUndef()) {
1703 // Give it a chance to recover from unknown.
1704 if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1705 if (Ex->getType()->isIntegralOrEnumerationType()) {
1706 // Try to recover some path-sensitivity. Right now casts of symbolic
1707 // integers that promote their values are currently not tracked well.
1708 // If 'Condition' is such an expression, try and recover the
1709 // underlying value and use that instead.
1710 SVal recovered = RecoverCastedSymbol(getStateManager(),
1711 PrevState, Condition,
1712 PredI->getLocationContext(),
1715 if (!recovered.isUnknown()) {
1722 // If the condition is still unknown, give up.
1723 if (X.isUnknownOrUndef()) {
1724 builder.generateNode(PrevState, true, PredI);
1725 builder.generateNode(PrevState, false, PredI);
1729 DefinedSVal V = X.castAs<DefinedSVal>();
1731 ProgramStateRef StTrue, StFalse;
1732 std::tie(StTrue, StFalse) = PrevState->assume(V);
1734 // Process the true branch.
1735 if (builder.isFeasible(true)) {
1737 builder.generateNode(StTrue, true, PredI);
1739 builder.markInfeasible(true);
1742 // Process the false branch.
1743 if (builder.isFeasible(false)) {
1745 builder.generateNode(StFalse, false, PredI);
1747 builder.markInfeasible(false);
1750 currBldrCtx = nullptr;
1753 /// The GDM component containing the set of global variables which have been
1754 /// previously initialized with explicit initializers.
1755 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1756 llvm::ImmutableSet<const VarDecl *>)
1758 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1759 NodeBuilderContext &BuilderCtx,
1761 clang::ento::ExplodedNodeSet &Dst,
1762 const CFGBlock *DstT,
1763 const CFGBlock *DstF) {
1764 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1765 currBldrCtx = &BuilderCtx;
1767 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1768 ProgramStateRef state = Pred->getState();
1769 bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1770 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1773 state = state->add<InitializedGlobalsSet>(VD);
1776 builder.generateNode(state, initHasRun, Pred);
1777 builder.markInfeasible(!initHasRun);
1779 currBldrCtx = nullptr;
1782 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
1783 /// nodes by processing the 'effects' of a computed goto jump.
1784 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1786 ProgramStateRef state = builder.getState();
1787 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1789 // Three possibilities:
1791 // (1) We know the computed label.
1792 // (2) The label is NULL (or some other constant), or Undefined.
1793 // (3) We have no clue about the label. Dispatch to all targets.
1796 typedef IndirectGotoNodeBuilder::iterator iterator;
1798 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1799 const LabelDecl *L = LV->getLabel();
1801 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1802 if (I.getLabel() == L) {
1803 builder.generateNode(I, state);
1808 llvm_unreachable("No block with label.");
1811 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1812 // Dispatch to the first target and mark it as a sink.
1813 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1814 // FIXME: add checker visit.
1815 // UndefBranches.insert(N);
1819 // This is really a catch-all. We don't support symbolics yet.
1820 // FIXME: Implement dispatch for symbolic pointers.
1822 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1823 builder.generateNode(I, state);
1827 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) {
1828 const StackFrameContext* Frame = Pred.getStackFrame();
1829 const llvm::ImmutableSet<CXXBindTemporaryContext> &Set =
1830 Pred.getState()->get<InitializedTemporariesSet>();
1831 return std::find_if(Set.begin(), Set.end(),
1832 [&](const CXXBindTemporaryContext &Ctx) {
1833 if (Ctx.second == Frame) {
1835 llvm::errs() << "\n";
1837 return Ctx.second == Frame;
1842 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
1844 ExplodedNodeSet &Dst,
1845 const BlockEdge &L) {
1846 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
1847 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
1850 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
1851 /// nodes when the control reaches the end of a function.
1852 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1854 const ReturnStmt *RS) {
1855 // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)).
1856 // We currently cannot enable this assert, as lifetime extended temporaries
1857 // are not modelled correctly.
1858 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1859 StateMgr.EndPath(Pred->getState());
1861 ExplodedNodeSet Dst;
1862 if (Pred->getLocationContext()->inTopFrame()) {
1863 // Remove dead symbols.
1864 ExplodedNodeSet AfterRemovedDead;
1865 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1868 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1869 E = AfterRemovedDead.end(); I != E; ++I) {
1870 getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1873 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1876 Engine.enqueueEndOfFunction(Dst, RS);
1879 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
1880 /// nodes by processing the 'effects' of a switch statement.
1881 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1882 typedef SwitchNodeBuilder::iterator iterator;
1883 ProgramStateRef state = builder.getState();
1884 const Expr *CondE = builder.getCondition();
1885 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1887 if (CondV_untested.isUndef()) {
1888 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1889 // FIXME: add checker
1890 //UndefBranches.insert(N);
1894 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1896 ProgramStateRef DefaultSt = state;
1898 iterator I = builder.begin(), EI = builder.end();
1899 bool defaultIsFeasible = I == EI;
1901 for ( ; I != EI; ++I) {
1902 // Successor may be pruned out during CFG construction.
1906 const CaseStmt *Case = I.getCase();
1908 // Evaluate the LHS of the case value.
1909 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1910 assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
1912 // Get the RHS of the case, if it exists.
1914 if (const Expr *E = Case->getRHS())
1915 V2 = E->EvaluateKnownConstInt(getContext());
1919 ProgramStateRef StateCase;
1920 if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
1921 std::tie(StateCase, DefaultSt) =
1922 DefaultSt->assumeInclusiveRange(*NL, V1, V2);
1924 StateCase = DefaultSt;
1927 builder.generateCaseStmtNode(I, StateCase);
1929 // Now "assume" that the case doesn't match. Add this state
1930 // to the default state (if it is feasible).
1932 defaultIsFeasible = true;
1934 defaultIsFeasible = false;
1939 if (!defaultIsFeasible)
1942 // If we have switch(enum value), the default branch is not
1943 // feasible if all of the enum constants not covered by 'case:' statements
1944 // are not feasible values for the switch condition.
1946 // Note that this isn't as accurate as it could be. Even if there isn't
1947 // a case for a particular enum value as long as that enum value isn't
1948 // feasible then it shouldn't be considered for making 'default:' reachable.
1949 const SwitchStmt *SS = builder.getSwitch();
1950 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1951 if (CondExpr->getType()->getAs<EnumType>()) {
1952 if (SS->isAllEnumCasesCovered())
1956 builder.generateDefaultCaseNode(DefaultSt);
1959 //===----------------------------------------------------------------------===//
1960 // Transfer functions: Loads and stores.
1961 //===----------------------------------------------------------------------===//
1963 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1965 ExplodedNodeSet &Dst) {
1966 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1968 ProgramStateRef state = Pred->getState();
1969 const LocationContext *LCtx = Pred->getLocationContext();
1971 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1972 // C permits "extern void v", and if you cast the address to a valid type,
1973 // you can even do things with it. We simply pretend
1974 assert(Ex->isGLValue() || VD->getType()->isVoidType());
1975 const LocationContext *LocCtxt = Pred->getLocationContext();
1976 const Decl *D = LocCtxt->getDecl();
1977 const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr;
1978 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
1981 if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
1982 DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
1983 MD->getParent()->isLambda()) {
1984 // Lookup the field of the lambda.
1985 const CXXRecordDecl *CXXRec = MD->getParent();
1986 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
1987 FieldDecl *LambdaThisCaptureField;
1988 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
1989 const FieldDecl *FD = LambdaCaptureFields[VD];
1991 // When a constant is captured, sometimes no corresponding field is
1992 // created in the lambda object.
1993 assert(VD->getType().isConstQualified());
1994 V = state->getLValue(VD, LocCtxt);
1995 IsReference = false;
1998 svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame());
1999 SVal CXXThisVal = state->getSVal(CXXThis);
2000 V = state->getLValue(FD, CXXThisVal);
2001 IsReference = FD->getType()->isReferenceType();
2004 V = state->getLValue(VD, LocCtxt);
2005 IsReference = VD->getType()->isReferenceType();
2008 // For references, the 'lvalue' is the pointer address stored in the
2009 // reference region.
2011 if (const MemRegion *R = V.getAsRegion())
2012 V = state->getSVal(R);
2017 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2018 ProgramPoint::PostLValueKind);
2021 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
2022 assert(!Ex->isGLValue());
2023 SVal V = svalBuilder.makeIntVal(ED->getInitVal());
2024 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
2027 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2028 SVal V = svalBuilder.getFunctionPointer(FD);
2029 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2030 ProgramPoint::PostLValueKind);
2033 if (isa<FieldDecl>(D)) {
2034 // FIXME: Compute lvalue of field pointers-to-member.
2035 // Right now we just use a non-null void pointer, so that it gives proper
2036 // results in boolean contexts.
2037 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
2038 currBldrCtx->blockCount());
2039 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
2040 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2041 ProgramPoint::PostLValueKind);
2045 llvm_unreachable("Support for this Decl not implemented.");
2048 /// VisitArraySubscriptExpr - Transfer function for array accesses
2049 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
2051 ExplodedNodeSet &Dst){
2053 const Expr *Base = A->getBase()->IgnoreParens();
2054 const Expr *Idx = A->getIdx()->IgnoreParens();
2056 ExplodedNodeSet CheckerPreStmt;
2057 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
2059 ExplodedNodeSet EvalSet;
2060 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
2061 assert(A->isGLValue() ||
2062 (!AMgr.getLangOpts().CPlusPlus &&
2063 A->getType().isCForbiddenLValueType()));
2065 for (auto *Node : CheckerPreStmt) {
2066 const LocationContext *LCtx = Node->getLocationContext();
2067 ProgramStateRef state = Node->getState();
2068 SVal V = state->getLValue(A->getType(),
2069 state->getSVal(Idx, LCtx),
2070 state->getSVal(Base, LCtx));
2071 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
2072 ProgramPoint::PostLValueKind);
2075 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
2078 /// VisitMemberExpr - Transfer function for member expressions.
2079 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
2080 ExplodedNodeSet &Dst) {
2082 // FIXME: Prechecks eventually go in ::Visit().
2083 ExplodedNodeSet CheckedSet;
2084 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
2086 ExplodedNodeSet EvalSet;
2087 ValueDecl *Member = M->getMemberDecl();
2089 // Handle static member variables and enum constants accessed via
2091 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2092 ExplodedNodeSet Dst;
2093 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2095 VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
2098 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2099 ExplodedNodeSet Tmp;
2101 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2103 ProgramStateRef state = (*I)->getState();
2104 const LocationContext *LCtx = (*I)->getLocationContext();
2105 Expr *BaseExpr = M->getBase();
2107 // Handle C++ method calls.
2108 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
2109 if (MD->isInstance())
2110 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2112 SVal MDVal = svalBuilder.getFunctionPointer(MD);
2113 state = state->BindExpr(M, LCtx, MDVal);
2115 Bldr.generateNode(M, *I, state);
2119 // Handle regular struct fields / member variables.
2120 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2121 SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
2123 FieldDecl *field = cast<FieldDecl>(Member);
2124 SVal L = state->getLValue(field, baseExprVal);
2126 if (M->isGLValue() || M->getType()->isArrayType()) {
2127 // We special-case rvalues of array type because the analyzer cannot
2128 // reason about them, since we expect all regions to be wrapped in Locs.
2129 // We instead treat these as lvalues and assume that they will decay to
2130 // pointers as soon as they are used.
2131 if (!M->isGLValue()) {
2132 assert(M->getType()->isArrayType());
2133 const ImplicitCastExpr *PE =
2134 dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParentIgnoreParens(M));
2135 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2136 llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2140 if (field->getType()->isReferenceType()) {
2141 if (const MemRegion *R = L.getAsRegion())
2142 L = state->getSVal(R);
2147 Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
2148 ProgramPoint::PostLValueKind);
2151 evalLoad(Tmp, M, M, *I, state, L);
2157 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2160 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
2161 ExplodedNodeSet &Dst) {
2162 ExplodedNodeSet AfterPreSet;
2163 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
2165 // For now, treat all the arguments to C11 atomics as escaping.
2166 // FIXME: Ideally we should model the behavior of the atomics precisely here.
2168 ExplodedNodeSet AfterInvalidateSet;
2169 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
2171 for (ExplodedNodeSet::iterator I = AfterPreSet.begin(), E = AfterPreSet.end();
2173 ProgramStateRef State = (*I)->getState();
2174 const LocationContext *LCtx = (*I)->getLocationContext();
2176 SmallVector<SVal, 8> ValuesToInvalidate;
2177 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
2178 const Expr *SubExpr = AE->getSubExprs()[SI];
2179 SVal SubExprVal = State->getSVal(SubExpr, LCtx);
2180 ValuesToInvalidate.push_back(SubExprVal);
2183 State = State->invalidateRegions(ValuesToInvalidate, AE,
2184 currBldrCtx->blockCount(),
2186 /*CausedByPointerEscape*/true,
2187 /*Symbols=*/nullptr);
2189 SVal ResultVal = UnknownVal();
2190 State = State->BindExpr(AE, LCtx, ResultVal);
2191 Bldr.generateNode(AE, *I, State, nullptr,
2192 ProgramPoint::PostStmtKind);
2195 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
2199 class CollectReachableSymbolsCallback final : public SymbolVisitor {
2200 InvalidatedSymbols Symbols;
2203 CollectReachableSymbolsCallback(ProgramStateRef State) {}
2204 const InvalidatedSymbols &getSymbols() const { return Symbols; }
2206 bool VisitSymbol(SymbolRef Sym) override {
2207 Symbols.insert(Sym);
2211 } // end anonymous namespace
2213 // A value escapes in three possible cases:
2214 // (1) We are binding to something that is not a memory region.
2215 // (2) We are binding to a MemrRegion that does not have stack storage.
2216 // (3) We are binding to a MemRegion with stack storage that the store
2217 // does not understand.
2218 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2221 const LocationContext *LCtx) {
2222 // Are we storing to something that causes the value to "escape"?
2223 bool escapes = true;
2225 // TODO: Move to StoreManager.
2226 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2227 escapes = !regionLoc->getRegion()->hasStackStorage();
2230 // To test (3), generate a new state with the binding added. If it is
2231 // the same state, then it escapes (since the store cannot represent
2233 // Do this only if we know that the store is not supposed to generate the
2235 SVal StoredVal = State->getSVal(regionLoc->getRegion());
2236 if (StoredVal != Val)
2237 escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
2241 // If our store can represent the binding and we aren't storing to something
2242 // that doesn't have local storage then just return and have the simulation
2243 // state continue as is.
2247 // Otherwise, find all symbols referenced by 'val' that we are tracking
2248 // and stop tracking them.
2249 CollectReachableSymbolsCallback Scanner =
2250 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
2251 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
2252 State = getCheckerManager().runCheckersForPointerEscape(State,
2254 /*CallEvent*/ nullptr,
2262 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2263 const InvalidatedSymbols *Invalidated,
2264 ArrayRef<const MemRegion *> ExplicitRegions,
2265 ArrayRef<const MemRegion *> Regions,
2266 const CallEvent *Call,
2267 RegionAndSymbolInvalidationTraits &ITraits) {
2269 if (!Invalidated || Invalidated->empty())
2273 return getCheckerManager().runCheckersForPointerEscape(State,
2279 // If the symbols were invalidated by a call, we want to find out which ones
2280 // were invalidated directly due to being arguments to the call.
2281 InvalidatedSymbols SymbolsDirectlyInvalidated;
2282 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
2283 E = ExplicitRegions.end(); I != E; ++I) {
2284 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
2285 SymbolsDirectlyInvalidated.insert(R->getSymbol());
2288 InvalidatedSymbols SymbolsIndirectlyInvalidated;
2289 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
2290 E = Invalidated->end(); I!=E; ++I) {
2292 if (SymbolsDirectlyInvalidated.count(sym))
2294 SymbolsIndirectlyInvalidated.insert(sym);
2297 if (!SymbolsDirectlyInvalidated.empty())
2298 State = getCheckerManager().runCheckersForPointerEscape(State,
2299 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2301 // Notify about the symbols that get indirectly invalidated by the call.
2302 if (!SymbolsIndirectlyInvalidated.empty())
2303 State = getCheckerManager().runCheckersForPointerEscape(State,
2304 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2309 /// evalBind - Handle the semantics of binding a value to a specific location.
2310 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
2311 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2313 SVal location, SVal Val,
2314 bool atDeclInit, const ProgramPoint *PP) {
2316 const LocationContext *LC = Pred->getLocationContext();
2317 PostStmt PS(StoreE, LC);
2321 // Do a previsit of the bind.
2322 ExplodedNodeSet CheckedSet;
2323 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2324 StoreE, *this, *PP);
2326 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2328 // If the location is not a 'Loc', it will already be handled by
2329 // the checkers. There is nothing left to do.
2330 if (!location.getAs<Loc>()) {
2331 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2333 ProgramStateRef state = Pred->getState();
2334 state = processPointerEscapedOnBind(state, location, Val, LC);
2335 Bldr.generateNode(L, state, Pred);
2339 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2341 ExplodedNode *PredI = *I;
2342 ProgramStateRef state = PredI->getState();
2344 state = processPointerEscapedOnBind(state, location, Val, LC);
2346 // When binding the value, pass on the hint that this is a initialization.
2347 // For initializations, we do not need to inform clients of region
2349 state = state->bindLoc(location.castAs<Loc>(),
2350 Val, LC, /* notifyChanges = */ !atDeclInit);
2352 const MemRegion *LocReg = nullptr;
2353 if (Optional<loc::MemRegionVal> LocRegVal =
2354 location.getAs<loc::MemRegionVal>()) {
2355 LocReg = LocRegVal->getRegion();
2358 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2359 Bldr.generateNode(L, state, PredI);
2363 /// evalStore - Handle the semantics of a store via an assignment.
2364 /// @param Dst The node set to store generated state nodes
2365 /// @param AssignE The assignment expression if the store happens in an
2367 /// @param LocationE The location expression that is stored to.
2368 /// @param state The current simulation state
2369 /// @param location The location to store the value
2370 /// @param Val The value to be stored
2371 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2372 const Expr *LocationE,
2374 ProgramStateRef state, SVal location, SVal Val,
2375 const ProgramPointTag *tag) {
2376 // Proceed with the store. We use AssignE as the anchor for the PostStore
2377 // ProgramPoint if it is non-NULL, and LocationE otherwise.
2378 const Expr *StoreE = AssignE ? AssignE : LocationE;
2380 // Evaluate the location (checks for bad dereferences).
2381 ExplodedNodeSet Tmp;
2382 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2387 if (location.isUndef())
2390 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2391 evalBind(Dst, StoreE, *NI, location, Val, false);
2394 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2396 const Expr *BoundEx,
2398 ProgramStateRef state,
2400 const ProgramPointTag *tag,
2403 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2405 // Are we loading from a region? This actually results in two loads; one
2406 // to fetch the address of the referenced value and one to fetch the
2407 // referenced value.
2408 if (const TypedValueRegion *TR =
2409 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2411 QualType ValTy = TR->getValueType();
2412 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2413 static SimpleProgramPointTag
2414 loadReferenceTag(TagProviderName, "Load Reference");
2415 ExplodedNodeSet Tmp;
2416 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2417 location, &loadReferenceTag,
2418 getContext().getPointerType(RT->getPointeeType()));
2420 // Perform the load from the referenced value.
2421 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2422 state = (*I)->getState();
2423 location = state->getSVal(BoundEx, (*I)->getLocationContext());
2424 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2430 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2433 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2435 const Expr *BoundEx,
2437 ProgramStateRef state,
2439 const ProgramPointTag *tag,
2443 // Evaluate the location (checks for bad dereferences).
2444 ExplodedNodeSet Tmp;
2445 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2449 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2450 if (location.isUndef())
2453 // Proceed with the load.
2454 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2455 state = (*NI)->getState();
2456 const LocationContext *LCtx = (*NI)->getLocationContext();
2458 SVal V = UnknownVal();
2459 if (location.isValid()) {
2460 if (LoadTy.isNull())
2461 LoadTy = BoundEx->getType();
2462 V = state->getSVal(location.castAs<Loc>(), LoadTy);
2465 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2466 ProgramPoint::PostLoadKind);
2470 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2472 const Stmt *BoundEx,
2474 ProgramStateRef state,
2476 const ProgramPointTag *tag,
2478 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2479 // Early checks for performance reason.
2480 if (location.isUnknown()) {
2484 ExplodedNodeSet Src;
2485 BldrTop.takeNodes(Pred);
2486 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2487 if (Pred->getState() != state) {
2488 // Associate this new state with an ExplodedNode.
2489 // FIXME: If I pass null tag, the graph is incorrect, e.g for
2493 // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2494 // instead "int *p" is noted as
2495 // "Variable 'p' initialized to a null pointer value"
2497 static SimpleProgramPointTag tag(TagProviderName, "Location");
2498 Bldr.generateNode(NodeEx, Pred, state, &tag);
2500 ExplodedNodeSet Tmp;
2501 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2502 NodeEx, BoundEx, *this);
2503 BldrTop.addNodes(Tmp);
2506 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2507 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2508 static SimpleProgramPointTag
2509 eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2510 "Eagerly Assume True"),
2511 eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2512 "Eagerly Assume False");
2513 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2514 &eagerlyAssumeBinOpBifurcationFalse);
2517 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2518 ExplodedNodeSet &Src,
2520 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2522 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2523 ExplodedNode *Pred = *I;
2524 // Test if the previous node was as the same expression. This can happen
2525 // when the expression fails to evaluate to anything meaningful and
2526 // (as an optimization) we don't generate a node.
2527 ProgramPoint P = Pred->getLocation();
2528 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2532 ProgramStateRef state = Pred->getState();
2533 SVal V = state->getSVal(Ex, Pred->getLocationContext());
2534 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2535 if (SEV && SEV->isExpression()) {
2536 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2537 geteagerlyAssumeBinOpBifurcationTags();
2539 ProgramStateRef StateTrue, StateFalse;
2540 std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2542 // First assume that the condition is true.
2544 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2545 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2546 Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2549 // Next, assume that the condition is false.
2551 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2552 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2553 Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2559 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2560 ExplodedNodeSet &Dst) {
2561 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2562 // We have processed both the inputs and the outputs. All of the outputs
2563 // should evaluate to Locs. Nuke all of their values.
2565 // FIXME: Some day in the future it would be nice to allow a "plug-in"
2566 // which interprets the inline asm and stores proper results in the
2569 ProgramStateRef state = Pred->getState();
2571 for (const Expr *O : A->outputs()) {
2572 SVal X = state->getSVal(O, Pred->getLocationContext());
2573 assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2575 if (Optional<Loc> LV = X.getAs<Loc>())
2576 state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
2579 Bldr.generateNode(A, Pred, state);
2582 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2583 ExplodedNodeSet &Dst) {
2584 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2585 Bldr.generateNode(A, Pred, Pred->getState());
2588 //===----------------------------------------------------------------------===//
2590 //===----------------------------------------------------------------------===//
2593 static ExprEngine* GraphPrintCheckerState;
2594 static SourceManager* GraphPrintSourceManager;
2598 struct DOTGraphTraits<ExplodedNode*> :
2599 public DefaultDOTGraphTraits {
2601 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2603 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2605 static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2609 // De-duplicate some source location pretty-printing.
2610 static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2611 if (SLoc.isFileID()) {
2613 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2615 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2619 static void printLocation2(raw_ostream &Out, SourceLocation SLoc) {
2620 if (SLoc.isFileID() && GraphPrintSourceManager->isInMainFile(SLoc))
2621 Out << "line " << GraphPrintSourceManager->getExpansionLineNumber(SLoc);
2623 SLoc.print(Out, *GraphPrintSourceManager);
2626 static std::string getNodeLabel(const ExplodedNode *N, void*){
2629 llvm::raw_string_ostream Out(sbuf);
2631 // Program Location.
2632 ProgramPoint Loc = N->getLocation();
2634 switch (Loc.getKind()) {
2635 case ProgramPoint::BlockEntranceKind: {
2636 Out << "Block Entrance: B"
2637 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2641 case ProgramPoint::BlockExitKind:
2645 case ProgramPoint::CallEnterKind:
2649 case ProgramPoint::CallExitBeginKind:
2650 Out << "CallExitBegin";
2653 case ProgramPoint::CallExitEndKind:
2654 Out << "CallExitEnd";
2657 case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2658 Out << "PostStmtPurgeDeadSymbols";
2661 case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2662 Out << "PreStmtPurgeDeadSymbols";
2665 case ProgramPoint::EpsilonKind:
2666 Out << "Epsilon Point";
2669 case ProgramPoint::PreImplicitCallKind: {
2670 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2673 // FIXME: Get proper printing options.
2674 PC.getDecl()->print(Out, LangOptions());
2675 printLocation(Out, PC.getLocation());
2679 case ProgramPoint::PostImplicitCallKind: {
2680 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2681 Out << "PostCall: ";
2683 // FIXME: Get proper printing options.
2684 PC.getDecl()->print(Out, LangOptions());
2685 printLocation(Out, PC.getLocation());
2689 case ProgramPoint::PostInitializerKind: {
2690 Out << "PostInitializer: ";
2691 const CXXCtorInitializer *Init =
2692 Loc.castAs<PostInitializer>().getInitializer();
2693 if (const FieldDecl *FD = Init->getAnyMember())
2696 QualType Ty = Init->getTypeSourceInfo()->getType();
2697 Ty = Ty.getLocalUnqualifiedType();
2698 LangOptions LO; // FIXME.
2704 case ProgramPoint::BlockEdgeKind: {
2705 const BlockEdge &E = Loc.castAs<BlockEdge>();
2706 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2707 << E.getDst()->getBlockID() << ')';
2709 if (const Stmt *T = E.getSrc()->getTerminator()) {
2710 SourceLocation SLoc = T->getLocStart();
2712 Out << "\\|Terminator: ";
2713 LangOptions LO; // FIXME.
2714 E.getSrc()->printTerminator(Out, LO);
2716 if (SLoc.isFileID()) {
2718 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2720 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2723 if (isa<SwitchStmt>(T)) {
2724 const Stmt *Label = E.getDst()->getLabel();
2727 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2729 LangOptions LO; // FIXME.
2731 C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
2733 if (const Stmt *RHS = C->getRHS()) {
2735 RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
2741 assert (isa<DefaultStmt>(Label));
2742 Out << "\\ldefault:";
2746 Out << "\\l(implicit) default:";
2748 else if (isa<IndirectGotoStmt>(T)) {
2752 Out << "\\lCondition: ";
2753 if (*E.getSrc()->succ_begin() == E.getDst())
2766 const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2767 assert(S != nullptr && "Expecting non-null Stmt");
2769 Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2770 LangOptions LO; // FIXME.
2771 S->printPretty(Out, nullptr, PrintingPolicy(LO));
2772 printLocation(Out, S->getLocStart());
2774 if (Loc.getAs<PreStmt>())
2775 Out << "\\lPreStmt\\l;";
2776 else if (Loc.getAs<PostLoad>())
2777 Out << "\\lPostLoad\\l;";
2778 else if (Loc.getAs<PostStore>())
2779 Out << "\\lPostStore\\l";
2780 else if (Loc.getAs<PostLValue>())
2781 Out << "\\lPostLValue\\l";
2787 ProgramStateRef state = N->getState();
2788 Out << "\\|StateID: " << (const void*) state.get()
2789 << " NodeID: " << (const void*) N << "\\|";
2791 // Analysis stack backtrace.
2792 Out << "Location context stack (from current to outer):\\l";
2793 const LocationContext *LC = Loc.getLocationContext();
2795 for (; LC; LC = LC->getParent(), ++Idx) {
2796 Out << Idx << ". (" << (const void *)LC << ") ";
2797 switch (LC->getKind()) {
2798 case LocationContext::StackFrame:
2799 if (const NamedDecl *D = dyn_cast<NamedDecl>(LC->getDecl()))
2800 Out << "Calling " << D->getQualifiedNameAsString();
2802 Out << "Calling anonymous code";
2803 if (const Stmt *S = cast<StackFrameContext>(LC)->getCallSite()) {
2805 printLocation2(Out, S->getLocStart());
2808 case LocationContext::Block:
2809 Out << "Invoking block";
2810 if (const Decl *D = cast<BlockInvocationContext>(LC)->getBlockDecl()) {
2811 Out << " defined at ";
2812 printLocation2(Out, D->getLocStart());
2815 case LocationContext::Scope:
2816 Out << "Entering scope";
2817 // FIXME: Add more info once ScopeContext is activated.
2824 state->printDOT(Out);
2828 if (const ProgramPointTag *tag = Loc.getTag()) {
2829 Out << "\\|Tag: " << tag->getTagDescription();
2835 } // end llvm namespace
2838 void ExprEngine::ViewGraph(bool trim) {
2841 std::vector<const ExplodedNode*> Src;
2843 // Flush any outstanding reports to make sure we cover all the nodes.
2844 // This does not cause them to get displayed.
2845 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2846 const_cast<BugType*>(*I)->FlushReports(BR);
2848 // Iterate through the reports and get their nodes.
2849 for (BugReporter::EQClasses_iterator
2850 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2851 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2852 if (N) Src.push_back(N);
2858 GraphPrintCheckerState = this;
2859 GraphPrintSourceManager = &getContext().getSourceManager();
2861 llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2863 GraphPrintCheckerState = nullptr;
2864 GraphPrintSourceManager = nullptr;
2869 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
2871 GraphPrintCheckerState = this;
2872 GraphPrintSourceManager = &getContext().getSourceManager();
2874 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2876 if (!TrimmedG.get())
2877 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2879 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2881 GraphPrintCheckerState = nullptr;
2882 GraphPrintSourceManager = nullptr;