clang  8.0.0
RetainSummaryManager.cpp
Go to the documentation of this file.
1 //== RetainSummaryManager.cpp - Summaries for reference counting --*- 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 summaries implementation for retain counting, which
11 // implements a reference count checker for Core Foundation, Cocoa
12 // and OSObject (on Mac OS X).
13 //
14 //===----------------------------------------------------------------------===//
15 
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ParentMap.h"
23 
24 using namespace clang;
25 using namespace ento;
26 
27 template <class T>
28 constexpr static bool isOneOf() {
29  return false;
30 }
31 
32 /// Helper function to check whether the class is one of the
33 /// rest of varargs.
34 template <class T, class P, class... ToCompare>
35 constexpr static bool isOneOf() {
36  return std::is_same<T, P>::value || isOneOf<T, ToCompare...>();
37 }
38 
39 namespace {
40 
41 /// Fake attribute class for RC* attributes.
42 struct GeneralizedReturnsRetainedAttr {
43  static bool classof(const Attr *A) {
44  if (auto AA = dyn_cast<AnnotateAttr>(A))
45  return AA->getAnnotation() == "rc_ownership_returns_retained";
46  return false;
47  }
48 };
49 
50 struct GeneralizedReturnsNotRetainedAttr {
51  static bool classof(const Attr *A) {
52  if (auto AA = dyn_cast<AnnotateAttr>(A))
53  return AA->getAnnotation() == "rc_ownership_returns_not_retained";
54  return false;
55  }
56 };
57 
58 struct GeneralizedConsumedAttr {
59  static bool classof(const Attr *A) {
60  if (auto AA = dyn_cast<AnnotateAttr>(A))
61  return AA->getAnnotation() == "rc_ownership_consumed";
62  return false;
63  }
64 };
65 
66 }
67 
68 template <class T>
69 Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D,
70  QualType QT) {
71  ObjKind K;
72  if (isOneOf<T, CFConsumedAttr, CFReturnsRetainedAttr,
73  CFReturnsNotRetainedAttr>()) {
74  if (!TrackObjCAndCFObjects)
75  return None;
76 
77  K = ObjKind::CF;
78  } else if (isOneOf<T, NSConsumedAttr, NSConsumesSelfAttr,
79  NSReturnsAutoreleasedAttr, NSReturnsRetainedAttr,
80  NSReturnsNotRetainedAttr, NSConsumesSelfAttr>()) {
81 
82  if (!TrackObjCAndCFObjects)
83  return None;
84 
85  if (isOneOf<T, NSReturnsRetainedAttr, NSReturnsAutoreleasedAttr,
86  NSReturnsNotRetainedAttr>() &&
88  return None;
89  K = ObjKind::ObjC;
90  } else if (isOneOf<T, OSConsumedAttr, OSConsumesThisAttr,
91  OSReturnsNotRetainedAttr, OSReturnsRetainedAttr,
92  OSReturnsRetainedOnZeroAttr,
93  OSReturnsRetainedOnNonZeroAttr>()) {
94  if (!TrackOSObjects)
95  return None;
96  K = ObjKind::OS;
97  } else if (isOneOf<T, GeneralizedReturnsNotRetainedAttr,
98  GeneralizedReturnsRetainedAttr,
99  GeneralizedConsumedAttr>()) {
101  } else {
102  llvm_unreachable("Unexpected attribute");
103  }
104  if (D->hasAttr<T>())
105  return K;
106  return None;
107 }
108 
109 template <class T1, class T2, class... Others>
110 Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D,
111  QualType QT) {
112  if (auto Out = hasAnyEnabledAttrOf<T1>(D, QT))
113  return Out;
114  return hasAnyEnabledAttrOf<T2, Others...>(D, QT);
115 }
116 
117 const RetainSummary *
118 RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
119  // Unique "simple" summaries -- those without ArgEffects.
120  if (OldSumm.isSimple()) {
121  ::llvm::FoldingSetNodeID ID;
122  OldSumm.Profile(ID);
123 
124  void *Pos;
125  CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
126 
127  if (!N) {
128  N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
129  new (N) CachedSummaryNode(OldSumm);
130  SimpleSummaries.InsertNode(N, Pos);
131  }
132 
133  return &N->getValue();
134  }
135 
136  RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
137  new (Summ) RetainSummary(OldSumm);
138  return Summ;
139 }
140 
141 static bool isSubclass(const Decl *D,
142  StringRef ClassName) {
143  using namespace ast_matchers;
144  DeclarationMatcher SubclassM = cxxRecordDecl(isSameOrDerivedFrom(ClassName));
145  return !(match(SubclassM, *D, D->getASTContext()).empty());
146 }
147 
148 static bool isOSObjectSubclass(const Decl *D) {
149  return isSubclass(D, "OSObject");
150 }
151 
152 static bool isOSObjectDynamicCast(StringRef S) {
153  return S == "safeMetaCast";
154 }
155 
156 static bool isOSIteratorSubclass(const Decl *D) {
157  return isSubclass(D, "OSIterator");
158 }
159 
160 static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) {
161  for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {
162  if (Ann->getAnnotation() == rcAnnotation)
163  return true;
164  }
165  return false;
166 }
167 
168 static bool isRetain(const FunctionDecl *FD, StringRef FName) {
169  return FName.startswith_lower("retain") || FName.endswith_lower("retain");
170 }
171 
172 static bool isRelease(const FunctionDecl *FD, StringRef FName) {
173  return FName.startswith_lower("release") || FName.endswith_lower("release");
174 }
175 
176 static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
177  return FName.startswith_lower("autorelease") ||
178  FName.endswith_lower("autorelease");
179 }
180 
181 static bool isMakeCollectable(StringRef FName) {
182  return FName.contains_lower("MakeCollectable");
183 }
184 
185 /// A function is OSObject related if it is declared on a subclass
186 /// of OSObject, or any of the parameters is a subclass of an OSObject.
187 static bool isOSObjectRelated(const CXXMethodDecl *MD) {
188  if (isOSObjectSubclass(MD->getParent()))
189  return true;
190 
191  for (ParmVarDecl *Param : MD->parameters()) {
192  QualType PT = Param->getType()->getPointeeType();
193  if (!PT.isNull())
194  if (CXXRecordDecl *RD = PT->getAsCXXRecordDecl())
195  if (isOSObjectSubclass(RD))
196  return true;
197  }
198 
199  return false;
200 }
201 
202 const RetainSummary *
203 RetainSummaryManager::getSummaryForOSObject(const FunctionDecl *FD,
204  StringRef FName, QualType RetTy) {
205  if (RetTy->isPointerType()) {
206  const CXXRecordDecl *PD = RetTy->getPointeeType()->getAsCXXRecordDecl();
207  if (PD && isOSObjectSubclass(PD)) {
208  if (const IdentifierInfo *II = FD->getIdentifier()) {
209  if (isOSObjectDynamicCast(II->getName()))
210  return getDefaultSummary();
211 
212  // All objects returned with functions *not* starting with
213  // get, or iterators, are returned at +1.
214  if ((!II->getName().startswith("get") &&
215  !II->getName().startswith("Get")) ||
216  isOSIteratorSubclass(PD)) {
217  return getOSSummaryCreateRule(FD);
218  } else {
219  return getOSSummaryGetRule(FD);
220  }
221  }
222  }
223  }
224 
225  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
226  const CXXRecordDecl *Parent = MD->getParent();
227  if (TrackOSObjects && Parent && isOSObjectSubclass(Parent)) {
228  if (FName == "release")
229  return getOSSummaryReleaseRule(FD);
230 
231  if (FName == "retain")
232  return getOSSummaryRetainRule(FD);
233 
234  if (FName == "free")
235  return getOSSummaryFreeRule(FD);
236 
237  if (MD->getOverloadedOperator() == OO_New)
238  return getOSSummaryCreateRule(MD);
239  }
240  }
241 
242  return nullptr;
243 }
244 
245 const RetainSummary *RetainSummaryManager::getSummaryForObjCOrCFObject(
246  const FunctionDecl *FD,
247  StringRef FName,
248  QualType RetTy,
249  const FunctionType *FT,
250  bool &AllowAnnotations) {
251 
252  ArgEffects ScratchArgs(AF.getEmptyMap());
253 
254  std::string RetTyName = RetTy.getAsString();
255  if (FName == "pthread_create" || FName == "pthread_setspecific") {
256  // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
257  // This will be addressed better with IPA.
258  return getPersistentStopSummary();
259  } else if(FName == "NSMakeCollectable") {
260  // Handle: id NSMakeCollectable(CFTypeRef)
261  AllowAnnotations = false;
262  return RetTy->isObjCIdType() ? getUnarySummary(FT, DoNothing)
263  : getPersistentStopSummary();
264  } else if (FName == "CMBufferQueueDequeueAndRetain" ||
265  FName == "CMBufferQueueDequeueIfDataReadyAndRetain") {
266  // Part of: <rdar://problem/39390714>.
267  return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
268  ScratchArgs,
271  } else if (FName == "CFPlugInInstanceCreate") {
272  return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs);
273  } else if (FName == "IORegistryEntrySearchCFProperty" ||
274  (RetTyName == "CFMutableDictionaryRef" &&
275  (FName == "IOBSDNameMatching" || FName == "IOServiceMatching" ||
276  FName == "IOServiceNameMatching" ||
277  FName == "IORegistryEntryIDMatching" ||
278  FName == "IOOpenFirmwarePathMatching"))) {
279  // Part of <rdar://problem/6961230>. (IOKit)
280  // This should be addressed using a API table.
281  return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
283  } else if (FName == "IOServiceGetMatchingService" ||
284  FName == "IOServiceGetMatchingServices") {
285  // FIXES: <rdar://problem/6326900>
286  // This should be addressed using a API table. This strcmp is also
287  // a little gross, but there is no need to super optimize here.
288  ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(DecRef, ObjKind::CF));
289  return getPersistentSummary(RetEffect::MakeNoRet(),
290  ScratchArgs,
292  } else if (FName == "IOServiceAddNotification" ||
293  FName == "IOServiceAddMatchingNotification") {
294  // Part of <rdar://problem/6961230>. (IOKit)
295  // This should be addressed using a API table.
296  ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(DecRef, ObjKind::CF));
297  return getPersistentSummary(RetEffect::MakeNoRet(),
298  ScratchArgs,
300  } else if (FName == "CVPixelBufferCreateWithBytes") {
301  // FIXES: <rdar://problem/7283567>
302  // Eventually this can be improved by recognizing that the pixel
303  // buffer passed to CVPixelBufferCreateWithBytes is released via
304  // a callback and doing full IPA to make sure this is done correctly.
305  // FIXME: This function has an out parameter that returns an
306  // allocated object.
307  ScratchArgs = AF.add(ScratchArgs, 7, ArgEffect(StopTracking));
308  return getPersistentSummary(RetEffect::MakeNoRet(),
309  ScratchArgs,
311  } else if (FName == "CGBitmapContextCreateWithData") {
312  // FIXES: <rdar://problem/7358899>
313  // Eventually this can be improved by recognizing that 'releaseInfo'
314  // passed to CGBitmapContextCreateWithData is released via
315  // a callback and doing full IPA to make sure this is done correctly.
316  ScratchArgs = AF.add(ScratchArgs, 8, ArgEffect(ArgEffect(StopTracking)));
317  return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
319  } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
320  // FIXES: <rdar://problem/7283567>
321  // Eventually this can be improved by recognizing that the pixel
322  // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
323  // via a callback and doing full IPA to make sure this is done
324  // correctly.
325  ScratchArgs = AF.add(ScratchArgs, 12, ArgEffect(StopTracking));
326  return getPersistentSummary(RetEffect::MakeNoRet(),
327  ScratchArgs,
329  } else if (FName == "VTCompressionSessionEncodeFrame") {
330  // The context argument passed to VTCompressionSessionEncodeFrame()
331  // is passed to the callback specified when creating the session
332  // (e.g. with VTCompressionSessionCreate()) which can release it.
333  // To account for this possibility, conservatively stop tracking
334  // the context.
335  ScratchArgs = AF.add(ScratchArgs, 5, ArgEffect(StopTracking));
336  return getPersistentSummary(RetEffect::MakeNoRet(),
337  ScratchArgs,
339  } else if (FName == "dispatch_set_context" ||
340  FName == "xpc_connection_set_context") {
341  // <rdar://problem/11059275> - The analyzer currently doesn't have
342  // a good way to reason about the finalizer function for libdispatch.
343  // If we pass a context object that is memory managed, stop tracking it.
344  // <rdar://problem/13783514> - Same problem, but for XPC.
345  // FIXME: this hack should possibly go away once we can handle
346  // libdispatch and XPC finalizers.
347  ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking));
348  return getPersistentSummary(RetEffect::MakeNoRet(),
349  ScratchArgs,
351  } else if (FName.startswith("NSLog")) {
352  return getDoNothingSummary();
353  } else if (FName.startswith("NS") &&
354  (FName.find("Insert") != StringRef::npos)) {
355  // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
356  // be deallocated by NSMapRemove. (radar://11152419)
357  ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking));
358  ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(StopTracking));
359  return getPersistentSummary(RetEffect::MakeNoRet(),
360  ScratchArgs, ArgEffect(DoNothing),
362  }
363 
364  if (RetTy->isPointerType()) {
365 
366  // For CoreFoundation ('CF') types.
367  if (cocoa::isRefType(RetTy, "CF", FName)) {
368  if (isRetain(FD, FName)) {
369  // CFRetain isn't supposed to be annotated. However, this may as
370  // well be a user-made "safe" CFRetain function that is incorrectly
371  // annotated as cf_returns_retained due to lack of better options.
372  // We want to ignore such annotation.
373  AllowAnnotations = false;
374 
375  return getUnarySummary(FT, IncRef);
376  } else if (isAutorelease(FD, FName)) {
377  // The headers use cf_consumed, but we can fully model CFAutorelease
378  // ourselves.
379  AllowAnnotations = false;
380 
381  return getUnarySummary(FT, Autorelease);
382  } else if (isMakeCollectable(FName)) {
383  AllowAnnotations = false;
384  return getUnarySummary(FT, DoNothing);
385  } else {
386  return getCFCreateGetRuleSummary(FD);
387  }
388  }
389 
390  // For CoreGraphics ('CG') and CoreVideo ('CV') types.
391  if (cocoa::isRefType(RetTy, "CG", FName) ||
392  cocoa::isRefType(RetTy, "CV", FName)) {
393  if (isRetain(FD, FName))
394  return getUnarySummary(FT, IncRef);
395  else
396  return getCFCreateGetRuleSummary(FD);
397  }
398 
399  // For all other CF-style types, use the Create/Get
400  // rule for summaries but don't support Retain functions
401  // with framework-specific prefixes.
402  if (coreFoundation::isCFObjectRef(RetTy)) {
403  return getCFCreateGetRuleSummary(FD);
404  }
405 
406  if (FD->hasAttr<CFAuditedTransferAttr>()) {
407  return getCFCreateGetRuleSummary(FD);
408  }
409  }
410 
411  // Check for release functions, the only kind of functions that we care
412  // about that don't return a pointer type.
413  if (FName.startswith("CG") || FName.startswith("CF")) {
414  // Test for 'CGCF'.
415  FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
416 
417  if (isRelease(FD, FName))
418  return getUnarySummary(FT, DecRef);
419  else {
420  assert(ScratchArgs.isEmpty());
421  // Remaining CoreFoundation and CoreGraphics functions.
422  // We use to assume that they all strictly followed the ownership idiom
423  // and that ownership cannot be transferred. While this is technically
424  // correct, many methods allow a tracked object to escape. For example:
425  //
426  // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
427  // CFDictionaryAddValue(y, key, x);
428  // CFRelease(x);
429  // ... it is okay to use 'x' since 'y' has a reference to it
430  //
431  // We handle this and similar cases with the follow heuristic. If the
432  // function name contains "InsertValue", "SetValue", "AddValue",
433  // "AppendValue", or "SetAttribute", then we assume that arguments may
434  // "escape." This means that something else holds on to the object,
435  // allowing it be used even after its local retain count drops to 0.
436  ArgEffectKind E =
437  (StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
438  StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
439  StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
440  StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
441  StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
442  ? MayEscape
443  : DoNothing;
444 
445  return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
447  }
448  }
449 
450  return nullptr;
451 }
452 
453 const RetainSummary *
454 RetainSummaryManager::generateSummary(const FunctionDecl *FD,
455  bool &AllowAnnotations) {
456  // We generate "stop" summaries for implicitly defined functions.
457  if (FD->isImplicit())
458  return getPersistentStopSummary();
459 
460  const IdentifierInfo *II = FD->getIdentifier();
461 
462  StringRef FName = II ? II->getName() : "";
463 
464  // Strip away preceding '_'. Doing this here will effect all the checks
465  // down below.
466  FName = FName.substr(FName.find_first_not_of('_'));
467 
468  // Inspect the result type. Strip away any typedefs.
469  const auto *FT = FD->getType()->getAs<FunctionType>();
470  QualType RetTy = FT->getReturnType();
471 
472  if (TrackOSObjects)
473  if (const RetainSummary *S = getSummaryForOSObject(FD, FName, RetTy))
474  return S;
475 
476  if (TrackObjCAndCFObjects)
477  if (const RetainSummary *S =
478  getSummaryForObjCOrCFObject(FD, FName, RetTy, FT, AllowAnnotations))
479  return S;
480 
481  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
482  if (!(TrackOSObjects && isOSObjectRelated(MD)))
483  return getPersistentSummary(RetEffect::MakeNoRet(),
484  ArgEffects(AF.getEmptyMap()),
488 
489  return getDefaultSummary();
490 }
491 
492 const RetainSummary *
493 RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
494  // If we don't know what function we're calling, use our default summary.
495  if (!FD)
496  return getDefaultSummary();
497 
498  // Look up a summary in our cache of FunctionDecls -> Summaries.
499  FuncSummariesTy::iterator I = FuncSummaries.find(FD);
500  if (I != FuncSummaries.end())
501  return I->second;
502 
503  // No summary? Generate one.
504  bool AllowAnnotations = true;
505  const RetainSummary *S = generateSummary(FD, AllowAnnotations);
506 
507  // Annotations override defaults.
508  if (AllowAnnotations)
509  updateSummaryFromAnnotations(S, FD);
510 
511  FuncSummaries[FD] = S;
512  return S;
513 }
514 
515 //===----------------------------------------------------------------------===//
516 // Summary creation for functions (largely uses of Core Foundation).
517 //===----------------------------------------------------------------------===//
518 
520  switch (E.getKind()) {
521  case DoNothing:
522  case Autorelease:
524  case IncRef:
529  case MayEscape:
530  case StopTracking:
531  case StopTrackingHard:
532  return E.withKind(StopTrackingHard);
533  case DecRef:
536  case Dealloc:
537  return E.withKind(Dealloc);
538  }
539 
540  llvm_unreachable("Unknown ArgEffect kind");
541 }
542 
543 void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
544  const CallEvent &Call) {
545  if (Call.hasNonZeroCallbackArg()) {
546  ArgEffect RecEffect =
547  getStopTrackingHardEquivalent(S->getReceiverEffect());
548  ArgEffect DefEffect =
549  getStopTrackingHardEquivalent(S->getDefaultArgEffect());
550 
551  ArgEffects ScratchArgs(AF.getEmptyMap());
552  ArgEffects CustomArgEffects = S->getArgEffects();
553  for (ArgEffects::iterator I = CustomArgEffects.begin(),
554  E = CustomArgEffects.end();
555  I != E; ++I) {
556  ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
557  if (Translated.getKind() != DefEffect.getKind())
558  ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
559  }
560 
562 
563  // Special cases where the callback argument CANNOT free the return value.
564  // This can generally only happen if we know that the callback will only be
565  // called when the return value is already being deallocated.
566  if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
567  if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
568  // When the CGBitmapContext is deallocated, the callback here will free
569  // the associated data buffer.
570  // The callback in dispatch_data_create frees the buffer, but not
571  // the data object.
572  if (Name->isStr("CGBitmapContextCreateWithData") ||
573  Name->isStr("dispatch_data_create"))
574  RE = S->getRetEffect();
575  }
576  }
577 
578  S = getPersistentSummary(RE, ScratchArgs, RecEffect, DefEffect);
579  }
580 
581  // Special case '[super init];' and '[self init];'
582  //
583  // Even though calling '[super init]' without assigning the result to self
584  // and checking if the parent returns 'nil' is a bad pattern, it is common.
585  // Additionally, our Self Init checker already warns about it. To avoid
586  // overwhelming the user with messages from both checkers, we model the case
587  // of '[super init]' in cases when it is not consumed by another expression
588  // as if the call preserves the value of 'self'; essentially, assuming it can
589  // never fail and return 'nil'.
590  // Note, we don't want to just stop tracking the value since we want the
591  // RetainCount checker to report leaks and use-after-free if SelfInit checker
592  // is turned off.
593  if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
594  if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
595 
596  // Check if the message is not consumed, we know it will not be used in
597  // an assignment, ex: "self = [super init]".
598  const Expr *ME = MC->getOriginExpr();
599  const LocationContext *LCtx = MC->getLocationContext();
601  if (!PM.isConsumedExpr(ME)) {
602  RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
603  ModifiableSummaryTemplate->setReceiverEffect(ArgEffect(DoNothing));
604  ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
605  }
606  }
607  }
608 }
609 
610 const RetainSummary *
611 RetainSummaryManager::getSummary(const CallEvent &Call,
612  QualType ReceiverType) {
613  const RetainSummary *Summ;
614  switch (Call.getKind()) {
615  case CE_Function:
616  case CE_CXXMember:
618  case CE_CXXConstructor:
619  case CE_CXXAllocator:
620  Summ = getFunctionSummary(cast_or_null<FunctionDecl>(Call.getDecl()));
621  break;
622  case CE_Block:
623  case CE_CXXDestructor:
624  // FIXME: These calls are currently unsupported.
625  return getPersistentStopSummary();
626  case CE_ObjCMessage: {
627  const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
628  if (Msg.isInstanceMessage())
629  Summ = getInstanceMethodSummary(Msg, ReceiverType);
630  else
631  Summ = getClassMethodSummary(Msg);
632  break;
633  }
634  }
635 
636  updateSummaryForCall(Summ, Call);
637 
638  assert(Summ && "Unknown call type?");
639  return Summ;
640 }
641 
642 
643 const RetainSummary *
644 RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
646  return getCFSummaryCreateRule(FD);
647 
648  return getCFSummaryGetRule(FD);
649 }
650 
651 bool RetainSummaryManager::isTrustedReferenceCountImplementation(
652  const FunctionDecl *FD) {
653  return hasRCAnnotation(FD, "rc_ownership_trusted_implementation");
654 }
655 
657 RetainSummaryManager::canEval(const CallExpr *CE, const FunctionDecl *FD,
658  bool &hasTrustedImplementationAnnotation) {
659 
660  IdentifierInfo *II = FD->getIdentifier();
661  if (!II)
662  return None;
663 
664  StringRef FName = II->getName();
665  FName = FName.substr(FName.find_first_not_of('_'));
666 
667  QualType ResultTy = CE->getCallReturnType(Ctx);
668  if (ResultTy->isObjCIdType()) {
669  if (II->isStr("NSMakeCollectable"))
670  return BehaviorSummary::Identity;
671  } else if (ResultTy->isPointerType()) {
672  // Handle: (CF|CG|CV)Retain
673  // CFAutorelease
674  // It's okay to be a little sloppy here.
675  if (FName == "CMBufferQueueDequeueAndRetain" ||
676  FName == "CMBufferQueueDequeueIfDataReadyAndRetain") {
677  // Part of: <rdar://problem/39390714>.
678  // These are not retain. They just return something and retain it.
679  return None;
680  }
681  if (cocoa::isRefType(ResultTy, "CF", FName) ||
682  cocoa::isRefType(ResultTy, "CG", FName) ||
683  cocoa::isRefType(ResultTy, "CV", FName))
684  if (isRetain(FD, FName) || isAutorelease(FD, FName) ||
685  isMakeCollectable(FName))
686  return BehaviorSummary::Identity;
687 
688  // safeMetaCast is called by OSDynamicCast.
689  // We assume that OSDynamicCast is either an identity (cast is OK,
690  // the input was non-zero),
691  // or that it returns zero (when the cast failed, or the input
692  // was zero).
693  if (TrackOSObjects && isOSObjectDynamicCast(FName)) {
694  return BehaviorSummary::IdentityOrZero;
695  }
696 
697  const FunctionDecl* FDD = FD->getDefinition();
698  if (FDD && isTrustedReferenceCountImplementation(FDD)) {
699  hasTrustedImplementationAnnotation = true;
700  return BehaviorSummary::Identity;
701  }
702  }
703 
704  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
705  const CXXRecordDecl *Parent = MD->getParent();
706  if (TrackOSObjects && Parent && isOSObjectSubclass(Parent))
707  if (FName == "release" || FName == "retain")
708  return BehaviorSummary::NoOp;
709  }
710 
711  return None;
712 }
713 
714 const RetainSummary *
715 RetainSummaryManager::getUnarySummary(const FunctionType* FT,
716  ArgEffectKind AE) {
717 
718  // Unary functions have no arg effects by definition.
719  ArgEffects ScratchArgs(AF.getEmptyMap());
720 
721  // Sanity check that this is *really* a unary function. This can
722  // happen if people do weird things.
723  const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
724  if (!FTP || FTP->getNumParams() != 1)
725  return getPersistentStopSummary();
726 
727  ArgEffect Effect(AE, ObjKind::CF);
728 
729  ScratchArgs = AF.add(ScratchArgs, 0, Effect);
730  return getPersistentSummary(RetEffect::MakeNoRet(),
731  ScratchArgs,
733 }
734 
735 const RetainSummary *
736 RetainSummaryManager::getOSSummaryRetainRule(const FunctionDecl *FD) {
737  return getPersistentSummary(RetEffect::MakeNoRet(),
738  AF.getEmptyMap(),
739  /*ReceiverEff=*/ArgEffect(DoNothing),
740  /*DefaultEff=*/ArgEffect(DoNothing),
741  /*ThisEff=*/ArgEffect(IncRef, ObjKind::OS));
742 }
743 
744 const RetainSummary *
745 RetainSummaryManager::getOSSummaryReleaseRule(const FunctionDecl *FD) {
746  return getPersistentSummary(RetEffect::MakeNoRet(),
747  AF.getEmptyMap(),
748  /*ReceiverEff=*/ArgEffect(DoNothing),
749  /*DefaultEff=*/ArgEffect(DoNothing),
750  /*ThisEff=*/ArgEffect(DecRef, ObjKind::OS));
751 }
752 
753 const RetainSummary *
754 RetainSummaryManager::getOSSummaryFreeRule(const FunctionDecl *FD) {
755  return getPersistentSummary(RetEffect::MakeNoRet(),
756  AF.getEmptyMap(),
757  /*ReceiverEff=*/ArgEffect(DoNothing),
758  /*DefaultEff=*/ArgEffect(DoNothing),
759  /*ThisEff=*/ArgEffect(Dealloc, ObjKind::OS));
760 }
761 
762 const RetainSummary *
763 RetainSummaryManager::getOSSummaryCreateRule(const FunctionDecl *FD) {
764  return getPersistentSummary(RetEffect::MakeOwned(ObjKind::OS),
765  AF.getEmptyMap());
766 }
767 
768 const RetainSummary *
769 RetainSummaryManager::getOSSummaryGetRule(const FunctionDecl *FD) {
770  return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::OS),
771  AF.getEmptyMap());
772 }
773 
774 const RetainSummary *
775 RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
776  return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
777  ArgEffects(AF.getEmptyMap()));
778 }
779 
780 const RetainSummary *
781 RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
782  return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::CF),
783  ArgEffects(AF.getEmptyMap()),
785 }
786 
787 
788 
789 
790 //===----------------------------------------------------------------------===//
791 // Summary creation for Selectors.
792 //===----------------------------------------------------------------------===//
793 
795 RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
796  const Decl *D) {
797  if (hasAnyEnabledAttrOf<NSReturnsRetainedAttr>(D, RetTy))
798  return ObjCAllocRetE;
799 
800  if (auto K = hasAnyEnabledAttrOf<CFReturnsRetainedAttr, OSReturnsRetainedAttr,
801  GeneralizedReturnsRetainedAttr>(D, RetTy))
802  return RetEffect::MakeOwned(*K);
803 
804  if (auto K = hasAnyEnabledAttrOf<
805  CFReturnsNotRetainedAttr, OSReturnsNotRetainedAttr,
806  GeneralizedReturnsNotRetainedAttr, NSReturnsNotRetainedAttr,
807  NSReturnsAutoreleasedAttr>(D, RetTy))
808  return RetEffect::MakeNotOwned(*K);
809 
810  if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
811  for (const auto *PD : MD->overridden_methods())
812  if (auto RE = getRetEffectFromAnnotations(RetTy, PD))
813  return RE;
814 
815  return None;
816 }
817 
818 /// \return Whether the chain of typedefs starting from {@code QT}
819 /// has a typedef with a given name {@code Name}.
820 static bool hasTypedefNamed(QualType QT,
821  StringRef Name) {
822  while (auto *T = dyn_cast<TypedefType>(QT)) {
823  const auto &Context = T->getDecl()->getASTContext();
824  if (T->getDecl()->getIdentifier() == &Context.Idents.get(Name))
825  return true;
826  QT = T->getDecl()->getUnderlyingType();
827  }
828  return false;
829 }
830 
831 static QualType getCallableReturnType(const NamedDecl *ND) {
832  if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
833  return FD->getReturnType();
834  } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(ND)) {
835  return MD->getReturnType();
836  } else {
837  llvm_unreachable("Unexpected decl");
838  }
839 }
840 
841 bool RetainSummaryManager::applyParamAnnotationEffect(
842  const ParmVarDecl *pd, unsigned parm_idx, const NamedDecl *FD,
843  RetainSummaryTemplate &Template) {
844  QualType QT = pd->getType();
845  if (auto K =
846  hasAnyEnabledAttrOf<NSConsumedAttr, CFConsumedAttr, OSConsumedAttr,
847  GeneralizedConsumedAttr>(pd, QT)) {
848  Template->addArg(AF, parm_idx, ArgEffect(DecRef, *K));
849  return true;
850  } else if (auto K = hasAnyEnabledAttrOf<
851  CFReturnsRetainedAttr, OSReturnsRetainedAttr,
852  OSReturnsRetainedOnNonZeroAttr, OSReturnsRetainedOnZeroAttr,
853  GeneralizedReturnsRetainedAttr>(pd, QT)) {
854 
855  // For OSObjects, we try to guess whether the object is created based
856  // on the return value.
857  if (K == ObjKind::OS) {
858  QualType QT = getCallableReturnType(FD);
859 
860  bool HasRetainedOnZero = pd->hasAttr<OSReturnsRetainedOnZeroAttr>();
861  bool HasRetainedOnNonZero = pd->hasAttr<OSReturnsRetainedOnNonZeroAttr>();
862 
863  // The usual convention is to create an object on non-zero return, but
864  // it's reverted if the typedef chain has a typedef kern_return_t,
865  // because kReturnSuccess constant is defined as zero.
866  // The convention can be overwritten by custom attributes.
867  bool SuccessOnZero =
868  HasRetainedOnZero ||
869  (hasTypedefNamed(QT, "kern_return_t") && !HasRetainedOnNonZero);
870  bool ShouldSplit = !QT.isNull() && !QT->isVoidType();
872  if (ShouldSplit && SuccessOnZero) {
874  } else if (ShouldSplit && (!SuccessOnZero || HasRetainedOnNonZero)) {
876  }
877  Template->addArg(AF, parm_idx, ArgEffect(AK, ObjKind::OS));
878  }
879 
880  // For others:
881  // Do nothing. Retained out parameters will either point to a +1 reference
882  // or NULL, but the way you check for failure differs depending on the
883  // API. Consequently, we don't have a good way to track them yet.
884  return true;
885  } else if (auto K = hasAnyEnabledAttrOf<CFReturnsNotRetainedAttr,
886  OSReturnsNotRetainedAttr,
887  GeneralizedReturnsNotRetainedAttr>(
888  pd, QT)) {
889  Template->addArg(AF, parm_idx, ArgEffect(UnretainedOutParameter, *K));
890  return true;
891  }
892 
893  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
894  for (const auto *OD : MD->overridden_methods()) {
895  const ParmVarDecl *OP = OD->parameters()[parm_idx];
896  if (applyParamAnnotationEffect(OP, parm_idx, OD, Template))
897  return true;
898  }
899  }
900 
901  return false;
902 }
903 
904 void
905 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
906  const FunctionDecl *FD) {
907  if (!FD)
908  return;
909 
910  assert(Summ && "Must have a summary to add annotations to.");
911  RetainSummaryTemplate Template(Summ, *this);
912 
913  // Effects on the parameters.
914  unsigned parm_idx = 0;
915  for (auto pi = FD->param_begin(),
916  pe = FD->param_end(); pi != pe; ++pi, ++parm_idx)
917  applyParamAnnotationEffect(*pi, parm_idx, FD, Template);
918 
919  QualType RetTy = FD->getReturnType();
920  if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
921  Template->setRetEffect(*RetE);
922 
923  if (hasAnyEnabledAttrOf<OSConsumesThisAttr>(FD, RetTy))
924  Template->setThisEffect(ArgEffect(DecRef, ObjKind::OS));
925 }
926 
927 void
928 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
929  const ObjCMethodDecl *MD) {
930  if (!MD)
931  return;
932 
933  assert(Summ && "Must have a valid summary to add annotations to");
934  RetainSummaryTemplate Template(Summ, *this);
935 
936  // Effects on the receiver.
937  if (hasAnyEnabledAttrOf<NSConsumesSelfAttr>(MD, MD->getReturnType()))
938  Template->setReceiverEffect(ArgEffect(DecRef, ObjKind::ObjC));
939 
940  // Effects on the parameters.
941  unsigned parm_idx = 0;
942  for (auto pi = MD->param_begin(), pe = MD->param_end(); pi != pe;
943  ++pi, ++parm_idx)
944  applyParamAnnotationEffect(*pi, parm_idx, MD, Template);
945 
946  QualType RetTy = MD->getReturnType();
947  if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
948  Template->setRetEffect(*RetE);
949 }
950 
951 const RetainSummary *
952 RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
953  Selector S, QualType RetTy) {
954  // Any special effects?
955  ArgEffect ReceiverEff = ArgEffect(DoNothing, ObjKind::ObjC);
956  RetEffect ResultEff = RetEffect::MakeNoRet();
957 
958  // Check the method family, and apply any default annotations.
959  switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
960  case OMF_None:
961  case OMF_initialize:
962  case OMF_performSelector:
963  // Assume all Objective-C methods follow Cocoa Memory Management rules.
964  // FIXME: Does the non-threaded performSelector family really belong here?
965  // The selector could be, say, @selector(copy).
966  if (cocoa::isCocoaObjectRef(RetTy))
968  else if (coreFoundation::isCFObjectRef(RetTy)) {
969  // ObjCMethodDecl currently doesn't consider CF objects as valid return
970  // values for alloc, new, copy, or mutableCopy, so we have to
971  // double-check with the selector. This is ugly, but there aren't that
972  // many Objective-C methods that return CF objects, right?
973  if (MD) {
974  switch (S.getMethodFamily()) {
975  case OMF_alloc:
976  case OMF_new:
977  case OMF_copy:
978  case OMF_mutableCopy:
979  ResultEff = RetEffect::MakeOwned(ObjKind::CF);
980  break;
981  default:
983  break;
984  }
985  } else {
987  }
988  }
989  break;
990  case OMF_init:
991  ResultEff = ObjCInitRetE;
992  ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC);
993  break;
994  case OMF_alloc:
995  case OMF_new:
996  case OMF_copy:
997  case OMF_mutableCopy:
998  if (cocoa::isCocoaObjectRef(RetTy))
999  ResultEff = ObjCAllocRetE;
1000  else if (coreFoundation::isCFObjectRef(RetTy))
1001  ResultEff = RetEffect::MakeOwned(ObjKind::CF);
1002  break;
1003  case OMF_autorelease:
1004  ReceiverEff = ArgEffect(Autorelease, ObjKind::ObjC);
1005  break;
1006  case OMF_retain:
1007  ReceiverEff = ArgEffect(IncRef, ObjKind::ObjC);
1008  break;
1009  case OMF_release:
1010  ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC);
1011  break;
1012  case OMF_dealloc:
1013  ReceiverEff = ArgEffect(Dealloc, ObjKind::ObjC);
1014  break;
1015  case OMF_self:
1016  // -self is handled specially by the ExprEngine to propagate the receiver.
1017  break;
1018  case OMF_retainCount:
1019  case OMF_finalize:
1020  // These methods don't return objects.
1021  break;
1022  }
1023 
1024  // If one of the arguments in the selector has the keyword 'delegate' we
1025  // should stop tracking the reference count for the receiver. This is
1026  // because the reference count is quite possibly handled by a delegate
1027  // method.
1028  if (S.isKeywordSelector()) {
1029  for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1030  StringRef Slot = S.getNameForSlot(i);
1031  if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1032  if (ResultEff == ObjCInitRetE)
1033  ResultEff = RetEffect::MakeNoRetHard();
1034  else
1035  ReceiverEff = ArgEffect(StopTrackingHard, ObjKind::ObjC);
1036  }
1037  }
1038  }
1039 
1040  if (ReceiverEff.getKind() == DoNothing &&
1041  ResultEff.getKind() == RetEffect::NoRet)
1042  return getDefaultSummary();
1043 
1044  return getPersistentSummary(ResultEff, ArgEffects(AF.getEmptyMap()),
1045  ArgEffect(ReceiverEff), ArgEffect(MayEscape));
1046 }
1047 
1048 const RetainSummary *RetainSummaryManager::getInstanceMethodSummary(
1049  const ObjCMethodCall &Msg,
1050  QualType ReceiverType) {
1051  const ObjCInterfaceDecl *ReceiverClass = nullptr;
1052 
1053  // We do better tracking of the type of the object than the core ExprEngine.
1054  // See if we have its type in our private state.
1055  if (!ReceiverType.isNull())
1056  if (const auto *PT = ReceiverType->getAs<ObjCObjectPointerType>())
1057  ReceiverClass = PT->getInterfaceDecl();
1058 
1059  // If we don't know what kind of object this is, fall back to its static type.
1060  if (!ReceiverClass)
1061  ReceiverClass = Msg.getReceiverInterface();
1062 
1063  // FIXME: The receiver could be a reference to a class, meaning that
1064  // we should use the class method.
1065  // id x = [NSObject class];
1066  // [x performSelector:... withObject:... afterDelay:...];
1067  Selector S = Msg.getSelector();
1068  const ObjCMethodDecl *Method = Msg.getDecl();
1069  if (!Method && ReceiverClass)
1070  Method = ReceiverClass->getInstanceMethod(S);
1071 
1072  return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1073  ObjCMethodSummaries);
1074 }
1075 
1076 const RetainSummary *
1077 RetainSummaryManager::getMethodSummary(Selector S,
1078  const ObjCInterfaceDecl *ID,
1079  const ObjCMethodDecl *MD, QualType RetTy,
1080  ObjCMethodSummariesTy &CachedSummaries) {
1081 
1082  // Objective-C method summaries are only applicable to ObjC and CF objects.
1083  if (!TrackObjCAndCFObjects)
1084  return getDefaultSummary();
1085 
1086  // Look up a summary in our summary cache.
1087  const RetainSummary *Summ = CachedSummaries.find(ID, S);
1088 
1089  if (!Summ) {
1090  Summ = getStandardMethodSummary(MD, S, RetTy);
1091 
1092  // Annotations override defaults.
1093  updateSummaryFromAnnotations(Summ, MD);
1094 
1095  // Memoize the summary.
1096  CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1097  }
1098 
1099  return Summ;
1100 }
1101 
1102 void RetainSummaryManager::InitializeClassMethodSummaries() {
1103  ArgEffects ScratchArgs = AF.getEmptyMap();
1104 
1105  // Create the [NSAssertionHandler currentHander] summary.
1106  addClassMethSummary("NSAssertionHandler", "currentHandler",
1107  getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::ObjC),
1108  ScratchArgs));
1109 
1110  // Create the [NSAutoreleasePool addObject:] summary.
1111  ScratchArgs = AF.add(ScratchArgs, 0, ArgEffect(Autorelease));
1112  addClassMethSummary("NSAutoreleasePool", "addObject",
1113  getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
1116 }
1117 
1118 void RetainSummaryManager::InitializeMethodSummaries() {
1119 
1120  ArgEffects ScratchArgs = AF.getEmptyMap();
1121  // Create the "init" selector. It just acts as a pass-through for the
1122  // receiver.
1123  const RetainSummary *InitSumm = getPersistentSummary(
1124  ObjCInitRetE, ScratchArgs, ArgEffect(DecRef, ObjKind::ObjC));
1125  addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1126 
1127  // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1128  // claims the receiver and returns a retained object.
1129  addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1130  InitSumm);
1131 
1132  // The next methods are allocators.
1133  const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE,
1134  ScratchArgs);
1135  const RetainSummary *CFAllocSumm =
1136  getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs);
1137 
1138  // Create the "retain" selector.
1139  RetEffect NoRet = RetEffect::MakeNoRet();
1140  const RetainSummary *Summ = getPersistentSummary(
1141  NoRet, ScratchArgs, ArgEffect(IncRef, ObjKind::ObjC));
1142  addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1143 
1144  // Create the "release" selector.
1145  Summ = getPersistentSummary(NoRet, ScratchArgs,
1147  addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1148 
1149  // Create the -dealloc summary.
1150  Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Dealloc,
1151  ObjKind::ObjC));
1152  addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1153 
1154  // Create the "autorelease" selector.
1155  Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Autorelease,
1156  ObjKind::ObjC));
1157  addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1158 
1159  // For NSWindow, allocated objects are (initially) self-owned.
1160  // FIXME: For now we opt for false negatives with NSWindow, as these objects
1161  // self-own themselves. However, they only do this once they are displayed.
1162  // Thus, we need to track an NSWindow's display status.
1163  // This is tracked in <rdar://problem/6062711>.
1164  // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1165  const RetainSummary *NoTrackYet =
1166  getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
1168 
1169  addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1170 
1171  // For NSPanel (which subclasses NSWindow), allocated objects are not
1172  // self-owned.
1173  // FIXME: For now we don't track NSPanels. object for the same reason
1174  // as for NSWindow objects.
1175  addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1176 
1177  // For NSNull, objects returned by +null are singletons that ignore
1178  // retain/release semantics. Just don't track them.
1179  // <rdar://problem/12858915>
1180  addClassMethSummary("NSNull", "null", NoTrackYet);
1181 
1182  // Don't track allocated autorelease pools, as it is okay to prematurely
1183  // exit a method.
1184  addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1185  addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1186  addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
1187 
1188  // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1189  addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType");
1190  addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType");
1191 
1192  // Create summaries for CIContext, 'createCGImage' and
1193  // 'createCGLayerWithSize'. These objects are CF objects, and are not
1194  // automatically garbage collected.
1195  addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect");
1196  addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1197  "format", "colorSpace");
1198  addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info");
1199 }
1200 
1202  ASTContext &Ctx = MD->getASTContext();
1203  LangOptions L = Ctx.getLangOpts();
1204  RetainSummaryManager M(Ctx, L.ObjCAutoRefCount,
1205  /*TrackNSAndCFObjects=*/true,
1206  /*TrackOSObjects=*/false);
1207  const RetainSummary *S = M.getMethodSummary(MD);
1208  CallEffects CE(S->getRetEffect(), S->getReceiverEffect());
1209  unsigned N = MD->param_size();
1210  for (unsigned i = 0; i < N; ++i) {
1211  CE.Args.push_back(S->getArg(i));
1212  }
1213  return CE;
1214 }
1215 
1217  ASTContext &Ctx = FD->getASTContext();
1218  LangOptions L = Ctx.getLangOpts();
1219  RetainSummaryManager M(Ctx, L.ObjCAutoRefCount,
1220  /*TrackNSAndCFObjects=*/true,
1221  /*TrackOSObjects=*/false);
1222  const RetainSummary *S = M.getFunctionSummary(FD);
1223  CallEffects CE(S->getRetEffect());
1224  unsigned N = FD->param_size();
1225  for (unsigned i = 0; i < N; ++i) {
1226  CE.Args.push_back(S->getArg(i));
1227  }
1228  return CE;
1229 }
Indicates that the tracked object is a generalized object.
Indicates that the tracked object is a CF object.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:1955
Encapsulates the retain count semantics on the arguments, return value, and receiver (if any) of a fu...
Represents a function declaration or definition.
Definition: Decl.h:1738
There is no effect.
Smart pointer class that efficiently represents Objective-C method names.
ObjKind
Determines the object kind of a tracked object.
A (possibly-)qualified type.
Definition: Type.h:638
unsigned param_size() const
Definition: DeclObjC.h:341
static bool isOSObjectDynamicCast(StringRef S)
The argument has its reference count decreased by 1 to model a transferred bridge cast under ARC...
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3355
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
All typestate tracking of the object ceases.
static RetEffect MakeOwned(ObjKind o)
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
The argument has its reference count increased by 1.
StringRef P
bool isCocoaObjectRef(QualType T)
The argument is treated as if an -autorelease message had been sent to the referenced object...
Indicates that no retain count information is tracked for the return value.
param_const_iterator param_end() const
Definition: DeclObjC.h:352
size_t param_size() const
Definition: Decl.h:2278
bool isConsumedExpr(Expr *E) const
Definition: ParentMap.cpp:160
static RetEffect MakeNoRet()
QualType getReturnType() const
Definition: Decl.h:2302
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6748
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
Represents a parameter to a function.
Definition: Decl.h:1550
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
bool isObjCIdType() const
Definition: Type.h:6422
static bool isAutorelease(const FunctionDecl *FD, StringRef FName)
const ObjCInterfaceDecl * getReceiverInterface() const
Get the interface for the receiver.
Definition: CallEvent.h:1034
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
IdentifierTable & Idents
Definition: ASTContext.h:566
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2262
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:986
The argument has its reference count decreased by 1.
bool followsCreateRule(const FunctionDecl *FD)
Represents any expression that calls an Objective-C method.
Definition: CallEvent.h:970
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +0 v...
virtual Kind getKind() const =0
Returns the kind of call this is.
bool hasNonZeroCallbackArg() const
Returns true if any of the arguments appear to represent callbacks.
Definition: CallEvent.cpp:154
Selector GetNullarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing a nullary selector.
Definition: ASTContext.h:2953
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
static bool isOSObjectSubclass(const Decl *D)
static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation)
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1172
QualType getReturnType() const
Definition: DeclObjC.h:323
param_iterator param_begin()
Definition: Decl.h:2274
NodeId Parent
Definition: ASTDiff.cpp:192
bool hasAttr() const
Definition: DeclBase.h:531
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1613
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3687
The argument is treated as potentially escaping, meaning that even when its reference count hits 0 it...
This represents one expression.
Definition: Expr.h:106
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:547
static constexpr bool isOneOf()
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
static bool isOSObjectRelated(const CXXMethodDecl *MD)
A function is OSObject related if it is declared on a subclass of OSObject, or any of the parameters ...
virtual const Decl * getDecl() const
Returns the declaration of the function or method that will be called.
Definition: CallEvent.h:235
The argument is treated as if the referenced object was deallocated.
static bool isRelease(const FunctionDecl *FD, StringRef FName)
static RetEffect MakeNotOwned(ObjKind o)
unsigned getNumArgs() const
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:703
Represents a C function or static C++ member function call.
Definition: CallEvent.h:528
ArgEffectKind getKind() const
ObjCMethodFamily getMethodFamily() const
Derive the conventional family of this method.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
QualType getReturnType() const
Definition: Type.h:3613
Indicates that the tracked object is an Objective-C object.
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:376
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2041
static bool isMakeCollectable(StringRef FName)
Performs the combined functionality of DecRef and StopTrackingHard.
A key identifying a summary.
const ObjCMethodDecl * getDecl() const override
Definition: CallEvent.h:998
StringRef getName() const
Return the actual identifier string.
Selector getSelector() const
Definition: CallEvent.h:1018
Dataflow Directional Tag Classes.
bool isRefType(QualType RetTy, StringRef Prefix, StringRef Name=StringRef())
static RetEffect MakeNoRetHard()
const internal::VariadicDynCastAllOfMatcher< Decl, CXXRecordDecl > cxxRecordDecl
Matches C++ class declarations.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:971
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2166
bool isKeywordSelector() const
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1396
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:171
param_iterator param_end()
Definition: Decl.h:2275
Represents a pointer to an Objective C object.
Definition: Type.h:5794
bool isInstanceMessage() const
Definition: CallEvent.h:1010
static ArgEffect getStopTrackingHardEquivalent(ArgEffect E)
Indicates that the tracking object is a descendant of a referenced-counted OSObject, used in the Darwin kernel.
static bool classof(const OMPClause *T)
static bool isRetain(const FunctionDecl *FD, StringRef FName)
param_const_iterator param_begin() const
Definition: DeclObjC.h:348
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:513
ArgEffect withKind(ArgEffectKind NewK)
No particular method family.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
All typestate tracking of the object ceases.
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
Selector GetUnarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing an unary selector.
Definition: ASTContext.h:2959
bool isVoidType() const
Definition: Type.h:6544
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
static bool isOSIteratorSubclass(const Decl *D)
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2396
static bool isSubclass(const Decl *D, StringRef ClassName)
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
bool isPointerType() const
Definition: Type.h:6296
QualType getType() const
Definition: Decl.h:648
An ArgEffect summarizes the retain count behavior on an argument or receiver to a function or method...
This represents a decl that may have a name.
Definition: Decl.h:249
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
Definition: DeclObjC.h:1087
AnalysisDeclContext * getAnalysisDeclContext() const
static CallEffects getEffect(const ObjCMethodDecl *MD)
Return the CallEfect for a given Objective-C method.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:707
Attr - This represents one attribute.
Definition: Attr.h:44
internal::Matcher< Decl > DeclarationMatcher
Types of matchers for the top-level classes in the AST class hierarchy.
Definition: ASTMatchers.h:145
RetEffect summarizes a call&#39;s retain/release behavior with respect to its return value.