1 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-= 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 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. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 17 #include "PrettyStackTraceLocationContext.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/ParentMap.h" 20 #include "clang/AST/StmtCXX.h" 21 #include "clang/AST/StmtObjC.h" 22 #include "clang/Basic/Builtins.h" 23 #include "clang/Basic/PrettyStackTrace.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 26 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 27 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 28 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 29 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h" 30 #include "llvm/ADT/Statistic.h" 31 #include "llvm/Support/SaveAndRestore.h" 32 #include "llvm/Support/raw_ostream.h" 33 34 #ifndef NDEBUG 35 #include "llvm/Support/GraphWriter.h" 36 #endif 37 38 using namespace clang; 39 using namespace ento; 40 using llvm::APSInt; 41 42 #define DEBUG_TYPE "ExprEngine" 43 44 STATISTIC(NumRemoveDeadBindings, 45 "The # of times RemoveDeadBindings is called"); 46 STATISTIC(NumMaxBlockCountReached, 47 "The # of aborted paths due to reaching the maximum block count in " 48 "a top level function"); 49 STATISTIC(NumMaxBlockCountReachedInInlined, 50 "The # of aborted paths due to reaching the maximum block count in " 51 "an inlined function"); 52 STATISTIC(NumTimesRetriedWithoutInlining, 53 "The # of times we re-evaluated a call without inlining"); 54 55 typedef std::pair<const CXXBindTemporaryExpr *, const StackFrameContext *> 56 CXXBindTemporaryContext; 57 58 // Keeps track of whether CXXBindTemporaryExpr nodes have been evaluated. 59 // The StackFrameContext assures that nested calls due to inlined recursive 60 // functions do not interfere. 61 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedTemporariesSet, 62 llvm::ImmutableSet<CXXBindTemporaryContext>) 63 64 //===----------------------------------------------------------------------===// 65 // Engine construction and deletion. 66 //===----------------------------------------------------------------------===// 67 68 static const char* TagProviderName = "ExprEngine"; 69 70 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled, 71 SetOfConstDecls *VisitedCalleesIn, 72 FunctionSummariesTy *FS, 73 InliningModes HowToInlineIn) 74 : AMgr(mgr), 75 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()), 76 Engine(*this, FS), 77 G(Engine.getGraph()), 78 StateMgr(getContext(), mgr.getStoreManagerCreator(), 79 mgr.getConstraintManagerCreator(), G.getAllocator(), 80 this), 81 SymMgr(StateMgr.getSymbolManager()), 82 svalBuilder(StateMgr.getSValBuilder()), 83 currStmtIdx(0), currBldrCtx(nullptr), 84 ObjCNoRet(mgr.getASTContext()), 85 ObjCGCEnabled(gcEnabled), BR(mgr, *this), 86 VisitedCallees(VisitedCalleesIn), 87 HowToInline(HowToInlineIn) 88 { 89 unsigned TrimInterval = mgr.options.getGraphTrimInterval(); 90 if (TrimInterval != 0) { 91 // Enable eager node reclaimation when constructing the ExplodedGraph. 92 G.enableNodeReclamation(TrimInterval); 93 } 94 } 95 96 ExprEngine::~ExprEngine() { 97 BR.FlushReports(); 98 } 99 100 //===----------------------------------------------------------------------===// 101 // Utility methods. 102 //===----------------------------------------------------------------------===// 103 104 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) { 105 ProgramStateRef state = StateMgr.getInitialState(InitLoc); 106 const Decl *D = InitLoc->getDecl(); 107 108 // Preconditions. 109 // FIXME: It would be nice if we had a more general mechanism to add 110 // such preconditions. Some day. 111 do { 112 113 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 114 // Precondition: the first argument of 'main' is an integer guaranteed 115 // to be > 0. 116 const IdentifierInfo *II = FD->getIdentifier(); 117 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0)) 118 break; 119 120 const ParmVarDecl *PD = FD->getParamDecl(0); 121 QualType T = PD->getType(); 122 const BuiltinType *BT = dyn_cast<BuiltinType>(T); 123 if (!BT || !BT->isInteger()) 124 break; 125 126 const MemRegion *R = state->getRegion(PD, InitLoc); 127 if (!R) 128 break; 129 130 SVal V = state->getSVal(loc::MemRegionVal(R)); 131 SVal Constraint_untested = evalBinOp(state, BO_GT, V, 132 svalBuilder.makeZeroVal(T), 133 svalBuilder.getConditionType()); 134 135 Optional<DefinedOrUnknownSVal> Constraint = 136 Constraint_untested.getAs<DefinedOrUnknownSVal>(); 137 138 if (!Constraint) 139 break; 140 141 if (ProgramStateRef newState = state->assume(*Constraint, true)) 142 state = newState; 143 } 144 break; 145 } 146 while (0); 147 148 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 149 // Precondition: 'self' is always non-null upon entry to an Objective-C 150 // method. 151 const ImplicitParamDecl *SelfD = MD->getSelfDecl(); 152 const MemRegion *R = state->getRegion(SelfD, InitLoc); 153 SVal V = state->getSVal(loc::MemRegionVal(R)); 154 155 if (Optional<Loc> LV = V.getAs<Loc>()) { 156 // Assume that the pointer value in 'self' is non-null. 157 state = state->assume(*LV, true); 158 assert(state && "'self' cannot be null"); 159 } 160 } 161 162 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 163 if (!MD->isStatic()) { 164 // Precondition: 'this' is always non-null upon entry to the 165 // top-level function. This is our starting assumption for 166 // analyzing an "open" program. 167 const StackFrameContext *SFC = InitLoc->getCurrentStackFrame(); 168 if (SFC->getParent() == nullptr) { 169 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC); 170 SVal V = state->getSVal(L); 171 if (Optional<Loc> LV = V.getAs<Loc>()) { 172 state = state->assume(*LV, true); 173 assert(state && "'this' cannot be null"); 174 } 175 } 176 } 177 } 178 179 return state; 180 } 181 182 ProgramStateRef 183 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State, 184 const LocationContext *LC, 185 const Expr *InitWithAdjustments, 186 const Expr *Result) { 187 // FIXME: This function is a hack that works around the quirky AST 188 // we're often having with respect to C++ temporaries. If only we modelled 189 // the actual execution order of statements properly in the CFG, 190 // all the hassle with adjustments would not be necessary, 191 // and perhaps the whole function would be removed. 192 SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC); 193 if (!Result) { 194 // If we don't have an explicit result expression, we're in "if needed" 195 // mode. Only create a region if the current value is a NonLoc. 196 if (!InitValWithAdjustments.getAs<NonLoc>()) 197 return State; 198 Result = InitWithAdjustments; 199 } else { 200 // We need to create a region no matter what. For sanity, make sure we don't 201 // try to stuff a Loc into a non-pointer temporary region. 202 assert(!InitValWithAdjustments.getAs<Loc>() || 203 Loc::isLocType(Result->getType()) || 204 Result->getType()->isMemberPointerType()); 205 } 206 207 ProgramStateManager &StateMgr = State->getStateManager(); 208 MemRegionManager &MRMgr = StateMgr.getRegionManager(); 209 StoreManager &StoreMgr = StateMgr.getStoreManager(); 210 211 // MaterializeTemporaryExpr may appear out of place, after a few field and 212 // base-class accesses have been made to the object, even though semantically 213 // it is the whole object that gets materialized and lifetime-extended. 214 // 215 // For example: 216 // 217 // `-MaterializeTemporaryExpr 218 // `-MemberExpr 219 // `-CXXTemporaryObjectExpr 220 // 221 // instead of the more natural 222 // 223 // `-MemberExpr 224 // `-MaterializeTemporaryExpr 225 // `-CXXTemporaryObjectExpr 226 // 227 // Use the usual methods for obtaining the expression of the base object, 228 // and record the adjustments that we need to make to obtain the sub-object 229 // that the whole expression 'Ex' refers to. This trick is usual, 230 // in the sense that CodeGen takes a similar route. 231 232 SmallVector<const Expr *, 2> CommaLHSs; 233 SmallVector<SubobjectAdjustment, 2> Adjustments; 234 235 const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments( 236 CommaLHSs, Adjustments); 237 238 const TypedValueRegion *TR = nullptr; 239 if (const MaterializeTemporaryExpr *MT = 240 dyn_cast<MaterializeTemporaryExpr>(Result)) { 241 StorageDuration SD = MT->getStorageDuration(); 242 // If this object is bound to a reference with static storage duration, we 243 // put it in a different region to prevent "address leakage" warnings. 244 if (SD == SD_Static || SD == SD_Thread) 245 TR = MRMgr.getCXXStaticTempObjectRegion(Init); 246 } 247 if (!TR) 248 TR = MRMgr.getCXXTempObjectRegion(Init, LC); 249 250 SVal Reg = loc::MemRegionVal(TR); 251 SVal BaseReg = Reg; 252 253 // Make the necessary adjustments to obtain the sub-object. 254 for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) { 255 const SubobjectAdjustment &Adj = *I; 256 switch (Adj.Kind) { 257 case SubobjectAdjustment::DerivedToBaseAdjustment: 258 Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath); 259 break; 260 case SubobjectAdjustment::FieldAdjustment: 261 Reg = StoreMgr.getLValueField(Adj.Field, Reg); 262 break; 263 case SubobjectAdjustment::MemberPointerAdjustment: 264 // FIXME: Unimplemented. 265 State = State->bindDefault(Reg, UnknownVal(), LC); 266 return State; 267 } 268 } 269 270 // What remains is to copy the value of the object to the new region. 271 // FIXME: In other words, what we should always do is copy value of the 272 // Init expression (which corresponds to the bigger object) to the whole 273 // temporary region TR. However, this value is often no longer present 274 // in the Environment. If it has disappeared, we instead invalidate TR. 275 // Still, what we can do is assign the value of expression Ex (which 276 // corresponds to the sub-object) to the TR's sub-region Reg. At least, 277 // values inside Reg would be correct. 278 SVal InitVal = State->getSVal(Init, LC); 279 if (InitVal.isUnknown()) { 280 InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(), 281 currBldrCtx->blockCount()); 282 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false); 283 284 // Then we'd need to take the value that certainly exists and bind it over. 285 if (InitValWithAdjustments.isUnknown()) { 286 // Try to recover some path sensitivity in case we couldn't 287 // compute the value. 288 InitValWithAdjustments = getSValBuilder().conjureSymbolVal( 289 Result, LC, InitWithAdjustments->getType(), 290 currBldrCtx->blockCount()); 291 } 292 State = 293 State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false); 294 } else { 295 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false); 296 } 297 298 // The result expression would now point to the correct sub-region of the 299 // newly created temporary region. Do this last in order to getSVal of Init 300 // correctly in case (Result == Init). 301 State = State->BindExpr(Result, LC, Reg); 302 303 // Notify checkers once for two bindLoc()s. 304 State = processRegionChange(State, TR, LC); 305 306 return State; 307 } 308 309 //===----------------------------------------------------------------------===// 310 // Top-level transfer function logic (Dispatcher). 311 //===----------------------------------------------------------------------===// 312 313 /// evalAssume - Called by ConstraintManager. Used to call checker-specific 314 /// logic for handling assumptions on symbolic values. 315 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state, 316 SVal cond, bool assumption) { 317 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption); 318 } 319 320 ProgramStateRef 321 ExprEngine::processRegionChanges(ProgramStateRef state, 322 const InvalidatedSymbols *invalidated, 323 ArrayRef<const MemRegion *> Explicits, 324 ArrayRef<const MemRegion *> Regions, 325 const LocationContext *LCtx, 326 const CallEvent *Call) { 327 return getCheckerManager().runCheckersForRegionChanges(state, invalidated, 328 Explicits, Regions, 329 LCtx, Call); 330 } 331 332 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State, 333 const char *NL, const char *Sep) { 334 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep); 335 } 336 337 void ExprEngine::processEndWorklist(bool hasWorkRemaining) { 338 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this); 339 } 340 341 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred, 342 unsigned StmtIdx, NodeBuilderContext *Ctx) { 343 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 344 currStmtIdx = StmtIdx; 345 currBldrCtx = Ctx; 346 347 switch (E.getKind()) { 348 case CFGElement::Statement: 349 ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred); 350 return; 351 case CFGElement::Initializer: 352 ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred); 353 return; 354 case CFGElement::NewAllocator: 355 ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(), 356 Pred); 357 return; 358 case CFGElement::AutomaticObjectDtor: 359 case CFGElement::DeleteDtor: 360 case CFGElement::BaseDtor: 361 case CFGElement::MemberDtor: 362 case CFGElement::TemporaryDtor: 363 ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred); 364 return; 365 case CFGElement::LifetimeEnds: 366 return; 367 } 368 } 369 370 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr, 371 const CFGStmt S, 372 const ExplodedNode *Pred, 373 const LocationContext *LC) { 374 375 // Are we never purging state values? 376 if (AMgr.options.AnalysisPurgeOpt == PurgeNone) 377 return false; 378 379 // Is this the beginning of a basic block? 380 if (Pred->getLocation().getAs<BlockEntrance>()) 381 return true; 382 383 // Is this on a non-expression? 384 if (!isa<Expr>(S.getStmt())) 385 return true; 386 387 // Run before processing a call. 388 if (CallEvent::isCallStmt(S.getStmt())) 389 return true; 390 391 // Is this an expression that is consumed by another expression? If so, 392 // postpone cleaning out the state. 393 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap(); 394 return !PM.isConsumedExpr(cast<Expr>(S.getStmt())); 395 } 396 397 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out, 398 const Stmt *ReferenceStmt, 399 const LocationContext *LC, 400 const Stmt *DiagnosticStmt, 401 ProgramPoint::Kind K) { 402 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind || 403 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt)) 404 && "PostStmt is not generally supported by the SymbolReaper yet"); 405 assert(LC && "Must pass the current (or expiring) LocationContext"); 406 407 if (!DiagnosticStmt) { 408 DiagnosticStmt = ReferenceStmt; 409 assert(DiagnosticStmt && "Required for clearing a LocationContext"); 410 } 411 412 NumRemoveDeadBindings++; 413 ProgramStateRef CleanedState = Pred->getState(); 414 415 // LC is the location context being destroyed, but SymbolReaper wants a 416 // location context that is still live. (If this is the top-level stack 417 // frame, this will be null.) 418 if (!ReferenceStmt) { 419 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind && 420 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext"); 421 LC = LC->getParent(); 422 } 423 424 const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : nullptr; 425 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager()); 426 427 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper); 428 429 // Create a state in which dead bindings are removed from the environment 430 // and the store. TODO: The function should just return new env and store, 431 // not a new state. 432 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper); 433 434 // Process any special transfer function for dead symbols. 435 // A tag to track convenience transitions, which can be removed at cleanup. 436 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node"); 437 if (!SymReaper.hasDeadSymbols()) { 438 // Generate a CleanedNode that has the environment and store cleaned 439 // up. Since no symbols are dead, we can optimize and not clean out 440 // the constraint manager. 441 StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx); 442 Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K); 443 444 } else { 445 // Call checkers with the non-cleaned state so that they could query the 446 // values of the soon to be dead symbols. 447 ExplodedNodeSet CheckedSet; 448 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper, 449 DiagnosticStmt, *this, K); 450 451 // For each node in CheckedSet, generate CleanedNodes that have the 452 // environment, the store, and the constraints cleaned up but have the 453 // user-supplied states as the predecessors. 454 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx); 455 for (ExplodedNodeSet::const_iterator 456 I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) { 457 ProgramStateRef CheckerState = (*I)->getState(); 458 459 // The constraint manager has not been cleaned up yet, so clean up now. 460 CheckerState = getConstraintManager().removeDeadBindings(CheckerState, 461 SymReaper); 462 463 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) && 464 "Checkers are not allowed to modify the Environment as a part of " 465 "checkDeadSymbols processing."); 466 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) && 467 "Checkers are not allowed to modify the Store as a part of " 468 "checkDeadSymbols processing."); 469 470 // Create a state based on CleanedState with CheckerState GDM and 471 // generate a transition to that state. 472 ProgramStateRef CleanedCheckerSt = 473 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState); 474 Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K); 475 } 476 } 477 } 478 479 void ExprEngine::ProcessStmt(const CFGStmt S, 480 ExplodedNode *Pred) { 481 // Reclaim any unnecessary nodes in the ExplodedGraph. 482 G.reclaimRecentlyAllocatedNodes(); 483 484 const Stmt *currStmt = S.getStmt(); 485 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 486 currStmt->getLocStart(), 487 "Error evaluating statement"); 488 489 // Remove dead bindings and symbols. 490 ExplodedNodeSet CleanedStates; 491 if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){ 492 removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext()); 493 } else 494 CleanedStates.Add(Pred); 495 496 // Visit the statement. 497 ExplodedNodeSet Dst; 498 for (ExplodedNodeSet::iterator I = CleanedStates.begin(), 499 E = CleanedStates.end(); I != E; ++I) { 500 ExplodedNodeSet DstI; 501 // Visit the statement. 502 Visit(currStmt, *I, DstI); 503 Dst.insert(DstI); 504 } 505 506 // Enqueue the new nodes onto the work list. 507 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 508 } 509 510 void ExprEngine::ProcessInitializer(const CFGInitializer Init, 511 ExplodedNode *Pred) { 512 const CXXCtorInitializer *BMI = Init.getInitializer(); 513 514 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 515 BMI->getSourceLocation(), 516 "Error evaluating initializer"); 517 518 // We don't clean up dead bindings here. 519 const StackFrameContext *stackFrame = 520 cast<StackFrameContext>(Pred->getLocationContext()); 521 const CXXConstructorDecl *decl = 522 cast<CXXConstructorDecl>(stackFrame->getDecl()); 523 524 ProgramStateRef State = Pred->getState(); 525 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame)); 526 527 ExplodedNodeSet Tmp(Pred); 528 SVal FieldLoc; 529 530 // Evaluate the initializer, if necessary 531 if (BMI->isAnyMemberInitializer()) { 532 // Constructors build the object directly in the field, 533 // but non-objects must be copied in from the initializer. 534 if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) { 535 assert(BMI->getInit()->IgnoreImplicit() == CtorExpr); 536 (void)CtorExpr; 537 // The field was directly constructed, so there is no need to bind. 538 } else { 539 const Expr *Init = BMI->getInit()->IgnoreImplicit(); 540 const ValueDecl *Field; 541 if (BMI->isIndirectMemberInitializer()) { 542 Field = BMI->getIndirectMember(); 543 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal); 544 } else { 545 Field = BMI->getMember(); 546 FieldLoc = State->getLValue(BMI->getMember(), thisVal); 547 } 548 549 SVal InitVal; 550 if (Init->getType()->isArrayType()) { 551 // Handle arrays of trivial type. We can represent this with a 552 // primitive load/copy from the base array region. 553 const ArraySubscriptExpr *ASE; 554 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init))) 555 Init = ASE->getBase()->IgnoreImplicit(); 556 557 SVal LValue = State->getSVal(Init, stackFrame); 558 if (!Field->getType()->isReferenceType()) 559 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>()) 560 InitVal = State->getSVal(*LValueLoc); 561 562 // If we fail to get the value for some reason, use a symbolic value. 563 if (InitVal.isUnknownOrUndef()) { 564 SValBuilder &SVB = getSValBuilder(); 565 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame, 566 Field->getType(), 567 currBldrCtx->blockCount()); 568 } 569 } else { 570 InitVal = State->getSVal(BMI->getInit(), stackFrame); 571 } 572 573 assert(Tmp.size() == 1 && "have not generated any new nodes yet"); 574 assert(*Tmp.begin() == Pred && "have not generated any new nodes yet"); 575 Tmp.clear(); 576 577 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame); 578 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP); 579 } 580 } else { 581 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer()); 582 // We already did all the work when visiting the CXXConstructExpr. 583 } 584 585 // Construct PostInitializer nodes whether the state changed or not, 586 // so that the diagnostics don't get confused. 587 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame); 588 ExplodedNodeSet Dst; 589 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 590 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) { 591 ExplodedNode *N = *I; 592 Bldr.generateNode(PP, N->getState(), N); 593 } 594 595 // Enqueue the new nodes onto the work list. 596 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 597 } 598 599 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D, 600 ExplodedNode *Pred) { 601 ExplodedNodeSet Dst; 602 switch (D.getKind()) { 603 case CFGElement::AutomaticObjectDtor: 604 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst); 605 break; 606 case CFGElement::BaseDtor: 607 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst); 608 break; 609 case CFGElement::MemberDtor: 610 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst); 611 break; 612 case CFGElement::TemporaryDtor: 613 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst); 614 break; 615 case CFGElement::DeleteDtor: 616 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst); 617 break; 618 default: 619 llvm_unreachable("Unexpected dtor kind."); 620 } 621 622 // Enqueue the new nodes onto the work list. 623 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 624 } 625 626 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE, 627 ExplodedNode *Pred) { 628 ExplodedNodeSet Dst; 629 AnalysisManager &AMgr = getAnalysisManager(); 630 AnalyzerOptions &Opts = AMgr.options; 631 // TODO: We're not evaluating allocators for all cases just yet as 632 // we're not handling the return value correctly, which causes false 633 // positives when the alpha.cplusplus.NewDeleteLeaks check is on. 634 if (Opts.mayInlineCXXAllocator()) 635 VisitCXXNewAllocatorCall(NE, Pred, Dst); 636 else { 637 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 638 const LocationContext *LCtx = Pred->getLocationContext(); 639 PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx); 640 Bldr.generateNode(PP, Pred->getState(), Pred); 641 } 642 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 643 } 644 645 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor, 646 ExplodedNode *Pred, 647 ExplodedNodeSet &Dst) { 648 const VarDecl *varDecl = Dtor.getVarDecl(); 649 QualType varType = varDecl->getType(); 650 651 ProgramStateRef state = Pred->getState(); 652 SVal dest = state->getLValue(varDecl, Pred->getLocationContext()); 653 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion(); 654 655 if (varType->isReferenceType()) { 656 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion(); 657 if (!ValueRegion) { 658 // FIXME: This should not happen. The language guarantees a presence 659 // of a valid initializer here, so the reference shall not be undefined. 660 // It seems that we're calling destructors over variables that 661 // were not initialized yet. 662 return; 663 } 664 Region = ValueRegion->getBaseRegion(); 665 varType = cast<TypedValueRegion>(Region)->getValueType(); 666 } 667 668 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false, 669 Pred, Dst); 670 } 671 672 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor, 673 ExplodedNode *Pred, 674 ExplodedNodeSet &Dst) { 675 ProgramStateRef State = Pred->getState(); 676 const LocationContext *LCtx = Pred->getLocationContext(); 677 const CXXDeleteExpr *DE = Dtor.getDeleteExpr(); 678 const Stmt *Arg = DE->getArgument(); 679 SVal ArgVal = State->getSVal(Arg, LCtx); 680 681 // If the argument to delete is known to be a null value, 682 // don't run destructor. 683 if (State->isNull(ArgVal).isConstrainedTrue()) { 684 QualType DTy = DE->getDestroyedType(); 685 QualType BTy = getContext().getBaseElementType(DTy); 686 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl(); 687 const CXXDestructorDecl *Dtor = RD->getDestructor(); 688 689 PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx); 690 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 691 Bldr.generateNode(PP, Pred->getState(), Pred); 692 return; 693 } 694 695 VisitCXXDestructor(DE->getDestroyedType(), 696 ArgVal.getAsRegion(), 697 DE, /*IsBase=*/ false, 698 Pred, Dst); 699 } 700 701 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D, 702 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 703 const LocationContext *LCtx = Pred->getLocationContext(); 704 705 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 706 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor, 707 LCtx->getCurrentStackFrame()); 708 SVal ThisVal = Pred->getState()->getSVal(ThisPtr); 709 710 // Create the base object region. 711 const CXXBaseSpecifier *Base = D.getBaseSpecifier(); 712 QualType BaseTy = Base->getType(); 713 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy, 714 Base->isVirtual()); 715 716 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(), 717 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst); 718 } 719 720 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D, 721 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 722 const FieldDecl *Member = D.getFieldDecl(); 723 ProgramStateRef State = Pred->getState(); 724 const LocationContext *LCtx = Pred->getLocationContext(); 725 726 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 727 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor, 728 LCtx->getCurrentStackFrame()); 729 SVal FieldVal = 730 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>()); 731 732 VisitCXXDestructor(Member->getType(), 733 FieldVal.castAs<loc::MemRegionVal>().getRegion(), 734 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst); 735 } 736 737 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, 738 ExplodedNode *Pred, 739 ExplodedNodeSet &Dst) { 740 ExplodedNodeSet CleanDtorState; 741 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx); 742 ProgramStateRef State = Pred->getState(); 743 if (State->contains<InitializedTemporariesSet>( 744 std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()))) { 745 // FIXME: Currently we insert temporary destructors for default parameters, 746 // but we don't insert the constructors. 747 State = State->remove<InitializedTemporariesSet>( 748 std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame())); 749 } 750 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State); 751 752 QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType(); 753 // FIXME: Currently CleanDtorState can be empty here due to temporaries being 754 // bound to default parameters. 755 assert(CleanDtorState.size() <= 1); 756 ExplodedNode *CleanPred = 757 CleanDtorState.empty() ? Pred : *CleanDtorState.begin(); 758 // FIXME: Inlining of temporary destructors is not supported yet anyway, so 759 // we just put a NULL region for now. This will need to be changed later. 760 VisitCXXDestructor(varType, nullptr, D.getBindTemporaryExpr(), 761 /*IsBase=*/false, CleanPred, Dst); 762 } 763 764 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, 765 NodeBuilderContext &BldCtx, 766 ExplodedNode *Pred, 767 ExplodedNodeSet &Dst, 768 const CFGBlock *DstT, 769 const CFGBlock *DstF) { 770 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF); 771 if (Pred->getState()->contains<InitializedTemporariesSet>( 772 std::make_pair(BTE, Pred->getStackFrame()))) { 773 TempDtorBuilder.markInfeasible(false); 774 TempDtorBuilder.generateNode(Pred->getState(), true, Pred); 775 } else { 776 TempDtorBuilder.markInfeasible(true); 777 TempDtorBuilder.generateNode(Pred->getState(), false, Pred); 778 } 779 } 780 781 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, 782 ExplodedNodeSet &PreVisit, 783 ExplodedNodeSet &Dst) { 784 if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) { 785 // In case we don't have temporary destructors in the CFG, do not mark 786 // the initialization - we would otherwise never clean it up. 787 Dst = PreVisit; 788 return; 789 } 790 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx); 791 for (ExplodedNode *Node : PreVisit) { 792 ProgramStateRef State = Node->getState(); 793 794 if (!State->contains<InitializedTemporariesSet>( 795 std::make_pair(BTE, Node->getStackFrame()))) { 796 // FIXME: Currently the state might already contain the marker due to 797 // incorrect handling of temporaries bound to default parameters; for 798 // those, we currently skip the CXXBindTemporaryExpr but rely on adding 799 // temporary destructor nodes. 800 State = State->add<InitializedTemporariesSet>( 801 std::make_pair(BTE, Node->getStackFrame())); 802 } 803 StmtBldr.generateNode(BTE, Node, State); 804 } 805 } 806 807 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, 808 ExplodedNodeSet &DstTop) { 809 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 810 S->getLocStart(), 811 "Error evaluating statement"); 812 ExplodedNodeSet Dst; 813 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx); 814 815 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens()); 816 817 switch (S->getStmtClass()) { 818 // C++, OpenMP and ARC stuff we don't support yet. 819 case Expr::ObjCIndirectCopyRestoreExprClass: 820 case Stmt::CXXDependentScopeMemberExprClass: 821 case Stmt::CXXInheritedCtorInitExprClass: 822 case Stmt::CXXTryStmtClass: 823 case Stmt::CXXTypeidExprClass: 824 case Stmt::CXXUuidofExprClass: 825 case Stmt::CXXFoldExprClass: 826 case Stmt::MSPropertyRefExprClass: 827 case Stmt::MSPropertySubscriptExprClass: 828 case Stmt::CXXUnresolvedConstructExprClass: 829 case Stmt::DependentScopeDeclRefExprClass: 830 case Stmt::ArrayTypeTraitExprClass: 831 case Stmt::ExpressionTraitExprClass: 832 case Stmt::UnresolvedLookupExprClass: 833 case Stmt::UnresolvedMemberExprClass: 834 case Stmt::TypoExprClass: 835 case Stmt::CXXNoexceptExprClass: 836 case Stmt::PackExpansionExprClass: 837 case Stmt::SubstNonTypeTemplateParmPackExprClass: 838 case Stmt::FunctionParmPackExprClass: 839 case Stmt::CoroutineBodyStmtClass: 840 case Stmt::CoawaitExprClass: 841 case Stmt::DependentCoawaitExprClass: 842 case Stmt::CoreturnStmtClass: 843 case Stmt::CoyieldExprClass: 844 case Stmt::SEHTryStmtClass: 845 case Stmt::SEHExceptStmtClass: 846 case Stmt::SEHLeaveStmtClass: 847 case Stmt::SEHFinallyStmtClass: 848 case Stmt::OMPParallelDirectiveClass: 849 case Stmt::OMPSimdDirectiveClass: 850 case Stmt::OMPForDirectiveClass: 851 case Stmt::OMPForSimdDirectiveClass: 852 case Stmt::OMPSectionsDirectiveClass: 853 case Stmt::OMPSectionDirectiveClass: 854 case Stmt::OMPSingleDirectiveClass: 855 case Stmt::OMPMasterDirectiveClass: 856 case Stmt::OMPCriticalDirectiveClass: 857 case Stmt::OMPParallelForDirectiveClass: 858 case Stmt::OMPParallelForSimdDirectiveClass: 859 case Stmt::OMPParallelSectionsDirectiveClass: 860 case Stmt::OMPTaskDirectiveClass: 861 case Stmt::OMPTaskyieldDirectiveClass: 862 case Stmt::OMPBarrierDirectiveClass: 863 case Stmt::OMPTaskwaitDirectiveClass: 864 case Stmt::OMPTaskgroupDirectiveClass: 865 case Stmt::OMPFlushDirectiveClass: 866 case Stmt::OMPOrderedDirectiveClass: 867 case Stmt::OMPAtomicDirectiveClass: 868 case Stmt::OMPTargetDirectiveClass: 869 case Stmt::OMPTargetDataDirectiveClass: 870 case Stmt::OMPTargetEnterDataDirectiveClass: 871 case Stmt::OMPTargetExitDataDirectiveClass: 872 case Stmt::OMPTargetParallelDirectiveClass: 873 case Stmt::OMPTargetParallelForDirectiveClass: 874 case Stmt::OMPTargetUpdateDirectiveClass: 875 case Stmt::OMPTeamsDirectiveClass: 876 case Stmt::OMPCancellationPointDirectiveClass: 877 case Stmt::OMPCancelDirectiveClass: 878 case Stmt::OMPTaskLoopDirectiveClass: 879 case Stmt::OMPTaskLoopSimdDirectiveClass: 880 case Stmt::OMPDistributeDirectiveClass: 881 case Stmt::OMPDistributeParallelForDirectiveClass: 882 case Stmt::OMPDistributeParallelForSimdDirectiveClass: 883 case Stmt::OMPDistributeSimdDirectiveClass: 884 case Stmt::OMPTargetParallelForSimdDirectiveClass: 885 case Stmt::OMPTargetSimdDirectiveClass: 886 case Stmt::OMPTeamsDistributeDirectiveClass: 887 case Stmt::OMPTeamsDistributeSimdDirectiveClass: 888 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass: 889 case Stmt::OMPTeamsDistributeParallelForDirectiveClass: 890 case Stmt::OMPTargetTeamsDirectiveClass: 891 case Stmt::OMPTargetTeamsDistributeDirectiveClass: 892 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass: 893 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass: 894 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass: 895 case Stmt::CapturedStmtClass: 896 { 897 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 898 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 899 break; 900 } 901 902 case Stmt::ParenExprClass: 903 llvm_unreachable("ParenExprs already handled."); 904 case Stmt::GenericSelectionExprClass: 905 llvm_unreachable("GenericSelectionExprs already handled."); 906 // Cases that should never be evaluated simply because they shouldn't 907 // appear in the CFG. 908 case Stmt::BreakStmtClass: 909 case Stmt::CaseStmtClass: 910 case Stmt::CompoundStmtClass: 911 case Stmt::ContinueStmtClass: 912 case Stmt::CXXForRangeStmtClass: 913 case Stmt::DefaultStmtClass: 914 case Stmt::DoStmtClass: 915 case Stmt::ForStmtClass: 916 case Stmt::GotoStmtClass: 917 case Stmt::IfStmtClass: 918 case Stmt::IndirectGotoStmtClass: 919 case Stmt::LabelStmtClass: 920 case Stmt::NoStmtClass: 921 case Stmt::NullStmtClass: 922 case Stmt::SwitchStmtClass: 923 case Stmt::WhileStmtClass: 924 case Expr::MSDependentExistsStmtClass: 925 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 926 927 case Stmt::ObjCSubscriptRefExprClass: 928 case Stmt::ObjCPropertyRefExprClass: 929 llvm_unreachable("These are handled by PseudoObjectExpr"); 930 931 case Stmt::GNUNullExprClass: { 932 // GNU __null is a pointer-width integer, not an actual pointer. 933 ProgramStateRef state = Pred->getState(); 934 state = state->BindExpr(S, Pred->getLocationContext(), 935 svalBuilder.makeIntValWithPtrWidth(0, false)); 936 Bldr.generateNode(S, Pred, state); 937 break; 938 } 939 940 case Stmt::ObjCAtSynchronizedStmtClass: 941 Bldr.takeNodes(Pred); 942 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 943 Bldr.addNodes(Dst); 944 break; 945 946 case Stmt::ExprWithCleanupsClass: 947 // Handled due to fully linearised CFG. 948 break; 949 950 case Stmt::CXXBindTemporaryExprClass: { 951 Bldr.takeNodes(Pred); 952 ExplodedNodeSet PreVisit; 953 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 954 ExplodedNodeSet Next; 955 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next); 956 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this); 957 Bldr.addNodes(Dst); 958 break; 959 } 960 961 // Cases not handled yet; but will handle some day. 962 case Stmt::DesignatedInitExprClass: 963 case Stmt::DesignatedInitUpdateExprClass: 964 case Stmt::ArrayInitLoopExprClass: 965 case Stmt::ArrayInitIndexExprClass: 966 case Stmt::ExtVectorElementExprClass: 967 case Stmt::ImaginaryLiteralClass: 968 case Stmt::ObjCAtCatchStmtClass: 969 case Stmt::ObjCAtFinallyStmtClass: 970 case Stmt::ObjCAtTryStmtClass: 971 case Stmt::ObjCAutoreleasePoolStmtClass: 972 case Stmt::ObjCEncodeExprClass: 973 case Stmt::ObjCIsaExprClass: 974 case Stmt::ObjCProtocolExprClass: 975 case Stmt::ObjCSelectorExprClass: 976 case Stmt::ParenListExprClass: 977 case Stmt::ShuffleVectorExprClass: 978 case Stmt::ConvertVectorExprClass: 979 case Stmt::VAArgExprClass: 980 case Stmt::CUDAKernelCallExprClass: 981 case Stmt::OpaqueValueExprClass: 982 case Stmt::AsTypeExprClass: 983 // Fall through. 984 985 // Cases we intentionally don't evaluate, since they don't need 986 // to be explicitly evaluated. 987 case Stmt::PredefinedExprClass: 988 case Stmt::AddrLabelExprClass: 989 case Stmt::AttributedStmtClass: 990 case Stmt::IntegerLiteralClass: 991 case Stmt::CharacterLiteralClass: 992 case Stmt::ImplicitValueInitExprClass: 993 case Stmt::CXXScalarValueInitExprClass: 994 case Stmt::CXXBoolLiteralExprClass: 995 case Stmt::ObjCBoolLiteralExprClass: 996 case Stmt::ObjCAvailabilityCheckExprClass: 997 case Stmt::FloatingLiteralClass: 998 case Stmt::NoInitExprClass: 999 case Stmt::SizeOfPackExprClass: 1000 case Stmt::StringLiteralClass: 1001 case Stmt::ObjCStringLiteralClass: 1002 case Stmt::CXXPseudoDestructorExprClass: 1003 case Stmt::SubstNonTypeTemplateParmExprClass: 1004 case Stmt::CXXNullPtrLiteralExprClass: 1005 case Stmt::OMPArraySectionExprClass: 1006 case Stmt::TypeTraitExprClass: { 1007 Bldr.takeNodes(Pred); 1008 ExplodedNodeSet preVisit; 1009 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 1010 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this); 1011 Bldr.addNodes(Dst); 1012 break; 1013 } 1014 1015 case Stmt::CXXDefaultArgExprClass: 1016 case Stmt::CXXDefaultInitExprClass: { 1017 Bldr.takeNodes(Pred); 1018 ExplodedNodeSet PreVisit; 1019 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1020 1021 ExplodedNodeSet Tmp; 1022 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx); 1023 1024 const Expr *ArgE; 1025 if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S)) 1026 ArgE = DefE->getExpr(); 1027 else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S)) 1028 ArgE = DefE->getExpr(); 1029 else 1030 llvm_unreachable("unknown constant wrapper kind"); 1031 1032 bool IsTemporary = false; 1033 if (const MaterializeTemporaryExpr *MTE = 1034 dyn_cast<MaterializeTemporaryExpr>(ArgE)) { 1035 ArgE = MTE->GetTemporaryExpr(); 1036 IsTemporary = true; 1037 } 1038 1039 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE); 1040 if (!ConstantVal) 1041 ConstantVal = UnknownVal(); 1042 1043 const LocationContext *LCtx = Pred->getLocationContext(); 1044 for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end(); 1045 I != E; ++I) { 1046 ProgramStateRef State = (*I)->getState(); 1047 State = State->BindExpr(S, LCtx, *ConstantVal); 1048 if (IsTemporary) 1049 State = createTemporaryRegionIfNeeded(State, LCtx, 1050 cast<Expr>(S), 1051 cast<Expr>(S)); 1052 Bldr2.generateNode(S, *I, State); 1053 } 1054 1055 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 1056 Bldr.addNodes(Dst); 1057 break; 1058 } 1059 1060 // Cases we evaluate as opaque expressions, conjuring a symbol. 1061 case Stmt::CXXStdInitializerListExprClass: 1062 case Expr::ObjCArrayLiteralClass: 1063 case Expr::ObjCDictionaryLiteralClass: 1064 case Expr::ObjCBoxedExprClass: { 1065 Bldr.takeNodes(Pred); 1066 1067 ExplodedNodeSet preVisit; 1068 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 1069 1070 ExplodedNodeSet Tmp; 1071 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx); 1072 1073 const Expr *Ex = cast<Expr>(S); 1074 QualType resultType = Ex->getType(); 1075 1076 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end(); 1077 it != et; ++it) { 1078 ExplodedNode *N = *it; 1079 const LocationContext *LCtx = N->getLocationContext(); 1080 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx, 1081 resultType, 1082 currBldrCtx->blockCount()); 1083 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result); 1084 Bldr2.generateNode(S, N, state); 1085 } 1086 1087 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 1088 Bldr.addNodes(Dst); 1089 break; 1090 } 1091 1092 case Stmt::ArraySubscriptExprClass: 1093 Bldr.takeNodes(Pred); 1094 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 1095 Bldr.addNodes(Dst); 1096 break; 1097 1098 case Stmt::GCCAsmStmtClass: 1099 Bldr.takeNodes(Pred); 1100 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst); 1101 Bldr.addNodes(Dst); 1102 break; 1103 1104 case Stmt::MSAsmStmtClass: 1105 Bldr.takeNodes(Pred); 1106 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst); 1107 Bldr.addNodes(Dst); 1108 break; 1109 1110 case Stmt::BlockExprClass: 1111 Bldr.takeNodes(Pred); 1112 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 1113 Bldr.addNodes(Dst); 1114 break; 1115 1116 case Stmt::LambdaExprClass: 1117 if (AMgr.options.shouldInlineLambdas()) { 1118 Bldr.takeNodes(Pred); 1119 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst); 1120 Bldr.addNodes(Dst); 1121 } else { 1122 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 1123 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 1124 } 1125 break; 1126 1127 case Stmt::BinaryOperatorClass: { 1128 const BinaryOperator* B = cast<BinaryOperator>(S); 1129 if (B->isLogicalOp()) { 1130 Bldr.takeNodes(Pred); 1131 VisitLogicalExpr(B, Pred, Dst); 1132 Bldr.addNodes(Dst); 1133 break; 1134 } 1135 else if (B->getOpcode() == BO_Comma) { 1136 ProgramStateRef state = Pred->getState(); 1137 Bldr.generateNode(B, Pred, 1138 state->BindExpr(B, Pred->getLocationContext(), 1139 state->getSVal(B->getRHS(), 1140 Pred->getLocationContext()))); 1141 break; 1142 } 1143 1144 Bldr.takeNodes(Pred); 1145 1146 if (AMgr.options.eagerlyAssumeBinOpBifurcation && 1147 (B->isRelationalOp() || B->isEqualityOp())) { 1148 ExplodedNodeSet Tmp; 1149 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 1150 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S)); 1151 } 1152 else 1153 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 1154 1155 Bldr.addNodes(Dst); 1156 break; 1157 } 1158 1159 case Stmt::CXXOperatorCallExprClass: { 1160 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S); 1161 1162 // For instance method operators, make sure the 'this' argument has a 1163 // valid region. 1164 const Decl *Callee = OCE->getCalleeDecl(); 1165 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) { 1166 if (MD->isInstance()) { 1167 ProgramStateRef State = Pred->getState(); 1168 const LocationContext *LCtx = Pred->getLocationContext(); 1169 ProgramStateRef NewState = 1170 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0)); 1171 if (NewState != State) { 1172 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr, 1173 ProgramPoint::PreStmtKind); 1174 // Did we cache out? 1175 if (!Pred) 1176 break; 1177 } 1178 } 1179 } 1180 // FALLTHROUGH 1181 LLVM_FALLTHROUGH; 1182 } 1183 case Stmt::CallExprClass: 1184 case Stmt::CXXMemberCallExprClass: 1185 case Stmt::UserDefinedLiteralClass: { 1186 Bldr.takeNodes(Pred); 1187 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 1188 Bldr.addNodes(Dst); 1189 break; 1190 } 1191 1192 case Stmt::CXXCatchStmtClass: { 1193 Bldr.takeNodes(Pred); 1194 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst); 1195 Bldr.addNodes(Dst); 1196 break; 1197 } 1198 1199 case Stmt::CXXTemporaryObjectExprClass: 1200 case Stmt::CXXConstructExprClass: { 1201 Bldr.takeNodes(Pred); 1202 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst); 1203 Bldr.addNodes(Dst); 1204 break; 1205 } 1206 1207 case Stmt::CXXNewExprClass: { 1208 Bldr.takeNodes(Pred); 1209 ExplodedNodeSet PostVisit; 1210 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit); 1211 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this); 1212 Bldr.addNodes(Dst); 1213 break; 1214 } 1215 1216 case Stmt::CXXDeleteExprClass: { 1217 Bldr.takeNodes(Pred); 1218 ExplodedNodeSet PreVisit; 1219 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S); 1220 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1221 1222 for (ExplodedNodeSet::iterator i = PreVisit.begin(), 1223 e = PreVisit.end(); i != e ; ++i) 1224 VisitCXXDeleteExpr(CDE, *i, Dst); 1225 1226 Bldr.addNodes(Dst); 1227 break; 1228 } 1229 // FIXME: ChooseExpr is really a constant. We need to fix 1230 // the CFG do not model them as explicit control-flow. 1231 1232 case Stmt::ChooseExprClass: { // __builtin_choose_expr 1233 Bldr.takeNodes(Pred); 1234 const ChooseExpr *C = cast<ChooseExpr>(S); 1235 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 1236 Bldr.addNodes(Dst); 1237 break; 1238 } 1239 1240 case Stmt::CompoundAssignOperatorClass: 1241 Bldr.takeNodes(Pred); 1242 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 1243 Bldr.addNodes(Dst); 1244 break; 1245 1246 case Stmt::CompoundLiteralExprClass: 1247 Bldr.takeNodes(Pred); 1248 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 1249 Bldr.addNodes(Dst); 1250 break; 1251 1252 case Stmt::BinaryConditionalOperatorClass: 1253 case Stmt::ConditionalOperatorClass: { // '?' operator 1254 Bldr.takeNodes(Pred); 1255 const AbstractConditionalOperator *C 1256 = cast<AbstractConditionalOperator>(S); 1257 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 1258 Bldr.addNodes(Dst); 1259 break; 1260 } 1261 1262 case Stmt::CXXThisExprClass: 1263 Bldr.takeNodes(Pred); 1264 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 1265 Bldr.addNodes(Dst); 1266 break; 1267 1268 case Stmt::DeclRefExprClass: { 1269 Bldr.takeNodes(Pred); 1270 const DeclRefExpr *DE = cast<DeclRefExpr>(S); 1271 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 1272 Bldr.addNodes(Dst); 1273 break; 1274 } 1275 1276 case Stmt::DeclStmtClass: 1277 Bldr.takeNodes(Pred); 1278 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 1279 Bldr.addNodes(Dst); 1280 break; 1281 1282 case Stmt::ImplicitCastExprClass: 1283 case Stmt::CStyleCastExprClass: 1284 case Stmt::CXXStaticCastExprClass: 1285 case Stmt::CXXDynamicCastExprClass: 1286 case Stmt::CXXReinterpretCastExprClass: 1287 case Stmt::CXXConstCastExprClass: 1288 case Stmt::CXXFunctionalCastExprClass: 1289 case Stmt::ObjCBridgedCastExprClass: { 1290 Bldr.takeNodes(Pred); 1291 const CastExpr *C = cast<CastExpr>(S); 1292 ExplodedNodeSet dstExpr; 1293 VisitCast(C, C->getSubExpr(), Pred, dstExpr); 1294 1295 // Handle the postvisit checks. 1296 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 1297 Bldr.addNodes(Dst); 1298 break; 1299 } 1300 1301 case Expr::MaterializeTemporaryExprClass: { 1302 Bldr.takeNodes(Pred); 1303 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S); 1304 ExplodedNodeSet dstPrevisit; 1305 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this); 1306 ExplodedNodeSet dstExpr; 1307 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(), 1308 e = dstPrevisit.end(); i != e ; ++i) { 1309 CreateCXXTemporaryObject(MTE, *i, dstExpr); 1310 } 1311 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this); 1312 Bldr.addNodes(Dst); 1313 break; 1314 } 1315 1316 case Stmt::InitListExprClass: 1317 Bldr.takeNodes(Pred); 1318 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 1319 Bldr.addNodes(Dst); 1320 break; 1321 1322 case Stmt::MemberExprClass: 1323 Bldr.takeNodes(Pred); 1324 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 1325 Bldr.addNodes(Dst); 1326 break; 1327 1328 case Stmt::AtomicExprClass: 1329 Bldr.takeNodes(Pred); 1330 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst); 1331 Bldr.addNodes(Dst); 1332 break; 1333 1334 case Stmt::ObjCIvarRefExprClass: 1335 Bldr.takeNodes(Pred); 1336 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 1337 Bldr.addNodes(Dst); 1338 break; 1339 1340 case Stmt::ObjCForCollectionStmtClass: 1341 Bldr.takeNodes(Pred); 1342 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 1343 Bldr.addNodes(Dst); 1344 break; 1345 1346 case Stmt::ObjCMessageExprClass: 1347 Bldr.takeNodes(Pred); 1348 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst); 1349 Bldr.addNodes(Dst); 1350 break; 1351 1352 case Stmt::ObjCAtThrowStmtClass: 1353 case Stmt::CXXThrowExprClass: 1354 // FIXME: This is not complete. We basically treat @throw as 1355 // an abort. 1356 Bldr.generateSink(S, Pred, Pred->getState()); 1357 break; 1358 1359 case Stmt::ReturnStmtClass: 1360 Bldr.takeNodes(Pred); 1361 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 1362 Bldr.addNodes(Dst); 1363 break; 1364 1365 case Stmt::OffsetOfExprClass: 1366 Bldr.takeNodes(Pred); 1367 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst); 1368 Bldr.addNodes(Dst); 1369 break; 1370 1371 case Stmt::UnaryExprOrTypeTraitExprClass: 1372 Bldr.takeNodes(Pred); 1373 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 1374 Pred, Dst); 1375 Bldr.addNodes(Dst); 1376 break; 1377 1378 case Stmt::StmtExprClass: { 1379 const StmtExpr *SE = cast<StmtExpr>(S); 1380 1381 if (SE->getSubStmt()->body_empty()) { 1382 // Empty statement expression. 1383 assert(SE->getType() == getContext().VoidTy 1384 && "Empty statement expression must have void type."); 1385 break; 1386 } 1387 1388 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 1389 ProgramStateRef state = Pred->getState(); 1390 Bldr.generateNode(SE, Pred, 1391 state->BindExpr(SE, Pred->getLocationContext(), 1392 state->getSVal(LastExpr, 1393 Pred->getLocationContext()))); 1394 } 1395 break; 1396 } 1397 1398 case Stmt::UnaryOperatorClass: { 1399 Bldr.takeNodes(Pred); 1400 const UnaryOperator *U = cast<UnaryOperator>(S); 1401 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) { 1402 ExplodedNodeSet Tmp; 1403 VisitUnaryOperator(U, Pred, Tmp); 1404 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U); 1405 } 1406 else 1407 VisitUnaryOperator(U, Pred, Dst); 1408 Bldr.addNodes(Dst); 1409 break; 1410 } 1411 1412 case Stmt::PseudoObjectExprClass: { 1413 Bldr.takeNodes(Pred); 1414 ProgramStateRef state = Pred->getState(); 1415 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S); 1416 if (const Expr *Result = PE->getResultExpr()) { 1417 SVal V = state->getSVal(Result, Pred->getLocationContext()); 1418 Bldr.generateNode(S, Pred, 1419 state->BindExpr(S, Pred->getLocationContext(), V)); 1420 } 1421 else 1422 Bldr.generateNode(S, Pred, 1423 state->BindExpr(S, Pred->getLocationContext(), 1424 UnknownVal())); 1425 1426 Bldr.addNodes(Dst); 1427 break; 1428 } 1429 } 1430 } 1431 1432 bool ExprEngine::replayWithoutInlining(ExplodedNode *N, 1433 const LocationContext *CalleeLC) { 1434 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1435 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame(); 1436 assert(CalleeSF && CallerSF); 1437 ExplodedNode *BeforeProcessingCall = nullptr; 1438 const Stmt *CE = CalleeSF->getCallSite(); 1439 1440 // Find the first node before we started processing the call expression. 1441 while (N) { 1442 ProgramPoint L = N->getLocation(); 1443 BeforeProcessingCall = N; 1444 N = N->pred_empty() ? nullptr : *(N->pred_begin()); 1445 1446 // Skip the nodes corresponding to the inlined code. 1447 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF) 1448 continue; 1449 // We reached the caller. Find the node right before we started 1450 // processing the call. 1451 if (L.isPurgeKind()) 1452 continue; 1453 if (L.getAs<PreImplicitCall>()) 1454 continue; 1455 if (L.getAs<CallEnter>()) 1456 continue; 1457 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>()) 1458 if (SP->getStmt() == CE) 1459 continue; 1460 break; 1461 } 1462 1463 if (!BeforeProcessingCall) 1464 return false; 1465 1466 // TODO: Clean up the unneeded nodes. 1467 1468 // Build an Epsilon node from which we will restart the analyzes. 1469 // Note that CE is permitted to be NULL! 1470 ProgramPoint NewNodeLoc = 1471 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE); 1472 // Add the special flag to GDM to signal retrying with no inlining. 1473 // Note, changing the state ensures that we are not going to cache out. 1474 ProgramStateRef NewNodeState = BeforeProcessingCall->getState(); 1475 NewNodeState = 1476 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE)); 1477 1478 // Make the new node a successor of BeforeProcessingCall. 1479 bool IsNew = false; 1480 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew); 1481 // We cached out at this point. Caching out is common due to us backtracking 1482 // from the inlined function, which might spawn several paths. 1483 if (!IsNew) 1484 return true; 1485 1486 NewNode->addPredecessor(BeforeProcessingCall, G); 1487 1488 // Add the new node to the work list. 1489 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(), 1490 CalleeSF->getIndex()); 1491 NumTimesRetriedWithoutInlining++; 1492 return true; 1493 } 1494 1495 /// Block entrance. (Update counters). 1496 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L, 1497 NodeBuilderWithSinks &nodeBuilder, 1498 ExplodedNode *Pred) { 1499 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1500 1501 // If this block is terminated by a loop and it has already been visited the 1502 // maximum number of times, widen the loop. 1503 unsigned int BlockCount = nodeBuilder.getContext().blockCount(); 1504 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 && 1505 AMgr.options.shouldWidenLoops()) { 1506 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator(); 1507 if (!(Term && 1508 (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term)))) 1509 return; 1510 // Widen. 1511 const LocationContext *LCtx = Pred->getLocationContext(); 1512 ProgramStateRef WidenedState = 1513 getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term); 1514 nodeBuilder.generateNode(WidenedState, Pred); 1515 return; 1516 } 1517 1518 // FIXME: Refactor this into a checker. 1519 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) { 1520 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded"); 1521 const ExplodedNode *Sink = 1522 nodeBuilder.generateSink(Pred->getState(), Pred, &tag); 1523 1524 // Check if we stopped at the top level function or not. 1525 // Root node should have the location context of the top most function. 1526 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext(); 1527 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1528 const LocationContext *RootLC = 1529 (*G.roots_begin())->getLocation().getLocationContext(); 1530 if (RootLC->getCurrentStackFrame() != CalleeSF) { 1531 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl()); 1532 1533 // Re-run the call evaluation without inlining it, by storing the 1534 // no-inlining policy in the state and enqueuing the new work item on 1535 // the list. Replay should almost never fail. Use the stats to catch it 1536 // if it does. 1537 if ((!AMgr.options.NoRetryExhausted && 1538 replayWithoutInlining(Pred, CalleeLC))) 1539 return; 1540 NumMaxBlockCountReachedInInlined++; 1541 } else 1542 NumMaxBlockCountReached++; 1543 1544 // Make sink nodes as exhausted(for stats) only if retry failed. 1545 Engine.blocksExhausted.push_back(std::make_pair(L, Sink)); 1546 } 1547 } 1548 1549 //===----------------------------------------------------------------------===// 1550 // Branch processing. 1551 //===----------------------------------------------------------------------===// 1552 1553 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used 1554 /// to try to recover some path-sensitivity for casts of symbolic 1555 /// integers that promote their values (which are currently not tracked well). 1556 /// This function returns the SVal bound to Condition->IgnoreCasts if all the 1557 // cast(s) did was sign-extend the original value. 1558 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr, 1559 ProgramStateRef state, 1560 const Stmt *Condition, 1561 const LocationContext *LCtx, 1562 ASTContext &Ctx) { 1563 1564 const Expr *Ex = dyn_cast<Expr>(Condition); 1565 if (!Ex) 1566 return UnknownVal(); 1567 1568 uint64_t bits = 0; 1569 bool bitsInit = false; 1570 1571 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 1572 QualType T = CE->getType(); 1573 1574 if (!T->isIntegralOrEnumerationType()) 1575 return UnknownVal(); 1576 1577 uint64_t newBits = Ctx.getTypeSize(T); 1578 if (!bitsInit || newBits < bits) { 1579 bitsInit = true; 1580 bits = newBits; 1581 } 1582 1583 Ex = CE->getSubExpr(); 1584 } 1585 1586 // We reached a non-cast. Is it a symbolic value? 1587 QualType T = Ex->getType(); 1588 1589 if (!bitsInit || !T->isIntegralOrEnumerationType() || 1590 Ctx.getTypeSize(T) > bits) 1591 return UnknownVal(); 1592 1593 return state->getSVal(Ex, LCtx); 1594 } 1595 1596 #ifndef NDEBUG 1597 static const Stmt *getRightmostLeaf(const Stmt *Condition) { 1598 while (Condition) { 1599 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition); 1600 if (!BO || !BO->isLogicalOp()) { 1601 return Condition; 1602 } 1603 Condition = BO->getRHS()->IgnoreParens(); 1604 } 1605 return nullptr; 1606 } 1607 #endif 1608 1609 // Returns the condition the branch at the end of 'B' depends on and whose value 1610 // has been evaluated within 'B'. 1611 // In most cases, the terminator condition of 'B' will be evaluated fully in 1612 // the last statement of 'B'; in those cases, the resolved condition is the 1613 // given 'Condition'. 1614 // If the condition of the branch is a logical binary operator tree, the CFG is 1615 // optimized: in that case, we know that the expression formed by all but the 1616 // rightmost leaf of the logical binary operator tree must be true, and thus 1617 // the branch condition is at this point equivalent to the truth value of that 1618 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf 1619 // expression in its final statement. As the full condition in that case was 1620 // not evaluated, and is thus not in the SVal cache, we need to use that leaf 1621 // expression to evaluate the truth value of the condition in the current state 1622 // space. 1623 static const Stmt *ResolveCondition(const Stmt *Condition, 1624 const CFGBlock *B) { 1625 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1626 Condition = Ex->IgnoreParens(); 1627 1628 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition); 1629 if (!BO || !BO->isLogicalOp()) 1630 return Condition; 1631 1632 assert(!B->getTerminator().isTemporaryDtorsBranch() && 1633 "Temporary destructor branches handled by processBindTemporary."); 1634 1635 // For logical operations, we still have the case where some branches 1636 // use the traditional "merge" approach and others sink the branch 1637 // directly into the basic blocks representing the logical operation. 1638 // We need to distinguish between those two cases here. 1639 1640 // The invariants are still shifting, but it is possible that the 1641 // last element in a CFGBlock is not a CFGStmt. Look for the last 1642 // CFGStmt as the value of the condition. 1643 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend(); 1644 for (; I != E; ++I) { 1645 CFGElement Elem = *I; 1646 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>(); 1647 if (!CS) 1648 continue; 1649 const Stmt *LastStmt = CS->getStmt(); 1650 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition)); 1651 return LastStmt; 1652 } 1653 llvm_unreachable("could not resolve condition"); 1654 } 1655 1656 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term, 1657 NodeBuilderContext& BldCtx, 1658 ExplodedNode *Pred, 1659 ExplodedNodeSet &Dst, 1660 const CFGBlock *DstT, 1661 const CFGBlock *DstF) { 1662 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) && 1663 "CXXBindTemporaryExprs are handled by processBindTemporary."); 1664 const LocationContext *LCtx = Pred->getLocationContext(); 1665 PrettyStackTraceLocationContext StackCrashInfo(LCtx); 1666 currBldrCtx = &BldCtx; 1667 1668 // Check for NULL conditions; e.g. "for(;;)" 1669 if (!Condition) { 1670 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF); 1671 NullCondBldr.markInfeasible(false); 1672 NullCondBldr.generateNode(Pred->getState(), true, Pred); 1673 return; 1674 } 1675 1676 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1677 Condition = Ex->IgnoreParens(); 1678 1679 Condition = ResolveCondition(Condition, BldCtx.getBlock()); 1680 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1681 Condition->getLocStart(), 1682 "Error evaluating branch"); 1683 1684 ExplodedNodeSet CheckersOutSet; 1685 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet, 1686 Pred, *this); 1687 // We generated only sinks. 1688 if (CheckersOutSet.empty()) 1689 return; 1690 1691 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF); 1692 for (NodeBuilder::iterator I = CheckersOutSet.begin(), 1693 E = CheckersOutSet.end(); E != I; ++I) { 1694 ExplodedNode *PredI = *I; 1695 1696 if (PredI->isSink()) 1697 continue; 1698 1699 ProgramStateRef PrevState = PredI->getState(); 1700 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext()); 1701 1702 if (X.isUnknownOrUndef()) { 1703 // Give it a chance to recover from unknown. 1704 if (const Expr *Ex = dyn_cast<Expr>(Condition)) { 1705 if (Ex->getType()->isIntegralOrEnumerationType()) { 1706 // Try to recover some path-sensitivity. Right now casts of symbolic 1707 // integers that promote their values are currently not tracked well. 1708 // If 'Condition' is such an expression, try and recover the 1709 // underlying value and use that instead. 1710 SVal recovered = RecoverCastedSymbol(getStateManager(), 1711 PrevState, Condition, 1712 PredI->getLocationContext(), 1713 getContext()); 1714 1715 if (!recovered.isUnknown()) { 1716 X = recovered; 1717 } 1718 } 1719 } 1720 } 1721 1722 // If the condition is still unknown, give up. 1723 if (X.isUnknownOrUndef()) { 1724 builder.generateNode(PrevState, true, PredI); 1725 builder.generateNode(PrevState, false, PredI); 1726 continue; 1727 } 1728 1729 DefinedSVal V = X.castAs<DefinedSVal>(); 1730 1731 ProgramStateRef StTrue, StFalse; 1732 std::tie(StTrue, StFalse) = PrevState->assume(V); 1733 1734 // Process the true branch. 1735 if (builder.isFeasible(true)) { 1736 if (StTrue) 1737 builder.generateNode(StTrue, true, PredI); 1738 else 1739 builder.markInfeasible(true); 1740 } 1741 1742 // Process the false branch. 1743 if (builder.isFeasible(false)) { 1744 if (StFalse) 1745 builder.generateNode(StFalse, false, PredI); 1746 else 1747 builder.markInfeasible(false); 1748 } 1749 } 1750 currBldrCtx = nullptr; 1751 } 1752 1753 /// The GDM component containing the set of global variables which have been 1754 /// previously initialized with explicit initializers. 1755 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet, 1756 llvm::ImmutableSet<const VarDecl *>) 1757 1758 void ExprEngine::processStaticInitializer(const DeclStmt *DS, 1759 NodeBuilderContext &BuilderCtx, 1760 ExplodedNode *Pred, 1761 clang::ento::ExplodedNodeSet &Dst, 1762 const CFGBlock *DstT, 1763 const CFGBlock *DstF) { 1764 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1765 currBldrCtx = &BuilderCtx; 1766 1767 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); 1768 ProgramStateRef state = Pred->getState(); 1769 bool initHasRun = state->contains<InitializedGlobalsSet>(VD); 1770 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF); 1771 1772 if (!initHasRun) { 1773 state = state->add<InitializedGlobalsSet>(VD); 1774 } 1775 1776 builder.generateNode(state, initHasRun, Pred); 1777 builder.markInfeasible(!initHasRun); 1778 1779 currBldrCtx = nullptr; 1780 } 1781 1782 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 1783 /// nodes by processing the 'effects' of a computed goto jump. 1784 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 1785 1786 ProgramStateRef state = builder.getState(); 1787 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext()); 1788 1789 // Three possibilities: 1790 // 1791 // (1) We know the computed label. 1792 // (2) The label is NULL (or some other constant), or Undefined. 1793 // (3) We have no clue about the label. Dispatch to all targets. 1794 // 1795 1796 typedef IndirectGotoNodeBuilder::iterator iterator; 1797 1798 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) { 1799 const LabelDecl *L = LV->getLabel(); 1800 1801 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { 1802 if (I.getLabel() == L) { 1803 builder.generateNode(I, state); 1804 return; 1805 } 1806 } 1807 1808 llvm_unreachable("No block with label."); 1809 } 1810 1811 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) { 1812 // Dispatch to the first target and mark it as a sink. 1813 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 1814 // FIXME: add checker visit. 1815 // UndefBranches.insert(N); 1816 return; 1817 } 1818 1819 // This is really a catch-all. We don't support symbolics yet. 1820 // FIXME: Implement dispatch for symbolic pointers. 1821 1822 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) 1823 builder.generateNode(I, state); 1824 } 1825 1826 #if 0 1827 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) { 1828 const StackFrameContext* Frame = Pred.getStackFrame(); 1829 const llvm::ImmutableSet<CXXBindTemporaryContext> &Set = 1830 Pred.getState()->get<InitializedTemporariesSet>(); 1831 return std::find_if(Set.begin(), Set.end(), 1832 [&](const CXXBindTemporaryContext &Ctx) { 1833 if (Ctx.second == Frame) { 1834 Ctx.first->dump(); 1835 llvm::errs() << "\n"; 1836 } 1837 return Ctx.second == Frame; 1838 }) == Set.end(); 1839 } 1840 #endif 1841 1842 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC, 1843 ExplodedNode *Pred, 1844 ExplodedNodeSet &Dst, 1845 const BlockEdge &L) { 1846 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC); 1847 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this); 1848 } 1849 1850 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 1851 /// nodes when the control reaches the end of a function. 1852 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC, 1853 ExplodedNode *Pred, 1854 const ReturnStmt *RS) { 1855 // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)). 1856 // We currently cannot enable this assert, as lifetime extended temporaries 1857 // are not modelled correctly. 1858 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1859 StateMgr.EndPath(Pred->getState()); 1860 1861 ExplodedNodeSet Dst; 1862 if (Pred->getLocationContext()->inTopFrame()) { 1863 // Remove dead symbols. 1864 ExplodedNodeSet AfterRemovedDead; 1865 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead); 1866 1867 // Notify checkers. 1868 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(), 1869 E = AfterRemovedDead.end(); I != E; ++I) { 1870 getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this); 1871 } 1872 } else { 1873 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this); 1874 } 1875 1876 Engine.enqueueEndOfFunction(Dst, RS); 1877 } 1878 1879 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 1880 /// nodes by processing the 'effects' of a switch statement. 1881 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 1882 typedef SwitchNodeBuilder::iterator iterator; 1883 ProgramStateRef state = builder.getState(); 1884 const Expr *CondE = builder.getCondition(); 1885 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext()); 1886 1887 if (CondV_untested.isUndef()) { 1888 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 1889 // FIXME: add checker 1890 //UndefBranches.insert(N); 1891 1892 return; 1893 } 1894 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>(); 1895 1896 ProgramStateRef DefaultSt = state; 1897 1898 iterator I = builder.begin(), EI = builder.end(); 1899 bool defaultIsFeasible = I == EI; 1900 1901 for ( ; I != EI; ++I) { 1902 // Successor may be pruned out during CFG construction. 1903 if (!I.getBlock()) 1904 continue; 1905 1906 const CaseStmt *Case = I.getCase(); 1907 1908 // Evaluate the LHS of the case value. 1909 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); 1910 assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType())); 1911 1912 // Get the RHS of the case, if it exists. 1913 llvm::APSInt V2; 1914 if (const Expr *E = Case->getRHS()) 1915 V2 = E->EvaluateKnownConstInt(getContext()); 1916 else 1917 V2 = V1; 1918 1919 ProgramStateRef StateCase; 1920 if (Optional<NonLoc> NL = CondV.getAs<NonLoc>()) 1921 std::tie(StateCase, DefaultSt) = 1922 DefaultSt->assumeInclusiveRange(*NL, V1, V2); 1923 else // UnknownVal 1924 StateCase = DefaultSt; 1925 1926 if (StateCase) 1927 builder.generateCaseStmtNode(I, StateCase); 1928 1929 // Now "assume" that the case doesn't match. Add this state 1930 // to the default state (if it is feasible). 1931 if (DefaultSt) 1932 defaultIsFeasible = true; 1933 else { 1934 defaultIsFeasible = false; 1935 break; 1936 } 1937 } 1938 1939 if (!defaultIsFeasible) 1940 return; 1941 1942 // If we have switch(enum value), the default branch is not 1943 // feasible if all of the enum constants not covered by 'case:' statements 1944 // are not feasible values for the switch condition. 1945 // 1946 // Note that this isn't as accurate as it could be. Even if there isn't 1947 // a case for a particular enum value as long as that enum value isn't 1948 // feasible then it shouldn't be considered for making 'default:' reachable. 1949 const SwitchStmt *SS = builder.getSwitch(); 1950 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 1951 if (CondExpr->getType()->getAs<EnumType>()) { 1952 if (SS->isAllEnumCasesCovered()) 1953 return; 1954 } 1955 1956 builder.generateDefaultCaseNode(DefaultSt); 1957 } 1958 1959 //===----------------------------------------------------------------------===// 1960 // Transfer functions: Loads and stores. 1961 //===----------------------------------------------------------------------===// 1962 1963 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 1964 ExplodedNode *Pred, 1965 ExplodedNodeSet &Dst) { 1966 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1967 1968 ProgramStateRef state = Pred->getState(); 1969 const LocationContext *LCtx = Pred->getLocationContext(); 1970 1971 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1972 // C permits "extern void v", and if you cast the address to a valid type, 1973 // you can even do things with it. We simply pretend 1974 assert(Ex->isGLValue() || VD->getType()->isVoidType()); 1975 const LocationContext *LocCtxt = Pred->getLocationContext(); 1976 const Decl *D = LocCtxt->getDecl(); 1977 const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr; 1978 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex); 1979 SVal V; 1980 bool IsReference; 1981 if (AMgr.options.shouldInlineLambdas() && DeclRefEx && 1982 DeclRefEx->refersToEnclosingVariableOrCapture() && MD && 1983 MD->getParent()->isLambda()) { 1984 // Lookup the field of the lambda. 1985 const CXXRecordDecl *CXXRec = MD->getParent(); 1986 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 1987 FieldDecl *LambdaThisCaptureField; 1988 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField); 1989 const FieldDecl *FD = LambdaCaptureFields[VD]; 1990 if (!FD) { 1991 // When a constant is captured, sometimes no corresponding field is 1992 // created in the lambda object. 1993 assert(VD->getType().isConstQualified()); 1994 V = state->getLValue(VD, LocCtxt); 1995 IsReference = false; 1996 } else { 1997 Loc CXXThis = 1998 svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame()); 1999 SVal CXXThisVal = state->getSVal(CXXThis); 2000 V = state->getLValue(FD, CXXThisVal); 2001 IsReference = FD->getType()->isReferenceType(); 2002 } 2003 } else { 2004 V = state->getLValue(VD, LocCtxt); 2005 IsReference = VD->getType()->isReferenceType(); 2006 } 2007 2008 // For references, the 'lvalue' is the pointer address stored in the 2009 // reference region. 2010 if (IsReference) { 2011 if (const MemRegion *R = V.getAsRegion()) 2012 V = state->getSVal(R); 2013 else 2014 V = UnknownVal(); 2015 } 2016 2017 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 2018 ProgramPoint::PostLValueKind); 2019 return; 2020 } 2021 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 2022 assert(!Ex->isGLValue()); 2023 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 2024 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V)); 2025 return; 2026 } 2027 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2028 SVal V = svalBuilder.getFunctionPointer(FD); 2029 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 2030 ProgramPoint::PostLValueKind); 2031 return; 2032 } 2033 if (isa<FieldDecl>(D)) { 2034 // FIXME: Compute lvalue of field pointers-to-member. 2035 // Right now we just use a non-null void pointer, so that it gives proper 2036 // results in boolean contexts. 2037 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy, 2038 currBldrCtx->blockCount()); 2039 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true); 2040 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 2041 ProgramPoint::PostLValueKind); 2042 return; 2043 } 2044 2045 llvm_unreachable("Support for this Decl not implemented."); 2046 } 2047 2048 /// VisitArraySubscriptExpr - Transfer function for array accesses 2049 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A, 2050 ExplodedNode *Pred, 2051 ExplodedNodeSet &Dst){ 2052 2053 const Expr *Base = A->getBase()->IgnoreParens(); 2054 const Expr *Idx = A->getIdx()->IgnoreParens(); 2055 2056 ExplodedNodeSet CheckerPreStmt; 2057 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this); 2058 2059 ExplodedNodeSet EvalSet; 2060 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx); 2061 assert(A->isGLValue() || 2062 (!AMgr.getLangOpts().CPlusPlus && 2063 A->getType().isCForbiddenLValueType())); 2064 2065 for (auto *Node : CheckerPreStmt) { 2066 const LocationContext *LCtx = Node->getLocationContext(); 2067 ProgramStateRef state = Node->getState(); 2068 SVal V = state->getLValue(A->getType(), 2069 state->getSVal(Idx, LCtx), 2070 state->getSVal(Base, LCtx)); 2071 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr, 2072 ProgramPoint::PostLValueKind); 2073 } 2074 2075 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this); 2076 } 2077 2078 /// VisitMemberExpr - Transfer function for member expressions. 2079 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 2080 ExplodedNodeSet &Dst) { 2081 2082 // FIXME: Prechecks eventually go in ::Visit(). 2083 ExplodedNodeSet CheckedSet; 2084 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this); 2085 2086 ExplodedNodeSet EvalSet; 2087 ValueDecl *Member = M->getMemberDecl(); 2088 2089 // Handle static member variables and enum constants accessed via 2090 // member syntax. 2091 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) { 2092 ExplodedNodeSet Dst; 2093 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2094 I != E; ++I) { 2095 VisitCommonDeclRefExpr(M, Member, Pred, EvalSet); 2096 } 2097 } else { 2098 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx); 2099 ExplodedNodeSet Tmp; 2100 2101 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2102 I != E; ++I) { 2103 ProgramStateRef state = (*I)->getState(); 2104 const LocationContext *LCtx = (*I)->getLocationContext(); 2105 Expr *BaseExpr = M->getBase(); 2106 2107 // Handle C++ method calls. 2108 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) { 2109 if (MD->isInstance()) 2110 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 2111 2112 SVal MDVal = svalBuilder.getFunctionPointer(MD); 2113 state = state->BindExpr(M, LCtx, MDVal); 2114 2115 Bldr.generateNode(M, *I, state); 2116 continue; 2117 } 2118 2119 // Handle regular struct fields / member variables. 2120 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 2121 SVal baseExprVal = state->getSVal(BaseExpr, LCtx); 2122 2123 FieldDecl *field = cast<FieldDecl>(Member); 2124 SVal L = state->getLValue(field, baseExprVal); 2125 2126 if (M->isGLValue() || M->getType()->isArrayType()) { 2127 // We special-case rvalues of array type because the analyzer cannot 2128 // reason about them, since we expect all regions to be wrapped in Locs. 2129 // We instead treat these as lvalues and assume that they will decay to 2130 // pointers as soon as they are used. 2131 if (!M->isGLValue()) { 2132 assert(M->getType()->isArrayType()); 2133 const ImplicitCastExpr *PE = 2134 dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParentIgnoreParens(M)); 2135 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) { 2136 llvm_unreachable("should always be wrapped in ArrayToPointerDecay"); 2137 } 2138 } 2139 2140 if (field->getType()->isReferenceType()) { 2141 if (const MemRegion *R = L.getAsRegion()) 2142 L = state->getSVal(R); 2143 else 2144 L = UnknownVal(); 2145 } 2146 2147 Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr, 2148 ProgramPoint::PostLValueKind); 2149 } else { 2150 Bldr.takeNodes(*I); 2151 evalLoad(Tmp, M, M, *I, state, L); 2152 Bldr.addNodes(Tmp); 2153 } 2154 } 2155 } 2156 2157 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this); 2158 } 2159 2160 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred, 2161 ExplodedNodeSet &Dst) { 2162 ExplodedNodeSet AfterPreSet; 2163 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this); 2164 2165 // For now, treat all the arguments to C11 atomics as escaping. 2166 // FIXME: Ideally we should model the behavior of the atomics precisely here. 2167 2168 ExplodedNodeSet AfterInvalidateSet; 2169 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx); 2170 2171 for (ExplodedNodeSet::iterator I = AfterPreSet.begin(), E = AfterPreSet.end(); 2172 I != E; ++I) { 2173 ProgramStateRef State = (*I)->getState(); 2174 const LocationContext *LCtx = (*I)->getLocationContext(); 2175 2176 SmallVector<SVal, 8> ValuesToInvalidate; 2177 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) { 2178 const Expr *SubExpr = AE->getSubExprs()[SI]; 2179 SVal SubExprVal = State->getSVal(SubExpr, LCtx); 2180 ValuesToInvalidate.push_back(SubExprVal); 2181 } 2182 2183 State = State->invalidateRegions(ValuesToInvalidate, AE, 2184 currBldrCtx->blockCount(), 2185 LCtx, 2186 /*CausedByPointerEscape*/true, 2187 /*Symbols=*/nullptr); 2188 2189 SVal ResultVal = UnknownVal(); 2190 State = State->BindExpr(AE, LCtx, ResultVal); 2191 Bldr.generateNode(AE, *I, State, nullptr, 2192 ProgramPoint::PostStmtKind); 2193 } 2194 2195 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this); 2196 } 2197 2198 namespace { 2199 class CollectReachableSymbolsCallback final : public SymbolVisitor { 2200 InvalidatedSymbols Symbols; 2201 2202 public: 2203 CollectReachableSymbolsCallback(ProgramStateRef State) {} 2204 const InvalidatedSymbols &getSymbols() const { return Symbols; } 2205 2206 bool VisitSymbol(SymbolRef Sym) override { 2207 Symbols.insert(Sym); 2208 return true; 2209 } 2210 }; 2211 } // end anonymous namespace 2212 2213 // A value escapes in three possible cases: 2214 // (1) We are binding to something that is not a memory region. 2215 // (2) We are binding to a MemrRegion that does not have stack storage. 2216 // (3) We are binding to a MemRegion with stack storage that the store 2217 // does not understand. 2218 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, 2219 SVal Loc, 2220 SVal Val, 2221 const LocationContext *LCtx) { 2222 // Are we storing to something that causes the value to "escape"? 2223 bool escapes = true; 2224 2225 // TODO: Move to StoreManager. 2226 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) { 2227 escapes = !regionLoc->getRegion()->hasStackStorage(); 2228 2229 if (!escapes) { 2230 // To test (3), generate a new state with the binding added. If it is 2231 // the same state, then it escapes (since the store cannot represent 2232 // the binding). 2233 // Do this only if we know that the store is not supposed to generate the 2234 // same state. 2235 SVal StoredVal = State->getSVal(regionLoc->getRegion()); 2236 if (StoredVal != Val) 2237 escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx))); 2238 } 2239 } 2240 2241 // If our store can represent the binding and we aren't storing to something 2242 // that doesn't have local storage then just return and have the simulation 2243 // state continue as is. 2244 if (!escapes) 2245 return State; 2246 2247 // Otherwise, find all symbols referenced by 'val' that we are tracking 2248 // and stop tracking them. 2249 CollectReachableSymbolsCallback Scanner = 2250 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val); 2251 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols(); 2252 State = getCheckerManager().runCheckersForPointerEscape(State, 2253 EscapedSymbols, 2254 /*CallEvent*/ nullptr, 2255 PSK_EscapeOnBind, 2256 nullptr); 2257 2258 return State; 2259 } 2260 2261 ProgramStateRef 2262 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State, 2263 const InvalidatedSymbols *Invalidated, 2264 ArrayRef<const MemRegion *> ExplicitRegions, 2265 ArrayRef<const MemRegion *> Regions, 2266 const CallEvent *Call, 2267 RegionAndSymbolInvalidationTraits &ITraits) { 2268 2269 if (!Invalidated || Invalidated->empty()) 2270 return State; 2271 2272 if (!Call) 2273 return getCheckerManager().runCheckersForPointerEscape(State, 2274 *Invalidated, 2275 nullptr, 2276 PSK_EscapeOther, 2277 &ITraits); 2278 2279 // If the symbols were invalidated by a call, we want to find out which ones 2280 // were invalidated directly due to being arguments to the call. 2281 InvalidatedSymbols SymbolsDirectlyInvalidated; 2282 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), 2283 E = ExplicitRegions.end(); I != E; ++I) { 2284 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>()) 2285 SymbolsDirectlyInvalidated.insert(R->getSymbol()); 2286 } 2287 2288 InvalidatedSymbols SymbolsIndirectlyInvalidated; 2289 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(), 2290 E = Invalidated->end(); I!=E; ++I) { 2291 SymbolRef sym = *I; 2292 if (SymbolsDirectlyInvalidated.count(sym)) 2293 continue; 2294 SymbolsIndirectlyInvalidated.insert(sym); 2295 } 2296 2297 if (!SymbolsDirectlyInvalidated.empty()) 2298 State = getCheckerManager().runCheckersForPointerEscape(State, 2299 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits); 2300 2301 // Notify about the symbols that get indirectly invalidated by the call. 2302 if (!SymbolsIndirectlyInvalidated.empty()) 2303 State = getCheckerManager().runCheckersForPointerEscape(State, 2304 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits); 2305 2306 return State; 2307 } 2308 2309 /// evalBind - Handle the semantics of binding a value to a specific location. 2310 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 2311 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, 2312 ExplodedNode *Pred, 2313 SVal location, SVal Val, 2314 bool atDeclInit, const ProgramPoint *PP) { 2315 2316 const LocationContext *LC = Pred->getLocationContext(); 2317 PostStmt PS(StoreE, LC); 2318 if (!PP) 2319 PP = &PS; 2320 2321 // Do a previsit of the bind. 2322 ExplodedNodeSet CheckedSet; 2323 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val, 2324 StoreE, *this, *PP); 2325 2326 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx); 2327 2328 // If the location is not a 'Loc', it will already be handled by 2329 // the checkers. There is nothing left to do. 2330 if (!location.getAs<Loc>()) { 2331 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr, 2332 /*tag*/nullptr); 2333 ProgramStateRef state = Pred->getState(); 2334 state = processPointerEscapedOnBind(state, location, Val, LC); 2335 Bldr.generateNode(L, state, Pred); 2336 return; 2337 } 2338 2339 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2340 I!=E; ++I) { 2341 ExplodedNode *PredI = *I; 2342 ProgramStateRef state = PredI->getState(); 2343 2344 state = processPointerEscapedOnBind(state, location, Val, LC); 2345 2346 // When binding the value, pass on the hint that this is a initialization. 2347 // For initializations, we do not need to inform clients of region 2348 // changes. 2349 state = state->bindLoc(location.castAs<Loc>(), 2350 Val, LC, /* notifyChanges = */ !atDeclInit); 2351 2352 const MemRegion *LocReg = nullptr; 2353 if (Optional<loc::MemRegionVal> LocRegVal = 2354 location.getAs<loc::MemRegionVal>()) { 2355 LocReg = LocRegVal->getRegion(); 2356 } 2357 2358 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr); 2359 Bldr.generateNode(L, state, PredI); 2360 } 2361 } 2362 2363 /// evalStore - Handle the semantics of a store via an assignment. 2364 /// @param Dst The node set to store generated state nodes 2365 /// @param AssignE The assignment expression if the store happens in an 2366 /// assignment. 2367 /// @param LocationE The location expression that is stored to. 2368 /// @param state The current simulation state 2369 /// @param location The location to store the value 2370 /// @param Val The value to be stored 2371 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, 2372 const Expr *LocationE, 2373 ExplodedNode *Pred, 2374 ProgramStateRef state, SVal location, SVal Val, 2375 const ProgramPointTag *tag) { 2376 // Proceed with the store. We use AssignE as the anchor for the PostStore 2377 // ProgramPoint if it is non-NULL, and LocationE otherwise. 2378 const Expr *StoreE = AssignE ? AssignE : LocationE; 2379 2380 // Evaluate the location (checks for bad dereferences). 2381 ExplodedNodeSet Tmp; 2382 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false); 2383 2384 if (Tmp.empty()) 2385 return; 2386 2387 if (location.isUndef()) 2388 return; 2389 2390 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 2391 evalBind(Dst, StoreE, *NI, location, Val, false); 2392 } 2393 2394 void ExprEngine::evalLoad(ExplodedNodeSet &Dst, 2395 const Expr *NodeEx, 2396 const Expr *BoundEx, 2397 ExplodedNode *Pred, 2398 ProgramStateRef state, 2399 SVal location, 2400 const ProgramPointTag *tag, 2401 QualType LoadTy) 2402 { 2403 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc."); 2404 2405 // Are we loading from a region? This actually results in two loads; one 2406 // to fetch the address of the referenced value and one to fetch the 2407 // referenced value. 2408 if (const TypedValueRegion *TR = 2409 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) { 2410 2411 QualType ValTy = TR->getValueType(); 2412 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) { 2413 static SimpleProgramPointTag 2414 loadReferenceTag(TagProviderName, "Load Reference"); 2415 ExplodedNodeSet Tmp; 2416 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state, 2417 location, &loadReferenceTag, 2418 getContext().getPointerType(RT->getPointeeType())); 2419 2420 // Perform the load from the referenced value. 2421 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) { 2422 state = (*I)->getState(); 2423 location = state->getSVal(BoundEx, (*I)->getLocationContext()); 2424 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy); 2425 } 2426 return; 2427 } 2428 } 2429 2430 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy); 2431 } 2432 2433 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst, 2434 const Expr *NodeEx, 2435 const Expr *BoundEx, 2436 ExplodedNode *Pred, 2437 ProgramStateRef state, 2438 SVal location, 2439 const ProgramPointTag *tag, 2440 QualType LoadTy) { 2441 assert(NodeEx); 2442 assert(BoundEx); 2443 // Evaluate the location (checks for bad dereferences). 2444 ExplodedNodeSet Tmp; 2445 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true); 2446 if (Tmp.empty()) 2447 return; 2448 2449 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 2450 if (location.isUndef()) 2451 return; 2452 2453 // Proceed with the load. 2454 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 2455 state = (*NI)->getState(); 2456 const LocationContext *LCtx = (*NI)->getLocationContext(); 2457 2458 SVal V = UnknownVal(); 2459 if (location.isValid()) { 2460 if (LoadTy.isNull()) 2461 LoadTy = BoundEx->getType(); 2462 V = state->getSVal(location.castAs<Loc>(), LoadTy); 2463 } 2464 2465 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag, 2466 ProgramPoint::PostLoadKind); 2467 } 2468 } 2469 2470 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, 2471 const Stmt *NodeEx, 2472 const Stmt *BoundEx, 2473 ExplodedNode *Pred, 2474 ProgramStateRef state, 2475 SVal location, 2476 const ProgramPointTag *tag, 2477 bool isLoad) { 2478 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx); 2479 // Early checks for performance reason. 2480 if (location.isUnknown()) { 2481 return; 2482 } 2483 2484 ExplodedNodeSet Src; 2485 BldrTop.takeNodes(Pred); 2486 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx); 2487 if (Pred->getState() != state) { 2488 // Associate this new state with an ExplodedNode. 2489 // FIXME: If I pass null tag, the graph is incorrect, e.g for 2490 // int *p; 2491 // p = 0; 2492 // *p = 0xDEADBEEF; 2493 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 2494 // instead "int *p" is noted as 2495 // "Variable 'p' initialized to a null pointer value" 2496 2497 static SimpleProgramPointTag tag(TagProviderName, "Location"); 2498 Bldr.generateNode(NodeEx, Pred, state, &tag); 2499 } 2500 ExplodedNodeSet Tmp; 2501 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, 2502 NodeEx, BoundEx, *this); 2503 BldrTop.addNodes(Tmp); 2504 } 2505 2506 std::pair<const ProgramPointTag *, const ProgramPointTag*> 2507 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() { 2508 static SimpleProgramPointTag 2509 eagerlyAssumeBinOpBifurcationTrue(TagProviderName, 2510 "Eagerly Assume True"), 2511 eagerlyAssumeBinOpBifurcationFalse(TagProviderName, 2512 "Eagerly Assume False"); 2513 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue, 2514 &eagerlyAssumeBinOpBifurcationFalse); 2515 } 2516 2517 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, 2518 ExplodedNodeSet &Src, 2519 const Expr *Ex) { 2520 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx); 2521 2522 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { 2523 ExplodedNode *Pred = *I; 2524 // Test if the previous node was as the same expression. This can happen 2525 // when the expression fails to evaluate to anything meaningful and 2526 // (as an optimization) we don't generate a node. 2527 ProgramPoint P = Pred->getLocation(); 2528 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) { 2529 continue; 2530 } 2531 2532 ProgramStateRef state = Pred->getState(); 2533 SVal V = state->getSVal(Ex, Pred->getLocationContext()); 2534 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>(); 2535 if (SEV && SEV->isExpression()) { 2536 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = 2537 geteagerlyAssumeBinOpBifurcationTags(); 2538 2539 ProgramStateRef StateTrue, StateFalse; 2540 std::tie(StateTrue, StateFalse) = state->assume(*SEV); 2541 2542 // First assume that the condition is true. 2543 if (StateTrue) { 2544 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType()); 2545 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val); 2546 Bldr.generateNode(Ex, Pred, StateTrue, tags.first); 2547 } 2548 2549 // Next, assume that the condition is false. 2550 if (StateFalse) { 2551 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType()); 2552 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val); 2553 Bldr.generateNode(Ex, Pred, StateFalse, tags.second); 2554 } 2555 } 2556 } 2557 } 2558 2559 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 2560 ExplodedNodeSet &Dst) { 2561 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2562 // We have processed both the inputs and the outputs. All of the outputs 2563 // should evaluate to Locs. Nuke all of their values. 2564 2565 // FIXME: Some day in the future it would be nice to allow a "plug-in" 2566 // which interprets the inline asm and stores proper results in the 2567 // outputs. 2568 2569 ProgramStateRef state = Pred->getState(); 2570 2571 for (const Expr *O : A->outputs()) { 2572 SVal X = state->getSVal(O, Pred->getLocationContext()); 2573 assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef. 2574 2575 if (Optional<Loc> LV = X.getAs<Loc>()) 2576 state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext()); 2577 } 2578 2579 Bldr.generateNode(A, Pred, state); 2580 } 2581 2582 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 2583 ExplodedNodeSet &Dst) { 2584 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2585 Bldr.generateNode(A, Pred, Pred->getState()); 2586 } 2587 2588 //===----------------------------------------------------------------------===// 2589 // Visualization. 2590 //===----------------------------------------------------------------------===// 2591 2592 #ifndef NDEBUG 2593 static ExprEngine* GraphPrintCheckerState; 2594 static SourceManager* GraphPrintSourceManager; 2595 2596 namespace llvm { 2597 template<> 2598 struct DOTGraphTraits<ExplodedNode*> : 2599 public DefaultDOTGraphTraits { 2600 2601 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 2602 2603 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not 2604 // work. 2605 static std::string getNodeAttributes(const ExplodedNode *N, void*) { 2606 return ""; 2607 } 2608 2609 // De-duplicate some source location pretty-printing. 2610 static void printLocation(raw_ostream &Out, SourceLocation SLoc) { 2611 if (SLoc.isFileID()) { 2612 Out << "\\lline=" 2613 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2614 << " col=" 2615 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc) 2616 << "\\l"; 2617 } 2618 } 2619 static void printLocation2(raw_ostream &Out, SourceLocation SLoc) { 2620 if (SLoc.isFileID() && GraphPrintSourceManager->isInMainFile(SLoc)) 2621 Out << "line " << GraphPrintSourceManager->getExpansionLineNumber(SLoc); 2622 else 2623 SLoc.print(Out, *GraphPrintSourceManager); 2624 } 2625 2626 static std::string getNodeLabel(const ExplodedNode *N, void*){ 2627 2628 std::string sbuf; 2629 llvm::raw_string_ostream Out(sbuf); 2630 2631 // Program Location. 2632 ProgramPoint Loc = N->getLocation(); 2633 2634 switch (Loc.getKind()) { 2635 case ProgramPoint::BlockEntranceKind: { 2636 Out << "Block Entrance: B" 2637 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID(); 2638 break; 2639 } 2640 2641 case ProgramPoint::BlockExitKind: 2642 assert (false); 2643 break; 2644 2645 case ProgramPoint::CallEnterKind: 2646 Out << "CallEnter"; 2647 break; 2648 2649 case ProgramPoint::CallExitBeginKind: 2650 Out << "CallExitBegin"; 2651 break; 2652 2653 case ProgramPoint::CallExitEndKind: 2654 Out << "CallExitEnd"; 2655 break; 2656 2657 case ProgramPoint::PostStmtPurgeDeadSymbolsKind: 2658 Out << "PostStmtPurgeDeadSymbols"; 2659 break; 2660 2661 case ProgramPoint::PreStmtPurgeDeadSymbolsKind: 2662 Out << "PreStmtPurgeDeadSymbols"; 2663 break; 2664 2665 case ProgramPoint::EpsilonKind: 2666 Out << "Epsilon Point"; 2667 break; 2668 2669 case ProgramPoint::PreImplicitCallKind: { 2670 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>(); 2671 Out << "PreCall: "; 2672 2673 // FIXME: Get proper printing options. 2674 PC.getDecl()->print(Out, LangOptions()); 2675 printLocation(Out, PC.getLocation()); 2676 break; 2677 } 2678 2679 case ProgramPoint::PostImplicitCallKind: { 2680 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>(); 2681 Out << "PostCall: "; 2682 2683 // FIXME: Get proper printing options. 2684 PC.getDecl()->print(Out, LangOptions()); 2685 printLocation(Out, PC.getLocation()); 2686 break; 2687 } 2688 2689 case ProgramPoint::PostInitializerKind: { 2690 Out << "PostInitializer: "; 2691 const CXXCtorInitializer *Init = 2692 Loc.castAs<PostInitializer>().getInitializer(); 2693 if (const FieldDecl *FD = Init->getAnyMember()) 2694 Out << *FD; 2695 else { 2696 QualType Ty = Init->getTypeSourceInfo()->getType(); 2697 Ty = Ty.getLocalUnqualifiedType(); 2698 LangOptions LO; // FIXME. 2699 Ty.print(Out, LO); 2700 } 2701 break; 2702 } 2703 2704 case ProgramPoint::BlockEdgeKind: { 2705 const BlockEdge &E = Loc.castAs<BlockEdge>(); 2706 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" 2707 << E.getDst()->getBlockID() << ')'; 2708 2709 if (const Stmt *T = E.getSrc()->getTerminator()) { 2710 SourceLocation SLoc = T->getLocStart(); 2711 2712 Out << "\\|Terminator: "; 2713 LangOptions LO; // FIXME. 2714 E.getSrc()->printTerminator(Out, LO); 2715 2716 if (SLoc.isFileID()) { 2717 Out << "\\lline=" 2718 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2719 << " col=" 2720 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc); 2721 } 2722 2723 if (isa<SwitchStmt>(T)) { 2724 const Stmt *Label = E.getDst()->getLabel(); 2725 2726 if (Label) { 2727 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 2728 Out << "\\lcase "; 2729 LangOptions LO; // FIXME. 2730 if (C->getLHS()) 2731 C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO)); 2732 2733 if (const Stmt *RHS = C->getRHS()) { 2734 Out << " .. "; 2735 RHS->printPretty(Out, nullptr, PrintingPolicy(LO)); 2736 } 2737 2738 Out << ":"; 2739 } 2740 else { 2741 assert (isa<DefaultStmt>(Label)); 2742 Out << "\\ldefault:"; 2743 } 2744 } 2745 else 2746 Out << "\\l(implicit) default:"; 2747 } 2748 else if (isa<IndirectGotoStmt>(T)) { 2749 // FIXME 2750 } 2751 else { 2752 Out << "\\lCondition: "; 2753 if (*E.getSrc()->succ_begin() == E.getDst()) 2754 Out << "true"; 2755 else 2756 Out << "false"; 2757 } 2758 2759 Out << "\\l"; 2760 } 2761 2762 break; 2763 } 2764 2765 default: { 2766 const Stmt *S = Loc.castAs<StmtPoint>().getStmt(); 2767 assert(S != nullptr && "Expecting non-null Stmt"); 2768 2769 Out << S->getStmtClassName() << ' ' << (const void*) S << ' '; 2770 LangOptions LO; // FIXME. 2771 S->printPretty(Out, nullptr, PrintingPolicy(LO)); 2772 printLocation(Out, S->getLocStart()); 2773 2774 if (Loc.getAs<PreStmt>()) 2775 Out << "\\lPreStmt\\l;"; 2776 else if (Loc.getAs<PostLoad>()) 2777 Out << "\\lPostLoad\\l;"; 2778 else if (Loc.getAs<PostStore>()) 2779 Out << "\\lPostStore\\l"; 2780 else if (Loc.getAs<PostLValue>()) 2781 Out << "\\lPostLValue\\l"; 2782 2783 break; 2784 } 2785 } 2786 2787 ProgramStateRef state = N->getState(); 2788 Out << "\\|StateID: " << (const void*) state.get() 2789 << " NodeID: " << (const void*) N << "\\|"; 2790 2791 // Analysis stack backtrace. 2792 Out << "Location context stack (from current to outer):\\l"; 2793 const LocationContext *LC = Loc.getLocationContext(); 2794 unsigned Idx = 0; 2795 for (; LC; LC = LC->getParent(), ++Idx) { 2796 Out << Idx << ". (" << (const void *)LC << ") "; 2797 switch (LC->getKind()) { 2798 case LocationContext::StackFrame: 2799 if (const NamedDecl *D = dyn_cast<NamedDecl>(LC->getDecl())) 2800 Out << "Calling " << D->getQualifiedNameAsString(); 2801 else 2802 Out << "Calling anonymous code"; 2803 if (const Stmt *S = cast<StackFrameContext>(LC)->getCallSite()) { 2804 Out << " at "; 2805 printLocation2(Out, S->getLocStart()); 2806 } 2807 break; 2808 case LocationContext::Block: 2809 Out << "Invoking block"; 2810 if (const Decl *D = cast<BlockInvocationContext>(LC)->getBlockDecl()) { 2811 Out << " defined at "; 2812 printLocation2(Out, D->getLocStart()); 2813 } 2814 break; 2815 case LocationContext::Scope: 2816 Out << "Entering scope"; 2817 // FIXME: Add more info once ScopeContext is activated. 2818 break; 2819 } 2820 Out << "\\l"; 2821 } 2822 Out << "\\l"; 2823 2824 state->printDOT(Out); 2825 2826 Out << "\\l"; 2827 2828 if (const ProgramPointTag *tag = Loc.getTag()) { 2829 Out << "\\|Tag: " << tag->getTagDescription(); 2830 Out << "\\l"; 2831 } 2832 return Out.str(); 2833 } 2834 }; 2835 } // end llvm namespace 2836 #endif 2837 2838 void ExprEngine::ViewGraph(bool trim) { 2839 #ifndef NDEBUG 2840 if (trim) { 2841 std::vector<const ExplodedNode*> Src; 2842 2843 // Flush any outstanding reports to make sure we cover all the nodes. 2844 // This does not cause them to get displayed. 2845 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) 2846 const_cast<BugType*>(*I)->FlushReports(BR); 2847 2848 // Iterate through the reports and get their nodes. 2849 for (BugReporter::EQClasses_iterator 2850 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 2851 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode()); 2852 if (N) Src.push_back(N); 2853 } 2854 2855 ViewGraph(Src); 2856 } 2857 else { 2858 GraphPrintCheckerState = this; 2859 GraphPrintSourceManager = &getContext().getSourceManager(); 2860 2861 llvm::ViewGraph(*G.roots_begin(), "ExprEngine"); 2862 2863 GraphPrintCheckerState = nullptr; 2864 GraphPrintSourceManager = nullptr; 2865 } 2866 #endif 2867 } 2868 2869 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) { 2870 #ifndef NDEBUG 2871 GraphPrintCheckerState = this; 2872 GraphPrintSourceManager = &getContext().getSourceManager(); 2873 2874 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes)); 2875 2876 if (!TrimmedG.get()) 2877 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 2878 else 2879 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine"); 2880 2881 GraphPrintCheckerState = nullptr; 2882 GraphPrintSourceManager = nullptr; 2883 #endif 2884 } 2885