ExprEngineCallAndReturn.cpp revision 73f0563009a6715a5d3d41f664f5bfab5096d51f
1//=-- ExprEngineCallAndReturn.cpp - Support for call/return -----*- 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 ExprEngine's support for calls and returns. 11// 12//===----------------------------------------------------------------------===// 13 14#define DEBUG_TYPE "ExprEngine" 15 16#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 17#include "clang/AST/CXXInheritance.h" 18#include "clang/AST/DeclCXX.h" 19#include "clang/AST/ParentMap.h" 20#include "clang/Analysis/Analyses/LiveVariables.h" 21#include "clang/StaticAnalyzer/Core/CheckerManager.h" 22#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 23#include "llvm/ADT/SmallSet.h" 24#include "llvm/ADT/Statistic.h" 25#include "llvm/Support/SaveAndRestore.h" 26 27using namespace clang; 28using namespace ento; 29 30STATISTIC(NumOfDynamicDispatchPathSplits, 31 "The # of times we split the path due to imprecise dynamic dispatch info"); 32 33STATISTIC(NumInlinedCalls, 34 "The # of times we inlined a call"); 35 36STATISTIC(NumReachedInlineCountMax, 37 "The # of times we reached inline count maximum"); 38 39void ExprEngine::processCallEnter(CallEnter CE, ExplodedNode *Pred) { 40 // Get the entry block in the CFG of the callee. 41 const StackFrameContext *calleeCtx = CE.getCalleeContext(); 42 const CFG *CalleeCFG = calleeCtx->getCFG(); 43 const CFGBlock *Entry = &(CalleeCFG->getEntry()); 44 45 // Validate the CFG. 46 assert(Entry->empty()); 47 assert(Entry->succ_size() == 1); 48 49 // Get the solitary sucessor. 50 const CFGBlock *Succ = *(Entry->succ_begin()); 51 52 // Construct an edge representing the starting location in the callee. 53 BlockEdge Loc(Entry, Succ, calleeCtx); 54 55 ProgramStateRef state = Pred->getState(); 56 57 // Construct a new node and add it to the worklist. 58 bool isNew; 59 ExplodedNode *Node = G.getNode(Loc, state, false, &isNew); 60 Node->addPredecessor(Pred, G); 61 if (isNew) 62 Engine.getWorkList()->enqueue(Node); 63} 64 65// Find the last statement on the path to the exploded node and the 66// corresponding Block. 67static std::pair<const Stmt*, 68 const CFGBlock*> getLastStmt(const ExplodedNode *Node) { 69 const Stmt *S = 0; 70 const CFGBlock *Blk = 0; 71 const StackFrameContext *SF = 72 Node->getLocation().getLocationContext()->getCurrentStackFrame(); 73 74 // Back up through the ExplodedGraph until we reach a statement node in this 75 // stack frame. 76 while (Node) { 77 const ProgramPoint &PP = Node->getLocation(); 78 79 if (PP.getLocationContext()->getCurrentStackFrame() == SF) { 80 if (const StmtPoint *SP = dyn_cast<StmtPoint>(&PP)) { 81 S = SP->getStmt(); 82 break; 83 } else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&PP)) { 84 S = CEE->getCalleeContext()->getCallSite(); 85 if (S) 86 break; 87 88 // If there is no statement, this is an implicitly-generated call. 89 // We'll walk backwards over it and then continue the loop to find 90 // an actual statement. 91 const CallEnter *CE; 92 do { 93 Node = Node->getFirstPred(); 94 CE = Node->getLocationAs<CallEnter>(); 95 } while (!CE || CE->getCalleeContext() != CEE->getCalleeContext()); 96 97 // Continue searching the graph. 98 } else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&PP)) { 99 Blk = BE->getSrc(); 100 } 101 } else if (const CallEnter *CE = dyn_cast<CallEnter>(&PP)) { 102 // If we reached the CallEnter for this function, it has no statements. 103 if (CE->getCalleeContext() == SF) 104 break; 105 } 106 107 if (Node->pred_empty()) 108 return std::pair<const Stmt*, const CFGBlock*>((Stmt*)0, (CFGBlock*)0); 109 110 Node = *Node->pred_begin(); 111 } 112 113 return std::pair<const Stmt*, const CFGBlock*>(S, Blk); 114} 115 116/// Adjusts a return value when the called function's return type does not 117/// match the caller's expression type. This can happen when a dynamic call 118/// is devirtualized, and the overridding method has a covariant (more specific) 119/// return type than the parent's method. For C++ objects, this means we need 120/// to add base casts. 121static SVal adjustReturnValue(SVal V, QualType ExpectedTy, QualType ActualTy, 122 StoreManager &StoreMgr) { 123 // For now, the only adjustments we handle apply only to locations. 124 if (!isa<Loc>(V)) 125 return V; 126 127 // If the types already match, don't do any unnecessary work. 128 ExpectedTy = ExpectedTy.getCanonicalType(); 129 ActualTy = ActualTy.getCanonicalType(); 130 if (ExpectedTy == ActualTy) 131 return V; 132 133 // No adjustment is needed between Objective-C pointer types. 134 if (ExpectedTy->isObjCObjectPointerType() && 135 ActualTy->isObjCObjectPointerType()) 136 return V; 137 138 // C++ object pointers may need "derived-to-base" casts. 139 const CXXRecordDecl *ExpectedClass = ExpectedTy->getPointeeCXXRecordDecl(); 140 const CXXRecordDecl *ActualClass = ActualTy->getPointeeCXXRecordDecl(); 141 if (ExpectedClass && ActualClass) { 142 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 143 /*DetectVirtual=*/false); 144 if (ActualClass->isDerivedFrom(ExpectedClass, Paths) && 145 !Paths.isAmbiguous(ActualTy->getCanonicalTypeUnqualified())) { 146 return StoreMgr.evalDerivedToBase(V, Paths.front()); 147 } 148 } 149 150 // Unfortunately, Objective-C does not enforce that overridden methods have 151 // covariant return types, so we can't assert that that never happens. 152 // Be safe and return UnknownVal(). 153 return UnknownVal(); 154} 155 156void ExprEngine::removeDeadOnEndOfFunction(NodeBuilderContext& BC, 157 ExplodedNode *Pred, 158 ExplodedNodeSet &Dst) { 159 // Find the last statement in the function and the corresponding basic block. 160 const Stmt *LastSt = 0; 161 const CFGBlock *Blk = 0; 162 llvm::tie(LastSt, Blk) = getLastStmt(Pred); 163 if (!Blk || !LastSt) { 164 Dst.Add(Pred); 165 return; 166 } 167 168 // Here, we destroy the current location context. We use the current 169 // function's entire body as a diagnostic statement, with which the program 170 // point will be associated. However, we only want to use LastStmt as a 171 // reference for what to clean up if it's a ReturnStmt; otherwise, everything 172 // is dead. 173 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC); 174 const LocationContext *LCtx = Pred->getLocationContext(); 175 removeDead(Pred, Dst, dyn_cast<ReturnStmt>(LastSt), LCtx, 176 LCtx->getAnalysisDeclContext()->getBody(), 177 ProgramPoint::PostStmtPurgeDeadSymbolsKind); 178} 179 180static bool wasDifferentDeclUsedForInlining(CallEventRef<> Call, 181 const StackFrameContext *calleeCtx) { 182 const Decl *RuntimeCallee = calleeCtx->getDecl(); 183 const Decl *StaticDecl = Call->getDecl(); 184 assert(RuntimeCallee); 185 if (!StaticDecl) 186 return true; 187 return RuntimeCallee->getCanonicalDecl() != StaticDecl->getCanonicalDecl(); 188} 189 190/// The call exit is simulated with a sequence of nodes, which occur between 191/// CallExitBegin and CallExitEnd. The following operations occur between the 192/// two program points: 193/// 1. CallExitBegin (triggers the start of call exit sequence) 194/// 2. Bind the return value 195/// 3. Run Remove dead bindings to clean up the dead symbols from the callee. 196/// 4. CallExitEnd (switch to the caller context) 197/// 5. PostStmt<CallExpr> 198void ExprEngine::processCallExit(ExplodedNode *CEBNode) { 199 // Step 1 CEBNode was generated before the call. 200 201 const StackFrameContext *calleeCtx = 202 CEBNode->getLocationContext()->getCurrentStackFrame(); 203 204 // The parent context might not be a stack frame, so make sure we 205 // look up the first enclosing stack frame. 206 const StackFrameContext *callerCtx = 207 calleeCtx->getParent()->getCurrentStackFrame(); 208 209 const Stmt *CE = calleeCtx->getCallSite(); 210 ProgramStateRef state = CEBNode->getState(); 211 // Find the last statement in the function and the corresponding basic block. 212 const Stmt *LastSt = 0; 213 const CFGBlock *Blk = 0; 214 llvm::tie(LastSt, Blk) = getLastStmt(CEBNode); 215 216 // Generate a CallEvent /before/ cleaning the state, so that we can get the 217 // correct value for 'this' (if necessary). 218 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 219 CallEventRef<> Call = CEMgr.getCaller(calleeCtx, state); 220 221 // Step 2: generate node with bound return value: CEBNode -> BindedRetNode. 222 223 // If the callee returns an expression, bind its value to CallExpr. 224 if (CE) { 225 if (const ReturnStmt *RS = dyn_cast_or_null<ReturnStmt>(LastSt)) { 226 const LocationContext *LCtx = CEBNode->getLocationContext(); 227 SVal V = state->getSVal(RS, LCtx); 228 229 // Ensure that the return type matches the type of the returned Expr. 230 if (wasDifferentDeclUsedForInlining(Call, calleeCtx)) { 231 QualType ReturnedTy = 232 CallEvent::getDeclaredResultType(calleeCtx->getDecl()); 233 if (!ReturnedTy.isNull()) { 234 if (const Expr *Ex = dyn_cast<Expr>(CE)) { 235 V = adjustReturnValue(V, Ex->getType(), ReturnedTy, 236 getStoreManager()); 237 } 238 } 239 } 240 241 state = state->BindExpr(CE, callerCtx, V); 242 } 243 244 // Bind the constructed object value to CXXConstructExpr. 245 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) { 246 loc::MemRegionVal This = 247 svalBuilder.getCXXThis(CCE->getConstructor()->getParent(), calleeCtx); 248 SVal ThisV = state->getSVal(This); 249 250 // If the constructed object is a prvalue, get its bindings. 251 // Note that we have to be careful here because constructors embedded 252 // in DeclStmts are not marked as lvalues. 253 if (!CCE->isGLValue()) 254 if (const MemRegion *MR = ThisV.getAsRegion()) 255 if (isa<CXXTempObjectRegion>(MR)) 256 ThisV = state->getSVal(cast<Loc>(ThisV)); 257 258 state = state->BindExpr(CCE, callerCtx, ThisV); 259 } 260 } 261 262 // Step 3: BindedRetNode -> CleanedNodes 263 // If we can find a statement and a block in the inlined function, run remove 264 // dead bindings before returning from the call. This is important to ensure 265 // that we report the issues such as leaks in the stack contexts in which 266 // they occurred. 267 ExplodedNodeSet CleanedNodes; 268 if (LastSt && Blk && AMgr.options.AnalysisPurgeOpt != PurgeNone) { 269 static SimpleProgramPointTag retValBind("ExprEngine : Bind Return Value"); 270 PostStmt Loc(LastSt, calleeCtx, &retValBind); 271 bool isNew; 272 ExplodedNode *BindedRetNode = G.getNode(Loc, state, false, &isNew); 273 BindedRetNode->addPredecessor(CEBNode, G); 274 if (!isNew) 275 return; 276 277 NodeBuilderContext Ctx(getCoreEngine(), Blk, BindedRetNode); 278 currBldrCtx = &Ctx; 279 // Here, we call the Symbol Reaper with 0 statement and callee location 280 // context, telling it to clean up everything in the callee's context 281 // (and its children). We use the callee's function body as a diagnostic 282 // statement, with which the program point will be associated. 283 removeDead(BindedRetNode, CleanedNodes, 0, calleeCtx, 284 calleeCtx->getAnalysisDeclContext()->getBody(), 285 ProgramPoint::PostStmtPurgeDeadSymbolsKind); 286 currBldrCtx = 0; 287 } else { 288 CleanedNodes.Add(CEBNode); 289 } 290 291 for (ExplodedNodeSet::iterator I = CleanedNodes.begin(), 292 E = CleanedNodes.end(); I != E; ++I) { 293 294 // Step 4: Generate the CallExit and leave the callee's context. 295 // CleanedNodes -> CEENode 296 CallExitEnd Loc(calleeCtx, callerCtx); 297 bool isNew; 298 ProgramStateRef CEEState = (*I == CEBNode) ? state : (*I)->getState(); 299 ExplodedNode *CEENode = G.getNode(Loc, CEEState, false, &isNew); 300 CEENode->addPredecessor(*I, G); 301 if (!isNew) 302 return; 303 304 // Step 5: Perform the post-condition check of the CallExpr and enqueue the 305 // result onto the work list. 306 // CEENode -> Dst -> WorkList 307 NodeBuilderContext Ctx(Engine, calleeCtx->getCallSiteBlock(), CEENode); 308 SaveAndRestore<const NodeBuilderContext*> NBCSave(currBldrCtx, 309 &Ctx); 310 SaveAndRestore<unsigned> CBISave(currStmtIdx, calleeCtx->getIndex()); 311 312 CallEventRef<> UpdatedCall = Call.cloneWithState(CEEState); 313 314 ExplodedNodeSet DstPostCall; 315 getCheckerManager().runCheckersForPostCall(DstPostCall, CEENode, 316 *UpdatedCall, *this, 317 /*WasInlined=*/true); 318 319 ExplodedNodeSet Dst; 320 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) { 321 getCheckerManager().runCheckersForPostObjCMessage(Dst, DstPostCall, *Msg, 322 *this, 323 /*WasInlined=*/true); 324 } else if (CE) { 325 getCheckerManager().runCheckersForPostStmt(Dst, DstPostCall, CE, 326 *this, /*WasInlined=*/true); 327 } else { 328 Dst.insert(DstPostCall); 329 } 330 331 // Enqueue the next element in the block. 332 for (ExplodedNodeSet::iterator PSI = Dst.begin(), PSE = Dst.end(); 333 PSI != PSE; ++PSI) { 334 Engine.getWorkList()->enqueue(*PSI, calleeCtx->getCallSiteBlock(), 335 calleeCtx->getIndex()+1); 336 } 337 } 338} 339 340void ExprEngine::examineStackFrames(const Decl *D, const LocationContext *LCtx, 341 bool &IsRecursive, unsigned &StackDepth) { 342 IsRecursive = false; 343 StackDepth = 0; 344 345 while (LCtx) { 346 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LCtx)) { 347 const Decl *DI = SFC->getDecl(); 348 349 // Mark recursive (and mutually recursive) functions and always count 350 // them when measuring the stack depth. 351 if (DI == D) { 352 IsRecursive = true; 353 ++StackDepth; 354 LCtx = LCtx->getParent(); 355 continue; 356 } 357 358 // Do not count the small functions when determining the stack depth. 359 AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(DI); 360 const CFG *CalleeCFG = CalleeADC->getCFG(); 361 if (CalleeCFG->getNumBlockIDs() > AMgr.options.getAlwaysInlineSize()) 362 ++StackDepth; 363 } 364 LCtx = LCtx->getParent(); 365 } 366 367} 368 369static bool IsInStdNamespace(const FunctionDecl *FD) { 370 const DeclContext *DC = FD->getEnclosingNamespaceContext(); 371 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC); 372 if (!ND) 373 return false; 374 375 while (const DeclContext *Parent = ND->getParent()) { 376 if (!isa<NamespaceDecl>(Parent)) 377 break; 378 ND = cast<NamespaceDecl>(Parent); 379 } 380 381 return ND->getName() == "std"; 382} 383 384// Determine if we should inline the call. 385bool ExprEngine::shouldInlineDecl(const Decl *D, ExplodedNode *Pred) { 386 AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D); 387 const CFG *CalleeCFG = CalleeADC->getCFG(); 388 389 // It is possible that the CFG cannot be constructed. 390 // Be safe, and check if the CalleeCFG is valid. 391 if (!CalleeCFG) 392 return false; 393 394 bool IsRecursive = false; 395 unsigned StackDepth = 0; 396 examineStackFrames(D, Pred->getLocationContext(), IsRecursive, StackDepth); 397 if ((StackDepth >= AMgr.options.InlineMaxStackDepth) && 398 ((CalleeCFG->getNumBlockIDs() > AMgr.options.getAlwaysInlineSize()) 399 || IsRecursive)) 400 return false; 401 402 if (Engine.FunctionSummaries->hasReachedMaxBlockCount(D)) 403 return false; 404 405 if (CalleeCFG->getNumBlockIDs() > AMgr.options.InlineMaxFunctionSize) 406 return false; 407 408 // Do not inline variadic calls (for now). 409 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 410 if (BD->isVariadic()) 411 return false; 412 } 413 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 414 if (FD->isVariadic()) 415 return false; 416 } 417 418 if (getContext().getLangOpts().CPlusPlus) { 419 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 420 // Conditionally allow the inlining of template functions. 421 if (!AMgr.options.mayInlineTemplateFunctions()) 422 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate) 423 return false; 424 425 // Conditionally allow the inlining of C++ standard library functions. 426 if (!AMgr.options.mayInlineCXXStandardLibrary()) 427 if (getContext().getSourceManager().isInSystemHeader(FD->getLocation())) 428 if (IsInStdNamespace(FD)) 429 return false; 430 } 431 } 432 433 // It is possible that the live variables analysis cannot be 434 // run. If so, bail out. 435 if (!CalleeADC->getAnalysis<RelaxedLiveVariables>()) 436 return false; 437 438 if (Engine.FunctionSummaries->getNumTimesInlined(D) > 439 AMgr.options.getMaxTimesInlineLarge() && 440 CalleeCFG->getNumBlockIDs() > 13) { 441 NumReachedInlineCountMax++; 442 return false; 443 } 444 Engine.FunctionSummaries->bumpNumTimesInlined(D); 445 446 return true; 447} 448 449// The GDM component containing the dynamic dispatch bifurcation info. When 450// the exact type of the receiver is not known, we want to explore both paths - 451// one on which we do inline it and the other one on which we don't. This is 452// done to ensure we do not drop coverage. 453// This is the map from the receiver region to a bool, specifying either we 454// consider this region's information precise or not along the given path. 455namespace { 456 enum DynamicDispatchMode { 457 DynamicDispatchModeInlined = 1, 458 DynamicDispatchModeConservative 459 }; 460} 461REGISTER_TRAIT_WITH_PROGRAMSTATE(DynamicDispatchBifurcationMap, 462 CLANG_ENTO_PROGRAMSTATE_MAP(const MemRegion *, 463 unsigned)) 464 465bool ExprEngine::inlineCall(const CallEvent &Call, const Decl *D, 466 NodeBuilder &Bldr, ExplodedNode *Pred, 467 ProgramStateRef State) { 468 assert(D); 469 470 const LocationContext *CurLC = Pred->getLocationContext(); 471 const StackFrameContext *CallerSFC = CurLC->getCurrentStackFrame(); 472 const LocationContext *ParentOfCallee = 0; 473 474 AnalyzerOptions &Opts = getAnalysisManager().options; 475 476 // FIXME: Refactor this check into a hypothetical CallEvent::canInline. 477 switch (Call.getKind()) { 478 case CE_Function: 479 break; 480 case CE_CXXMember: 481 case CE_CXXMemberOperator: 482 if (!Opts.mayInlineCXXMemberFunction(CIMK_MemberFunctions)) 483 return false; 484 break; 485 case CE_CXXConstructor: { 486 if (!Opts.mayInlineCXXMemberFunction(CIMK_Constructors)) 487 return false; 488 489 const CXXConstructorCall &Ctor = cast<CXXConstructorCall>(Call); 490 491 // FIXME: We don't handle constructors or destructors for arrays properly. 492 const MemRegion *Target = Ctor.getCXXThisVal().getAsRegion(); 493 if (Target && isa<ElementRegion>(Target)) 494 return false; 495 496 // FIXME: This is a hack. We don't use the correct region for a new 497 // expression, so if we inline the constructor its result will just be 498 // thrown away. This short-term hack is tracked in <rdar://problem/12180598> 499 // and the longer-term possible fix is discussed in PR12014. 500 const CXXConstructExpr *CtorExpr = Ctor.getOriginExpr(); 501 if (const Stmt *Parent = CurLC->getParentMap().getParent(CtorExpr)) 502 if (isa<CXXNewExpr>(Parent)) 503 return false; 504 505 // Inlining constructors requires including initializers in the CFG. 506 const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext(); 507 assert(ADC->getCFGBuildOptions().AddInitializers && "No CFG initializers"); 508 (void)ADC; 509 510 // If the destructor is trivial, it's always safe to inline the constructor. 511 if (Ctor.getDecl()->getParent()->hasTrivialDestructor()) 512 break; 513 514 // For other types, only inline constructors if destructor inlining is 515 // also enabled. 516 if (!Opts.mayInlineCXXMemberFunction(CIMK_Destructors)) 517 return false; 518 519 // FIXME: This is a hack. We don't handle temporary destructors 520 // right now, so we shouldn't inline their constructors. 521 if (CtorExpr->getConstructionKind() == CXXConstructExpr::CK_Complete) 522 if (!Target || !isa<DeclRegion>(Target)) 523 return false; 524 525 break; 526 } 527 case CE_CXXDestructor: { 528 if (!Opts.mayInlineCXXMemberFunction(CIMK_Destructors)) 529 return false; 530 531 // Inlining destructors requires building the CFG correctly. 532 const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext(); 533 assert(ADC->getCFGBuildOptions().AddImplicitDtors && "No CFG destructors"); 534 (void)ADC; 535 536 const CXXDestructorCall &Dtor = cast<CXXDestructorCall>(Call); 537 538 // FIXME: We don't handle constructors or destructors for arrays properly. 539 const MemRegion *Target = Dtor.getCXXThisVal().getAsRegion(); 540 if (Target && isa<ElementRegion>(Target)) 541 return false; 542 543 break; 544 } 545 case CE_CXXAllocator: 546 // Do not inline allocators until we model deallocators. 547 // This is unfortunate, but basically necessary for smart pointers and such. 548 return false; 549 case CE_Block: { 550 const BlockDataRegion *BR = cast<BlockCall>(Call).getBlockRegion(); 551 assert(BR && "If we have the block definition we should have its region"); 552 AnalysisDeclContext *BlockCtx = AMgr.getAnalysisDeclContext(D); 553 ParentOfCallee = BlockCtx->getBlockInvocationContext(CallerSFC, 554 cast<BlockDecl>(D), 555 BR); 556 break; 557 } 558 case CE_ObjCMessage: 559 if (!Opts.mayInlineObjCMethod()) 560 return false; 561 AnalyzerOptions &Options = getAnalysisManager().options; 562 if (!(Options.getIPAMode() == DynamicDispatch || 563 Options.getIPAMode() == DynamicDispatchBifurcate)) 564 return false; 565 break; 566 } 567 568 if (!shouldInlineDecl(D, Pred)) 569 return false; 570 571 if (!ParentOfCallee) 572 ParentOfCallee = CallerSFC; 573 574 // This may be NULL, but that's fine. 575 const Expr *CallE = Call.getOriginExpr(); 576 577 // Construct a new stack frame for the callee. 578 AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D); 579 const StackFrameContext *CalleeSFC = 580 CalleeADC->getStackFrame(ParentOfCallee, CallE, 581 currBldrCtx->getBlock(), 582 currStmtIdx); 583 584 CallEnter Loc(CallE, CalleeSFC, CurLC); 585 586 // Construct a new state which contains the mapping from actual to 587 // formal arguments. 588 State = State->enterStackFrame(Call, CalleeSFC); 589 590 bool isNew; 591 if (ExplodedNode *N = G.getNode(Loc, State, false, &isNew)) { 592 N->addPredecessor(Pred, G); 593 if (isNew) 594 Engine.getWorkList()->enqueue(N); 595 } 596 597 // If we decided to inline the call, the successor has been manually 598 // added onto the work list so remove it from the node builder. 599 Bldr.takeNodes(Pred); 600 601 NumInlinedCalls++; 602 603 // Mark the decl as visited. 604 if (VisitedCallees) 605 VisitedCallees->insert(D); 606 607 return true; 608} 609 610static ProgramStateRef getInlineFailedState(ProgramStateRef State, 611 const Stmt *CallE) { 612 const void *ReplayState = State->get<ReplayWithoutInlining>(); 613 if (!ReplayState) 614 return 0; 615 616 assert(ReplayState == CallE && "Backtracked to the wrong call."); 617 (void)CallE; 618 619 return State->remove<ReplayWithoutInlining>(); 620} 621 622void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, 623 ExplodedNodeSet &dst) { 624 // Perform the previsit of the CallExpr. 625 ExplodedNodeSet dstPreVisit; 626 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this); 627 628 // Get the call in its initial state. We use this as a template to perform 629 // all the checks. 630 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 631 CallEventRef<> CallTemplate 632 = CEMgr.getSimpleCall(CE, Pred->getState(), Pred->getLocationContext()); 633 634 // Evaluate the function call. We try each of the checkers 635 // to see if the can evaluate the function call. 636 ExplodedNodeSet dstCallEvaluated; 637 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end(); 638 I != E; ++I) { 639 evalCall(dstCallEvaluated, *I, *CallTemplate); 640 } 641 642 // Finally, perform the post-condition check of the CallExpr and store 643 // the created nodes in 'Dst'. 644 // Note that if the call was inlined, dstCallEvaluated will be empty. 645 // The post-CallExpr check will occur in processCallExit. 646 getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE, 647 *this); 648} 649 650void ExprEngine::evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, 651 const CallEvent &Call) { 652 // WARNING: At this time, the state attached to 'Call' may be older than the 653 // state in 'Pred'. This is a minor optimization since CheckerManager will 654 // use an updated CallEvent instance when calling checkers, but if 'Call' is 655 // ever used directly in this function all callers should be updated to pass 656 // the most recent state. (It is probably not worth doing the work here since 657 // for some callers this will not be necessary.) 658 659 // Run any pre-call checks using the generic call interface. 660 ExplodedNodeSet dstPreVisit; 661 getCheckerManager().runCheckersForPreCall(dstPreVisit, Pred, Call, *this); 662 663 // Actually evaluate the function call. We try each of the checkers 664 // to see if the can evaluate the function call, and get a callback at 665 // defaultEvalCall if all of them fail. 666 ExplodedNodeSet dstCallEvaluated; 667 getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, dstPreVisit, 668 Call, *this); 669 670 // Finally, run any post-call checks. 671 getCheckerManager().runCheckersForPostCall(Dst, dstCallEvaluated, 672 Call, *this); 673} 674 675ProgramStateRef ExprEngine::bindReturnValue(const CallEvent &Call, 676 const LocationContext *LCtx, 677 ProgramStateRef State) { 678 const Expr *E = Call.getOriginExpr(); 679 if (!E) 680 return State; 681 682 // Some method families have known return values. 683 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(&Call)) { 684 switch (Msg->getMethodFamily()) { 685 default: 686 break; 687 case OMF_autorelease: 688 case OMF_retain: 689 case OMF_self: { 690 // These methods return their receivers. 691 return State->BindExpr(E, LCtx, Msg->getReceiverSVal()); 692 } 693 } 694 } else if (const CXXConstructorCall *C = dyn_cast<CXXConstructorCall>(&Call)){ 695 return State->BindExpr(E, LCtx, C->getCXXThisVal()); 696 } 697 698 // Conjure a symbol if the return value is unknown. 699 QualType ResultTy = Call.getResultType(); 700 SValBuilder &SVB = getSValBuilder(); 701 unsigned Count = currBldrCtx->blockCount(); 702 SVal R = SVB.conjureSymbolVal(0, E, LCtx, ResultTy, Count); 703 return State->BindExpr(E, LCtx, R); 704} 705 706// Conservatively evaluate call by invalidating regions and binding 707// a conjured return value. 708void ExprEngine::conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr, 709 ExplodedNode *Pred, ProgramStateRef State) { 710 State = Call.invalidateRegions(currBldrCtx->blockCount(), State); 711 State = bindReturnValue(Call, Pred->getLocationContext(), State); 712 713 // And make the result node. 714 Bldr.generateNode(Call.getProgramPoint(), State, Pred); 715} 716 717void ExprEngine::defaultEvalCall(NodeBuilder &Bldr, ExplodedNode *Pred, 718 const CallEvent &CallTemplate) { 719 // Make sure we have the most recent state attached to the call. 720 ProgramStateRef State = Pred->getState(); 721 CallEventRef<> Call = CallTemplate.cloneWithState(State); 722 723 if (HowToInline == Inline_None) { 724 conservativeEvalCall(*Call, Bldr, Pred, State); 725 return; 726 } 727 // Try to inline the call. 728 // The origin expression here is just used as a kind of checksum; 729 // this should still be safe even for CallEvents that don't come from exprs. 730 const Expr *E = Call->getOriginExpr(); 731 ProgramStateRef InlinedFailedState = getInlineFailedState(State, E); 732 733 if (InlinedFailedState) { 734 // If we already tried once and failed, make sure we don't retry later. 735 State = InlinedFailedState; 736 } else { 737 RuntimeDefinition RD = Call->getRuntimeDefinition(); 738 const Decl *D = RD.getDecl(); 739 if (D) { 740 if (RD.mayHaveOtherDefinitions()) { 741 AnalyzerOptions &Options = getAnalysisManager().options; 742 743 // Explore with and without inlining the call. 744 if (Options.getIPAMode() == DynamicDispatchBifurcate) { 745 BifurcateCall(RD.getDispatchRegion(), *Call, D, Bldr, Pred); 746 return; 747 } 748 749 // Don't inline if we're not in any dynamic dispatch mode. 750 if (Options.getIPAMode() != DynamicDispatch) { 751 conservativeEvalCall(*Call, Bldr, Pred, State); 752 return; 753 } 754 } 755 756 // We are not bifurcating and we do have a Decl, so just inline. 757 if (inlineCall(*Call, D, Bldr, Pred, State)) 758 return; 759 } 760 } 761 762 // If we can't inline it, handle the return value and invalidate the regions. 763 conservativeEvalCall(*Call, Bldr, Pred, State); 764} 765 766void ExprEngine::BifurcateCall(const MemRegion *BifurReg, 767 const CallEvent &Call, const Decl *D, 768 NodeBuilder &Bldr, ExplodedNode *Pred) { 769 assert(BifurReg); 770 BifurReg = BifurReg->StripCasts(); 771 772 // Check if we've performed the split already - note, we only want 773 // to split the path once per memory region. 774 ProgramStateRef State = Pred->getState(); 775 const unsigned *BState = 776 State->get<DynamicDispatchBifurcationMap>(BifurReg); 777 if (BState) { 778 // If we are on "inline path", keep inlining if possible. 779 if (*BState == DynamicDispatchModeInlined) 780 if (inlineCall(Call, D, Bldr, Pred, State)) 781 return; 782 // If inline failed, or we are on the path where we assume we 783 // don't have enough info about the receiver to inline, conjure the 784 // return value and invalidate the regions. 785 conservativeEvalCall(Call, Bldr, Pred, State); 786 return; 787 } 788 789 // If we got here, this is the first time we process a message to this 790 // region, so split the path. 791 ProgramStateRef IState = 792 State->set<DynamicDispatchBifurcationMap>(BifurReg, 793 DynamicDispatchModeInlined); 794 inlineCall(Call, D, Bldr, Pred, IState); 795 796 ProgramStateRef NoIState = 797 State->set<DynamicDispatchBifurcationMap>(BifurReg, 798 DynamicDispatchModeConservative); 799 conservativeEvalCall(Call, Bldr, Pred, NoIState); 800 801 NumOfDynamicDispatchPathSplits++; 802 return; 803} 804 805 806void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred, 807 ExplodedNodeSet &Dst) { 808 809 ExplodedNodeSet dstPreVisit; 810 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this); 811 812 StmtNodeBuilder B(dstPreVisit, Dst, *currBldrCtx); 813 814 if (RS->getRetValue()) { 815 for (ExplodedNodeSet::iterator it = dstPreVisit.begin(), 816 ei = dstPreVisit.end(); it != ei; ++it) { 817 B.generateNode(RS, *it, (*it)->getState()); 818 } 819 } 820} 821