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/Analysis/CFGStmtMap.h"
21 #include "clang/AST/StmtCXX.h"
22 #include "clang/AST/StmtObjC.h"
23 #include "clang/Basic/Builtins.h"
24 #include "clang/Basic/PrettyStackTrace.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
27 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/SaveAndRestore.h"
34 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Support/GraphWriter.h"
40 using namespace clang;
44 #define DEBUG_TYPE "ExprEngine"
46 STATISTIC(NumRemoveDeadBindings,
47 "The # of times RemoveDeadBindings is called");
48 STATISTIC(NumMaxBlockCountReached,
49 "The # of aborted paths due to reaching the maximum block count in "
50 "a top level function");
51 STATISTIC(NumMaxBlockCountReachedInInlined,
52 "The # of aborted paths due to reaching the maximum block count in "
53 "an inlined function");
54 STATISTIC(NumTimesRetriedWithoutInlining,
55 "The # of times we re-evaluated a call without inlining");
57 typedef std::pair<const CXXBindTemporaryExpr *, const StackFrameContext *>
58 CXXBindTemporaryContext;
60 // Keeps track of whether CXXBindTemporaryExpr nodes have been evaluated.
61 // The StackFrameContext assures that nested calls due to inlined recursive
62 // functions do not interfere.
63 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedTemporariesSet,
64 llvm::ImmutableSet<CXXBindTemporaryContext>)
66 //===----------------------------------------------------------------------===//
67 // Engine construction and deletion.
68 //===----------------------------------------------------------------------===//
70 static const char* TagProviderName = "ExprEngine";
72 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
73 SetOfConstDecls *VisitedCalleesIn,
74 FunctionSummariesTy *FS,
75 InliningModes HowToInlineIn)
77 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
80 StateMgr(getContext(), mgr.getStoreManagerCreator(),
81 mgr.getConstraintManagerCreator(), G.getAllocator(),
83 SymMgr(StateMgr.getSymbolManager()),
84 svalBuilder(StateMgr.getSValBuilder()),
85 currStmtIdx(0), currBldrCtx(nullptr),
86 ObjCNoRet(mgr.getASTContext()),
87 ObjCGCEnabled(gcEnabled), BR(mgr, *this),
88 VisitedCallees(VisitedCalleesIn),
89 HowToInline(HowToInlineIn)
91 unsigned TrimInterval = mgr.options.getGraphTrimInterval();
92 if (TrimInterval != 0) {
93 // Enable eager node reclaimation when constructing the ExplodedGraph.
94 G.enableNodeReclamation(TrimInterval);
98 ExprEngine::~ExprEngine() {
102 //===----------------------------------------------------------------------===//
104 //===----------------------------------------------------------------------===//
106 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
107 ProgramStateRef state = StateMgr.getInitialState(InitLoc);
108 const Decl *D = InitLoc->getDecl();
111 // FIXME: It would be nice if we had a more general mechanism to add
112 // such preconditions. Some day.
115 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
116 // Precondition: the first argument of 'main' is an integer guaranteed
118 const IdentifierInfo *II = FD->getIdentifier();
119 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
122 const ParmVarDecl *PD = FD->getParamDecl(0);
123 QualType T = PD->getType();
124 const BuiltinType *BT = dyn_cast<BuiltinType>(T);
125 if (!BT || !BT->isInteger())
128 const MemRegion *R = state->getRegion(PD, InitLoc);
132 SVal V = state->getSVal(loc::MemRegionVal(R));
133 SVal Constraint_untested = evalBinOp(state, BO_GT, V,
134 svalBuilder.makeZeroVal(T),
135 svalBuilder.getConditionType());
137 Optional<DefinedOrUnknownSVal> Constraint =
138 Constraint_untested.getAs<DefinedOrUnknownSVal>();
143 if (ProgramStateRef newState = state->assume(*Constraint, true))
150 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
151 // Precondition: 'self' is always non-null upon entry to an Objective-C
153 const ImplicitParamDecl *SelfD = MD->getSelfDecl();
154 const MemRegion *R = state->getRegion(SelfD, InitLoc);
155 SVal V = state->getSVal(loc::MemRegionVal(R));
157 if (Optional<Loc> LV = V.getAs<Loc>()) {
158 // Assume that the pointer value in 'self' is non-null.
159 state = state->assume(*LV, true);
160 assert(state && "'self' cannot be null");
164 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
165 if (!MD->isStatic()) {
166 // Precondition: 'this' is always non-null upon entry to the
167 // top-level function. This is our starting assumption for
168 // analyzing an "open" program.
169 const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
170 if (SFC->getParent() == nullptr) {
171 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
172 SVal V = state->getSVal(L);
173 if (Optional<Loc> LV = V.getAs<Loc>()) {
174 state = state->assume(*LV, true);
175 assert(state && "'this' cannot be null");
185 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
186 const LocationContext *LC,
187 const Expr *InitWithAdjustments,
188 const Expr *Result) {
189 // FIXME: This function is a hack that works around the quirky AST
190 // we're often having with respect to C++ temporaries. If only we modelled
191 // the actual execution order of statements properly in the CFG,
192 // all the hassle with adjustments would not be necessary,
193 // and perhaps the whole function would be removed.
194 SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
196 // If we don't have an explicit result expression, we're in "if needed"
197 // mode. Only create a region if the current value is a NonLoc.
198 if (!InitValWithAdjustments.getAs<NonLoc>())
200 Result = InitWithAdjustments;
202 // We need to create a region no matter what. For sanity, make sure we don't
203 // try to stuff a Loc into a non-pointer temporary region.
204 assert(!InitValWithAdjustments.getAs<Loc>() ||
205 Loc::isLocType(Result->getType()) ||
206 Result->getType()->isMemberPointerType());
209 ProgramStateManager &StateMgr = State->getStateManager();
210 MemRegionManager &MRMgr = StateMgr.getRegionManager();
211 StoreManager &StoreMgr = StateMgr.getStoreManager();
213 // MaterializeTemporaryExpr may appear out of place, after a few field and
214 // base-class accesses have been made to the object, even though semantically
215 // it is the whole object that gets materialized and lifetime-extended.
219 // `-MaterializeTemporaryExpr
221 // `-CXXTemporaryObjectExpr
223 // instead of the more natural
226 // `-MaterializeTemporaryExpr
227 // `-CXXTemporaryObjectExpr
229 // Use the usual methods for obtaining the expression of the base object,
230 // and record the adjustments that we need to make to obtain the sub-object
231 // that the whole expression 'Ex' refers to. This trick is usual,
232 // in the sense that CodeGen takes a similar route.
234 SmallVector<const Expr *, 2> CommaLHSs;
235 SmallVector<SubobjectAdjustment, 2> Adjustments;
237 const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
238 CommaLHSs, Adjustments);
240 const TypedValueRegion *TR = nullptr;
241 if (const MaterializeTemporaryExpr *MT =
242 dyn_cast<MaterializeTemporaryExpr>(Result)) {
243 StorageDuration SD = MT->getStorageDuration();
244 // If this object is bound to a reference with static storage duration, we
245 // put it in a different region to prevent "address leakage" warnings.
246 if (SD == SD_Static || SD == SD_Thread)
247 TR = MRMgr.getCXXStaticTempObjectRegion(Init);
250 TR = MRMgr.getCXXTempObjectRegion(Init, LC);
252 SVal Reg = loc::MemRegionVal(TR);
255 // Make the necessary adjustments to obtain the sub-object.
256 for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
257 const SubobjectAdjustment &Adj = *I;
259 case SubobjectAdjustment::DerivedToBaseAdjustment:
260 Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
262 case SubobjectAdjustment::FieldAdjustment:
263 Reg = StoreMgr.getLValueField(Adj.Field, Reg);
265 case SubobjectAdjustment::MemberPointerAdjustment:
266 // FIXME: Unimplemented.
267 State = State->bindDefault(Reg, UnknownVal(), LC);
272 // What remains is to copy the value of the object to the new region.
273 // FIXME: In other words, what we should always do is copy value of the
274 // Init expression (which corresponds to the bigger object) to the whole
275 // temporary region TR. However, this value is often no longer present
276 // in the Environment. If it has disappeared, we instead invalidate TR.
277 // Still, what we can do is assign the value of expression Ex (which
278 // corresponds to the sub-object) to the TR's sub-region Reg. At least,
279 // values inside Reg would be correct.
280 SVal InitVal = State->getSVal(Init, LC);
281 if (InitVal.isUnknown()) {
282 InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
283 currBldrCtx->blockCount());
284 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
286 // Then we'd need to take the value that certainly exists and bind it over.
287 if (InitValWithAdjustments.isUnknown()) {
288 // Try to recover some path sensitivity in case we couldn't
289 // compute the value.
290 InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
291 Result, LC, InitWithAdjustments->getType(),
292 currBldrCtx->blockCount());
295 State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
297 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
300 // The result expression would now point to the correct sub-region of the
301 // newly created temporary region. Do this last in order to getSVal of Init
302 // correctly in case (Result == Init).
303 State = State->BindExpr(Result, LC, Reg);
305 // Notify checkers once for two bindLoc()s.
306 State = processRegionChange(State, TR, LC);
311 //===----------------------------------------------------------------------===//
312 // Top-level transfer function logic (Dispatcher).
313 //===----------------------------------------------------------------------===//
315 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
316 /// logic for handling assumptions on symbolic values.
317 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
318 SVal cond, bool assumption) {
319 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
323 ExprEngine::processRegionChanges(ProgramStateRef state,
324 const InvalidatedSymbols *invalidated,
325 ArrayRef<const MemRegion *> Explicits,
326 ArrayRef<const MemRegion *> Regions,
327 const LocationContext *LCtx,
328 const CallEvent *Call) {
329 return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
334 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
335 const char *NL, const char *Sep) {
336 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
339 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
340 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
343 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
344 unsigned StmtIdx, NodeBuilderContext *Ctx) {
345 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
346 currStmtIdx = StmtIdx;
349 switch (E.getKind()) {
350 case CFGElement::Statement:
351 ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred);
353 case CFGElement::Initializer:
354 ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred);
356 case CFGElement::NewAllocator:
357 ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
360 case CFGElement::AutomaticObjectDtor:
361 case CFGElement::DeleteDtor:
362 case CFGElement::BaseDtor:
363 case CFGElement::MemberDtor:
364 case CFGElement::TemporaryDtor:
365 ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
367 case CFGElement::LoopExit:
368 ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
370 case CFGElement::LifetimeEnds:
375 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
377 const ExplodedNode *Pred,
378 const LocationContext *LC) {
380 // Are we never purging state values?
381 if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
384 // Is this the beginning of a basic block?
385 if (Pred->getLocation().getAs<BlockEntrance>())
388 // Is this on a non-expression?
389 if (!isa<Expr>(S.getStmt()))
392 // Run before processing a call.
393 if (CallEvent::isCallStmt(S.getStmt()))
396 // Is this an expression that is consumed by another expression? If so,
397 // postpone cleaning out the state.
398 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
399 return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
402 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
403 const Stmt *ReferenceStmt,
404 const LocationContext *LC,
405 const Stmt *DiagnosticStmt,
406 ProgramPoint::Kind K) {
407 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
408 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
409 && "PostStmt is not generally supported by the SymbolReaper yet");
410 assert(LC && "Must pass the current (or expiring) LocationContext");
412 if (!DiagnosticStmt) {
413 DiagnosticStmt = ReferenceStmt;
414 assert(DiagnosticStmt && "Required for clearing a LocationContext");
417 NumRemoveDeadBindings++;
418 ProgramStateRef CleanedState = Pred->getState();
420 // LC is the location context being destroyed, but SymbolReaper wants a
421 // location context that is still live. (If this is the top-level stack
422 // frame, this will be null.)
423 if (!ReferenceStmt) {
424 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
425 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
426 LC = LC->getParent();
429 const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : nullptr;
430 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
432 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
434 // Create a state in which dead bindings are removed from the environment
435 // and the store. TODO: The function should just return new env and store,
437 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
439 // Process any special transfer function for dead symbols.
440 // A tag to track convenience transitions, which can be removed at cleanup.
441 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
442 if (!SymReaper.hasDeadSymbols()) {
443 // Generate a CleanedNode that has the environment and store cleaned
444 // up. Since no symbols are dead, we can optimize and not clean out
445 // the constraint manager.
446 StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
447 Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
450 // Call checkers with the non-cleaned state so that they could query the
451 // values of the soon to be dead symbols.
452 ExplodedNodeSet CheckedSet;
453 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
454 DiagnosticStmt, *this, K);
456 // For each node in CheckedSet, generate CleanedNodes that have the
457 // environment, the store, and the constraints cleaned up but have the
458 // user-supplied states as the predecessors.
459 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
460 for (ExplodedNodeSet::const_iterator
461 I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
462 ProgramStateRef CheckerState = (*I)->getState();
464 // The constraint manager has not been cleaned up yet, so clean up now.
465 CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
468 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
469 "Checkers are not allowed to modify the Environment as a part of "
470 "checkDeadSymbols processing.");
471 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
472 "Checkers are not allowed to modify the Store as a part of "
473 "checkDeadSymbols processing.");
475 // Create a state based on CleanedState with CheckerState GDM and
476 // generate a transition to that state.
477 ProgramStateRef CleanedCheckerSt =
478 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
479 Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
484 void ExprEngine::ProcessStmt(const CFGStmt S,
485 ExplodedNode *Pred) {
486 // Reclaim any unnecessary nodes in the ExplodedGraph.
487 G.reclaimRecentlyAllocatedNodes();
489 const Stmt *currStmt = S.getStmt();
490 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
491 currStmt->getLocStart(),
492 "Error evaluating statement");
494 // Remove dead bindings and symbols.
495 ExplodedNodeSet CleanedStates;
496 if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
497 removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
499 CleanedStates.Add(Pred);
501 // Visit the statement.
503 for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
504 E = CleanedStates.end(); I != E; ++I) {
505 ExplodedNodeSet DstI;
506 // Visit the statement.
507 Visit(currStmt, *I, DstI);
511 // Enqueue the new nodes onto the work list.
512 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
515 void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) {
516 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
518 "Error evaluating end of the loop");
521 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
522 ProgramStateRef NewState = Pred->getState();
524 if(AMgr.options.shouldUnrollLoops())
525 NewState = processLoopEnd(S, NewState);
527 LoopExit PP(S, Pred->getLocationContext());
528 Bldr.generateNode(PP, NewState, Pred);
529 // Enqueue the new nodes onto the work list.
530 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
533 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
534 ExplodedNode *Pred) {
535 const CXXCtorInitializer *BMI = Init.getInitializer();
537 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
538 BMI->getSourceLocation(),
539 "Error evaluating initializer");
541 // We don't clean up dead bindings here.
542 const StackFrameContext *stackFrame =
543 cast<StackFrameContext>(Pred->getLocationContext());
544 const CXXConstructorDecl *decl =
545 cast<CXXConstructorDecl>(stackFrame->getDecl());
547 ProgramStateRef State = Pred->getState();
548 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
550 ExplodedNodeSet Tmp(Pred);
553 // Evaluate the initializer, if necessary
554 if (BMI->isAnyMemberInitializer()) {
555 // Constructors build the object directly in the field,
556 // but non-objects must be copied in from the initializer.
557 if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) {
558 assert(BMI->getInit()->IgnoreImplicit() == CtorExpr);
560 // The field was directly constructed, so there is no need to bind.
562 const Expr *Init = BMI->getInit()->IgnoreImplicit();
563 const ValueDecl *Field;
564 if (BMI->isIndirectMemberInitializer()) {
565 Field = BMI->getIndirectMember();
566 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
568 Field = BMI->getMember();
569 FieldLoc = State->getLValue(BMI->getMember(), thisVal);
573 if (Init->getType()->isArrayType()) {
574 // Handle arrays of trivial type. We can represent this with a
575 // primitive load/copy from the base array region.
576 const ArraySubscriptExpr *ASE;
577 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
578 Init = ASE->getBase()->IgnoreImplicit();
580 SVal LValue = State->getSVal(Init, stackFrame);
581 if (!Field->getType()->isReferenceType())
582 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
583 InitVal = State->getSVal(*LValueLoc);
585 // If we fail to get the value for some reason, use a symbolic value.
586 if (InitVal.isUnknownOrUndef()) {
587 SValBuilder &SVB = getSValBuilder();
588 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
590 currBldrCtx->blockCount());
593 InitVal = State->getSVal(BMI->getInit(), stackFrame);
596 assert(Tmp.size() == 1 && "have not generated any new nodes yet");
597 assert(*Tmp.begin() == Pred && "have not generated any new nodes yet");
600 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
601 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
604 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
605 // We already did all the work when visiting the CXXConstructExpr.
608 // Construct PostInitializer nodes whether the state changed or not,
609 // so that the diagnostics don't get confused.
610 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
612 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
613 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
614 ExplodedNode *N = *I;
615 Bldr.generateNode(PP, N->getState(), N);
618 // Enqueue the new nodes onto the work list.
619 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
622 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
623 ExplodedNode *Pred) {
625 switch (D.getKind()) {
626 case CFGElement::AutomaticObjectDtor:
627 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
629 case CFGElement::BaseDtor:
630 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
632 case CFGElement::MemberDtor:
633 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
635 case CFGElement::TemporaryDtor:
636 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
638 case CFGElement::DeleteDtor:
639 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
642 llvm_unreachable("Unexpected dtor kind.");
645 // Enqueue the new nodes onto the work list.
646 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
649 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
650 ExplodedNode *Pred) {
652 AnalysisManager &AMgr = getAnalysisManager();
653 AnalyzerOptions &Opts = AMgr.options;
654 // TODO: We're not evaluating allocators for all cases just yet as
655 // we're not handling the return value correctly, which causes false
656 // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
657 if (Opts.mayInlineCXXAllocator())
658 VisitCXXNewAllocatorCall(NE, Pred, Dst);
660 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
661 const LocationContext *LCtx = Pred->getLocationContext();
662 PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
663 Bldr.generateNode(PP, Pred->getState(), Pred);
665 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
668 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
670 ExplodedNodeSet &Dst) {
671 const VarDecl *varDecl = Dtor.getVarDecl();
672 QualType varType = varDecl->getType();
674 ProgramStateRef state = Pred->getState();
675 SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
676 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
678 if (varType->isReferenceType()) {
679 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
681 // FIXME: This should not happen. The language guarantees a presence
682 // of a valid initializer here, so the reference shall not be undefined.
683 // It seems that we're calling destructors over variables that
684 // were not initialized yet.
687 Region = ValueRegion->getBaseRegion();
688 varType = cast<TypedValueRegion>(Region)->getValueType();
691 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
695 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
697 ExplodedNodeSet &Dst) {
698 ProgramStateRef State = Pred->getState();
699 const LocationContext *LCtx = Pred->getLocationContext();
700 const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
701 const Stmt *Arg = DE->getArgument();
702 SVal ArgVal = State->getSVal(Arg, LCtx);
704 // If the argument to delete is known to be a null value,
705 // don't run destructor.
706 if (State->isNull(ArgVal).isConstrainedTrue()) {
707 QualType DTy = DE->getDestroyedType();
708 QualType BTy = getContext().getBaseElementType(DTy);
709 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
710 const CXXDestructorDecl *Dtor = RD->getDestructor();
712 PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
713 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
714 Bldr.generateNode(PP, Pred->getState(), Pred);
718 VisitCXXDestructor(DE->getDestroyedType(),
719 ArgVal.getAsRegion(),
720 DE, /*IsBase=*/ false,
724 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
725 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
726 const LocationContext *LCtx = Pred->getLocationContext();
728 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
729 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
730 LCtx->getCurrentStackFrame());
731 SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
733 // Create the base object region.
734 const CXXBaseSpecifier *Base = D.getBaseSpecifier();
735 QualType BaseTy = Base->getType();
736 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
739 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
740 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst);
743 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
744 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
745 const FieldDecl *Member = D.getFieldDecl();
746 ProgramStateRef State = Pred->getState();
747 const LocationContext *LCtx = Pred->getLocationContext();
749 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
750 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
751 LCtx->getCurrentStackFrame());
753 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
755 VisitCXXDestructor(Member->getType(),
756 FieldVal.castAs<loc::MemRegionVal>().getRegion(),
757 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
760 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
762 ExplodedNodeSet &Dst) {
763 ExplodedNodeSet CleanDtorState;
764 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
765 ProgramStateRef State = Pred->getState();
766 if (State->contains<InitializedTemporariesSet>(
767 std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()))) {
768 // FIXME: Currently we insert temporary destructors for default parameters,
769 // but we don't insert the constructors.
770 State = State->remove<InitializedTemporariesSet>(
771 std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()));
773 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
775 QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType();
776 // FIXME: Currently CleanDtorState can be empty here due to temporaries being
777 // bound to default parameters.
778 assert(CleanDtorState.size() <= 1);
779 ExplodedNode *CleanPred =
780 CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
781 // FIXME: Inlining of temporary destructors is not supported yet anyway, so
782 // we just put a NULL region for now. This will need to be changed later.
783 VisitCXXDestructor(varType, nullptr, D.getBindTemporaryExpr(),
784 /*IsBase=*/false, CleanPred, Dst);
787 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
788 NodeBuilderContext &BldCtx,
790 ExplodedNodeSet &Dst,
791 const CFGBlock *DstT,
792 const CFGBlock *DstF) {
793 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
794 if (Pred->getState()->contains<InitializedTemporariesSet>(
795 std::make_pair(BTE, Pred->getStackFrame()))) {
796 TempDtorBuilder.markInfeasible(false);
797 TempDtorBuilder.generateNode(Pred->getState(), true, Pred);
799 TempDtorBuilder.markInfeasible(true);
800 TempDtorBuilder.generateNode(Pred->getState(), false, Pred);
804 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
805 ExplodedNodeSet &PreVisit,
806 ExplodedNodeSet &Dst) {
807 if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
808 // In case we don't have temporary destructors in the CFG, do not mark
809 // the initialization - we would otherwise never clean it up.
813 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
814 for (ExplodedNode *Node : PreVisit) {
815 ProgramStateRef State = Node->getState();
817 if (!State->contains<InitializedTemporariesSet>(
818 std::make_pair(BTE, Node->getStackFrame()))) {
819 // FIXME: Currently the state might already contain the marker due to
820 // incorrect handling of temporaries bound to default parameters; for
821 // those, we currently skip the CXXBindTemporaryExpr but rely on adding
822 // temporary destructor nodes.
823 State = State->add<InitializedTemporariesSet>(
824 std::make_pair(BTE, Node->getStackFrame()));
826 StmtBldr.generateNode(BTE, Node, State);
831 class CollectReachableSymbolsCallback final : public SymbolVisitor {
832 InvalidatedSymbols Symbols;
835 explicit CollectReachableSymbolsCallback(ProgramStateRef State) {}
836 const InvalidatedSymbols &getSymbols() const { return Symbols; }
838 bool VisitSymbol(SymbolRef Sym) override {
843 } // end anonymous namespace
845 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
846 ExplodedNodeSet &DstTop) {
847 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
849 "Error evaluating statement");
851 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
853 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
855 switch (S->getStmtClass()) {
856 // C++, OpenMP and ARC stuff we don't support yet.
857 case Expr::ObjCIndirectCopyRestoreExprClass:
858 case Stmt::CXXDependentScopeMemberExprClass:
859 case Stmt::CXXInheritedCtorInitExprClass:
860 case Stmt::CXXTryStmtClass:
861 case Stmt::CXXTypeidExprClass:
862 case Stmt::CXXUuidofExprClass:
863 case Stmt::CXXFoldExprClass:
864 case Stmt::MSPropertyRefExprClass:
865 case Stmt::MSPropertySubscriptExprClass:
866 case Stmt::CXXUnresolvedConstructExprClass:
867 case Stmt::DependentScopeDeclRefExprClass:
868 case Stmt::ArrayTypeTraitExprClass:
869 case Stmt::ExpressionTraitExprClass:
870 case Stmt::UnresolvedLookupExprClass:
871 case Stmt::UnresolvedMemberExprClass:
872 case Stmt::TypoExprClass:
873 case Stmt::CXXNoexceptExprClass:
874 case Stmt::PackExpansionExprClass:
875 case Stmt::SubstNonTypeTemplateParmPackExprClass:
876 case Stmt::FunctionParmPackExprClass:
877 case Stmt::CoroutineBodyStmtClass:
878 case Stmt::CoawaitExprClass:
879 case Stmt::DependentCoawaitExprClass:
880 case Stmt::CoreturnStmtClass:
881 case Stmt::CoyieldExprClass:
882 case Stmt::SEHTryStmtClass:
883 case Stmt::SEHExceptStmtClass:
884 case Stmt::SEHLeaveStmtClass:
885 case Stmt::SEHFinallyStmtClass:
886 case Stmt::OMPParallelDirectiveClass:
887 case Stmt::OMPSimdDirectiveClass:
888 case Stmt::OMPForDirectiveClass:
889 case Stmt::OMPForSimdDirectiveClass:
890 case Stmt::OMPSectionsDirectiveClass:
891 case Stmt::OMPSectionDirectiveClass:
892 case Stmt::OMPSingleDirectiveClass:
893 case Stmt::OMPMasterDirectiveClass:
894 case Stmt::OMPCriticalDirectiveClass:
895 case Stmt::OMPParallelForDirectiveClass:
896 case Stmt::OMPParallelForSimdDirectiveClass:
897 case Stmt::OMPParallelSectionsDirectiveClass:
898 case Stmt::OMPTaskDirectiveClass:
899 case Stmt::OMPTaskyieldDirectiveClass:
900 case Stmt::OMPBarrierDirectiveClass:
901 case Stmt::OMPTaskwaitDirectiveClass:
902 case Stmt::OMPTaskgroupDirectiveClass:
903 case Stmt::OMPFlushDirectiveClass:
904 case Stmt::OMPOrderedDirectiveClass:
905 case Stmt::OMPAtomicDirectiveClass:
906 case Stmt::OMPTargetDirectiveClass:
907 case Stmt::OMPTargetDataDirectiveClass:
908 case Stmt::OMPTargetEnterDataDirectiveClass:
909 case Stmt::OMPTargetExitDataDirectiveClass:
910 case Stmt::OMPTargetParallelDirectiveClass:
911 case Stmt::OMPTargetParallelForDirectiveClass:
912 case Stmt::OMPTargetUpdateDirectiveClass:
913 case Stmt::OMPTeamsDirectiveClass:
914 case Stmt::OMPCancellationPointDirectiveClass:
915 case Stmt::OMPCancelDirectiveClass:
916 case Stmt::OMPTaskLoopDirectiveClass:
917 case Stmt::OMPTaskLoopSimdDirectiveClass:
918 case Stmt::OMPDistributeDirectiveClass:
919 case Stmt::OMPDistributeParallelForDirectiveClass:
920 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
921 case Stmt::OMPDistributeSimdDirectiveClass:
922 case Stmt::OMPTargetParallelForSimdDirectiveClass:
923 case Stmt::OMPTargetSimdDirectiveClass:
924 case Stmt::OMPTeamsDistributeDirectiveClass:
925 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
926 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
927 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
928 case Stmt::OMPTargetTeamsDirectiveClass:
929 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
930 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
931 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
932 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
933 case Stmt::CapturedStmtClass:
935 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
936 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
940 case Stmt::ParenExprClass:
941 llvm_unreachable("ParenExprs already handled.");
942 case Stmt::GenericSelectionExprClass:
943 llvm_unreachable("GenericSelectionExprs already handled.");
944 // Cases that should never be evaluated simply because they shouldn't
945 // appear in the CFG.
946 case Stmt::BreakStmtClass:
947 case Stmt::CaseStmtClass:
948 case Stmt::CompoundStmtClass:
949 case Stmt::ContinueStmtClass:
950 case Stmt::CXXForRangeStmtClass:
951 case Stmt::DefaultStmtClass:
952 case Stmt::DoStmtClass:
953 case Stmt::ForStmtClass:
954 case Stmt::GotoStmtClass:
955 case Stmt::IfStmtClass:
956 case Stmt::IndirectGotoStmtClass:
957 case Stmt::LabelStmtClass:
958 case Stmt::NoStmtClass:
959 case Stmt::NullStmtClass:
960 case Stmt::SwitchStmtClass:
961 case Stmt::WhileStmtClass:
962 case Expr::MSDependentExistsStmtClass:
963 llvm_unreachable("Stmt should not be in analyzer evaluation loop");
965 case Stmt::ObjCSubscriptRefExprClass:
966 case Stmt::ObjCPropertyRefExprClass:
967 llvm_unreachable("These are handled by PseudoObjectExpr");
969 case Stmt::GNUNullExprClass: {
970 // GNU __null is a pointer-width integer, not an actual pointer.
971 ProgramStateRef state = Pred->getState();
972 state = state->BindExpr(S, Pred->getLocationContext(),
973 svalBuilder.makeIntValWithPtrWidth(0, false));
974 Bldr.generateNode(S, Pred, state);
978 case Stmt::ObjCAtSynchronizedStmtClass:
979 Bldr.takeNodes(Pred);
980 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
984 case Stmt::ExprWithCleanupsClass:
985 // Handled due to fully linearised CFG.
988 case Stmt::CXXBindTemporaryExprClass: {
989 Bldr.takeNodes(Pred);
990 ExplodedNodeSet PreVisit;
991 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
992 ExplodedNodeSet Next;
993 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
994 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
999 // Cases not handled yet; but will handle some day.
1000 case Stmt::DesignatedInitExprClass:
1001 case Stmt::DesignatedInitUpdateExprClass:
1002 case Stmt::ArrayInitLoopExprClass:
1003 case Stmt::ArrayInitIndexExprClass:
1004 case Stmt::ExtVectorElementExprClass:
1005 case Stmt::ImaginaryLiteralClass:
1006 case Stmt::ObjCAtCatchStmtClass:
1007 case Stmt::ObjCAtFinallyStmtClass:
1008 case Stmt::ObjCAtTryStmtClass:
1009 case Stmt::ObjCAutoreleasePoolStmtClass:
1010 case Stmt::ObjCEncodeExprClass:
1011 case Stmt::ObjCIsaExprClass:
1012 case Stmt::ObjCProtocolExprClass:
1013 case Stmt::ObjCSelectorExprClass:
1014 case Stmt::ParenListExprClass:
1015 case Stmt::ShuffleVectorExprClass:
1016 case Stmt::ConvertVectorExprClass:
1017 case Stmt::VAArgExprClass:
1018 case Stmt::CUDAKernelCallExprClass:
1019 case Stmt::OpaqueValueExprClass:
1020 case Stmt::AsTypeExprClass:
1023 // Cases we intentionally don't evaluate, since they don't need
1024 // to be explicitly evaluated.
1025 case Stmt::PredefinedExprClass:
1026 case Stmt::AddrLabelExprClass:
1027 case Stmt::AttributedStmtClass:
1028 case Stmt::IntegerLiteralClass:
1029 case Stmt::CharacterLiteralClass:
1030 case Stmt::ImplicitValueInitExprClass:
1031 case Stmt::CXXScalarValueInitExprClass:
1032 case Stmt::CXXBoolLiteralExprClass:
1033 case Stmt::ObjCBoolLiteralExprClass:
1034 case Stmt::ObjCAvailabilityCheckExprClass:
1035 case Stmt::FloatingLiteralClass:
1036 case Stmt::NoInitExprClass:
1037 case Stmt::SizeOfPackExprClass:
1038 case Stmt::StringLiteralClass:
1039 case Stmt::ObjCStringLiteralClass:
1040 case Stmt::CXXPseudoDestructorExprClass:
1041 case Stmt::SubstNonTypeTemplateParmExprClass:
1042 case Stmt::CXXNullPtrLiteralExprClass:
1043 case Stmt::OMPArraySectionExprClass:
1044 case Stmt::TypeTraitExprClass: {
1045 Bldr.takeNodes(Pred);
1046 ExplodedNodeSet preVisit;
1047 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1048 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
1053 case Stmt::CXXDefaultArgExprClass:
1054 case Stmt::CXXDefaultInitExprClass: {
1055 Bldr.takeNodes(Pred);
1056 ExplodedNodeSet PreVisit;
1057 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1059 ExplodedNodeSet Tmp;
1060 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
1063 if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
1064 ArgE = DefE->getExpr();
1065 else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
1066 ArgE = DefE->getExpr();
1068 llvm_unreachable("unknown constant wrapper kind");
1070 bool IsTemporary = false;
1071 if (const MaterializeTemporaryExpr *MTE =
1072 dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
1073 ArgE = MTE->GetTemporaryExpr();
1077 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
1079 ConstantVal = UnknownVal();
1081 const LocationContext *LCtx = Pred->getLocationContext();
1082 for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
1084 ProgramStateRef State = (*I)->getState();
1085 State = State->BindExpr(S, LCtx, *ConstantVal);
1087 State = createTemporaryRegionIfNeeded(State, LCtx,
1090 Bldr2.generateNode(S, *I, State);
1093 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1098 // Cases we evaluate as opaque expressions, conjuring a symbol.
1099 case Stmt::CXXStdInitializerListExprClass:
1100 case Expr::ObjCArrayLiteralClass:
1101 case Expr::ObjCDictionaryLiteralClass:
1102 case Expr::ObjCBoxedExprClass: {
1103 Bldr.takeNodes(Pred);
1105 ExplodedNodeSet preVisit;
1106 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1108 ExplodedNodeSet Tmp;
1109 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
1111 const Expr *Ex = cast<Expr>(S);
1112 QualType resultType = Ex->getType();
1114 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
1116 ExplodedNode *N = *it;
1117 const LocationContext *LCtx = N->getLocationContext();
1118 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1120 currBldrCtx->blockCount());
1121 ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
1123 // Escape pointers passed into the list, unless it's an ObjC boxed
1124 // expression which is not a boxable C structure.
1125 if (!(isa<ObjCBoxedExpr>(Ex) &&
1126 !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
1127 ->getType()->isRecordType()))
1128 for (auto Child : Ex->children()) {
1131 SVal Val = State->getSVal(Child, LCtx);
1133 CollectReachableSymbolsCallback Scanner =
1134 State->scanReachableSymbols<CollectReachableSymbolsCallback>(
1136 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
1138 State = getCheckerManager().runCheckersForPointerEscape(
1139 State, EscapedSymbols,
1140 /*CallEvent*/ nullptr, PSK_EscapeOther, nullptr);
1143 Bldr2.generateNode(S, N, State);
1146 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1151 case Stmt::ArraySubscriptExprClass:
1152 Bldr.takeNodes(Pred);
1153 VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1157 case Stmt::GCCAsmStmtClass:
1158 Bldr.takeNodes(Pred);
1159 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1163 case Stmt::MSAsmStmtClass:
1164 Bldr.takeNodes(Pred);
1165 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1169 case Stmt::BlockExprClass:
1170 Bldr.takeNodes(Pred);
1171 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1175 case Stmt::LambdaExprClass:
1176 if (AMgr.options.shouldInlineLambdas()) {
1177 Bldr.takeNodes(Pred);
1178 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1181 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1182 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1186 case Stmt::BinaryOperatorClass: {
1187 const BinaryOperator* B = cast<BinaryOperator>(S);
1188 if (B->isLogicalOp()) {
1189 Bldr.takeNodes(Pred);
1190 VisitLogicalExpr(B, Pred, Dst);
1194 else if (B->getOpcode() == BO_Comma) {
1195 ProgramStateRef state = Pred->getState();
1196 Bldr.generateNode(B, Pred,
1197 state->BindExpr(B, Pred->getLocationContext(),
1198 state->getSVal(B->getRHS(),
1199 Pred->getLocationContext())));
1203 Bldr.takeNodes(Pred);
1205 if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
1206 (B->isRelationalOp() || B->isEqualityOp())) {
1207 ExplodedNodeSet Tmp;
1208 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1209 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1212 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1218 case Stmt::CXXOperatorCallExprClass: {
1219 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
1221 // For instance method operators, make sure the 'this' argument has a
1223 const Decl *Callee = OCE->getCalleeDecl();
1224 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1225 if (MD->isInstance()) {
1226 ProgramStateRef State = Pred->getState();
1227 const LocationContext *LCtx = Pred->getLocationContext();
1228 ProgramStateRef NewState =
1229 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1230 if (NewState != State) {
1231 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1232 ProgramPoint::PreStmtKind);
1233 // Did we cache out?
1242 case Stmt::CallExprClass:
1243 case Stmt::CXXMemberCallExprClass:
1244 case Stmt::UserDefinedLiteralClass: {
1245 Bldr.takeNodes(Pred);
1246 VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1251 case Stmt::CXXCatchStmtClass: {
1252 Bldr.takeNodes(Pred);
1253 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1258 case Stmt::CXXTemporaryObjectExprClass:
1259 case Stmt::CXXConstructExprClass: {
1260 Bldr.takeNodes(Pred);
1261 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1266 case Stmt::CXXNewExprClass: {
1267 Bldr.takeNodes(Pred);
1268 ExplodedNodeSet PostVisit;
1269 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
1270 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1275 case Stmt::CXXDeleteExprClass: {
1276 Bldr.takeNodes(Pred);
1277 ExplodedNodeSet PreVisit;
1278 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
1279 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1281 for (ExplodedNodeSet::iterator i = PreVisit.begin(),
1282 e = PreVisit.end(); i != e ; ++i)
1283 VisitCXXDeleteExpr(CDE, *i, Dst);
1288 // FIXME: ChooseExpr is really a constant. We need to fix
1289 // the CFG do not model them as explicit control-flow.
1291 case Stmt::ChooseExprClass: { // __builtin_choose_expr
1292 Bldr.takeNodes(Pred);
1293 const ChooseExpr *C = cast<ChooseExpr>(S);
1294 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1299 case Stmt::CompoundAssignOperatorClass:
1300 Bldr.takeNodes(Pred);
1301 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1305 case Stmt::CompoundLiteralExprClass:
1306 Bldr.takeNodes(Pred);
1307 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1311 case Stmt::BinaryConditionalOperatorClass:
1312 case Stmt::ConditionalOperatorClass: { // '?' operator
1313 Bldr.takeNodes(Pred);
1314 const AbstractConditionalOperator *C
1315 = cast<AbstractConditionalOperator>(S);
1316 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1321 case Stmt::CXXThisExprClass:
1322 Bldr.takeNodes(Pred);
1323 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1327 case Stmt::DeclRefExprClass: {
1328 Bldr.takeNodes(Pred);
1329 const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1330 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1335 case Stmt::DeclStmtClass:
1336 Bldr.takeNodes(Pred);
1337 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1341 case Stmt::ImplicitCastExprClass:
1342 case Stmt::CStyleCastExprClass:
1343 case Stmt::CXXStaticCastExprClass:
1344 case Stmt::CXXDynamicCastExprClass:
1345 case Stmt::CXXReinterpretCastExprClass:
1346 case Stmt::CXXConstCastExprClass:
1347 case Stmt::CXXFunctionalCastExprClass:
1348 case Stmt::ObjCBridgedCastExprClass: {
1349 Bldr.takeNodes(Pred);
1350 const CastExpr *C = cast<CastExpr>(S);
1351 ExplodedNodeSet dstExpr;
1352 VisitCast(C, C->getSubExpr(), Pred, dstExpr);
1354 // Handle the postvisit checks.
1355 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1360 case Expr::MaterializeTemporaryExprClass: {
1361 Bldr.takeNodes(Pred);
1362 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1363 ExplodedNodeSet dstPrevisit;
1364 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
1365 ExplodedNodeSet dstExpr;
1366 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1367 e = dstPrevisit.end(); i != e ; ++i) {
1368 CreateCXXTemporaryObject(MTE, *i, dstExpr);
1370 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
1375 case Stmt::InitListExprClass:
1376 Bldr.takeNodes(Pred);
1377 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1381 case Stmt::MemberExprClass:
1382 Bldr.takeNodes(Pred);
1383 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1387 case Stmt::AtomicExprClass:
1388 Bldr.takeNodes(Pred);
1389 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
1393 case Stmt::ObjCIvarRefExprClass:
1394 Bldr.takeNodes(Pred);
1395 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1399 case Stmt::ObjCForCollectionStmtClass:
1400 Bldr.takeNodes(Pred);
1401 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1405 case Stmt::ObjCMessageExprClass:
1406 Bldr.takeNodes(Pred);
1407 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1411 case Stmt::ObjCAtThrowStmtClass:
1412 case Stmt::CXXThrowExprClass:
1413 // FIXME: This is not complete. We basically treat @throw as
1415 Bldr.generateSink(S, Pred, Pred->getState());
1418 case Stmt::ReturnStmtClass:
1419 Bldr.takeNodes(Pred);
1420 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1424 case Stmt::OffsetOfExprClass:
1425 Bldr.takeNodes(Pred);
1426 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1430 case Stmt::UnaryExprOrTypeTraitExprClass:
1431 Bldr.takeNodes(Pred);
1432 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1437 case Stmt::StmtExprClass: {
1438 const StmtExpr *SE = cast<StmtExpr>(S);
1440 if (SE->getSubStmt()->body_empty()) {
1441 // Empty statement expression.
1442 assert(SE->getType() == getContext().VoidTy
1443 && "Empty statement expression must have void type.");
1447 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1448 ProgramStateRef state = Pred->getState();
1449 Bldr.generateNode(SE, Pred,
1450 state->BindExpr(SE, Pred->getLocationContext(),
1451 state->getSVal(LastExpr,
1452 Pred->getLocationContext())));
1457 case Stmt::UnaryOperatorClass: {
1458 Bldr.takeNodes(Pred);
1459 const UnaryOperator *U = cast<UnaryOperator>(S);
1460 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1461 ExplodedNodeSet Tmp;
1462 VisitUnaryOperator(U, Pred, Tmp);
1463 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1466 VisitUnaryOperator(U, Pred, Dst);
1471 case Stmt::PseudoObjectExprClass: {
1472 Bldr.takeNodes(Pred);
1473 ProgramStateRef state = Pred->getState();
1474 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1475 if (const Expr *Result = PE->getResultExpr()) {
1476 SVal V = state->getSVal(Result, Pred->getLocationContext());
1477 Bldr.generateNode(S, Pred,
1478 state->BindExpr(S, Pred->getLocationContext(), V));
1481 Bldr.generateNode(S, Pred,
1482 state->BindExpr(S, Pred->getLocationContext(),
1491 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1492 const LocationContext *CalleeLC) {
1493 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1494 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1495 assert(CalleeSF && CallerSF);
1496 ExplodedNode *BeforeProcessingCall = nullptr;
1497 const Stmt *CE = CalleeSF->getCallSite();
1499 // Find the first node before we started processing the call expression.
1501 ProgramPoint L = N->getLocation();
1502 BeforeProcessingCall = N;
1503 N = N->pred_empty() ? nullptr : *(N->pred_begin());
1505 // Skip the nodes corresponding to the inlined code.
1506 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1508 // We reached the caller. Find the node right before we started
1509 // processing the call.
1510 if (L.isPurgeKind())
1512 if (L.getAs<PreImplicitCall>())
1514 if (L.getAs<CallEnter>())
1516 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1517 if (SP->getStmt() == CE)
1522 if (!BeforeProcessingCall)
1525 // TODO: Clean up the unneeded nodes.
1527 // Build an Epsilon node from which we will restart the analyzes.
1528 // Note that CE is permitted to be NULL!
1529 ProgramPoint NewNodeLoc =
1530 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1531 // Add the special flag to GDM to signal retrying with no inlining.
1532 // Note, changing the state ensures that we are not going to cache out.
1533 ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1535 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1537 // Make the new node a successor of BeforeProcessingCall.
1539 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1540 // We cached out at this point. Caching out is common due to us backtracking
1541 // from the inlined function, which might spawn several paths.
1545 NewNode->addPredecessor(BeforeProcessingCall, G);
1547 // Add the new node to the work list.
1548 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1549 CalleeSF->getIndex());
1550 NumTimesRetriedWithoutInlining++;
1554 /// Block entrance. (Update counters).
1555 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1556 NodeBuilderWithSinks &nodeBuilder,
1557 ExplodedNode *Pred) {
1558 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1559 // If we reach a loop which has a known bound (and meets
1560 // other constraints) then consider completely unrolling it.
1561 if(AMgr.options.shouldUnrollLoops()) {
1562 unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
1563 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1565 ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
1566 Pred, maxBlockVisitOnPath);
1567 if (NewState != Pred->getState()) {
1568 ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
1574 // Is we are inside an unrolled loop then no need the check the counters.
1575 if(isUnrolledState(Pred->getState()))
1579 // If this block is terminated by a loop and it has already been visited the
1580 // maximum number of times, widen the loop.
1581 unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1582 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1583 AMgr.options.shouldWidenLoops()) {
1584 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1586 (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1589 const LocationContext *LCtx = Pred->getLocationContext();
1590 ProgramStateRef WidenedState =
1591 getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1592 nodeBuilder.generateNode(WidenedState, Pred);
1596 // FIXME: Refactor this into a checker.
1597 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1598 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1599 const ExplodedNode *Sink =
1600 nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1602 // Check if we stopped at the top level function or not.
1603 // Root node should have the location context of the top most function.
1604 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1605 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1606 const LocationContext *RootLC =
1607 (*G.roots_begin())->getLocation().getLocationContext();
1608 if (RootLC->getCurrentStackFrame() != CalleeSF) {
1609 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1611 // Re-run the call evaluation without inlining it, by storing the
1612 // no-inlining policy in the state and enqueuing the new work item on
1613 // the list. Replay should almost never fail. Use the stats to catch it
1615 if ((!AMgr.options.NoRetryExhausted &&
1616 replayWithoutInlining(Pred, CalleeLC)))
1618 NumMaxBlockCountReachedInInlined++;
1620 NumMaxBlockCountReached++;
1622 // Make sink nodes as exhausted(for stats) only if retry failed.
1623 Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1627 //===----------------------------------------------------------------------===//
1628 // Branch processing.
1629 //===----------------------------------------------------------------------===//
1631 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1632 /// to try to recover some path-sensitivity for casts of symbolic
1633 /// integers that promote their values (which are currently not tracked well).
1634 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1635 // cast(s) did was sign-extend the original value.
1636 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1637 ProgramStateRef state,
1638 const Stmt *Condition,
1639 const LocationContext *LCtx,
1642 const Expr *Ex = dyn_cast<Expr>(Condition);
1644 return UnknownVal();
1647 bool bitsInit = false;
1649 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1650 QualType T = CE->getType();
1652 if (!T->isIntegralOrEnumerationType())
1653 return UnknownVal();
1655 uint64_t newBits = Ctx.getTypeSize(T);
1656 if (!bitsInit || newBits < bits) {
1661 Ex = CE->getSubExpr();
1664 // We reached a non-cast. Is it a symbolic value?
1665 QualType T = Ex->getType();
1667 if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1668 Ctx.getTypeSize(T) > bits)
1669 return UnknownVal();
1671 return state->getSVal(Ex, LCtx);
1675 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1677 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1678 if (!BO || !BO->isLogicalOp()) {
1681 Condition = BO->getRHS()->IgnoreParens();
1687 // Returns the condition the branch at the end of 'B' depends on and whose value
1688 // has been evaluated within 'B'.
1689 // In most cases, the terminator condition of 'B' will be evaluated fully in
1690 // the last statement of 'B'; in those cases, the resolved condition is the
1691 // given 'Condition'.
1692 // If the condition of the branch is a logical binary operator tree, the CFG is
1693 // optimized: in that case, we know that the expression formed by all but the
1694 // rightmost leaf of the logical binary operator tree must be true, and thus
1695 // the branch condition is at this point equivalent to the truth value of that
1696 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1697 // expression in its final statement. As the full condition in that case was
1698 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1699 // expression to evaluate the truth value of the condition in the current state
1701 static const Stmt *ResolveCondition(const Stmt *Condition,
1702 const CFGBlock *B) {
1703 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1704 Condition = Ex->IgnoreParens();
1706 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1707 if (!BO || !BO->isLogicalOp())
1710 assert(!B->getTerminator().isTemporaryDtorsBranch() &&
1711 "Temporary destructor branches handled by processBindTemporary.");
1713 // For logical operations, we still have the case where some branches
1714 // use the traditional "merge" approach and others sink the branch
1715 // directly into the basic blocks representing the logical operation.
1716 // We need to distinguish between those two cases here.
1718 // The invariants are still shifting, but it is possible that the
1719 // last element in a CFGBlock is not a CFGStmt. Look for the last
1720 // CFGStmt as the value of the condition.
1721 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1722 for (; I != E; ++I) {
1723 CFGElement Elem = *I;
1724 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1727 const Stmt *LastStmt = CS->getStmt();
1728 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
1731 llvm_unreachable("could not resolve condition");
1734 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1735 NodeBuilderContext& BldCtx,
1737 ExplodedNodeSet &Dst,
1738 const CFGBlock *DstT,
1739 const CFGBlock *DstF) {
1740 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
1741 "CXXBindTemporaryExprs are handled by processBindTemporary.");
1742 const LocationContext *LCtx = Pred->getLocationContext();
1743 PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1744 currBldrCtx = &BldCtx;
1746 // Check for NULL conditions; e.g. "for(;;)"
1748 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1749 NullCondBldr.markInfeasible(false);
1750 NullCondBldr.generateNode(Pred->getState(), true, Pred);
1754 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1755 Condition = Ex->IgnoreParens();
1757 Condition = ResolveCondition(Condition, BldCtx.getBlock());
1758 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1759 Condition->getLocStart(),
1760 "Error evaluating branch");
1762 ExplodedNodeSet CheckersOutSet;
1763 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1765 // We generated only sinks.
1766 if (CheckersOutSet.empty())
1769 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1770 for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1771 E = CheckersOutSet.end(); E != I; ++I) {
1772 ExplodedNode *PredI = *I;
1774 if (PredI->isSink())
1777 ProgramStateRef PrevState = PredI->getState();
1778 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1780 if (X.isUnknownOrUndef()) {
1781 // Give it a chance to recover from unknown.
1782 if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1783 if (Ex->getType()->isIntegralOrEnumerationType()) {
1784 // Try to recover some path-sensitivity. Right now casts of symbolic
1785 // integers that promote their values are currently not tracked well.
1786 // If 'Condition' is such an expression, try and recover the
1787 // underlying value and use that instead.
1788 SVal recovered = RecoverCastedSymbol(getStateManager(),
1789 PrevState, Condition,
1790 PredI->getLocationContext(),
1793 if (!recovered.isUnknown()) {
1800 // If the condition is still unknown, give up.
1801 if (X.isUnknownOrUndef()) {
1802 builder.generateNode(PrevState, true, PredI);
1803 builder.generateNode(PrevState, false, PredI);
1807 DefinedSVal V = X.castAs<DefinedSVal>();
1809 ProgramStateRef StTrue, StFalse;
1810 std::tie(StTrue, StFalse) = PrevState->assume(V);
1812 // Process the true branch.
1813 if (builder.isFeasible(true)) {
1815 builder.generateNode(StTrue, true, PredI);
1817 builder.markInfeasible(true);
1820 // Process the false branch.
1821 if (builder.isFeasible(false)) {
1823 builder.generateNode(StFalse, false, PredI);
1825 builder.markInfeasible(false);
1828 currBldrCtx = nullptr;
1831 /// The GDM component containing the set of global variables which have been
1832 /// previously initialized with explicit initializers.
1833 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1834 llvm::ImmutableSet<const VarDecl *>)
1836 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1837 NodeBuilderContext &BuilderCtx,
1839 clang::ento::ExplodedNodeSet &Dst,
1840 const CFGBlock *DstT,
1841 const CFGBlock *DstF) {
1842 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1843 currBldrCtx = &BuilderCtx;
1845 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1846 ProgramStateRef state = Pred->getState();
1847 bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1848 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1851 state = state->add<InitializedGlobalsSet>(VD);
1854 builder.generateNode(state, initHasRun, Pred);
1855 builder.markInfeasible(!initHasRun);
1857 currBldrCtx = nullptr;
1860 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
1861 /// nodes by processing the 'effects' of a computed goto jump.
1862 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1864 ProgramStateRef state = builder.getState();
1865 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1867 // Three possibilities:
1869 // (1) We know the computed label.
1870 // (2) The label is NULL (or some other constant), or Undefined.
1871 // (3) We have no clue about the label. Dispatch to all targets.
1874 typedef IndirectGotoNodeBuilder::iterator iterator;
1876 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1877 const LabelDecl *L = LV->getLabel();
1879 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1880 if (I.getLabel() == L) {
1881 builder.generateNode(I, state);
1886 llvm_unreachable("No block with label.");
1889 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1890 // Dispatch to the first target and mark it as a sink.
1891 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1892 // FIXME: add checker visit.
1893 // UndefBranches.insert(N);
1897 // This is really a catch-all. We don't support symbolics yet.
1898 // FIXME: Implement dispatch for symbolic pointers.
1900 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1901 builder.generateNode(I, state);
1905 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) {
1906 const StackFrameContext* Frame = Pred.getStackFrame();
1907 const llvm::ImmutableSet<CXXBindTemporaryContext> &Set =
1908 Pred.getState()->get<InitializedTemporariesSet>();
1909 return std::find_if(Set.begin(), Set.end(),
1910 [&](const CXXBindTemporaryContext &Ctx) {
1911 if (Ctx.second == Frame) {
1913 llvm::errs() << "\n";
1915 return Ctx.second == Frame;
1920 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
1922 ExplodedNodeSet &Dst,
1923 const BlockEdge &L) {
1924 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
1925 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
1928 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
1929 /// nodes when the control reaches the end of a function.
1930 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1932 const ReturnStmt *RS) {
1933 // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)).
1934 // We currently cannot enable this assert, as lifetime extended temporaries
1935 // are not modelled correctly.
1936 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1937 StateMgr.EndPath(Pred->getState());
1939 ExplodedNodeSet Dst;
1940 if (Pred->getLocationContext()->inTopFrame()) {
1941 // Remove dead symbols.
1942 ExplodedNodeSet AfterRemovedDead;
1943 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1946 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1947 E = AfterRemovedDead.end(); I != E; ++I) {
1948 getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1951 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1954 Engine.enqueueEndOfFunction(Dst, RS);
1957 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
1958 /// nodes by processing the 'effects' of a switch statement.
1959 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1960 typedef SwitchNodeBuilder::iterator iterator;
1961 ProgramStateRef state = builder.getState();
1962 const Expr *CondE = builder.getCondition();
1963 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1965 if (CondV_untested.isUndef()) {
1966 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1967 // FIXME: add checker
1968 //UndefBranches.insert(N);
1972 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1974 ProgramStateRef DefaultSt = state;
1976 iterator I = builder.begin(), EI = builder.end();
1977 bool defaultIsFeasible = I == EI;
1979 for ( ; I != EI; ++I) {
1980 // Successor may be pruned out during CFG construction.
1984 const CaseStmt *Case = I.getCase();
1986 // Evaluate the LHS of the case value.
1987 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1988 assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
1990 // Get the RHS of the case, if it exists.
1992 if (const Expr *E = Case->getRHS())
1993 V2 = E->EvaluateKnownConstInt(getContext());
1997 ProgramStateRef StateCase;
1998 if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
1999 std::tie(StateCase, DefaultSt) =
2000 DefaultSt->assumeInclusiveRange(*NL, V1, V2);
2002 StateCase = DefaultSt;
2005 builder.generateCaseStmtNode(I, StateCase);
2007 // Now "assume" that the case doesn't match. Add this state
2008 // to the default state (if it is feasible).
2010 defaultIsFeasible = true;
2012 defaultIsFeasible = false;
2017 if (!defaultIsFeasible)
2020 // If we have switch(enum value), the default branch is not
2021 // feasible if all of the enum constants not covered by 'case:' statements
2022 // are not feasible values for the switch condition.
2024 // Note that this isn't as accurate as it could be. Even if there isn't
2025 // a case for a particular enum value as long as that enum value isn't
2026 // feasible then it shouldn't be considered for making 'default:' reachable.
2027 const SwitchStmt *SS = builder.getSwitch();
2028 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
2029 if (CondExpr->getType()->getAs<EnumType>()) {
2030 if (SS->isAllEnumCasesCovered())
2034 builder.generateDefaultCaseNode(DefaultSt);
2037 //===----------------------------------------------------------------------===//
2038 // Transfer functions: Loads and stores.
2039 //===----------------------------------------------------------------------===//
2041 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
2043 ExplodedNodeSet &Dst) {
2044 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2046 ProgramStateRef state = Pred->getState();
2047 const LocationContext *LCtx = Pred->getLocationContext();
2049 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2050 // C permits "extern void v", and if you cast the address to a valid type,
2051 // you can even do things with it. We simply pretend
2052 assert(Ex->isGLValue() || VD->getType()->isVoidType());
2053 const LocationContext *LocCtxt = Pred->getLocationContext();
2054 const Decl *D = LocCtxt->getDecl();
2055 const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr;
2056 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
2059 if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
2060 DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
2061 MD->getParent()->isLambda()) {
2062 // Lookup the field of the lambda.
2063 const CXXRecordDecl *CXXRec = MD->getParent();
2064 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
2065 FieldDecl *LambdaThisCaptureField;
2066 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
2067 const FieldDecl *FD = LambdaCaptureFields[VD];
2069 // When a constant is captured, sometimes no corresponding field is
2070 // created in the lambda object.
2071 assert(VD->getType().isConstQualified());
2072 V = state->getLValue(VD, LocCtxt);
2073 IsReference = false;
2076 svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame());
2077 SVal CXXThisVal = state->getSVal(CXXThis);
2078 V = state->getLValue(FD, CXXThisVal);
2079 IsReference = FD->getType()->isReferenceType();
2082 V = state->getLValue(VD, LocCtxt);
2083 IsReference = VD->getType()->isReferenceType();
2086 // For references, the 'lvalue' is the pointer address stored in the
2087 // reference region.
2089 if (const MemRegion *R = V.getAsRegion())
2090 V = state->getSVal(R);
2095 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2096 ProgramPoint::PostLValueKind);
2099 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
2100 assert(!Ex->isGLValue());
2101 SVal V = svalBuilder.makeIntVal(ED->getInitVal());
2102 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
2105 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2106 SVal V = svalBuilder.getFunctionPointer(FD);
2107 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2108 ProgramPoint::PostLValueKind);
2111 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
2112 // FIXME: Compute lvalue of field pointers-to-member.
2113 // Right now we just use a non-null void pointer, so that it gives proper
2114 // results in boolean contexts.
2115 // FIXME: Maybe delegate this to the surrounding operator&.
2116 // Note how this expression is lvalue, however pointer-to-member is NonLoc.
2117 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
2118 currBldrCtx->blockCount());
2119 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
2120 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2121 ProgramPoint::PostLValueKind);
2125 llvm_unreachable("Support for this Decl not implemented.");
2128 /// VisitArraySubscriptExpr - Transfer function for array accesses
2129 void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A,
2131 ExplodedNodeSet &Dst){
2132 const Expr *Base = A->getBase()->IgnoreParens();
2133 const Expr *Idx = A->getIdx()->IgnoreParens();
2135 ExplodedNodeSet CheckerPreStmt;
2136 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
2138 ExplodedNodeSet EvalSet;
2139 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
2141 bool IsVectorType = A->getBase()->getType()->isVectorType();
2143 // The "like" case is for situations where C standard prohibits the type to
2144 // be an lvalue, e.g. taking the address of a subscript of an expression of
2146 bool IsGLValueLike = A->isGLValue() ||
2147 (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
2149 for (auto *Node : CheckerPreStmt) {
2150 const LocationContext *LCtx = Node->getLocationContext();
2151 ProgramStateRef state = Node->getState();
2153 if (IsGLValueLike) {
2154 SVal V = state->getLValue(A->getType(),
2155 state->getSVal(Idx, LCtx),
2156 state->getSVal(Base, LCtx));
2157 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
2158 ProgramPoint::PostLValueKind);
2159 } else if (IsVectorType) {
2160 // FIXME: non-glvalue vector reads are not modelled.
2161 Bldr.generateNode(A, Node, state, nullptr);
2163 llvm_unreachable("Array subscript should be an lValue when not \
2164 a vector and not a forbidden lvalue type");
2168 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
2171 /// VisitMemberExpr - Transfer function for member expressions.
2172 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
2173 ExplodedNodeSet &Dst) {
2175 // FIXME: Prechecks eventually go in ::Visit().
2176 ExplodedNodeSet CheckedSet;
2177 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
2179 ExplodedNodeSet EvalSet;
2180 ValueDecl *Member = M->getMemberDecl();
2182 // Handle static member variables and enum constants accessed via
2184 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2185 ExplodedNodeSet Dst;
2186 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2188 VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
2191 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2192 ExplodedNodeSet Tmp;
2194 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2196 ProgramStateRef state = (*I)->getState();
2197 const LocationContext *LCtx = (*I)->getLocationContext();
2198 Expr *BaseExpr = M->getBase();
2200 // Handle C++ method calls.
2201 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
2202 if (MD->isInstance())
2203 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2205 SVal MDVal = svalBuilder.getFunctionPointer(MD);
2206 state = state->BindExpr(M, LCtx, MDVal);
2208 Bldr.generateNode(M, *I, state);
2212 // Handle regular struct fields / member variables.
2213 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2214 SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
2216 FieldDecl *field = cast<FieldDecl>(Member);
2217 SVal L = state->getLValue(field, baseExprVal);
2219 if (M->isGLValue() || M->getType()->isArrayType()) {
2220 // We special-case rvalues of array type because the analyzer cannot
2221 // reason about them, since we expect all regions to be wrapped in Locs.
2222 // We instead treat these as lvalues and assume that they will decay to
2223 // pointers as soon as they are used.
2224 if (!M->isGLValue()) {
2225 assert(M->getType()->isArrayType());
2226 const ImplicitCastExpr *PE =
2227 dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParentIgnoreParens(M));
2228 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2229 llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2233 if (field->getType()->isReferenceType()) {
2234 if (const MemRegion *R = L.getAsRegion())
2235 L = state->getSVal(R);
2240 Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
2241 ProgramPoint::PostLValueKind);
2244 evalLoad(Tmp, M, M, *I, state, L);
2250 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2253 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
2254 ExplodedNodeSet &Dst) {
2255 ExplodedNodeSet AfterPreSet;
2256 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
2258 // For now, treat all the arguments to C11 atomics as escaping.
2259 // FIXME: Ideally we should model the behavior of the atomics precisely here.
2261 ExplodedNodeSet AfterInvalidateSet;
2262 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
2264 for (ExplodedNodeSet::iterator I = AfterPreSet.begin(), E = AfterPreSet.end();
2266 ProgramStateRef State = (*I)->getState();
2267 const LocationContext *LCtx = (*I)->getLocationContext();
2269 SmallVector<SVal, 8> ValuesToInvalidate;
2270 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
2271 const Expr *SubExpr = AE->getSubExprs()[SI];
2272 SVal SubExprVal = State->getSVal(SubExpr, LCtx);
2273 ValuesToInvalidate.push_back(SubExprVal);
2276 State = State->invalidateRegions(ValuesToInvalidate, AE,
2277 currBldrCtx->blockCount(),
2279 /*CausedByPointerEscape*/true,
2280 /*Symbols=*/nullptr);
2282 SVal ResultVal = UnknownVal();
2283 State = State->BindExpr(AE, LCtx, ResultVal);
2284 Bldr.generateNode(AE, *I, State, nullptr,
2285 ProgramPoint::PostStmtKind);
2288 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
2291 // A value escapes in three possible cases:
2292 // (1) We are binding to something that is not a memory region.
2293 // (2) We are binding to a MemrRegion that does not have stack storage.
2294 // (3) We are binding to a MemRegion with stack storage that the store
2295 // does not understand.
2296 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2299 const LocationContext *LCtx) {
2300 // Are we storing to something that causes the value to "escape"?
2301 bool escapes = true;
2303 // TODO: Move to StoreManager.
2304 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2305 escapes = !regionLoc->getRegion()->hasStackStorage();
2308 // To test (3), generate a new state with the binding added. If it is
2309 // the same state, then it escapes (since the store cannot represent
2311 // Do this only if we know that the store is not supposed to generate the
2313 SVal StoredVal = State->getSVal(regionLoc->getRegion());
2314 if (StoredVal != Val)
2315 escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
2319 // If our store can represent the binding and we aren't storing to something
2320 // that doesn't have local storage then just return and have the simulation
2321 // state continue as is.
2325 // Otherwise, find all symbols referenced by 'val' that we are tracking
2326 // and stop tracking them.
2327 CollectReachableSymbolsCallback Scanner =
2328 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
2329 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
2330 State = getCheckerManager().runCheckersForPointerEscape(State,
2332 /*CallEvent*/ nullptr,
2340 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2341 const InvalidatedSymbols *Invalidated,
2342 ArrayRef<const MemRegion *> ExplicitRegions,
2343 ArrayRef<const MemRegion *> Regions,
2344 const CallEvent *Call,
2345 RegionAndSymbolInvalidationTraits &ITraits) {
2347 if (!Invalidated || Invalidated->empty())
2351 return getCheckerManager().runCheckersForPointerEscape(State,
2357 // If the symbols were invalidated by a call, we want to find out which ones
2358 // were invalidated directly due to being arguments to the call.
2359 InvalidatedSymbols SymbolsDirectlyInvalidated;
2360 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
2361 E = ExplicitRegions.end(); I != E; ++I) {
2362 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
2363 SymbolsDirectlyInvalidated.insert(R->getSymbol());
2366 InvalidatedSymbols SymbolsIndirectlyInvalidated;
2367 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
2368 E = Invalidated->end(); I!=E; ++I) {
2370 if (SymbolsDirectlyInvalidated.count(sym))
2372 SymbolsIndirectlyInvalidated.insert(sym);
2375 if (!SymbolsDirectlyInvalidated.empty())
2376 State = getCheckerManager().runCheckersForPointerEscape(State,
2377 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2379 // Notify about the symbols that get indirectly invalidated by the call.
2380 if (!SymbolsIndirectlyInvalidated.empty())
2381 State = getCheckerManager().runCheckersForPointerEscape(State,
2382 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2387 /// evalBind - Handle the semantics of binding a value to a specific location.
2388 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
2389 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2391 SVal location, SVal Val,
2392 bool atDeclInit, const ProgramPoint *PP) {
2394 const LocationContext *LC = Pred->getLocationContext();
2395 PostStmt PS(StoreE, LC);
2399 // Do a previsit of the bind.
2400 ExplodedNodeSet CheckedSet;
2401 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2402 StoreE, *this, *PP);
2404 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2406 // If the location is not a 'Loc', it will already be handled by
2407 // the checkers. There is nothing left to do.
2408 if (!location.getAs<Loc>()) {
2409 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2411 ProgramStateRef state = Pred->getState();
2412 state = processPointerEscapedOnBind(state, location, Val, LC);
2413 Bldr.generateNode(L, state, Pred);
2417 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2419 ExplodedNode *PredI = *I;
2420 ProgramStateRef state = PredI->getState();
2422 state = processPointerEscapedOnBind(state, location, Val, LC);
2424 // When binding the value, pass on the hint that this is a initialization.
2425 // For initializations, we do not need to inform clients of region
2427 state = state->bindLoc(location.castAs<Loc>(),
2428 Val, LC, /* notifyChanges = */ !atDeclInit);
2430 const MemRegion *LocReg = nullptr;
2431 if (Optional<loc::MemRegionVal> LocRegVal =
2432 location.getAs<loc::MemRegionVal>()) {
2433 LocReg = LocRegVal->getRegion();
2436 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2437 Bldr.generateNode(L, state, PredI);
2441 /// evalStore - Handle the semantics of a store via an assignment.
2442 /// @param Dst The node set to store generated state nodes
2443 /// @param AssignE The assignment expression if the store happens in an
2445 /// @param LocationE The location expression that is stored to.
2446 /// @param state The current simulation state
2447 /// @param location The location to store the value
2448 /// @param Val The value to be stored
2449 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2450 const Expr *LocationE,
2452 ProgramStateRef state, SVal location, SVal Val,
2453 const ProgramPointTag *tag) {
2454 // Proceed with the store. We use AssignE as the anchor for the PostStore
2455 // ProgramPoint if it is non-NULL, and LocationE otherwise.
2456 const Expr *StoreE = AssignE ? AssignE : LocationE;
2458 // Evaluate the location (checks for bad dereferences).
2459 ExplodedNodeSet Tmp;
2460 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2465 if (location.isUndef())
2468 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2469 evalBind(Dst, StoreE, *NI, location, Val, false);
2472 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2474 const Expr *BoundEx,
2476 ProgramStateRef state,
2478 const ProgramPointTag *tag,
2481 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2483 // Are we loading from a region? This actually results in two loads; one
2484 // to fetch the address of the referenced value and one to fetch the
2485 // referenced value.
2486 if (const TypedValueRegion *TR =
2487 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2489 QualType ValTy = TR->getValueType();
2490 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2491 static SimpleProgramPointTag
2492 loadReferenceTag(TagProviderName, "Load Reference");
2493 ExplodedNodeSet Tmp;
2494 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2495 location, &loadReferenceTag,
2496 getContext().getPointerType(RT->getPointeeType()));
2498 // Perform the load from the referenced value.
2499 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2500 state = (*I)->getState();
2501 location = state->getSVal(BoundEx, (*I)->getLocationContext());
2502 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2508 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2511 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2513 const Expr *BoundEx,
2515 ProgramStateRef state,
2517 const ProgramPointTag *tag,
2521 // Evaluate the location (checks for bad dereferences).
2522 ExplodedNodeSet Tmp;
2523 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2527 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2528 if (location.isUndef())
2531 // Proceed with the load.
2532 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2533 state = (*NI)->getState();
2534 const LocationContext *LCtx = (*NI)->getLocationContext();
2536 SVal V = UnknownVal();
2537 if (location.isValid()) {
2538 if (LoadTy.isNull())
2539 LoadTy = BoundEx->getType();
2540 V = state->getSVal(location.castAs<Loc>(), LoadTy);
2543 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2544 ProgramPoint::PostLoadKind);
2548 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2550 const Stmt *BoundEx,
2552 ProgramStateRef state,
2554 const ProgramPointTag *tag,
2556 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2557 // Early checks for performance reason.
2558 if (location.isUnknown()) {
2562 ExplodedNodeSet Src;
2563 BldrTop.takeNodes(Pred);
2564 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2565 if (Pred->getState() != state) {
2566 // Associate this new state with an ExplodedNode.
2567 // FIXME: If I pass null tag, the graph is incorrect, e.g for
2571 // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2572 // instead "int *p" is noted as
2573 // "Variable 'p' initialized to a null pointer value"
2575 static SimpleProgramPointTag tag(TagProviderName, "Location");
2576 Bldr.generateNode(NodeEx, Pred, state, &tag);
2578 ExplodedNodeSet Tmp;
2579 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2580 NodeEx, BoundEx, *this);
2581 BldrTop.addNodes(Tmp);
2584 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2585 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2586 static SimpleProgramPointTag
2587 eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2588 "Eagerly Assume True"),
2589 eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2590 "Eagerly Assume False");
2591 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2592 &eagerlyAssumeBinOpBifurcationFalse);
2595 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2596 ExplodedNodeSet &Src,
2598 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2600 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2601 ExplodedNode *Pred = *I;
2602 // Test if the previous node was as the same expression. This can happen
2603 // when the expression fails to evaluate to anything meaningful and
2604 // (as an optimization) we don't generate a node.
2605 ProgramPoint P = Pred->getLocation();
2606 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2610 ProgramStateRef state = Pred->getState();
2611 SVal V = state->getSVal(Ex, Pred->getLocationContext());
2612 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2613 if (SEV && SEV->isExpression()) {
2614 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2615 geteagerlyAssumeBinOpBifurcationTags();
2617 ProgramStateRef StateTrue, StateFalse;
2618 std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2620 // First assume that the condition is true.
2622 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2623 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2624 Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2627 // Next, assume that the condition is false.
2629 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2630 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2631 Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2637 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2638 ExplodedNodeSet &Dst) {
2639 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2640 // We have processed both the inputs and the outputs. All of the outputs
2641 // should evaluate to Locs. Nuke all of their values.
2643 // FIXME: Some day in the future it would be nice to allow a "plug-in"
2644 // which interprets the inline asm and stores proper results in the
2647 ProgramStateRef state = Pred->getState();
2649 for (const Expr *O : A->outputs()) {
2650 SVal X = state->getSVal(O, Pred->getLocationContext());
2651 assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2653 if (Optional<Loc> LV = X.getAs<Loc>())
2654 state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
2657 Bldr.generateNode(A, Pred, state);
2660 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2661 ExplodedNodeSet &Dst) {
2662 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2663 Bldr.generateNode(A, Pred, Pred->getState());
2666 //===----------------------------------------------------------------------===//
2668 //===----------------------------------------------------------------------===//
2671 static ExprEngine* GraphPrintCheckerState;
2672 static SourceManager* GraphPrintSourceManager;
2676 struct DOTGraphTraits<ExplodedNode*> :
2677 public DefaultDOTGraphTraits {
2679 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2681 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2683 static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2687 // De-duplicate some source location pretty-printing.
2688 static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2689 if (SLoc.isFileID()) {
2691 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2693 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2697 static void printLocation2(raw_ostream &Out, SourceLocation SLoc) {
2698 if (SLoc.isFileID() && GraphPrintSourceManager->isInMainFile(SLoc))
2699 Out << "line " << GraphPrintSourceManager->getExpansionLineNumber(SLoc);
2701 SLoc.print(Out, *GraphPrintSourceManager);
2704 static std::string getNodeLabel(const ExplodedNode *N, void*){
2707 llvm::raw_string_ostream Out(sbuf);
2709 // Program Location.
2710 ProgramPoint Loc = N->getLocation();
2712 switch (Loc.getKind()) {
2713 case ProgramPoint::BlockEntranceKind: {
2714 Out << "Block Entrance: B"
2715 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2719 case ProgramPoint::BlockExitKind:
2723 case ProgramPoint::CallEnterKind:
2727 case ProgramPoint::CallExitBeginKind:
2728 Out << "CallExitBegin";
2731 case ProgramPoint::CallExitEndKind:
2732 Out << "CallExitEnd";
2735 case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2736 Out << "PostStmtPurgeDeadSymbols";
2739 case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2740 Out << "PreStmtPurgeDeadSymbols";
2743 case ProgramPoint::EpsilonKind:
2744 Out << "Epsilon Point";
2747 case ProgramPoint::LoopExitKind: {
2748 LoopExit LE = Loc.castAs<LoopExit>();
2749 Out << "LoopExit: " << LE.getLoopStmt()->getStmtClassName();
2753 case ProgramPoint::PreImplicitCallKind: {
2754 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2757 // FIXME: Get proper printing options.
2758 PC.getDecl()->print(Out, LangOptions());
2759 printLocation(Out, PC.getLocation());
2763 case ProgramPoint::PostImplicitCallKind: {
2764 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2765 Out << "PostCall: ";
2767 // FIXME: Get proper printing options.
2768 PC.getDecl()->print(Out, LangOptions());
2769 printLocation(Out, PC.getLocation());
2773 case ProgramPoint::PostInitializerKind: {
2774 Out << "PostInitializer: ";
2775 const CXXCtorInitializer *Init =
2776 Loc.castAs<PostInitializer>().getInitializer();
2777 if (const FieldDecl *FD = Init->getAnyMember())
2780 QualType Ty = Init->getTypeSourceInfo()->getType();
2781 Ty = Ty.getLocalUnqualifiedType();
2782 LangOptions LO; // FIXME.
2788 case ProgramPoint::BlockEdgeKind: {
2789 const BlockEdge &E = Loc.castAs<BlockEdge>();
2790 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2791 << E.getDst()->getBlockID() << ')';
2793 if (const Stmt *T = E.getSrc()->getTerminator()) {
2794 SourceLocation SLoc = T->getLocStart();
2796 Out << "\\|Terminator: ";
2797 LangOptions LO; // FIXME.
2798 E.getSrc()->printTerminator(Out, LO);
2800 if (SLoc.isFileID()) {
2802 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2804 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2807 if (isa<SwitchStmt>(T)) {
2808 const Stmt *Label = E.getDst()->getLabel();
2811 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2813 LangOptions LO; // FIXME.
2815 C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
2817 if (const Stmt *RHS = C->getRHS()) {
2819 RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
2825 assert (isa<DefaultStmt>(Label));
2826 Out << "\\ldefault:";
2830 Out << "\\l(implicit) default:";
2832 else if (isa<IndirectGotoStmt>(T)) {
2836 Out << "\\lCondition: ";
2837 if (*E.getSrc()->succ_begin() == E.getDst())
2850 const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2851 assert(S != nullptr && "Expecting non-null Stmt");
2853 Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2854 LangOptions LO; // FIXME.
2855 S->printPretty(Out, nullptr, PrintingPolicy(LO));
2856 printLocation(Out, S->getLocStart());
2858 if (Loc.getAs<PreStmt>())
2859 Out << "\\lPreStmt\\l;";
2860 else if (Loc.getAs<PostLoad>())
2861 Out << "\\lPostLoad\\l;";
2862 else if (Loc.getAs<PostStore>())
2863 Out << "\\lPostStore\\l";
2864 else if (Loc.getAs<PostLValue>())
2865 Out << "\\lPostLValue\\l";
2871 ProgramStateRef state = N->getState();
2872 Out << "\\|StateID: " << (const void*) state.get()
2873 << " NodeID: " << (const void*) N << "\\|";
2875 // Analysis stack backtrace.
2876 Out << "Location context stack (from current to outer):\\l";
2877 const LocationContext *LC = Loc.getLocationContext();
2879 for (; LC; LC = LC->getParent(), ++Idx) {
2880 Out << Idx << ". (" << (const void *)LC << ") ";
2881 switch (LC->getKind()) {
2882 case LocationContext::StackFrame:
2883 if (const NamedDecl *D = dyn_cast<NamedDecl>(LC->getDecl()))
2884 Out << "Calling " << D->getQualifiedNameAsString();
2886 Out << "Calling anonymous code";
2887 if (const Stmt *S = cast<StackFrameContext>(LC)->getCallSite()) {
2889 printLocation2(Out, S->getLocStart());
2892 case LocationContext::Block:
2893 Out << "Invoking block";
2894 if (const Decl *D = cast<BlockInvocationContext>(LC)->getBlockDecl()) {
2895 Out << " defined at ";
2896 printLocation2(Out, D->getLocStart());
2899 case LocationContext::Scope:
2900 Out << "Entering scope";
2901 // FIXME: Add more info once ScopeContext is activated.
2908 state->printDOT(Out);
2912 if (const ProgramPointTag *tag = Loc.getTag()) {
2913 Out << "\\|Tag: " << tag->getTagDescription();
2919 } // end llvm namespace
2922 void ExprEngine::ViewGraph(bool trim) {
2925 std::vector<const ExplodedNode*> Src;
2927 // Flush any outstanding reports to make sure we cover all the nodes.
2928 // This does not cause them to get displayed.
2929 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2930 const_cast<BugType*>(*I)->FlushReports(BR);
2932 // Iterate through the reports and get their nodes.
2933 for (BugReporter::EQClasses_iterator
2934 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2935 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2936 if (N) Src.push_back(N);
2942 GraphPrintCheckerState = this;
2943 GraphPrintSourceManager = &getContext().getSourceManager();
2945 llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2947 GraphPrintCheckerState = nullptr;
2948 GraphPrintSourceManager = nullptr;
2953 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
2955 GraphPrintCheckerState = this;
2956 GraphPrintSourceManager = &getContext().getSourceManager();
2958 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2960 if (!TrimmedG.get())
2961 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2963 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2965 GraphPrintCheckerState = nullptr;
2966 GraphPrintSourceManager = nullptr;