xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Analysis/RetainSummaryManager.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //== RetainSummaryManager.cpp - Summaries for reference counting --*- C++ -*--//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg //  This file defines summaries implementation for retain counting, which
107330f729Sjoerg //  implements a reference count checker for Core Foundation, Cocoa
117330f729Sjoerg //  and OSObject (on Mac OS X).
127330f729Sjoerg //
137330f729Sjoerg //===----------------------------------------------------------------------===//
147330f729Sjoerg 
157330f729Sjoerg #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
167330f729Sjoerg #include "clang/Analysis/RetainSummaryManager.h"
177330f729Sjoerg #include "clang/AST/Attr.h"
187330f729Sjoerg #include "clang/AST/DeclCXX.h"
197330f729Sjoerg #include "clang/AST/DeclObjC.h"
207330f729Sjoerg #include "clang/AST/ParentMap.h"
217330f729Sjoerg #include "clang/ASTMatchers/ASTMatchFinder.h"
227330f729Sjoerg 
237330f729Sjoerg using namespace clang;
247330f729Sjoerg using namespace ento;
257330f729Sjoerg 
267330f729Sjoerg template <class T>
isOneOf()277330f729Sjoerg constexpr static bool isOneOf() {
287330f729Sjoerg   return false;
297330f729Sjoerg }
307330f729Sjoerg 
317330f729Sjoerg /// Helper function to check whether the class is one of the
327330f729Sjoerg /// rest of varargs.
337330f729Sjoerg template <class T, class P, class... ToCompare>
isOneOf()347330f729Sjoerg constexpr static bool isOneOf() {
357330f729Sjoerg   return std::is_same<T, P>::value || isOneOf<T, ToCompare...>();
367330f729Sjoerg }
377330f729Sjoerg 
387330f729Sjoerg namespace {
397330f729Sjoerg 
407330f729Sjoerg /// Fake attribute class for RC* attributes.
417330f729Sjoerg struct GeneralizedReturnsRetainedAttr {
classof__anon962e9d040111::GeneralizedReturnsRetainedAttr427330f729Sjoerg   static bool classof(const Attr *A) {
437330f729Sjoerg     if (auto AA = dyn_cast<AnnotateAttr>(A))
447330f729Sjoerg       return AA->getAnnotation() == "rc_ownership_returns_retained";
457330f729Sjoerg     return false;
467330f729Sjoerg   }
477330f729Sjoerg };
487330f729Sjoerg 
497330f729Sjoerg struct GeneralizedReturnsNotRetainedAttr {
classof__anon962e9d040111::GeneralizedReturnsNotRetainedAttr507330f729Sjoerg   static bool classof(const Attr *A) {
517330f729Sjoerg     if (auto AA = dyn_cast<AnnotateAttr>(A))
527330f729Sjoerg       return AA->getAnnotation() == "rc_ownership_returns_not_retained";
537330f729Sjoerg     return false;
547330f729Sjoerg   }
557330f729Sjoerg };
567330f729Sjoerg 
577330f729Sjoerg struct GeneralizedConsumedAttr {
classof__anon962e9d040111::GeneralizedConsumedAttr587330f729Sjoerg   static bool classof(const Attr *A) {
597330f729Sjoerg     if (auto AA = dyn_cast<AnnotateAttr>(A))
607330f729Sjoerg       return AA->getAnnotation() == "rc_ownership_consumed";
617330f729Sjoerg     return false;
627330f729Sjoerg   }
637330f729Sjoerg };
647330f729Sjoerg 
657330f729Sjoerg }
667330f729Sjoerg 
677330f729Sjoerg template <class T>
hasAnyEnabledAttrOf(const Decl * D,QualType QT)687330f729Sjoerg Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D,
697330f729Sjoerg                                                             QualType QT) {
707330f729Sjoerg   ObjKind K;
717330f729Sjoerg   if (isOneOf<T, CFConsumedAttr, CFReturnsRetainedAttr,
727330f729Sjoerg               CFReturnsNotRetainedAttr>()) {
737330f729Sjoerg     if (!TrackObjCAndCFObjects)
747330f729Sjoerg       return None;
757330f729Sjoerg 
767330f729Sjoerg     K = ObjKind::CF;
777330f729Sjoerg   } else if (isOneOf<T, NSConsumedAttr, NSConsumesSelfAttr,
787330f729Sjoerg                      NSReturnsAutoreleasedAttr, NSReturnsRetainedAttr,
797330f729Sjoerg                      NSReturnsNotRetainedAttr, NSConsumesSelfAttr>()) {
807330f729Sjoerg 
817330f729Sjoerg     if (!TrackObjCAndCFObjects)
827330f729Sjoerg       return None;
837330f729Sjoerg 
847330f729Sjoerg     if (isOneOf<T, NSReturnsRetainedAttr, NSReturnsAutoreleasedAttr,
857330f729Sjoerg                 NSReturnsNotRetainedAttr>() &&
867330f729Sjoerg         !cocoa::isCocoaObjectRef(QT))
877330f729Sjoerg       return None;
887330f729Sjoerg     K = ObjKind::ObjC;
897330f729Sjoerg   } else if (isOneOf<T, OSConsumedAttr, OSConsumesThisAttr,
907330f729Sjoerg                      OSReturnsNotRetainedAttr, OSReturnsRetainedAttr,
917330f729Sjoerg                      OSReturnsRetainedOnZeroAttr,
927330f729Sjoerg                      OSReturnsRetainedOnNonZeroAttr>()) {
937330f729Sjoerg     if (!TrackOSObjects)
947330f729Sjoerg       return None;
957330f729Sjoerg     K = ObjKind::OS;
967330f729Sjoerg   } else if (isOneOf<T, GeneralizedReturnsNotRetainedAttr,
977330f729Sjoerg                      GeneralizedReturnsRetainedAttr,
987330f729Sjoerg                      GeneralizedConsumedAttr>()) {
997330f729Sjoerg     K = ObjKind::Generalized;
1007330f729Sjoerg   } else {
1017330f729Sjoerg     llvm_unreachable("Unexpected attribute");
1027330f729Sjoerg   }
1037330f729Sjoerg   if (D->hasAttr<T>())
1047330f729Sjoerg     return K;
1057330f729Sjoerg   return None;
1067330f729Sjoerg }
1077330f729Sjoerg 
1087330f729Sjoerg template <class T1, class T2, class... Others>
hasAnyEnabledAttrOf(const Decl * D,QualType QT)1097330f729Sjoerg Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D,
1107330f729Sjoerg                                                             QualType QT) {
1117330f729Sjoerg   if (auto Out = hasAnyEnabledAttrOf<T1>(D, QT))
1127330f729Sjoerg     return Out;
1137330f729Sjoerg   return hasAnyEnabledAttrOf<T2, Others...>(D, QT);
1147330f729Sjoerg }
1157330f729Sjoerg 
1167330f729Sjoerg const RetainSummary *
getPersistentSummary(const RetainSummary & OldSumm)1177330f729Sjoerg RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
1187330f729Sjoerg   // Unique "simple" summaries -- those without ArgEffects.
1197330f729Sjoerg   if (OldSumm.isSimple()) {
1207330f729Sjoerg     ::llvm::FoldingSetNodeID ID;
1217330f729Sjoerg     OldSumm.Profile(ID);
1227330f729Sjoerg 
1237330f729Sjoerg     void *Pos;
1247330f729Sjoerg     CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
1257330f729Sjoerg 
1267330f729Sjoerg     if (!N) {
1277330f729Sjoerg       N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
1287330f729Sjoerg       new (N) CachedSummaryNode(OldSumm);
1297330f729Sjoerg       SimpleSummaries.InsertNode(N, Pos);
1307330f729Sjoerg     }
1317330f729Sjoerg 
1327330f729Sjoerg     return &N->getValue();
1337330f729Sjoerg   }
1347330f729Sjoerg 
1357330f729Sjoerg   RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
1367330f729Sjoerg   new (Summ) RetainSummary(OldSumm);
1377330f729Sjoerg   return Summ;
1387330f729Sjoerg }
1397330f729Sjoerg 
isSubclass(const Decl * D,StringRef ClassName)1407330f729Sjoerg static bool isSubclass(const Decl *D,
1417330f729Sjoerg                        StringRef ClassName) {
1427330f729Sjoerg   using namespace ast_matchers;
143*e038c9c4Sjoerg   DeclarationMatcher SubclassM =
144*e038c9c4Sjoerg       cxxRecordDecl(isSameOrDerivedFrom(std::string(ClassName)));
1457330f729Sjoerg   return !(match(SubclassM, *D, D->getASTContext()).empty());
1467330f729Sjoerg }
1477330f729Sjoerg 
isOSObjectSubclass(const Decl * D)1487330f729Sjoerg static bool isOSObjectSubclass(const Decl *D) {
1497330f729Sjoerg   return D && isSubclass(D, "OSMetaClassBase");
1507330f729Sjoerg }
1517330f729Sjoerg 
isOSObjectDynamicCast(StringRef S)1527330f729Sjoerg static bool isOSObjectDynamicCast(StringRef S) {
1537330f729Sjoerg   return S == "safeMetaCast";
1547330f729Sjoerg }
1557330f729Sjoerg 
isOSObjectRequiredCast(StringRef S)1567330f729Sjoerg static bool isOSObjectRequiredCast(StringRef S) {
1577330f729Sjoerg   return S == "requiredMetaCast";
1587330f729Sjoerg }
1597330f729Sjoerg 
isOSObjectThisCast(StringRef S)1607330f729Sjoerg static bool isOSObjectThisCast(StringRef S) {
1617330f729Sjoerg   return S == "metaCast";
1627330f729Sjoerg }
1637330f729Sjoerg 
1647330f729Sjoerg 
isOSObjectPtr(QualType QT)1657330f729Sjoerg static bool isOSObjectPtr(QualType QT) {
1667330f729Sjoerg   return isOSObjectSubclass(QT->getPointeeCXXRecordDecl());
1677330f729Sjoerg }
1687330f729Sjoerg 
isISLObjectRef(QualType Ty)1697330f729Sjoerg static bool isISLObjectRef(QualType Ty) {
1707330f729Sjoerg   return StringRef(Ty.getAsString()).startswith("isl_");
1717330f729Sjoerg }
1727330f729Sjoerg 
isOSIteratorSubclass(const Decl * D)1737330f729Sjoerg static bool isOSIteratorSubclass(const Decl *D) {
1747330f729Sjoerg   return isSubclass(D, "OSIterator");
1757330f729Sjoerg }
1767330f729Sjoerg 
hasRCAnnotation(const Decl * D,StringRef rcAnnotation)1777330f729Sjoerg static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) {
1787330f729Sjoerg   for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {
1797330f729Sjoerg     if (Ann->getAnnotation() == rcAnnotation)
1807330f729Sjoerg       return true;
1817330f729Sjoerg   }
1827330f729Sjoerg   return false;
1837330f729Sjoerg }
1847330f729Sjoerg 
isRetain(const FunctionDecl * FD,StringRef FName)1857330f729Sjoerg static bool isRetain(const FunctionDecl *FD, StringRef FName) {
1867330f729Sjoerg   return FName.startswith_lower("retain") || FName.endswith_lower("retain");
1877330f729Sjoerg }
1887330f729Sjoerg 
isRelease(const FunctionDecl * FD,StringRef FName)1897330f729Sjoerg static bool isRelease(const FunctionDecl *FD, StringRef FName) {
1907330f729Sjoerg   return FName.startswith_lower("release") || FName.endswith_lower("release");
1917330f729Sjoerg }
1927330f729Sjoerg 
isAutorelease(const FunctionDecl * FD,StringRef FName)1937330f729Sjoerg static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
1947330f729Sjoerg   return FName.startswith_lower("autorelease") ||
1957330f729Sjoerg          FName.endswith_lower("autorelease");
1967330f729Sjoerg }
1977330f729Sjoerg 
isMakeCollectable(StringRef FName)1987330f729Sjoerg static bool isMakeCollectable(StringRef FName) {
1997330f729Sjoerg   return FName.contains_lower("MakeCollectable");
2007330f729Sjoerg }
2017330f729Sjoerg 
2027330f729Sjoerg /// A function is OSObject related if it is declared on a subclass
2037330f729Sjoerg /// of OSObject, or any of the parameters is a subclass of an OSObject.
isOSObjectRelated(const CXXMethodDecl * MD)2047330f729Sjoerg static bool isOSObjectRelated(const CXXMethodDecl *MD) {
2057330f729Sjoerg   if (isOSObjectSubclass(MD->getParent()))
2067330f729Sjoerg     return true;
2077330f729Sjoerg 
2087330f729Sjoerg   for (ParmVarDecl *Param : MD->parameters()) {
2097330f729Sjoerg     QualType PT = Param->getType()->getPointeeType();
2107330f729Sjoerg     if (!PT.isNull())
2117330f729Sjoerg       if (CXXRecordDecl *RD = PT->getAsCXXRecordDecl())
2127330f729Sjoerg         if (isOSObjectSubclass(RD))
2137330f729Sjoerg           return true;
2147330f729Sjoerg   }
2157330f729Sjoerg 
2167330f729Sjoerg   return false;
2177330f729Sjoerg }
2187330f729Sjoerg 
2197330f729Sjoerg bool
isKnownSmartPointer(QualType QT)2207330f729Sjoerg RetainSummaryManager::isKnownSmartPointer(QualType QT) {
2217330f729Sjoerg   QT = QT.getCanonicalType();
2227330f729Sjoerg   const auto *RD = QT->getAsCXXRecordDecl();
2237330f729Sjoerg   if (!RD)
2247330f729Sjoerg     return false;
2257330f729Sjoerg   const IdentifierInfo *II = RD->getIdentifier();
2267330f729Sjoerg   if (II && II->getName() == "smart_ptr")
2277330f729Sjoerg     if (const auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext()))
2287330f729Sjoerg       if (ND->getNameAsString() == "os")
2297330f729Sjoerg         return true;
2307330f729Sjoerg   return false;
2317330f729Sjoerg }
2327330f729Sjoerg 
2337330f729Sjoerg const RetainSummary *
getSummaryForOSObject(const FunctionDecl * FD,StringRef FName,QualType RetTy)2347330f729Sjoerg RetainSummaryManager::getSummaryForOSObject(const FunctionDecl *FD,
2357330f729Sjoerg                                             StringRef FName, QualType RetTy) {
2367330f729Sjoerg   assert(TrackOSObjects &&
2377330f729Sjoerg          "Requesting a summary for an OSObject but OSObjects are not tracked");
2387330f729Sjoerg 
2397330f729Sjoerg   if (RetTy->isPointerType()) {
2407330f729Sjoerg     const CXXRecordDecl *PD = RetTy->getPointeeType()->getAsCXXRecordDecl();
2417330f729Sjoerg     if (PD && isOSObjectSubclass(PD)) {
2427330f729Sjoerg       if (isOSObjectDynamicCast(FName) || isOSObjectRequiredCast(FName) ||
2437330f729Sjoerg           isOSObjectThisCast(FName))
2447330f729Sjoerg         return getDefaultSummary();
2457330f729Sjoerg 
2467330f729Sjoerg       // TODO: Add support for the slightly common *Matching(table) idiom.
2477330f729Sjoerg       // Cf. IOService::nameMatching() etc. - these function have an unusual
2487330f729Sjoerg       // contract of returning at +0 or +1 depending on their last argument.
2497330f729Sjoerg       if (FName.endswith("Matching")) {
2507330f729Sjoerg         return getPersistentStopSummary();
2517330f729Sjoerg       }
2527330f729Sjoerg 
2537330f729Sjoerg       // All objects returned with functions *not* starting with 'get',
2547330f729Sjoerg       // or iterators, are returned at +1.
2557330f729Sjoerg       if ((!FName.startswith("get") && !FName.startswith("Get")) ||
2567330f729Sjoerg           isOSIteratorSubclass(PD)) {
2577330f729Sjoerg         return getOSSummaryCreateRule(FD);
2587330f729Sjoerg       } else {
2597330f729Sjoerg         return getOSSummaryGetRule(FD);
2607330f729Sjoerg       }
2617330f729Sjoerg     }
2627330f729Sjoerg   }
2637330f729Sjoerg 
2647330f729Sjoerg   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
2657330f729Sjoerg     const CXXRecordDecl *Parent = MD->getParent();
2667330f729Sjoerg     if (Parent && isOSObjectSubclass(Parent)) {
2677330f729Sjoerg       if (FName == "release" || FName == "taggedRelease")
2687330f729Sjoerg         return getOSSummaryReleaseRule(FD);
2697330f729Sjoerg 
2707330f729Sjoerg       if (FName == "retain" || FName == "taggedRetain")
2717330f729Sjoerg         return getOSSummaryRetainRule(FD);
2727330f729Sjoerg 
2737330f729Sjoerg       if (FName == "free")
2747330f729Sjoerg         return getOSSummaryFreeRule(FD);
2757330f729Sjoerg 
2767330f729Sjoerg       if (MD->getOverloadedOperator() == OO_New)
2777330f729Sjoerg         return getOSSummaryCreateRule(MD);
2787330f729Sjoerg     }
2797330f729Sjoerg   }
2807330f729Sjoerg 
2817330f729Sjoerg   return nullptr;
2827330f729Sjoerg }
2837330f729Sjoerg 
getSummaryForObjCOrCFObject(const FunctionDecl * FD,StringRef FName,QualType RetTy,const FunctionType * FT,bool & AllowAnnotations)2847330f729Sjoerg const RetainSummary *RetainSummaryManager::getSummaryForObjCOrCFObject(
2857330f729Sjoerg     const FunctionDecl *FD,
2867330f729Sjoerg     StringRef FName,
2877330f729Sjoerg     QualType RetTy,
2887330f729Sjoerg     const FunctionType *FT,
2897330f729Sjoerg     bool &AllowAnnotations) {
2907330f729Sjoerg 
2917330f729Sjoerg   ArgEffects ScratchArgs(AF.getEmptyMap());
2927330f729Sjoerg 
2937330f729Sjoerg   std::string RetTyName = RetTy.getAsString();
2947330f729Sjoerg   if (FName == "pthread_create" || FName == "pthread_setspecific") {
2957330f729Sjoerg     // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
2967330f729Sjoerg     // This will be addressed better with IPA.
2977330f729Sjoerg     return getPersistentStopSummary();
2987330f729Sjoerg   } else if(FName == "NSMakeCollectable") {
2997330f729Sjoerg     // Handle: id NSMakeCollectable(CFTypeRef)
3007330f729Sjoerg     AllowAnnotations = false;
3017330f729Sjoerg     return RetTy->isObjCIdType() ? getUnarySummary(FT, DoNothing)
3027330f729Sjoerg                                  : getPersistentStopSummary();
3037330f729Sjoerg   } else if (FName == "CMBufferQueueDequeueAndRetain" ||
3047330f729Sjoerg              FName == "CMBufferQueueDequeueIfDataReadyAndRetain") {
3057330f729Sjoerg     // Part of: <rdar://problem/39390714>.
3067330f729Sjoerg     return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
3077330f729Sjoerg                                 ScratchArgs,
3087330f729Sjoerg                                 ArgEffect(DoNothing),
3097330f729Sjoerg                                 ArgEffect(DoNothing));
3107330f729Sjoerg   } else if (FName == "CFPlugInInstanceCreate") {
3117330f729Sjoerg     return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs);
3127330f729Sjoerg   } else if (FName == "IORegistryEntrySearchCFProperty" ||
3137330f729Sjoerg              (RetTyName == "CFMutableDictionaryRef" &&
3147330f729Sjoerg               (FName == "IOBSDNameMatching" || FName == "IOServiceMatching" ||
3157330f729Sjoerg                FName == "IOServiceNameMatching" ||
3167330f729Sjoerg                FName == "IORegistryEntryIDMatching" ||
3177330f729Sjoerg                FName == "IOOpenFirmwarePathMatching"))) {
3187330f729Sjoerg     // Part of <rdar://problem/6961230>. (IOKit)
3197330f729Sjoerg     // This should be addressed using a API table.
3207330f729Sjoerg     return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
3217330f729Sjoerg                                 ArgEffect(DoNothing), ArgEffect(DoNothing));
3227330f729Sjoerg   } else if (FName == "IOServiceGetMatchingService" ||
3237330f729Sjoerg              FName == "IOServiceGetMatchingServices") {
3247330f729Sjoerg     // FIXES: <rdar://problem/6326900>
3257330f729Sjoerg     // This should be addressed using a API table.  This strcmp is also
3267330f729Sjoerg     // a little gross, but there is no need to super optimize here.
3277330f729Sjoerg     ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(DecRef, ObjKind::CF));
3287330f729Sjoerg     return getPersistentSummary(RetEffect::MakeNoRet(),
3297330f729Sjoerg                                 ScratchArgs,
3307330f729Sjoerg                                 ArgEffect(DoNothing), ArgEffect(DoNothing));
3317330f729Sjoerg   } else if (FName == "IOServiceAddNotification" ||
3327330f729Sjoerg              FName == "IOServiceAddMatchingNotification") {
3337330f729Sjoerg     // Part of <rdar://problem/6961230>. (IOKit)
3347330f729Sjoerg     // This should be addressed using a API table.
3357330f729Sjoerg     ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(DecRef, ObjKind::CF));
3367330f729Sjoerg     return getPersistentSummary(RetEffect::MakeNoRet(),
3377330f729Sjoerg                                 ScratchArgs,
3387330f729Sjoerg                                 ArgEffect(DoNothing), ArgEffect(DoNothing));
3397330f729Sjoerg   } else if (FName == "CVPixelBufferCreateWithBytes") {
3407330f729Sjoerg     // FIXES: <rdar://problem/7283567>
3417330f729Sjoerg     // Eventually this can be improved by recognizing that the pixel
3427330f729Sjoerg     // buffer passed to CVPixelBufferCreateWithBytes is released via
3437330f729Sjoerg     // a callback and doing full IPA to make sure this is done correctly.
3447330f729Sjoerg     // FIXME: This function has an out parameter that returns an
3457330f729Sjoerg     // allocated object.
3467330f729Sjoerg     ScratchArgs = AF.add(ScratchArgs, 7, ArgEffect(StopTracking));
3477330f729Sjoerg     return getPersistentSummary(RetEffect::MakeNoRet(),
3487330f729Sjoerg                                 ScratchArgs,
3497330f729Sjoerg                                 ArgEffect(DoNothing), ArgEffect(DoNothing));
3507330f729Sjoerg   } else if (FName == "CGBitmapContextCreateWithData") {
3517330f729Sjoerg     // FIXES: <rdar://problem/7358899>
3527330f729Sjoerg     // Eventually this can be improved by recognizing that 'releaseInfo'
3537330f729Sjoerg     // passed to CGBitmapContextCreateWithData is released via
3547330f729Sjoerg     // a callback and doing full IPA to make sure this is done correctly.
3557330f729Sjoerg     ScratchArgs = AF.add(ScratchArgs, 8, ArgEffect(ArgEffect(StopTracking)));
3567330f729Sjoerg     return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
3577330f729Sjoerg                                 ArgEffect(DoNothing), ArgEffect(DoNothing));
3587330f729Sjoerg   } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
3597330f729Sjoerg     // FIXES: <rdar://problem/7283567>
3607330f729Sjoerg     // Eventually this can be improved by recognizing that the pixel
3617330f729Sjoerg     // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
3627330f729Sjoerg     // via a callback and doing full IPA to make sure this is done
3637330f729Sjoerg     // correctly.
3647330f729Sjoerg     ScratchArgs = AF.add(ScratchArgs, 12, ArgEffect(StopTracking));
3657330f729Sjoerg     return getPersistentSummary(RetEffect::MakeNoRet(),
3667330f729Sjoerg                                 ScratchArgs,
3677330f729Sjoerg                                 ArgEffect(DoNothing), ArgEffect(DoNothing));
3687330f729Sjoerg   } else if (FName == "VTCompressionSessionEncodeFrame") {
3697330f729Sjoerg     // The context argument passed to VTCompressionSessionEncodeFrame()
3707330f729Sjoerg     // is passed to the callback specified when creating the session
3717330f729Sjoerg     // (e.g. with VTCompressionSessionCreate()) which can release it.
3727330f729Sjoerg     // To account for this possibility, conservatively stop tracking
3737330f729Sjoerg     // the context.
3747330f729Sjoerg     ScratchArgs = AF.add(ScratchArgs, 5, ArgEffect(StopTracking));
3757330f729Sjoerg     return getPersistentSummary(RetEffect::MakeNoRet(),
3767330f729Sjoerg                                 ScratchArgs,
3777330f729Sjoerg                                 ArgEffect(DoNothing), ArgEffect(DoNothing));
3787330f729Sjoerg   } else if (FName == "dispatch_set_context" ||
3797330f729Sjoerg              FName == "xpc_connection_set_context") {
3807330f729Sjoerg     // <rdar://problem/11059275> - The analyzer currently doesn't have
3817330f729Sjoerg     // a good way to reason about the finalizer function for libdispatch.
3827330f729Sjoerg     // If we pass a context object that is memory managed, stop tracking it.
3837330f729Sjoerg     // <rdar://problem/13783514> - Same problem, but for XPC.
3847330f729Sjoerg     // FIXME: this hack should possibly go away once we can handle
3857330f729Sjoerg     // libdispatch and XPC finalizers.
3867330f729Sjoerg     ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking));
3877330f729Sjoerg     return getPersistentSummary(RetEffect::MakeNoRet(),
3887330f729Sjoerg                                 ScratchArgs,
3897330f729Sjoerg                                 ArgEffect(DoNothing), ArgEffect(DoNothing));
3907330f729Sjoerg   } else if (FName.startswith("NSLog")) {
3917330f729Sjoerg     return getDoNothingSummary();
3927330f729Sjoerg   } else if (FName.startswith("NS") &&
3937330f729Sjoerg              (FName.find("Insert") != StringRef::npos)) {
3947330f729Sjoerg     // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
3957330f729Sjoerg     // be deallocated by NSMapRemove. (radar://11152419)
3967330f729Sjoerg     ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking));
3977330f729Sjoerg     ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(StopTracking));
3987330f729Sjoerg     return getPersistentSummary(RetEffect::MakeNoRet(),
3997330f729Sjoerg                                 ScratchArgs, ArgEffect(DoNothing),
4007330f729Sjoerg                                 ArgEffect(DoNothing));
4017330f729Sjoerg   }
4027330f729Sjoerg 
4037330f729Sjoerg   if (RetTy->isPointerType()) {
4047330f729Sjoerg 
4057330f729Sjoerg     // For CoreFoundation ('CF') types.
4067330f729Sjoerg     if (cocoa::isRefType(RetTy, "CF", FName)) {
4077330f729Sjoerg       if (isRetain(FD, FName)) {
4087330f729Sjoerg         // CFRetain isn't supposed to be annotated. However, this may as
4097330f729Sjoerg         // well be a user-made "safe" CFRetain function that is incorrectly
4107330f729Sjoerg         // annotated as cf_returns_retained due to lack of better options.
4117330f729Sjoerg         // We want to ignore such annotation.
4127330f729Sjoerg         AllowAnnotations = false;
4137330f729Sjoerg 
4147330f729Sjoerg         return getUnarySummary(FT, IncRef);
4157330f729Sjoerg       } else if (isAutorelease(FD, FName)) {
4167330f729Sjoerg         // The headers use cf_consumed, but we can fully model CFAutorelease
4177330f729Sjoerg         // ourselves.
4187330f729Sjoerg         AllowAnnotations = false;
4197330f729Sjoerg 
4207330f729Sjoerg         return getUnarySummary(FT, Autorelease);
4217330f729Sjoerg       } else if (isMakeCollectable(FName)) {
4227330f729Sjoerg         AllowAnnotations = false;
4237330f729Sjoerg         return getUnarySummary(FT, DoNothing);
4247330f729Sjoerg       } else {
4257330f729Sjoerg         return getCFCreateGetRuleSummary(FD);
4267330f729Sjoerg       }
4277330f729Sjoerg     }
4287330f729Sjoerg 
4297330f729Sjoerg     // For CoreGraphics ('CG') and CoreVideo ('CV') types.
4307330f729Sjoerg     if (cocoa::isRefType(RetTy, "CG", FName) ||
4317330f729Sjoerg         cocoa::isRefType(RetTy, "CV", FName)) {
4327330f729Sjoerg       if (isRetain(FD, FName))
4337330f729Sjoerg         return getUnarySummary(FT, IncRef);
4347330f729Sjoerg       else
4357330f729Sjoerg         return getCFCreateGetRuleSummary(FD);
4367330f729Sjoerg     }
4377330f729Sjoerg 
4387330f729Sjoerg     // For all other CF-style types, use the Create/Get
4397330f729Sjoerg     // rule for summaries but don't support Retain functions
4407330f729Sjoerg     // with framework-specific prefixes.
4417330f729Sjoerg     if (coreFoundation::isCFObjectRef(RetTy)) {
4427330f729Sjoerg       return getCFCreateGetRuleSummary(FD);
4437330f729Sjoerg     }
4447330f729Sjoerg 
4457330f729Sjoerg     if (FD->hasAttr<CFAuditedTransferAttr>()) {
4467330f729Sjoerg       return getCFCreateGetRuleSummary(FD);
4477330f729Sjoerg     }
4487330f729Sjoerg   }
4497330f729Sjoerg 
4507330f729Sjoerg   // Check for release functions, the only kind of functions that we care
4517330f729Sjoerg   // about that don't return a pointer type.
4527330f729Sjoerg   if (FName.startswith("CG") || FName.startswith("CF")) {
4537330f729Sjoerg     // Test for 'CGCF'.
4547330f729Sjoerg     FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
4557330f729Sjoerg 
4567330f729Sjoerg     if (isRelease(FD, FName))
4577330f729Sjoerg       return getUnarySummary(FT, DecRef);
4587330f729Sjoerg     else {
4597330f729Sjoerg       assert(ScratchArgs.isEmpty());
4607330f729Sjoerg       // Remaining CoreFoundation and CoreGraphics functions.
4617330f729Sjoerg       // We use to assume that they all strictly followed the ownership idiom
4627330f729Sjoerg       // and that ownership cannot be transferred.  While this is technically
4637330f729Sjoerg       // correct, many methods allow a tracked object to escape.  For example:
4647330f729Sjoerg       //
4657330f729Sjoerg       //   CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
4667330f729Sjoerg       //   CFDictionaryAddValue(y, key, x);
4677330f729Sjoerg       //   CFRelease(x);
4687330f729Sjoerg       //   ... it is okay to use 'x' since 'y' has a reference to it
4697330f729Sjoerg       //
4707330f729Sjoerg       // We handle this and similar cases with the follow heuristic.  If the
4717330f729Sjoerg       // function name contains "InsertValue", "SetValue", "AddValue",
4727330f729Sjoerg       // "AppendValue", or "SetAttribute", then we assume that arguments may
4737330f729Sjoerg       // "escape."  This means that something else holds on to the object,
4747330f729Sjoerg       // allowing it be used even after its local retain count drops to 0.
4757330f729Sjoerg       ArgEffectKind E =
4767330f729Sjoerg           (StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
4777330f729Sjoerg            StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
4787330f729Sjoerg            StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
4797330f729Sjoerg            StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
4807330f729Sjoerg            StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
4817330f729Sjoerg               ? MayEscape
4827330f729Sjoerg               : DoNothing;
4837330f729Sjoerg 
4847330f729Sjoerg       return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
4857330f729Sjoerg                                   ArgEffect(DoNothing), ArgEffect(E, ObjKind::CF));
4867330f729Sjoerg     }
4877330f729Sjoerg   }
4887330f729Sjoerg 
4897330f729Sjoerg   return nullptr;
4907330f729Sjoerg }
4917330f729Sjoerg 
4927330f729Sjoerg const RetainSummary *
generateSummary(const FunctionDecl * FD,bool & AllowAnnotations)4937330f729Sjoerg RetainSummaryManager::generateSummary(const FunctionDecl *FD,
4947330f729Sjoerg                                       bool &AllowAnnotations) {
4957330f729Sjoerg   // We generate "stop" summaries for implicitly defined functions.
4967330f729Sjoerg   if (FD->isImplicit())
4977330f729Sjoerg     return getPersistentStopSummary();
4987330f729Sjoerg 
4997330f729Sjoerg   const IdentifierInfo *II = FD->getIdentifier();
5007330f729Sjoerg 
5017330f729Sjoerg   StringRef FName = II ? II->getName() : "";
5027330f729Sjoerg 
5037330f729Sjoerg   // Strip away preceding '_'.  Doing this here will effect all the checks
5047330f729Sjoerg   // down below.
5057330f729Sjoerg   FName = FName.substr(FName.find_first_not_of('_'));
5067330f729Sjoerg 
5077330f729Sjoerg   // Inspect the result type. Strip away any typedefs.
5087330f729Sjoerg   const auto *FT = FD->getType()->castAs<FunctionType>();
5097330f729Sjoerg   QualType RetTy = FT->getReturnType();
5107330f729Sjoerg 
5117330f729Sjoerg   if (TrackOSObjects)
5127330f729Sjoerg     if (const RetainSummary *S = getSummaryForOSObject(FD, FName, RetTy))
5137330f729Sjoerg       return S;
5147330f729Sjoerg 
5157330f729Sjoerg   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
5167330f729Sjoerg     if (!isOSObjectRelated(MD))
5177330f729Sjoerg       return getPersistentSummary(RetEffect::MakeNoRet(),
5187330f729Sjoerg                                   ArgEffects(AF.getEmptyMap()),
5197330f729Sjoerg                                   ArgEffect(DoNothing),
5207330f729Sjoerg                                   ArgEffect(StopTracking),
5217330f729Sjoerg                                   ArgEffect(DoNothing));
5227330f729Sjoerg 
5237330f729Sjoerg   if (TrackObjCAndCFObjects)
5247330f729Sjoerg     if (const RetainSummary *S =
5257330f729Sjoerg             getSummaryForObjCOrCFObject(FD, FName, RetTy, FT, AllowAnnotations))
5267330f729Sjoerg       return S;
5277330f729Sjoerg 
5287330f729Sjoerg   return getDefaultSummary();
5297330f729Sjoerg }
5307330f729Sjoerg 
5317330f729Sjoerg const RetainSummary *
getFunctionSummary(const FunctionDecl * FD)5327330f729Sjoerg RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
5337330f729Sjoerg   // If we don't know what function we're calling, use our default summary.
5347330f729Sjoerg   if (!FD)
5357330f729Sjoerg     return getDefaultSummary();
5367330f729Sjoerg 
5377330f729Sjoerg   // Look up a summary in our cache of FunctionDecls -> Summaries.
5387330f729Sjoerg   FuncSummariesTy::iterator I = FuncSummaries.find(FD);
5397330f729Sjoerg   if (I != FuncSummaries.end())
5407330f729Sjoerg     return I->second;
5417330f729Sjoerg 
5427330f729Sjoerg   // No summary?  Generate one.
5437330f729Sjoerg   bool AllowAnnotations = true;
5447330f729Sjoerg   const RetainSummary *S = generateSummary(FD, AllowAnnotations);
5457330f729Sjoerg 
5467330f729Sjoerg   // Annotations override defaults.
5477330f729Sjoerg   if (AllowAnnotations)
5487330f729Sjoerg     updateSummaryFromAnnotations(S, FD);
5497330f729Sjoerg 
5507330f729Sjoerg   FuncSummaries[FD] = S;
5517330f729Sjoerg   return S;
5527330f729Sjoerg }
5537330f729Sjoerg 
5547330f729Sjoerg //===----------------------------------------------------------------------===//
5557330f729Sjoerg // Summary creation for functions (largely uses of Core Foundation).
5567330f729Sjoerg //===----------------------------------------------------------------------===//
5577330f729Sjoerg 
getStopTrackingHardEquivalent(ArgEffect E)5587330f729Sjoerg static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
5597330f729Sjoerg   switch (E.getKind()) {
5607330f729Sjoerg   case DoNothing:
5617330f729Sjoerg   case Autorelease:
5627330f729Sjoerg   case DecRefBridgedTransferred:
5637330f729Sjoerg   case IncRef:
5647330f729Sjoerg   case UnretainedOutParameter:
5657330f729Sjoerg   case RetainedOutParameter:
5667330f729Sjoerg   case RetainedOutParameterOnZero:
5677330f729Sjoerg   case RetainedOutParameterOnNonZero:
5687330f729Sjoerg   case MayEscape:
5697330f729Sjoerg   case StopTracking:
5707330f729Sjoerg   case StopTrackingHard:
5717330f729Sjoerg     return E.withKind(StopTrackingHard);
5727330f729Sjoerg   case DecRef:
5737330f729Sjoerg   case DecRefAndStopTrackingHard:
5747330f729Sjoerg     return E.withKind(DecRefAndStopTrackingHard);
5757330f729Sjoerg   case Dealloc:
5767330f729Sjoerg     return E.withKind(Dealloc);
5777330f729Sjoerg   }
5787330f729Sjoerg 
5797330f729Sjoerg   llvm_unreachable("Unknown ArgEffect kind");
5807330f729Sjoerg }
5817330f729Sjoerg 
5827330f729Sjoerg const RetainSummary *
updateSummaryForNonZeroCallbackArg(const RetainSummary * S,AnyCall & C)5837330f729Sjoerg RetainSummaryManager::updateSummaryForNonZeroCallbackArg(const RetainSummary *S,
5847330f729Sjoerg                                                          AnyCall &C) {
5857330f729Sjoerg   ArgEffect RecEffect = getStopTrackingHardEquivalent(S->getReceiverEffect());
5867330f729Sjoerg   ArgEffect DefEffect = getStopTrackingHardEquivalent(S->getDefaultArgEffect());
5877330f729Sjoerg 
5887330f729Sjoerg   ArgEffects ScratchArgs(AF.getEmptyMap());
5897330f729Sjoerg   ArgEffects CustomArgEffects = S->getArgEffects();
5907330f729Sjoerg   for (ArgEffects::iterator I = CustomArgEffects.begin(),
5917330f729Sjoerg                             E = CustomArgEffects.end();
5927330f729Sjoerg        I != E; ++I) {
5937330f729Sjoerg     ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
5947330f729Sjoerg     if (Translated.getKind() != DefEffect.getKind())
5957330f729Sjoerg       ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
5967330f729Sjoerg   }
5977330f729Sjoerg 
5987330f729Sjoerg   RetEffect RE = RetEffect::MakeNoRetHard();
5997330f729Sjoerg 
6007330f729Sjoerg   // Special cases where the callback argument CANNOT free the return value.
6017330f729Sjoerg   // This can generally only happen if we know that the callback will only be
6027330f729Sjoerg   // called when the return value is already being deallocated.
6037330f729Sjoerg   if (const IdentifierInfo *Name = C.getIdentifier()) {
6047330f729Sjoerg     // When the CGBitmapContext is deallocated, the callback here will free
6057330f729Sjoerg     // the associated data buffer.
6067330f729Sjoerg     // The callback in dispatch_data_create frees the buffer, but not
6077330f729Sjoerg     // the data object.
6087330f729Sjoerg     if (Name->isStr("CGBitmapContextCreateWithData") ||
6097330f729Sjoerg         Name->isStr("dispatch_data_create"))
6107330f729Sjoerg       RE = S->getRetEffect();
6117330f729Sjoerg   }
6127330f729Sjoerg 
6137330f729Sjoerg   return getPersistentSummary(RE, ScratchArgs, RecEffect, DefEffect);
6147330f729Sjoerg }
6157330f729Sjoerg 
updateSummaryForReceiverUnconsumedSelf(const RetainSummary * & S)6167330f729Sjoerg void RetainSummaryManager::updateSummaryForReceiverUnconsumedSelf(
6177330f729Sjoerg     const RetainSummary *&S) {
6187330f729Sjoerg 
6197330f729Sjoerg   RetainSummaryTemplate Template(S, *this);
6207330f729Sjoerg 
6217330f729Sjoerg   Template->setReceiverEffect(ArgEffect(DoNothing));
6227330f729Sjoerg   Template->setRetEffect(RetEffect::MakeNoRet());
6237330f729Sjoerg }
6247330f729Sjoerg 
6257330f729Sjoerg 
updateSummaryForArgumentTypes(const AnyCall & C,const RetainSummary * & RS)6267330f729Sjoerg void RetainSummaryManager::updateSummaryForArgumentTypes(
6277330f729Sjoerg   const AnyCall &C, const RetainSummary *&RS) {
6287330f729Sjoerg   RetainSummaryTemplate Template(RS, *this);
6297330f729Sjoerg 
6307330f729Sjoerg   unsigned parm_idx = 0;
6317330f729Sjoerg   for (auto pi = C.param_begin(), pe = C.param_end(); pi != pe;
6327330f729Sjoerg        ++pi, ++parm_idx) {
6337330f729Sjoerg     QualType QT = (*pi)->getType();
6347330f729Sjoerg 
6357330f729Sjoerg     // Skip already created values.
6367330f729Sjoerg     if (RS->getArgEffects().contains(parm_idx))
6377330f729Sjoerg       continue;
6387330f729Sjoerg 
6397330f729Sjoerg     ObjKind K = ObjKind::AnyObj;
6407330f729Sjoerg 
6417330f729Sjoerg     if (isISLObjectRef(QT)) {
6427330f729Sjoerg       K = ObjKind::Generalized;
6437330f729Sjoerg     } else if (isOSObjectPtr(QT)) {
6447330f729Sjoerg       K = ObjKind::OS;
6457330f729Sjoerg     } else if (cocoa::isCocoaObjectRef(QT)) {
6467330f729Sjoerg       K = ObjKind::ObjC;
6477330f729Sjoerg     } else if (coreFoundation::isCFObjectRef(QT)) {
6487330f729Sjoerg       K = ObjKind::CF;
6497330f729Sjoerg     }
6507330f729Sjoerg 
6517330f729Sjoerg     if (K != ObjKind::AnyObj)
6527330f729Sjoerg       Template->addArg(AF, parm_idx,
6537330f729Sjoerg                        ArgEffect(RS->getDefaultArgEffect().getKind(), K));
6547330f729Sjoerg   }
6557330f729Sjoerg }
6567330f729Sjoerg 
6577330f729Sjoerg const RetainSummary *
getSummary(AnyCall C,bool HasNonZeroCallbackArg,bool IsReceiverUnconsumedSelf,QualType ReceiverType)6587330f729Sjoerg RetainSummaryManager::getSummary(AnyCall C,
6597330f729Sjoerg                                  bool HasNonZeroCallbackArg,
6607330f729Sjoerg                                  bool IsReceiverUnconsumedSelf,
6617330f729Sjoerg                                  QualType ReceiverType) {
6627330f729Sjoerg   const RetainSummary *Summ;
6637330f729Sjoerg   switch (C.getKind()) {
6647330f729Sjoerg   case AnyCall::Function:
6657330f729Sjoerg   case AnyCall::Constructor:
666*e038c9c4Sjoerg   case AnyCall::InheritedConstructor:
6677330f729Sjoerg   case AnyCall::Allocator:
6687330f729Sjoerg   case AnyCall::Deallocator:
6697330f729Sjoerg     Summ = getFunctionSummary(cast_or_null<FunctionDecl>(C.getDecl()));
6707330f729Sjoerg     break;
6717330f729Sjoerg   case AnyCall::Block:
6727330f729Sjoerg   case AnyCall::Destructor:
6737330f729Sjoerg     // FIXME: These calls are currently unsupported.
6747330f729Sjoerg     return getPersistentStopSummary();
6757330f729Sjoerg   case AnyCall::ObjCMethod: {
6767330f729Sjoerg     const auto *ME = cast_or_null<ObjCMessageExpr>(C.getExpr());
6777330f729Sjoerg     if (!ME) {
6787330f729Sjoerg       Summ = getMethodSummary(cast<ObjCMethodDecl>(C.getDecl()));
6797330f729Sjoerg     } else if (ME->isInstanceMessage()) {
6807330f729Sjoerg       Summ = getInstanceMethodSummary(ME, ReceiverType);
6817330f729Sjoerg     } else {
6827330f729Sjoerg       Summ = getClassMethodSummary(ME);
6837330f729Sjoerg     }
6847330f729Sjoerg     break;
6857330f729Sjoerg   }
6867330f729Sjoerg   }
6877330f729Sjoerg 
6887330f729Sjoerg   if (HasNonZeroCallbackArg)
6897330f729Sjoerg     Summ = updateSummaryForNonZeroCallbackArg(Summ, C);
6907330f729Sjoerg 
6917330f729Sjoerg   if (IsReceiverUnconsumedSelf)
6927330f729Sjoerg     updateSummaryForReceiverUnconsumedSelf(Summ);
6937330f729Sjoerg 
6947330f729Sjoerg   updateSummaryForArgumentTypes(C, Summ);
6957330f729Sjoerg 
6967330f729Sjoerg   assert(Summ && "Unknown call type?");
6977330f729Sjoerg   return Summ;
6987330f729Sjoerg }
6997330f729Sjoerg 
7007330f729Sjoerg 
7017330f729Sjoerg const RetainSummary *
getCFCreateGetRuleSummary(const FunctionDecl * FD)7027330f729Sjoerg RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
7037330f729Sjoerg   if (coreFoundation::followsCreateRule(FD))
7047330f729Sjoerg     return getCFSummaryCreateRule(FD);
7057330f729Sjoerg 
7067330f729Sjoerg   return getCFSummaryGetRule(FD);
7077330f729Sjoerg }
7087330f729Sjoerg 
isTrustedReferenceCountImplementation(const Decl * FD)7097330f729Sjoerg bool RetainSummaryManager::isTrustedReferenceCountImplementation(
7107330f729Sjoerg     const Decl *FD) {
7117330f729Sjoerg   return hasRCAnnotation(FD, "rc_ownership_trusted_implementation");
7127330f729Sjoerg }
7137330f729Sjoerg 
7147330f729Sjoerg Optional<RetainSummaryManager::BehaviorSummary>
canEval(const CallExpr * CE,const FunctionDecl * FD,bool & hasTrustedImplementationAnnotation)7157330f729Sjoerg RetainSummaryManager::canEval(const CallExpr *CE, const FunctionDecl *FD,
7167330f729Sjoerg                               bool &hasTrustedImplementationAnnotation) {
7177330f729Sjoerg 
7187330f729Sjoerg   IdentifierInfo *II = FD->getIdentifier();
7197330f729Sjoerg   if (!II)
7207330f729Sjoerg     return None;
7217330f729Sjoerg 
7227330f729Sjoerg   StringRef FName = II->getName();
7237330f729Sjoerg   FName = FName.substr(FName.find_first_not_of('_'));
7247330f729Sjoerg 
7257330f729Sjoerg   QualType ResultTy = CE->getCallReturnType(Ctx);
7267330f729Sjoerg   if (ResultTy->isObjCIdType()) {
7277330f729Sjoerg     if (II->isStr("NSMakeCollectable"))
7287330f729Sjoerg       return BehaviorSummary::Identity;
7297330f729Sjoerg   } else if (ResultTy->isPointerType()) {
7307330f729Sjoerg     // Handle: (CF|CG|CV)Retain
7317330f729Sjoerg     //         CFAutorelease
7327330f729Sjoerg     // It's okay to be a little sloppy here.
7337330f729Sjoerg     if (FName == "CMBufferQueueDequeueAndRetain" ||
7347330f729Sjoerg         FName == "CMBufferQueueDequeueIfDataReadyAndRetain") {
7357330f729Sjoerg       // Part of: <rdar://problem/39390714>.
7367330f729Sjoerg       // These are not retain. They just return something and retain it.
7377330f729Sjoerg       return None;
7387330f729Sjoerg     }
7397330f729Sjoerg     if (CE->getNumArgs() == 1 &&
7407330f729Sjoerg         (cocoa::isRefType(ResultTy, "CF", FName) ||
7417330f729Sjoerg          cocoa::isRefType(ResultTy, "CG", FName) ||
7427330f729Sjoerg          cocoa::isRefType(ResultTy, "CV", FName)) &&
7437330f729Sjoerg         (isRetain(FD, FName) || isAutorelease(FD, FName) ||
7447330f729Sjoerg          isMakeCollectable(FName)))
7457330f729Sjoerg       return BehaviorSummary::Identity;
7467330f729Sjoerg 
7477330f729Sjoerg     // safeMetaCast is called by OSDynamicCast.
7487330f729Sjoerg     // We assume that OSDynamicCast is either an identity (cast is OK,
7497330f729Sjoerg     // the input was non-zero),
7507330f729Sjoerg     // or that it returns zero (when the cast failed, or the input
7517330f729Sjoerg     // was zero).
7527330f729Sjoerg     if (TrackOSObjects) {
7537330f729Sjoerg       if (isOSObjectDynamicCast(FName) && FD->param_size() >= 1) {
7547330f729Sjoerg         return BehaviorSummary::IdentityOrZero;
7557330f729Sjoerg       } else if (isOSObjectRequiredCast(FName) && FD->param_size() >= 1) {
7567330f729Sjoerg         return BehaviorSummary::Identity;
7577330f729Sjoerg       } else if (isOSObjectThisCast(FName) && isa<CXXMethodDecl>(FD) &&
7587330f729Sjoerg                  !cast<CXXMethodDecl>(FD)->isStatic()) {
7597330f729Sjoerg         return BehaviorSummary::IdentityThis;
7607330f729Sjoerg       }
7617330f729Sjoerg     }
7627330f729Sjoerg 
7637330f729Sjoerg     const FunctionDecl* FDD = FD->getDefinition();
7647330f729Sjoerg     if (FDD && isTrustedReferenceCountImplementation(FDD)) {
7657330f729Sjoerg       hasTrustedImplementationAnnotation = true;
7667330f729Sjoerg       return BehaviorSummary::Identity;
7677330f729Sjoerg     }
7687330f729Sjoerg   }
7697330f729Sjoerg 
7707330f729Sjoerg   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7717330f729Sjoerg     const CXXRecordDecl *Parent = MD->getParent();
7727330f729Sjoerg     if (TrackOSObjects && Parent && isOSObjectSubclass(Parent))
7737330f729Sjoerg       if (FName == "release" || FName == "retain")
7747330f729Sjoerg         return BehaviorSummary::NoOp;
7757330f729Sjoerg   }
7767330f729Sjoerg 
7777330f729Sjoerg   return None;
7787330f729Sjoerg }
7797330f729Sjoerg 
7807330f729Sjoerg const RetainSummary *
getUnarySummary(const FunctionType * FT,ArgEffectKind AE)7817330f729Sjoerg RetainSummaryManager::getUnarySummary(const FunctionType* FT,
7827330f729Sjoerg                                       ArgEffectKind AE) {
7837330f729Sjoerg 
7847330f729Sjoerg   // Unary functions have no arg effects by definition.
7857330f729Sjoerg   ArgEffects ScratchArgs(AF.getEmptyMap());
7867330f729Sjoerg 
7877330f729Sjoerg   // Sanity check that this is *really* a unary function.  This can
7887330f729Sjoerg   // happen if people do weird things.
7897330f729Sjoerg   const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
7907330f729Sjoerg   if (!FTP || FTP->getNumParams() != 1)
7917330f729Sjoerg     return getPersistentStopSummary();
7927330f729Sjoerg 
7937330f729Sjoerg   ArgEffect Effect(AE, ObjKind::CF);
7947330f729Sjoerg 
7957330f729Sjoerg   ScratchArgs = AF.add(ScratchArgs, 0, Effect);
7967330f729Sjoerg   return getPersistentSummary(RetEffect::MakeNoRet(),
7977330f729Sjoerg                               ScratchArgs,
7987330f729Sjoerg                               ArgEffect(DoNothing), ArgEffect(DoNothing));
7997330f729Sjoerg }
8007330f729Sjoerg 
8017330f729Sjoerg const RetainSummary *
getOSSummaryRetainRule(const FunctionDecl * FD)8027330f729Sjoerg RetainSummaryManager::getOSSummaryRetainRule(const FunctionDecl *FD) {
8037330f729Sjoerg   return getPersistentSummary(RetEffect::MakeNoRet(),
8047330f729Sjoerg                               AF.getEmptyMap(),
8057330f729Sjoerg                               /*ReceiverEff=*/ArgEffect(DoNothing),
8067330f729Sjoerg                               /*DefaultEff=*/ArgEffect(DoNothing),
8077330f729Sjoerg                               /*ThisEff=*/ArgEffect(IncRef, ObjKind::OS));
8087330f729Sjoerg }
8097330f729Sjoerg 
8107330f729Sjoerg const RetainSummary *
getOSSummaryReleaseRule(const FunctionDecl * FD)8117330f729Sjoerg RetainSummaryManager::getOSSummaryReleaseRule(const FunctionDecl *FD) {
8127330f729Sjoerg   return getPersistentSummary(RetEffect::MakeNoRet(),
8137330f729Sjoerg                               AF.getEmptyMap(),
8147330f729Sjoerg                               /*ReceiverEff=*/ArgEffect(DoNothing),
8157330f729Sjoerg                               /*DefaultEff=*/ArgEffect(DoNothing),
8167330f729Sjoerg                               /*ThisEff=*/ArgEffect(DecRef, ObjKind::OS));
8177330f729Sjoerg }
8187330f729Sjoerg 
8197330f729Sjoerg const RetainSummary *
getOSSummaryFreeRule(const FunctionDecl * FD)8207330f729Sjoerg RetainSummaryManager::getOSSummaryFreeRule(const FunctionDecl *FD) {
8217330f729Sjoerg   return getPersistentSummary(RetEffect::MakeNoRet(),
8227330f729Sjoerg                               AF.getEmptyMap(),
8237330f729Sjoerg                               /*ReceiverEff=*/ArgEffect(DoNothing),
8247330f729Sjoerg                               /*DefaultEff=*/ArgEffect(DoNothing),
8257330f729Sjoerg                               /*ThisEff=*/ArgEffect(Dealloc, ObjKind::OS));
8267330f729Sjoerg }
8277330f729Sjoerg 
8287330f729Sjoerg const RetainSummary *
getOSSummaryCreateRule(const FunctionDecl * FD)8297330f729Sjoerg RetainSummaryManager::getOSSummaryCreateRule(const FunctionDecl *FD) {
8307330f729Sjoerg   return getPersistentSummary(RetEffect::MakeOwned(ObjKind::OS),
8317330f729Sjoerg                               AF.getEmptyMap());
8327330f729Sjoerg }
8337330f729Sjoerg 
8347330f729Sjoerg const RetainSummary *
getOSSummaryGetRule(const FunctionDecl * FD)8357330f729Sjoerg RetainSummaryManager::getOSSummaryGetRule(const FunctionDecl *FD) {
8367330f729Sjoerg   return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::OS),
8377330f729Sjoerg                               AF.getEmptyMap());
8387330f729Sjoerg }
8397330f729Sjoerg 
8407330f729Sjoerg const RetainSummary *
getCFSummaryCreateRule(const FunctionDecl * FD)8417330f729Sjoerg RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
8427330f729Sjoerg   return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
8437330f729Sjoerg                               ArgEffects(AF.getEmptyMap()));
8447330f729Sjoerg }
8457330f729Sjoerg 
8467330f729Sjoerg const RetainSummary *
getCFSummaryGetRule(const FunctionDecl * FD)8477330f729Sjoerg RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
8487330f729Sjoerg   return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::CF),
8497330f729Sjoerg                               ArgEffects(AF.getEmptyMap()),
8507330f729Sjoerg                               ArgEffect(DoNothing), ArgEffect(DoNothing));
8517330f729Sjoerg }
8527330f729Sjoerg 
8537330f729Sjoerg 
8547330f729Sjoerg 
8557330f729Sjoerg 
8567330f729Sjoerg //===----------------------------------------------------------------------===//
8577330f729Sjoerg // Summary creation for Selectors.
8587330f729Sjoerg //===----------------------------------------------------------------------===//
8597330f729Sjoerg 
8607330f729Sjoerg Optional<RetEffect>
getRetEffectFromAnnotations(QualType RetTy,const Decl * D)8617330f729Sjoerg RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
8627330f729Sjoerg                                                   const Decl *D) {
8637330f729Sjoerg   if (hasAnyEnabledAttrOf<NSReturnsRetainedAttr>(D, RetTy))
8647330f729Sjoerg     return ObjCAllocRetE;
8657330f729Sjoerg 
8667330f729Sjoerg   if (auto K = hasAnyEnabledAttrOf<CFReturnsRetainedAttr, OSReturnsRetainedAttr,
8677330f729Sjoerg                                    GeneralizedReturnsRetainedAttr>(D, RetTy))
8687330f729Sjoerg     return RetEffect::MakeOwned(*K);
8697330f729Sjoerg 
8707330f729Sjoerg   if (auto K = hasAnyEnabledAttrOf<
8717330f729Sjoerg           CFReturnsNotRetainedAttr, OSReturnsNotRetainedAttr,
8727330f729Sjoerg           GeneralizedReturnsNotRetainedAttr, NSReturnsNotRetainedAttr,
8737330f729Sjoerg           NSReturnsAutoreleasedAttr>(D, RetTy))
8747330f729Sjoerg     return RetEffect::MakeNotOwned(*K);
8757330f729Sjoerg 
8767330f729Sjoerg   if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
8777330f729Sjoerg     for (const auto *PD : MD->overridden_methods())
8787330f729Sjoerg       if (auto RE = getRetEffectFromAnnotations(RetTy, PD))
8797330f729Sjoerg         return RE;
8807330f729Sjoerg 
8817330f729Sjoerg   return None;
8827330f729Sjoerg }
8837330f729Sjoerg 
884*e038c9c4Sjoerg /// \return Whether the chain of typedefs starting from @c QT
885*e038c9c4Sjoerg /// has a typedef with a given name @c Name.
hasTypedefNamed(QualType QT,StringRef Name)8867330f729Sjoerg static bool hasTypedefNamed(QualType QT,
8877330f729Sjoerg                             StringRef Name) {
8887330f729Sjoerg   while (auto *T = dyn_cast<TypedefType>(QT)) {
8897330f729Sjoerg     const auto &Context = T->getDecl()->getASTContext();
8907330f729Sjoerg     if (T->getDecl()->getIdentifier() == &Context.Idents.get(Name))
8917330f729Sjoerg       return true;
8927330f729Sjoerg     QT = T->getDecl()->getUnderlyingType();
8937330f729Sjoerg   }
8947330f729Sjoerg   return false;
8957330f729Sjoerg }
8967330f729Sjoerg 
getCallableReturnType(const NamedDecl * ND)8977330f729Sjoerg static QualType getCallableReturnType(const NamedDecl *ND) {
8987330f729Sjoerg   if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8997330f729Sjoerg     return FD->getReturnType();
9007330f729Sjoerg   } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(ND)) {
9017330f729Sjoerg     return MD->getReturnType();
9027330f729Sjoerg   } else {
9037330f729Sjoerg     llvm_unreachable("Unexpected decl");
9047330f729Sjoerg   }
9057330f729Sjoerg }
9067330f729Sjoerg 
applyParamAnnotationEffect(const ParmVarDecl * pd,unsigned parm_idx,const NamedDecl * FD,RetainSummaryTemplate & Template)9077330f729Sjoerg bool RetainSummaryManager::applyParamAnnotationEffect(
9087330f729Sjoerg     const ParmVarDecl *pd, unsigned parm_idx, const NamedDecl *FD,
9097330f729Sjoerg     RetainSummaryTemplate &Template) {
9107330f729Sjoerg   QualType QT = pd->getType();
9117330f729Sjoerg   if (auto K =
9127330f729Sjoerg           hasAnyEnabledAttrOf<NSConsumedAttr, CFConsumedAttr, OSConsumedAttr,
9137330f729Sjoerg                               GeneralizedConsumedAttr>(pd, QT)) {
9147330f729Sjoerg     Template->addArg(AF, parm_idx, ArgEffect(DecRef, *K));
9157330f729Sjoerg     return true;
9167330f729Sjoerg   } else if (auto K = hasAnyEnabledAttrOf<
9177330f729Sjoerg                  CFReturnsRetainedAttr, OSReturnsRetainedAttr,
9187330f729Sjoerg                  OSReturnsRetainedOnNonZeroAttr, OSReturnsRetainedOnZeroAttr,
9197330f729Sjoerg                  GeneralizedReturnsRetainedAttr>(pd, QT)) {
9207330f729Sjoerg 
9217330f729Sjoerg     // For OSObjects, we try to guess whether the object is created based
9227330f729Sjoerg     // on the return value.
9237330f729Sjoerg     if (K == ObjKind::OS) {
9247330f729Sjoerg       QualType QT = getCallableReturnType(FD);
9257330f729Sjoerg 
9267330f729Sjoerg       bool HasRetainedOnZero = pd->hasAttr<OSReturnsRetainedOnZeroAttr>();
9277330f729Sjoerg       bool HasRetainedOnNonZero = pd->hasAttr<OSReturnsRetainedOnNonZeroAttr>();
9287330f729Sjoerg 
9297330f729Sjoerg       // The usual convention is to create an object on non-zero return, but
9307330f729Sjoerg       // it's reverted if the typedef chain has a typedef kern_return_t,
9317330f729Sjoerg       // because kReturnSuccess constant is defined as zero.
9327330f729Sjoerg       // The convention can be overwritten by custom attributes.
9337330f729Sjoerg       bool SuccessOnZero =
9347330f729Sjoerg           HasRetainedOnZero ||
9357330f729Sjoerg           (hasTypedefNamed(QT, "kern_return_t") && !HasRetainedOnNonZero);
9367330f729Sjoerg       bool ShouldSplit = !QT.isNull() && !QT->isVoidType();
9377330f729Sjoerg       ArgEffectKind AK = RetainedOutParameter;
9387330f729Sjoerg       if (ShouldSplit && SuccessOnZero) {
9397330f729Sjoerg         AK = RetainedOutParameterOnZero;
9407330f729Sjoerg       } else if (ShouldSplit && (!SuccessOnZero || HasRetainedOnNonZero)) {
9417330f729Sjoerg         AK = RetainedOutParameterOnNonZero;
9427330f729Sjoerg       }
9437330f729Sjoerg       Template->addArg(AF, parm_idx, ArgEffect(AK, ObjKind::OS));
9447330f729Sjoerg     }
9457330f729Sjoerg 
9467330f729Sjoerg     // For others:
9477330f729Sjoerg     // Do nothing. Retained out parameters will either point to a +1 reference
9487330f729Sjoerg     // or NULL, but the way you check for failure differs depending on the
9497330f729Sjoerg     // API. Consequently, we don't have a good way to track them yet.
9507330f729Sjoerg     return true;
9517330f729Sjoerg   } else if (auto K = hasAnyEnabledAttrOf<CFReturnsNotRetainedAttr,
9527330f729Sjoerg                                           OSReturnsNotRetainedAttr,
9537330f729Sjoerg                                           GeneralizedReturnsNotRetainedAttr>(
9547330f729Sjoerg                  pd, QT)) {
9557330f729Sjoerg     Template->addArg(AF, parm_idx, ArgEffect(UnretainedOutParameter, *K));
9567330f729Sjoerg     return true;
9577330f729Sjoerg   }
9587330f729Sjoerg 
9597330f729Sjoerg   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
9607330f729Sjoerg     for (const auto *OD : MD->overridden_methods()) {
9617330f729Sjoerg       const ParmVarDecl *OP = OD->parameters()[parm_idx];
9627330f729Sjoerg       if (applyParamAnnotationEffect(OP, parm_idx, OD, Template))
9637330f729Sjoerg         return true;
9647330f729Sjoerg     }
9657330f729Sjoerg   }
9667330f729Sjoerg 
9677330f729Sjoerg   return false;
9687330f729Sjoerg }
9697330f729Sjoerg 
9707330f729Sjoerg void
updateSummaryFromAnnotations(const RetainSummary * & Summ,const FunctionDecl * FD)9717330f729Sjoerg RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
9727330f729Sjoerg                                                    const FunctionDecl *FD) {
9737330f729Sjoerg   if (!FD)
9747330f729Sjoerg     return;
9757330f729Sjoerg 
9767330f729Sjoerg   assert(Summ && "Must have a summary to add annotations to.");
9777330f729Sjoerg   RetainSummaryTemplate Template(Summ, *this);
9787330f729Sjoerg 
9797330f729Sjoerg   // Effects on the parameters.
9807330f729Sjoerg   unsigned parm_idx = 0;
9817330f729Sjoerg   for (auto pi = FD->param_begin(),
9827330f729Sjoerg          pe = FD->param_end(); pi != pe; ++pi, ++parm_idx)
9837330f729Sjoerg     applyParamAnnotationEffect(*pi, parm_idx, FD, Template);
9847330f729Sjoerg 
9857330f729Sjoerg   QualType RetTy = FD->getReturnType();
9867330f729Sjoerg   if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
9877330f729Sjoerg     Template->setRetEffect(*RetE);
9887330f729Sjoerg 
9897330f729Sjoerg   if (hasAnyEnabledAttrOf<OSConsumesThisAttr>(FD, RetTy))
9907330f729Sjoerg     Template->setThisEffect(ArgEffect(DecRef, ObjKind::OS));
9917330f729Sjoerg }
9927330f729Sjoerg 
9937330f729Sjoerg void
updateSummaryFromAnnotations(const RetainSummary * & Summ,const ObjCMethodDecl * MD)9947330f729Sjoerg RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
9957330f729Sjoerg                                                    const ObjCMethodDecl *MD) {
9967330f729Sjoerg   if (!MD)
9977330f729Sjoerg     return;
9987330f729Sjoerg 
9997330f729Sjoerg   assert(Summ && "Must have a valid summary to add annotations to");
10007330f729Sjoerg   RetainSummaryTemplate Template(Summ, *this);
10017330f729Sjoerg 
10027330f729Sjoerg   // Effects on the receiver.
10037330f729Sjoerg   if (hasAnyEnabledAttrOf<NSConsumesSelfAttr>(MD, MD->getReturnType()))
10047330f729Sjoerg     Template->setReceiverEffect(ArgEffect(DecRef, ObjKind::ObjC));
10057330f729Sjoerg 
10067330f729Sjoerg   // Effects on the parameters.
10077330f729Sjoerg   unsigned parm_idx = 0;
10087330f729Sjoerg   for (auto pi = MD->param_begin(), pe = MD->param_end(); pi != pe;
10097330f729Sjoerg        ++pi, ++parm_idx)
10107330f729Sjoerg     applyParamAnnotationEffect(*pi, parm_idx, MD, Template);
10117330f729Sjoerg 
10127330f729Sjoerg   QualType RetTy = MD->getReturnType();
10137330f729Sjoerg   if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
10147330f729Sjoerg     Template->setRetEffect(*RetE);
10157330f729Sjoerg }
10167330f729Sjoerg 
10177330f729Sjoerg const RetainSummary *
getStandardMethodSummary(const ObjCMethodDecl * MD,Selector S,QualType RetTy)10187330f729Sjoerg RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
10197330f729Sjoerg                                                Selector S, QualType RetTy) {
10207330f729Sjoerg   // Any special effects?
10217330f729Sjoerg   ArgEffect ReceiverEff = ArgEffect(DoNothing, ObjKind::ObjC);
10227330f729Sjoerg   RetEffect ResultEff = RetEffect::MakeNoRet();
10237330f729Sjoerg 
10247330f729Sjoerg   // Check the method family, and apply any default annotations.
10257330f729Sjoerg   switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
10267330f729Sjoerg     case OMF_None:
10277330f729Sjoerg     case OMF_initialize:
10287330f729Sjoerg     case OMF_performSelector:
10297330f729Sjoerg       // Assume all Objective-C methods follow Cocoa Memory Management rules.
10307330f729Sjoerg       // FIXME: Does the non-threaded performSelector family really belong here?
10317330f729Sjoerg       // The selector could be, say, @selector(copy).
10327330f729Sjoerg       if (cocoa::isCocoaObjectRef(RetTy))
10337330f729Sjoerg         ResultEff = RetEffect::MakeNotOwned(ObjKind::ObjC);
10347330f729Sjoerg       else if (coreFoundation::isCFObjectRef(RetTy)) {
10357330f729Sjoerg         // ObjCMethodDecl currently doesn't consider CF objects as valid return
10367330f729Sjoerg         // values for alloc, new, copy, or mutableCopy, so we have to
10377330f729Sjoerg         // double-check with the selector. This is ugly, but there aren't that
10387330f729Sjoerg         // many Objective-C methods that return CF objects, right?
10397330f729Sjoerg         if (MD) {
10407330f729Sjoerg           switch (S.getMethodFamily()) {
10417330f729Sjoerg           case OMF_alloc:
10427330f729Sjoerg           case OMF_new:
10437330f729Sjoerg           case OMF_copy:
10447330f729Sjoerg           case OMF_mutableCopy:
10457330f729Sjoerg             ResultEff = RetEffect::MakeOwned(ObjKind::CF);
10467330f729Sjoerg             break;
10477330f729Sjoerg           default:
10487330f729Sjoerg             ResultEff = RetEffect::MakeNotOwned(ObjKind::CF);
10497330f729Sjoerg             break;
10507330f729Sjoerg           }
10517330f729Sjoerg         } else {
10527330f729Sjoerg           ResultEff = RetEffect::MakeNotOwned(ObjKind::CF);
10537330f729Sjoerg         }
10547330f729Sjoerg       }
10557330f729Sjoerg       break;
10567330f729Sjoerg     case OMF_init:
10577330f729Sjoerg       ResultEff = ObjCInitRetE;
10587330f729Sjoerg       ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC);
10597330f729Sjoerg       break;
10607330f729Sjoerg     case OMF_alloc:
10617330f729Sjoerg     case OMF_new:
10627330f729Sjoerg     case OMF_copy:
10637330f729Sjoerg     case OMF_mutableCopy:
10647330f729Sjoerg       if (cocoa::isCocoaObjectRef(RetTy))
10657330f729Sjoerg         ResultEff = ObjCAllocRetE;
10667330f729Sjoerg       else if (coreFoundation::isCFObjectRef(RetTy))
10677330f729Sjoerg         ResultEff = RetEffect::MakeOwned(ObjKind::CF);
10687330f729Sjoerg       break;
10697330f729Sjoerg     case OMF_autorelease:
10707330f729Sjoerg       ReceiverEff = ArgEffect(Autorelease, ObjKind::ObjC);
10717330f729Sjoerg       break;
10727330f729Sjoerg     case OMF_retain:
10737330f729Sjoerg       ReceiverEff = ArgEffect(IncRef, ObjKind::ObjC);
10747330f729Sjoerg       break;
10757330f729Sjoerg     case OMF_release:
10767330f729Sjoerg       ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC);
10777330f729Sjoerg       break;
10787330f729Sjoerg     case OMF_dealloc:
10797330f729Sjoerg       ReceiverEff = ArgEffect(Dealloc, ObjKind::ObjC);
10807330f729Sjoerg       break;
10817330f729Sjoerg     case OMF_self:
10827330f729Sjoerg       // -self is handled specially by the ExprEngine to propagate the receiver.
10837330f729Sjoerg       break;
10847330f729Sjoerg     case OMF_retainCount:
10857330f729Sjoerg     case OMF_finalize:
10867330f729Sjoerg       // These methods don't return objects.
10877330f729Sjoerg       break;
10887330f729Sjoerg   }
10897330f729Sjoerg 
10907330f729Sjoerg   // If one of the arguments in the selector has the keyword 'delegate' we
10917330f729Sjoerg   // should stop tracking the reference count for the receiver.  This is
10927330f729Sjoerg   // because the reference count is quite possibly handled by a delegate
10937330f729Sjoerg   // method.
10947330f729Sjoerg   if (S.isKeywordSelector()) {
10957330f729Sjoerg     for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
10967330f729Sjoerg       StringRef Slot = S.getNameForSlot(i);
10977330f729Sjoerg       if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
10987330f729Sjoerg         if (ResultEff == ObjCInitRetE)
10997330f729Sjoerg           ResultEff = RetEffect::MakeNoRetHard();
11007330f729Sjoerg         else
11017330f729Sjoerg           ReceiverEff = ArgEffect(StopTrackingHard, ObjKind::ObjC);
11027330f729Sjoerg       }
11037330f729Sjoerg     }
11047330f729Sjoerg   }
11057330f729Sjoerg 
11067330f729Sjoerg   if (ReceiverEff.getKind() == DoNothing &&
11077330f729Sjoerg       ResultEff.getKind() == RetEffect::NoRet)
11087330f729Sjoerg     return getDefaultSummary();
11097330f729Sjoerg 
11107330f729Sjoerg   return getPersistentSummary(ResultEff, ArgEffects(AF.getEmptyMap()),
11117330f729Sjoerg                               ArgEffect(ReceiverEff), ArgEffect(MayEscape));
11127330f729Sjoerg }
11137330f729Sjoerg 
11147330f729Sjoerg const RetainSummary *
getClassMethodSummary(const ObjCMessageExpr * ME)11157330f729Sjoerg RetainSummaryManager::getClassMethodSummary(const ObjCMessageExpr *ME) {
11167330f729Sjoerg   assert(!ME->isInstanceMessage());
11177330f729Sjoerg   const ObjCInterfaceDecl *Class = ME->getReceiverInterface();
11187330f729Sjoerg 
11197330f729Sjoerg   return getMethodSummary(ME->getSelector(), Class, ME->getMethodDecl(),
11207330f729Sjoerg                           ME->getType(), ObjCClassMethodSummaries);
11217330f729Sjoerg }
11227330f729Sjoerg 
getInstanceMethodSummary(const ObjCMessageExpr * ME,QualType ReceiverType)11237330f729Sjoerg const RetainSummary *RetainSummaryManager::getInstanceMethodSummary(
11247330f729Sjoerg     const ObjCMessageExpr *ME,
11257330f729Sjoerg     QualType ReceiverType) {
11267330f729Sjoerg   const ObjCInterfaceDecl *ReceiverClass = nullptr;
11277330f729Sjoerg 
11287330f729Sjoerg   // We do better tracking of the type of the object than the core ExprEngine.
11297330f729Sjoerg   // See if we have its type in our private state.
11307330f729Sjoerg   if (!ReceiverType.isNull())
11317330f729Sjoerg     if (const auto *PT = ReceiverType->getAs<ObjCObjectPointerType>())
11327330f729Sjoerg       ReceiverClass = PT->getInterfaceDecl();
11337330f729Sjoerg 
11347330f729Sjoerg   // If we don't know what kind of object this is, fall back to its static type.
11357330f729Sjoerg   if (!ReceiverClass)
11367330f729Sjoerg     ReceiverClass = ME->getReceiverInterface();
11377330f729Sjoerg 
11387330f729Sjoerg   // FIXME: The receiver could be a reference to a class, meaning that
11397330f729Sjoerg   //  we should use the class method.
11407330f729Sjoerg   // id x = [NSObject class];
11417330f729Sjoerg   // [x performSelector:... withObject:... afterDelay:...];
11427330f729Sjoerg   Selector S = ME->getSelector();
11437330f729Sjoerg   const ObjCMethodDecl *Method = ME->getMethodDecl();
11447330f729Sjoerg   if (!Method && ReceiverClass)
11457330f729Sjoerg     Method = ReceiverClass->getInstanceMethod(S);
11467330f729Sjoerg 
11477330f729Sjoerg   return getMethodSummary(S, ReceiverClass, Method, ME->getType(),
11487330f729Sjoerg                           ObjCMethodSummaries);
11497330f729Sjoerg }
11507330f729Sjoerg 
11517330f729Sjoerg const RetainSummary *
getMethodSummary(Selector S,const ObjCInterfaceDecl * ID,const ObjCMethodDecl * MD,QualType RetTy,ObjCMethodSummariesTy & CachedSummaries)11527330f729Sjoerg RetainSummaryManager::getMethodSummary(Selector S,
11537330f729Sjoerg                                        const ObjCInterfaceDecl *ID,
11547330f729Sjoerg                                        const ObjCMethodDecl *MD, QualType RetTy,
11557330f729Sjoerg                                        ObjCMethodSummariesTy &CachedSummaries) {
11567330f729Sjoerg 
11577330f729Sjoerg   // Objective-C method summaries are only applicable to ObjC and CF objects.
11587330f729Sjoerg   if (!TrackObjCAndCFObjects)
11597330f729Sjoerg     return getDefaultSummary();
11607330f729Sjoerg 
11617330f729Sjoerg   // Look up a summary in our summary cache.
11627330f729Sjoerg   const RetainSummary *Summ = CachedSummaries.find(ID, S);
11637330f729Sjoerg 
11647330f729Sjoerg   if (!Summ) {
11657330f729Sjoerg     Summ = getStandardMethodSummary(MD, S, RetTy);
11667330f729Sjoerg 
11677330f729Sjoerg     // Annotations override defaults.
11687330f729Sjoerg     updateSummaryFromAnnotations(Summ, MD);
11697330f729Sjoerg 
11707330f729Sjoerg     // Memoize the summary.
11717330f729Sjoerg     CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
11727330f729Sjoerg   }
11737330f729Sjoerg 
11747330f729Sjoerg   return Summ;
11757330f729Sjoerg }
11767330f729Sjoerg 
InitializeClassMethodSummaries()11777330f729Sjoerg void RetainSummaryManager::InitializeClassMethodSummaries() {
11787330f729Sjoerg   ArgEffects ScratchArgs = AF.getEmptyMap();
11797330f729Sjoerg 
11807330f729Sjoerg   // Create the [NSAssertionHandler currentHander] summary.
11817330f729Sjoerg   addClassMethSummary("NSAssertionHandler", "currentHandler",
11827330f729Sjoerg                 getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::ObjC),
11837330f729Sjoerg                                      ScratchArgs));
11847330f729Sjoerg 
11857330f729Sjoerg   // Create the [NSAutoreleasePool addObject:] summary.
11867330f729Sjoerg   ScratchArgs = AF.add(ScratchArgs, 0, ArgEffect(Autorelease));
11877330f729Sjoerg   addClassMethSummary("NSAutoreleasePool", "addObject",
11887330f729Sjoerg                       getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
11897330f729Sjoerg                                            ArgEffect(DoNothing),
11907330f729Sjoerg                                            ArgEffect(Autorelease)));
11917330f729Sjoerg }
11927330f729Sjoerg 
InitializeMethodSummaries()11937330f729Sjoerg void RetainSummaryManager::InitializeMethodSummaries() {
11947330f729Sjoerg 
11957330f729Sjoerg   ArgEffects ScratchArgs = AF.getEmptyMap();
11967330f729Sjoerg   // Create the "init" selector.  It just acts as a pass-through for the
11977330f729Sjoerg   // receiver.
11987330f729Sjoerg   const RetainSummary *InitSumm = getPersistentSummary(
11997330f729Sjoerg       ObjCInitRetE, ScratchArgs, ArgEffect(DecRef, ObjKind::ObjC));
12007330f729Sjoerg   addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
12017330f729Sjoerg 
12027330f729Sjoerg   // awakeAfterUsingCoder: behaves basically like an 'init' method.  It
12037330f729Sjoerg   // claims the receiver and returns a retained object.
12047330f729Sjoerg   addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
12057330f729Sjoerg                          InitSumm);
12067330f729Sjoerg 
12077330f729Sjoerg   // The next methods are allocators.
12087330f729Sjoerg   const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE,
12097330f729Sjoerg                                                         ScratchArgs);
12107330f729Sjoerg   const RetainSummary *CFAllocSumm =
12117330f729Sjoerg     getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs);
12127330f729Sjoerg 
12137330f729Sjoerg   // Create the "retain" selector.
12147330f729Sjoerg   RetEffect NoRet = RetEffect::MakeNoRet();
12157330f729Sjoerg   const RetainSummary *Summ = getPersistentSummary(
12167330f729Sjoerg       NoRet, ScratchArgs, ArgEffect(IncRef, ObjKind::ObjC));
12177330f729Sjoerg   addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
12187330f729Sjoerg 
12197330f729Sjoerg   // Create the "release" selector.
12207330f729Sjoerg   Summ = getPersistentSummary(NoRet, ScratchArgs,
12217330f729Sjoerg                               ArgEffect(DecRef, ObjKind::ObjC));
12227330f729Sjoerg   addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
12237330f729Sjoerg 
12247330f729Sjoerg   // Create the -dealloc summary.
12257330f729Sjoerg   Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Dealloc,
12267330f729Sjoerg                                                             ObjKind::ObjC));
12277330f729Sjoerg   addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
12287330f729Sjoerg 
12297330f729Sjoerg   // Create the "autorelease" selector.
12307330f729Sjoerg   Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Autorelease,
12317330f729Sjoerg                                                             ObjKind::ObjC));
12327330f729Sjoerg   addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
12337330f729Sjoerg 
12347330f729Sjoerg   // For NSWindow, allocated objects are (initially) self-owned.
12357330f729Sjoerg   // FIXME: For now we opt for false negatives with NSWindow, as these objects
12367330f729Sjoerg   //  self-own themselves.  However, they only do this once they are displayed.
12377330f729Sjoerg   //  Thus, we need to track an NSWindow's display status.
12387330f729Sjoerg   //  This is tracked in <rdar://problem/6062711>.
12397330f729Sjoerg   //  See also http://llvm.org/bugs/show_bug.cgi?id=3714.
12407330f729Sjoerg   const RetainSummary *NoTrackYet =
12417330f729Sjoerg       getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
12427330f729Sjoerg                            ArgEffect(StopTracking), ArgEffect(StopTracking));
12437330f729Sjoerg 
12447330f729Sjoerg   addClassMethSummary("NSWindow", "alloc", NoTrackYet);
12457330f729Sjoerg 
12467330f729Sjoerg   // For NSPanel (which subclasses NSWindow), allocated objects are not
12477330f729Sjoerg   //  self-owned.
12487330f729Sjoerg   // FIXME: For now we don't track NSPanels. object for the same reason
12497330f729Sjoerg   //   as for NSWindow objects.
12507330f729Sjoerg   addClassMethSummary("NSPanel", "alloc", NoTrackYet);
12517330f729Sjoerg 
12527330f729Sjoerg   // For NSNull, objects returned by +null are singletons that ignore
12537330f729Sjoerg   // retain/release semantics.  Just don't track them.
12547330f729Sjoerg   // <rdar://problem/12858915>
12557330f729Sjoerg   addClassMethSummary("NSNull", "null", NoTrackYet);
12567330f729Sjoerg 
12577330f729Sjoerg   // Don't track allocated autorelease pools, as it is okay to prematurely
12587330f729Sjoerg   // exit a method.
12597330f729Sjoerg   addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
12607330f729Sjoerg   addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
12617330f729Sjoerg   addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
12627330f729Sjoerg 
12637330f729Sjoerg   // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
12647330f729Sjoerg   addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType");
12657330f729Sjoerg   addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType");
12667330f729Sjoerg 
12677330f729Sjoerg   // Create summaries for CIContext, 'createCGImage' and
12687330f729Sjoerg   // 'createCGLayerWithSize'.  These objects are CF objects, and are not
12697330f729Sjoerg   // automatically garbage collected.
12707330f729Sjoerg   addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect");
12717330f729Sjoerg   addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
12727330f729Sjoerg                      "format", "colorSpace");
12737330f729Sjoerg   addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info");
12747330f729Sjoerg }
12757330f729Sjoerg 
12767330f729Sjoerg const RetainSummary *
getMethodSummary(const ObjCMethodDecl * MD)12777330f729Sjoerg RetainSummaryManager::getMethodSummary(const ObjCMethodDecl *MD) {
12787330f729Sjoerg   const ObjCInterfaceDecl *ID = MD->getClassInterface();
12797330f729Sjoerg   Selector S = MD->getSelector();
12807330f729Sjoerg   QualType ResultTy = MD->getReturnType();
12817330f729Sjoerg 
12827330f729Sjoerg   ObjCMethodSummariesTy *CachedSummaries;
12837330f729Sjoerg   if (MD->isInstanceMethod())
12847330f729Sjoerg     CachedSummaries = &ObjCMethodSummaries;
12857330f729Sjoerg   else
12867330f729Sjoerg     CachedSummaries = &ObjCClassMethodSummaries;
12877330f729Sjoerg 
12887330f729Sjoerg   return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
12897330f729Sjoerg }
1290