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