CallEvent.cpp revision 658a28479dd775f6ff2c07fa5699a7ea01e04127
1//===- Calls.cpp - Wrapper for all function and method calls ------*- 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/// \file This file defines CallEvent and its subclasses, which represent path-
11/// sensitive instances of different kinds of function and method calls
12/// (C, C++, and Objective-C).
13//
14//===----------------------------------------------------------------------===//
15
16#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
17#include "clang/AST/ParentMap.h"
18#include "clang/Analysis/ProgramPoint.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/raw_ostream.h"
23
24using namespace clang;
25using namespace ento;
26
27QualType CallEvent::getResultType() const {
28  const Expr *E = getOriginExpr();
29  assert(E && "Calls without origin expressions do not have results");
30  QualType ResultTy = E->getType();
31
32  ASTContext &Ctx = getState()->getStateManager().getContext();
33
34  // A function that returns a reference to 'int' will have a result type
35  // of simply 'int'. Check the origin expr's value kind to recover the
36  // proper type.
37  switch (E->getValueKind()) {
38  case VK_LValue:
39    ResultTy = Ctx.getLValueReferenceType(ResultTy);
40    break;
41  case VK_XValue:
42    ResultTy = Ctx.getRValueReferenceType(ResultTy);
43    break;
44  case VK_RValue:
45    // No adjustment is necessary.
46    break;
47  }
48
49  return ResultTy;
50}
51
52static bool isCallbackArg(SVal V, QualType T) {
53  // If the parameter is 0, it's harmless.
54  if (V.isZeroConstant())
55    return false;
56
57  // If a parameter is a block or a callback, assume it can modify pointer.
58  if (T->isBlockPointerType() ||
59      T->isFunctionPointerType() ||
60      T->isObjCSelType())
61    return true;
62
63  // Check if a callback is passed inside a struct (for both, struct passed by
64  // reference and by value). Dig just one level into the struct for now.
65
66  if (T->isAnyPointerType() || T->isReferenceType())
67    T = T->getPointeeType();
68
69  if (const RecordType *RT = T->getAsStructureType()) {
70    const RecordDecl *RD = RT->getDecl();
71    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
72         I != E; ++I) {
73      QualType FieldT = I->getType();
74      if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
75        return true;
76    }
77  }
78
79  return false;
80}
81
82bool CallEvent::hasNonZeroCallbackArg() const {
83  unsigned NumOfArgs = getNumArgs();
84
85  // If calling using a function pointer, assume the function does not
86  // have a callback. TODO: We could check the types of the arguments here.
87  if (!getDecl())
88    return false;
89
90  unsigned Idx = 0;
91  for (CallEvent::param_type_iterator I = param_type_begin(),
92                                       E = param_type_end();
93       I != E && Idx < NumOfArgs; ++I, ++Idx) {
94    if (NumOfArgs <= Idx)
95      break;
96
97    if (isCallbackArg(getArgSVal(Idx), *I))
98      return true;
99  }
100
101  return false;
102}
103
104bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
105  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
106  if (!FD)
107    return false;
108
109  return CheckerContext::isCLibraryFunction(FD, FunctionName);
110}
111
112/// \brief Returns true if a type is a pointer-to-const or reference-to-const
113/// with no further indirection.
114static bool isPointerToConst(QualType Ty) {
115  QualType PointeeTy = Ty->getPointeeType();
116  if (PointeeTy == QualType())
117    return false;
118  if (!PointeeTy.isConstQualified())
119    return false;
120  if (PointeeTy->isAnyPointerType())
121    return false;
122  return true;
123}
124
125// Try to retrieve the function declaration and find the function parameter
126// types which are pointers/references to a non-pointer const.
127// We will not invalidate the corresponding argument regions.
128static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
129                                 const CallEvent &Call) {
130  unsigned Idx = 0;
131  for (CallEvent::param_type_iterator I = Call.param_type_begin(),
132                                      E = Call.param_type_end();
133       I != E; ++I, ++Idx) {
134    if (isPointerToConst(*I))
135      PreserveArgs.insert(Idx);
136  }
137}
138
139ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
140                                             ProgramStateRef Orig) const {
141  ProgramStateRef Result = (Orig ? Orig : getState());
142
143  SmallVector<SVal, 8> ConstValues;
144  SmallVector<SVal, 8> ValuesToInvalidate;
145
146  getExtraInvalidatedValues(ValuesToInvalidate);
147
148  // Indexes of arguments whose values will be preserved by the call.
149  llvm::SmallSet<unsigned, 4> PreserveArgs;
150  if (!argumentsMayEscape())
151    findPtrToConstParams(PreserveArgs, *this);
152
153  for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
154    // Mark this region for invalidation.  We batch invalidate regions
155    // below for efficiency.
156    if (PreserveArgs.count(Idx))
157      ConstValues.push_back(getArgSVal(Idx));
158    else
159      ValuesToInvalidate.push_back(getArgSVal(Idx));
160  }
161
162  // Invalidate designated regions using the batch invalidation API.
163  // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
164  //  global variables.
165  return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(),
166                                   BlockCount, getLocationContext(),
167                                   /*CausedByPointerEscape*/ true,
168                                   /*Symbols=*/0, this, ConstValues);
169}
170
171ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
172                                        const ProgramPointTag *Tag) const {
173  if (const Expr *E = getOriginExpr()) {
174    if (IsPreVisit)
175      return PreStmt(E, getLocationContext(), Tag);
176    return PostStmt(E, getLocationContext(), Tag);
177  }
178
179  const Decl *D = getDecl();
180  assert(D && "Cannot get a program point without a statement or decl");
181
182  SourceLocation Loc = getSourceRange().getBegin();
183  if (IsPreVisit)
184    return PreImplicitCall(D, Loc, getLocationContext(), Tag);
185  return PostImplicitCall(D, Loc, getLocationContext(), Tag);
186}
187
188SVal CallEvent::getArgSVal(unsigned Index) const {
189  const Expr *ArgE = getArgExpr(Index);
190  if (!ArgE)
191    return UnknownVal();
192  return getSVal(ArgE);
193}
194
195SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
196  const Expr *ArgE = getArgExpr(Index);
197  if (!ArgE)
198    return SourceRange();
199  return ArgE->getSourceRange();
200}
201
202SVal CallEvent::getReturnValue() const {
203  const Expr *E = getOriginExpr();
204  if (!E)
205    return UndefinedVal();
206  return getSVal(E);
207}
208
209void CallEvent::dump() const {
210  dump(llvm::errs());
211}
212
213void CallEvent::dump(raw_ostream &Out) const {
214  ASTContext &Ctx = getState()->getStateManager().getContext();
215  if (const Expr *E = getOriginExpr()) {
216    E->printPretty(Out, 0, Ctx.getPrintingPolicy());
217    Out << "\n";
218    return;
219  }
220
221  if (const Decl *D = getDecl()) {
222    Out << "Call to ";
223    D->print(Out, Ctx.getPrintingPolicy());
224    return;
225  }
226
227  // FIXME: a string representation of the kind would be nice.
228  Out << "Unknown call (type " << getKind() << ")";
229}
230
231
232bool CallEvent::isCallStmt(const Stmt *S) {
233  return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
234                          || isa<CXXConstructExpr>(S)
235                          || isa<CXXNewExpr>(S);
236}
237
238QualType CallEvent::getDeclaredResultType(const Decl *D) {
239  assert(D);
240  if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D))
241    return FD->getResultType();
242  else if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D))
243    return MD->getResultType();
244  return QualType();
245}
246
247static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
248                                         CallEvent::BindingsTy &Bindings,
249                                         SValBuilder &SVB,
250                                         const CallEvent &Call,
251                                         CallEvent::param_iterator I,
252                                         CallEvent::param_iterator E) {
253  MemRegionManager &MRMgr = SVB.getRegionManager();
254
255  unsigned Idx = 0;
256  for (; I != E; ++I, ++Idx) {
257    const ParmVarDecl *ParamDecl = *I;
258    assert(ParamDecl && "Formal parameter has no decl?");
259
260    SVal ArgVal = Call.getArgSVal(Idx);
261    if (!ArgVal.isUnknown()) {
262      Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
263      Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
264    }
265  }
266
267  // FIXME: Variadic arguments are not handled at all right now.
268}
269
270
271CallEvent::param_iterator AnyFunctionCall::param_begin() const {
272  const FunctionDecl *D = getDecl();
273  if (!D)
274    return 0;
275
276  return D->param_begin();
277}
278
279CallEvent::param_iterator AnyFunctionCall::param_end() const {
280  const FunctionDecl *D = getDecl();
281  if (!D)
282    return 0;
283
284  return D->param_end();
285}
286
287void AnyFunctionCall::getInitialStackFrameContents(
288                                        const StackFrameContext *CalleeCtx,
289                                        BindingsTy &Bindings) const {
290  const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
291  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
292  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
293                               D->param_begin(), D->param_end());
294}
295
296bool AnyFunctionCall::argumentsMayEscape() const {
297  if (hasNonZeroCallbackArg())
298    return true;
299
300  const FunctionDecl *D = getDecl();
301  if (!D)
302    return true;
303
304  const IdentifierInfo *II = D->getIdentifier();
305  if (!II)
306    return false;
307
308  // This set of "escaping" APIs is
309
310  // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
311  //   value into thread local storage. The value can later be retrieved with
312  //   'void *ptheread_getspecific(pthread_key)'. So even thought the
313  //   parameter is 'const void *', the region escapes through the call.
314  if (II->isStr("pthread_setspecific"))
315    return true;
316
317  // - xpc_connection_set_context stores a value which can be retrieved later
318  //   with xpc_connection_get_context.
319  if (II->isStr("xpc_connection_set_context"))
320    return true;
321
322  // - funopen - sets a buffer for future IO calls.
323  if (II->isStr("funopen"))
324    return true;
325
326  StringRef FName = II->getName();
327
328  // - CoreFoundation functions that end with "NoCopy" can free a passed-in
329  //   buffer even if it is const.
330  if (FName.endswith("NoCopy"))
331    return true;
332
333  // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
334  //   be deallocated by NSMapRemove.
335  if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
336    return true;
337
338  // - Many CF containers allow objects to escape through custom
339  //   allocators/deallocators upon container construction. (PR12101)
340  if (FName.startswith("CF") || FName.startswith("CG")) {
341    return StrInStrNoCase(FName, "InsertValue")  != StringRef::npos ||
342           StrInStrNoCase(FName, "AddValue")     != StringRef::npos ||
343           StrInStrNoCase(FName, "SetValue")     != StringRef::npos ||
344           StrInStrNoCase(FName, "WithData")     != StringRef::npos ||
345           StrInStrNoCase(FName, "AppendValue")  != StringRef::npos ||
346           StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
347  }
348
349  return false;
350}
351
352
353const FunctionDecl *SimpleCall::getDecl() const {
354  const FunctionDecl *D = getOriginExpr()->getDirectCallee();
355  if (D)
356    return D;
357
358  return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
359}
360
361
362const FunctionDecl *CXXInstanceCall::getDecl() const {
363  const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
364  if (!CE)
365    return AnyFunctionCall::getDecl();
366
367  const FunctionDecl *D = CE->getDirectCallee();
368  if (D)
369    return D;
370
371  return getSVal(CE->getCallee()).getAsFunctionDecl();
372}
373
374void CXXInstanceCall::getExtraInvalidatedValues(ValueList &Values) const {
375  Values.push_back(getCXXThisVal());
376}
377
378SVal CXXInstanceCall::getCXXThisVal() const {
379  const Expr *Base = getCXXThisExpr();
380  // FIXME: This doesn't handle an overloaded ->* operator.
381  if (!Base)
382    return UnknownVal();
383
384  SVal ThisVal = getSVal(Base);
385  assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
386  return ThisVal;
387}
388
389
390RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
391  // Do we have a decl at all?
392  const Decl *D = getDecl();
393  if (!D)
394    return RuntimeDefinition();
395
396  // If the method is non-virtual, we know we can inline it.
397  const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
398  if (!MD->isVirtual())
399    return AnyFunctionCall::getRuntimeDefinition();
400
401  // Do we know the implicit 'this' object being called?
402  const MemRegion *R = getCXXThisVal().getAsRegion();
403  if (!R)
404    return RuntimeDefinition();
405
406  // Do we know anything about the type of 'this'?
407  DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R);
408  if (!DynType.isValid())
409    return RuntimeDefinition();
410
411  // Is the type a C++ class? (This is mostly a defensive check.)
412  QualType RegionType = DynType.getType()->getPointeeType();
413  assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
414
415  const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
416  if (!RD || !RD->hasDefinition())
417    return RuntimeDefinition();
418
419  // Find the decl for this method in that class.
420  const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
421  if (!Result) {
422    // We might not even get the original statically-resolved method due to
423    // some particularly nasty casting (e.g. casts to sister classes).
424    // However, we should at least be able to search up and down our own class
425    // hierarchy, and some real bugs have been caught by checking this.
426    assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
427
428    // FIXME: This is checking that our DynamicTypeInfo is at least as good as
429    // the static type. However, because we currently don't update
430    // DynamicTypeInfo when an object is cast, we can't actually be sure the
431    // DynamicTypeInfo is up to date. This assert should be re-enabled once
432    // this is fixed. <rdar://problem/12287087>
433    //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
434
435    return RuntimeDefinition();
436  }
437
438  // Does the decl that we found have an implementation?
439  const FunctionDecl *Definition;
440  if (!Result->hasBody(Definition))
441    return RuntimeDefinition();
442
443  // We found a definition. If we're not sure that this devirtualization is
444  // actually what will happen at runtime, make sure to provide the region so
445  // that ExprEngine can decide what to do with it.
446  if (DynType.canBeASubClass())
447    return RuntimeDefinition(Definition, R->StripCasts());
448  return RuntimeDefinition(Definition, /*DispatchRegion=*/0);
449}
450
451void CXXInstanceCall::getInitialStackFrameContents(
452                                            const StackFrameContext *CalleeCtx,
453                                            BindingsTy &Bindings) const {
454  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
455
456  // Handle the binding of 'this' in the new stack frame.
457  SVal ThisVal = getCXXThisVal();
458  if (!ThisVal.isUnknown()) {
459    ProgramStateManager &StateMgr = getState()->getStateManager();
460    SValBuilder &SVB = StateMgr.getSValBuilder();
461
462    const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
463    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
464
465    // If we devirtualized to a different member function, we need to make sure
466    // we have the proper layering of CXXBaseObjectRegions.
467    if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
468      ASTContext &Ctx = SVB.getContext();
469      const CXXRecordDecl *Class = MD->getParent();
470      QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
471
472      // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
473      bool Failed;
474      ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed);
475      assert(!Failed && "Calling an incorrectly devirtualized method");
476    }
477
478    if (!ThisVal.isUnknown())
479      Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
480  }
481}
482
483
484
485const Expr *CXXMemberCall::getCXXThisExpr() const {
486  return getOriginExpr()->getImplicitObjectArgument();
487}
488
489RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
490  // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
491  // id-expression in the class member access expression is a qualified-id,
492  // that function is called. Otherwise, its final overrider in the dynamic type
493  // of the object expression is called.
494  if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
495    if (ME->hasQualifier())
496      return AnyFunctionCall::getRuntimeDefinition();
497
498  return CXXInstanceCall::getRuntimeDefinition();
499}
500
501
502const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
503  return getOriginExpr()->getArg(0);
504}
505
506
507const BlockDataRegion *BlockCall::getBlockRegion() const {
508  const Expr *Callee = getOriginExpr()->getCallee();
509  const MemRegion *DataReg = getSVal(Callee).getAsRegion();
510
511  return dyn_cast_or_null<BlockDataRegion>(DataReg);
512}
513
514CallEvent::param_iterator BlockCall::param_begin() const {
515  const BlockDecl *D = getBlockDecl();
516  if (!D)
517    return 0;
518  return D->param_begin();
519}
520
521CallEvent::param_iterator BlockCall::param_end() const {
522  const BlockDecl *D = getBlockDecl();
523  if (!D)
524    return 0;
525  return D->param_end();
526}
527
528void BlockCall::getExtraInvalidatedValues(ValueList &Values) const {
529  // FIXME: This also needs to invalidate captured globals.
530  if (const MemRegion *R = getBlockRegion())
531    Values.push_back(loc::MemRegionVal(R));
532}
533
534void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
535                                             BindingsTy &Bindings) const {
536  const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl());
537  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
538  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
539                               D->param_begin(), D->param_end());
540}
541
542
543SVal CXXConstructorCall::getCXXThisVal() const {
544  if (Data)
545    return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
546  return UnknownVal();
547}
548
549void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values) const {
550  if (Data)
551    Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data)));
552}
553
554void CXXConstructorCall::getInitialStackFrameContents(
555                                             const StackFrameContext *CalleeCtx,
556                                             BindingsTy &Bindings) const {
557  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
558
559  SVal ThisVal = getCXXThisVal();
560  if (!ThisVal.isUnknown()) {
561    SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
562    const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
563    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
564    Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
565  }
566}
567
568
569
570SVal CXXDestructorCall::getCXXThisVal() const {
571  if (Data)
572    return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
573  return UnknownVal();
574}
575
576RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
577  // Base destructors are always called non-virtually.
578  // Skip CXXInstanceCall's devirtualization logic in this case.
579  if (isBaseDestructor())
580    return AnyFunctionCall::getRuntimeDefinition();
581
582  return CXXInstanceCall::getRuntimeDefinition();
583}
584
585
586CallEvent::param_iterator ObjCMethodCall::param_begin() const {
587  const ObjCMethodDecl *D = getDecl();
588  if (!D)
589    return 0;
590
591  return D->param_begin();
592}
593
594CallEvent::param_iterator ObjCMethodCall::param_end() const {
595  const ObjCMethodDecl *D = getDecl();
596  if (!D)
597    return 0;
598
599  return D->param_end();
600}
601
602void
603ObjCMethodCall::getExtraInvalidatedValues(ValueList &Values) const {
604  Values.push_back(getReceiverSVal());
605}
606
607SVal ObjCMethodCall::getSelfSVal() const {
608  const LocationContext *LCtx = getLocationContext();
609  const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
610  if (!SelfDecl)
611    return SVal();
612  return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
613}
614
615SVal ObjCMethodCall::getReceiverSVal() const {
616  // FIXME: Is this the best way to handle class receivers?
617  if (!isInstanceMessage())
618    return UnknownVal();
619
620  if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
621    return getSVal(RecE);
622
623  // An instance message with no expression means we are sending to super.
624  // In this case the object reference is the same as 'self'.
625  assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
626  SVal SelfVal = getSelfSVal();
627  assert(SelfVal.isValid() && "Calling super but not in ObjC method");
628  return SelfVal;
629}
630
631bool ObjCMethodCall::isReceiverSelfOrSuper() const {
632  if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
633      getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
634      return true;
635
636  if (!isInstanceMessage())
637    return false;
638
639  SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
640
641  return (RecVal == getSelfSVal());
642}
643
644SourceRange ObjCMethodCall::getSourceRange() const {
645  switch (getMessageKind()) {
646  case OCM_Message:
647    return getOriginExpr()->getSourceRange();
648  case OCM_PropertyAccess:
649  case OCM_Subscript:
650    return getContainingPseudoObjectExpr()->getSourceRange();
651  }
652  llvm_unreachable("unknown message kind");
653}
654
655typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
656
657const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
658  assert(Data != 0 && "Lazy lookup not yet performed.");
659  assert(getMessageKind() != OCM_Message && "Explicit message send.");
660  return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
661}
662
663ObjCMessageKind ObjCMethodCall::getMessageKind() const {
664  if (Data == 0) {
665    ParentMap &PM = getLocationContext()->getParentMap();
666    const Stmt *S = PM.getParent(getOriginExpr());
667    if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
668      const Expr *Syntactic = POE->getSyntacticForm();
669
670      // This handles the funny case of assigning to the result of a getter.
671      // This can happen if the getter returns a non-const reference.
672      if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
673        Syntactic = BO->getLHS();
674
675      ObjCMessageKind K;
676      switch (Syntactic->getStmtClass()) {
677      case Stmt::ObjCPropertyRefExprClass:
678        K = OCM_PropertyAccess;
679        break;
680      case Stmt::ObjCSubscriptRefExprClass:
681        K = OCM_Subscript;
682        break;
683      default:
684        // FIXME: Can this ever happen?
685        K = OCM_Message;
686        break;
687      }
688
689      if (K != OCM_Message) {
690        const_cast<ObjCMethodCall *>(this)->Data
691          = ObjCMessageDataTy(POE, K).getOpaqueValue();
692        assert(getMessageKind() == K);
693        return K;
694      }
695    }
696
697    const_cast<ObjCMethodCall *>(this)->Data
698      = ObjCMessageDataTy(0, 1).getOpaqueValue();
699    assert(getMessageKind() == OCM_Message);
700    return OCM_Message;
701  }
702
703  ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
704  if (!Info.getPointer())
705    return OCM_Message;
706  return static_cast<ObjCMessageKind>(Info.getInt());
707}
708
709
710bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
711                                             Selector Sel) const {
712  assert(IDecl);
713  const SourceManager &SM =
714    getState()->getStateManager().getContext().getSourceManager();
715
716  // If the class interface is declared inside the main file, assume it is not
717  // subcassed.
718  // TODO: It could actually be subclassed if the subclass is private as well.
719  // This is probably very rare.
720  SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
721  if (InterfLoc.isValid() && SM.isFromMainFile(InterfLoc))
722    return false;
723
724  // Assume that property accessors are not overridden.
725  if (getMessageKind() == OCM_PropertyAccess)
726    return false;
727
728  // We assume that if the method is public (declared outside of main file) or
729  // has a parent which publicly declares the method, the method could be
730  // overridden in a subclass.
731
732  // Find the first declaration in the class hierarchy that declares
733  // the selector.
734  ObjCMethodDecl *D = 0;
735  while (true) {
736    D = IDecl->lookupMethod(Sel, true);
737
738    // Cannot find a public definition.
739    if (!D)
740      return false;
741
742    // If outside the main file,
743    if (D->getLocation().isValid() && !SM.isFromMainFile(D->getLocation()))
744      return true;
745
746    if (D->isOverriding()) {
747      // Search in the superclass on the next iteration.
748      IDecl = D->getClassInterface();
749      if (!IDecl)
750        return false;
751
752      IDecl = IDecl->getSuperClass();
753      if (!IDecl)
754        return false;
755
756      continue;
757    }
758
759    return false;
760  };
761
762  llvm_unreachable("The while loop should always terminate.");
763}
764
765RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
766  const ObjCMessageExpr *E = getOriginExpr();
767  assert(E);
768  Selector Sel = E->getSelector();
769
770  if (E->isInstanceMessage()) {
771
772    // Find the the receiver type.
773    const ObjCObjectPointerType *ReceiverT = 0;
774    bool CanBeSubClassed = false;
775    QualType SupersType = E->getSuperType();
776    const MemRegion *Receiver = 0;
777
778    if (!SupersType.isNull()) {
779      // Super always means the type of immediate predecessor to the method
780      // where the call occurs.
781      ReceiverT = cast<ObjCObjectPointerType>(SupersType);
782    } else {
783      Receiver = getReceiverSVal().getAsRegion();
784      if (!Receiver)
785        return RuntimeDefinition();
786
787      DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver);
788      QualType DynType = DTI.getType();
789      CanBeSubClassed = DTI.canBeASubClass();
790      ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType);
791
792      if (ReceiverT && CanBeSubClassed)
793        if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
794          if (!canBeOverridenInSubclass(IDecl, Sel))
795            CanBeSubClassed = false;
796    }
797
798    // Lookup the method implementation.
799    if (ReceiverT)
800      if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
801        // Repeatedly calling lookupPrivateMethod() is expensive, especially
802        // when in many cases it returns null.  We cache the results so
803        // that repeated queries on the same ObjCIntefaceDecl and Selector
804        // don't incur the same cost.  On some test cases, we can see the
805        // same query being issued thousands of times.
806        //
807        // NOTE: This cache is essentially a "global" variable, but it
808        // only gets lazily created when we get here.  The value of the
809        // cache probably comes from it being global across ExprEngines,
810        // where the same queries may get issued.  If we are worried about
811        // concurrency, or possibly loading/unloading ASTs, etc., we may
812        // need to revisit this someday.  In terms of memory, this table
813        // stays around until clang quits, which also may be bad if we
814        // need to release memory.
815        typedef std::pair<const ObjCInterfaceDecl*, Selector>
816                PrivateMethodKey;
817        typedef llvm::DenseMap<PrivateMethodKey,
818                               Optional<const ObjCMethodDecl *> >
819                PrivateMethodCache;
820
821        static PrivateMethodCache PMC;
822        Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
823
824        // Query lookupPrivateMethod() if the cache does not hit.
825        if (!Val.hasValue())
826          Val = IDecl->lookupPrivateMethod(Sel);
827
828        const ObjCMethodDecl *MD = Val.getValue();
829        if (CanBeSubClassed)
830          return RuntimeDefinition(MD, Receiver);
831        else
832          return RuntimeDefinition(MD, 0);
833      }
834
835  } else {
836    // This is a class method.
837    // If we have type info for the receiver class, we are calling via
838    // class name.
839    if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
840      // Find/Return the method implementation.
841      return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
842    }
843  }
844
845  return RuntimeDefinition();
846}
847
848void ObjCMethodCall::getInitialStackFrameContents(
849                                             const StackFrameContext *CalleeCtx,
850                                             BindingsTy &Bindings) const {
851  const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
852  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
853  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
854                               D->param_begin(), D->param_end());
855
856  SVal SelfVal = getReceiverSVal();
857  if (!SelfVal.isUnknown()) {
858    const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
859    MemRegionManager &MRMgr = SVB.getRegionManager();
860    Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
861    Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
862  }
863}
864
865CallEventRef<>
866CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
867                                const LocationContext *LCtx) {
868  if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
869    return create<CXXMemberCall>(MCE, State, LCtx);
870
871  if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
872    const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
873    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
874      if (MD->isInstance())
875        return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
876
877  } else if (CE->getCallee()->getType()->isBlockPointerType()) {
878    return create<BlockCall>(CE, State, LCtx);
879  }
880
881  // Otherwise, it's a normal function call, static member function call, or
882  // something we can't reason about.
883  return create<FunctionCall>(CE, State, LCtx);
884}
885
886
887CallEventRef<>
888CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
889                            ProgramStateRef State) {
890  const LocationContext *ParentCtx = CalleeCtx->getParent();
891  const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
892  assert(CallerCtx && "This should not be used for top-level stack frames");
893
894  const Stmt *CallSite = CalleeCtx->getCallSite();
895
896  if (CallSite) {
897    if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
898      return getSimpleCall(CE, State, CallerCtx);
899
900    switch (CallSite->getStmtClass()) {
901    case Stmt::CXXConstructExprClass:
902    case Stmt::CXXTemporaryObjectExprClass: {
903      SValBuilder &SVB = State->getStateManager().getSValBuilder();
904      const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
905      Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
906      SVal ThisVal = State->getSVal(ThisPtr);
907
908      return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
909                                   ThisVal.getAsRegion(), State, CallerCtx);
910    }
911    case Stmt::CXXNewExprClass:
912      return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
913    case Stmt::ObjCMessageExprClass:
914      return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
915                               State, CallerCtx);
916    default:
917      llvm_unreachable("This is not an inlineable statement.");
918    }
919  }
920
921  // Fall back to the CFG. The only thing we haven't handled yet is
922  // destructors, though this could change in the future.
923  const CFGBlock *B = CalleeCtx->getCallSiteBlock();
924  CFGElement E = (*B)[CalleeCtx->getIndex()];
925  assert(E.getAs<CFGImplicitDtor>() &&
926         "All other CFG elements should have exprs");
927  assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet");
928
929  SValBuilder &SVB = State->getStateManager().getSValBuilder();
930  const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
931  Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
932  SVal ThisVal = State->getSVal(ThisPtr);
933
934  const Stmt *Trigger;
935  if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
936    Trigger = AutoDtor->getTriggerStmt();
937  else
938    Trigger = Dtor->getBody();
939
940  return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
941                              E.getAs<CFGBaseDtor>().hasValue(), State,
942                              CallerCtx);
943}
944