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 #define DEBUG_TYPE "ExprEngine"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
19 #include "PrettyStackTraceLocationContext.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/ParentMap.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/Basic/Builtins.h"
25 #include "clang/Basic/PrettyStackTrace.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
28 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
31 #include "llvm/ADT/ImmutableList.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Support/GraphWriter.h"
39 using namespace clang;
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 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
59 SetOfConstDecls *VisitedCalleesIn,
60 FunctionSummariesTy *FS,
61 InliningModes HowToInlineIn)
63 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
66 StateMgr(getContext(), mgr.getStoreManagerCreator(),
67 mgr.getConstraintManagerCreator(), G.getAllocator(),
69 SymMgr(StateMgr.getSymbolManager()),
70 svalBuilder(StateMgr.getSValBuilder()),
71 currStmtIdx(0), currBldrCtx(0),
72 ObjCNoRet(mgr.getASTContext()),
73 ObjCGCEnabled(gcEnabled), BR(mgr, *this),
74 VisitedCallees(VisitedCalleesIn),
75 HowToInline(HowToInlineIn)
77 unsigned TrimInterval = mgr.options.getGraphTrimInterval();
78 if (TrimInterval != 0) {
79 // Enable eager node reclaimation when constructing the ExplodedGraph.
80 G.enableNodeReclamation(TrimInterval);
84 ExprEngine::~ExprEngine() {
88 //===----------------------------------------------------------------------===//
90 //===----------------------------------------------------------------------===//
92 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
93 ProgramStateRef state = StateMgr.getInitialState(InitLoc);
94 const Decl *D = InitLoc->getDecl();
97 // FIXME: It would be nice if we had a more general mechanism to add
98 // such preconditions. Some day.
101 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
102 // Precondition: the first argument of 'main' is an integer guaranteed
104 const IdentifierInfo *II = FD->getIdentifier();
105 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
108 const ParmVarDecl *PD = FD->getParamDecl(0);
109 QualType T = PD->getType();
110 const BuiltinType *BT = dyn_cast<BuiltinType>(T);
111 if (!BT || !BT->isInteger())
114 const MemRegion *R = state->getRegion(PD, InitLoc);
118 SVal V = state->getSVal(loc::MemRegionVal(R));
119 SVal Constraint_untested = evalBinOp(state, BO_GT, V,
120 svalBuilder.makeZeroVal(T),
123 Optional<DefinedOrUnknownSVal> Constraint =
124 Constraint_untested.getAs<DefinedOrUnknownSVal>();
129 if (ProgramStateRef newState = state->assume(*Constraint, true))
136 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
137 // Precondition: 'self' is always non-null upon entry to an Objective-C
139 const ImplicitParamDecl *SelfD = MD->getSelfDecl();
140 const MemRegion *R = state->getRegion(SelfD, InitLoc);
141 SVal V = state->getSVal(loc::MemRegionVal(R));
143 if (Optional<Loc> LV = V.getAs<Loc>()) {
144 // Assume that the pointer value in 'self' is non-null.
145 state = state->assume(*LV, true);
146 assert(state && "'self' cannot be null");
150 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
151 if (!MD->isStatic()) {
152 // Precondition: 'this' is always non-null upon entry to the
153 // top-level function. This is our starting assumption for
154 // analyzing an "open" program.
155 const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
156 if (SFC->getParent() == 0) {
157 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
158 SVal V = state->getSVal(L);
159 if (Optional<Loc> LV = V.getAs<Loc>()) {
160 state = state->assume(*LV, true);
161 assert(state && "'this' cannot be null");
171 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
172 const LocationContext *LC,
174 const Expr *Result) {
175 SVal V = State->getSVal(Ex, LC);
177 // If we don't have an explicit result expression, we're in "if needed"
178 // mode. Only create a region if the current value is a NonLoc.
179 if (!V.getAs<NonLoc>())
183 // We need to create a region no matter what. For sanity, make sure we don't
184 // try to stuff a Loc into a non-pointer temporary region.
185 assert(!V.getAs<Loc>() || Loc::isLocType(Result->getType()) ||
186 Result->getType()->isMemberPointerType());
189 ProgramStateManager &StateMgr = State->getStateManager();
190 MemRegionManager &MRMgr = StateMgr.getRegionManager();
191 StoreManager &StoreMgr = StateMgr.getStoreManager();
193 // We need to be careful about treating a derived type's value as
194 // bindings for a base type. Unless we're creating a temporary pointer region,
195 // start by stripping and recording base casts.
196 SmallVector<const CastExpr *, 4> Casts;
197 const Expr *Inner = Ex->IgnoreParens();
198 if (!Loc::isLocType(Result->getType())) {
199 while (const CastExpr *CE = dyn_cast<CastExpr>(Inner)) {
200 if (CE->getCastKind() == CK_DerivedToBase ||
201 CE->getCastKind() == CK_UncheckedDerivedToBase)
203 else if (CE->getCastKind() != CK_NoOp)
206 Inner = CE->getSubExpr()->IgnoreParens();
210 // Create a temporary object region for the inner expression (which may have
211 // a more derived type) and bind the value into it.
212 const TypedValueRegion *TR = NULL;
213 if (const MaterializeTemporaryExpr *MT =
214 dyn_cast<MaterializeTemporaryExpr>(Result)) {
215 StorageDuration SD = MT->getStorageDuration();
216 // If this object is bound to a reference with static storage duration, we
217 // put it in a different region to prevent "address leakage" warnings.
218 if (SD == SD_Static || SD == SD_Thread)
219 TR = MRMgr.getCXXStaticTempObjectRegion(Inner);
222 TR = MRMgr.getCXXTempObjectRegion(Inner, LC);
224 SVal Reg = loc::MemRegionVal(TR);
227 V = getSValBuilder().conjureSymbolVal(Result, LC, TR->getValueType(),
228 currBldrCtx->blockCount());
229 State = State->bindLoc(Reg, V);
231 // Re-apply the casts (from innermost to outermost) for type sanity.
232 for (SmallVectorImpl<const CastExpr *>::reverse_iterator I = Casts.rbegin(),
235 Reg = StoreMgr.evalDerivedToBase(Reg, *I);
238 State = State->BindExpr(Result, LC, Reg);
242 //===----------------------------------------------------------------------===//
243 // Top-level transfer function logic (Dispatcher).
244 //===----------------------------------------------------------------------===//
246 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
247 /// logic for handling assumptions on symbolic values.
248 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
249 SVal cond, bool assumption) {
250 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
253 bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
254 return getCheckerManager().wantsRegionChangeUpdate(state);
258 ExprEngine::processRegionChanges(ProgramStateRef state,
259 const InvalidatedSymbols *invalidated,
260 ArrayRef<const MemRegion *> Explicits,
261 ArrayRef<const MemRegion *> Regions,
262 const CallEvent *Call) {
263 return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
264 Explicits, Regions, Call);
267 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
268 const char *NL, const char *Sep) {
269 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
272 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
273 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
276 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
277 unsigned StmtIdx, NodeBuilderContext *Ctx) {
278 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
279 currStmtIdx = StmtIdx;
282 switch (E.getKind()) {
283 case CFGElement::Statement:
284 ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred);
286 case CFGElement::Initializer:
287 ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred);
289 case CFGElement::AutomaticObjectDtor:
290 case CFGElement::DeleteDtor:
291 case CFGElement::BaseDtor:
292 case CFGElement::MemberDtor:
293 case CFGElement::TemporaryDtor:
294 ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
299 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
301 const ExplodedNode *Pred,
302 const LocationContext *LC) {
304 // Are we never purging state values?
305 if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
308 // Is this the beginning of a basic block?
309 if (Pred->getLocation().getAs<BlockEntrance>())
312 // Is this on a non-expression?
313 if (!isa<Expr>(S.getStmt()))
316 // Run before processing a call.
317 if (CallEvent::isCallStmt(S.getStmt()))
320 // Is this an expression that is consumed by another expression? If so,
321 // postpone cleaning out the state.
322 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
323 return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
326 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
327 const Stmt *ReferenceStmt,
328 const LocationContext *LC,
329 const Stmt *DiagnosticStmt,
330 ProgramPoint::Kind K) {
331 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
332 ReferenceStmt == 0 || isa<ReturnStmt>(ReferenceStmt))
333 && "PostStmt is not generally supported by the SymbolReaper yet");
334 assert(LC && "Must pass the current (or expiring) LocationContext");
336 if (!DiagnosticStmt) {
337 DiagnosticStmt = ReferenceStmt;
338 assert(DiagnosticStmt && "Required for clearing a LocationContext");
341 NumRemoveDeadBindings++;
342 ProgramStateRef CleanedState = Pred->getState();
344 // LC is the location context being destroyed, but SymbolReaper wants a
345 // location context that is still live. (If this is the top-level stack
346 // frame, this will be null.)
347 if (!ReferenceStmt) {
348 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
349 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
350 LC = LC->getParent();
353 const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : 0;
354 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
356 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
358 // Create a state in which dead bindings are removed from the environment
359 // and the store. TODO: The function should just return new env and store,
361 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
363 // Process any special transfer function for dead symbols.
364 // A tag to track convenience transitions, which can be removed at cleanup.
365 static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node");
366 if (!SymReaper.hasDeadSymbols()) {
367 // Generate a CleanedNode that has the environment and store cleaned
368 // up. Since no symbols are dead, we can optimize and not clean out
369 // the constraint manager.
370 StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
371 Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
374 // Call checkers with the non-cleaned state so that they could query the
375 // values of the soon to be dead symbols.
376 ExplodedNodeSet CheckedSet;
377 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
378 DiagnosticStmt, *this, K);
380 // For each node in CheckedSet, generate CleanedNodes that have the
381 // environment, the store, and the constraints cleaned up but have the
382 // user-supplied states as the predecessors.
383 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
384 for (ExplodedNodeSet::const_iterator
385 I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
386 ProgramStateRef CheckerState = (*I)->getState();
388 // The constraint manager has not been cleaned up yet, so clean up now.
389 CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
392 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
393 "Checkers are not allowed to modify the Environment as a part of "
394 "checkDeadSymbols processing.");
395 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
396 "Checkers are not allowed to modify the Store as a part of "
397 "checkDeadSymbols processing.");
399 // Create a state based on CleanedState with CheckerState GDM and
400 // generate a transition to that state.
401 ProgramStateRef CleanedCheckerSt =
402 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
403 Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
408 void ExprEngine::ProcessStmt(const CFGStmt S,
409 ExplodedNode *Pred) {
410 // Reclaim any unnecessary nodes in the ExplodedGraph.
411 G.reclaimRecentlyAllocatedNodes();
413 const Stmt *currStmt = S.getStmt();
414 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
415 currStmt->getLocStart(),
416 "Error evaluating statement");
418 // Remove dead bindings and symbols.
419 ExplodedNodeSet CleanedStates;
420 if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
421 removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
423 CleanedStates.Add(Pred);
425 // Visit the statement.
427 for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
428 E = CleanedStates.end(); I != E; ++I) {
429 ExplodedNodeSet DstI;
430 // Visit the statement.
431 Visit(currStmt, *I, DstI);
435 // Enqueue the new nodes onto the work list.
436 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
439 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
440 ExplodedNode *Pred) {
441 const CXXCtorInitializer *BMI = Init.getInitializer();
443 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
444 BMI->getSourceLocation(),
445 "Error evaluating initializer");
447 // We don't clean up dead bindings here.
448 const StackFrameContext *stackFrame =
449 cast<StackFrameContext>(Pred->getLocationContext());
450 const CXXConstructorDecl *decl =
451 cast<CXXConstructorDecl>(stackFrame->getDecl());
453 ProgramStateRef State = Pred->getState();
454 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
456 ExplodedNodeSet Tmp(Pred);
459 // Evaluate the initializer, if necessary
460 if (BMI->isAnyMemberInitializer()) {
461 // Constructors build the object directly in the field,
462 // but non-objects must be copied in from the initializer.
463 const Expr *Init = BMI->getInit()->IgnoreImplicit();
464 if (!isa<CXXConstructExpr>(Init)) {
465 const ValueDecl *Field;
466 if (BMI->isIndirectMemberInitializer()) {
467 Field = BMI->getIndirectMember();
468 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
470 Field = BMI->getMember();
471 FieldLoc = State->getLValue(BMI->getMember(), thisVal);
475 if (BMI->getNumArrayIndices() > 0) {
476 // Handle arrays of trivial type. We can represent this with a
477 // primitive load/copy from the base array region.
478 const ArraySubscriptExpr *ASE;
479 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
480 Init = ASE->getBase()->IgnoreImplicit();
482 SVal LValue = State->getSVal(Init, stackFrame);
483 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
484 InitVal = State->getSVal(*LValueLoc);
486 // If we fail to get the value for some reason, use a symbolic value.
487 if (InitVal.isUnknownOrUndef()) {
488 SValBuilder &SVB = getSValBuilder();
489 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
491 currBldrCtx->blockCount());
494 InitVal = State->getSVal(BMI->getInit(), stackFrame);
497 assert(Tmp.size() == 1 && "have not generated any new nodes yet");
498 assert(*Tmp.begin() == Pred && "have not generated any new nodes yet");
501 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
502 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
505 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
506 // We already did all the work when visiting the CXXConstructExpr.
509 // Construct PostInitializer nodes whether the state changed or not,
510 // so that the diagnostics don't get confused.
511 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
513 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
514 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
515 ExplodedNode *N = *I;
516 Bldr.generateNode(PP, N->getState(), N);
519 // Enqueue the new nodes onto the work list.
520 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
523 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
524 ExplodedNode *Pred) {
526 switch (D.getKind()) {
527 case CFGElement::AutomaticObjectDtor:
528 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
530 case CFGElement::BaseDtor:
531 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
533 case CFGElement::MemberDtor:
534 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
536 case CFGElement::TemporaryDtor:
537 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
539 case CFGElement::DeleteDtor:
540 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
543 llvm_unreachable("Unexpected dtor kind.");
546 // Enqueue the new nodes onto the work list.
547 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
550 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
552 ExplodedNodeSet &Dst) {
553 const VarDecl *varDecl = Dtor.getVarDecl();
554 QualType varType = varDecl->getType();
556 ProgramStateRef state = Pred->getState();
557 SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
558 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
560 if (const ReferenceType *refType = varType->getAs<ReferenceType>()) {
561 varType = refType->getPointeeType();
562 Region = state->getSVal(Region).getAsRegion();
565 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
569 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
571 ExplodedNodeSet &Dst) {
572 ProgramStateRef State = Pred->getState();
573 const LocationContext *LCtx = Pred->getLocationContext();
574 const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
575 const Stmt *Arg = DE->getArgument();
576 SVal ArgVal = State->getSVal(Arg, LCtx);
578 // If the argument to delete is known to be a null value,
579 // don't run destructor.
580 if (State->isNull(ArgVal).isConstrainedTrue()) {
581 QualType DTy = DE->getDestroyedType();
582 QualType BTy = getContext().getBaseElementType(DTy);
583 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
584 const CXXDestructorDecl *Dtor = RD->getDestructor();
586 PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
587 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
588 Bldr.generateNode(PP, Pred->getState(), Pred);
592 VisitCXXDestructor(DE->getDestroyedType(),
593 ArgVal.getAsRegion(),
594 DE, /*IsBase=*/ false,
598 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
599 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
600 const LocationContext *LCtx = Pred->getLocationContext();
601 ProgramStateRef State = Pred->getState();
603 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
604 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
605 LCtx->getCurrentStackFrame());
606 SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
608 // Create the base object region.
609 const CXXBaseSpecifier *Base = D.getBaseSpecifier();
610 QualType BaseTy = Base->getType();
611 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
614 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
615 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst);
618 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
619 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
620 const FieldDecl *Member = D.getFieldDecl();
621 ProgramStateRef State = Pred->getState();
622 const LocationContext *LCtx = Pred->getLocationContext();
624 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
625 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
626 LCtx->getCurrentStackFrame());
628 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
630 VisitCXXDestructor(Member->getType(),
631 FieldVal.castAs<loc::MemRegionVal>().getRegion(),
632 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
635 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
637 ExplodedNodeSet &Dst) {
639 QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType();
641 // FIXME: Inlining of temporary destructors is not supported yet anyway, so we
642 // just put a NULL region for now. This will need to be changed later.
643 VisitCXXDestructor(varType, NULL, D.getBindTemporaryExpr(),
644 /*IsBase=*/ false, Pred, Dst);
647 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
648 ExplodedNodeSet &DstTop) {
649 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
651 "Error evaluating statement");
653 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
655 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
657 switch (S->getStmtClass()) {
658 // C++ and ARC stuff we don't support yet.
659 case Expr::ObjCIndirectCopyRestoreExprClass:
660 case Stmt::CXXDependentScopeMemberExprClass:
661 case Stmt::CXXTryStmtClass:
662 case Stmt::CXXTypeidExprClass:
663 case Stmt::CXXUuidofExprClass:
664 case Stmt::MSPropertyRefExprClass:
665 case Stmt::CXXUnresolvedConstructExprClass:
666 case Stmt::DependentScopeDeclRefExprClass:
667 case Stmt::UnaryTypeTraitExprClass:
668 case Stmt::BinaryTypeTraitExprClass:
669 case Stmt::TypeTraitExprClass:
670 case Stmt::ArrayTypeTraitExprClass:
671 case Stmt::ExpressionTraitExprClass:
672 case Stmt::UnresolvedLookupExprClass:
673 case Stmt::UnresolvedMemberExprClass:
674 case Stmt::CXXNoexceptExprClass:
675 case Stmt::PackExpansionExprClass:
676 case Stmt::SubstNonTypeTemplateParmPackExprClass:
677 case Stmt::FunctionParmPackExprClass:
678 case Stmt::SEHTryStmtClass:
679 case Stmt::SEHExceptStmtClass:
680 case Stmt::LambdaExprClass:
681 case Stmt::SEHFinallyStmtClass: {
682 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
683 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
687 case Stmt::ParenExprClass:
688 llvm_unreachable("ParenExprs already handled.");
689 case Stmt::GenericSelectionExprClass:
690 llvm_unreachable("GenericSelectionExprs already handled.");
691 // Cases that should never be evaluated simply because they shouldn't
692 // appear in the CFG.
693 case Stmt::BreakStmtClass:
694 case Stmt::CaseStmtClass:
695 case Stmt::CompoundStmtClass:
696 case Stmt::ContinueStmtClass:
697 case Stmt::CXXForRangeStmtClass:
698 case Stmt::DefaultStmtClass:
699 case Stmt::DoStmtClass:
700 case Stmt::ForStmtClass:
701 case Stmt::GotoStmtClass:
702 case Stmt::IfStmtClass:
703 case Stmt::IndirectGotoStmtClass:
704 case Stmt::LabelStmtClass:
705 case Stmt::NoStmtClass:
706 case Stmt::NullStmtClass:
707 case Stmt::SwitchStmtClass:
708 case Stmt::WhileStmtClass:
709 case Expr::MSDependentExistsStmtClass:
710 case Stmt::CapturedStmtClass:
711 case Stmt::OMPParallelDirectiveClass:
712 llvm_unreachable("Stmt should not be in analyzer evaluation loop");
714 case Stmt::ObjCSubscriptRefExprClass:
715 case Stmt::ObjCPropertyRefExprClass:
716 llvm_unreachable("These are handled by PseudoObjectExpr");
718 case Stmt::GNUNullExprClass: {
719 // GNU __null is a pointer-width integer, not an actual pointer.
720 ProgramStateRef state = Pred->getState();
721 state = state->BindExpr(S, Pred->getLocationContext(),
722 svalBuilder.makeIntValWithPtrWidth(0, false));
723 Bldr.generateNode(S, Pred, state);
727 case Stmt::ObjCAtSynchronizedStmtClass:
728 Bldr.takeNodes(Pred);
729 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
733 case Stmt::ExprWithCleanupsClass:
734 // Handled due to fully linearised CFG.
737 // Cases not handled yet; but will handle some day.
738 case Stmt::DesignatedInitExprClass:
739 case Stmt::ExtVectorElementExprClass:
740 case Stmt::ImaginaryLiteralClass:
741 case Stmt::ObjCAtCatchStmtClass:
742 case Stmt::ObjCAtFinallyStmtClass:
743 case Stmt::ObjCAtTryStmtClass:
744 case Stmt::ObjCAutoreleasePoolStmtClass:
745 case Stmt::ObjCEncodeExprClass:
746 case Stmt::ObjCIsaExprClass:
747 case Stmt::ObjCProtocolExprClass:
748 case Stmt::ObjCSelectorExprClass:
749 case Stmt::ParenListExprClass:
750 case Stmt::PredefinedExprClass:
751 case Stmt::ShuffleVectorExprClass:
752 case Stmt::ConvertVectorExprClass:
753 case Stmt::VAArgExprClass:
754 case Stmt::CUDAKernelCallExprClass:
755 case Stmt::OpaqueValueExprClass:
756 case Stmt::AsTypeExprClass:
757 case Stmt::AtomicExprClass:
760 // Cases we intentionally don't evaluate, since they don't need
761 // to be explicitly evaluated.
762 case Stmt::AddrLabelExprClass:
763 case Stmt::AttributedStmtClass:
764 case Stmt::IntegerLiteralClass:
765 case Stmt::CharacterLiteralClass:
766 case Stmt::ImplicitValueInitExprClass:
767 case Stmt::CXXScalarValueInitExprClass:
768 case Stmt::CXXBoolLiteralExprClass:
769 case Stmt::ObjCBoolLiteralExprClass:
770 case Stmt::FloatingLiteralClass:
771 case Stmt::SizeOfPackExprClass:
772 case Stmt::StringLiteralClass:
773 case Stmt::ObjCStringLiteralClass:
774 case Stmt::CXXBindTemporaryExprClass:
775 case Stmt::CXXPseudoDestructorExprClass:
776 case Stmt::SubstNonTypeTemplateParmExprClass:
777 case Stmt::CXXNullPtrLiteralExprClass: {
778 Bldr.takeNodes(Pred);
779 ExplodedNodeSet preVisit;
780 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
781 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
786 case Stmt::CXXDefaultArgExprClass:
787 case Stmt::CXXDefaultInitExprClass: {
788 Bldr.takeNodes(Pred);
789 ExplodedNodeSet PreVisit;
790 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
793 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
796 if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
797 ArgE = DefE->getExpr();
798 else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
799 ArgE = DefE->getExpr();
801 llvm_unreachable("unknown constant wrapper kind");
803 bool IsTemporary = false;
804 if (const MaterializeTemporaryExpr *MTE =
805 dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
806 ArgE = MTE->GetTemporaryExpr();
810 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
812 ConstantVal = UnknownVal();
814 const LocationContext *LCtx = Pred->getLocationContext();
815 for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
817 ProgramStateRef State = (*I)->getState();
818 State = State->BindExpr(S, LCtx, *ConstantVal);
820 State = createTemporaryRegionIfNeeded(State, LCtx,
823 Bldr2.generateNode(S, *I, State);
826 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
831 // Cases we evaluate as opaque expressions, conjuring a symbol.
832 case Stmt::CXXStdInitializerListExprClass:
833 case Expr::ObjCArrayLiteralClass:
834 case Expr::ObjCDictionaryLiteralClass:
835 case Expr::ObjCBoxedExprClass: {
836 Bldr.takeNodes(Pred);
838 ExplodedNodeSet preVisit;
839 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
842 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
844 const Expr *Ex = cast<Expr>(S);
845 QualType resultType = Ex->getType();
847 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
849 ExplodedNode *N = *it;
850 const LocationContext *LCtx = N->getLocationContext();
851 SVal result = svalBuilder.conjureSymbolVal(0, Ex, LCtx, resultType,
852 currBldrCtx->blockCount());
853 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
854 Bldr2.generateNode(S, N, state);
857 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
862 case Stmt::ArraySubscriptExprClass:
863 Bldr.takeNodes(Pred);
864 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
868 case Stmt::GCCAsmStmtClass:
869 Bldr.takeNodes(Pred);
870 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
874 case Stmt::MSAsmStmtClass:
875 Bldr.takeNodes(Pred);
876 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
880 case Stmt::BlockExprClass:
881 Bldr.takeNodes(Pred);
882 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
886 case Stmt::BinaryOperatorClass: {
887 const BinaryOperator* B = cast<BinaryOperator>(S);
888 if (B->isLogicalOp()) {
889 Bldr.takeNodes(Pred);
890 VisitLogicalExpr(B, Pred, Dst);
894 else if (B->getOpcode() == BO_Comma) {
895 ProgramStateRef state = Pred->getState();
896 Bldr.generateNode(B, Pred,
897 state->BindExpr(B, Pred->getLocationContext(),
898 state->getSVal(B->getRHS(),
899 Pred->getLocationContext())));
903 Bldr.takeNodes(Pred);
905 if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
906 (B->isRelationalOp() || B->isEqualityOp())) {
908 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
909 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
912 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
918 case Stmt::CXXOperatorCallExprClass: {
919 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
921 // For instance method operators, make sure the 'this' argument has a
923 const Decl *Callee = OCE->getCalleeDecl();
924 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
925 if (MD->isInstance()) {
926 ProgramStateRef State = Pred->getState();
927 const LocationContext *LCtx = Pred->getLocationContext();
928 ProgramStateRef NewState =
929 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
930 if (NewState != State) {
931 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/0,
932 ProgramPoint::PreStmtKind);
941 case Stmt::CallExprClass:
942 case Stmt::CXXMemberCallExprClass:
943 case Stmt::UserDefinedLiteralClass: {
944 Bldr.takeNodes(Pred);
945 VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
950 case Stmt::CXXCatchStmtClass: {
951 Bldr.takeNodes(Pred);
952 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
957 case Stmt::CXXTemporaryObjectExprClass:
958 case Stmt::CXXConstructExprClass: {
959 Bldr.takeNodes(Pred);
960 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
965 case Stmt::CXXNewExprClass: {
966 Bldr.takeNodes(Pred);
967 ExplodedNodeSet PostVisit;
968 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
969 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
974 case Stmt::CXXDeleteExprClass: {
975 Bldr.takeNodes(Pred);
976 ExplodedNodeSet PreVisit;
977 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
978 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
980 for (ExplodedNodeSet::iterator i = PreVisit.begin(),
981 e = PreVisit.end(); i != e ; ++i)
982 VisitCXXDeleteExpr(CDE, *i, Dst);
987 // FIXME: ChooseExpr is really a constant. We need to fix
988 // the CFG do not model them as explicit control-flow.
990 case Stmt::ChooseExprClass: { // __builtin_choose_expr
991 Bldr.takeNodes(Pred);
992 const ChooseExpr *C = cast<ChooseExpr>(S);
993 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
998 case Stmt::CompoundAssignOperatorClass:
999 Bldr.takeNodes(Pred);
1000 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1004 case Stmt::CompoundLiteralExprClass:
1005 Bldr.takeNodes(Pred);
1006 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1010 case Stmt::BinaryConditionalOperatorClass:
1011 case Stmt::ConditionalOperatorClass: { // '?' operator
1012 Bldr.takeNodes(Pred);
1013 const AbstractConditionalOperator *C
1014 = cast<AbstractConditionalOperator>(S);
1015 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1020 case Stmt::CXXThisExprClass:
1021 Bldr.takeNodes(Pred);
1022 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1026 case Stmt::DeclRefExprClass: {
1027 Bldr.takeNodes(Pred);
1028 const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1029 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1034 case Stmt::DeclStmtClass:
1035 Bldr.takeNodes(Pred);
1036 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1040 case Stmt::ImplicitCastExprClass:
1041 case Stmt::CStyleCastExprClass:
1042 case Stmt::CXXStaticCastExprClass:
1043 case Stmt::CXXDynamicCastExprClass:
1044 case Stmt::CXXReinterpretCastExprClass:
1045 case Stmt::CXXConstCastExprClass:
1046 case Stmt::CXXFunctionalCastExprClass:
1047 case Stmt::ObjCBridgedCastExprClass: {
1048 Bldr.takeNodes(Pred);
1049 const CastExpr *C = cast<CastExpr>(S);
1050 // Handle the previsit checks.
1051 ExplodedNodeSet dstPrevisit;
1052 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
1054 // Handle the expression itself.
1055 ExplodedNodeSet dstExpr;
1056 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1057 e = dstPrevisit.end(); i != e ; ++i) {
1058 VisitCast(C, C->getSubExpr(), *i, dstExpr);
1061 // Handle the postvisit checks.
1062 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1067 case Expr::MaterializeTemporaryExprClass: {
1068 Bldr.takeNodes(Pred);
1069 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1070 CreateCXXTemporaryObject(MTE, Pred, Dst);
1075 case Stmt::InitListExprClass:
1076 Bldr.takeNodes(Pred);
1077 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1081 case Stmt::MemberExprClass:
1082 Bldr.takeNodes(Pred);
1083 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1087 case Stmt::ObjCIvarRefExprClass:
1088 Bldr.takeNodes(Pred);
1089 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1093 case Stmt::ObjCForCollectionStmtClass:
1094 Bldr.takeNodes(Pred);
1095 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1099 case Stmt::ObjCMessageExprClass:
1100 Bldr.takeNodes(Pred);
1101 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1105 case Stmt::ObjCAtThrowStmtClass:
1106 case Stmt::CXXThrowExprClass:
1107 // FIXME: This is not complete. We basically treat @throw as
1109 Bldr.generateSink(S, Pred, Pred->getState());
1112 case Stmt::ReturnStmtClass:
1113 Bldr.takeNodes(Pred);
1114 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1118 case Stmt::OffsetOfExprClass:
1119 Bldr.takeNodes(Pred);
1120 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1124 case Stmt::UnaryExprOrTypeTraitExprClass:
1125 Bldr.takeNodes(Pred);
1126 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1131 case Stmt::StmtExprClass: {
1132 const StmtExpr *SE = cast<StmtExpr>(S);
1134 if (SE->getSubStmt()->body_empty()) {
1135 // Empty statement expression.
1136 assert(SE->getType() == getContext().VoidTy
1137 && "Empty statement expression must have void type.");
1141 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1142 ProgramStateRef state = Pred->getState();
1143 Bldr.generateNode(SE, Pred,
1144 state->BindExpr(SE, Pred->getLocationContext(),
1145 state->getSVal(LastExpr,
1146 Pred->getLocationContext())));
1151 case Stmt::UnaryOperatorClass: {
1152 Bldr.takeNodes(Pred);
1153 const UnaryOperator *U = cast<UnaryOperator>(S);
1154 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1155 ExplodedNodeSet Tmp;
1156 VisitUnaryOperator(U, Pred, Tmp);
1157 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1160 VisitUnaryOperator(U, Pred, Dst);
1165 case Stmt::PseudoObjectExprClass: {
1166 Bldr.takeNodes(Pred);
1167 ProgramStateRef state = Pred->getState();
1168 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1169 if (const Expr *Result = PE->getResultExpr()) {
1170 SVal V = state->getSVal(Result, Pred->getLocationContext());
1171 Bldr.generateNode(S, Pred,
1172 state->BindExpr(S, Pred->getLocationContext(), V));
1175 Bldr.generateNode(S, Pred,
1176 state->BindExpr(S, Pred->getLocationContext(),
1185 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1186 const LocationContext *CalleeLC) {
1187 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1188 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1189 assert(CalleeSF && CallerSF);
1190 ExplodedNode *BeforeProcessingCall = 0;
1191 const Stmt *CE = CalleeSF->getCallSite();
1193 // Find the first node before we started processing the call expression.
1195 ProgramPoint L = N->getLocation();
1196 BeforeProcessingCall = N;
1197 N = N->pred_empty() ? NULL : *(N->pred_begin());
1199 // Skip the nodes corresponding to the inlined code.
1200 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1202 // We reached the caller. Find the node right before we started
1203 // processing the call.
1204 if (L.isPurgeKind())
1206 if (L.getAs<PreImplicitCall>())
1208 if (L.getAs<CallEnter>())
1210 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1211 if (SP->getStmt() == CE)
1216 if (!BeforeProcessingCall)
1219 // TODO: Clean up the unneeded nodes.
1221 // Build an Epsilon node from which we will restart the analyzes.
1222 // Note that CE is permitted to be NULL!
1223 ProgramPoint NewNodeLoc =
1224 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1225 // Add the special flag to GDM to signal retrying with no inlining.
1226 // Note, changing the state ensures that we are not going to cache out.
1227 ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1229 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1231 // Make the new node a successor of BeforeProcessingCall.
1233 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1234 // We cached out at this point. Caching out is common due to us backtracking
1235 // from the inlined function, which might spawn several paths.
1239 NewNode->addPredecessor(BeforeProcessingCall, G);
1241 // Add the new node to the work list.
1242 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1243 CalleeSF->getIndex());
1244 NumTimesRetriedWithoutInlining++;
1248 /// Block entrance. (Update counters).
1249 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1250 NodeBuilderWithSinks &nodeBuilder,
1251 ExplodedNode *Pred) {
1252 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1254 // FIXME: Refactor this into a checker.
1255 if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) {
1256 static SimpleProgramPointTag tag("ExprEngine : Block count exceeded");
1257 const ExplodedNode *Sink =
1258 nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1260 // Check if we stopped at the top level function or not.
1261 // Root node should have the location context of the top most function.
1262 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1263 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1264 const LocationContext *RootLC =
1265 (*G.roots_begin())->getLocation().getLocationContext();
1266 if (RootLC->getCurrentStackFrame() != CalleeSF) {
1267 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1269 // Re-run the call evaluation without inlining it, by storing the
1270 // no-inlining policy in the state and enqueuing the new work item on
1271 // the list. Replay should almost never fail. Use the stats to catch it
1273 if ((!AMgr.options.NoRetryExhausted &&
1274 replayWithoutInlining(Pred, CalleeLC)))
1276 NumMaxBlockCountReachedInInlined++;
1278 NumMaxBlockCountReached++;
1280 // Make sink nodes as exhausted(for stats) only if retry failed.
1281 Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1285 //===----------------------------------------------------------------------===//
1286 // Branch processing.
1287 //===----------------------------------------------------------------------===//
1289 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1290 /// to try to recover some path-sensitivity for casts of symbolic
1291 /// integers that promote their values (which are currently not tracked well).
1292 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1293 // cast(s) did was sign-extend the original value.
1294 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1295 ProgramStateRef state,
1296 const Stmt *Condition,
1297 const LocationContext *LCtx,
1300 const Expr *Ex = dyn_cast<Expr>(Condition);
1302 return UnknownVal();
1305 bool bitsInit = false;
1307 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1308 QualType T = CE->getType();
1310 if (!T->isIntegralOrEnumerationType())
1311 return UnknownVal();
1313 uint64_t newBits = Ctx.getTypeSize(T);
1314 if (!bitsInit || newBits < bits) {
1319 Ex = CE->getSubExpr();
1322 // We reached a non-cast. Is it a symbolic value?
1323 QualType T = Ex->getType();
1325 if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1326 Ctx.getTypeSize(T) > bits)
1327 return UnknownVal();
1329 return state->getSVal(Ex, LCtx);
1332 static const Stmt *ResolveCondition(const Stmt *Condition,
1333 const CFGBlock *B) {
1334 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1335 Condition = Ex->IgnoreParens();
1337 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1338 if (!BO || !BO->isLogicalOp())
1341 // For logical operations, we still have the case where some branches
1342 // use the traditional "merge" approach and others sink the branch
1343 // directly into the basic blocks representing the logical operation.
1344 // We need to distinguish between those two cases here.
1346 // The invariants are still shifting, but it is possible that the
1347 // last element in a CFGBlock is not a CFGStmt. Look for the last
1348 // CFGStmt as the value of the condition.
1349 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1350 for (; I != E; ++I) {
1351 CFGElement Elem = *I;
1352 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1355 if (CS->getStmt() != Condition)
1363 BO = dyn_cast<BinaryOperator>(Condition);
1364 if (!BO || !BO->isLogicalOp())
1366 Condition = BO->getRHS()->IgnoreParens();
1368 llvm_unreachable("could not resolve condition");
1371 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1372 NodeBuilderContext& BldCtx,
1374 ExplodedNodeSet &Dst,
1375 const CFGBlock *DstT,
1376 const CFGBlock *DstF) {
1377 const LocationContext *LCtx = Pred->getLocationContext();
1378 PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1379 currBldrCtx = &BldCtx;
1381 // Check for NULL conditions; e.g. "for(;;)"
1383 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1384 NullCondBldr.markInfeasible(false);
1385 NullCondBldr.generateNode(Pred->getState(), true, Pred);
1390 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1391 Condition = Ex->IgnoreParens();
1393 Condition = ResolveCondition(Condition, BldCtx.getBlock());
1394 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1395 Condition->getLocStart(),
1396 "Error evaluating branch");
1398 ExplodedNodeSet CheckersOutSet;
1399 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1401 // We generated only sinks.
1402 if (CheckersOutSet.empty())
1405 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1406 for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1407 E = CheckersOutSet.end(); E != I; ++I) {
1408 ExplodedNode *PredI = *I;
1410 if (PredI->isSink())
1413 ProgramStateRef PrevState = PredI->getState();
1414 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1416 if (X.isUnknownOrUndef()) {
1417 // Give it a chance to recover from unknown.
1418 if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1419 if (Ex->getType()->isIntegralOrEnumerationType()) {
1420 // Try to recover some path-sensitivity. Right now casts of symbolic
1421 // integers that promote their values are currently not tracked well.
1422 // If 'Condition' is such an expression, try and recover the
1423 // underlying value and use that instead.
1424 SVal recovered = RecoverCastedSymbol(getStateManager(),
1425 PrevState, Condition,
1426 PredI->getLocationContext(),
1429 if (!recovered.isUnknown()) {
1436 // If the condition is still unknown, give up.
1437 if (X.isUnknownOrUndef()) {
1438 builder.generateNode(PrevState, true, PredI);
1439 builder.generateNode(PrevState, false, PredI);
1443 DefinedSVal V = X.castAs<DefinedSVal>();
1445 ProgramStateRef StTrue, StFalse;
1446 tie(StTrue, StFalse) = PrevState->assume(V);
1448 // Process the true branch.
1449 if (builder.isFeasible(true)) {
1451 builder.generateNode(StTrue, true, PredI);
1453 builder.markInfeasible(true);
1456 // Process the false branch.
1457 if (builder.isFeasible(false)) {
1459 builder.generateNode(StFalse, false, PredI);
1461 builder.markInfeasible(false);
1467 /// The GDM component containing the set of global variables which have been
1468 /// previously initialized with explicit initializers.
1469 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1470 llvm::ImmutableSet<const VarDecl *>)
1472 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1473 NodeBuilderContext &BuilderCtx,
1475 clang::ento::ExplodedNodeSet &Dst,
1476 const CFGBlock *DstT,
1477 const CFGBlock *DstF) {
1478 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1479 currBldrCtx = &BuilderCtx;
1481 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1482 ProgramStateRef state = Pred->getState();
1483 bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1484 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1487 state = state->add<InitializedGlobalsSet>(VD);
1490 builder.generateNode(state, initHasRun, Pred);
1491 builder.markInfeasible(!initHasRun);
1496 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
1497 /// nodes by processing the 'effects' of a computed goto jump.
1498 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1500 ProgramStateRef state = builder.getState();
1501 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1503 // Three possibilities:
1505 // (1) We know the computed label.
1506 // (2) The label is NULL (or some other constant), or Undefined.
1507 // (3) We have no clue about the label. Dispatch to all targets.
1510 typedef IndirectGotoNodeBuilder::iterator iterator;
1512 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1513 const LabelDecl *L = LV->getLabel();
1515 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1516 if (I.getLabel() == L) {
1517 builder.generateNode(I, state);
1522 llvm_unreachable("No block with label.");
1525 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1526 // Dispatch to the first target and mark it as a sink.
1527 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1528 // FIXME: add checker visit.
1529 // UndefBranches.insert(N);
1533 // This is really a catch-all. We don't support symbolics yet.
1534 // FIXME: Implement dispatch for symbolic pointers.
1536 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1537 builder.generateNode(I, state);
1540 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
1541 /// nodes when the control reaches the end of a function.
1542 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1543 ExplodedNode *Pred) {
1544 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1545 StateMgr.EndPath(Pred->getState());
1547 ExplodedNodeSet Dst;
1548 if (Pred->getLocationContext()->inTopFrame()) {
1549 // Remove dead symbols.
1550 ExplodedNodeSet AfterRemovedDead;
1551 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1554 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1555 E = AfterRemovedDead.end(); I != E; ++I) {
1556 getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1559 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1562 Engine.enqueueEndOfFunction(Dst);
1565 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
1566 /// nodes by processing the 'effects' of a switch statement.
1567 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1568 typedef SwitchNodeBuilder::iterator iterator;
1569 ProgramStateRef state = builder.getState();
1570 const Expr *CondE = builder.getCondition();
1571 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1573 if (CondV_untested.isUndef()) {
1574 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1575 // FIXME: add checker
1576 //UndefBranches.insert(N);
1580 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1582 ProgramStateRef DefaultSt = state;
1584 iterator I = builder.begin(), EI = builder.end();
1585 bool defaultIsFeasible = I == EI;
1587 for ( ; I != EI; ++I) {
1588 // Successor may be pruned out during CFG construction.
1592 const CaseStmt *Case = I.getCase();
1594 // Evaluate the LHS of the case value.
1595 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1596 assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1598 // Get the RHS of the case, if it exists.
1600 if (const Expr *E = Case->getRHS())
1601 V2 = E->EvaluateKnownConstInt(getContext());
1605 // FIXME: Eventually we should replace the logic below with a range
1606 // comparison, rather than concretize the values within the range.
1607 // This should be easy once we have "ranges" for NonLVals.
1610 nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
1611 DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
1614 // Now "assume" that the case matches.
1615 if (ProgramStateRef stateNew = state->assume(Res, true)) {
1616 builder.generateCaseStmtNode(I, stateNew);
1618 // If CondV evaluates to a constant, then we know that this
1619 // is the *only* case that we can take, so stop evaluating the
1621 if (CondV.getAs<nonloc::ConcreteInt>())
1625 // Now "assume" that the case doesn't match. Add this state
1626 // to the default state (if it is feasible).
1628 if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
1629 defaultIsFeasible = true;
1630 DefaultSt = stateNew;
1633 defaultIsFeasible = false;
1638 // Concretize the next value in the range.
1648 if (!defaultIsFeasible)
1651 // If we have switch(enum value), the default branch is not
1652 // feasible if all of the enum constants not covered by 'case:' statements
1653 // are not feasible values for the switch condition.
1655 // Note that this isn't as accurate as it could be. Even if there isn't
1656 // a case for a particular enum value as long as that enum value isn't
1657 // feasible then it shouldn't be considered for making 'default:' reachable.
1658 const SwitchStmt *SS = builder.getSwitch();
1659 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1660 if (CondExpr->getType()->getAs<EnumType>()) {
1661 if (SS->isAllEnumCasesCovered())
1665 builder.generateDefaultCaseNode(DefaultSt);
1668 //===----------------------------------------------------------------------===//
1669 // Transfer functions: Loads and stores.
1670 //===----------------------------------------------------------------------===//
1672 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1674 ExplodedNodeSet &Dst) {
1675 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1677 ProgramStateRef state = Pred->getState();
1678 const LocationContext *LCtx = Pred->getLocationContext();
1680 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1681 // C permits "extern void v", and if you cast the address to a valid type,
1682 // you can even do things with it. We simply pretend
1683 assert(Ex->isGLValue() || VD->getType()->isVoidType());
1684 SVal V = state->getLValue(VD, Pred->getLocationContext());
1686 // For references, the 'lvalue' is the pointer address stored in the
1687 // reference region.
1688 if (VD->getType()->isReferenceType()) {
1689 if (const MemRegion *R = V.getAsRegion())
1690 V = state->getSVal(R);
1695 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
1696 ProgramPoint::PostLValueKind);
1699 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
1700 assert(!Ex->isGLValue());
1701 SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1702 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
1705 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1706 SVal V = svalBuilder.getFunctionPointer(FD);
1707 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
1708 ProgramPoint::PostLValueKind);
1711 if (isa<FieldDecl>(D)) {
1712 // FIXME: Compute lvalue of field pointers-to-member.
1713 // Right now we just use a non-null void pointer, so that it gives proper
1714 // results in boolean contexts.
1715 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
1716 currBldrCtx->blockCount());
1717 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
1718 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
1719 ProgramPoint::PostLValueKind);
1723 llvm_unreachable("Support for this Decl not implemented.");
1726 /// VisitArraySubscriptExpr - Transfer function for array accesses
1727 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
1729 ExplodedNodeSet &Dst){
1731 const Expr *Base = A->getBase()->IgnoreParens();
1732 const Expr *Idx = A->getIdx()->IgnoreParens();
1735 ExplodedNodeSet checkerPreStmt;
1736 getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
1738 StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
1740 for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
1741 ei = checkerPreStmt.end(); it != ei; ++it) {
1742 const LocationContext *LCtx = (*it)->getLocationContext();
1743 ProgramStateRef state = (*it)->getState();
1744 SVal V = state->getLValue(A->getType(),
1745 state->getSVal(Idx, LCtx),
1746 state->getSVal(Base, LCtx));
1747 assert(A->isGLValue());
1748 Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), 0,
1749 ProgramPoint::PostLValueKind);
1753 /// VisitMemberExpr - Transfer function for member expressions.
1754 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
1755 ExplodedNodeSet &TopDst) {
1757 StmtNodeBuilder Bldr(Pred, TopDst, *currBldrCtx);
1758 ExplodedNodeSet Dst;
1759 ValueDecl *Member = M->getMemberDecl();
1761 // Handle static member variables and enum constants accessed via
1763 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
1764 Bldr.takeNodes(Pred);
1765 VisitCommonDeclRefExpr(M, Member, Pred, Dst);
1770 ProgramStateRef state = Pred->getState();
1771 const LocationContext *LCtx = Pred->getLocationContext();
1772 Expr *BaseExpr = M->getBase();
1774 // Handle C++ method calls.
1775 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
1776 if (MD->isInstance())
1777 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1779 SVal MDVal = svalBuilder.getFunctionPointer(MD);
1780 state = state->BindExpr(M, LCtx, MDVal);
1782 Bldr.generateNode(M, Pred, state);
1786 // Handle regular struct fields / member variables.
1787 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1788 SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
1790 FieldDecl *field = cast<FieldDecl>(Member);
1791 SVal L = state->getLValue(field, baseExprVal);
1793 if (M->isGLValue() || M->getType()->isArrayType()) {
1795 // We special case rvalue of array type because the analyzer cannot reason
1796 // about it, since we expect all regions to be wrapped in Locs. So we will
1797 // treat these as lvalues assuming that they will decay to pointers as soon
1798 // as they are used.
1799 if (!M->isGLValue()) {
1800 assert(M->getType()->isArrayType());
1801 const ImplicitCastExpr *PE =
1802 dyn_cast<ImplicitCastExpr>(Pred->getParentMap().getParent(M));
1803 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
1805 "We assume that array is always wrapped in ArrayToPointerDecay");
1810 if (field->getType()->isReferenceType()) {
1811 if (const MemRegion *R = L.getAsRegion())
1812 L = state->getSVal(R);
1817 Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), 0,
1818 ProgramPoint::PostLValueKind);
1820 Bldr.takeNodes(Pred);
1821 evalLoad(Dst, M, M, Pred, state, L);
1827 class CollectReachableSymbolsCallback : public SymbolVisitor {
1828 InvalidatedSymbols Symbols;
1830 CollectReachableSymbolsCallback(ProgramStateRef State) {}
1831 const InvalidatedSymbols &getSymbols() const { return Symbols; }
1833 bool VisitSymbol(SymbolRef Sym) {
1834 Symbols.insert(Sym);
1838 } // end anonymous namespace
1840 // A value escapes in three possible cases:
1841 // (1) We are binding to something that is not a memory region.
1842 // (2) We are binding to a MemrRegion that does not have stack storage.
1843 // (3) We are binding to a MemRegion with stack storage that the store
1844 // does not understand.
1845 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
1846 SVal Loc, SVal Val) {
1847 // Are we storing to something that causes the value to "escape"?
1848 bool escapes = true;
1850 // TODO: Move to StoreManager.
1851 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
1852 escapes = !regionLoc->getRegion()->hasStackStorage();
1855 // To test (3), generate a new state with the binding added. If it is
1856 // the same state, then it escapes (since the store cannot represent
1858 // Do this only if we know that the store is not supposed to generate the
1860 SVal StoredVal = State->getSVal(regionLoc->getRegion());
1861 if (StoredVal != Val)
1862 escapes = (State == (State->bindLoc(*regionLoc, Val)));
1866 // If our store can represent the binding and we aren't storing to something
1867 // that doesn't have local storage then just return and have the simulation
1868 // state continue as is.
1872 // Otherwise, find all symbols referenced by 'val' that we are tracking
1873 // and stop tracking them.
1874 CollectReachableSymbolsCallback Scanner =
1875 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
1876 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
1877 State = getCheckerManager().runCheckersForPointerEscape(State,
1887 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
1888 const InvalidatedSymbols *Invalidated,
1889 ArrayRef<const MemRegion *> ExplicitRegions,
1890 ArrayRef<const MemRegion *> Regions,
1891 const CallEvent *Call,
1892 RegionAndSymbolInvalidationTraits &ITraits) {
1894 if (!Invalidated || Invalidated->empty())
1898 return getCheckerManager().runCheckersForPointerEscape(State,
1904 // If the symbols were invalidated by a call, we want to find out which ones
1905 // were invalidated directly due to being arguments to the call.
1906 InvalidatedSymbols SymbolsDirectlyInvalidated;
1907 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1908 E = ExplicitRegions.end(); I != E; ++I) {
1909 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1910 SymbolsDirectlyInvalidated.insert(R->getSymbol());
1913 InvalidatedSymbols SymbolsIndirectlyInvalidated;
1914 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
1915 E = Invalidated->end(); I!=E; ++I) {
1917 if (SymbolsDirectlyInvalidated.count(sym))
1919 SymbolsIndirectlyInvalidated.insert(sym);
1922 if (!SymbolsDirectlyInvalidated.empty())
1923 State = getCheckerManager().runCheckersForPointerEscape(State,
1924 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
1926 // Notify about the symbols that get indirectly invalidated by the call.
1927 if (!SymbolsIndirectlyInvalidated.empty())
1928 State = getCheckerManager().runCheckersForPointerEscape(State,
1929 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
1934 /// evalBind - Handle the semantics of binding a value to a specific location.
1935 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
1936 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
1938 SVal location, SVal Val,
1939 bool atDeclInit, const ProgramPoint *PP) {
1941 const LocationContext *LC = Pred->getLocationContext();
1942 PostStmt PS(StoreE, LC);
1946 // Do a previsit of the bind.
1947 ExplodedNodeSet CheckedSet;
1948 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
1949 StoreE, *this, *PP);
1952 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
1954 // If the location is not a 'Loc', it will already be handled by
1955 // the checkers. There is nothing left to do.
1956 if (!location.getAs<Loc>()) {
1957 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/0, /*tag*/0);
1958 ProgramStateRef state = Pred->getState();
1959 state = processPointerEscapedOnBind(state, location, Val);
1960 Bldr.generateNode(L, state, Pred);
1965 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1967 ExplodedNode *PredI = *I;
1968 ProgramStateRef state = PredI->getState();
1970 state = processPointerEscapedOnBind(state, location, Val);
1972 // When binding the value, pass on the hint that this is a initialization.
1973 // For initializations, we do not need to inform clients of region
1975 state = state->bindLoc(location.castAs<Loc>(),
1976 Val, /* notifyChanges = */ !atDeclInit);
1978 const MemRegion *LocReg = 0;
1979 if (Optional<loc::MemRegionVal> LocRegVal =
1980 location.getAs<loc::MemRegionVal>()) {
1981 LocReg = LocRegVal->getRegion();
1984 const ProgramPoint L = PostStore(StoreE, LC, LocReg, 0);
1985 Bldr.generateNode(L, state, PredI);
1989 /// evalStore - Handle the semantics of a store via an assignment.
1990 /// @param Dst The node set to store generated state nodes
1991 /// @param AssignE The assignment expression if the store happens in an
1993 /// @param LocationE The location expression that is stored to.
1994 /// @param state The current simulation state
1995 /// @param location The location to store the value
1996 /// @param Val The value to be stored
1997 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
1998 const Expr *LocationE,
2000 ProgramStateRef state, SVal location, SVal Val,
2001 const ProgramPointTag *tag) {
2002 // Proceed with the store. We use AssignE as the anchor for the PostStore
2003 // ProgramPoint if it is non-NULL, and LocationE otherwise.
2004 const Expr *StoreE = AssignE ? AssignE : LocationE;
2006 // Evaluate the location (checks for bad dereferences).
2007 ExplodedNodeSet Tmp;
2008 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2013 if (location.isUndef())
2016 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2017 evalBind(Dst, StoreE, *NI, location, Val, false);
2020 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2022 const Expr *BoundEx,
2024 ProgramStateRef state,
2026 const ProgramPointTag *tag,
2029 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2031 // Are we loading from a region? This actually results in two loads; one
2032 // to fetch the address of the referenced value and one to fetch the
2033 // referenced value.
2034 if (const TypedValueRegion *TR =
2035 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2037 QualType ValTy = TR->getValueType();
2038 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2039 static SimpleProgramPointTag
2040 loadReferenceTag("ExprEngine : Load Reference");
2041 ExplodedNodeSet Tmp;
2042 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2043 location, &loadReferenceTag,
2044 getContext().getPointerType(RT->getPointeeType()));
2046 // Perform the load from the referenced value.
2047 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2048 state = (*I)->getState();
2049 location = state->getSVal(BoundEx, (*I)->getLocationContext());
2050 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2056 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2059 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2061 const Expr *BoundEx,
2063 ProgramStateRef state,
2065 const ProgramPointTag *tag,
2069 // Evaluate the location (checks for bad dereferences).
2070 ExplodedNodeSet Tmp;
2071 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2075 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2076 if (location.isUndef())
2079 // Proceed with the load.
2080 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2081 state = (*NI)->getState();
2082 const LocationContext *LCtx = (*NI)->getLocationContext();
2084 SVal V = UnknownVal();
2085 if (location.isValid()) {
2086 if (LoadTy.isNull())
2087 LoadTy = BoundEx->getType();
2088 V = state->getSVal(location.castAs<Loc>(), LoadTy);
2091 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2092 ProgramPoint::PostLoadKind);
2096 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2098 const Stmt *BoundEx,
2100 ProgramStateRef state,
2102 const ProgramPointTag *tag,
2104 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2105 // Early checks for performance reason.
2106 if (location.isUnknown()) {
2110 ExplodedNodeSet Src;
2111 BldrTop.takeNodes(Pred);
2112 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2113 if (Pred->getState() != state) {
2114 // Associate this new state with an ExplodedNode.
2115 // FIXME: If I pass null tag, the graph is incorrect, e.g for
2119 // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2120 // instead "int *p" is noted as
2121 // "Variable 'p' initialized to a null pointer value"
2123 static SimpleProgramPointTag tag("ExprEngine: Location");
2124 Bldr.generateNode(NodeEx, Pred, state, &tag);
2126 ExplodedNodeSet Tmp;
2127 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2128 NodeEx, BoundEx, *this);
2129 BldrTop.addNodes(Tmp);
2132 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2133 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2134 static SimpleProgramPointTag
2135 eagerlyAssumeBinOpBifurcationTrue("ExprEngine : Eagerly Assume True"),
2136 eagerlyAssumeBinOpBifurcationFalse("ExprEngine : Eagerly Assume False");
2137 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2138 &eagerlyAssumeBinOpBifurcationFalse);
2141 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2142 ExplodedNodeSet &Src,
2144 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2146 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2147 ExplodedNode *Pred = *I;
2148 // Test if the previous node was as the same expression. This can happen
2149 // when the expression fails to evaluate to anything meaningful and
2150 // (as an optimization) we don't generate a node.
2151 ProgramPoint P = Pred->getLocation();
2152 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2156 ProgramStateRef state = Pred->getState();
2157 SVal V = state->getSVal(Ex, Pred->getLocationContext());
2158 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2159 if (SEV && SEV->isExpression()) {
2160 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2161 geteagerlyAssumeBinOpBifurcationTags();
2163 ProgramStateRef StateTrue, StateFalse;
2164 tie(StateTrue, StateFalse) = state->assume(*SEV);
2166 // First assume that the condition is true.
2168 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2169 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2170 Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2173 // Next, assume that the condition is false.
2175 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2176 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2177 Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2183 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2184 ExplodedNodeSet &Dst) {
2185 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2186 // We have processed both the inputs and the outputs. All of the outputs
2187 // should evaluate to Locs. Nuke all of their values.
2189 // FIXME: Some day in the future it would be nice to allow a "plug-in"
2190 // which interprets the inline asm and stores proper results in the
2193 ProgramStateRef state = Pred->getState();
2195 for (GCCAsmStmt::const_outputs_iterator OI = A->begin_outputs(),
2196 OE = A->end_outputs(); OI != OE; ++OI) {
2197 SVal X = state->getSVal(*OI, Pred->getLocationContext());
2198 assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2200 if (Optional<Loc> LV = X.getAs<Loc>())
2201 state = state->bindLoc(*LV, UnknownVal());
2204 Bldr.generateNode(A, Pred, state);
2207 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2208 ExplodedNodeSet &Dst) {
2209 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2210 Bldr.generateNode(A, Pred, Pred->getState());
2213 //===----------------------------------------------------------------------===//
2215 //===----------------------------------------------------------------------===//
2218 static ExprEngine* GraphPrintCheckerState;
2219 static SourceManager* GraphPrintSourceManager;
2223 struct DOTGraphTraits<ExplodedNode*> :
2224 public DefaultDOTGraphTraits {
2226 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2228 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2230 static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2233 // FIXME: Replace with a general scheme to tell if the node is
2235 if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
2236 GraphPrintCheckerState->isExplicitNullDeref(N) ||
2237 GraphPrintCheckerState->isUndefDeref(N) ||
2238 GraphPrintCheckerState->isUndefStore(N) ||
2239 GraphPrintCheckerState->isUndefControlFlow(N) ||
2240 GraphPrintCheckerState->isUndefResult(N) ||
2241 GraphPrintCheckerState->isBadCall(N) ||
2242 GraphPrintCheckerState->isUndefArg(N))
2243 return "color=\"red\",style=\"filled\"";
2245 if (GraphPrintCheckerState->isNoReturnCall(N))
2246 return "color=\"blue\",style=\"filled\"";
2251 static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2252 if (SLoc.isFileID()) {
2254 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2256 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2261 static std::string getNodeLabel(const ExplodedNode *N, void*){
2264 llvm::raw_string_ostream Out(sbuf);
2266 // Program Location.
2267 ProgramPoint Loc = N->getLocation();
2269 switch (Loc.getKind()) {
2270 case ProgramPoint::BlockEntranceKind: {
2271 Out << "Block Entrance: B"
2272 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2273 if (const NamedDecl *ND =
2274 dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
2282 case ProgramPoint::BlockExitKind:
2286 case ProgramPoint::CallEnterKind:
2290 case ProgramPoint::CallExitBeginKind:
2291 Out << "CallExitBegin";
2294 case ProgramPoint::CallExitEndKind:
2295 Out << "CallExitEnd";
2298 case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2299 Out << "PostStmtPurgeDeadSymbols";
2302 case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2303 Out << "PreStmtPurgeDeadSymbols";
2306 case ProgramPoint::EpsilonKind:
2307 Out << "Epsilon Point";
2310 case ProgramPoint::PreImplicitCallKind: {
2311 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2314 // FIXME: Get proper printing options.
2315 PC.getDecl()->print(Out, LangOptions());
2316 printLocation(Out, PC.getLocation());
2320 case ProgramPoint::PostImplicitCallKind: {
2321 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2322 Out << "PostCall: ";
2324 // FIXME: Get proper printing options.
2325 PC.getDecl()->print(Out, LangOptions());
2326 printLocation(Out, PC.getLocation());
2330 case ProgramPoint::PostInitializerKind: {
2331 Out << "PostInitializer: ";
2332 const CXXCtorInitializer *Init =
2333 Loc.castAs<PostInitializer>().getInitializer();
2334 if (const FieldDecl *FD = Init->getAnyMember())
2337 QualType Ty = Init->getTypeSourceInfo()->getType();
2338 Ty = Ty.getLocalUnqualifiedType();
2339 LangOptions LO; // FIXME.
2345 case ProgramPoint::BlockEdgeKind: {
2346 const BlockEdge &E = Loc.castAs<BlockEdge>();
2347 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2348 << E.getDst()->getBlockID() << ')';
2350 if (const Stmt *T = E.getSrc()->getTerminator()) {
2351 SourceLocation SLoc = T->getLocStart();
2353 Out << "\\|Terminator: ";
2354 LangOptions LO; // FIXME.
2355 E.getSrc()->printTerminator(Out, LO);
2357 if (SLoc.isFileID()) {
2359 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2361 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2364 if (isa<SwitchStmt>(T)) {
2365 const Stmt *Label = E.getDst()->getLabel();
2368 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2370 LangOptions LO; // FIXME.
2371 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
2373 if (const Stmt *RHS = C->getRHS()) {
2375 RHS->printPretty(Out, 0, PrintingPolicy(LO));
2381 assert (isa<DefaultStmt>(Label));
2382 Out << "\\ldefault:";
2386 Out << "\\l(implicit) default:";
2388 else if (isa<IndirectGotoStmt>(T)) {
2392 Out << "\\lCondition: ";
2393 if (*E.getSrc()->succ_begin() == E.getDst())
2403 // FIXME: Replace with a general scheme to determine
2404 // the name of the check.
2405 if (GraphPrintCheckerState->isUndefControlFlow(N)) {
2406 Out << "\\|Control-flow based on\\lUndefined value.\\l";
2413 const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2415 Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2416 LangOptions LO; // FIXME.
2417 S->printPretty(Out, 0, PrintingPolicy(LO));
2418 printLocation(Out, S->getLocStart());
2420 if (Loc.getAs<PreStmt>())
2421 Out << "\\lPreStmt\\l;";
2422 else if (Loc.getAs<PostLoad>())
2423 Out << "\\lPostLoad\\l;";
2424 else if (Loc.getAs<PostStore>())
2425 Out << "\\lPostStore\\l";
2426 else if (Loc.getAs<PostLValue>())
2427 Out << "\\lPostLValue\\l";
2430 // FIXME: Replace with a general scheme to determine
2431 // the name of the check.
2432 if (GraphPrintCheckerState->isImplicitNullDeref(N))
2433 Out << "\\|Implicit-Null Dereference.\\l";
2434 else if (GraphPrintCheckerState->isExplicitNullDeref(N))
2435 Out << "\\|Explicit-Null Dereference.\\l";
2436 else if (GraphPrintCheckerState->isUndefDeref(N))
2437 Out << "\\|Dereference of undefialied value.\\l";
2438 else if (GraphPrintCheckerState->isUndefStore(N))
2439 Out << "\\|Store to Undefined Loc.";
2440 else if (GraphPrintCheckerState->isUndefResult(N))
2441 Out << "\\|Result of operation is undefined.";
2442 else if (GraphPrintCheckerState->isNoReturnCall(N))
2443 Out << "\\|Call to function marked \"noreturn\".";
2444 else if (GraphPrintCheckerState->isBadCall(N))
2445 Out << "\\|Call to NULL/Undefined.";
2446 else if (GraphPrintCheckerState->isUndefArg(N))
2447 Out << "\\|Argument in call is undefined";
2454 ProgramStateRef state = N->getState();
2455 Out << "\\|StateID: " << (const void*) state.getPtr()
2456 << " NodeID: " << (const void*) N << "\\|";
2457 state->printDOT(Out);
2461 if (const ProgramPointTag *tag = Loc.getTag()) {
2462 Out << "\\|Tag: " << tag->getTagDescription();
2468 } // end llvm namespace
2472 template <typename ITERATOR>
2473 ExplodedNode *GetGraphNode(ITERATOR I) { return *I; }
2475 template <> ExplodedNode*
2476 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
2477 (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
2482 void ExprEngine::ViewGraph(bool trim) {
2485 std::vector<const ExplodedNode*> Src;
2487 // Flush any outstanding reports to make sure we cover all the nodes.
2488 // This does not cause them to get displayed.
2489 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2490 const_cast<BugType*>(*I)->FlushReports(BR);
2492 // Iterate through the reports and get their nodes.
2493 for (BugReporter::EQClasses_iterator
2494 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2495 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2496 if (N) Src.push_back(N);
2502 GraphPrintCheckerState = this;
2503 GraphPrintSourceManager = &getContext().getSourceManager();
2505 llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2507 GraphPrintCheckerState = NULL;
2508 GraphPrintSourceManager = NULL;
2513 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
2515 GraphPrintCheckerState = this;
2516 GraphPrintSourceManager = &getContext().getSourceManager();
2518 OwningPtr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2520 if (!TrimmedG.get())
2521 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2523 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2525 GraphPrintCheckerState = NULL;
2526 GraphPrintSourceManager = NULL;