ExprEngineCXX.cpp revision 5500fc193af4b786bbbbee6ece743f523448e90b
1//===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- 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 the C++ expression evaluation engine.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/StmtCXX.h"
17#include "clang/Basic/PrettyStackTrace.h"
18#include "clang/StaticAnalyzer/Core/CheckerManager.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21
22using namespace clang;
23using namespace ento;
24
25void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
26                                          ExplodedNode *Pred,
27                                          ExplodedNodeSet &Dst) {
28  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
29  const Expr *tempExpr = ME->GetTemporaryExpr()->IgnoreParens();
30  ProgramStateRef state = Pred->getState();
31  const LocationContext *LCtx = Pred->getLocationContext();
32
33  // Bind the temporary object to the value of the expression. Then bind
34  // the expression to the location of the object.
35  SVal V = state->getSVal(tempExpr, LCtx);
36
37  // If the value is already a CXXTempObjectRegion, it is fine as it is.
38  // Otherwise, create a new CXXTempObjectRegion, and copy the value into it.
39  const MemRegion *MR = V.getAsRegion();
40  if (!MR || !isa<CXXTempObjectRegion>(MR)) {
41    const MemRegion *R =
42      svalBuilder.getRegionManager().getCXXTempObjectRegion(ME, LCtx);
43
44    SVal L = loc::MemRegionVal(R);
45    state = state->bindLoc(L, V);
46    V = L;
47  }
48
49  Bldr.generateNode(ME, Pred, state->BindExpr(ME, LCtx, V));
50}
51
52void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
53                                    const CXXConstructorCall &Call) {
54  const CXXConstructExpr *CtorExpr = Call.getOriginExpr();
55  assert(CtorExpr->getConstructor()->isCopyOrMoveConstructor());
56  assert(CtorExpr->getConstructor()->isTrivial());
57
58  SVal ThisVal = Call.getCXXThisVal();
59  const LocationContext *LCtx = Pred->getLocationContext();
60
61  ExplodedNodeSet Dst;
62  Bldr.takeNodes(Pred);
63
64  SVal V = Call.getArgSVal(0);
65
66  // Make sure the value being copied is not unknown.
67  if (const Loc *L = dyn_cast<Loc>(&V))
68    V = Pred->getState()->getSVal(*L);
69
70  evalBind(Dst, CtorExpr, Pred, ThisVal, V, true);
71
72  PostStmt PS(CtorExpr, LCtx);
73  for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
74       I != E; ++I) {
75    ProgramStateRef State = (*I)->getState();
76    State = bindReturnValue(Call, LCtx, State);
77    Bldr.generateNode(PS, State, *I);
78  }
79}
80
81void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
82                                       ExplodedNode *Pred,
83                                       ExplodedNodeSet &destNodes) {
84  const LocationContext *LCtx = Pred->getLocationContext();
85  ProgramStateRef State = Pred->getState();
86
87  const MemRegion *Target = 0;
88  bool IsArray = false;
89
90  switch (CE->getConstructionKind()) {
91  case CXXConstructExpr::CK_Complete: {
92    // See if we're constructing an existing region by looking at the next
93    // element in the CFG.
94    const CFGBlock *B = currBldrCtx->getBlock();
95    if (currStmtIdx + 1 < B->size()) {
96      CFGElement Next = (*B)[currStmtIdx+1];
97
98      // Is this a constructor for a local variable?
99      if (const CFGStmt *StmtElem = dyn_cast<CFGStmt>(&Next)) {
100        if (const DeclStmt *DS = dyn_cast<DeclStmt>(StmtElem->getStmt())) {
101          if (const VarDecl *Var = dyn_cast<VarDecl>(DS->getSingleDecl())) {
102            if (Var->getInit()->IgnoreImplicit() == CE) {
103              QualType Ty = Var->getType();
104              if (const ArrayType *AT = getContext().getAsArrayType(Ty)) {
105                // FIXME: Handle arrays, which run the same constructor for
106                // every element. This workaround will just run the first
107                // constructor (which should still invalidate the entire array).
108                SVal Base = State->getLValue(Var, LCtx);
109                Target = State->getLValue(AT->getElementType(),
110                                          getSValBuilder().makeZeroArrayIndex(),
111                                          Base).getAsRegion();
112                IsArray = true;
113              } else {
114                Target = State->getLValue(Var, LCtx).getAsRegion();
115              }
116            }
117          }
118        }
119      }
120
121      // Is this a constructor for a member?
122      if (const CFGInitializer *InitElem = dyn_cast<CFGInitializer>(&Next)) {
123        const CXXCtorInitializer *Init = InitElem->getInitializer();
124        assert(Init->isAnyMemberInitializer());
125
126        const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
127        Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
128                                                  LCtx->getCurrentStackFrame());
129        SVal ThisVal = State->getSVal(ThisPtr);
130
131        if (Init->isIndirectMemberInitializer()) {
132          SVal Field = State->getLValue(Init->getIndirectMember(), ThisVal);
133          Target = Field.getAsRegion();
134        } else {
135          SVal Field = State->getLValue(Init->getMember(), ThisVal);
136          Target = Field.getAsRegion();
137        }
138      }
139
140      // FIXME: This will eventually need to handle new-expressions as well.
141    }
142
143    // If we couldn't find an existing region to construct into, assume we're
144    // constructing a temporary.
145    if (!Target) {
146      MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
147      Target = MRMgr.getCXXTempObjectRegion(CE, LCtx);
148    }
149
150    break;
151  }
152  case CXXConstructExpr::CK_NonVirtualBase:
153  case CXXConstructExpr::CK_VirtualBase:
154  case CXXConstructExpr::CK_Delegating: {
155    const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
156    Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
157                                              LCtx->getCurrentStackFrame());
158    SVal ThisVal = State->getSVal(ThisPtr);
159
160    if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) {
161      Target = ThisVal.getAsRegion();
162    } else {
163      // Cast to the base type.
164      QualType BaseTy = CE->getType();
165      SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy);
166      Target = BaseVal.getAsRegion();
167    }
168    break;
169  }
170  }
171
172  CallEventManager &CEMgr = getStateManager().getCallEventManager();
173  CallEventRef<CXXConstructorCall> Call =
174    CEMgr.getCXXConstructorCall(CE, Target, State, LCtx);
175
176  ExplodedNodeSet DstPreVisit;
177  getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
178  ExplodedNodeSet DstPreCall;
179  getCheckerManager().runCheckersForPreCall(DstPreCall, DstPreVisit,
180                                            *Call, *this);
181
182  ExplodedNodeSet DstEvaluated;
183  StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
184
185  if (CE->getConstructor()->isTrivial() &&
186      CE->getConstructor()->isCopyOrMoveConstructor() &&
187      !IsArray) {
188    // FIXME: Handle other kinds of trivial constructors as well.
189    for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
190         I != E; ++I)
191      performTrivialCopy(Bldr, *I, *Call);
192
193  } else {
194    for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
195         I != E; ++I)
196      defaultEvalCall(Bldr, *I, *Call);
197  }
198
199  ExplodedNodeSet DstPostCall;
200  getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated,
201                                             *Call, *this);
202  getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
203}
204
205void ExprEngine::VisitCXXDestructor(QualType ObjectType,
206                                    const MemRegion *Dest,
207                                    const Stmt *S,
208                                    bool IsBaseDtor,
209                                    ExplodedNode *Pred,
210                                    ExplodedNodeSet &Dst) {
211  const LocationContext *LCtx = Pred->getLocationContext();
212  ProgramStateRef State = Pred->getState();
213
214  // FIXME: We need to run the same destructor on every element of the array.
215  // This workaround will just run the first destructor (which will still
216  // invalidate the entire array).
217  // This is a loop because of multidimensional arrays.
218  while (const ArrayType *AT = getContext().getAsArrayType(ObjectType)) {
219    ObjectType = AT->getElementType();
220    Dest = State->getLValue(ObjectType, getSValBuilder().makeZeroArrayIndex(),
221                            loc::MemRegionVal(Dest)).getAsRegion();
222  }
223
224  const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
225  assert(RecordDecl && "Only CXXRecordDecls should have destructors");
226  const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
227
228  CallEventManager &CEMgr = getStateManager().getCallEventManager();
229  CallEventRef<CXXDestructorCall> Call =
230    CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
231
232  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
233                                Call->getSourceRange().getBegin(),
234                                "Error evaluating destructor");
235
236  ExplodedNodeSet DstPreCall;
237  getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
238                                            *Call, *this);
239
240  ExplodedNodeSet DstInvalidated;
241  StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
242  for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
243       I != E; ++I)
244    defaultEvalCall(Bldr, *I, *Call);
245
246  ExplodedNodeSet DstPostCall;
247  getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
248                                             *Call, *this);
249}
250
251void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
252                                   ExplodedNodeSet &Dst) {
253  // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
254  // Also, we need to decide how allocators actually work -- they're not
255  // really part of the CXXNewExpr because they happen BEFORE the
256  // CXXConstructExpr subexpression. See PR12014 for some discussion.
257  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
258
259  unsigned blockCount = currBldrCtx->blockCount();
260  const LocationContext *LCtx = Pred->getLocationContext();
261  DefinedOrUnknownSVal symVal = svalBuilder.conjureSymbolVal(0, CNE, LCtx,
262                                                             CNE->getType(),
263                                                             blockCount);
264  ProgramStateRef State = Pred->getState();
265
266  CallEventManager &CEMgr = getStateManager().getCallEventManager();
267  CallEventRef<CXXAllocatorCall> Call =
268    CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
269
270  // Invalidate placement args.
271  // FIXME: Once we figure out how we want allocators to work,
272  // we should be using the usual pre-/(default-)eval-/post-call checks here.
273  State = Call->invalidateRegions(blockCount);
274
275  // If we're compiling with exceptions enabled, and this allocation function
276  // is not declared as non-throwing, failures /must/ be signalled by
277  // exceptions, and thus the return value will never be NULL.
278  // C++11 [basic.stc.dynamic.allocation]p3.
279  FunctionDecl *FD = CNE->getOperatorNew();
280  if (FD && getContext().getLangOpts().CXXExceptions) {
281    QualType Ty = FD->getType();
282    if (const FunctionProtoType *ProtoType = Ty->getAs<FunctionProtoType>())
283      if (!ProtoType->isNothrow(getContext()))
284        State = State->assume(symVal, true);
285  }
286
287  if (CNE->isArray()) {
288    // FIXME: allocating an array requires simulating the constructors.
289    // For now, just return a symbolicated region.
290    const MemRegion *NewReg = cast<loc::MemRegionVal>(symVal).getRegion();
291    QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
292    const ElementRegion *EleReg =
293      getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
294    State = State->BindExpr(CNE, Pred->getLocationContext(),
295                            loc::MemRegionVal(EleReg));
296    Bldr.generateNode(CNE, Pred, State);
297    return;
298  }
299
300  // FIXME: Once we have proper support for CXXConstructExprs inside
301  // CXXNewExpr, we need to make sure that the constructed object is not
302  // immediately invalidated here. (The placement call should happen before
303  // the constructor call anyway.)
304  if (FD && FD->isReservedGlobalPlacementOperator()) {
305    // Non-array placement new should always return the placement location.
306    SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
307    SVal Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
308                                       CNE->getPlacementArg(0)->getType());
309    State = State->BindExpr(CNE, LCtx, Result);
310  } else {
311    State = State->BindExpr(CNE, LCtx, symVal);
312  }
313
314  // If the type is not a record, we won't have a CXXConstructExpr as an
315  // initializer. Copy the value over.
316  if (const Expr *Init = CNE->getInitializer()) {
317    if (!isa<CXXConstructExpr>(Init)) {
318      QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
319      (void)ObjTy;
320      assert(!ObjTy->isRecordType());
321      SVal Location = State->getSVal(CNE, LCtx);
322      if (isa<Loc>(Location))
323        State = State->bindLoc(cast<Loc>(Location), State->getSVal(Init, LCtx));
324    }
325  }
326
327  Bldr.generateNode(CNE, Pred, State);
328}
329
330void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
331                                    ExplodedNode *Pred, ExplodedNodeSet &Dst) {
332  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
333  ProgramStateRef state = Pred->getState();
334  Bldr.generateNode(CDE, Pred, state);
335}
336
337void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
338                                   ExplodedNode *Pred,
339                                   ExplodedNodeSet &Dst) {
340  const VarDecl *VD = CS->getExceptionDecl();
341  if (!VD) {
342    Dst.Add(Pred);
343    return;
344  }
345
346  const LocationContext *LCtx = Pred->getLocationContext();
347  SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
348                                        currBldrCtx->blockCount());
349  ProgramStateRef state = Pred->getState();
350  state = state->bindLoc(state->getLValue(VD, LCtx), V);
351
352  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
353  Bldr.generateNode(CS, Pred, state);
354}
355
356void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
357                                    ExplodedNodeSet &Dst) {
358  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
359
360  // Get the this object region from StoreManager.
361  const LocationContext *LCtx = Pred->getLocationContext();
362  const MemRegion *R =
363    svalBuilder.getRegionManager().getCXXThisRegion(
364                                  getContext().getCanonicalType(TE->getType()),
365                                                    LCtx);
366
367  ProgramStateRef state = Pred->getState();
368  SVal V = state->getSVal(loc::MemRegionVal(R));
369  Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
370}
371