Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:15

0001 //===- ObjCARCAnalysisUtils.h - ObjC ARC Analysis Utilities -----*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 /// \file
0009 /// This file defines common analysis utilities used by the ObjC ARC Optimizer.
0010 /// ARC stands for Automatic Reference Counting and is a system for managing
0011 /// reference counts for objects in Objective C.
0012 ///
0013 /// WARNING: This file knows about certain library functions. It recognizes them
0014 /// by name, and hardwires knowledge of their semantics.
0015 ///
0016 /// WARNING: This file knows about how certain Objective-C library functions are
0017 /// used. Naive LLVM IR transformations which would otherwise be
0018 /// behavior-preserving may break these assumptions.
0019 ///
0020 //===----------------------------------------------------------------------===//
0021 
0022 #ifndef LLVM_ANALYSIS_OBJCARCANALYSISUTILS_H
0023 #define LLVM_ANALYSIS_OBJCARCANALYSISUTILS_H
0024 
0025 #include "llvm/Analysis/ObjCARCInstKind.h"
0026 #include "llvm/Analysis/ValueTracking.h"
0027 #include "llvm/IR/Constants.h"
0028 #include "llvm/IR/Module.h"
0029 #include "llvm/IR/ValueHandle.h"
0030 #include <optional>
0031 
0032 namespace llvm {
0033 
0034 class AAResults;
0035 
0036 namespace objcarc {
0037 
0038 /// A handy option to enable/disable all ARC Optimizations.
0039 extern bool EnableARCOpts;
0040 
0041 /// Test if the given module looks interesting to run ARC optimization
0042 /// on.
0043 inline bool ModuleHasARC(const Module &M) {
0044   return M.getNamedValue("llvm.objc.retain") ||
0045          M.getNamedValue("llvm.objc.release") ||
0046          M.getNamedValue("llvm.objc.autorelease") ||
0047          M.getNamedValue("llvm.objc.retainAutoreleasedReturnValue") ||
0048          M.getNamedValue("llvm.objc.unsafeClaimAutoreleasedReturnValue") ||
0049          M.getNamedValue("llvm.objc.retainBlock") ||
0050          M.getNamedValue("llvm.objc.autoreleaseReturnValue") ||
0051          M.getNamedValue("llvm.objc.autoreleasePoolPush") ||
0052          M.getNamedValue("llvm.objc.loadWeakRetained") ||
0053          M.getNamedValue("llvm.objc.loadWeak") ||
0054          M.getNamedValue("llvm.objc.destroyWeak") ||
0055          M.getNamedValue("llvm.objc.storeWeak") ||
0056          M.getNamedValue("llvm.objc.initWeak") ||
0057          M.getNamedValue("llvm.objc.moveWeak") ||
0058          M.getNamedValue("llvm.objc.copyWeak") ||
0059          M.getNamedValue("llvm.objc.retainedObject") ||
0060          M.getNamedValue("llvm.objc.unretainedObject") ||
0061          M.getNamedValue("llvm.objc.unretainedPointer") ||
0062          M.getNamedValue("llvm.objc.clang.arc.noop.use") ||
0063          M.getNamedValue("llvm.objc.clang.arc.use");
0064 }
0065 
0066 /// This is a wrapper around getUnderlyingObject which also knows how to
0067 /// look through objc_retain and objc_autorelease calls, which we know to return
0068 /// their argument verbatim.
0069 inline const Value *GetUnderlyingObjCPtr(const Value *V) {
0070   for (;;) {
0071     V = getUnderlyingObject(V);
0072     if (!IsForwarding(GetBasicARCInstKind(V)))
0073       break;
0074     V = cast<CallInst>(V)->getArgOperand(0);
0075   }
0076 
0077   return V;
0078 }
0079 
0080 /// A wrapper for GetUnderlyingObjCPtr used for results memoization.
0081 inline const Value *GetUnderlyingObjCPtrCached(
0082     const Value *V,
0083     DenseMap<const Value *, std::pair<WeakVH, WeakTrackingVH>> &Cache) {
0084   // The entry is invalid if either value handle is null.
0085   auto InCache = Cache.lookup(V);
0086   if (InCache.first && InCache.second)
0087     return InCache.second;
0088 
0089   const Value *Computed = GetUnderlyingObjCPtr(V);
0090   Cache[V] =
0091       std::make_pair(const_cast<Value *>(V), const_cast<Value *>(Computed));
0092   return Computed;
0093 }
0094 
0095 /// The RCIdentity root of a value \p V is a dominating value U for which
0096 /// retaining or releasing U is equivalent to retaining or releasing V. In other
0097 /// words, ARC operations on \p V are equivalent to ARC operations on \p U.
0098 ///
0099 /// We use this in the ARC optimizer to make it easier to match up ARC
0100 /// operations by always mapping ARC operations to RCIdentityRoots instead of
0101 /// pointers themselves.
0102 ///
0103 /// The two ways that we see RCIdentical values in ObjC are via:
0104 ///
0105 ///   1. PointerCasts
0106 ///   2. Forwarding Calls that return their argument verbatim.
0107 ///
0108 /// Thus this function strips off pointer casts and forwarding calls. *NOTE*
0109 /// This implies that two RCIdentical values must alias.
0110 inline const Value *GetRCIdentityRoot(const Value *V) {
0111   for (;;) {
0112     V = V->stripPointerCasts();
0113     if (!IsForwarding(GetBasicARCInstKind(V)))
0114       break;
0115     V = cast<CallInst>(V)->getArgOperand(0);
0116   }
0117   return V;
0118 }
0119 
0120 /// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
0121 /// casts away the const of the result. For documentation about what an
0122 /// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
0123 /// function.
0124 inline Value *GetRCIdentityRoot(Value *V) {
0125   return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
0126 }
0127 
0128 /// Assuming the given instruction is one of the special calls such as
0129 /// objc_retain or objc_release, return the RCIdentity root of the argument of
0130 /// the call.
0131 inline Value *GetArgRCIdentityRoot(Value *Inst) {
0132   return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
0133 }
0134 
0135 inline bool IsNullOrUndef(const Value *V) {
0136   return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
0137 }
0138 
0139 inline bool IsNoopInstruction(const Instruction *I) {
0140   return isa<BitCastInst>(I) ||
0141     (isa<GetElementPtrInst>(I) &&
0142      cast<GetElementPtrInst>(I)->hasAllZeroIndices());
0143 }
0144 
0145 /// Test whether the given value is possible a retainable object pointer.
0146 inline bool IsPotentialRetainableObjPtr(const Value *Op) {
0147   // Pointers to static or stack storage are not valid retainable object
0148   // pointers.
0149   if (isa<Constant>(Op) || isa<AllocaInst>(Op))
0150     return false;
0151   // Special arguments can not be a valid retainable object pointer.
0152   if (const Argument *Arg = dyn_cast<Argument>(Op))
0153     if (Arg->hasPassPointeeByValueCopyAttr() || Arg->hasNestAttr() ||
0154         Arg->hasStructRetAttr())
0155       return false;
0156   // Only consider values with pointer types.
0157   //
0158   // It seemes intuitive to exclude function pointer types as well, since
0159   // functions are never retainable object pointers, however clang occasionally
0160   // bitcasts retainable object pointers to function-pointer type temporarily.
0161   PointerType *Ty = dyn_cast<PointerType>(Op->getType());
0162   if (!Ty)
0163     return false;
0164   // Conservatively assume anything else is a potential retainable object
0165   // pointer.
0166   return true;
0167 }
0168 
0169 bool IsPotentialRetainableObjPtr(const Value *Op, AAResults &AA);
0170 
0171 /// Helper for GetARCInstKind. Determines what kind of construct CS
0172 /// is.
0173 inline ARCInstKind GetCallSiteClass(const CallBase &CB) {
0174   for (const Use &U : CB.args())
0175     if (IsPotentialRetainableObjPtr(U))
0176       return CB.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
0177 
0178   return CB.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
0179 }
0180 
0181 /// Return true if this value refers to a distinct and identifiable
0182 /// object.
0183 ///
0184 /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
0185 /// special knowledge of ObjC conventions.
0186 inline bool IsObjCIdentifiedObject(const Value *V) {
0187   // Assume that call results and arguments have their own "provenance".
0188   // Constants (including GlobalVariables) and Allocas are never
0189   // reference-counted.
0190   if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
0191       isa<Argument>(V) || isa<Constant>(V) ||
0192       isa<AllocaInst>(V))
0193     return true;
0194 
0195   if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
0196     const Value *Pointer =
0197       GetRCIdentityRoot(LI->getPointerOperand());
0198     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
0199       // A constant pointer can't be pointing to an object on the heap. It may
0200       // be reference-counted, but it won't be deleted.
0201       if (GV->isConstant())
0202         return true;
0203       StringRef Name = GV->getName();
0204       // These special variables are known to hold values which are not
0205       // reference-counted pointers.
0206       if (Name.starts_with("\01l_objc_msgSend_fixup_"))
0207         return true;
0208 
0209       StringRef Section = GV->getSection();
0210       if (Section.contains("__message_refs") ||
0211           Section.contains("__objc_classrefs") ||
0212           Section.contains("__objc_superrefs") ||
0213           Section.contains("__objc_methname") || Section.contains("__cstring"))
0214         return true;
0215     }
0216   }
0217 
0218   return false;
0219 }
0220 
0221 enum class ARCMDKindID {
0222   ImpreciseRelease,
0223   CopyOnEscape,
0224   NoObjCARCExceptions,
0225 };
0226 
0227 /// A cache of MDKinds used by various ARC optimizations.
0228 class ARCMDKindCache {
0229   Module *M;
0230 
0231   /// The Metadata Kind for clang.imprecise_release metadata.
0232   std::optional<unsigned> ImpreciseReleaseMDKind;
0233 
0234   /// The Metadata Kind for clang.arc.copy_on_escape metadata.
0235   std::optional<unsigned> CopyOnEscapeMDKind;
0236 
0237   /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
0238   std::optional<unsigned> NoObjCARCExceptionsMDKind;
0239 
0240 public:
0241   void init(Module *Mod) {
0242     M = Mod;
0243     ImpreciseReleaseMDKind = std::nullopt;
0244     CopyOnEscapeMDKind = std::nullopt;
0245     NoObjCARCExceptionsMDKind = std::nullopt;
0246   }
0247 
0248   unsigned get(ARCMDKindID ID) {
0249     switch (ID) {
0250     case ARCMDKindID::ImpreciseRelease:
0251       if (!ImpreciseReleaseMDKind)
0252         ImpreciseReleaseMDKind =
0253             M->getContext().getMDKindID("clang.imprecise_release");
0254       return *ImpreciseReleaseMDKind;
0255     case ARCMDKindID::CopyOnEscape:
0256       if (!CopyOnEscapeMDKind)
0257         CopyOnEscapeMDKind =
0258             M->getContext().getMDKindID("clang.arc.copy_on_escape");
0259       return *CopyOnEscapeMDKind;
0260     case ARCMDKindID::NoObjCARCExceptions:
0261       if (!NoObjCARCExceptionsMDKind)
0262         NoObjCARCExceptionsMDKind =
0263             M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
0264       return *NoObjCARCExceptionsMDKind;
0265     }
0266     llvm_unreachable("Covered switch isn't covered?!");
0267   }
0268 };
0269 
0270 } // end namespace objcarc
0271 } // end namespace llvm
0272 
0273 #endif