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