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