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