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