1 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-=
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a meta-engine for path-sensitive dataflow analysis that
11 // is built on GREngine, but provides the boilerplate to execute transfer
12 // functions and build the ExplodedGraph at the expression level.
14 //===----------------------------------------------------------------------===//
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17 #include "PrettyStackTraceLocationContext.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ParentMap.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/PrettyStackTrace.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
26 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
29 #include "llvm/ADT/ImmutableList.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Support/GraphWriter.h"
37 using namespace clang;
41 #define DEBUG_TYPE "ExprEngine"
43 STATISTIC(NumRemoveDeadBindings,
44 "The # of times RemoveDeadBindings is called");
45 STATISTIC(NumMaxBlockCountReached,
46 "The # of aborted paths due to reaching the maximum block count in "
47 "a top level function");
48 STATISTIC(NumMaxBlockCountReachedInInlined,
49 "The # of aborted paths due to reaching the maximum block count in "
50 "an inlined function");
51 STATISTIC(NumTimesRetriedWithoutInlining,
52 "The # of times we re-evaluated a call without inlining");
54 //===----------------------------------------------------------------------===//
55 // Engine construction and deletion.
56 //===----------------------------------------------------------------------===//
58 static const char* TagProviderName = "ExprEngine";
60 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
61 SetOfConstDecls *VisitedCalleesIn,
62 FunctionSummariesTy *FS,
63 InliningModes HowToInlineIn)
65 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
68 StateMgr(getContext(), mgr.getStoreManagerCreator(),
69 mgr.getConstraintManagerCreator(), G.getAllocator(),
71 SymMgr(StateMgr.getSymbolManager()),
72 svalBuilder(StateMgr.getSValBuilder()),
73 currStmtIdx(0), currBldrCtx(nullptr),
74 ObjCNoRet(mgr.getASTContext()),
75 ObjCGCEnabled(gcEnabled), BR(mgr, *this),
76 VisitedCallees(VisitedCalleesIn),
77 HowToInline(HowToInlineIn)
79 unsigned TrimInterval = mgr.options.getGraphTrimInterval();
80 if (TrimInterval != 0) {
81 // Enable eager node reclaimation when constructing the ExplodedGraph.
82 G.enableNodeReclamation(TrimInterval);
86 ExprEngine::~ExprEngine() {
90 //===----------------------------------------------------------------------===//
92 //===----------------------------------------------------------------------===//
94 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
95 ProgramStateRef state = StateMgr.getInitialState(InitLoc);
96 const Decl *D = InitLoc->getDecl();
99 // FIXME: It would be nice if we had a more general mechanism to add
100 // such preconditions. Some day.
103 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
104 // Precondition: the first argument of 'main' is an integer guaranteed
106 const IdentifierInfo *II = FD->getIdentifier();
107 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
110 const ParmVarDecl *PD = FD->getParamDecl(0);
111 QualType T = PD->getType();
112 const BuiltinType *BT = dyn_cast<BuiltinType>(T);
113 if (!BT || !BT->isInteger())
116 const MemRegion *R = state->getRegion(PD, InitLoc);
120 SVal V = state->getSVal(loc::MemRegionVal(R));
121 SVal Constraint_untested = evalBinOp(state, BO_GT, V,
122 svalBuilder.makeZeroVal(T),
123 svalBuilder.getConditionType());
125 Optional<DefinedOrUnknownSVal> Constraint =
126 Constraint_untested.getAs<DefinedOrUnknownSVal>();
131 if (ProgramStateRef newState = state->assume(*Constraint, true))
138 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
139 // Precondition: 'self' is always non-null upon entry to an Objective-C
141 const ImplicitParamDecl *SelfD = MD->getSelfDecl();
142 const MemRegion *R = state->getRegion(SelfD, InitLoc);
143 SVal V = state->getSVal(loc::MemRegionVal(R));
145 if (Optional<Loc> LV = V.getAs<Loc>()) {
146 // Assume that the pointer value in 'self' is non-null.
147 state = state->assume(*LV, true);
148 assert(state && "'self' cannot be null");
152 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
153 if (!MD->isStatic()) {
154 // Precondition: 'this' is always non-null upon entry to the
155 // top-level function. This is our starting assumption for
156 // analyzing an "open" program.
157 const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
158 if (SFC->getParent() == nullptr) {
159 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
160 SVal V = state->getSVal(L);
161 if (Optional<Loc> LV = V.getAs<Loc>()) {
162 state = state->assume(*LV, true);
163 assert(state && "'this' cannot be null");
173 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
174 const LocationContext *LC,
176 const Expr *Result) {
177 SVal V = State->getSVal(Ex, LC);
179 // If we don't have an explicit result expression, we're in "if needed"
180 // mode. Only create a region if the current value is a NonLoc.
181 if (!V.getAs<NonLoc>())
185 // We need to create a region no matter what. For sanity, make sure we don't
186 // try to stuff a Loc into a non-pointer temporary region.
187 assert(!V.getAs<Loc>() || Loc::isLocType(Result->getType()) ||
188 Result->getType()->isMemberPointerType());
191 ProgramStateManager &StateMgr = State->getStateManager();
192 MemRegionManager &MRMgr = StateMgr.getRegionManager();
193 StoreManager &StoreMgr = StateMgr.getStoreManager();
195 // We need to be careful about treating a derived type's value as
196 // bindings for a base type. Unless we're creating a temporary pointer region,
197 // start by stripping and recording base casts.
198 SmallVector<const CastExpr *, 4> Casts;
199 const Expr *Inner = Ex->IgnoreParens();
200 if (!Loc::isLocType(Result->getType())) {
201 while (const CastExpr *CE = dyn_cast<CastExpr>(Inner)) {
202 if (CE->getCastKind() == CK_DerivedToBase ||
203 CE->getCastKind() == CK_UncheckedDerivedToBase)
205 else if (CE->getCastKind() != CK_NoOp)
208 Inner = CE->getSubExpr()->IgnoreParens();
212 // Create a temporary object region for the inner expression (which may have
213 // a more derived type) and bind the value into it.
214 const TypedValueRegion *TR = nullptr;
215 if (const MaterializeTemporaryExpr *MT =
216 dyn_cast<MaterializeTemporaryExpr>(Result)) {
217 StorageDuration SD = MT->getStorageDuration();
218 // If this object is bound to a reference with static storage duration, we
219 // put it in a different region to prevent "address leakage" warnings.
220 if (SD == SD_Static || SD == SD_Thread)
221 TR = MRMgr.getCXXStaticTempObjectRegion(Inner);
224 TR = MRMgr.getCXXTempObjectRegion(Inner, LC);
226 SVal Reg = loc::MemRegionVal(TR);
229 V = getSValBuilder().conjureSymbolVal(Result, LC, TR->getValueType(),
230 currBldrCtx->blockCount());
231 State = State->bindLoc(Reg, V);
233 // Re-apply the casts (from innermost to outermost) for type sanity.
234 for (SmallVectorImpl<const CastExpr *>::reverse_iterator I = Casts.rbegin(),
237 Reg = StoreMgr.evalDerivedToBase(Reg, *I);
240 State = State->BindExpr(Result, LC, Reg);
244 //===----------------------------------------------------------------------===//
245 // Top-level transfer function logic (Dispatcher).
246 //===----------------------------------------------------------------------===//
248 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
249 /// logic for handling assumptions on symbolic values.
250 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
251 SVal cond, bool assumption) {
252 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
255 bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
256 return getCheckerManager().wantsRegionChangeUpdate(state);
260 ExprEngine::processRegionChanges(ProgramStateRef state,
261 const InvalidatedSymbols *invalidated,
262 ArrayRef<const MemRegion *> Explicits,
263 ArrayRef<const MemRegion *> Regions,
264 const CallEvent *Call) {
265 return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
266 Explicits, Regions, Call);
269 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
270 const char *NL, const char *Sep) {
271 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
274 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
275 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
278 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
279 unsigned StmtIdx, NodeBuilderContext *Ctx) {
280 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
281 currStmtIdx = StmtIdx;
284 switch (E.getKind()) {
285 case CFGElement::Statement:
286 ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred);
288 case CFGElement::Initializer:
289 ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred);
291 case CFGElement::NewAllocator:
292 ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
295 case CFGElement::AutomaticObjectDtor:
296 case CFGElement::DeleteDtor:
297 case CFGElement::BaseDtor:
298 case CFGElement::MemberDtor:
299 case CFGElement::TemporaryDtor:
300 ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
305 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
307 const ExplodedNode *Pred,
308 const LocationContext *LC) {
310 // Are we never purging state values?
311 if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
314 // Is this the beginning of a basic block?
315 if (Pred->getLocation().getAs<BlockEntrance>())
318 // Is this on a non-expression?
319 if (!isa<Expr>(S.getStmt()))
322 // Run before processing a call.
323 if (CallEvent::isCallStmt(S.getStmt()))
326 // Is this an expression that is consumed by another expression? If so,
327 // postpone cleaning out the state.
328 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
329 return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
332 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
333 const Stmt *ReferenceStmt,
334 const LocationContext *LC,
335 const Stmt *DiagnosticStmt,
336 ProgramPoint::Kind K) {
337 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
338 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
339 && "PostStmt is not generally supported by the SymbolReaper yet");
340 assert(LC && "Must pass the current (or expiring) LocationContext");
342 if (!DiagnosticStmt) {
343 DiagnosticStmt = ReferenceStmt;
344 assert(DiagnosticStmt && "Required for clearing a LocationContext");
347 NumRemoveDeadBindings++;
348 ProgramStateRef CleanedState = Pred->getState();
350 // LC is the location context being destroyed, but SymbolReaper wants a
351 // location context that is still live. (If this is the top-level stack
352 // frame, this will be null.)
353 if (!ReferenceStmt) {
354 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
355 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
356 LC = LC->getParent();
359 const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : nullptr;
360 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
362 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
364 // Create a state in which dead bindings are removed from the environment
365 // and the store. TODO: The function should just return new env and store,
367 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
369 // Process any special transfer function for dead symbols.
370 // A tag to track convenience transitions, which can be removed at cleanup.
371 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
372 if (!SymReaper.hasDeadSymbols()) {
373 // Generate a CleanedNode that has the environment and store cleaned
374 // up. Since no symbols are dead, we can optimize and not clean out
375 // the constraint manager.
376 StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
377 Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
380 // Call checkers with the non-cleaned state so that they could query the
381 // values of the soon to be dead symbols.
382 ExplodedNodeSet CheckedSet;
383 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
384 DiagnosticStmt, *this, K);
386 // For each node in CheckedSet, generate CleanedNodes that have the
387 // environment, the store, and the constraints cleaned up but have the
388 // user-supplied states as the predecessors.
389 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
390 for (ExplodedNodeSet::const_iterator
391 I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
392 ProgramStateRef CheckerState = (*I)->getState();
394 // The constraint manager has not been cleaned up yet, so clean up now.
395 CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
398 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
399 "Checkers are not allowed to modify the Environment as a part of "
400 "checkDeadSymbols processing.");
401 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
402 "Checkers are not allowed to modify the Store as a part of "
403 "checkDeadSymbols processing.");
405 // Create a state based on CleanedState with CheckerState GDM and
406 // generate a transition to that state.
407 ProgramStateRef CleanedCheckerSt =
408 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
409 Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
414 void ExprEngine::ProcessStmt(const CFGStmt S,
415 ExplodedNode *Pred) {
416 // Reclaim any unnecessary nodes in the ExplodedGraph.
417 G.reclaimRecentlyAllocatedNodes();
419 const Stmt *currStmt = S.getStmt();
420 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
421 currStmt->getLocStart(),
422 "Error evaluating statement");
424 // Remove dead bindings and symbols.
425 ExplodedNodeSet CleanedStates;
426 if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
427 removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
429 CleanedStates.Add(Pred);
431 // Visit the statement.
433 for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
434 E = CleanedStates.end(); I != E; ++I) {
435 ExplodedNodeSet DstI;
436 // Visit the statement.
437 Visit(currStmt, *I, DstI);
441 // Enqueue the new nodes onto the work list.
442 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
445 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
446 ExplodedNode *Pred) {
447 const CXXCtorInitializer *BMI = Init.getInitializer();
449 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
450 BMI->getSourceLocation(),
451 "Error evaluating initializer");
453 // We don't clean up dead bindings here.
454 const StackFrameContext *stackFrame =
455 cast<StackFrameContext>(Pred->getLocationContext());
456 const CXXConstructorDecl *decl =
457 cast<CXXConstructorDecl>(stackFrame->getDecl());
459 ProgramStateRef State = Pred->getState();
460 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
462 ExplodedNodeSet Tmp(Pred);
465 // Evaluate the initializer, if necessary
466 if (BMI->isAnyMemberInitializer()) {
467 // Constructors build the object directly in the field,
468 // but non-objects must be copied in from the initializer.
469 const Expr *Init = BMI->getInit()->IgnoreImplicit();
470 if (!isa<CXXConstructExpr>(Init)) {
471 const ValueDecl *Field;
472 if (BMI->isIndirectMemberInitializer()) {
473 Field = BMI->getIndirectMember();
474 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
476 Field = BMI->getMember();
477 FieldLoc = State->getLValue(BMI->getMember(), thisVal);
481 if (BMI->getNumArrayIndices() > 0) {
482 // Handle arrays of trivial type. We can represent this with a
483 // primitive load/copy from the base array region.
484 const ArraySubscriptExpr *ASE;
485 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
486 Init = ASE->getBase()->IgnoreImplicit();
488 SVal LValue = State->getSVal(Init, stackFrame);
489 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
490 InitVal = State->getSVal(*LValueLoc);
492 // If we fail to get the value for some reason, use a symbolic value.
493 if (InitVal.isUnknownOrUndef()) {
494 SValBuilder &SVB = getSValBuilder();
495 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
497 currBldrCtx->blockCount());
500 InitVal = State->getSVal(BMI->getInit(), stackFrame);
503 assert(Tmp.size() == 1 && "have not generated any new nodes yet");
504 assert(*Tmp.begin() == Pred && "have not generated any new nodes yet");
507 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
508 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
511 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
512 // We already did all the work when visiting the CXXConstructExpr.
515 // Construct PostInitializer nodes whether the state changed or not,
516 // so that the diagnostics don't get confused.
517 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
519 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
520 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
521 ExplodedNode *N = *I;
522 Bldr.generateNode(PP, N->getState(), N);
525 // Enqueue the new nodes onto the work list.
526 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
529 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
530 ExplodedNode *Pred) {
532 switch (D.getKind()) {
533 case CFGElement::AutomaticObjectDtor:
534 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
536 case CFGElement::BaseDtor:
537 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
539 case CFGElement::MemberDtor:
540 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
542 case CFGElement::TemporaryDtor:
543 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
545 case CFGElement::DeleteDtor:
546 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
549 llvm_unreachable("Unexpected dtor kind.");
552 // Enqueue the new nodes onto the work list.
553 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
556 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
557 ExplodedNode *Pred) {
559 AnalysisManager &AMgr = getAnalysisManager();
560 AnalyzerOptions &Opts = AMgr.options;
561 // TODO: We're not evaluating allocators for all cases just yet as
562 // we're not handling the return value correctly, which causes false
563 // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
564 if (Opts.mayInlineCXXAllocator())
565 VisitCXXNewAllocatorCall(NE, Pred, Dst);
567 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
568 const LocationContext *LCtx = Pred->getLocationContext();
569 PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
570 Bldr.generateNode(PP, Pred->getState(), Pred);
572 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
575 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
577 ExplodedNodeSet &Dst) {
578 const VarDecl *varDecl = Dtor.getVarDecl();
579 QualType varType = varDecl->getType();
581 ProgramStateRef state = Pred->getState();
582 SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
583 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
585 if (const ReferenceType *refType = varType->getAs<ReferenceType>()) {
586 varType = refType->getPointeeType();
587 Region = state->getSVal(Region).getAsRegion();
590 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
594 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
596 ExplodedNodeSet &Dst) {
597 ProgramStateRef State = Pred->getState();
598 const LocationContext *LCtx = Pred->getLocationContext();
599 const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
600 const Stmt *Arg = DE->getArgument();
601 SVal ArgVal = State->getSVal(Arg, LCtx);
603 // If the argument to delete is known to be a null value,
604 // don't run destructor.
605 if (State->isNull(ArgVal).isConstrainedTrue()) {
606 QualType DTy = DE->getDestroyedType();
607 QualType BTy = getContext().getBaseElementType(DTy);
608 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
609 const CXXDestructorDecl *Dtor = RD->getDestructor();
611 PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
612 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
613 Bldr.generateNode(PP, Pred->getState(), Pred);
617 VisitCXXDestructor(DE->getDestroyedType(),
618 ArgVal.getAsRegion(),
619 DE, /*IsBase=*/ false,
623 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
624 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
625 const LocationContext *LCtx = Pred->getLocationContext();
627 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
628 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
629 LCtx->getCurrentStackFrame());
630 SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
632 // Create the base object region.
633 const CXXBaseSpecifier *Base = D.getBaseSpecifier();
634 QualType BaseTy = Base->getType();
635 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
638 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
639 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst);
642 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
643 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
644 const FieldDecl *Member = D.getFieldDecl();
645 ProgramStateRef State = Pred->getState();
646 const LocationContext *LCtx = Pred->getLocationContext();
648 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
649 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
650 LCtx->getCurrentStackFrame());
652 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
654 VisitCXXDestructor(Member->getType(),
655 FieldVal.castAs<loc::MemRegionVal>().getRegion(),
656 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
659 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
661 ExplodedNodeSet &Dst) {
663 QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType();
665 // FIXME: Inlining of temporary destructors is not supported yet anyway, so we
666 // just put a NULL region for now. This will need to be changed later.
667 VisitCXXDestructor(varType, nullptr, D.getBindTemporaryExpr(),
668 /*IsBase=*/ false, Pred, Dst);
671 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
672 ExplodedNodeSet &DstTop) {
673 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
675 "Error evaluating statement");
677 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
679 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
681 switch (S->getStmtClass()) {
682 // C++ and ARC stuff we don't support yet.
683 case Expr::ObjCIndirectCopyRestoreExprClass:
684 case Stmt::CXXDependentScopeMemberExprClass:
685 case Stmt::CXXTryStmtClass:
686 case Stmt::CXXTypeidExprClass:
687 case Stmt::CXXUuidofExprClass:
688 case Stmt::MSPropertyRefExprClass:
689 case Stmt::CXXUnresolvedConstructExprClass:
690 case Stmt::DependentScopeDeclRefExprClass:
691 case Stmt::TypeTraitExprClass:
692 case Stmt::ArrayTypeTraitExprClass:
693 case Stmt::ExpressionTraitExprClass:
694 case Stmt::UnresolvedLookupExprClass:
695 case Stmt::UnresolvedMemberExprClass:
696 case Stmt::CXXNoexceptExprClass:
697 case Stmt::PackExpansionExprClass:
698 case Stmt::SubstNonTypeTemplateParmPackExprClass:
699 case Stmt::FunctionParmPackExprClass:
700 case Stmt::SEHTryStmtClass:
701 case Stmt::SEHExceptStmtClass:
702 case Stmt::SEHLeaveStmtClass:
703 case Stmt::LambdaExprClass:
704 case Stmt::SEHFinallyStmtClass: {
705 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
706 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
710 case Stmt::ParenExprClass:
711 llvm_unreachable("ParenExprs already handled.");
712 case Stmt::GenericSelectionExprClass:
713 llvm_unreachable("GenericSelectionExprs already handled.");
714 // Cases that should never be evaluated simply because they shouldn't
715 // appear in the CFG.
716 case Stmt::BreakStmtClass:
717 case Stmt::CaseStmtClass:
718 case Stmt::CompoundStmtClass:
719 case Stmt::ContinueStmtClass:
720 case Stmt::CXXForRangeStmtClass:
721 case Stmt::DefaultStmtClass:
722 case Stmt::DoStmtClass:
723 case Stmt::ForStmtClass:
724 case Stmt::GotoStmtClass:
725 case Stmt::IfStmtClass:
726 case Stmt::IndirectGotoStmtClass:
727 case Stmt::LabelStmtClass:
728 case Stmt::NoStmtClass:
729 case Stmt::NullStmtClass:
730 case Stmt::SwitchStmtClass:
731 case Stmt::WhileStmtClass:
732 case Expr::MSDependentExistsStmtClass:
733 case Stmt::CapturedStmtClass:
734 case Stmt::OMPParallelDirectiveClass:
735 case Stmt::OMPSimdDirectiveClass:
736 case Stmt::OMPForDirectiveClass:
737 case Stmt::OMPSectionsDirectiveClass:
738 case Stmt::OMPSectionDirectiveClass:
739 case Stmt::OMPSingleDirectiveClass:
740 case Stmt::OMPMasterDirectiveClass:
741 case Stmt::OMPCriticalDirectiveClass:
742 case Stmt::OMPParallelForDirectiveClass:
743 case Stmt::OMPParallelSectionsDirectiveClass:
744 case Stmt::OMPTaskDirectiveClass:
745 case Stmt::OMPTaskyieldDirectiveClass:
746 case Stmt::OMPBarrierDirectiveClass:
747 case Stmt::OMPTaskwaitDirectiveClass:
748 case Stmt::OMPFlushDirectiveClass:
749 llvm_unreachable("Stmt should not be in analyzer evaluation loop");
751 case Stmt::ObjCSubscriptRefExprClass:
752 case Stmt::ObjCPropertyRefExprClass:
753 llvm_unreachable("These are handled by PseudoObjectExpr");
755 case Stmt::GNUNullExprClass: {
756 // GNU __null is a pointer-width integer, not an actual pointer.
757 ProgramStateRef state = Pred->getState();
758 state = state->BindExpr(S, Pred->getLocationContext(),
759 svalBuilder.makeIntValWithPtrWidth(0, false));
760 Bldr.generateNode(S, Pred, state);
764 case Stmt::ObjCAtSynchronizedStmtClass:
765 Bldr.takeNodes(Pred);
766 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
770 case Stmt::ExprWithCleanupsClass:
771 // Handled due to fully linearised CFG.
774 // Cases not handled yet; but will handle some day.
775 case Stmt::DesignatedInitExprClass:
776 case Stmt::ExtVectorElementExprClass:
777 case Stmt::ImaginaryLiteralClass:
778 case Stmt::ObjCAtCatchStmtClass:
779 case Stmt::ObjCAtFinallyStmtClass:
780 case Stmt::ObjCAtTryStmtClass:
781 case Stmt::ObjCAutoreleasePoolStmtClass:
782 case Stmt::ObjCEncodeExprClass:
783 case Stmt::ObjCIsaExprClass:
784 case Stmt::ObjCProtocolExprClass:
785 case Stmt::ObjCSelectorExprClass:
786 case Stmt::ParenListExprClass:
787 case Stmt::PredefinedExprClass:
788 case Stmt::ShuffleVectorExprClass:
789 case Stmt::ConvertVectorExprClass:
790 case Stmt::VAArgExprClass:
791 case Stmt::CUDAKernelCallExprClass:
792 case Stmt::OpaqueValueExprClass:
793 case Stmt::AsTypeExprClass:
794 case Stmt::AtomicExprClass:
797 // Cases we intentionally don't evaluate, since they don't need
798 // to be explicitly evaluated.
799 case Stmt::AddrLabelExprClass:
800 case Stmt::AttributedStmtClass:
801 case Stmt::IntegerLiteralClass:
802 case Stmt::CharacterLiteralClass:
803 case Stmt::ImplicitValueInitExprClass:
804 case Stmt::CXXScalarValueInitExprClass:
805 case Stmt::CXXBoolLiteralExprClass:
806 case Stmt::ObjCBoolLiteralExprClass:
807 case Stmt::FloatingLiteralClass:
808 case Stmt::SizeOfPackExprClass:
809 case Stmt::StringLiteralClass:
810 case Stmt::ObjCStringLiteralClass:
811 case Stmt::CXXBindTemporaryExprClass:
812 case Stmt::CXXPseudoDestructorExprClass:
813 case Stmt::SubstNonTypeTemplateParmExprClass:
814 case Stmt::CXXNullPtrLiteralExprClass: {
815 Bldr.takeNodes(Pred);
816 ExplodedNodeSet preVisit;
817 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
818 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
823 case Stmt::CXXDefaultArgExprClass:
824 case Stmt::CXXDefaultInitExprClass: {
825 Bldr.takeNodes(Pred);
826 ExplodedNodeSet PreVisit;
827 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
830 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
833 if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
834 ArgE = DefE->getExpr();
835 else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
836 ArgE = DefE->getExpr();
838 llvm_unreachable("unknown constant wrapper kind");
840 bool IsTemporary = false;
841 if (const MaterializeTemporaryExpr *MTE =
842 dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
843 ArgE = MTE->GetTemporaryExpr();
847 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
849 ConstantVal = UnknownVal();
851 const LocationContext *LCtx = Pred->getLocationContext();
852 for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
854 ProgramStateRef State = (*I)->getState();
855 State = State->BindExpr(S, LCtx, *ConstantVal);
857 State = createTemporaryRegionIfNeeded(State, LCtx,
860 Bldr2.generateNode(S, *I, State);
863 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
868 // Cases we evaluate as opaque expressions, conjuring a symbol.
869 case Stmt::CXXStdInitializerListExprClass:
870 case Expr::ObjCArrayLiteralClass:
871 case Expr::ObjCDictionaryLiteralClass:
872 case Expr::ObjCBoxedExprClass: {
873 Bldr.takeNodes(Pred);
875 ExplodedNodeSet preVisit;
876 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
879 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
881 const Expr *Ex = cast<Expr>(S);
882 QualType resultType = Ex->getType();
884 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
886 ExplodedNode *N = *it;
887 const LocationContext *LCtx = N->getLocationContext();
888 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
890 currBldrCtx->blockCount());
891 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
892 Bldr2.generateNode(S, N, state);
895 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
900 case Stmt::ArraySubscriptExprClass:
901 Bldr.takeNodes(Pred);
902 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
906 case Stmt::GCCAsmStmtClass:
907 Bldr.takeNodes(Pred);
908 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
912 case Stmt::MSAsmStmtClass:
913 Bldr.takeNodes(Pred);
914 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
918 case Stmt::BlockExprClass:
919 Bldr.takeNodes(Pred);
920 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
924 case Stmt::BinaryOperatorClass: {
925 const BinaryOperator* B = cast<BinaryOperator>(S);
926 if (B->isLogicalOp()) {
927 Bldr.takeNodes(Pred);
928 VisitLogicalExpr(B, Pred, Dst);
932 else if (B->getOpcode() == BO_Comma) {
933 ProgramStateRef state = Pred->getState();
934 Bldr.generateNode(B, Pred,
935 state->BindExpr(B, Pred->getLocationContext(),
936 state->getSVal(B->getRHS(),
937 Pred->getLocationContext())));
941 Bldr.takeNodes(Pred);
943 if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
944 (B->isRelationalOp() || B->isEqualityOp())) {
946 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
947 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
950 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
956 case Stmt::CXXOperatorCallExprClass: {
957 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
959 // For instance method operators, make sure the 'this' argument has a
961 const Decl *Callee = OCE->getCalleeDecl();
962 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
963 if (MD->isInstance()) {
964 ProgramStateRef State = Pred->getState();
965 const LocationContext *LCtx = Pred->getLocationContext();
966 ProgramStateRef NewState =
967 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
968 if (NewState != State) {
969 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
970 ProgramPoint::PreStmtKind);
979 case Stmt::CallExprClass:
980 case Stmt::CXXMemberCallExprClass:
981 case Stmt::UserDefinedLiteralClass: {
982 Bldr.takeNodes(Pred);
983 VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
988 case Stmt::CXXCatchStmtClass: {
989 Bldr.takeNodes(Pred);
990 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
995 case Stmt::CXXTemporaryObjectExprClass:
996 case Stmt::CXXConstructExprClass: {
997 Bldr.takeNodes(Pred);
998 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1003 case Stmt::CXXNewExprClass: {
1004 Bldr.takeNodes(Pred);
1005 ExplodedNodeSet PostVisit;
1006 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
1007 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1012 case Stmt::CXXDeleteExprClass: {
1013 Bldr.takeNodes(Pred);
1014 ExplodedNodeSet PreVisit;
1015 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
1016 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1018 for (ExplodedNodeSet::iterator i = PreVisit.begin(),
1019 e = PreVisit.end(); i != e ; ++i)
1020 VisitCXXDeleteExpr(CDE, *i, Dst);
1025 // FIXME: ChooseExpr is really a constant. We need to fix
1026 // the CFG do not model them as explicit control-flow.
1028 case Stmt::ChooseExprClass: { // __builtin_choose_expr
1029 Bldr.takeNodes(Pred);
1030 const ChooseExpr *C = cast<ChooseExpr>(S);
1031 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1036 case Stmt::CompoundAssignOperatorClass:
1037 Bldr.takeNodes(Pred);
1038 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1042 case Stmt::CompoundLiteralExprClass:
1043 Bldr.takeNodes(Pred);
1044 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1048 case Stmt::BinaryConditionalOperatorClass:
1049 case Stmt::ConditionalOperatorClass: { // '?' operator
1050 Bldr.takeNodes(Pred);
1051 const AbstractConditionalOperator *C
1052 = cast<AbstractConditionalOperator>(S);
1053 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1058 case Stmt::CXXThisExprClass:
1059 Bldr.takeNodes(Pred);
1060 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1064 case Stmt::DeclRefExprClass: {
1065 Bldr.takeNodes(Pred);
1066 const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1067 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1072 case Stmt::DeclStmtClass:
1073 Bldr.takeNodes(Pred);
1074 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1078 case Stmt::ImplicitCastExprClass:
1079 case Stmt::CStyleCastExprClass:
1080 case Stmt::CXXStaticCastExprClass:
1081 case Stmt::CXXDynamicCastExprClass:
1082 case Stmt::CXXReinterpretCastExprClass:
1083 case Stmt::CXXConstCastExprClass:
1084 case Stmt::CXXFunctionalCastExprClass:
1085 case Stmt::ObjCBridgedCastExprClass: {
1086 Bldr.takeNodes(Pred);
1087 const CastExpr *C = cast<CastExpr>(S);
1088 // Handle the previsit checks.
1089 ExplodedNodeSet dstPrevisit;
1090 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
1092 // Handle the expression itself.
1093 ExplodedNodeSet dstExpr;
1094 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1095 e = dstPrevisit.end(); i != e ; ++i) {
1096 VisitCast(C, C->getSubExpr(), *i, dstExpr);
1099 // Handle the postvisit checks.
1100 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1105 case Expr::MaterializeTemporaryExprClass: {
1106 Bldr.takeNodes(Pred);
1107 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1108 CreateCXXTemporaryObject(MTE, Pred, Dst);
1113 case Stmt::InitListExprClass:
1114 Bldr.takeNodes(Pred);
1115 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1119 case Stmt::MemberExprClass:
1120 Bldr.takeNodes(Pred);
1121 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1125 case Stmt::ObjCIvarRefExprClass:
1126 Bldr.takeNodes(Pred);
1127 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1131 case Stmt::ObjCForCollectionStmtClass:
1132 Bldr.takeNodes(Pred);
1133 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1137 case Stmt::ObjCMessageExprClass:
1138 Bldr.takeNodes(Pred);
1139 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1143 case Stmt::ObjCAtThrowStmtClass:
1144 case Stmt::CXXThrowExprClass:
1145 // FIXME: This is not complete. We basically treat @throw as
1147 Bldr.generateSink(S, Pred, Pred->getState());
1150 case Stmt::ReturnStmtClass:
1151 Bldr.takeNodes(Pred);
1152 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1156 case Stmt::OffsetOfExprClass:
1157 Bldr.takeNodes(Pred);
1158 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1162 case Stmt::UnaryExprOrTypeTraitExprClass:
1163 Bldr.takeNodes(Pred);
1164 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1169 case Stmt::StmtExprClass: {
1170 const StmtExpr *SE = cast<StmtExpr>(S);
1172 if (SE->getSubStmt()->body_empty()) {
1173 // Empty statement expression.
1174 assert(SE->getType() == getContext().VoidTy
1175 && "Empty statement expression must have void type.");
1179 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1180 ProgramStateRef state = Pred->getState();
1181 Bldr.generateNode(SE, Pred,
1182 state->BindExpr(SE, Pred->getLocationContext(),
1183 state->getSVal(LastExpr,
1184 Pred->getLocationContext())));
1189 case Stmt::UnaryOperatorClass: {
1190 Bldr.takeNodes(Pred);
1191 const UnaryOperator *U = cast<UnaryOperator>(S);
1192 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1193 ExplodedNodeSet Tmp;
1194 VisitUnaryOperator(U, Pred, Tmp);
1195 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1198 VisitUnaryOperator(U, Pred, Dst);
1203 case Stmt::PseudoObjectExprClass: {
1204 Bldr.takeNodes(Pred);
1205 ProgramStateRef state = Pred->getState();
1206 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1207 if (const Expr *Result = PE->getResultExpr()) {
1208 SVal V = state->getSVal(Result, Pred->getLocationContext());
1209 Bldr.generateNode(S, Pred,
1210 state->BindExpr(S, Pred->getLocationContext(), V));
1213 Bldr.generateNode(S, Pred,
1214 state->BindExpr(S, Pred->getLocationContext(),
1223 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1224 const LocationContext *CalleeLC) {
1225 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1226 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1227 assert(CalleeSF && CallerSF);
1228 ExplodedNode *BeforeProcessingCall = nullptr;
1229 const Stmt *CE = CalleeSF->getCallSite();
1231 // Find the first node before we started processing the call expression.
1233 ProgramPoint L = N->getLocation();
1234 BeforeProcessingCall = N;
1235 N = N->pred_empty() ? nullptr : *(N->pred_begin());
1237 // Skip the nodes corresponding to the inlined code.
1238 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1240 // We reached the caller. Find the node right before we started
1241 // processing the call.
1242 if (L.isPurgeKind())
1244 if (L.getAs<PreImplicitCall>())
1246 if (L.getAs<CallEnter>())
1248 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1249 if (SP->getStmt() == CE)
1254 if (!BeforeProcessingCall)
1257 // TODO: Clean up the unneeded nodes.
1259 // Build an Epsilon node from which we will restart the analyzes.
1260 // Note that CE is permitted to be NULL!
1261 ProgramPoint NewNodeLoc =
1262 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1263 // Add the special flag to GDM to signal retrying with no inlining.
1264 // Note, changing the state ensures that we are not going to cache out.
1265 ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1267 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1269 // Make the new node a successor of BeforeProcessingCall.
1271 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1272 // We cached out at this point. Caching out is common due to us backtracking
1273 // from the inlined function, which might spawn several paths.
1277 NewNode->addPredecessor(BeforeProcessingCall, G);
1279 // Add the new node to the work list.
1280 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1281 CalleeSF->getIndex());
1282 NumTimesRetriedWithoutInlining++;
1286 /// Block entrance. (Update counters).
1287 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1288 NodeBuilderWithSinks &nodeBuilder,
1289 ExplodedNode *Pred) {
1290 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1292 // FIXME: Refactor this into a checker.
1293 if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) {
1294 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1295 const ExplodedNode *Sink =
1296 nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1298 // Check if we stopped at the top level function or not.
1299 // Root node should have the location context of the top most function.
1300 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1301 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1302 const LocationContext *RootLC =
1303 (*G.roots_begin())->getLocation().getLocationContext();
1304 if (RootLC->getCurrentStackFrame() != CalleeSF) {
1305 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1307 // Re-run the call evaluation without inlining it, by storing the
1308 // no-inlining policy in the state and enqueuing the new work item on
1309 // the list. Replay should almost never fail. Use the stats to catch it
1311 if ((!AMgr.options.NoRetryExhausted &&
1312 replayWithoutInlining(Pred, CalleeLC)))
1314 NumMaxBlockCountReachedInInlined++;
1316 NumMaxBlockCountReached++;
1318 // Make sink nodes as exhausted(for stats) only if retry failed.
1319 Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1323 //===----------------------------------------------------------------------===//
1324 // Branch processing.
1325 //===----------------------------------------------------------------------===//
1327 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1328 /// to try to recover some path-sensitivity for casts of symbolic
1329 /// integers that promote their values (which are currently not tracked well).
1330 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1331 // cast(s) did was sign-extend the original value.
1332 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1333 ProgramStateRef state,
1334 const Stmt *Condition,
1335 const LocationContext *LCtx,
1338 const Expr *Ex = dyn_cast<Expr>(Condition);
1340 return UnknownVal();
1343 bool bitsInit = false;
1345 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1346 QualType T = CE->getType();
1348 if (!T->isIntegralOrEnumerationType())
1349 return UnknownVal();
1351 uint64_t newBits = Ctx.getTypeSize(T);
1352 if (!bitsInit || newBits < bits) {
1357 Ex = CE->getSubExpr();
1360 // We reached a non-cast. Is it a symbolic value?
1361 QualType T = Ex->getType();
1363 if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1364 Ctx.getTypeSize(T) > bits)
1365 return UnknownVal();
1367 return state->getSVal(Ex, LCtx);
1371 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1373 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1374 if (!BO || !BO->isLogicalOp()) {
1377 Condition = BO->getRHS()->IgnoreParens();
1383 // Returns the condition the branch at the end of 'B' depends on and whose value
1384 // has been evaluated within 'B'.
1385 // In most cases, the terminator condition of 'B' will be evaluated fully in
1386 // the last statement of 'B'; in those cases, the resolved condition is the
1387 // given 'Condition'.
1388 // If the condition of the branch is a logical binary operator tree, the CFG is
1389 // optimized: in that case, we know that the expression formed by all but the
1390 // rightmost leaf of the logical binary operator tree must be true, and thus
1391 // the branch condition is at this point equivalent to the truth value of that
1392 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1393 // expression in its final statement. As the full condition in that case was
1394 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1395 // expression to evaluate the truth value of the condition in the current state
1397 static const Stmt *ResolveCondition(const Stmt *Condition,
1398 const CFGBlock *B) {
1399 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1400 Condition = Ex->IgnoreParens();
1402 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1403 if (!BO || !BO->isLogicalOp())
1406 // FIXME: This is a workaround until we handle temporary destructor branches
1407 // correctly; currently, temporary destructor branches lead to blocks that
1408 // only have a terminator (and no statements). These blocks violate the
1409 // invariant this function assumes.
1410 if (B->getTerminator().isTemporaryDtorsBranch()) return Condition;
1412 // For logical operations, we still have the case where some branches
1413 // use the traditional "merge" approach and others sink the branch
1414 // directly into the basic blocks representing the logical operation.
1415 // We need to distinguish between those two cases here.
1417 // The invariants are still shifting, but it is possible that the
1418 // last element in a CFGBlock is not a CFGStmt. Look for the last
1419 // CFGStmt as the value of the condition.
1420 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1421 for (; I != E; ++I) {
1422 CFGElement Elem = *I;
1423 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1426 const Stmt *LastStmt = CS->getStmt();
1427 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
1430 llvm_unreachable("could not resolve condition");
1433 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1434 NodeBuilderContext& BldCtx,
1436 ExplodedNodeSet &Dst,
1437 const CFGBlock *DstT,
1438 const CFGBlock *DstF) {
1439 const LocationContext *LCtx = Pred->getLocationContext();
1440 PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1441 currBldrCtx = &BldCtx;
1443 // Check for NULL conditions; e.g. "for(;;)"
1445 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1446 NullCondBldr.markInfeasible(false);
1447 NullCondBldr.generateNode(Pred->getState(), true, Pred);
1452 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1453 Condition = Ex->IgnoreParens();
1455 Condition = ResolveCondition(Condition, BldCtx.getBlock());
1456 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1457 Condition->getLocStart(),
1458 "Error evaluating branch");
1460 ExplodedNodeSet CheckersOutSet;
1461 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1463 // We generated only sinks.
1464 if (CheckersOutSet.empty())
1467 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1468 for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1469 E = CheckersOutSet.end(); E != I; ++I) {
1470 ExplodedNode *PredI = *I;
1472 if (PredI->isSink())
1475 ProgramStateRef PrevState = PredI->getState();
1476 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1478 if (X.isUnknownOrUndef()) {
1479 // Give it a chance to recover from unknown.
1480 if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1481 if (Ex->getType()->isIntegralOrEnumerationType()) {
1482 // Try to recover some path-sensitivity. Right now casts of symbolic
1483 // integers that promote their values are currently not tracked well.
1484 // If 'Condition' is such an expression, try and recover the
1485 // underlying value and use that instead.
1486 SVal recovered = RecoverCastedSymbol(getStateManager(),
1487 PrevState, Condition,
1488 PredI->getLocationContext(),
1491 if (!recovered.isUnknown()) {
1498 // If the condition is still unknown, give up.
1499 if (X.isUnknownOrUndef()) {
1500 builder.generateNode(PrevState, true, PredI);
1501 builder.generateNode(PrevState, false, PredI);
1505 DefinedSVal V = X.castAs<DefinedSVal>();
1507 ProgramStateRef StTrue, StFalse;
1508 std::tie(StTrue, StFalse) = PrevState->assume(V);
1510 // Process the true branch.
1511 if (builder.isFeasible(true)) {
1513 builder.generateNode(StTrue, true, PredI);
1515 builder.markInfeasible(true);
1518 // Process the false branch.
1519 if (builder.isFeasible(false)) {
1521 builder.generateNode(StFalse, false, PredI);
1523 builder.markInfeasible(false);
1526 currBldrCtx = nullptr;
1529 /// The GDM component containing the set of global variables which have been
1530 /// previously initialized with explicit initializers.
1531 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1532 llvm::ImmutableSet<const VarDecl *>)
1534 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1535 NodeBuilderContext &BuilderCtx,
1537 clang::ento::ExplodedNodeSet &Dst,
1538 const CFGBlock *DstT,
1539 const CFGBlock *DstF) {
1540 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1541 currBldrCtx = &BuilderCtx;
1543 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1544 ProgramStateRef state = Pred->getState();
1545 bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1546 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1549 state = state->add<InitializedGlobalsSet>(VD);
1552 builder.generateNode(state, initHasRun, Pred);
1553 builder.markInfeasible(!initHasRun);
1555 currBldrCtx = nullptr;
1558 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
1559 /// nodes by processing the 'effects' of a computed goto jump.
1560 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1562 ProgramStateRef state = builder.getState();
1563 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1565 // Three possibilities:
1567 // (1) We know the computed label.
1568 // (2) The label is NULL (or some other constant), or Undefined.
1569 // (3) We have no clue about the label. Dispatch to all targets.
1572 typedef IndirectGotoNodeBuilder::iterator iterator;
1574 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1575 const LabelDecl *L = LV->getLabel();
1577 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1578 if (I.getLabel() == L) {
1579 builder.generateNode(I, state);
1584 llvm_unreachable("No block with label.");
1587 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1588 // Dispatch to the first target and mark it as a sink.
1589 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1590 // FIXME: add checker visit.
1591 // UndefBranches.insert(N);
1595 // This is really a catch-all. We don't support symbolics yet.
1596 // FIXME: Implement dispatch for symbolic pointers.
1598 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1599 builder.generateNode(I, state);
1602 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
1603 /// nodes when the control reaches the end of a function.
1604 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1605 ExplodedNode *Pred) {
1606 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1607 StateMgr.EndPath(Pred->getState());
1609 ExplodedNodeSet Dst;
1610 if (Pred->getLocationContext()->inTopFrame()) {
1611 // Remove dead symbols.
1612 ExplodedNodeSet AfterRemovedDead;
1613 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1616 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1617 E = AfterRemovedDead.end(); I != E; ++I) {
1618 getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1621 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1624 Engine.enqueueEndOfFunction(Dst);
1627 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
1628 /// nodes by processing the 'effects' of a switch statement.
1629 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1630 typedef SwitchNodeBuilder::iterator iterator;
1631 ProgramStateRef state = builder.getState();
1632 const Expr *CondE = builder.getCondition();
1633 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1635 if (CondV_untested.isUndef()) {
1636 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1637 // FIXME: add checker
1638 //UndefBranches.insert(N);
1642 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1644 ProgramStateRef DefaultSt = state;
1646 iterator I = builder.begin(), EI = builder.end();
1647 bool defaultIsFeasible = I == EI;
1649 for ( ; I != EI; ++I) {
1650 // Successor may be pruned out during CFG construction.
1654 const CaseStmt *Case = I.getCase();
1656 // Evaluate the LHS of the case value.
1657 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1658 assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1660 // Get the RHS of the case, if it exists.
1662 if (const Expr *E = Case->getRHS())
1663 V2 = E->EvaluateKnownConstInt(getContext());
1667 // FIXME: Eventually we should replace the logic below with a range
1668 // comparison, rather than concretize the values within the range.
1669 // This should be easy once we have "ranges" for NonLVals.
1672 nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
1673 DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
1676 // Now "assume" that the case matches.
1677 if (ProgramStateRef stateNew = state->assume(Res, true)) {
1678 builder.generateCaseStmtNode(I, stateNew);
1680 // If CondV evaluates to a constant, then we know that this
1681 // is the *only* case that we can take, so stop evaluating the
1683 if (CondV.getAs<nonloc::ConcreteInt>())
1687 // Now "assume" that the case doesn't match. Add this state
1688 // to the default state (if it is feasible).
1690 if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
1691 defaultIsFeasible = true;
1692 DefaultSt = stateNew;
1695 defaultIsFeasible = false;
1696 DefaultSt = nullptr;
1700 // Concretize the next value in the range.
1710 if (!defaultIsFeasible)
1713 // If we have switch(enum value), the default branch is not
1714 // feasible if all of the enum constants not covered by 'case:' statements
1715 // are not feasible values for the switch condition.
1717 // Note that this isn't as accurate as it could be. Even if there isn't
1718 // a case for a particular enum value as long as that enum value isn't
1719 // feasible then it shouldn't be considered for making 'default:' reachable.
1720 const SwitchStmt *SS = builder.getSwitch();
1721 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1722 if (CondExpr->getType()->getAs<EnumType>()) {
1723 if (SS->isAllEnumCasesCovered())
1727 builder.generateDefaultCaseNode(DefaultSt);
1730 //===----------------------------------------------------------------------===//
1731 // Transfer functions: Loads and stores.
1732 //===----------------------------------------------------------------------===//
1734 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1736 ExplodedNodeSet &Dst) {
1737 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1739 ProgramStateRef state = Pred->getState();
1740 const LocationContext *LCtx = Pred->getLocationContext();
1742 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1743 // C permits "extern void v", and if you cast the address to a valid type,
1744 // you can even do things with it. We simply pretend
1745 assert(Ex->isGLValue() || VD->getType()->isVoidType());
1746 SVal V = state->getLValue(VD, Pred->getLocationContext());
1748 // For references, the 'lvalue' is the pointer address stored in the
1749 // reference region.
1750 if (VD->getType()->isReferenceType()) {
1751 if (const MemRegion *R = V.getAsRegion())
1752 V = state->getSVal(R);
1757 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1758 ProgramPoint::PostLValueKind);
1761 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
1762 assert(!Ex->isGLValue());
1763 SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1764 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
1767 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1768 SVal V = svalBuilder.getFunctionPointer(FD);
1769 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1770 ProgramPoint::PostLValueKind);
1773 if (isa<FieldDecl>(D)) {
1774 // FIXME: Compute lvalue of field pointers-to-member.
1775 // Right now we just use a non-null void pointer, so that it gives proper
1776 // results in boolean contexts.
1777 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
1778 currBldrCtx->blockCount());
1779 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
1780 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1781 ProgramPoint::PostLValueKind);
1785 llvm_unreachable("Support for this Decl not implemented.");
1788 /// VisitArraySubscriptExpr - Transfer function for array accesses
1789 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
1791 ExplodedNodeSet &Dst){
1793 const Expr *Base = A->getBase()->IgnoreParens();
1794 const Expr *Idx = A->getIdx()->IgnoreParens();
1797 ExplodedNodeSet checkerPreStmt;
1798 getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
1800 StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
1802 for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
1803 ei = checkerPreStmt.end(); it != ei; ++it) {
1804 const LocationContext *LCtx = (*it)->getLocationContext();
1805 ProgramStateRef state = (*it)->getState();
1806 SVal V = state->getLValue(A->getType(),
1807 state->getSVal(Idx, LCtx),
1808 state->getSVal(Base, LCtx));
1809 assert(A->isGLValue());
1810 Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), nullptr,
1811 ProgramPoint::PostLValueKind);
1815 /// VisitMemberExpr - Transfer function for member expressions.
1816 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
1817 ExplodedNodeSet &Dst) {
1819 // FIXME: Prechecks eventually go in ::Visit().
1820 ExplodedNodeSet CheckedSet;
1821 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
1823 ExplodedNodeSet EvalSet;
1824 ValueDecl *Member = M->getMemberDecl();
1826 // Handle static member variables and enum constants accessed via
1828 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
1829 ExplodedNodeSet Dst;
1830 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1832 VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
1835 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
1836 ExplodedNodeSet Tmp;
1838 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1840 ProgramStateRef state = (*I)->getState();
1841 const LocationContext *LCtx = (*I)->getLocationContext();
1842 Expr *BaseExpr = M->getBase();
1844 // Handle C++ method calls.
1845 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
1846 if (MD->isInstance())
1847 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1849 SVal MDVal = svalBuilder.getFunctionPointer(MD);
1850 state = state->BindExpr(M, LCtx, MDVal);
1852 Bldr.generateNode(M, *I, state);
1856 // Handle regular struct fields / member variables.
1857 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1858 SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
1860 FieldDecl *field = cast<FieldDecl>(Member);
1861 SVal L = state->getLValue(field, baseExprVal);
1863 if (M->isGLValue() || M->getType()->isArrayType()) {
1864 // We special-case rvalues of array type because the analyzer cannot
1865 // reason about them, since we expect all regions to be wrapped in Locs.
1866 // We instead treat these as lvalues and assume that they will decay to
1867 // pointers as soon as they are used.
1868 if (!M->isGLValue()) {
1869 assert(M->getType()->isArrayType());
1870 const ImplicitCastExpr *PE =
1871 dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParent(M));
1872 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
1873 llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
1877 if (field->getType()->isReferenceType()) {
1878 if (const MemRegion *R = L.getAsRegion())
1879 L = state->getSVal(R);
1884 Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
1885 ProgramPoint::PostLValueKind);
1888 evalLoad(Tmp, M, M, *I, state, L);
1894 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
1898 class CollectReachableSymbolsCallback : public SymbolVisitor {
1899 InvalidatedSymbols Symbols;
1901 CollectReachableSymbolsCallback(ProgramStateRef State) {}
1902 const InvalidatedSymbols &getSymbols() const { return Symbols; }
1904 bool VisitSymbol(SymbolRef Sym) override {
1905 Symbols.insert(Sym);
1909 } // end anonymous namespace
1911 // A value escapes in three possible cases:
1912 // (1) We are binding to something that is not a memory region.
1913 // (2) We are binding to a MemrRegion that does not have stack storage.
1914 // (3) We are binding to a MemRegion with stack storage that the store
1915 // does not understand.
1916 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
1917 SVal Loc, SVal Val) {
1918 // Are we storing to something that causes the value to "escape"?
1919 bool escapes = true;
1921 // TODO: Move to StoreManager.
1922 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
1923 escapes = !regionLoc->getRegion()->hasStackStorage();
1926 // To test (3), generate a new state with the binding added. If it is
1927 // the same state, then it escapes (since the store cannot represent
1929 // Do this only if we know that the store is not supposed to generate the
1931 SVal StoredVal = State->getSVal(regionLoc->getRegion());
1932 if (StoredVal != Val)
1933 escapes = (State == (State->bindLoc(*regionLoc, Val)));
1937 // If our store can represent the binding and we aren't storing to something
1938 // that doesn't have local storage then just return and have the simulation
1939 // state continue as is.
1943 // Otherwise, find all symbols referenced by 'val' that we are tracking
1944 // and stop tracking them.
1945 CollectReachableSymbolsCallback Scanner =
1946 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
1947 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
1948 State = getCheckerManager().runCheckersForPointerEscape(State,
1950 /*CallEvent*/ nullptr,
1958 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
1959 const InvalidatedSymbols *Invalidated,
1960 ArrayRef<const MemRegion *> ExplicitRegions,
1961 ArrayRef<const MemRegion *> Regions,
1962 const CallEvent *Call,
1963 RegionAndSymbolInvalidationTraits &ITraits) {
1965 if (!Invalidated || Invalidated->empty())
1969 return getCheckerManager().runCheckersForPointerEscape(State,
1975 // If the symbols were invalidated by a call, we want to find out which ones
1976 // were invalidated directly due to being arguments to the call.
1977 InvalidatedSymbols SymbolsDirectlyInvalidated;
1978 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1979 E = ExplicitRegions.end(); I != E; ++I) {
1980 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1981 SymbolsDirectlyInvalidated.insert(R->getSymbol());
1984 InvalidatedSymbols SymbolsIndirectlyInvalidated;
1985 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
1986 E = Invalidated->end(); I!=E; ++I) {
1988 if (SymbolsDirectlyInvalidated.count(sym))
1990 SymbolsIndirectlyInvalidated.insert(sym);
1993 if (!SymbolsDirectlyInvalidated.empty())
1994 State = getCheckerManager().runCheckersForPointerEscape(State,
1995 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
1997 // Notify about the symbols that get indirectly invalidated by the call.
1998 if (!SymbolsIndirectlyInvalidated.empty())
1999 State = getCheckerManager().runCheckersForPointerEscape(State,
2000 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2005 /// evalBind - Handle the semantics of binding a value to a specific location.
2006 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
2007 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2009 SVal location, SVal Val,
2010 bool atDeclInit, const ProgramPoint *PP) {
2012 const LocationContext *LC = Pred->getLocationContext();
2013 PostStmt PS(StoreE, LC);
2017 // Do a previsit of the bind.
2018 ExplodedNodeSet CheckedSet;
2019 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2020 StoreE, *this, *PP);
2023 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2025 // If the location is not a 'Loc', it will already be handled by
2026 // the checkers. There is nothing left to do.
2027 if (!location.getAs<Loc>()) {
2028 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2030 ProgramStateRef state = Pred->getState();
2031 state = processPointerEscapedOnBind(state, location, Val);
2032 Bldr.generateNode(L, state, Pred);
2037 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2039 ExplodedNode *PredI = *I;
2040 ProgramStateRef state = PredI->getState();
2042 state = processPointerEscapedOnBind(state, location, Val);
2044 // When binding the value, pass on the hint that this is a initialization.
2045 // For initializations, we do not need to inform clients of region
2047 state = state->bindLoc(location.castAs<Loc>(),
2048 Val, /* notifyChanges = */ !atDeclInit);
2050 const MemRegion *LocReg = nullptr;
2051 if (Optional<loc::MemRegionVal> LocRegVal =
2052 location.getAs<loc::MemRegionVal>()) {
2053 LocReg = LocRegVal->getRegion();
2056 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2057 Bldr.generateNode(L, state, PredI);
2061 /// evalStore - Handle the semantics of a store via an assignment.
2062 /// @param Dst The node set to store generated state nodes
2063 /// @param AssignE The assignment expression if the store happens in an
2065 /// @param LocationE The location expression that is stored to.
2066 /// @param state The current simulation state
2067 /// @param location The location to store the value
2068 /// @param Val The value to be stored
2069 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2070 const Expr *LocationE,
2072 ProgramStateRef state, SVal location, SVal Val,
2073 const ProgramPointTag *tag) {
2074 // Proceed with the store. We use AssignE as the anchor for the PostStore
2075 // ProgramPoint if it is non-NULL, and LocationE otherwise.
2076 const Expr *StoreE = AssignE ? AssignE : LocationE;
2078 // Evaluate the location (checks for bad dereferences).
2079 ExplodedNodeSet Tmp;
2080 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2085 if (location.isUndef())
2088 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2089 evalBind(Dst, StoreE, *NI, location, Val, false);
2092 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2094 const Expr *BoundEx,
2096 ProgramStateRef state,
2098 const ProgramPointTag *tag,
2101 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2103 // Are we loading from a region? This actually results in two loads; one
2104 // to fetch the address of the referenced value and one to fetch the
2105 // referenced value.
2106 if (const TypedValueRegion *TR =
2107 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2109 QualType ValTy = TR->getValueType();
2110 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2111 static SimpleProgramPointTag
2112 loadReferenceTag(TagProviderName, "Load Reference");
2113 ExplodedNodeSet Tmp;
2114 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2115 location, &loadReferenceTag,
2116 getContext().getPointerType(RT->getPointeeType()));
2118 // Perform the load from the referenced value.
2119 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2120 state = (*I)->getState();
2121 location = state->getSVal(BoundEx, (*I)->getLocationContext());
2122 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2128 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2131 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2133 const Expr *BoundEx,
2135 ProgramStateRef state,
2137 const ProgramPointTag *tag,
2141 // Evaluate the location (checks for bad dereferences).
2142 ExplodedNodeSet Tmp;
2143 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2147 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2148 if (location.isUndef())
2151 // Proceed with the load.
2152 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2153 state = (*NI)->getState();
2154 const LocationContext *LCtx = (*NI)->getLocationContext();
2156 SVal V = UnknownVal();
2157 if (location.isValid()) {
2158 if (LoadTy.isNull())
2159 LoadTy = BoundEx->getType();
2160 V = state->getSVal(location.castAs<Loc>(), LoadTy);
2163 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2164 ProgramPoint::PostLoadKind);
2168 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2170 const Stmt *BoundEx,
2172 ProgramStateRef state,
2174 const ProgramPointTag *tag,
2176 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2177 // Early checks for performance reason.
2178 if (location.isUnknown()) {
2182 ExplodedNodeSet Src;
2183 BldrTop.takeNodes(Pred);
2184 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2185 if (Pred->getState() != state) {
2186 // Associate this new state with an ExplodedNode.
2187 // FIXME: If I pass null tag, the graph is incorrect, e.g for
2191 // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2192 // instead "int *p" is noted as
2193 // "Variable 'p' initialized to a null pointer value"
2195 static SimpleProgramPointTag tag(TagProviderName, "Location");
2196 Bldr.generateNode(NodeEx, Pred, state, &tag);
2198 ExplodedNodeSet Tmp;
2199 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2200 NodeEx, BoundEx, *this);
2201 BldrTop.addNodes(Tmp);
2204 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2205 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2206 static SimpleProgramPointTag
2207 eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2208 "Eagerly Assume True"),
2209 eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2210 "Eagerly Assume False");
2211 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2212 &eagerlyAssumeBinOpBifurcationFalse);
2215 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2216 ExplodedNodeSet &Src,
2218 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2220 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2221 ExplodedNode *Pred = *I;
2222 // Test if the previous node was as the same expression. This can happen
2223 // when the expression fails to evaluate to anything meaningful and
2224 // (as an optimization) we don't generate a node.
2225 ProgramPoint P = Pred->getLocation();
2226 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2230 ProgramStateRef state = Pred->getState();
2231 SVal V = state->getSVal(Ex, Pred->getLocationContext());
2232 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2233 if (SEV && SEV->isExpression()) {
2234 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2235 geteagerlyAssumeBinOpBifurcationTags();
2237 ProgramStateRef StateTrue, StateFalse;
2238 std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2240 // First assume that the condition is true.
2242 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2243 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2244 Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2247 // Next, assume that the condition is false.
2249 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2250 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2251 Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2257 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2258 ExplodedNodeSet &Dst) {
2259 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2260 // We have processed both the inputs and the outputs. All of the outputs
2261 // should evaluate to Locs. Nuke all of their values.
2263 // FIXME: Some day in the future it would be nice to allow a "plug-in"
2264 // which interprets the inline asm and stores proper results in the
2267 ProgramStateRef state = Pred->getState();
2269 for (const Expr *O : A->outputs()) {
2270 SVal X = state->getSVal(O, Pred->getLocationContext());
2271 assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2273 if (Optional<Loc> LV = X.getAs<Loc>())
2274 state = state->bindLoc(*LV, UnknownVal());
2277 Bldr.generateNode(A, Pred, state);
2280 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2281 ExplodedNodeSet &Dst) {
2282 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2283 Bldr.generateNode(A, Pred, Pred->getState());
2286 //===----------------------------------------------------------------------===//
2288 //===----------------------------------------------------------------------===//
2291 static ExprEngine* GraphPrintCheckerState;
2292 static SourceManager* GraphPrintSourceManager;
2296 struct DOTGraphTraits<ExplodedNode*> :
2297 public DefaultDOTGraphTraits {
2299 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2301 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2303 static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2306 // FIXME: Replace with a general scheme to tell if the node is
2308 if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
2309 GraphPrintCheckerState->isExplicitNullDeref(N) ||
2310 GraphPrintCheckerState->isUndefDeref(N) ||
2311 GraphPrintCheckerState->isUndefStore(N) ||
2312 GraphPrintCheckerState->isUndefControlFlow(N) ||
2313 GraphPrintCheckerState->isUndefResult(N) ||
2314 GraphPrintCheckerState->isBadCall(N) ||
2315 GraphPrintCheckerState->isUndefArg(N))
2316 return "color=\"red\",style=\"filled\"";
2318 if (GraphPrintCheckerState->isNoReturnCall(N))
2319 return "color=\"blue\",style=\"filled\"";
2324 static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2325 if (SLoc.isFileID()) {
2327 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2329 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2334 static std::string getNodeLabel(const ExplodedNode *N, void*){
2337 llvm::raw_string_ostream Out(sbuf);
2339 // Program Location.
2340 ProgramPoint Loc = N->getLocation();
2342 switch (Loc.getKind()) {
2343 case ProgramPoint::BlockEntranceKind: {
2344 Out << "Block Entrance: B"
2345 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2346 if (const NamedDecl *ND =
2347 dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
2355 case ProgramPoint::BlockExitKind:
2359 case ProgramPoint::CallEnterKind:
2363 case ProgramPoint::CallExitBeginKind:
2364 Out << "CallExitBegin";
2367 case ProgramPoint::CallExitEndKind:
2368 Out << "CallExitEnd";
2371 case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2372 Out << "PostStmtPurgeDeadSymbols";
2375 case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2376 Out << "PreStmtPurgeDeadSymbols";
2379 case ProgramPoint::EpsilonKind:
2380 Out << "Epsilon Point";
2383 case ProgramPoint::PreImplicitCallKind: {
2384 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2387 // FIXME: Get proper printing options.
2388 PC.getDecl()->print(Out, LangOptions());
2389 printLocation(Out, PC.getLocation());
2393 case ProgramPoint::PostImplicitCallKind: {
2394 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2395 Out << "PostCall: ";
2397 // FIXME: Get proper printing options.
2398 PC.getDecl()->print(Out, LangOptions());
2399 printLocation(Out, PC.getLocation());
2403 case ProgramPoint::PostInitializerKind: {
2404 Out << "PostInitializer: ";
2405 const CXXCtorInitializer *Init =
2406 Loc.castAs<PostInitializer>().getInitializer();
2407 if (const FieldDecl *FD = Init->getAnyMember())
2410 QualType Ty = Init->getTypeSourceInfo()->getType();
2411 Ty = Ty.getLocalUnqualifiedType();
2412 LangOptions LO; // FIXME.
2418 case ProgramPoint::BlockEdgeKind: {
2419 const BlockEdge &E = Loc.castAs<BlockEdge>();
2420 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2421 << E.getDst()->getBlockID() << ')';
2423 if (const Stmt *T = E.getSrc()->getTerminator()) {
2424 SourceLocation SLoc = T->getLocStart();
2426 Out << "\\|Terminator: ";
2427 LangOptions LO; // FIXME.
2428 E.getSrc()->printTerminator(Out, LO);
2430 if (SLoc.isFileID()) {
2432 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2434 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2437 if (isa<SwitchStmt>(T)) {
2438 const Stmt *Label = E.getDst()->getLabel();
2441 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2443 LangOptions LO; // FIXME.
2445 C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
2447 if (const Stmt *RHS = C->getRHS()) {
2449 RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
2455 assert (isa<DefaultStmt>(Label));
2456 Out << "\\ldefault:";
2460 Out << "\\l(implicit) default:";
2462 else if (isa<IndirectGotoStmt>(T)) {
2466 Out << "\\lCondition: ";
2467 if (*E.getSrc()->succ_begin() == E.getDst())
2477 // FIXME: Replace with a general scheme to determine
2478 // the name of the check.
2479 if (GraphPrintCheckerState->isUndefControlFlow(N)) {
2480 Out << "\\|Control-flow based on\\lUndefined value.\\l";
2487 const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2488 assert(S != nullptr && "Expecting non-null Stmt");
2490 Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2491 LangOptions LO; // FIXME.
2492 S->printPretty(Out, nullptr, PrintingPolicy(LO));
2493 printLocation(Out, S->getLocStart());
2495 if (Loc.getAs<PreStmt>())
2496 Out << "\\lPreStmt\\l;";
2497 else if (Loc.getAs<PostLoad>())
2498 Out << "\\lPostLoad\\l;";
2499 else if (Loc.getAs<PostStore>())
2500 Out << "\\lPostStore\\l";
2501 else if (Loc.getAs<PostLValue>())
2502 Out << "\\lPostLValue\\l";
2505 // FIXME: Replace with a general scheme to determine
2506 // the name of the check.
2507 if (GraphPrintCheckerState->isImplicitNullDeref(N))
2508 Out << "\\|Implicit-Null Dereference.\\l";
2509 else if (GraphPrintCheckerState->isExplicitNullDeref(N))
2510 Out << "\\|Explicit-Null Dereference.\\l";
2511 else if (GraphPrintCheckerState->isUndefDeref(N))
2512 Out << "\\|Dereference of undefialied value.\\l";
2513 else if (GraphPrintCheckerState->isUndefStore(N))
2514 Out << "\\|Store to Undefined Loc.";
2515 else if (GraphPrintCheckerState->isUndefResult(N))
2516 Out << "\\|Result of operation is undefined.";
2517 else if (GraphPrintCheckerState->isNoReturnCall(N))
2518 Out << "\\|Call to function marked \"noreturn\".";
2519 else if (GraphPrintCheckerState->isBadCall(N))
2520 Out << "\\|Call to NULL/Undefined.";
2521 else if (GraphPrintCheckerState->isUndefArg(N))
2522 Out << "\\|Argument in call is undefined";
2529 ProgramStateRef state = N->getState();
2530 Out << "\\|StateID: " << (const void*) state.get()
2531 << " NodeID: " << (const void*) N << "\\|";
2532 state->printDOT(Out);
2536 if (const ProgramPointTag *tag = Loc.getTag()) {
2537 Out << "\\|Tag: " << tag->getTagDescription();
2543 } // end llvm namespace
2547 template <typename ITERATOR>
2548 ExplodedNode *GetGraphNode(ITERATOR I) { return *I; }
2550 template <> ExplodedNode*
2551 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
2552 (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
2557 void ExprEngine::ViewGraph(bool trim) {
2560 std::vector<const ExplodedNode*> Src;
2562 // Flush any outstanding reports to make sure we cover all the nodes.
2563 // This does not cause them to get displayed.
2564 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2565 const_cast<BugType*>(*I)->FlushReports(BR);
2567 // Iterate through the reports and get their nodes.
2568 for (BugReporter::EQClasses_iterator
2569 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2570 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2571 if (N) Src.push_back(N);
2577 GraphPrintCheckerState = this;
2578 GraphPrintSourceManager = &getContext().getSourceManager();
2580 llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2582 GraphPrintCheckerState = nullptr;
2583 GraphPrintSourceManager = nullptr;
2588 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
2590 GraphPrintCheckerState = this;
2591 GraphPrintSourceManager = &getContext().getSourceManager();
2593 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2595 if (!TrimmedG.get())
2596 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2598 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2600 GraphPrintCheckerState = nullptr;
2601 GraphPrintSourceManager = nullptr;