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/CheckerManager.h" 17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 18 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 19 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 20 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h" 21 #include "clang/AST/CharUnits.h" 22 #include "clang/AST/ParentMap.h" 23 #include "clang/AST/StmtObjC.h" 24 #include "clang/AST/DeclCXX.h" 25 #include "clang/Basic/Builtins.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/PrettyStackTrace.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include "llvm/ADT/ImmutableList.h" 30 31 #ifndef NDEBUG 32 #include "llvm/Support/GraphWriter.h" 33 #endif 34 35 using namespace clang; 36 using namespace ento; 37 using llvm::APSInt; 38 39 //===----------------------------------------------------------------------===// 40 // Utility functions. 41 //===----------------------------------------------------------------------===// 42 43 static inline Selector GetNullarySelector(const char* name, ASTContext &Ctx) { 44 IdentifierInfo* II = &Ctx.Idents.get(name); 45 return Ctx.Selectors.getSelector(0, &II); 46 } 47 48 //===----------------------------------------------------------------------===// 49 // Engine construction and deletion. 50 //===----------------------------------------------------------------------===// 51 52 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled) 53 : AMgr(mgr), 54 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()), 55 Engine(*this), 56 G(Engine.getGraph()), 57 StateMgr(getContext(), mgr.getStoreManagerCreator(), 58 mgr.getConstraintManagerCreator(), G.getAllocator(), 59 *this), 60 SymMgr(StateMgr.getSymbolManager()), 61 svalBuilder(StateMgr.getSValBuilder()), 62 EntryNode(NULL), 63 currentStmt(NULL), currentStmtIdx(0), currentBuilderContext(0), 64 NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL), 65 RaiseSel(GetNullarySelector("raise", getContext())), 66 ObjCGCEnabled(gcEnabled), BR(mgr, *this) { 67 68 if (mgr.shouldEagerlyTrimExplodedGraph()) { 69 // Enable eager node reclaimation when constructing the ExplodedGraph. 70 G.enableNodeReclamation(); 71 } 72 } 73 74 ExprEngine::~ExprEngine() { 75 BR.FlushReports(); 76 delete [] NSExceptionInstanceRaiseSelectors; 77 } 78 79 //===----------------------------------------------------------------------===// 80 // Utility methods. 81 //===----------------------------------------------------------------------===// 82 83 const ProgramState *ExprEngine::getInitialState(const LocationContext *InitLoc) { 84 const ProgramState *state = StateMgr.getInitialState(InitLoc); 85 const Decl *D = InitLoc->getDecl(); 86 87 // Preconditions. 88 // FIXME: It would be nice if we had a more general mechanism to add 89 // such preconditions. Some day. 90 do { 91 92 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 93 // Precondition: the first argument of 'main' is an integer guaranteed 94 // to be > 0. 95 const IdentifierInfo *II = FD->getIdentifier(); 96 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0)) 97 break; 98 99 const ParmVarDecl *PD = FD->getParamDecl(0); 100 QualType T = PD->getType(); 101 if (!T->isIntegerType()) 102 break; 103 104 const MemRegion *R = state->getRegion(PD, InitLoc); 105 if (!R) 106 break; 107 108 SVal V = state->getSVal(loc::MemRegionVal(R)); 109 SVal Constraint_untested = evalBinOp(state, BO_GT, V, 110 svalBuilder.makeZeroVal(T), 111 getContext().IntTy); 112 113 DefinedOrUnknownSVal *Constraint = 114 dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested); 115 116 if (!Constraint) 117 break; 118 119 if (const ProgramState *newState = state->assume(*Constraint, true)) 120 state = newState; 121 } 122 break; 123 } 124 while (0); 125 126 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 127 // Precondition: 'self' is always non-null upon entry to an Objective-C 128 // method. 129 const ImplicitParamDecl *SelfD = MD->getSelfDecl(); 130 const MemRegion *R = state->getRegion(SelfD, InitLoc); 131 SVal V = state->getSVal(loc::MemRegionVal(R)); 132 133 if (const Loc *LV = dyn_cast<Loc>(&V)) { 134 // Assume that the pointer value in 'self' is non-null. 135 state = state->assume(*LV, true); 136 assert(state && "'self' cannot be null"); 137 } 138 } 139 140 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 141 if (!MD->isStatic()) { 142 // Precondition: 'this' is always non-null upon entry to the 143 // top-level function. This is our starting assumption for 144 // analyzing an "open" program. 145 const StackFrameContext *SFC = InitLoc->getCurrentStackFrame(); 146 if (SFC->getParent() == 0) { 147 loc::MemRegionVal L(getCXXThisRegion(MD, SFC)); 148 SVal V = state->getSVal(L); 149 if (const Loc *LV = dyn_cast<Loc>(&V)) { 150 state = state->assume(*LV, true); 151 assert(state && "'this' cannot be null"); 152 } 153 } 154 } 155 } 156 157 return state; 158 } 159 160 //===----------------------------------------------------------------------===// 161 // Top-level transfer function logic (Dispatcher). 162 //===----------------------------------------------------------------------===// 163 164 /// evalAssume - Called by ConstraintManager. Used to call checker-specific 165 /// logic for handling assumptions on symbolic values. 166 const ProgramState *ExprEngine::processAssume(const ProgramState *state, 167 SVal cond, bool assumption) { 168 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption); 169 } 170 171 bool ExprEngine::wantsRegionChangeUpdate(const ProgramState *state) { 172 return getCheckerManager().wantsRegionChangeUpdate(state); 173 } 174 175 const ProgramState * 176 ExprEngine::processRegionChanges(const ProgramState *state, 177 const StoreManager::InvalidatedSymbols *invalidated, 178 ArrayRef<const MemRegion *> Explicits, 179 ArrayRef<const MemRegion *> Regions) { 180 return getCheckerManager().runCheckersForRegionChanges(state, invalidated, 181 Explicits, Regions); 182 } 183 184 void ExprEngine::printState(raw_ostream &Out, const ProgramState *State, 185 const char *NL, const char *Sep) { 186 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep); 187 } 188 189 void ExprEngine::processEndWorklist(bool hasWorkRemaining) { 190 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this); 191 } 192 193 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred, 194 unsigned StmtIdx, NodeBuilderContext *Ctx) { 195 currentStmtIdx = StmtIdx; 196 currentBuilderContext = Ctx; 197 198 switch (E.getKind()) { 199 case CFGElement::Invalid: 200 llvm_unreachable("Unexpected CFGElement kind."); 201 case CFGElement::Statement: 202 ProcessStmt(const_cast<Stmt*>(E.getAs<CFGStmt>()->getStmt()), Pred); 203 return; 204 case CFGElement::Initializer: 205 ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), Pred); 206 return; 207 case CFGElement::AutomaticObjectDtor: 208 case CFGElement::BaseDtor: 209 case CFGElement::MemberDtor: 210 case CFGElement::TemporaryDtor: 211 ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), Pred); 212 return; 213 } 214 } 215 216 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr, 217 const CFGStmt S, 218 const ExplodedNode *Pred, 219 const LocationContext *LC) { 220 221 // Are we never purging state values? 222 if (AMgr.getPurgeMode() == PurgeNone) 223 return false; 224 225 // Is this the beginning of a basic block? 226 if (isa<BlockEntrance>(Pred->getLocation())) 227 return true; 228 229 // Is this on a non-expression? 230 if (!isa<Expr>(S.getStmt())) 231 return true; 232 233 // Is this an expression that is consumed by another expression? If so, 234 // postpone cleaning out the state. 235 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap(); 236 return !PM.isConsumedExpr(cast<Expr>(S.getStmt())); 237 } 238 239 void ExprEngine::ProcessStmt(const CFGStmt S, 240 ExplodedNode *Pred) { 241 // TODO: Use RAII to remove the unnecessary, tagged nodes. 242 //RegisterCreatedNodes registerCreatedNodes(getGraph()); 243 244 // Reclaim any unnecessary nodes in the ExplodedGraph. 245 G.reclaimRecentlyAllocatedNodes(); 246 // Recycle any unused states in the ProgramStateManager. 247 StateMgr.recycleUnusedStates(); 248 249 currentStmt = S.getStmt(); 250 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 251 currentStmt->getLocStart(), 252 "Error evaluating statement"); 253 254 EntryNode = Pred; 255 256 const ProgramState *EntryState = EntryNode->getState(); 257 CleanedState = EntryState; 258 259 // Create the cleaned state. 260 const LocationContext *LC = EntryNode->getLocationContext(); 261 SymbolReaper SymReaper(LC, currentStmt, SymMgr, getStoreManager()); 262 263 if (shouldRemoveDeadBindings(AMgr, S, Pred, LC)) { 264 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper); 265 266 const StackFrameContext *SFC = LC->getCurrentStackFrame(); 267 268 // Create a state in which dead bindings are removed from the environment 269 // and the store. TODO: The function should just return new env and store, 270 // not a new state. 271 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper); 272 } 273 274 // Process any special transfer function for dead symbols. 275 ExplodedNodeSet Tmp; 276 // A tag to track convenience transitions, which can be removed at cleanup. 277 static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node"); 278 279 if (!SymReaper.hasDeadSymbols()) { 280 // Generate a CleanedNode that has the environment and store cleaned 281 // up. Since no symbols are dead, we can optimize and not clean out 282 // the constraint manager. 283 StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext); 284 Bldr.generateNode(currentStmt, EntryNode, CleanedState, false, &cleanupTag); 285 286 } else { 287 // Call checkers with the non-cleaned state so that they could query the 288 // values of the soon to be dead symbols. 289 ExplodedNodeSet CheckedSet; 290 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, EntryNode, 291 SymReaper, currentStmt, *this); 292 293 // For each node in CheckedSet, generate CleanedNodes that have the 294 // environment, the store, and the constraints cleaned up but have the 295 // user-supplied states as the predecessors. 296 StmtNodeBuilder Bldr(CheckedSet, Tmp, *currentBuilderContext); 297 for (ExplodedNodeSet::const_iterator 298 I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) { 299 const ProgramState *CheckerState = (*I)->getState(); 300 301 // The constraint manager has not been cleaned up yet, so clean up now. 302 CheckerState = getConstraintManager().removeDeadBindings(CheckerState, 303 SymReaper); 304 305 assert(StateMgr.haveEqualEnvironments(CheckerState, EntryState) && 306 "Checkers are not allowed to modify the Environment as a part of " 307 "checkDeadSymbols processing."); 308 assert(StateMgr.haveEqualStores(CheckerState, EntryState) && 309 "Checkers are not allowed to modify the Store as a part of " 310 "checkDeadSymbols processing."); 311 312 // Create a state based on CleanedState with CheckerState GDM and 313 // generate a transition to that state. 314 const ProgramState *CleanedCheckerSt = 315 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState); 316 Bldr.generateNode(currentStmt, *I, CleanedCheckerSt, false, &cleanupTag, 317 ProgramPoint::PostPurgeDeadSymbolsKind); 318 } 319 } 320 321 ExplodedNodeSet Dst; 322 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 323 ExplodedNodeSet DstI; 324 // Visit the statement. 325 Visit(currentStmt, *I, DstI); 326 Dst.insert(DstI); 327 } 328 329 // Enqueue the new nodes onto the work list. 330 Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx); 331 332 // NULL out these variables to cleanup. 333 CleanedState = NULL; 334 EntryNode = NULL; 335 currentStmt = 0; 336 } 337 338 void ExprEngine::ProcessInitializer(const CFGInitializer Init, 339 ExplodedNode *Pred) { 340 ExplodedNodeSet Dst; 341 342 // We don't set EntryNode and currentStmt. And we don't clean up state. 343 const CXXCtorInitializer *BMI = Init.getInitializer(); 344 const StackFrameContext *stackFrame = 345 cast<StackFrameContext>(Pred->getLocationContext()); 346 const CXXConstructorDecl *decl = 347 cast<CXXConstructorDecl>(stackFrame->getDecl()); 348 const CXXThisRegion *thisReg = getCXXThisRegion(decl, stackFrame); 349 350 SVal thisVal = Pred->getState()->getSVal(thisReg); 351 352 if (BMI->isAnyMemberInitializer()) { 353 ExplodedNodeSet AfterEval; 354 355 // Evaluate the initializer. 356 Visit(BMI->getInit(), Pred, AfterEval); 357 358 StmtNodeBuilder Bldr(AfterEval, Dst, *currentBuilderContext); 359 for (ExplodedNodeSet::iterator I = AfterEval.begin(), 360 E = AfterEval.end(); I != E; ++I){ 361 ExplodedNode *P = *I; 362 const ProgramState *state = P->getState(); 363 364 const FieldDecl *FD = BMI->getAnyMember(); 365 366 SVal FieldLoc = state->getLValue(FD, thisVal); 367 SVal InitVal = state->getSVal(BMI->getInit(), Pred->getLocationContext()); 368 state = state->bindLoc(FieldLoc, InitVal); 369 370 // Use a custom node building process. 371 PostInitializer PP(BMI, stackFrame); 372 // Builder automatically add the generated node to the deferred set, 373 // which are processed in the builder's dtor. 374 Bldr.generateNode(PP, P, state); 375 } 376 } else { 377 assert(BMI->isBaseInitializer()); 378 379 // Get the base class declaration. 380 const CXXConstructExpr *ctorExpr = cast<CXXConstructExpr>(BMI->getInit()); 381 382 // Create the base object region. 383 SVal baseVal = 384 getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType()); 385 const MemRegion *baseReg = baseVal.getAsRegion(); 386 assert(baseReg); 387 388 VisitCXXConstructExpr(ctorExpr, baseReg, Pred, Dst); 389 } 390 391 // Enqueue the new nodes onto the work list. 392 Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx); 393 } 394 395 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D, 396 ExplodedNode *Pred) { 397 ExplodedNodeSet Dst; 398 switch (D.getKind()) { 399 case CFGElement::AutomaticObjectDtor: 400 ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), Pred, Dst); 401 break; 402 case CFGElement::BaseDtor: 403 ProcessBaseDtor(cast<CFGBaseDtor>(D), Pred, Dst); 404 break; 405 case CFGElement::MemberDtor: 406 ProcessMemberDtor(cast<CFGMemberDtor>(D), Pred, Dst); 407 break; 408 case CFGElement::TemporaryDtor: 409 ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), Pred, Dst); 410 break; 411 default: 412 llvm_unreachable("Unexpected dtor kind."); 413 } 414 415 // Enqueue the new nodes onto the work list. 416 Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx); 417 } 418 419 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor, 420 ExplodedNode *Pred, 421 ExplodedNodeSet &Dst) { 422 const ProgramState *state = Pred->getState(); 423 const VarDecl *varDecl = Dtor.getVarDecl(); 424 425 QualType varType = varDecl->getType(); 426 427 if (const ReferenceType *refType = varType->getAs<ReferenceType>()) 428 varType = refType->getPointeeType(); 429 430 const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl(); 431 assert(recordDecl && "get CXXRecordDecl fail"); 432 const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor(); 433 434 Loc dest = state->getLValue(varDecl, Pred->getLocationContext()); 435 436 VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(), 437 Dtor.getTriggerStmt(), Pred, Dst); 438 } 439 440 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D, 441 ExplodedNode *Pred, ExplodedNodeSet &Dst) {} 442 443 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D, 444 ExplodedNode *Pred, ExplodedNodeSet &Dst) {} 445 446 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, 447 ExplodedNode *Pred, 448 ExplodedNodeSet &Dst) {} 449 450 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, 451 ExplodedNodeSet &DstTop) { 452 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 453 S->getLocStart(), 454 "Error evaluating statement"); 455 ExplodedNodeSet Dst; 456 StmtNodeBuilder Bldr(Pred, DstTop, *currentBuilderContext); 457 458 // Expressions to ignore. 459 if (const Expr *Ex = dyn_cast<Expr>(S)) 460 S = Ex->IgnoreParens(); 461 462 // FIXME: add metadata to the CFG so that we can disable 463 // this check when we KNOW that there is no block-level subexpression. 464 // The motivation is that this check requires a hashtable lookup. 465 466 if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S)) 467 return; 468 469 switch (S->getStmtClass()) { 470 // C++ and ARC stuff we don't support yet. 471 case Expr::ObjCIndirectCopyRestoreExprClass: 472 case Stmt::CXXBindTemporaryExprClass: 473 case Stmt::CXXCatchStmtClass: 474 case Stmt::CXXDependentScopeMemberExprClass: 475 case Stmt::CXXPseudoDestructorExprClass: 476 case Stmt::CXXThrowExprClass: 477 case Stmt::CXXTryStmtClass: 478 case Stmt::CXXTypeidExprClass: 479 case Stmt::CXXUuidofExprClass: 480 case Stmt::CXXUnresolvedConstructExprClass: 481 case Stmt::CXXScalarValueInitExprClass: 482 case Stmt::DependentScopeDeclRefExprClass: 483 case Stmt::UnaryTypeTraitExprClass: 484 case Stmt::BinaryTypeTraitExprClass: 485 case Stmt::ArrayTypeTraitExprClass: 486 case Stmt::ExpressionTraitExprClass: 487 case Stmt::UnresolvedLookupExprClass: 488 case Stmt::UnresolvedMemberExprClass: 489 case Stmt::CXXNoexceptExprClass: 490 case Stmt::PackExpansionExprClass: 491 case Stmt::SubstNonTypeTemplateParmPackExprClass: 492 case Stmt::SEHTryStmtClass: 493 case Stmt::SEHExceptStmtClass: 494 case Stmt::SEHFinallyStmtClass: { 495 const ExplodedNode *node = Bldr.generateNode(S, Pred, Pred->getState()); 496 Engine.addAbortedBlock(node, currentBuilderContext->getBlock()); 497 break; 498 } 499 500 // We don't handle default arguments either yet, but we can fake it 501 // for now by just skipping them. 502 case Stmt::SubstNonTypeTemplateParmExprClass: 503 case Stmt::CXXDefaultArgExprClass: 504 break; 505 506 case Stmt::ParenExprClass: 507 llvm_unreachable("ParenExprs already handled."); 508 case Stmt::GenericSelectionExprClass: 509 llvm_unreachable("GenericSelectionExprs already handled."); 510 // Cases that should never be evaluated simply because they shouldn't 511 // appear in the CFG. 512 case Stmt::BreakStmtClass: 513 case Stmt::CaseStmtClass: 514 case Stmt::CompoundStmtClass: 515 case Stmt::ContinueStmtClass: 516 case Stmt::CXXForRangeStmtClass: 517 case Stmt::DefaultStmtClass: 518 case Stmt::DoStmtClass: 519 case Stmt::ForStmtClass: 520 case Stmt::GotoStmtClass: 521 case Stmt::IfStmtClass: 522 case Stmt::IndirectGotoStmtClass: 523 case Stmt::LabelStmtClass: 524 case Stmt::NoStmtClass: 525 case Stmt::NullStmtClass: 526 case Stmt::SwitchStmtClass: 527 case Stmt::WhileStmtClass: 528 case Expr::MSDependentExistsStmtClass: 529 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 530 531 case Stmt::GNUNullExprClass: { 532 // GNU __null is a pointer-width integer, not an actual pointer. 533 const ProgramState *state = Pred->getState(); 534 state = state->BindExpr(S, Pred->getLocationContext(), 535 svalBuilder.makeIntValWithPtrWidth(0, false)); 536 Bldr.generateNode(S, Pred, state); 537 break; 538 } 539 540 case Stmt::ObjCAtSynchronizedStmtClass: 541 Bldr.takeNodes(Pred); 542 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 543 Bldr.addNodes(Dst); 544 break; 545 546 case Stmt::ObjCPropertyRefExprClass: 547 // Implicitly handled by Environment::getSVal(). 548 break; 549 550 case Stmt::ImplicitValueInitExprClass: { 551 const ProgramState *state = Pred->getState(); 552 QualType ty = cast<ImplicitValueInitExpr>(S)->getType(); 553 SVal val = svalBuilder.makeZeroVal(ty); 554 Bldr.generateNode(S, Pred, state->BindExpr(S, Pred->getLocationContext(), 555 val)); 556 break; 557 } 558 559 case Stmt::ExprWithCleanupsClass: 560 Bldr.takeNodes(Pred); 561 Visit(cast<ExprWithCleanups>(S)->getSubExpr(), Pred, Dst); 562 Bldr.addNodes(Dst); 563 break; 564 565 // Cases not handled yet; but will handle some day. 566 case Stmt::DesignatedInitExprClass: 567 case Stmt::ExtVectorElementExprClass: 568 case Stmt::ImaginaryLiteralClass: 569 case Stmt::ObjCAtCatchStmtClass: 570 case Stmt::ObjCAtFinallyStmtClass: 571 case Stmt::ObjCAtTryStmtClass: 572 case Stmt::ObjCAutoreleasePoolStmtClass: 573 case Stmt::ObjCEncodeExprClass: 574 case Stmt::ObjCIsaExprClass: 575 case Stmt::ObjCProtocolExprClass: 576 case Stmt::ObjCSelectorExprClass: 577 case Stmt::ObjCStringLiteralClass: 578 case Stmt::ParenListExprClass: 579 case Stmt::PredefinedExprClass: 580 case Stmt::ShuffleVectorExprClass: 581 case Stmt::VAArgExprClass: 582 case Stmt::CUDAKernelCallExprClass: 583 case Stmt::OpaqueValueExprClass: 584 case Stmt::AsTypeExprClass: 585 case Stmt::AtomicExprClass: 586 // Fall through. 587 588 // Cases we intentionally don't evaluate, since they don't need 589 // to be explicitly evaluated. 590 case Stmt::AddrLabelExprClass: 591 case Stmt::IntegerLiteralClass: 592 case Stmt::CharacterLiteralClass: 593 case Stmt::CXXBoolLiteralExprClass: 594 case Stmt::FloatingLiteralClass: 595 case Stmt::SizeOfPackExprClass: 596 case Stmt::CXXNullPtrLiteralExprClass: 597 // No-op. Simply propagate the current state unchanged. 598 break; 599 600 case Stmt::ArraySubscriptExprClass: 601 Bldr.takeNodes(Pred); 602 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 603 Bldr.addNodes(Dst); 604 break; 605 606 case Stmt::AsmStmtClass: 607 Bldr.takeNodes(Pred); 608 VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst); 609 Bldr.addNodes(Dst); 610 break; 611 612 case Stmt::BlockDeclRefExprClass: { 613 Bldr.takeNodes(Pred); 614 const BlockDeclRefExpr *BE = cast<BlockDeclRefExpr>(S); 615 VisitCommonDeclRefExpr(BE, BE->getDecl(), Pred, Dst); 616 Bldr.addNodes(Dst); 617 break; 618 } 619 620 case Stmt::BlockExprClass: 621 Bldr.takeNodes(Pred); 622 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 623 Bldr.addNodes(Dst); 624 break; 625 626 case Stmt::BinaryOperatorClass: { 627 const BinaryOperator* B = cast<BinaryOperator>(S); 628 if (B->isLogicalOp()) { 629 Bldr.takeNodes(Pred); 630 VisitLogicalExpr(B, Pred, Dst); 631 Bldr.addNodes(Dst); 632 break; 633 } 634 else if (B->getOpcode() == BO_Comma) { 635 const ProgramState *state = Pred->getState(); 636 Bldr.generateNode(B, Pred, 637 state->BindExpr(B, Pred->getLocationContext(), 638 state->getSVal(B->getRHS(), 639 Pred->getLocationContext()))); 640 break; 641 } 642 643 Bldr.takeNodes(Pred); 644 645 if (AMgr.shouldEagerlyAssume() && 646 (B->isRelationalOp() || B->isEqualityOp())) { 647 ExplodedNodeSet Tmp; 648 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 649 evalEagerlyAssume(Dst, Tmp, cast<Expr>(S)); 650 } 651 else 652 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 653 654 Bldr.addNodes(Dst); 655 break; 656 } 657 658 case Stmt::CallExprClass: 659 case Stmt::CXXOperatorCallExprClass: 660 case Stmt::CXXMemberCallExprClass: { 661 Bldr.takeNodes(Pred); 662 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 663 Bldr.addNodes(Dst); 664 break; 665 } 666 667 case Stmt::CXXTemporaryObjectExprClass: 668 case Stmt::CXXConstructExprClass: { 669 const CXXConstructExpr *C = cast<CXXConstructExpr>(S); 670 // For block-level CXXConstructExpr, we don't have a destination region. 671 // Let VisitCXXConstructExpr() create one. 672 Bldr.takeNodes(Pred); 673 VisitCXXConstructExpr(C, 0, Pred, Dst); 674 Bldr.addNodes(Dst); 675 break; 676 } 677 678 case Stmt::CXXNewExprClass: { 679 Bldr.takeNodes(Pred); 680 const CXXNewExpr *NE = cast<CXXNewExpr>(S); 681 VisitCXXNewExpr(NE, Pred, Dst); 682 Bldr.addNodes(Dst); 683 break; 684 } 685 686 case Stmt::CXXDeleteExprClass: { 687 Bldr.takeNodes(Pred); 688 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S); 689 VisitCXXDeleteExpr(CDE, Pred, Dst); 690 Bldr.addNodes(Dst); 691 break; 692 } 693 // FIXME: ChooseExpr is really a constant. We need to fix 694 // the CFG do not model them as explicit control-flow. 695 696 case Stmt::ChooseExprClass: { // __builtin_choose_expr 697 Bldr.takeNodes(Pred); 698 const ChooseExpr *C = cast<ChooseExpr>(S); 699 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 700 Bldr.addNodes(Dst); 701 break; 702 } 703 704 case Stmt::CompoundAssignOperatorClass: 705 Bldr.takeNodes(Pred); 706 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 707 Bldr.addNodes(Dst); 708 break; 709 710 case Stmt::CompoundLiteralExprClass: 711 Bldr.takeNodes(Pred); 712 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 713 Bldr.addNodes(Dst); 714 break; 715 716 case Stmt::BinaryConditionalOperatorClass: 717 case Stmt::ConditionalOperatorClass: { // '?' operator 718 Bldr.takeNodes(Pred); 719 const AbstractConditionalOperator *C 720 = cast<AbstractConditionalOperator>(S); 721 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 722 Bldr.addNodes(Dst); 723 break; 724 } 725 726 case Stmt::CXXThisExprClass: 727 Bldr.takeNodes(Pred); 728 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 729 Bldr.addNodes(Dst); 730 break; 731 732 case Stmt::DeclRefExprClass: { 733 Bldr.takeNodes(Pred); 734 const DeclRefExpr *DE = cast<DeclRefExpr>(S); 735 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 736 Bldr.addNodes(Dst); 737 break; 738 } 739 740 case Stmt::DeclStmtClass: 741 Bldr.takeNodes(Pred); 742 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 743 Bldr.addNodes(Dst); 744 break; 745 746 case Stmt::ImplicitCastExprClass: 747 case Stmt::CStyleCastExprClass: 748 case Stmt::CXXStaticCastExprClass: 749 case Stmt::CXXDynamicCastExprClass: 750 case Stmt::CXXReinterpretCastExprClass: 751 case Stmt::CXXConstCastExprClass: 752 case Stmt::CXXFunctionalCastExprClass: 753 case Stmt::ObjCBridgedCastExprClass: { 754 Bldr.takeNodes(Pred); 755 const CastExpr *C = cast<CastExpr>(S); 756 // Handle the previsit checks. 757 ExplodedNodeSet dstPrevisit; 758 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this); 759 760 // Handle the expression itself. 761 ExplodedNodeSet dstExpr; 762 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(), 763 e = dstPrevisit.end(); i != e ; ++i) { 764 VisitCast(C, C->getSubExpr(), *i, dstExpr); 765 } 766 767 // Handle the postvisit checks. 768 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 769 Bldr.addNodes(Dst); 770 break; 771 } 772 773 case Expr::MaterializeTemporaryExprClass: { 774 Bldr.takeNodes(Pred); 775 const MaterializeTemporaryExpr *Materialize 776 = cast<MaterializeTemporaryExpr>(S); 777 if (!Materialize->getType()->isRecordType()) 778 CreateCXXTemporaryObject(Materialize, Pred, Dst); 779 else 780 Visit(Materialize->GetTemporaryExpr(), Pred, Dst); 781 Bldr.addNodes(Dst); 782 break; 783 } 784 785 case Stmt::InitListExprClass: 786 Bldr.takeNodes(Pred); 787 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 788 Bldr.addNodes(Dst); 789 break; 790 791 case Stmt::MemberExprClass: 792 Bldr.takeNodes(Pred); 793 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 794 Bldr.addNodes(Dst); 795 break; 796 797 case Stmt::ObjCIvarRefExprClass: 798 Bldr.takeNodes(Pred); 799 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 800 Bldr.addNodes(Dst); 801 break; 802 803 case Stmt::ObjCForCollectionStmtClass: 804 Bldr.takeNodes(Pred); 805 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 806 Bldr.addNodes(Dst); 807 break; 808 809 case Stmt::ObjCMessageExprClass: 810 Bldr.takeNodes(Pred); 811 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst); 812 Bldr.addNodes(Dst); 813 break; 814 815 case Stmt::ObjCAtThrowStmtClass: { 816 // FIXME: This is not complete. We basically treat @throw as 817 // an abort. 818 Bldr.generateNode(S, Pred, Pred->getState()); 819 break; 820 } 821 822 case Stmt::ReturnStmtClass: 823 Bldr.takeNodes(Pred); 824 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 825 Bldr.addNodes(Dst); 826 break; 827 828 case Stmt::OffsetOfExprClass: 829 Bldr.takeNodes(Pred); 830 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst); 831 Bldr.addNodes(Dst); 832 break; 833 834 case Stmt::UnaryExprOrTypeTraitExprClass: 835 Bldr.takeNodes(Pred); 836 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 837 Pred, Dst); 838 Bldr.addNodes(Dst); 839 break; 840 841 case Stmt::StmtExprClass: { 842 const StmtExpr *SE = cast<StmtExpr>(S); 843 844 if (SE->getSubStmt()->body_empty()) { 845 // Empty statement expression. 846 assert(SE->getType() == getContext().VoidTy 847 && "Empty statement expression must have void type."); 848 break; 849 } 850 851 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 852 const ProgramState *state = Pred->getState(); 853 Bldr.generateNode(SE, Pred, 854 state->BindExpr(SE, Pred->getLocationContext(), 855 state->getSVal(LastExpr, 856 Pred->getLocationContext()))); 857 } 858 break; 859 } 860 861 case Stmt::StringLiteralClass: { 862 const ProgramState *state = Pred->getState(); 863 SVal V = state->getLValue(cast<StringLiteral>(S)); 864 Bldr.generateNode(S, Pred, state->BindExpr(S, Pred->getLocationContext(), 865 V)); 866 return; 867 } 868 869 case Stmt::UnaryOperatorClass: { 870 Bldr.takeNodes(Pred); 871 const UnaryOperator *U = cast<UnaryOperator>(S); 872 if (AMgr.shouldEagerlyAssume() && (U->getOpcode() == UO_LNot)) { 873 ExplodedNodeSet Tmp; 874 VisitUnaryOperator(U, Pred, Tmp); 875 evalEagerlyAssume(Dst, Tmp, U); 876 } 877 else 878 VisitUnaryOperator(U, Pred, Dst); 879 Bldr.addNodes(Dst); 880 break; 881 } 882 883 case Stmt::PseudoObjectExprClass: { 884 Bldr.takeNodes(Pred); 885 const ProgramState *state = Pred->getState(); 886 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S); 887 if (const Expr *Result = PE->getResultExpr()) { 888 SVal V = state->getSVal(Result, Pred->getLocationContext()); 889 Bldr.generateNode(S, Pred, 890 state->BindExpr(S, Pred->getLocationContext(), V)); 891 } 892 else 893 Bldr.generateNode(S, Pred, 894 state->BindExpr(S, Pred->getLocationContext(), 895 UnknownVal())); 896 897 Bldr.addNodes(Dst); 898 break; 899 } 900 } 901 } 902 903 /// Block entrance. (Update counters). 904 void ExprEngine::processCFGBlockEntrance(NodeBuilderWithSinks &nodeBuilder) { 905 906 // FIXME: Refactor this into a checker. 907 ExplodedNode *pred = nodeBuilder.getContext().getPred(); 908 909 if (nodeBuilder.getContext().getCurrentBlockCount() >= AMgr.getMaxVisit()) { 910 static SimpleProgramPointTag tag("ExprEngine : Block count exceeded"); 911 nodeBuilder.generateNode(pred->getState(), pred, &tag, true); 912 } 913 } 914 915 //===----------------------------------------------------------------------===// 916 // Branch processing. 917 //===----------------------------------------------------------------------===// 918 919 const ProgramState *ExprEngine::MarkBranch(const ProgramState *state, 920 const Stmt *Terminator, 921 const LocationContext *LCtx, 922 bool branchTaken) { 923 924 switch (Terminator->getStmtClass()) { 925 default: 926 return state; 927 928 case Stmt::BinaryOperatorClass: { // '&&' and '||' 929 930 const BinaryOperator* B = cast<BinaryOperator>(Terminator); 931 BinaryOperator::Opcode Op = B->getOpcode(); 932 933 assert (Op == BO_LAnd || Op == BO_LOr); 934 935 // For &&, if we take the true branch, then the value of the whole 936 // expression is that of the RHS expression. 937 // 938 // For ||, if we take the false branch, then the value of the whole 939 // expression is that of the RHS expression. 940 941 const Expr *Ex = (Op == BO_LAnd && branchTaken) || 942 (Op == BO_LOr && !branchTaken) 943 ? B->getRHS() : B->getLHS(); 944 945 return state->BindExpr(B, LCtx, UndefinedVal(Ex)); 946 } 947 948 case Stmt::BinaryConditionalOperatorClass: 949 case Stmt::ConditionalOperatorClass: { // ?: 950 const AbstractConditionalOperator* C 951 = cast<AbstractConditionalOperator>(Terminator); 952 953 // For ?, if branchTaken == true then the value is either the LHS or 954 // the condition itself. (GNU extension). 955 956 const Expr *Ex; 957 958 if (branchTaken) 959 Ex = C->getTrueExpr(); 960 else 961 Ex = C->getFalseExpr(); 962 963 return state->BindExpr(C, LCtx, UndefinedVal(Ex)); 964 } 965 966 case Stmt::ChooseExprClass: { // ?: 967 968 const ChooseExpr *C = cast<ChooseExpr>(Terminator); 969 970 const Expr *Ex = branchTaken ? C->getLHS() : C->getRHS(); 971 return state->BindExpr(C, LCtx, UndefinedVal(Ex)); 972 } 973 } 974 } 975 976 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used 977 /// to try to recover some path-sensitivity for casts of symbolic 978 /// integers that promote their values (which are currently not tracked well). 979 /// This function returns the SVal bound to Condition->IgnoreCasts if all the 980 // cast(s) did was sign-extend the original value. 981 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr, 982 const ProgramState *state, 983 const Stmt *Condition, 984 const LocationContext *LCtx, 985 ASTContext &Ctx) { 986 987 const Expr *Ex = dyn_cast<Expr>(Condition); 988 if (!Ex) 989 return UnknownVal(); 990 991 uint64_t bits = 0; 992 bool bitsInit = false; 993 994 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 995 QualType T = CE->getType(); 996 997 if (!T->isIntegerType()) 998 return UnknownVal(); 999 1000 uint64_t newBits = Ctx.getTypeSize(T); 1001 if (!bitsInit || newBits < bits) { 1002 bitsInit = true; 1003 bits = newBits; 1004 } 1005 1006 Ex = CE->getSubExpr(); 1007 } 1008 1009 // We reached a non-cast. Is it a symbolic value? 1010 QualType T = Ex->getType(); 1011 1012 if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits) 1013 return UnknownVal(); 1014 1015 return state->getSVal(Ex, LCtx); 1016 } 1017 1018 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term, 1019 NodeBuilderContext& BldCtx, 1020 ExplodedNode *Pred, 1021 ExplodedNodeSet &Dst, 1022 const CFGBlock *DstT, 1023 const CFGBlock *DstF) { 1024 currentBuilderContext = &BldCtx; 1025 1026 // Check for NULL conditions; e.g. "for(;;)" 1027 if (!Condition) { 1028 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF); 1029 NullCondBldr.markInfeasible(false); 1030 NullCondBldr.generateNode(Pred->getState(), true, Pred); 1031 return; 1032 } 1033 1034 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1035 Condition->getLocStart(), 1036 "Error evaluating branch"); 1037 1038 ExplodedNodeSet CheckersOutSet; 1039 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet, 1040 Pred, *this); 1041 // We generated only sinks. 1042 if (CheckersOutSet.empty()) 1043 return; 1044 1045 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF); 1046 for (NodeBuilder::iterator I = CheckersOutSet.begin(), 1047 E = CheckersOutSet.end(); E != I; ++I) { 1048 ExplodedNode *PredI = *I; 1049 1050 if (PredI->isSink()) 1051 continue; 1052 1053 const ProgramState *PrevState = Pred->getState(); 1054 SVal X = PrevState->getSVal(Condition, Pred->getLocationContext()); 1055 1056 if (X.isUnknownOrUndef()) { 1057 // Give it a chance to recover from unknown. 1058 if (const Expr *Ex = dyn_cast<Expr>(Condition)) { 1059 if (Ex->getType()->isIntegerType()) { 1060 // Try to recover some path-sensitivity. Right now casts of symbolic 1061 // integers that promote their values are currently not tracked well. 1062 // If 'Condition' is such an expression, try and recover the 1063 // underlying value and use that instead. 1064 SVal recovered = RecoverCastedSymbol(getStateManager(), 1065 PrevState, Condition, 1066 Pred->getLocationContext(), 1067 getContext()); 1068 1069 if (!recovered.isUnknown()) { 1070 X = recovered; 1071 } 1072 } 1073 } 1074 } 1075 1076 const LocationContext *LCtx = PredI->getLocationContext(); 1077 1078 // If the condition is still unknown, give up. 1079 if (X.isUnknownOrUndef()) { 1080 builder.generateNode(MarkBranch(PrevState, Term, LCtx, true), 1081 true, PredI); 1082 builder.generateNode(MarkBranch(PrevState, Term, LCtx, false), 1083 false, PredI); 1084 continue; 1085 } 1086 1087 DefinedSVal V = cast<DefinedSVal>(X); 1088 1089 // Process the true branch. 1090 if (builder.isFeasible(true)) { 1091 if (const ProgramState *state = PrevState->assume(V, true)) 1092 builder.generateNode(MarkBranch(state, Term, LCtx, true), 1093 true, PredI); 1094 else 1095 builder.markInfeasible(true); 1096 } 1097 1098 // Process the false branch. 1099 if (builder.isFeasible(false)) { 1100 if (const ProgramState *state = PrevState->assume(V, false)) 1101 builder.generateNode(MarkBranch(state, Term, LCtx, false), 1102 false, PredI); 1103 else 1104 builder.markInfeasible(false); 1105 } 1106 } 1107 currentBuilderContext = 0; 1108 } 1109 1110 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 1111 /// nodes by processing the 'effects' of a computed goto jump. 1112 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 1113 1114 const ProgramState *state = builder.getState(); 1115 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext()); 1116 1117 // Three possibilities: 1118 // 1119 // (1) We know the computed label. 1120 // (2) The label is NULL (or some other constant), or Undefined. 1121 // (3) We have no clue about the label. Dispatch to all targets. 1122 // 1123 1124 typedef IndirectGotoNodeBuilder::iterator iterator; 1125 1126 if (isa<loc::GotoLabel>(V)) { 1127 const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel(); 1128 1129 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { 1130 if (I.getLabel() == L) { 1131 builder.generateNode(I, state); 1132 return; 1133 } 1134 } 1135 1136 llvm_unreachable("No block with label."); 1137 } 1138 1139 if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) { 1140 // Dispatch to the first target and mark it as a sink. 1141 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 1142 // FIXME: add checker visit. 1143 // UndefBranches.insert(N); 1144 return; 1145 } 1146 1147 // This is really a catch-all. We don't support symbolics yet. 1148 // FIXME: Implement dispatch for symbolic pointers. 1149 1150 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) 1151 builder.generateNode(I, state); 1152 } 1153 1154 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 1155 /// nodes when the control reaches the end of a function. 1156 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC) { 1157 StateMgr.EndPath(BC.Pred->getState()); 1158 ExplodedNodeSet Dst; 1159 getCheckerManager().runCheckersForEndPath(BC, Dst, *this); 1160 Engine.enqueueEndOfFunction(Dst); 1161 } 1162 1163 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 1164 /// nodes by processing the 'effects' of a switch statement. 1165 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 1166 typedef SwitchNodeBuilder::iterator iterator; 1167 const ProgramState *state = builder.getState(); 1168 const Expr *CondE = builder.getCondition(); 1169 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext()); 1170 1171 if (CondV_untested.isUndef()) { 1172 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 1173 // FIXME: add checker 1174 //UndefBranches.insert(N); 1175 1176 return; 1177 } 1178 DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested); 1179 1180 const ProgramState *DefaultSt = state; 1181 1182 iterator I = builder.begin(), EI = builder.end(); 1183 bool defaultIsFeasible = I == EI; 1184 1185 for ( ; I != EI; ++I) { 1186 // Successor may be pruned out during CFG construction. 1187 if (!I.getBlock()) 1188 continue; 1189 1190 const CaseStmt *Case = I.getCase(); 1191 1192 // Evaluate the LHS of the case value. 1193 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); 1194 assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType())); 1195 1196 // Get the RHS of the case, if it exists. 1197 llvm::APSInt V2; 1198 if (const Expr *E = Case->getRHS()) 1199 V2 = E->EvaluateKnownConstInt(getContext()); 1200 else 1201 V2 = V1; 1202 1203 // FIXME: Eventually we should replace the logic below with a range 1204 // comparison, rather than concretize the values within the range. 1205 // This should be easy once we have "ranges" for NonLVals. 1206 1207 do { 1208 nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1)); 1209 DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state, 1210 CondV, CaseVal); 1211 1212 // Now "assume" that the case matches. 1213 if (const ProgramState *stateNew = state->assume(Res, true)) { 1214 builder.generateCaseStmtNode(I, stateNew); 1215 1216 // If CondV evaluates to a constant, then we know that this 1217 // is the *only* case that we can take, so stop evaluating the 1218 // others. 1219 if (isa<nonloc::ConcreteInt>(CondV)) 1220 return; 1221 } 1222 1223 // Now "assume" that the case doesn't match. Add this state 1224 // to the default state (if it is feasible). 1225 if (DefaultSt) { 1226 if (const ProgramState *stateNew = DefaultSt->assume(Res, false)) { 1227 defaultIsFeasible = true; 1228 DefaultSt = stateNew; 1229 } 1230 else { 1231 defaultIsFeasible = false; 1232 DefaultSt = NULL; 1233 } 1234 } 1235 1236 // Concretize the next value in the range. 1237 if (V1 == V2) 1238 break; 1239 1240 ++V1; 1241 assert (V1 <= V2); 1242 1243 } while (true); 1244 } 1245 1246 if (!defaultIsFeasible) 1247 return; 1248 1249 // If we have switch(enum value), the default branch is not 1250 // feasible if all of the enum constants not covered by 'case:' statements 1251 // are not feasible values for the switch condition. 1252 // 1253 // Note that this isn't as accurate as it could be. Even if there isn't 1254 // a case for a particular enum value as long as that enum value isn't 1255 // feasible then it shouldn't be considered for making 'default:' reachable. 1256 const SwitchStmt *SS = builder.getSwitch(); 1257 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 1258 if (CondExpr->getType()->getAs<EnumType>()) { 1259 if (SS->isAllEnumCasesCovered()) 1260 return; 1261 } 1262 1263 builder.generateDefaultCaseNode(DefaultSt); 1264 } 1265 1266 //===----------------------------------------------------------------------===// 1267 // Transfer functions: Loads and stores. 1268 //===----------------------------------------------------------------------===// 1269 1270 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 1271 ExplodedNode *Pred, 1272 ExplodedNodeSet &Dst) { 1273 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 1274 1275 const ProgramState *state = Pred->getState(); 1276 const LocationContext *LCtx = Pred->getLocationContext(); 1277 1278 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1279 assert(Ex->isLValue()); 1280 SVal V = state->getLValue(VD, Pred->getLocationContext()); 1281 1282 // For references, the 'lvalue' is the pointer address stored in the 1283 // reference region. 1284 if (VD->getType()->isReferenceType()) { 1285 if (const MemRegion *R = V.getAsRegion()) 1286 V = state->getSVal(R); 1287 else 1288 V = UnknownVal(); 1289 } 1290 1291 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0, 1292 ProgramPoint::PostLValueKind); 1293 return; 1294 } 1295 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 1296 assert(!Ex->isLValue()); 1297 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 1298 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V)); 1299 return; 1300 } 1301 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1302 SVal V = svalBuilder.getFunctionPointer(FD); 1303 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0, 1304 ProgramPoint::PostLValueKind); 1305 return; 1306 } 1307 assert (false && 1308 "ValueDecl support for this ValueDecl not implemented."); 1309 } 1310 1311 /// VisitArraySubscriptExpr - Transfer function for array accesses 1312 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A, 1313 ExplodedNode *Pred, 1314 ExplodedNodeSet &Dst){ 1315 1316 const Expr *Base = A->getBase()->IgnoreParens(); 1317 const Expr *Idx = A->getIdx()->IgnoreParens(); 1318 1319 1320 ExplodedNodeSet checkerPreStmt; 1321 getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this); 1322 1323 StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currentBuilderContext); 1324 1325 for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(), 1326 ei = checkerPreStmt.end(); it != ei; ++it) { 1327 const LocationContext *LCtx = (*it)->getLocationContext(); 1328 const ProgramState *state = (*it)->getState(); 1329 SVal V = state->getLValue(A->getType(), 1330 state->getSVal(Idx, LCtx), 1331 state->getSVal(Base, LCtx)); 1332 assert(A->isLValue()); 1333 Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), 1334 false, 0, ProgramPoint::PostLValueKind); 1335 } 1336 } 1337 1338 /// VisitMemberExpr - Transfer function for member expressions. 1339 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 1340 ExplodedNodeSet &TopDst) { 1341 1342 StmtNodeBuilder Bldr(Pred, TopDst, *currentBuilderContext); 1343 ExplodedNodeSet Dst; 1344 Decl *member = M->getMemberDecl(); 1345 if (VarDecl *VD = dyn_cast<VarDecl>(member)) { 1346 assert(M->isLValue()); 1347 Bldr.takeNodes(Pred); 1348 VisitCommonDeclRefExpr(M, VD, Pred, Dst); 1349 Bldr.addNodes(Dst); 1350 return; 1351 } 1352 1353 FieldDecl *field = dyn_cast<FieldDecl>(member); 1354 if (!field) // FIXME: skipping member expressions for non-fields 1355 return; 1356 1357 Expr *baseExpr = M->getBase()->IgnoreParens(); 1358 const ProgramState *state = Pred->getState(); 1359 const LocationContext *LCtx = Pred->getLocationContext(); 1360 SVal baseExprVal = state->getSVal(baseExpr, Pred->getLocationContext()); 1361 if (isa<nonloc::LazyCompoundVal>(baseExprVal) || 1362 isa<nonloc::CompoundVal>(baseExprVal) || 1363 // FIXME: This can originate by conjuring a symbol for an unknown 1364 // temporary struct object, see test/Analysis/fields.c: 1365 // (p = getit()).x 1366 isa<nonloc::SymbolVal>(baseExprVal)) { 1367 Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, UnknownVal())); 1368 return; 1369 } 1370 1371 // FIXME: Should we insert some assumption logic in here to determine 1372 // if "Base" is a valid piece of memory? Before we put this assumption 1373 // later when using FieldOffset lvals (which we no longer have). 1374 1375 // For all other cases, compute an lvalue. 1376 SVal L = state->getLValue(field, baseExprVal); 1377 if (M->isLValue()) 1378 Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), false, 0, 1379 ProgramPoint::PostLValueKind); 1380 else { 1381 Bldr.takeNodes(Pred); 1382 evalLoad(Dst, M, Pred, state, L); 1383 Bldr.addNodes(Dst); 1384 } 1385 } 1386 1387 /// evalBind - Handle the semantics of binding a value to a specific location. 1388 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 1389 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, 1390 ExplodedNode *Pred, 1391 SVal location, SVal Val, bool atDeclInit, 1392 ProgramPoint::Kind PointKind) { 1393 1394 // Do a previsit of the bind. 1395 ExplodedNodeSet CheckedSet; 1396 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val, 1397 StoreE, *this, PointKind); 1398 1399 // TODO:AZ Remove TmpDst after NB refactoring is done. 1400 ExplodedNodeSet TmpDst; 1401 StmtNodeBuilder Bldr(CheckedSet, TmpDst, *currentBuilderContext); 1402 1403 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 1404 I!=E; ++I) { 1405 const ProgramState *state = (*I)->getState(); 1406 1407 if (atDeclInit) { 1408 const VarRegion *VR = 1409 cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion()); 1410 1411 state = state->bindDecl(VR, Val); 1412 } else { 1413 state = state->bindLoc(location, Val); 1414 } 1415 1416 Bldr.generateNode(StoreE, *I, state, false, 0, PointKind); 1417 } 1418 1419 Dst.insert(TmpDst); 1420 } 1421 1422 /// evalStore - Handle the semantics of a store via an assignment. 1423 /// @param Dst The node set to store generated state nodes 1424 /// @param AssignE The assignment expression if the store happens in an 1425 /// assignment. 1426 /// @param LocatioinE The location expression that is stored to. 1427 /// @param state The current simulation state 1428 /// @param location The location to store the value 1429 /// @param Val The value to be stored 1430 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, 1431 const Expr *LocationE, 1432 ExplodedNode *Pred, 1433 const ProgramState *state, SVal location, SVal Val, 1434 const ProgramPointTag *tag) { 1435 // Proceed with the store. We use AssignE as the anchor for the PostStore 1436 // ProgramPoint if it is non-NULL, and LocationE otherwise. 1437 const Expr *StoreE = AssignE ? AssignE : LocationE; 1438 1439 if (isa<loc::ObjCPropRef>(location)) { 1440 loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location); 1441 return VisitObjCMessage(ObjCPropertySetter(prop.getPropRefExpr(), 1442 StoreE, Val), Pred, Dst); 1443 } 1444 1445 // Evaluate the location (checks for bad dereferences). 1446 ExplodedNodeSet Tmp; 1447 evalLocation(Tmp, LocationE, Pred, state, location, tag, false); 1448 1449 if (Tmp.empty()) 1450 return; 1451 1452 if (location.isUndef()) 1453 return; 1454 1455 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 1456 evalBind(Dst, StoreE, *NI, location, Val, false, 1457 ProgramPoint::PostStoreKind); 1458 } 1459 1460 void ExprEngine::evalLoad(ExplodedNodeSet &Dst, const Expr *Ex, 1461 ExplodedNode *Pred, 1462 const ProgramState *state, SVal location, 1463 const ProgramPointTag *tag, QualType LoadTy) { 1464 assert(!isa<NonLoc>(location) && "location cannot be a NonLoc."); 1465 1466 if (isa<loc::ObjCPropRef>(location)) { 1467 loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location); 1468 return VisitObjCMessage(ObjCPropertyGetter(prop.getPropRefExpr(), Ex), 1469 Pred, Dst); 1470 } 1471 1472 // Are we loading from a region? This actually results in two loads; one 1473 // to fetch the address of the referenced value and one to fetch the 1474 // referenced value. 1475 if (const TypedValueRegion *TR = 1476 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) { 1477 1478 QualType ValTy = TR->getValueType(); 1479 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) { 1480 static SimpleProgramPointTag 1481 loadReferenceTag("ExprEngine : Load Reference"); 1482 ExplodedNodeSet Tmp; 1483 evalLoadCommon(Tmp, Ex, Pred, state, location, &loadReferenceTag, 1484 getContext().getPointerType(RT->getPointeeType())); 1485 1486 // Perform the load from the referenced value. 1487 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) { 1488 state = (*I)->getState(); 1489 location = state->getSVal(Ex, (*I)->getLocationContext()); 1490 evalLoadCommon(Dst, Ex, *I, state, location, tag, LoadTy); 1491 } 1492 return; 1493 } 1494 } 1495 1496 evalLoadCommon(Dst, Ex, Pred, state, location, tag, LoadTy); 1497 } 1498 1499 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst, const Expr *Ex, 1500 ExplodedNode *Pred, 1501 const ProgramState *state, SVal location, 1502 const ProgramPointTag *tag, QualType LoadTy) { 1503 1504 // Evaluate the location (checks for bad dereferences). 1505 ExplodedNodeSet Tmp; 1506 evalLocation(Tmp, Ex, Pred, state, location, tag, true); 1507 if (Tmp.empty()) 1508 return; 1509 1510 StmtNodeBuilder Bldr(Tmp, Dst, *currentBuilderContext); 1511 if (location.isUndef()) 1512 return; 1513 1514 // Proceed with the load. 1515 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 1516 state = (*NI)->getState(); 1517 const LocationContext *LCtx = (*NI)->getLocationContext(); 1518 1519 if (location.isUnknown()) { 1520 // This is important. We must nuke the old binding. 1521 Bldr.generateNode(Ex, *NI, state->BindExpr(Ex, LCtx, UnknownVal()), 1522 false, tag, ProgramPoint::PostLoadKind); 1523 } 1524 else { 1525 if (LoadTy.isNull()) 1526 LoadTy = Ex->getType(); 1527 SVal V = state->getSVal(cast<Loc>(location), LoadTy); 1528 Bldr.generateNode(Ex, *NI, state->bindExprAndLocation(Ex, LCtx, 1529 location, V), 1530 false, tag, ProgramPoint::PostLoadKind); 1531 } 1532 } 1533 } 1534 1535 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *S, 1536 ExplodedNode *Pred, 1537 const ProgramState *state, SVal location, 1538 const ProgramPointTag *tag, bool isLoad) { 1539 StmtNodeBuilder BldrTop(Pred, Dst, *currentBuilderContext); 1540 // Early checks for performance reason. 1541 if (location.isUnknown()) { 1542 return; 1543 } 1544 1545 ExplodedNodeSet Src; 1546 BldrTop.takeNodes(Pred); 1547 StmtNodeBuilder Bldr(Pred, Src, *currentBuilderContext); 1548 if (Pred->getState() != state) { 1549 // Associate this new state with an ExplodedNode. 1550 // FIXME: If I pass null tag, the graph is incorrect, e.g for 1551 // int *p; 1552 // p = 0; 1553 // *p = 0xDEADBEEF; 1554 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 1555 // instead "int *p" is noted as 1556 // "Variable 'p' initialized to a null pointer value" 1557 1558 // FIXME: why is 'tag' not used instead of etag? 1559 static SimpleProgramPointTag etag("ExprEngine: Location"); 1560 1561 Bldr.generateNode(S, Pred, state, false, &etag); 1562 } 1563 ExplodedNodeSet Tmp; 1564 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, S, 1565 *this); 1566 BldrTop.addNodes(Tmp); 1567 } 1568 1569 std::pair<const ProgramPointTag *, const ProgramPointTag*> 1570 ExprEngine::getEagerlyAssumeTags() { 1571 static SimpleProgramPointTag 1572 EagerlyAssumeTrue("ExprEngine : Eagerly Assume True"), 1573 EagerlyAssumeFalse("ExprEngine : Eagerly Assume False"); 1574 return std::make_pair(&EagerlyAssumeTrue, &EagerlyAssumeFalse); 1575 } 1576 1577 void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, 1578 const Expr *Ex) { 1579 StmtNodeBuilder Bldr(Src, Dst, *currentBuilderContext); 1580 1581 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { 1582 ExplodedNode *Pred = *I; 1583 // Test if the previous node was as the same expression. This can happen 1584 // when the expression fails to evaluate to anything meaningful and 1585 // (as an optimization) we don't generate a node. 1586 ProgramPoint P = Pred->getLocation(); 1587 if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) { 1588 continue; 1589 } 1590 1591 const ProgramState *state = Pred->getState(); 1592 SVal V = state->getSVal(Ex, Pred->getLocationContext()); 1593 nonloc::SymbolVal *SEV = dyn_cast<nonloc::SymbolVal>(&V); 1594 if (SEV && SEV->isExpression()) { 1595 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = 1596 getEagerlyAssumeTags(); 1597 1598 // First assume that the condition is true. 1599 if (const ProgramState *StateTrue = state->assume(*SEV, true)) { 1600 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType()); 1601 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val); 1602 Bldr.generateNode(Ex, Pred, StateTrue, false, tags.first); 1603 } 1604 1605 // Next, assume that the condition is false. 1606 if (const ProgramState *StateFalse = state->assume(*SEV, false)) { 1607 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType()); 1608 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val); 1609 Bldr.generateNode(Ex, Pred, StateFalse, false, tags.second); 1610 } 1611 } 1612 } 1613 } 1614 1615 void ExprEngine::VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred, 1616 ExplodedNodeSet &Dst) { 1617 VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred, Dst); 1618 } 1619 1620 void ExprEngine::VisitAsmStmtHelperOutputs(const AsmStmt *A, 1621 AsmStmt::const_outputs_iterator I, 1622 AsmStmt::const_outputs_iterator E, 1623 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 1624 if (I == E) { 1625 VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, Dst); 1626 return; 1627 } 1628 1629 ExplodedNodeSet Tmp; 1630 Visit(*I, Pred, Tmp); 1631 ++I; 1632 1633 for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end();NI != NE;++NI) 1634 VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst); 1635 } 1636 1637 void ExprEngine::VisitAsmStmtHelperInputs(const AsmStmt *A, 1638 AsmStmt::const_inputs_iterator I, 1639 AsmStmt::const_inputs_iterator E, 1640 ExplodedNode *Pred, 1641 ExplodedNodeSet &Dst) { 1642 if (I == E) { 1643 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 1644 // We have processed both the inputs and the outputs. All of the outputs 1645 // should evaluate to Locs. Nuke all of their values. 1646 1647 // FIXME: Some day in the future it would be nice to allow a "plug-in" 1648 // which interprets the inline asm and stores proper results in the 1649 // outputs. 1650 1651 const ProgramState *state = Pred->getState(); 1652 1653 for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(), 1654 OE = A->end_outputs(); OI != OE; ++OI) { 1655 1656 SVal X = state->getSVal(*OI, Pred->getLocationContext()); 1657 assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef. 1658 1659 if (isa<Loc>(X)) 1660 state = state->bindLoc(cast<Loc>(X), UnknownVal()); 1661 } 1662 1663 Bldr.generateNode(A, Pred, state); 1664 return; 1665 } 1666 1667 ExplodedNodeSet Tmp; 1668 Visit(*I, Pred, Tmp); 1669 1670 ++I; 1671 1672 for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI!=NE; ++NI) 1673 VisitAsmStmtHelperInputs(A, I, E, *NI, Dst); 1674 } 1675 1676 1677 //===----------------------------------------------------------------------===// 1678 // Visualization. 1679 //===----------------------------------------------------------------------===// 1680 1681 #ifndef NDEBUG 1682 static ExprEngine* GraphPrintCheckerState; 1683 static SourceManager* GraphPrintSourceManager; 1684 1685 namespace llvm { 1686 template<> 1687 struct DOTGraphTraits<ExplodedNode*> : 1688 public DefaultDOTGraphTraits { 1689 1690 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 1691 1692 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not 1693 // work. 1694 static std::string getNodeAttributes(const ExplodedNode *N, void*) { 1695 1696 #if 0 1697 // FIXME: Replace with a general scheme to tell if the node is 1698 // an error node. 1699 if (GraphPrintCheckerState->isImplicitNullDeref(N) || 1700 GraphPrintCheckerState->isExplicitNullDeref(N) || 1701 GraphPrintCheckerState->isUndefDeref(N) || 1702 GraphPrintCheckerState->isUndefStore(N) || 1703 GraphPrintCheckerState->isUndefControlFlow(N) || 1704 GraphPrintCheckerState->isUndefResult(N) || 1705 GraphPrintCheckerState->isBadCall(N) || 1706 GraphPrintCheckerState->isUndefArg(N)) 1707 return "color=\"red\",style=\"filled\""; 1708 1709 if (GraphPrintCheckerState->isNoReturnCall(N)) 1710 return "color=\"blue\",style=\"filled\""; 1711 #endif 1712 return ""; 1713 } 1714 1715 static std::string getNodeLabel(const ExplodedNode *N, void*){ 1716 1717 std::string sbuf; 1718 llvm::raw_string_ostream Out(sbuf); 1719 1720 // Program Location. 1721 ProgramPoint Loc = N->getLocation(); 1722 1723 switch (Loc.getKind()) { 1724 case ProgramPoint::BlockEntranceKind: 1725 Out << "Block Entrance: B" 1726 << cast<BlockEntrance>(Loc).getBlock()->getBlockID(); 1727 break; 1728 1729 case ProgramPoint::BlockExitKind: 1730 assert (false); 1731 break; 1732 1733 case ProgramPoint::CallEnterKind: 1734 Out << "CallEnter"; 1735 break; 1736 1737 case ProgramPoint::CallExitKind: 1738 Out << "CallExit"; 1739 break; 1740 1741 default: { 1742 if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) { 1743 const Stmt *S = L->getStmt(); 1744 SourceLocation SLoc = S->getLocStart(); 1745 1746 Out << S->getStmtClassName() << ' ' << (void*) S << ' '; 1747 LangOptions LO; // FIXME. 1748 S->printPretty(Out, 0, PrintingPolicy(LO)); 1749 1750 if (SLoc.isFileID()) { 1751 Out << "\\lline=" 1752 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 1753 << " col=" 1754 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc) 1755 << "\\l"; 1756 } 1757 1758 if (isa<PreStmt>(Loc)) 1759 Out << "\\lPreStmt\\l;"; 1760 else if (isa<PostLoad>(Loc)) 1761 Out << "\\lPostLoad\\l;"; 1762 else if (isa<PostStore>(Loc)) 1763 Out << "\\lPostStore\\l"; 1764 else if (isa<PostLValue>(Loc)) 1765 Out << "\\lPostLValue\\l"; 1766 1767 #if 0 1768 // FIXME: Replace with a general scheme to determine 1769 // the name of the check. 1770 if (GraphPrintCheckerState->isImplicitNullDeref(N)) 1771 Out << "\\|Implicit-Null Dereference.\\l"; 1772 else if (GraphPrintCheckerState->isExplicitNullDeref(N)) 1773 Out << "\\|Explicit-Null Dereference.\\l"; 1774 else if (GraphPrintCheckerState->isUndefDeref(N)) 1775 Out << "\\|Dereference of undefialied value.\\l"; 1776 else if (GraphPrintCheckerState->isUndefStore(N)) 1777 Out << "\\|Store to Undefined Loc."; 1778 else if (GraphPrintCheckerState->isUndefResult(N)) 1779 Out << "\\|Result of operation is undefined."; 1780 else if (GraphPrintCheckerState->isNoReturnCall(N)) 1781 Out << "\\|Call to function marked \"noreturn\"."; 1782 else if (GraphPrintCheckerState->isBadCall(N)) 1783 Out << "\\|Call to NULL/Undefined."; 1784 else if (GraphPrintCheckerState->isUndefArg(N)) 1785 Out << "\\|Argument in call is undefined"; 1786 #endif 1787 1788 break; 1789 } 1790 1791 const BlockEdge &E = cast<BlockEdge>(Loc); 1792 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" 1793 << E.getDst()->getBlockID() << ')'; 1794 1795 if (const Stmt *T = E.getSrc()->getTerminator()) { 1796 1797 SourceLocation SLoc = T->getLocStart(); 1798 1799 Out << "\\|Terminator: "; 1800 LangOptions LO; // FIXME. 1801 E.getSrc()->printTerminator(Out, LO); 1802 1803 if (SLoc.isFileID()) { 1804 Out << "\\lline=" 1805 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 1806 << " col=" 1807 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc); 1808 } 1809 1810 if (isa<SwitchStmt>(T)) { 1811 const Stmt *Label = E.getDst()->getLabel(); 1812 1813 if (Label) { 1814 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 1815 Out << "\\lcase "; 1816 LangOptions LO; // FIXME. 1817 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO)); 1818 1819 if (const Stmt *RHS = C->getRHS()) { 1820 Out << " .. "; 1821 RHS->printPretty(Out, 0, PrintingPolicy(LO)); 1822 } 1823 1824 Out << ":"; 1825 } 1826 else { 1827 assert (isa<DefaultStmt>(Label)); 1828 Out << "\\ldefault:"; 1829 } 1830 } 1831 else 1832 Out << "\\l(implicit) default:"; 1833 } 1834 else if (isa<IndirectGotoStmt>(T)) { 1835 // FIXME 1836 } 1837 else { 1838 Out << "\\lCondition: "; 1839 if (*E.getSrc()->succ_begin() == E.getDst()) 1840 Out << "true"; 1841 else 1842 Out << "false"; 1843 } 1844 1845 Out << "\\l"; 1846 } 1847 1848 #if 0 1849 // FIXME: Replace with a general scheme to determine 1850 // the name of the check. 1851 if (GraphPrintCheckerState->isUndefControlFlow(N)) { 1852 Out << "\\|Control-flow based on\\lUndefined value.\\l"; 1853 } 1854 #endif 1855 } 1856 } 1857 1858 const ProgramState *state = N->getState(); 1859 Out << "\\|StateID: " << (void*) state 1860 << " NodeID: " << (void*) N << "\\|"; 1861 state->printDOT(Out); 1862 1863 Out << "\\l"; 1864 1865 if (const ProgramPointTag *tag = Loc.getTag()) { 1866 Out << "\\|Tag: " << tag->getTagDescription(); 1867 Out << "\\l"; 1868 } 1869 return Out.str(); 1870 } 1871 }; 1872 } // end llvm namespace 1873 #endif 1874 1875 #ifndef NDEBUG 1876 template <typename ITERATOR> 1877 ExplodedNode *GetGraphNode(ITERATOR I) { return *I; } 1878 1879 template <> ExplodedNode* 1880 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator> 1881 (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) { 1882 return I->first; 1883 } 1884 #endif 1885 1886 void ExprEngine::ViewGraph(bool trim) { 1887 #ifndef NDEBUG 1888 if (trim) { 1889 std::vector<ExplodedNode*> Src; 1890 1891 // Flush any outstanding reports to make sure we cover all the nodes. 1892 // This does not cause them to get displayed. 1893 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) 1894 const_cast<BugType*>(*I)->FlushReports(BR); 1895 1896 // Iterate through the reports and get their nodes. 1897 for (BugReporter::EQClasses_iterator 1898 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 1899 BugReportEquivClass& EQ = *EI; 1900 const BugReport &R = **EQ.begin(); 1901 ExplodedNode *N = const_cast<ExplodedNode*>(R.getErrorNode()); 1902 if (N) Src.push_back(N); 1903 } 1904 1905 ViewGraph(&Src[0], &Src[0]+Src.size()); 1906 } 1907 else { 1908 GraphPrintCheckerState = this; 1909 GraphPrintSourceManager = &getContext().getSourceManager(); 1910 1911 llvm::ViewGraph(*G.roots_begin(), "ExprEngine"); 1912 1913 GraphPrintCheckerState = NULL; 1914 GraphPrintSourceManager = NULL; 1915 } 1916 #endif 1917 } 1918 1919 void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) { 1920 #ifndef NDEBUG 1921 GraphPrintCheckerState = this; 1922 GraphPrintSourceManager = &getContext().getSourceManager(); 1923 1924 std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first); 1925 1926 if (!TrimmedG.get()) 1927 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 1928 else 1929 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine"); 1930 1931 GraphPrintCheckerState = NULL; 1932 GraphPrintSourceManager = NULL; 1933 #endif 1934 } 1935