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