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