ExprEngineCallAndReturn.cpp revision 453cb859a3c8dcafe79ae840dfc35ff8eae1b4b3
11184aebb761cbeac9124c37189a80a1a58f04b6bhkuang//=-- ExprEngineCallAndReturn.cpp - Support for call/return -----*- C++ -*-===//
21184aebb761cbeac9124c37189a80a1a58f04b6bhkuang//
31184aebb761cbeac9124c37189a80a1a58f04b6bhkuang//                     The LLVM Compiler Infrastructure
41184aebb761cbeac9124c37189a80a1a58f04b6bhkuang//
51184aebb761cbeac9124c37189a80a1a58f04b6bhkuang// This file is distributed under the University of Illinois Open Source
61184aebb761cbeac9124c37189a80a1a58f04b6bhkuang// License. See LICENSE.TXT for details.
71184aebb761cbeac9124c37189a80a1a58f04b6bhkuang//
81184aebb761cbeac9124c37189a80a1a58f04b6bhkuang//===----------------------------------------------------------------------===//
91184aebb761cbeac9124c37189a80a1a58f04b6bhkuang//
101184aebb761cbeac9124c37189a80a1a58f04b6bhkuang//  This file defines ExprEngine's support for calls and returns.
111184aebb761cbeac9124c37189a80a1a58f04b6bhkuang//
121184aebb761cbeac9124c37189a80a1a58f04b6bhkuang//===----------------------------------------------------------------------===//
131184aebb761cbeac9124c37189a80a1a58f04b6bhkuang
141184aebb761cbeac9124c37189a80a1a58f04b6bhkuang#define DEBUG_TYPE "ExprEngine"
151184aebb761cbeac9124c37189a80a1a58f04b6bhkuang
165ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
171184aebb761cbeac9124c37189a80a1a58f04b6bhkuang#include "clang/AST/CXXInheritance.h"
185ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang#include "clang/AST/DeclCXX.h"
191184aebb761cbeac9124c37189a80a1a58f04b6bhkuang#include "clang/AST/ParentMap.h"
205ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang#include "clang/Analysis/Analyses/LiveVariables.h"
21b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian#include "clang/StaticAnalyzer/Core/CheckerManager.h"
225ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
23b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian#include "llvm/ADT/SmallSet.h"
24b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian#include "llvm/ADT/Statistic.h"
25b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian#include "llvm/Support/SaveAndRestore.h"
265ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
271184aebb761cbeac9124c37189a80a1a58f04b6bhkuangusing namespace clang;
285ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuangusing namespace ento;
29b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
305ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuangSTATISTIC(NumOfDynamicDispatchPathSplits,
315ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  "The # of times we split the path due to imprecise dynamic dispatch info");
325ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
335ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuangSTATISTIC(NumInlinedCalls,
345ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  "The # of times we inlined a call");
355ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
365ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuangSTATISTIC(NumReachedInlineCountMax,
375ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  "The # of times we reached inline count maximum");
385ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
395ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuangvoid ExprEngine::processCallEnter(CallEnter CE, ExplodedNode *Pred) {
405ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // Get the entry block in the CFG of the callee.
415ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const StackFrameContext *calleeCtx = CE.getCalleeContext();
425ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const CFG *CalleeCFG = calleeCtx->getCFG();
435ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const CFGBlock *Entry = &(CalleeCFG->getEntry());
445ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
455ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // Validate the CFG.
465ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  assert(Entry->empty());
475ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  assert(Entry->succ_size() == 1);
485ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
495ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // Get the solitary sucessor.
505ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const CFGBlock *Succ = *(Entry->succ_begin());
515ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
525ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // Construct an edge representing the starting location in the callee.
535ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  BlockEdge Loc(Entry, Succ, calleeCtx);
545ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
555ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  ProgramStateRef state = Pred->getState();
565ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
575ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // Construct a new node and add it to the worklist.
58b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  bool isNew;
59b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  ExplodedNode *Node = G.getNode(Loc, state, false, &isNew);
60b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  Node->addPredecessor(Pred, G);
61b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  if (isNew)
62b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    Engine.getWorkList()->enqueue(Node);
63b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian}
64b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
65b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian// Find the last statement on the path to the exploded node and the
66b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian// corresponding Block.
67b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanianstatic std::pair<const Stmt*,
68b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian                 const CFGBlock*> getLastStmt(const ExplodedNode *Node) {
69b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  const Stmt *S = 0;
706ac915abcdb404a00d927fe6308a47fcf09d9519hkuang  const CFGBlock *Blk = 0;
716ac915abcdb404a00d927fe6308a47fcf09d9519hkuang  const StackFrameContext *SF =
726ac915abcdb404a00d927fe6308a47fcf09d9519hkuang          Node->getLocation().getLocationContext()->getCurrentStackFrame();
736ac915abcdb404a00d927fe6308a47fcf09d9519hkuang
746ac915abcdb404a00d927fe6308a47fcf09d9519hkuang  // Back up through the ExplodedGraph until we reach a statement node in this
756ac915abcdb404a00d927fe6308a47fcf09d9519hkuang  // stack frame.
766ac915abcdb404a00d927fe6308a47fcf09d9519hkuang  while (Node) {
776ac915abcdb404a00d927fe6308a47fcf09d9519hkuang    const ProgramPoint &PP = Node->getLocation();
785ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
795ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    if (PP.getLocationContext()->getCurrentStackFrame() == SF) {
805ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      if (const StmtPoint *SP = dyn_cast<StmtPoint>(&PP)) {
815ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        S = SP->getStmt();
82b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian        break;
836ac915abcdb404a00d927fe6308a47fcf09d9519hkuang      } else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&PP)) {
846ac915abcdb404a00d927fe6308a47fcf09d9519hkuang        S = CEE->getCalleeContext()->getCallSite();
856ac915abcdb404a00d927fe6308a47fcf09d9519hkuang        if (S)
865ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang          break;
875ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
885ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        // If there is no statement, this is an implicitly-generated call.
895ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        // We'll walk backwards over it and then continue the loop to find
905ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        // an actual statement.
915ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        const CallEnter *CE;
925ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        do {
935ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang          Node = Node->getFirstPred();
945ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang          CE = Node->getLocationAs<CallEnter>();
955ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        } while (!CE || CE->getCalleeContext() != CEE->getCalleeContext());
965ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
975ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        // Continue searching the graph.
985ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      } else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&PP)) {
995ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        Blk = BE->getSrc();
1005ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      }
101b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    } else if (const CallEnter *CE = dyn_cast<CallEnter>(&PP)) {
102b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian      // If we reached the CallEnter for this function, it has no statements.
1035ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      if (CE->getCalleeContext() == SF)
1045ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        break;
105b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    }
106b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
107b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    if (Node->pred_empty())
108b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian      return std::pair<const Stmt*, const CFGBlock*>((Stmt*)0, (CFGBlock*)0);
1095ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
1105ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    Node = *Node->pred_begin();
111b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  }
1121184aebb761cbeac9124c37189a80a1a58f04b6bhkuang
113b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  return std::pair<const Stmt*, const CFGBlock*>(S, Blk);
1145ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang}
1155ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
1165ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang/// Adjusts a return value when the called function's return type does not
1175ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang/// match the caller's expression type. This can happen when a dynamic call
1181184aebb761cbeac9124c37189a80a1a58f04b6bhkuang/// is devirtualized, and the overridding method has a covariant (more specific)
1191184aebb761cbeac9124c37189a80a1a58f04b6bhkuang/// return type than the parent's method. For C++ objects, this means we need
1201184aebb761cbeac9124c37189a80a1a58f04b6bhkuang/// to add base casts.
1215ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuangstatic SVal adjustReturnValue(SVal V, QualType ExpectedTy, QualType ActualTy,
1225ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang                              StoreManager &StoreMgr) {
1235ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // For now, the only adjustments we handle apply only to locations.
124b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  if (!isa<Loc>(V))
125b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    return V;
126b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
127b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  // If the types already match, don't do any unnecessary work.
1281184aebb761cbeac9124c37189a80a1a58f04b6bhkuang  ExpectedTy = ExpectedTy.getCanonicalType();
129b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  ActualTy = ActualTy.getCanonicalType();
130b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  if (ExpectedTy == ActualTy)
131b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    return V;
1326ac915abcdb404a00d927fe6308a47fcf09d9519hkuang
1336ac915abcdb404a00d927fe6308a47fcf09d9519hkuang  // No adjustment is needed between Objective-C pointer types.
1341184aebb761cbeac9124c37189a80a1a58f04b6bhkuang  if (ExpectedTy->isObjCObjectPointerType() &&
1355ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      ActualTy->isObjCObjectPointerType())
1365ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    return V;
1375ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
1385ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // C++ object pointers may need "derived-to-base" casts.
1391184aebb761cbeac9124c37189a80a1a58f04b6bhkuang  const CXXRecordDecl *ExpectedClass = ExpectedTy->getPointeeCXXRecordDecl();
1405ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const CXXRecordDecl *ActualClass = ActualTy->getPointeeCXXRecordDecl();
1415ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  if (ExpectedClass && ActualClass) {
1421184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1431184aebb761cbeac9124c37189a80a1a58f04b6bhkuang                       /*DetectVirtual=*/false);
1441184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    if (ActualClass->isDerivedFrom(ExpectedClass, Paths) &&
1455ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        !Paths.isAmbiguous(ActualTy->getCanonicalTypeUnqualified())) {
1465ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      return StoreMgr.evalDerivedToBase(V, Paths.front());
1475ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    }
1485ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  }
1495ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
1505ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // Unfortunately, Objective-C does not enforce that overridden methods have
1515ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // covariant return types, so we can't assert that that never happens.
1525ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // Be safe and return UnknownVal().
1535ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  return UnknownVal();
1545ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang}
1555ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
1565ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuangvoid ExprEngine::removeDeadOnEndOfFunction(NodeBuilderContext& BC,
1575ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang                                           ExplodedNode *Pred,
1585ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang                                           ExplodedNodeSet &Dst) {
1595ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // Find the last statement in the function and the corresponding basic block.
1605ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const Stmt *LastSt = 0;
1615ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const CFGBlock *Blk = 0;
1625ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  llvm::tie(LastSt, Blk) = getLastStmt(Pred);
1635ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  if (!Blk || !LastSt) {
1645ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    Dst.Add(Pred);
1655ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    return;
1665ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  }
1675ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
1685ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // Here, we destroy the current location context. We use the current
1695ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // function's entire body as a diagnostic statement, with which the program
1705ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // point will be associated. However, we only want to use LastStmt as a
1715ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // reference for what to clean up if it's a ReturnStmt; otherwise, everything
1725ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // is dead.
1735ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
1745ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const LocationContext *LCtx = Pred->getLocationContext();
1755ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  removeDead(Pred, Dst, dyn_cast<ReturnStmt>(LastSt), LCtx,
1765ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang             LCtx->getAnalysisDeclContext()->getBody(),
1775ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang             ProgramPoint::PostStmtPurgeDeadSymbolsKind);
1785ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang}
1795ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
1805ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuangstatic bool wasDifferentDeclUsedForInlining(CallEventRef<> Call,
1815ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    const StackFrameContext *calleeCtx) {
1825ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const Decl *RuntimeCallee = calleeCtx->getDecl();
1835ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const Decl *StaticDecl = Call->getDecl();
1845ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  assert(RuntimeCallee);
185b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  if (!StaticDecl)
186b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    return true;
187b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  return RuntimeCallee->getCanonicalDecl() != StaticDecl->getCanonicalDecl();
188b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian}
189b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
190b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian/// Returns true if the CXXConstructExpr \p E was intended to construct a
191b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian/// prvalue for the region in \p V.
192b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian///
193b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian/// Note that we can't just test for rvalue vs. glvalue because
194b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian/// CXXConstructExprs embedded in DeclStmts and initializers are considered
195b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian/// rvalues by the AST, and the analyzer would like to treat them as lvalues.
196b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanianstatic bool isTemporaryPRValue(const CXXConstructExpr *E, SVal V) {
197b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  if (E->isGLValue())
198b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    return false;
199b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
2006ac915abcdb404a00d927fe6308a47fcf09d9519hkuang  const MemRegion *MR = V.getAsRegion();
2016ac915abcdb404a00d927fe6308a47fcf09d9519hkuang  if (!MR)
2026ac915abcdb404a00d927fe6308a47fcf09d9519hkuang    return false;
2036ac915abcdb404a00d927fe6308a47fcf09d9519hkuang
2046ac915abcdb404a00d927fe6308a47fcf09d9519hkuang  return isa<CXXTempObjectRegion>(MR);
2056ac915abcdb404a00d927fe6308a47fcf09d9519hkuang}
2066ac915abcdb404a00d927fe6308a47fcf09d9519hkuang
2076ac915abcdb404a00d927fe6308a47fcf09d9519hkuang/// The call exit is simulated with a sequence of nodes, which occur between
2085ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang/// CallExitBegin and CallExitEnd. The following operations occur between the
2095ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang/// two program points:
2105ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang/// 1. CallExitBegin (triggers the start of call exit sequence)
2115ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang/// 2. Bind the return value
2121184aebb761cbeac9124c37189a80a1a58f04b6bhkuang/// 3. Run Remove dead bindings to clean up the dead symbols from the callee.
213b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian/// 4. CallExitEnd (switch to the caller context)
214b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian/// 5. PostStmt<CallExpr>
215b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanianvoid ExprEngine::processCallExit(ExplodedNode *CEBNode) {
216b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  // Step 1 CEBNode was generated before the call.
217b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
218b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  const StackFrameContext *calleeCtx =
219b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian      CEBNode->getLocationContext()->getCurrentStackFrame();
220b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
221b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  // The parent context might not be a stack frame, so make sure we
222b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  // look up the first enclosing stack frame.
223b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  const StackFrameContext *callerCtx =
224b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    calleeCtx->getParent()->getCurrentStackFrame();
225b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
226b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  const Stmt *CE = calleeCtx->getCallSite();
227b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  ProgramStateRef state = CEBNode->getState();
228b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  // Find the last statement in the function and the corresponding basic block.
229b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  const Stmt *LastSt = 0;
230b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  const CFGBlock *Blk = 0;
231b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  llvm::tie(LastSt, Blk) = getLastStmt(CEBNode);
232b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
233b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  // Generate a CallEvent /before/ cleaning the state, so that we can get the
234b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  // correct value for 'this' (if necessary).
235b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  CallEventManager &CEMgr = getStateManager().getCallEventManager();
236b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  CallEventRef<> Call = CEMgr.getCaller(calleeCtx, state);
237b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
238b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  // Step 2: generate node with bound return value: CEBNode -> BindedRetNode.
239b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
240b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  // If the callee returns an expression, bind its value to CallExpr.
241b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  if (CE) {
242b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    if (const ReturnStmt *RS = dyn_cast_or_null<ReturnStmt>(LastSt)) {
2436ac915abcdb404a00d927fe6308a47fcf09d9519hkuang      const LocationContext *LCtx = CEBNode->getLocationContext();
2446ac915abcdb404a00d927fe6308a47fcf09d9519hkuang      SVal V = state->getSVal(RS, LCtx);
2456ac915abcdb404a00d927fe6308a47fcf09d9519hkuang
2466ac915abcdb404a00d927fe6308a47fcf09d9519hkuang      // Ensure that the return type matches the type of the returned Expr.
2476ac915abcdb404a00d927fe6308a47fcf09d9519hkuang      if (wasDifferentDeclUsedForInlining(Call, calleeCtx)) {
2486ac915abcdb404a00d927fe6308a47fcf09d9519hkuang        QualType ReturnedTy =
2496ac915abcdb404a00d927fe6308a47fcf09d9519hkuang          CallEvent::getDeclaredResultType(calleeCtx->getDecl());
2506ac915abcdb404a00d927fe6308a47fcf09d9519hkuang        if (!ReturnedTy.isNull()) {
2516ac915abcdb404a00d927fe6308a47fcf09d9519hkuang          if (const Expr *Ex = dyn_cast<Expr>(CE)) {
2526ac915abcdb404a00d927fe6308a47fcf09d9519hkuang            V = adjustReturnValue(V, Ex->getType(), ReturnedTy,
2536ac915abcdb404a00d927fe6308a47fcf09d9519hkuang                                  getStoreManager());
2545ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang          }
2555ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        }
2565ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      }
2575ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
2581184aebb761cbeac9124c37189a80a1a58f04b6bhkuang      state = state->BindExpr(CE, callerCtx, V);
2595ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    }
260b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
2615ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    // Bind the constructed object value to CXXConstructExpr.
2625ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) {
2635ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      loc::MemRegionVal This =
2645ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang        svalBuilder.getCXXThis(CCE->getConstructor()->getParent(), calleeCtx);
2651184aebb761cbeac9124c37189a80a1a58f04b6bhkuang      SVal ThisV = state->getSVal(This);
2665ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
2675ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      // If the constructed object is a temporary prvalue, get its bindings.
2685ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      if (isTemporaryPRValue(CCE, ThisV))
2691184aebb761cbeac9124c37189a80a1a58f04b6bhkuang        ThisV = state->getSVal(cast<Loc>(ThisV));
2705ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
2715ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      state = state->BindExpr(CCE, callerCtx, ThisV);
2725ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    }
2735ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  }
2745ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
275b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  // Step 3: BindedRetNode -> CleanedNodes
2765ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // If we can find a statement and a block in the inlined function, run remove
2775ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // dead bindings before returning from the call. This is important to ensure
2785ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // that we report the issues such as leaks in the stack contexts in which
2795ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  // they occurred.
280b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  ExplodedNodeSet CleanedNodes;
2811184aebb761cbeac9124c37189a80a1a58f04b6bhkuang  if (LastSt && Blk && AMgr.options.AnalysisPurgeOpt != PurgeNone) {
2821184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    static SimpleProgramPointTag retValBind("ExprEngine : Bind Return Value");
2835ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    PostStmt Loc(LastSt, calleeCtx, &retValBind);
2845ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    bool isNew;
285b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    ExplodedNode *BindedRetNode = G.getNode(Loc, state, false, &isNew);
286b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    BindedRetNode->addPredecessor(CEBNode, G);
2871184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    if (!isNew)
2885ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      return;
2895ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
2905ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    NodeBuilderContext Ctx(getCoreEngine(), Blk, BindedRetNode);
2915ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    currBldrCtx = &Ctx;
2921184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    // Here, we call the Symbol Reaper with 0 statement and callee location
2935ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    // context, telling it to clean up everything in the callee's context
2941184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    // (and its children). We use the callee's function body as a diagnostic
2951184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    // statement, with which the program point will be associated.
296b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    removeDead(BindedRetNode, CleanedNodes, 0, calleeCtx,
297a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian               calleeCtx->getAnalysisDeclContext()->getBody(),
2981184aebb761cbeac9124c37189a80a1a58f04b6bhkuang               ProgramPoint::PostStmtPurgeDeadSymbolsKind);
2995ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    currBldrCtx = 0;
3005ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  } else {
301b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    CleanedNodes.Add(CEBNode);
3025ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  }
3031184aebb761cbeac9124c37189a80a1a58f04b6bhkuang
3041184aebb761cbeac9124c37189a80a1a58f04b6bhkuang  for (ExplodedNodeSet::iterator I = CleanedNodes.begin(),
3055ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang                                 E = CleanedNodes.end(); I != E; ++I) {
3065ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
3075ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    // Step 4: Generate the CallExit and leave the callee's context.
3085ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    // CleanedNodes -> CEENode
3095ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    CallExitEnd Loc(calleeCtx, callerCtx);
3105ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    bool isNew;
3115ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    ProgramStateRef CEEState = (*I == CEBNode) ? state : (*I)->getState();
3125ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    ExplodedNode *CEENode = G.getNode(Loc, CEEState, false, &isNew);
3135ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    CEENode->addPredecessor(*I, G);
3145ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    if (!isNew)
3151184aebb761cbeac9124c37189a80a1a58f04b6bhkuang      return;
316b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
317b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    // Step 5: Perform the post-condition check of the CallExpr and enqueue the
318b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    // result onto the work list.
319b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    // CEENode -> Dst -> WorkList
320b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    NodeBuilderContext Ctx(Engine, calleeCtx->getCallSiteBlock(), CEENode);
321b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    SaveAndRestore<const NodeBuilderContext*> NBCSave(currBldrCtx,
322b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian        &Ctx);
323b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    SaveAndRestore<unsigned> CBISave(currStmtIdx, calleeCtx->getIndex());
324b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
3251184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    CallEventRef<> UpdatedCall = Call.cloneWithState(CEEState);
326b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
327b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    ExplodedNodeSet DstPostCall;
328b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    getCheckerManager().runCheckersForPostCall(DstPostCall, CEENode,
329b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian                                               *UpdatedCall, *this,
330b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian                                               /*WasInlined=*/true);
331b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
3321184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    ExplodedNodeSet Dst;
3331184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
334b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian      getCheckerManager().runCheckersForPostObjCMessage(Dst, DstPostCall, *Msg,
335b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian                                                        *this,
336b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian                                                        /*WasInlined=*/true);
337b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    } else if (CE) {
3385ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      getCheckerManager().runCheckersForPostStmt(Dst, DstPostCall, CE,
339a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian                                                 *this, /*WasInlined=*/true);
340a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian    } else {
341a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian      Dst.insert(DstPostCall);
342a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian    }
343a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian
344a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian    // Enqueue the next element in the block.
345b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    for (ExplodedNodeSet::iterator PSI = Dst.begin(), PSE = Dst.end();
346a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian                                   PSI != PSE; ++PSI) {
347a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian      Engine.getWorkList()->enqueue(*PSI, calleeCtx->getCallSiteBlock(),
3485ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang                                    calleeCtx->getIndex()+1);
3495ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    }
3501184aebb761cbeac9124c37189a80a1a58f04b6bhkuang  }
3511184aebb761cbeac9124c37189a80a1a58f04b6bhkuang}
352b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
353b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanianvoid ExprEngine::examineStackFrames(const Decl *D, const LocationContext *LCtx,
354b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian                               bool &IsRecursive, unsigned &StackDepth) {
355b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  IsRecursive = false;
356b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  StackDepth = 0;
357b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
358b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  while (LCtx) {
359b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LCtx)) {
360b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian      const Decl *DI = SFC->getDecl();
361b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
362b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian      // Mark recursive (and mutually recursive) functions and always count
363b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian      // them when measuring the stack depth.
3645ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang      if (DI == D) {
365a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian        IsRecursive = true;
366a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian        ++StackDepth;
367a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian        LCtx = LCtx->getParent();
368a72801d7d92ababb50eecf27a36bd222d031d2feVignesh Venkatasubramanian        continue;
3691184aebb761cbeac9124c37189a80a1a58f04b6bhkuang      }
3701184aebb761cbeac9124c37189a80a1a58f04b6bhkuang
371b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian      // Do not count the small functions when determining the stack depth.
3721184aebb761cbeac9124c37189a80a1a58f04b6bhkuang      AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(DI);
3731184aebb761cbeac9124c37189a80a1a58f04b6bhkuang      const CFG *CalleeCFG = CalleeADC->getCFG();
3741184aebb761cbeac9124c37189a80a1a58f04b6bhkuang      if (CalleeCFG->getNumBlockIDs() > AMgr.options.getAlwaysInlineSize())
3751184aebb761cbeac9124c37189a80a1a58f04b6bhkuang        ++StackDepth;
376b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    }
377b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian    LCtx = LCtx->getParent();
378b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian  }
379b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian
380b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanian}
3811184aebb761cbeac9124c37189a80a1a58f04b6bhkuang
382b08e2e23eec181e9951df33cd704ac294c5407b6Vignesh Venkatasubramanianstatic bool IsInStdNamespace(const FunctionDecl *FD) {
3835ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const DeclContext *DC = FD->getEnclosingNamespaceContext();
3845ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3855ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  if (!ND)
3865ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang    return false;
3875ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang
3885ae7ac49f08a179e4f054d99fcfc9dce78d26e58hkuang  while (const DeclContext *Parent = ND->getParent()) {
3891184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    if (!isa<NamespaceDecl>(Parent))
3901184aebb761cbeac9124c37189a80a1a58f04b6bhkuang      break;
3911184aebb761cbeac9124c37189a80a1a58f04b6bhkuang    ND = cast<NamespaceDecl>(Parent);
392  }
393
394  return ND->getName() == "std";
395}
396
397// Determine if we should inline the call.
398bool ExprEngine::shouldInlineDecl(const Decl *D, ExplodedNode *Pred) {
399  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D);
400  const CFG *CalleeCFG = CalleeADC->getCFG();
401
402  // It is possible that the CFG cannot be constructed.
403  // Be safe, and check if the CalleeCFG is valid.
404  if (!CalleeCFG)
405    return false;
406
407  bool IsRecursive = false;
408  unsigned StackDepth = 0;
409  examineStackFrames(D, Pred->getLocationContext(), IsRecursive, StackDepth);
410  if ((StackDepth >= AMgr.options.InlineMaxStackDepth) &&
411       ((CalleeCFG->getNumBlockIDs() > AMgr.options.getAlwaysInlineSize())
412         || IsRecursive))
413    return false;
414
415  if (Engine.FunctionSummaries->hasReachedMaxBlockCount(D))
416    return false;
417
418  if (CalleeCFG->getNumBlockIDs() > AMgr.options.getMaxInlinableSize())
419    return false;
420
421  // Do not inline variadic calls (for now).
422  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
423    if (BD->isVariadic())
424      return false;
425  }
426  else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
427    if (FD->isVariadic())
428      return false;
429  }
430
431  if (getContext().getLangOpts().CPlusPlus) {
432    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
433      // Conditionally allow the inlining of template functions.
434      if (!AMgr.options.mayInlineTemplateFunctions())
435        if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
436          return false;
437
438      // Conditionally allow the inlining of C++ standard library functions.
439      if (!AMgr.options.mayInlineCXXStandardLibrary())
440        if (getContext().getSourceManager().isInSystemHeader(FD->getLocation()))
441          if (IsInStdNamespace(FD))
442            return false;
443    }
444  }
445
446  // It is possible that the live variables analysis cannot be
447  // run.  If so, bail out.
448  if (!CalleeADC->getAnalysis<RelaxedLiveVariables>())
449    return false;
450
451  if (Engine.FunctionSummaries->getNumTimesInlined(D) >
452        AMgr.options.getMaxTimesInlineLarge() &&
453      CalleeCFG->getNumBlockIDs() > 13) {
454    NumReachedInlineCountMax++;
455    return false;
456  }
457  Engine.FunctionSummaries->bumpNumTimesInlined(D);
458
459  return true;
460}
461
462// The GDM component containing the dynamic dispatch bifurcation info. When
463// the exact type of the receiver is not known, we want to explore both paths -
464// one on which we do inline it and the other one on which we don't. This is
465// done to ensure we do not drop coverage.
466// This is the map from the receiver region to a bool, specifying either we
467// consider this region's information precise or not along the given path.
468namespace {
469  enum DynamicDispatchMode {
470    DynamicDispatchModeInlined = 1,
471    DynamicDispatchModeConservative
472  };
473}
474REGISTER_TRAIT_WITH_PROGRAMSTATE(DynamicDispatchBifurcationMap,
475                                 CLANG_ENTO_PROGRAMSTATE_MAP(const MemRegion *,
476                                                             unsigned))
477
478bool ExprEngine::inlineCall(const CallEvent &Call, const Decl *D,
479                            NodeBuilder &Bldr, ExplodedNode *Pred,
480                            ProgramStateRef State) {
481  assert(D);
482
483  const LocationContext *CurLC = Pred->getLocationContext();
484  const StackFrameContext *CallerSFC = CurLC->getCurrentStackFrame();
485  const LocationContext *ParentOfCallee = 0;
486
487  AnalyzerOptions &Opts = getAnalysisManager().options;
488
489  // FIXME: Refactor this check into a hypothetical CallEvent::canInline.
490  switch (Call.getKind()) {
491  case CE_Function:
492    break;
493  case CE_CXXMember:
494  case CE_CXXMemberOperator:
495    if (!Opts.mayInlineCXXMemberFunction(CIMK_MemberFunctions))
496      return false;
497    break;
498  case CE_CXXConstructor: {
499    if (!Opts.mayInlineCXXMemberFunction(CIMK_Constructors))
500      return false;
501
502    const CXXConstructorCall &Ctor = cast<CXXConstructorCall>(Call);
503
504    // FIXME: We don't handle constructors or destructors for arrays properly.
505    const MemRegion *Target = Ctor.getCXXThisVal().getAsRegion();
506    if (Target && isa<ElementRegion>(Target))
507      return false;
508
509    // FIXME: This is a hack. We don't use the correct region for a new
510    // expression, so if we inline the constructor its result will just be
511    // thrown away. This short-term hack is tracked in <rdar://problem/12180598>
512    // and the longer-term possible fix is discussed in PR12014.
513    const CXXConstructExpr *CtorExpr = Ctor.getOriginExpr();
514    if (const Stmt *Parent = CurLC->getParentMap().getParent(CtorExpr))
515      if (isa<CXXNewExpr>(Parent))
516        return false;
517
518    // Inlining constructors requires including initializers in the CFG.
519    const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext();
520    assert(ADC->getCFGBuildOptions().AddInitializers && "No CFG initializers");
521    (void)ADC;
522
523    // If the destructor is trivial, it's always safe to inline the constructor.
524    if (Ctor.getDecl()->getParent()->hasTrivialDestructor())
525      break;
526
527    // For other types, only inline constructors if destructor inlining is
528    // also enabled.
529    if (!Opts.mayInlineCXXMemberFunction(CIMK_Destructors))
530      return false;
531
532    // FIXME: This is a hack. We don't handle temporary destructors
533    // right now, so we shouldn't inline their constructors.
534    if (CtorExpr->getConstructionKind() == CXXConstructExpr::CK_Complete)
535      if (!Target || !isa<DeclRegion>(Target))
536        return false;
537
538    break;
539  }
540  case CE_CXXDestructor: {
541    if (!Opts.mayInlineCXXMemberFunction(CIMK_Destructors))
542      return false;
543
544    // Inlining destructors requires building the CFG correctly.
545    const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext();
546    assert(ADC->getCFGBuildOptions().AddImplicitDtors && "No CFG destructors");
547    (void)ADC;
548
549    const CXXDestructorCall &Dtor = cast<CXXDestructorCall>(Call);
550
551    // FIXME: We don't handle constructors or destructors for arrays properly.
552    const MemRegion *Target = Dtor.getCXXThisVal().getAsRegion();
553    if (Target && isa<ElementRegion>(Target))
554      return false;
555
556    break;
557  }
558  case CE_CXXAllocator:
559    // Do not inline allocators until we model deallocators.
560    // This is unfortunate, but basically necessary for smart pointers and such.
561    return false;
562  case CE_Block: {
563    const BlockDataRegion *BR = cast<BlockCall>(Call).getBlockRegion();
564    assert(BR && "If we have the block definition we should have its region");
565    AnalysisDeclContext *BlockCtx = AMgr.getAnalysisDeclContext(D);
566    ParentOfCallee = BlockCtx->getBlockInvocationContext(CallerSFC,
567                                                         cast<BlockDecl>(D),
568                                                         BR);
569    break;
570  }
571  case CE_ObjCMessage:
572    if (!Opts.mayInlineObjCMethod())
573      return false;
574    AnalyzerOptions &Options = getAnalysisManager().options;
575    if (!(Options.getIPAMode() == IPAK_DynamicDispatch ||
576          Options.getIPAMode() == IPAK_DynamicDispatchBifurcate))
577      return false;
578    break;
579  }
580
581  if (!shouldInlineDecl(D, Pred))
582    return false;
583
584  if (!ParentOfCallee)
585    ParentOfCallee = CallerSFC;
586
587  // This may be NULL, but that's fine.
588  const Expr *CallE = Call.getOriginExpr();
589
590  // Construct a new stack frame for the callee.
591  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D);
592  const StackFrameContext *CalleeSFC =
593    CalleeADC->getStackFrame(ParentOfCallee, CallE,
594                             currBldrCtx->getBlock(),
595                             currStmtIdx);
596
597  CallEnter Loc(CallE, CalleeSFC, CurLC);
598
599  // Construct a new state which contains the mapping from actual to
600  // formal arguments.
601  State = State->enterStackFrame(Call, CalleeSFC);
602
603  bool isNew;
604  if (ExplodedNode *N = G.getNode(Loc, State, false, &isNew)) {
605    N->addPredecessor(Pred, G);
606    if (isNew)
607      Engine.getWorkList()->enqueue(N);
608  }
609
610  // If we decided to inline the call, the successor has been manually
611  // added onto the work list so remove it from the node builder.
612  Bldr.takeNodes(Pred);
613
614  NumInlinedCalls++;
615
616  // Mark the decl as visited.
617  if (VisitedCallees)
618    VisitedCallees->insert(D);
619
620  return true;
621}
622
623static ProgramStateRef getInlineFailedState(ProgramStateRef State,
624                                            const Stmt *CallE) {
625  const void *ReplayState = State->get<ReplayWithoutInlining>();
626  if (!ReplayState)
627    return 0;
628
629  assert(ReplayState == CallE && "Backtracked to the wrong call.");
630  (void)CallE;
631
632  return State->remove<ReplayWithoutInlining>();
633}
634
635void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
636                               ExplodedNodeSet &dst) {
637  // Perform the previsit of the CallExpr.
638  ExplodedNodeSet dstPreVisit;
639  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this);
640
641  // Get the call in its initial state. We use this as a template to perform
642  // all the checks.
643  CallEventManager &CEMgr = getStateManager().getCallEventManager();
644  CallEventRef<> CallTemplate
645    = CEMgr.getSimpleCall(CE, Pred->getState(), Pred->getLocationContext());
646
647  // Evaluate the function call.  We try each of the checkers
648  // to see if the can evaluate the function call.
649  ExplodedNodeSet dstCallEvaluated;
650  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
651       I != E; ++I) {
652    evalCall(dstCallEvaluated, *I, *CallTemplate);
653  }
654
655  // Finally, perform the post-condition check of the CallExpr and store
656  // the created nodes in 'Dst'.
657  // Note that if the call was inlined, dstCallEvaluated will be empty.
658  // The post-CallExpr check will occur in processCallExit.
659  getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE,
660                                             *this);
661}
662
663void ExprEngine::evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
664                          const CallEvent &Call) {
665  // WARNING: At this time, the state attached to 'Call' may be older than the
666  // state in 'Pred'. This is a minor optimization since CheckerManager will
667  // use an updated CallEvent instance when calling checkers, but if 'Call' is
668  // ever used directly in this function all callers should be updated to pass
669  // the most recent state. (It is probably not worth doing the work here since
670  // for some callers this will not be necessary.)
671
672  // Run any pre-call checks using the generic call interface.
673  ExplodedNodeSet dstPreVisit;
674  getCheckerManager().runCheckersForPreCall(dstPreVisit, Pred, Call, *this);
675
676  // Actually evaluate the function call.  We try each of the checkers
677  // to see if the can evaluate the function call, and get a callback at
678  // defaultEvalCall if all of them fail.
679  ExplodedNodeSet dstCallEvaluated;
680  getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, dstPreVisit,
681                                             Call, *this);
682
683  // Finally, run any post-call checks.
684  getCheckerManager().runCheckersForPostCall(Dst, dstCallEvaluated,
685                                             Call, *this);
686}
687
688ProgramStateRef ExprEngine::bindReturnValue(const CallEvent &Call,
689                                            const LocationContext *LCtx,
690                                            ProgramStateRef State) {
691  const Expr *E = Call.getOriginExpr();
692  if (!E)
693    return State;
694
695  // Some method families have known return values.
696  if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(&Call)) {
697    switch (Msg->getMethodFamily()) {
698    default:
699      break;
700    case OMF_autorelease:
701    case OMF_retain:
702    case OMF_self: {
703      // These methods return their receivers.
704      return State->BindExpr(E, LCtx, Msg->getReceiverSVal());
705    }
706    }
707  } else if (const CXXConstructorCall *C = dyn_cast<CXXConstructorCall>(&Call)){
708    SVal ThisV = C->getCXXThisVal();
709
710    // If the constructed object is a temporary prvalue, get its bindings.
711    if (isTemporaryPRValue(cast<CXXConstructExpr>(E), ThisV))
712      ThisV = State->getSVal(cast<Loc>(ThisV));
713
714    return State->BindExpr(E, LCtx, ThisV);
715  }
716
717  // Conjure a symbol if the return value is unknown.
718  QualType ResultTy = Call.getResultType();
719  SValBuilder &SVB = getSValBuilder();
720  unsigned Count = currBldrCtx->blockCount();
721  SVal R = SVB.conjureSymbolVal(0, E, LCtx, ResultTy, Count);
722  return State->BindExpr(E, LCtx, R);
723}
724
725// Conservatively evaluate call by invalidating regions and binding
726// a conjured return value.
727void ExprEngine::conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr,
728                                      ExplodedNode *Pred, ProgramStateRef State) {
729  State = Call.invalidateRegions(currBldrCtx->blockCount(), State);
730  State = bindReturnValue(Call, Pred->getLocationContext(), State);
731
732  // And make the result node.
733  Bldr.generateNode(Call.getProgramPoint(), State, Pred);
734}
735
736static bool isEssentialToInline(const CallEvent &Call) {
737  const Decl *D = Call.getDecl();
738  if (D) {
739    AnalysisDeclContext *AD =
740      Call.getLocationContext()->getAnalysisDeclContext()->
741      getManager()->getContext(D);
742
743    // The auto-synthesized bodies are essential to inline as they are
744    // usually small and commonly used.
745    return AD->isBodyAutosynthesized();
746  }
747  return false;
748}
749
750void ExprEngine::defaultEvalCall(NodeBuilder &Bldr, ExplodedNode *Pred,
751                                 const CallEvent &CallTemplate) {
752  // Make sure we have the most recent state attached to the call.
753  ProgramStateRef State = Pred->getState();
754  CallEventRef<> Call = CallTemplate.cloneWithState(State);
755
756  if (HowToInline == Inline_None && !isEssentialToInline(CallTemplate)) {
757    conservativeEvalCall(*Call, Bldr, Pred, State);
758    return;
759  }
760  // Try to inline the call.
761  // The origin expression here is just used as a kind of checksum;
762  // this should still be safe even for CallEvents that don't come from exprs.
763  const Expr *E = Call->getOriginExpr();
764  ProgramStateRef InlinedFailedState = getInlineFailedState(State, E);
765
766  if (InlinedFailedState) {
767    // If we already tried once and failed, make sure we don't retry later.
768    State = InlinedFailedState;
769  } else {
770    RuntimeDefinition RD = Call->getRuntimeDefinition();
771    const Decl *D = RD.getDecl();
772    if (D) {
773      if (RD.mayHaveOtherDefinitions()) {
774        AnalyzerOptions &Options = getAnalysisManager().options;
775
776        // Explore with and without inlining the call.
777        if (Options.getIPAMode() == IPAK_DynamicDispatchBifurcate) {
778          BifurcateCall(RD.getDispatchRegion(), *Call, D, Bldr, Pred);
779          return;
780        }
781
782        // Don't inline if we're not in any dynamic dispatch mode.
783        if (Options.getIPAMode() != IPAK_DynamicDispatch) {
784          conservativeEvalCall(*Call, Bldr, Pred, State);
785          return;
786        }
787      }
788
789      // We are not bifurcating and we do have a Decl, so just inline.
790      if (inlineCall(*Call, D, Bldr, Pred, State))
791        return;
792    }
793  }
794
795  // If we can't inline it, handle the return value and invalidate the regions.
796  conservativeEvalCall(*Call, Bldr, Pred, State);
797}
798
799void ExprEngine::BifurcateCall(const MemRegion *BifurReg,
800                               const CallEvent &Call, const Decl *D,
801                               NodeBuilder &Bldr, ExplodedNode *Pred) {
802  assert(BifurReg);
803  BifurReg = BifurReg->StripCasts();
804
805  // Check if we've performed the split already - note, we only want
806  // to split the path once per memory region.
807  ProgramStateRef State = Pred->getState();
808  const unsigned *BState =
809                        State->get<DynamicDispatchBifurcationMap>(BifurReg);
810  if (BState) {
811    // If we are on "inline path", keep inlining if possible.
812    if (*BState == DynamicDispatchModeInlined)
813      if (inlineCall(Call, D, Bldr, Pred, State))
814        return;
815    // If inline failed, or we are on the path where we assume we
816    // don't have enough info about the receiver to inline, conjure the
817    // return value and invalidate the regions.
818    conservativeEvalCall(Call, Bldr, Pred, State);
819    return;
820  }
821
822  // If we got here, this is the first time we process a message to this
823  // region, so split the path.
824  ProgramStateRef IState =
825      State->set<DynamicDispatchBifurcationMap>(BifurReg,
826                                               DynamicDispatchModeInlined);
827  inlineCall(Call, D, Bldr, Pred, IState);
828
829  ProgramStateRef NoIState =
830      State->set<DynamicDispatchBifurcationMap>(BifurReg,
831                                               DynamicDispatchModeConservative);
832  conservativeEvalCall(Call, Bldr, Pred, NoIState);
833
834  NumOfDynamicDispatchPathSplits++;
835  return;
836}
837
838
839void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
840                                 ExplodedNodeSet &Dst) {
841
842  ExplodedNodeSet dstPreVisit;
843  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this);
844
845  StmtNodeBuilder B(dstPreVisit, Dst, *currBldrCtx);
846
847  if (RS->getRetValue()) {
848    for (ExplodedNodeSet::iterator it = dstPreVisit.begin(),
849                                  ei = dstPreVisit.end(); it != ei; ++it) {
850      B.generateNode(RS, *it, (*it)->getState());
851    }
852  }
853}
854