ExprEngineCXX.cpp revision 4411b423e91da0a2c879b70c0222aeba35f72044
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 (Optional<Loc> L = V.getAs<Loc>())
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      bool IsVirtual =
165        (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase);
166      SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(),
167                                                         IsVirtual);
168      Target = BaseVal.getAsRegion();
169    }
170    break;
171  }
172  }
173
174  CallEventManager &CEMgr = getStateManager().getCallEventManager();
175  CallEventRef<CXXConstructorCall> Call =
176    CEMgr.getCXXConstructorCall(CE, Target, State, LCtx);
177
178  ExplodedNodeSet DstPreVisit;
179  getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
180  ExplodedNodeSet DstPreCall;
181  getCheckerManager().runCheckersForPreCall(DstPreCall, DstPreVisit,
182                                            *Call, *this);
183
184  ExplodedNodeSet DstEvaluated;
185  StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
186
187  if (CE->getConstructor()->isTrivial() &&
188      CE->getConstructor()->isCopyOrMoveConstructor() &&
189      !IsArray) {
190    // FIXME: Handle other kinds of trivial constructors as well.
191    for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
192         I != E; ++I)
193      performTrivialCopy(Bldr, *I, *Call);
194
195  } else {
196    for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
197         I != E; ++I)
198      defaultEvalCall(Bldr, *I, *Call);
199  }
200
201  ExplodedNodeSet DstPostCall;
202  getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated,
203                                             *Call, *this);
204  getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
205}
206
207void ExprEngine::VisitCXXDestructor(QualType ObjectType,
208                                    const MemRegion *Dest,
209                                    const Stmt *S,
210                                    bool IsBaseDtor,
211                                    ExplodedNode *Pred,
212                                    ExplodedNodeSet &Dst) {
213  const LocationContext *LCtx = Pred->getLocationContext();
214  ProgramStateRef State = Pred->getState();
215
216  // FIXME: We need to run the same destructor on every element of the array.
217  // This workaround will just run the first destructor (which will still
218  // invalidate the entire array).
219  // This is a loop because of multidimensional arrays.
220  while (const ArrayType *AT = getContext().getAsArrayType(ObjectType)) {
221    ObjectType = AT->getElementType();
222    Dest = State->getLValue(ObjectType, getSValBuilder().makeZeroArrayIndex(),
223                            loc::MemRegionVal(Dest)).getAsRegion();
224  }
225
226  const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
227  assert(RecordDecl && "Only CXXRecordDecls should have destructors");
228  const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
229
230  CallEventManager &CEMgr = getStateManager().getCallEventManager();
231  CallEventRef<CXXDestructorCall> Call =
232    CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
233
234  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
235                                Call->getSourceRange().getBegin(),
236                                "Error evaluating destructor");
237
238  ExplodedNodeSet DstPreCall;
239  getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
240                                            *Call, *this);
241
242  ExplodedNodeSet DstInvalidated;
243  StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
244  for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
245       I != E; ++I)
246    defaultEvalCall(Bldr, *I, *Call);
247
248  ExplodedNodeSet DstPostCall;
249  getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
250                                             *Call, *this);
251}
252
253void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
254                                   ExplodedNodeSet &Dst) {
255  // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
256  // Also, we need to decide how allocators actually work -- they're not
257  // really part of the CXXNewExpr because they happen BEFORE the
258  // CXXConstructExpr subexpression. See PR12014 for some discussion.
259  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
260
261  unsigned blockCount = currBldrCtx->blockCount();
262  const LocationContext *LCtx = Pred->getLocationContext();
263  DefinedOrUnknownSVal symVal = svalBuilder.conjureSymbolVal(0, CNE, LCtx,
264                                                             CNE->getType(),
265                                                             blockCount);
266  ProgramStateRef State = Pred->getState();
267
268  CallEventManager &CEMgr = getStateManager().getCallEventManager();
269  CallEventRef<CXXAllocatorCall> Call =
270    CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
271
272  // Invalidate placement args.
273  // FIXME: Once we figure out how we want allocators to work,
274  // we should be using the usual pre-/(default-)eval-/post-call checks here.
275  State = Call->invalidateRegions(blockCount);
276
277  // If we're compiling with exceptions enabled, and this allocation function
278  // is not declared as non-throwing, failures /must/ be signalled by
279  // exceptions, and thus the return value will never be NULL.
280  // C++11 [basic.stc.dynamic.allocation]p3.
281  FunctionDecl *FD = CNE->getOperatorNew();
282  if (FD && getContext().getLangOpts().CXXExceptions) {
283    QualType Ty = FD->getType();
284    if (const FunctionProtoType *ProtoType = Ty->getAs<FunctionProtoType>())
285      if (!ProtoType->isNothrow(getContext()))
286        State = State->assume(symVal, true);
287  }
288
289  if (CNE->isArray()) {
290    // FIXME: allocating an array requires simulating the constructors.
291    // For now, just return a symbolicated region.
292    const MemRegion *NewReg = symVal.castAs<loc::MemRegionVal>().getRegion();
293    QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
294    const ElementRegion *EleReg =
295      getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
296    State = State->BindExpr(CNE, Pred->getLocationContext(),
297                            loc::MemRegionVal(EleReg));
298    Bldr.generateNode(CNE, Pred, State);
299    return;
300  }
301
302  // FIXME: Once we have proper support for CXXConstructExprs inside
303  // CXXNewExpr, we need to make sure that the constructed object is not
304  // immediately invalidated here. (The placement call should happen before
305  // the constructor call anyway.)
306  if (FD && FD->isReservedGlobalPlacementOperator()) {
307    // Non-array placement new should always return the placement location.
308    SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
309    SVal Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
310                                       CNE->getPlacementArg(0)->getType());
311    State = State->BindExpr(CNE, LCtx, Result);
312  } else {
313    State = State->BindExpr(CNE, LCtx, symVal);
314  }
315
316  // If the type is not a record, we won't have a CXXConstructExpr as an
317  // initializer. Copy the value over.
318  if (const Expr *Init = CNE->getInitializer()) {
319    if (!isa<CXXConstructExpr>(Init)) {
320      QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
321      (void)ObjTy;
322      assert(!ObjTy->isRecordType());
323      SVal Location = State->getSVal(CNE, LCtx);
324      if (Optional<Loc> LV = Location.getAs<Loc>())
325        State = State->bindLoc(*LV, State->getSVal(Init, LCtx));
326    }
327  }
328
329  Bldr.generateNode(CNE, Pred, State);
330}
331
332void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
333                                    ExplodedNode *Pred, ExplodedNodeSet &Dst) {
334  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
335  ProgramStateRef state = Pred->getState();
336  Bldr.generateNode(CDE, Pred, state);
337}
338
339void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
340                                   ExplodedNode *Pred,
341                                   ExplodedNodeSet &Dst) {
342  const VarDecl *VD = CS->getExceptionDecl();
343  if (!VD) {
344    Dst.Add(Pred);
345    return;
346  }
347
348  const LocationContext *LCtx = Pred->getLocationContext();
349  SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
350                                        currBldrCtx->blockCount());
351  ProgramStateRef state = Pred->getState();
352  state = state->bindLoc(state->getLValue(VD, LCtx), V);
353
354  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
355  Bldr.generateNode(CS, Pred, state);
356}
357
358void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
359                                    ExplodedNodeSet &Dst) {
360  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
361
362  // Get the this object region from StoreManager.
363  const LocationContext *LCtx = Pred->getLocationContext();
364  const MemRegion *R =
365    svalBuilder.getRegionManager().getCXXThisRegion(
366                                  getContext().getCanonicalType(TE->getType()),
367                                                    LCtx);
368
369  ProgramStateRef state = Pred->getState();
370  SVal V = state->getSVal(loc::MemRegionVal(R));
371  Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
372}
373