Michael Gottesman | 79d8d81 | 2013-01-28 01:35:51 +0000 | [diff] [blame] | 1 | //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 9 | /// \file |
| 10 | /// This file defines ObjC ARC optimizations. ARC stands for Automatic |
| 11 | /// Reference Counting and is a system for managing reference counts for objects |
| 12 | /// in Objective C. |
| 13 | /// |
| 14 | /// The optimizations performed include elimination of redundant, partially |
| 15 | /// redundant, and inconsequential reference count operations, elimination of |
Michael Gottesman | 697d8b9 | 2013-02-07 04:12:57 +0000 | [diff] [blame] | 16 | /// redundant weak pointer operations, and numerous minor simplifications. |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 17 | /// |
| 18 | /// WARNING: This file knows about certain library functions. It recognizes them |
| 19 | /// by name, and hardwires knowledge of their semantics. |
| 20 | /// |
| 21 | /// WARNING: This file knows about how certain Objective-C library functions are |
| 22 | /// used. Naive LLVM IR transformations which would otherwise be |
| 23 | /// behavior-preserving may break these assumptions. |
| 24 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 25 | //===----------------------------------------------------------------------===// |
| 26 | |
Michael Gottesman | 08904e3 | 2013-01-28 03:28:38 +0000 | [diff] [blame] | 27 | #define DEBUG_TYPE "objc-arc-opts" |
| 28 | #include "ObjCARC.h" |
Michael Gottesman | 278266f | 2013-01-29 04:20:52 +0000 | [diff] [blame] | 29 | #include "DependencyAnalysis.h" |
Michael Gottesman | 294e7da | 2013-01-28 05:51:54 +0000 | [diff] [blame] | 30 | #include "ObjCARCAliasAnalysis.h" |
Michael Gottesman | 778138e | 2013-01-29 03:03:03 +0000 | [diff] [blame] | 31 | #include "ProvenanceAnalysis.h" |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 32 | #include "llvm/ADT/DenseMap.h" |
Michael Gottesman | fa0939f | 2013-01-28 04:12:07 +0000 | [diff] [blame] | 33 | #include "llvm/ADT/STLExtras.h" |
Michael Gottesman | 778138e | 2013-01-29 03:03:03 +0000 | [diff] [blame] | 34 | #include "llvm/ADT/SmallPtrSet.h" |
Michael Gottesman | 278266f | 2013-01-29 04:20:52 +0000 | [diff] [blame] | 35 | #include "llvm/ADT/Statistic.h" |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 36 | #include "llvm/IR/IRBuilder.h" |
Michael Gottesman | 278266f | 2013-01-29 04:20:52 +0000 | [diff] [blame] | 37 | #include "llvm/IR/LLVMContext.h" |
Michael Gottesman | 778138e | 2013-01-29 03:03:03 +0000 | [diff] [blame] | 38 | #include "llvm/Support/CFG.h" |
Michael Gottesman | 13a5f1a | 2013-01-29 04:51:59 +0000 | [diff] [blame] | 39 | #include "llvm/Support/Debug.h" |
Timur Iskhodzhanov | 5d7ff00 | 2013-01-29 09:09:27 +0000 | [diff] [blame] | 40 | #include "llvm/Support/raw_ostream.h" |
Michael Gottesman | fa0939f | 2013-01-28 04:12:07 +0000 | [diff] [blame] | 41 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 42 | using namespace llvm; |
Michael Gottesman | 08904e3 | 2013-01-28 03:28:38 +0000 | [diff] [blame] | 43 | using namespace llvm::objcarc; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 44 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 45 | /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific. |
| 46 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 47 | |
| 48 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 49 | /// \brief An associative container with fast insertion-order (deterministic) |
| 50 | /// iteration over its elements. Plus the special blot operation. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 51 | template<class KeyT, class ValueT> |
| 52 | class MapVector { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 53 | /// Map keys to indices in Vector. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 54 | typedef DenseMap<KeyT, size_t> MapTy; |
| 55 | MapTy Map; |
| 56 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 57 | typedef std::vector<std::pair<KeyT, ValueT> > VectorTy; |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 58 | /// Keys and values. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 59 | VectorTy Vector; |
| 60 | |
| 61 | public: |
| 62 | typedef typename VectorTy::iterator iterator; |
| 63 | typedef typename VectorTy::const_iterator const_iterator; |
| 64 | iterator begin() { return Vector.begin(); } |
| 65 | iterator end() { return Vector.end(); } |
| 66 | const_iterator begin() const { return Vector.begin(); } |
| 67 | const_iterator end() const { return Vector.end(); } |
| 68 | |
| 69 | #ifdef XDEBUG |
| 70 | ~MapVector() { |
| 71 | assert(Vector.size() >= Map.size()); // May differ due to blotting. |
| 72 | for (typename MapTy::const_iterator I = Map.begin(), E = Map.end(); |
| 73 | I != E; ++I) { |
| 74 | assert(I->second < Vector.size()); |
| 75 | assert(Vector[I->second].first == I->first); |
| 76 | } |
| 77 | for (typename VectorTy::const_iterator I = Vector.begin(), |
| 78 | E = Vector.end(); I != E; ++I) |
| 79 | assert(!I->first || |
| 80 | (Map.count(I->first) && |
| 81 | Map[I->first] == size_t(I - Vector.begin()))); |
| 82 | } |
| 83 | #endif |
| 84 | |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 85 | ValueT &operator[](const KeyT &Arg) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 86 | std::pair<typename MapTy::iterator, bool> Pair = |
| 87 | Map.insert(std::make_pair(Arg, size_t(0))); |
| 88 | if (Pair.second) { |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 89 | size_t Num = Vector.size(); |
| 90 | Pair.first->second = Num; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 91 | Vector.push_back(std::make_pair(Arg, ValueT())); |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 92 | return Vector[Num].second; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 93 | } |
| 94 | return Vector[Pair.first->second].second; |
| 95 | } |
| 96 | |
| 97 | std::pair<iterator, bool> |
| 98 | insert(const std::pair<KeyT, ValueT> &InsertPair) { |
| 99 | std::pair<typename MapTy::iterator, bool> Pair = |
| 100 | Map.insert(std::make_pair(InsertPair.first, size_t(0))); |
| 101 | if (Pair.second) { |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 102 | size_t Num = Vector.size(); |
| 103 | Pair.first->second = Num; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 104 | Vector.push_back(InsertPair); |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 105 | return std::make_pair(Vector.begin() + Num, true); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 106 | } |
| 107 | return std::make_pair(Vector.begin() + Pair.first->second, false); |
| 108 | } |
| 109 | |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 110 | const_iterator find(const KeyT &Key) const { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 111 | typename MapTy::const_iterator It = Map.find(Key); |
| 112 | if (It == Map.end()) return Vector.end(); |
| 113 | return Vector.begin() + It->second; |
| 114 | } |
| 115 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 116 | /// This is similar to erase, but instead of removing the element from the |
| 117 | /// vector, it just zeros out the key in the vector. This leaves iterators |
| 118 | /// intact, but clients must be prepared for zeroed-out keys when iterating. |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 119 | void blot(const KeyT &Key) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 120 | typename MapTy::iterator It = Map.find(Key); |
| 121 | if (It == Map.end()) return; |
| 122 | Vector[It->second].first = KeyT(); |
| 123 | Map.erase(It); |
| 124 | } |
| 125 | |
| 126 | void clear() { |
| 127 | Map.clear(); |
| 128 | Vector.clear(); |
| 129 | } |
| 130 | }; |
| 131 | } |
| 132 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 133 | /// @} |
| 134 | /// |
| 135 | /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC. |
| 136 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 137 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 138 | /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon |
| 139 | /// as it finds a value with multiple uses. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 140 | static const Value *FindSingleUseIdentifiedObject(const Value *Arg) { |
| 141 | if (Arg->hasOneUse()) { |
| 142 | if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg)) |
| 143 | return FindSingleUseIdentifiedObject(BC->getOperand(0)); |
| 144 | if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg)) |
| 145 | if (GEP->hasAllZeroIndices()) |
| 146 | return FindSingleUseIdentifiedObject(GEP->getPointerOperand()); |
| 147 | if (IsForwarding(GetBasicInstructionClass(Arg))) |
| 148 | return FindSingleUseIdentifiedObject( |
| 149 | cast<CallInst>(Arg)->getArgOperand(0)); |
| 150 | if (!IsObjCIdentifiedObject(Arg)) |
| 151 | return 0; |
| 152 | return Arg; |
| 153 | } |
| 154 | |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 155 | // If we found an identifiable object but it has multiple uses, but they are |
| 156 | // trivial uses, we can still consider this to be a single-use value. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 157 | if (IsObjCIdentifiedObject(Arg)) { |
| 158 | for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end(); |
| 159 | UI != UE; ++UI) { |
| 160 | const User *U = *UI; |
| 161 | if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg) |
| 162 | return 0; |
| 163 | } |
| 164 | |
| 165 | return Arg; |
| 166 | } |
| 167 | |
| 168 | return 0; |
| 169 | } |
| 170 | |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 171 | /// \brief Test whether the given retainable object pointer escapes. |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 172 | /// |
| 173 | /// This differs from regular escape analysis in that a use as an |
| 174 | /// argument to a call is not considered an escape. |
| 175 | /// |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 176 | static bool DoesRetainableObjPtrEscape(const User *Ptr) { |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 177 | DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n"); |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 178 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 179 | // Walk the def-use chains. |
| 180 | SmallVector<const Value *, 4> Worklist; |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 181 | Worklist.push_back(Ptr); |
| 182 | // If Ptr has any operands add them as well. |
Michael Gottesman | 23cda0c | 2013-01-29 21:07:53 +0000 | [diff] [blame] | 183 | for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E; |
| 184 | ++I) { |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 185 | Worklist.push_back(*I); |
| 186 | } |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 187 | |
| 188 | // Ensure we do not visit any value twice. |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 189 | SmallPtrSet<const Value *, 8> VisitedSet; |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 190 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 191 | do { |
| 192 | const Value *V = Worklist.pop_back_val(); |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 193 | |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 194 | DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Visiting: " << *V << "\n"); |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 195 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 196 | for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end(); |
| 197 | UI != UE; ++UI) { |
| 198 | const User *UUser = *UI; |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 199 | |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 200 | DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User: " << *UUser << "\n"); |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 201 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 202 | // Special - Use by a call (callee or argument) is not considered |
| 203 | // to be an escape. |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 204 | switch (GetBasicInstructionClass(UUser)) { |
| 205 | case IC_StoreWeak: |
| 206 | case IC_InitWeak: |
| 207 | case IC_StoreStrong: |
| 208 | case IC_Autorelease: |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 209 | case IC_AutoreleaseRV: { |
Michael Gottesman | 23cda0c | 2013-01-29 21:07:53 +0000 | [diff] [blame] | 210 | DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User copies pointer " |
| 211 | "arguments. Pointer Escapes!\n"); |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 212 | // These special functions make copies of their pointer arguments. |
| 213 | return true; |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 214 | } |
John McCall | 20182ac | 2013-03-22 21:38:36 +0000 | [diff] [blame] | 215 | case IC_IntrinsicUser: |
| 216 | // Use by the use intrinsic is not an escape. |
| 217 | continue; |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 218 | case IC_User: |
| 219 | case IC_None: |
| 220 | // Use by an instruction which copies the value is an escape if the |
| 221 | // result is an escape. |
| 222 | if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) || |
| 223 | isa<PHINode>(UUser) || isa<SelectInst>(UUser)) { |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 224 | |
Michael Gottesman | f4b7761 | 2013-02-23 00:31:32 +0000 | [diff] [blame] | 225 | if (VisitedSet.insert(UUser)) { |
Michael Gottesman | 23cda0c | 2013-01-29 21:07:53 +0000 | [diff] [blame] | 226 | DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User copies value. " |
| 227 | "Ptr escapes if result escapes. Adding to list.\n"); |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 228 | Worklist.push_back(UUser); |
| 229 | } else { |
Michael Gottesman | 23cda0c | 2013-01-29 21:07:53 +0000 | [diff] [blame] | 230 | DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Already visited node." |
| 231 | "\n"); |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 232 | } |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 233 | continue; |
| 234 | } |
| 235 | // Use by a load is not an escape. |
| 236 | if (isa<LoadInst>(UUser)) |
| 237 | continue; |
| 238 | // Use by a store is not an escape if the use is the address. |
| 239 | if (const StoreInst *SI = dyn_cast<StoreInst>(UUser)) |
| 240 | if (V != SI->getValueOperand()) |
| 241 | continue; |
| 242 | break; |
| 243 | default: |
| 244 | // Regular calls and other stuff are not considered escapes. |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 245 | continue; |
| 246 | } |
Dan Gohman | eb6e015 | 2012-02-13 22:57:02 +0000 | [diff] [blame] | 247 | // Otherwise, conservatively assume an escape. |
Michael Gottesman | 23cda0c | 2013-01-29 21:07:53 +0000 | [diff] [blame] | 248 | DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Assuming ptr escapes.\n"); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 249 | return true; |
| 250 | } |
| 251 | } while (!Worklist.empty()); |
| 252 | |
| 253 | // No escapes found. |
Michael Gottesman | 23cda0c | 2013-01-29 21:07:53 +0000 | [diff] [blame] | 254 | DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Ptr does not escape.\n"); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 255 | return false; |
| 256 | } |
| 257 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 258 | /// @} |
| 259 | /// |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 260 | /// \defgroup ARCOpt ARC Optimization. |
| 261 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 262 | |
| 263 | // TODO: On code like this: |
| 264 | // |
| 265 | // objc_retain(%x) |
| 266 | // stuff_that_cannot_release() |
| 267 | // objc_autorelease(%x) |
| 268 | // stuff_that_cannot_release() |
| 269 | // objc_retain(%x) |
| 270 | // stuff_that_cannot_release() |
| 271 | // objc_autorelease(%x) |
| 272 | // |
| 273 | // The second retain and autorelease can be deleted. |
| 274 | |
| 275 | // TODO: It should be possible to delete |
| 276 | // objc_autoreleasePoolPush and objc_autoreleasePoolPop |
| 277 | // pairs if nothing is actually autoreleased between them. Also, autorelease |
| 278 | // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code |
| 279 | // after inlining) can be turned into plain release calls. |
| 280 | |
| 281 | // TODO: Critical-edge splitting. If the optimial insertion point is |
| 282 | // a critical edge, the current algorithm has to fail, because it doesn't |
| 283 | // know how to split edges. It should be possible to make the optimizer |
| 284 | // think in terms of edges, rather than blocks, and then split critical |
| 285 | // edges on demand. |
| 286 | |
| 287 | // TODO: OptimizeSequences could generalized to be Interprocedural. |
| 288 | |
| 289 | // TODO: Recognize that a bunch of other objc runtime calls have |
| 290 | // non-escaping arguments and non-releasing arguments, and may be |
| 291 | // non-autoreleasing. |
| 292 | |
| 293 | // TODO: Sink autorelease calls as far as possible. Unfortunately we |
| 294 | // usually can't sink them past other calls, which would be the main |
| 295 | // case where it would be useful. |
| 296 | |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 297 | // TODO: The pointer returned from objc_loadWeakRetained is retained. |
| 298 | |
| 299 | // TODO: Delete release+retain pairs (rare). |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 300 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 301 | STATISTIC(NumNoops, "Number of no-op objc calls eliminated"); |
| 302 | STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated"); |
| 303 | STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases"); |
| 304 | STATISTIC(NumRets, "Number of return value forwarding " |
| 305 | "retain+autoreleaes eliminated"); |
| 306 | STATISTIC(NumRRs, "Number of retain+release paths eliminated"); |
| 307 | STATISTIC(NumPeeps, "Number of calls peephole-optimized"); |
| 308 | |
| 309 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 310 | /// \enum Sequence |
| 311 | /// |
| 312 | /// \brief A sequence of states that a pointer may go through in which an |
| 313 | /// objc_retain and objc_release are actually needed. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 314 | enum Sequence { |
| 315 | S_None, |
Michael Gottesman | 53fd20b | 2013-01-29 21:07:51 +0000 | [diff] [blame] | 316 | S_Retain, ///< objc_retain(x). |
| 317 | S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement. |
| 318 | S_Use, ///< any use of x. |
Michael Gottesman | 386241c | 2013-01-29 21:39:02 +0000 | [diff] [blame] | 319 | S_Stop, ///< like S_Release, but code motion is stopped. |
Michael Gottesman | 53fd20b | 2013-01-29 21:07:51 +0000 | [diff] [blame] | 320 | S_Release, ///< objc_release(x). |
Michael Gottesman | 9bdab2b | 2013-01-29 21:41:44 +0000 | [diff] [blame] | 321 | S_MovableRelease ///< objc_release(x), !clang.imprecise_release. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 322 | }; |
Michael Gottesman | 53fd20b | 2013-01-29 21:07:51 +0000 | [diff] [blame] | 323 | |
| 324 | raw_ostream &operator<<(raw_ostream &OS, const Sequence S) |
| 325 | LLVM_ATTRIBUTE_UNUSED; |
| 326 | raw_ostream &operator<<(raw_ostream &OS, const Sequence S) { |
| 327 | switch (S) { |
| 328 | case S_None: |
| 329 | return OS << "S_None"; |
| 330 | case S_Retain: |
| 331 | return OS << "S_Retain"; |
| 332 | case S_CanRelease: |
| 333 | return OS << "S_CanRelease"; |
| 334 | case S_Use: |
| 335 | return OS << "S_Use"; |
| 336 | case S_Release: |
| 337 | return OS << "S_Release"; |
| 338 | case S_MovableRelease: |
| 339 | return OS << "S_MovableRelease"; |
| 340 | case S_Stop: |
| 341 | return OS << "S_Stop"; |
| 342 | } |
| 343 | llvm_unreachable("Unknown sequence type."); |
| 344 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 345 | } |
| 346 | |
| 347 | static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) { |
| 348 | // The easy cases. |
| 349 | if (A == B) |
| 350 | return A; |
| 351 | if (A == S_None || B == S_None) |
| 352 | return S_None; |
| 353 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 354 | if (A > B) std::swap(A, B); |
| 355 | if (TopDown) { |
| 356 | // Choose the side which is further along in the sequence. |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 357 | if ((A == S_Retain || A == S_CanRelease) && |
| 358 | (B == S_CanRelease || B == S_Use)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 359 | return B; |
| 360 | } else { |
| 361 | // Choose the side which is further along in the sequence. |
| 362 | if ((A == S_Use || A == S_CanRelease) && |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 363 | (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 364 | return A; |
| 365 | // If both sides are releases, choose the more conservative one. |
| 366 | if (A == S_Stop && (B == S_Release || B == S_MovableRelease)) |
| 367 | return A; |
| 368 | if (A == S_Release && B == S_MovableRelease) |
| 369 | return A; |
| 370 | } |
| 371 | |
| 372 | return S_None; |
| 373 | } |
| 374 | |
| 375 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 376 | /// \brief Unidirectional information about either a |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 377 | /// retain-decrement-use-release sequence or release-use-decrement-retain |
| 378 | /// reverese sequence. |
| 379 | struct RRInfo { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 380 | /// After an objc_retain, the reference count of the referenced |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 381 | /// object is known to be positive. Similarly, before an objc_release, the |
| 382 | /// reference count of the referenced object is known to be positive. If |
| 383 | /// there are retain-release pairs in code regions where the retain count |
| 384 | /// is known to be positive, they can be eliminated, regardless of any side |
| 385 | /// effects between them. |
| 386 | /// |
| 387 | /// Also, a retain+release pair nested within another retain+release |
| 388 | /// pair all on the known same pointer value can be eliminated, regardless |
| 389 | /// of any intervening side effects. |
| 390 | /// |
| 391 | /// KnownSafe is true when either of these conditions is satisfied. |
| 392 | bool KnownSafe; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 393 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 394 | /// True of the objc_release calls are all marked with the "tail" keyword. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 395 | bool IsTailCallRelease; |
| 396 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 397 | /// If the Calls are objc_release calls and they all have a |
| 398 | /// clang.imprecise_release tag, this is the metadata tag. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 399 | MDNode *ReleaseMetadata; |
| 400 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 401 | /// For a top-down sequence, the set of objc_retains or |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 402 | /// objc_retainBlocks. For bottom-up, the set of objc_releases. |
| 403 | SmallPtrSet<Instruction *, 2> Calls; |
| 404 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 405 | /// The set of optimal insert positions for moving calls in the opposite |
| 406 | /// sequence. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 407 | SmallPtrSet<Instruction *, 2> ReverseInsertPts; |
| 408 | |
| 409 | RRInfo() : |
Michael Gottesman | ba64859 | 2013-03-28 23:08:44 +0000 | [diff] [blame^] | 410 | KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0) {} |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 411 | |
| 412 | void clear(); |
| 413 | }; |
| 414 | } |
| 415 | |
| 416 | void RRInfo::clear() { |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 417 | KnownSafe = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 418 | IsTailCallRelease = false; |
| 419 | ReleaseMetadata = 0; |
| 420 | Calls.clear(); |
| 421 | ReverseInsertPts.clear(); |
| 422 | } |
| 423 | |
| 424 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 425 | /// \brief This class summarizes several per-pointer runtime properties which |
| 426 | /// are propogated through the flow graph. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 427 | class PtrState { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 428 | /// True if the reference count is known to be incremented. |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 429 | bool KnownPositiveRefCount; |
| 430 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 431 | /// True of we've seen an opportunity for partial RR elimination, such as |
| 432 | /// pushing calls into a CFG triangle or into one side of a CFG diamond. |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 433 | bool Partial; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 434 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 435 | /// The current position in the sequence. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 436 | Sequence Seq : 8; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 437 | |
| 438 | public: |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 439 | /// Unidirectional information about the current sequence. |
| 440 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 441 | /// TODO: Encapsulate this better. |
| 442 | RRInfo RRI; |
| 443 | |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 444 | PtrState() : KnownPositiveRefCount(false), Partial(false), |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 445 | Seq(S_None) {} |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 446 | |
Michael Gottesman | 415ddd7 | 2013-02-05 19:32:18 +0000 | [diff] [blame] | 447 | void SetKnownPositiveRefCount() { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 448 | KnownPositiveRefCount = true; |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 449 | } |
| 450 | |
Michael Gottesman | 764b1cf | 2013-03-23 05:46:19 +0000 | [diff] [blame] | 451 | void ClearKnownPositiveRefCount() { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 452 | KnownPositiveRefCount = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 453 | } |
| 454 | |
Michael Gottesman | 07beea4 | 2013-03-23 05:31:01 +0000 | [diff] [blame] | 455 | bool HasKnownPositiveRefCount() const { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 456 | return KnownPositiveRefCount; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 457 | } |
| 458 | |
Michael Gottesman | 415ddd7 | 2013-02-05 19:32:18 +0000 | [diff] [blame] | 459 | void SetSeq(Sequence NewSeq) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 460 | Seq = NewSeq; |
| 461 | } |
| 462 | |
Michael Gottesman | 415ddd7 | 2013-02-05 19:32:18 +0000 | [diff] [blame] | 463 | Sequence GetSeq() const { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 464 | return Seq; |
| 465 | } |
| 466 | |
Michael Gottesman | 415ddd7 | 2013-02-05 19:32:18 +0000 | [diff] [blame] | 467 | void ClearSequenceProgress() { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 468 | ResetSequenceProgress(S_None); |
| 469 | } |
| 470 | |
Michael Gottesman | 415ddd7 | 2013-02-05 19:32:18 +0000 | [diff] [blame] | 471 | void ResetSequenceProgress(Sequence NewSeq) { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 472 | Seq = NewSeq; |
| 473 | Partial = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 474 | RRI.clear(); |
| 475 | } |
| 476 | |
| 477 | void Merge(const PtrState &Other, bool TopDown); |
| 478 | }; |
| 479 | } |
| 480 | |
| 481 | void |
| 482 | PtrState::Merge(const PtrState &Other, bool TopDown) { |
| 483 | Seq = MergeSeqs(Seq, Other.Seq, TopDown); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 484 | KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount; |
Michael Gottesman | ba64859 | 2013-03-28 23:08:44 +0000 | [diff] [blame^] | 485 | |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 486 | // If we're not in a sequence (anymore), drop all associated state. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 487 | if (Seq == S_None) { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 488 | Partial = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 489 | RRI.clear(); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 490 | } else if (Partial || Other.Partial) { |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 491 | // If we're doing a merge on a path that's previously seen a partial |
| 492 | // merge, conservatively drop the sequence, to avoid doing partial |
| 493 | // RR elimination. If the branch predicates for the two merge differ, |
| 494 | // mixing them is unsafe. |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 495 | ClearSequenceProgress(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 496 | } else { |
| 497 | // Conservatively merge the ReleaseMetadata information. |
| 498 | if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata) |
| 499 | RRI.ReleaseMetadata = 0; |
| 500 | |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 501 | RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 502 | RRI.IsTailCallRelease = RRI.IsTailCallRelease && |
| 503 | Other.RRI.IsTailCallRelease; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 504 | RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end()); |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 505 | |
| 506 | // Merge the insert point sets. If there are any differences, |
| 507 | // that makes this a partial merge. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 508 | Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size(); |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 509 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 510 | I = Other.RRI.ReverseInsertPts.begin(), |
| 511 | E = Other.RRI.ReverseInsertPts.end(); I != E; ++I) |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 512 | Partial |= RRI.ReverseInsertPts.insert(*I); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 513 | } |
| 514 | } |
| 515 | |
| 516 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 517 | /// \brief Per-BasicBlock state. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 518 | class BBState { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 519 | /// The number of unique control paths from the entry which can reach this |
| 520 | /// block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 521 | unsigned TopDownPathCount; |
| 522 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 523 | /// The number of unique control paths to exits from this block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 524 | unsigned BottomUpPathCount; |
| 525 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 526 | /// A type for PerPtrTopDown and PerPtrBottomUp. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 527 | typedef MapVector<const Value *, PtrState> MapTy; |
| 528 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 529 | /// The top-down traversal uses this to record information known about a |
| 530 | /// pointer at the bottom of each block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 531 | MapTy PerPtrTopDown; |
| 532 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 533 | /// The bottom-up traversal uses this to record information known about a |
| 534 | /// pointer at the top of each block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 535 | MapTy PerPtrBottomUp; |
| 536 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 537 | /// Effective predecessors of the current block ignoring ignorable edges and |
| 538 | /// ignored backedges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 539 | SmallVector<BasicBlock *, 2> Preds; |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 540 | /// Effective successors of the current block ignoring ignorable edges and |
| 541 | /// ignored backedges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 542 | SmallVector<BasicBlock *, 2> Succs; |
| 543 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 544 | public: |
| 545 | BBState() : TopDownPathCount(0), BottomUpPathCount(0) {} |
| 546 | |
| 547 | typedef MapTy::iterator ptr_iterator; |
| 548 | typedef MapTy::const_iterator ptr_const_iterator; |
| 549 | |
| 550 | ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); } |
| 551 | ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); } |
| 552 | ptr_const_iterator top_down_ptr_begin() const { |
| 553 | return PerPtrTopDown.begin(); |
| 554 | } |
| 555 | ptr_const_iterator top_down_ptr_end() const { |
| 556 | return PerPtrTopDown.end(); |
| 557 | } |
| 558 | |
| 559 | ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); } |
| 560 | ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); } |
| 561 | ptr_const_iterator bottom_up_ptr_begin() const { |
| 562 | return PerPtrBottomUp.begin(); |
| 563 | } |
| 564 | ptr_const_iterator bottom_up_ptr_end() const { |
| 565 | return PerPtrBottomUp.end(); |
| 566 | } |
| 567 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 568 | /// Mark this block as being an entry block, which has one path from the |
| 569 | /// entry by definition. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 570 | void SetAsEntry() { TopDownPathCount = 1; } |
| 571 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 572 | /// Mark this block as being an exit block, which has one path to an exit by |
| 573 | /// definition. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 574 | void SetAsExit() { BottomUpPathCount = 1; } |
| 575 | |
| 576 | PtrState &getPtrTopDownState(const Value *Arg) { |
| 577 | return PerPtrTopDown[Arg]; |
| 578 | } |
| 579 | |
| 580 | PtrState &getPtrBottomUpState(const Value *Arg) { |
| 581 | return PerPtrBottomUp[Arg]; |
| 582 | } |
| 583 | |
| 584 | void clearBottomUpPointers() { |
Evan Cheng | e4df6a2 | 2011-08-04 18:40:26 +0000 | [diff] [blame] | 585 | PerPtrBottomUp.clear(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 586 | } |
| 587 | |
| 588 | void clearTopDownPointers() { |
| 589 | PerPtrTopDown.clear(); |
| 590 | } |
| 591 | |
| 592 | void InitFromPred(const BBState &Other); |
| 593 | void InitFromSucc(const BBState &Other); |
| 594 | void MergePred(const BBState &Other); |
| 595 | void MergeSucc(const BBState &Other); |
| 596 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 597 | /// Return the number of possible unique paths from an entry to an exit |
| 598 | /// which pass through this block. This is only valid after both the |
| 599 | /// top-down and bottom-up traversals are complete. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 600 | unsigned GetAllPathCount() const { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 601 | assert(TopDownPathCount != 0); |
| 602 | assert(BottomUpPathCount != 0); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 603 | return TopDownPathCount * BottomUpPathCount; |
| 604 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 605 | |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 606 | // Specialized CFG utilities. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 607 | typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 608 | edge_iterator pred_begin() { return Preds.begin(); } |
| 609 | edge_iterator pred_end() { return Preds.end(); } |
| 610 | edge_iterator succ_begin() { return Succs.begin(); } |
| 611 | edge_iterator succ_end() { return Succs.end(); } |
| 612 | |
| 613 | void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); } |
| 614 | void addPred(BasicBlock *Pred) { Preds.push_back(Pred); } |
| 615 | |
| 616 | bool isExit() const { return Succs.empty(); } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 617 | }; |
| 618 | } |
| 619 | |
| 620 | void BBState::InitFromPred(const BBState &Other) { |
| 621 | PerPtrTopDown = Other.PerPtrTopDown; |
| 622 | TopDownPathCount = Other.TopDownPathCount; |
| 623 | } |
| 624 | |
| 625 | void BBState::InitFromSucc(const BBState &Other) { |
| 626 | PerPtrBottomUp = Other.PerPtrBottomUp; |
| 627 | BottomUpPathCount = Other.BottomUpPathCount; |
| 628 | } |
| 629 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 630 | /// The top-down traversal uses this to merge information about predecessors to |
| 631 | /// form the initial state for a new block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 632 | void BBState::MergePred(const BBState &Other) { |
| 633 | // Other.TopDownPathCount can be 0, in which case it is either dead or a |
| 634 | // loop backedge. Loop backedges are special. |
| 635 | TopDownPathCount += Other.TopDownPathCount; |
| 636 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 637 | // Check for overflow. If we have overflow, fall back to conservative |
| 638 | // behavior. |
Dan Gohman | 7c84dad | 2012-09-12 20:45:17 +0000 | [diff] [blame] | 639 | if (TopDownPathCount < Other.TopDownPathCount) { |
| 640 | clearTopDownPointers(); |
| 641 | return; |
| 642 | } |
| 643 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 644 | // For each entry in the other set, if our set has an entry with the same key, |
| 645 | // merge the entries. Otherwise, copy the entry and merge it with an empty |
| 646 | // entry. |
| 647 | for (ptr_const_iterator MI = Other.top_down_ptr_begin(), |
| 648 | ME = Other.top_down_ptr_end(); MI != ME; ++MI) { |
| 649 | std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI); |
| 650 | Pair.first->second.Merge(Pair.second ? PtrState() : MI->second, |
| 651 | /*TopDown=*/true); |
| 652 | } |
| 653 | |
Dan Gohman | 7e315fc3 | 2011-08-11 21:06:32 +0000 | [diff] [blame] | 654 | // For each entry in our set, if the other set doesn't have an entry with the |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 655 | // same key, force it to merge with an empty entry. |
| 656 | for (ptr_iterator MI = top_down_ptr_begin(), |
| 657 | ME = top_down_ptr_end(); MI != ME; ++MI) |
| 658 | if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end()) |
| 659 | MI->second.Merge(PtrState(), /*TopDown=*/true); |
| 660 | } |
| 661 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 662 | /// The bottom-up traversal uses this to merge information about successors to |
| 663 | /// form the initial state for a new block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 664 | void BBState::MergeSucc(const BBState &Other) { |
| 665 | // Other.BottomUpPathCount can be 0, in which case it is either dead or a |
| 666 | // loop backedge. Loop backedges are special. |
| 667 | BottomUpPathCount += Other.BottomUpPathCount; |
| 668 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 669 | // Check for overflow. If we have overflow, fall back to conservative |
| 670 | // behavior. |
Dan Gohman | 7c84dad | 2012-09-12 20:45:17 +0000 | [diff] [blame] | 671 | if (BottomUpPathCount < Other.BottomUpPathCount) { |
| 672 | clearBottomUpPointers(); |
| 673 | return; |
| 674 | } |
| 675 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 676 | // For each entry in the other set, if our set has an entry with the |
| 677 | // same key, merge the entries. Otherwise, copy the entry and merge |
| 678 | // it with an empty entry. |
| 679 | for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(), |
| 680 | ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) { |
| 681 | std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI); |
| 682 | Pair.first->second.Merge(Pair.second ? PtrState() : MI->second, |
| 683 | /*TopDown=*/false); |
| 684 | } |
| 685 | |
Dan Gohman | 7e315fc3 | 2011-08-11 21:06:32 +0000 | [diff] [blame] | 686 | // For each entry in our set, if the other set doesn't have an entry |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 687 | // with the same key, force it to merge with an empty entry. |
| 688 | for (ptr_iterator MI = bottom_up_ptr_begin(), |
| 689 | ME = bottom_up_ptr_end(); MI != ME; ++MI) |
| 690 | if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end()) |
| 691 | MI->second.Merge(PtrState(), /*TopDown=*/false); |
| 692 | } |
| 693 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 694 | // Only enable ARC Annotations if we are building a debug version of |
| 695 | // libObjCARCOpts. |
| 696 | #ifndef NDEBUG |
| 697 | #define ARC_ANNOTATIONS |
| 698 | #endif |
| 699 | |
| 700 | // Define some macros along the lines of DEBUG and some helper functions to make |
| 701 | // it cleaner to create annotations in the source code and to no-op when not |
| 702 | // building in debug mode. |
| 703 | #ifdef ARC_ANNOTATIONS |
| 704 | |
| 705 | #include "llvm/Support/CommandLine.h" |
| 706 | |
| 707 | /// Enable/disable ARC sequence annotations. |
| 708 | static cl::opt<bool> |
| 709 | EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false)); |
| 710 | |
| 711 | /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an |
| 712 | /// instruction so that we can track backwards when post processing via the llvm |
| 713 | /// arc annotation processor tool. If the function is an |
| 714 | static MDString *AppendMDNodeToSourcePtr(unsigned NodeId, |
| 715 | Value *Ptr) { |
| 716 | MDString *Hash = 0; |
| 717 | |
| 718 | // If pointer is a result of an instruction and it does not have a source |
| 719 | // MDNode it, attach a new MDNode onto it. If pointer is a result of |
| 720 | // an instruction and does have a source MDNode attached to it, return a |
| 721 | // reference to said Node. Otherwise just return 0. |
| 722 | if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) { |
| 723 | MDNode *Node; |
| 724 | if (!(Node = Inst->getMetadata(NodeId))) { |
| 725 | // We do not have any node. Generate and attatch the hash MDString to the |
| 726 | // instruction. |
| 727 | |
| 728 | // We just use an MDString to ensure that this metadata gets written out |
| 729 | // of line at the module level and to provide a very simple format |
| 730 | // encoding the information herein. Both of these makes it simpler to |
| 731 | // parse the annotations by a simple external program. |
| 732 | std::string Str; |
| 733 | raw_string_ostream os(Str); |
| 734 | os << "(" << Inst->getParent()->getParent()->getName() << ",%" |
| 735 | << Inst->getName() << ")"; |
| 736 | |
| 737 | Hash = MDString::get(Inst->getContext(), os.str()); |
| 738 | Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash)); |
| 739 | } else { |
| 740 | // We have a node. Grab its hash and return it. |
| 741 | assert(Node->getNumOperands() == 1 && |
| 742 | "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand."); |
| 743 | Hash = cast<MDString>(Node->getOperand(0)); |
| 744 | } |
| 745 | } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) { |
| 746 | std::string str; |
| 747 | raw_string_ostream os(str); |
| 748 | os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName() |
| 749 | << ")"; |
| 750 | Hash = MDString::get(Arg->getContext(), os.str()); |
| 751 | } |
| 752 | |
| 753 | return Hash; |
| 754 | } |
| 755 | |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 756 | static std::string SequenceToString(Sequence A) { |
| 757 | std::string str; |
| 758 | raw_string_ostream os(str); |
| 759 | os << A; |
| 760 | return os.str(); |
| 761 | } |
| 762 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 763 | /// Helper function to change a Sequence into a String object using our overload |
| 764 | /// for raw_ostream so we only have printing code in one location. |
| 765 | static MDString *SequenceToMDString(LLVMContext &Context, |
| 766 | Sequence A) { |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 767 | return MDString::get(Context, SequenceToString(A)); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 768 | } |
| 769 | |
| 770 | /// A simple function to generate a MDNode which describes the change in state |
| 771 | /// for Value *Ptr caused by Instruction *Inst. |
| 772 | static void AppendMDNodeToInstForPtr(unsigned NodeId, |
| 773 | Instruction *Inst, |
| 774 | Value *Ptr, |
| 775 | MDString *PtrSourceMDNodeID, |
| 776 | Sequence OldSeq, |
| 777 | Sequence NewSeq) { |
| 778 | MDNode *Node = 0; |
| 779 | Value *tmp[3] = {PtrSourceMDNodeID, |
| 780 | SequenceToMDString(Inst->getContext(), |
| 781 | OldSeq), |
| 782 | SequenceToMDString(Inst->getContext(), |
| 783 | NewSeq)}; |
| 784 | Node = MDNode::get(Inst->getContext(), |
| 785 | ArrayRef<Value*>(tmp, 3)); |
| 786 | |
| 787 | Inst->setMetadata(NodeId, Node); |
| 788 | } |
| 789 | |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 790 | /// Add to the beginning of the basic block llvm.ptr.annotations which show the |
| 791 | /// state of a pointer at the entrance to a basic block. |
| 792 | static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB, |
| 793 | Value *Ptr, Sequence Seq) { |
| 794 | Module *M = BB->getParent()->getParent(); |
| 795 | LLVMContext &C = M->getContext(); |
| 796 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
| 797 | Type *I8XX = PointerType::getUnqual(I8X); |
| 798 | Type *Params[] = {I8XX, I8XX}; |
| 799 | FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), |
| 800 | ArrayRef<Type*>(Params, 2), |
| 801 | /*isVarArg=*/false); |
| 802 | Constant *Callee = M->getOrInsertFunction(Name, FTy); |
| 803 | |
| 804 | IRBuilder<> Builder(BB, BB->getFirstInsertionPt()); |
| 805 | |
| 806 | Value *PtrName; |
| 807 | StringRef Tmp = Ptr->getName(); |
| 808 | if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) { |
| 809 | Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp, |
| 810 | Tmp + "_STR"); |
| 811 | PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage, |
| 812 | cast<Constant>(ActualPtrName), Tmp); |
| 813 | } |
| 814 | |
| 815 | Value *S; |
| 816 | std::string SeqStr = SequenceToString(Seq); |
| 817 | if (0 == (S = M->getGlobalVariable(SeqStr, true))) { |
| 818 | Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr, |
| 819 | SeqStr + "_STR"); |
| 820 | S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage, |
| 821 | cast<Constant>(ActualPtrName), SeqStr); |
| 822 | } |
| 823 | |
| 824 | Builder.CreateCall2(Callee, PtrName, S); |
| 825 | } |
| 826 | |
| 827 | /// Add to the end of the basic block llvm.ptr.annotations which show the state |
| 828 | /// of the pointer at the bottom of the basic block. |
| 829 | static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB, |
| 830 | Value *Ptr, Sequence Seq) { |
| 831 | Module *M = BB->getParent()->getParent(); |
| 832 | LLVMContext &C = M->getContext(); |
| 833 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
| 834 | Type *I8XX = PointerType::getUnqual(I8X); |
| 835 | Type *Params[] = {I8XX, I8XX}; |
| 836 | FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), |
| 837 | ArrayRef<Type*>(Params, 2), |
| 838 | /*isVarArg=*/false); |
| 839 | Constant *Callee = M->getOrInsertFunction(Name, FTy); |
| 840 | |
| 841 | IRBuilder<> Builder(BB, llvm::prior(BB->end())); |
| 842 | |
| 843 | Value *PtrName; |
| 844 | StringRef Tmp = Ptr->getName(); |
| 845 | if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) { |
| 846 | Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp, |
| 847 | Tmp + "_STR"); |
| 848 | PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage, |
| 849 | cast<Constant>(ActualPtrName), Tmp); |
| 850 | } |
| 851 | |
| 852 | Value *S; |
| 853 | std::string SeqStr = SequenceToString(Seq); |
| 854 | if (0 == (S = M->getGlobalVariable(SeqStr, true))) { |
| 855 | Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr, |
| 856 | SeqStr + "_STR"); |
| 857 | S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage, |
| 858 | cast<Constant>(ActualPtrName), SeqStr); |
| 859 | } |
| 860 | Builder.CreateCall2(Callee, PtrName, S); |
| 861 | } |
| 862 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 863 | /// Adds a source annotation to pointer and a state change annotation to Inst |
| 864 | /// referencing the source annotation and the old/new state of pointer. |
| 865 | static void GenerateARCAnnotation(unsigned InstMDId, |
| 866 | unsigned PtrMDId, |
| 867 | Instruction *Inst, |
| 868 | Value *Ptr, |
| 869 | Sequence OldSeq, |
| 870 | Sequence NewSeq) { |
| 871 | if (EnableARCAnnotations) { |
| 872 | // First generate the source annotation on our pointer. This will return an |
| 873 | // MDString* if Ptr actually comes from an instruction implying we can put |
| 874 | // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL), |
| 875 | // then we know that our pointer is from an Argument so we put a reference |
| 876 | // to the argument number. |
| 877 | // |
| 878 | // The point of this is to make it easy for the |
| 879 | // llvm-arc-annotation-processor tool to cross reference where the source |
| 880 | // pointer is in the LLVM IR since the LLVM IR parser does not submit such |
| 881 | // information via debug info for backends to use (since why would anyone |
| 882 | // need such a thing from LLVM IR besides in non standard cases |
| 883 | // [i.e. this]). |
| 884 | MDString *SourcePtrMDNode = |
| 885 | AppendMDNodeToSourcePtr(PtrMDId, Ptr); |
| 886 | AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq, |
| 887 | NewSeq); |
| 888 | } |
| 889 | } |
| 890 | |
| 891 | // The actual interface for accessing the above functionality is defined via |
| 892 | // some simple macros which are defined below. We do this so that the user does |
| 893 | // not need to pass in what metadata id is needed resulting in cleaner code and |
| 894 | // additionally since it provides an easy way to conditionally no-op all |
| 895 | // annotation support in a non-debug build. |
| 896 | |
| 897 | /// Use this macro to annotate a sequence state change when processing |
| 898 | /// instructions bottom up, |
| 899 | #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \ |
| 900 | GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \ |
| 901 | ARCAnnotationProvenanceSourceMDKind, (inst), \ |
| 902 | const_cast<Value*>(ptr), (old), (new)) |
| 903 | /// Use this macro to annotate a sequence state change when processing |
| 904 | /// instructions top down. |
| 905 | #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \ |
| 906 | GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \ |
| 907 | ARCAnnotationProvenanceSourceMDKind, (inst), \ |
| 908 | const_cast<Value*>(ptr), (old), (new)) |
| 909 | |
| 910 | #else // !ARC_ANNOTATION |
| 911 | // If annotations are off, noop. |
| 912 | #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) |
| 913 | #define ANNOTATE_TOPDOWN(inst, ptr, old, new) |
| 914 | #endif // !ARC_ANNOTATION |
| 915 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 916 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 917 | /// \brief The main ARC optimization pass. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 918 | class ObjCARCOpt : public FunctionPass { |
| 919 | bool Changed; |
| 920 | ProvenanceAnalysis PA; |
| 921 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 922 | /// A flag indicating whether this optimization pass should run. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 923 | bool Run; |
| 924 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 925 | /// Declarations for ObjC runtime functions, for use in creating calls to |
| 926 | /// them. These are initialized lazily to avoid cluttering up the Module |
| 927 | /// with unused declarations. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 928 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 929 | /// Declaration for ObjC runtime function |
| 930 | /// objc_retainAutoreleasedReturnValue. |
| 931 | Constant *RetainRVCallee; |
| 932 | /// Declaration for ObjC runtime function objc_autoreleaseReturnValue. |
| 933 | Constant *AutoreleaseRVCallee; |
| 934 | /// Declaration for ObjC runtime function objc_release. |
| 935 | Constant *ReleaseCallee; |
| 936 | /// Declaration for ObjC runtime function objc_retain. |
| 937 | Constant *RetainCallee; |
| 938 | /// Declaration for ObjC runtime function objc_retainBlock. |
| 939 | Constant *RetainBlockCallee; |
| 940 | /// Declaration for ObjC runtime function objc_autorelease. |
| 941 | Constant *AutoreleaseCallee; |
| 942 | |
| 943 | /// Flags which determine whether each of the interesting runtine functions |
| 944 | /// is in fact used in the current function. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 945 | unsigned UsedInThisFunction; |
| 946 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 947 | /// The Metadata Kind for clang.imprecise_release metadata. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 948 | unsigned ImpreciseReleaseMDKind; |
| 949 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 950 | /// The Metadata Kind for clang.arc.copy_on_escape metadata. |
Dan Gohman | a7107f9 | 2011-10-17 22:53:25 +0000 | [diff] [blame] | 951 | unsigned CopyOnEscapeMDKind; |
| 952 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 953 | /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata. |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 954 | unsigned NoObjCARCExceptionsMDKind; |
| 955 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 956 | #ifdef ARC_ANNOTATIONS |
| 957 | /// The Metadata Kind for llvm.arc.annotation.bottomup metadata. |
| 958 | unsigned ARCAnnotationBottomUpMDKind; |
| 959 | /// The Metadata Kind for llvm.arc.annotation.topdown metadata. |
| 960 | unsigned ARCAnnotationTopDownMDKind; |
| 961 | /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata. |
| 962 | unsigned ARCAnnotationProvenanceSourceMDKind; |
| 963 | #endif // ARC_ANNOATIONS |
| 964 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 965 | Constant *getRetainRVCallee(Module *M); |
| 966 | Constant *getAutoreleaseRVCallee(Module *M); |
| 967 | Constant *getReleaseCallee(Module *M); |
| 968 | Constant *getRetainCallee(Module *M); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 969 | Constant *getRetainBlockCallee(Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 970 | Constant *getAutoreleaseCallee(Module *M); |
| 971 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 972 | bool IsRetainBlockOptimizable(const Instruction *Inst); |
| 973 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 974 | void OptimizeRetainCall(Function &F, Instruction *Retain); |
| 975 | bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV); |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 976 | void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV, |
| 977 | InstructionClass &Class); |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 978 | bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock, |
| 979 | InstructionClass &Class); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 980 | void OptimizeIndividualCalls(Function &F); |
| 981 | |
| 982 | void CheckForCFGHazards(const BasicBlock *BB, |
| 983 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 984 | BBState &MyStates) const; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 985 | bool VisitInstructionBottomUp(Instruction *Inst, |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 986 | BasicBlock *BB, |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 987 | MapVector<Value *, RRInfo> &Retains, |
| 988 | BBState &MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 989 | bool VisitBottomUp(BasicBlock *BB, |
| 990 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 991 | MapVector<Value *, RRInfo> &Retains); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 992 | bool VisitInstructionTopDown(Instruction *Inst, |
| 993 | DenseMap<Value *, RRInfo> &Releases, |
| 994 | BBState &MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 995 | bool VisitTopDown(BasicBlock *BB, |
| 996 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 997 | DenseMap<Value *, RRInfo> &Releases); |
| 998 | bool Visit(Function &F, |
| 999 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1000 | MapVector<Value *, RRInfo> &Retains, |
| 1001 | DenseMap<Value *, RRInfo> &Releases); |
| 1002 | |
| 1003 | void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove, |
| 1004 | MapVector<Value *, RRInfo> &Retains, |
| 1005 | DenseMap<Value *, RRInfo> &Releases, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1006 | SmallVectorImpl<Instruction *> &DeadInsts, |
| 1007 | Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1008 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 1009 | bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1010 | MapVector<Value *, RRInfo> &Retains, |
| 1011 | DenseMap<Value *, RRInfo> &Releases, |
| 1012 | Module *M, |
| 1013 | SmallVector<Instruction *, 4> &NewRetains, |
| 1014 | SmallVector<Instruction *, 4> &NewReleases, |
| 1015 | SmallVector<Instruction *, 8> &DeadInsts, |
| 1016 | RRInfo &RetainsToMove, |
| 1017 | RRInfo &ReleasesToMove, |
| 1018 | Value *Arg, |
| 1019 | bool KnownSafe, |
| 1020 | bool &AnyPairsCompletelyEliminated); |
| 1021 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1022 | bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1023 | MapVector<Value *, RRInfo> &Retains, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1024 | DenseMap<Value *, RRInfo> &Releases, |
| 1025 | Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1026 | |
| 1027 | void OptimizeWeakCalls(Function &F); |
| 1028 | |
| 1029 | bool OptimizeSequences(Function &F); |
| 1030 | |
| 1031 | void OptimizeReturns(Function &F); |
| 1032 | |
| 1033 | virtual void getAnalysisUsage(AnalysisUsage &AU) const; |
| 1034 | virtual bool doInitialization(Module &M); |
| 1035 | virtual bool runOnFunction(Function &F); |
| 1036 | virtual void releaseMemory(); |
| 1037 | |
| 1038 | public: |
| 1039 | static char ID; |
| 1040 | ObjCARCOpt() : FunctionPass(ID) { |
| 1041 | initializeObjCARCOptPass(*PassRegistry::getPassRegistry()); |
| 1042 | } |
| 1043 | }; |
| 1044 | } |
| 1045 | |
| 1046 | char ObjCARCOpt::ID = 0; |
| 1047 | INITIALIZE_PASS_BEGIN(ObjCARCOpt, |
| 1048 | "objc-arc", "ObjC ARC optimization", false, false) |
| 1049 | INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis) |
| 1050 | INITIALIZE_PASS_END(ObjCARCOpt, |
| 1051 | "objc-arc", "ObjC ARC optimization", false, false) |
| 1052 | |
| 1053 | Pass *llvm::createObjCARCOptPass() { |
| 1054 | return new ObjCARCOpt(); |
| 1055 | } |
| 1056 | |
| 1057 | void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const { |
| 1058 | AU.addRequired<ObjCARCAliasAnalysis>(); |
| 1059 | AU.addRequired<AliasAnalysis>(); |
| 1060 | // ARC optimization doesn't currently split critical edges. |
| 1061 | AU.setPreservesCFG(); |
| 1062 | } |
| 1063 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 1064 | bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) { |
| 1065 | // Without the magic metadata tag, we have to assume this might be an |
| 1066 | // objc_retainBlock call inserted to convert a block pointer to an id, |
| 1067 | // in which case it really is needed. |
| 1068 | if (!Inst->getMetadata(CopyOnEscapeMDKind)) |
| 1069 | return false; |
| 1070 | |
| 1071 | // If the pointer "escapes" (not including being used in a call), |
| 1072 | // the copy may be needed. |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 1073 | if (DoesRetainableObjPtrEscape(Inst)) |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 1074 | return false; |
| 1075 | |
| 1076 | // Otherwise, it's not needed. |
| 1077 | return true; |
| 1078 | } |
| 1079 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1080 | Constant *ObjCARCOpt::getRetainRVCallee(Module *M) { |
| 1081 | if (!RetainRVCallee) { |
| 1082 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 1083 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1084 | Type *Params[] = { I8X }; |
| 1085 | FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false); |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1086 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1087 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1088 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1089 | RetainRVCallee = |
| 1090 | M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy, |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1091 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1092 | } |
| 1093 | return RetainRVCallee; |
| 1094 | } |
| 1095 | |
| 1096 | Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) { |
| 1097 | if (!AutoreleaseRVCallee) { |
| 1098 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 1099 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1100 | Type *Params[] = { I8X }; |
| 1101 | FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false); |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1102 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1103 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1104 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1105 | AutoreleaseRVCallee = |
| 1106 | M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy, |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1107 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1108 | } |
| 1109 | return AutoreleaseRVCallee; |
| 1110 | } |
| 1111 | |
| 1112 | Constant *ObjCARCOpt::getReleaseCallee(Module *M) { |
| 1113 | if (!ReleaseCallee) { |
| 1114 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1115 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1116 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1117 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1118 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1119 | ReleaseCallee = |
| 1120 | M->getOrInsertFunction( |
| 1121 | "objc_release", |
| 1122 | FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1123 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1124 | } |
| 1125 | return ReleaseCallee; |
| 1126 | } |
| 1127 | |
| 1128 | Constant *ObjCARCOpt::getRetainCallee(Module *M) { |
| 1129 | if (!RetainCallee) { |
| 1130 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1131 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1132 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1133 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1134 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1135 | RetainCallee = |
| 1136 | M->getOrInsertFunction( |
| 1137 | "objc_retain", |
| 1138 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1139 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1140 | } |
| 1141 | return RetainCallee; |
| 1142 | } |
| 1143 | |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1144 | Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) { |
| 1145 | if (!RetainBlockCallee) { |
| 1146 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1147 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Dan Gohman | fca43c2 | 2011-09-14 18:33:34 +0000 | [diff] [blame] | 1148 | // objc_retainBlock is not nounwind because it calls user copy constructors |
| 1149 | // which could theoretically throw. |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1150 | RetainBlockCallee = |
| 1151 | M->getOrInsertFunction( |
| 1152 | "objc_retainBlock", |
| 1153 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | e94d843 | 2012-12-07 23:16:57 +0000 | [diff] [blame] | 1154 | AttributeSet()); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1155 | } |
| 1156 | return RetainBlockCallee; |
| 1157 | } |
| 1158 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1159 | Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) { |
| 1160 | if (!AutoreleaseCallee) { |
| 1161 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1162 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1163 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1164 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1165 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1166 | AutoreleaseCallee = |
| 1167 | M->getOrInsertFunction( |
| 1168 | "objc_autorelease", |
| 1169 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1170 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1171 | } |
| 1172 | return AutoreleaseCallee; |
| 1173 | } |
| 1174 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1175 | /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a |
| 1176 | /// return value. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1177 | void |
| 1178 | ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1179 | ImmutableCallSite CS(GetObjCArg(Retain)); |
| 1180 | const Instruction *Call = CS.getInstruction(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1181 | if (!Call) return; |
| 1182 | if (Call->getParent() != Retain->getParent()) return; |
| 1183 | |
| 1184 | // Check that the call is next to the retain. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1185 | BasicBlock::const_iterator I = Call; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1186 | ++I; |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1187 | while (IsNoopInstruction(I)) ++I; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1188 | if (&*I != Retain) |
| 1189 | return; |
| 1190 | |
| 1191 | // Turn it to an objc_retainAutoreleasedReturnValue.. |
| 1192 | Changed = true; |
| 1193 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1194 | |
Michael Gottesman | 1e00ac6 | 2013-01-04 21:30:38 +0000 | [diff] [blame] | 1195 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming " |
Michael Gottesman | 9f1be68 | 2013-01-12 03:45:49 +0000 | [diff] [blame] | 1196 | "objc_retain => objc_retainAutoreleasedReturnValue" |
| 1197 | " since the operand is a return value.\n" |
Michael Gottesman | 1e00ac6 | 2013-01-04 21:30:38 +0000 | [diff] [blame] | 1198 | " Old: " |
| 1199 | << *Retain << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1200 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1201 | cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent())); |
Michael Gottesman | 1e00ac6 | 2013-01-04 21:30:38 +0000 | [diff] [blame] | 1202 | |
| 1203 | DEBUG(dbgs() << " New: " |
| 1204 | << *Retain << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1205 | } |
| 1206 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1207 | /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is |
| 1208 | /// not a return value. Or, if it can be paired with an |
| 1209 | /// objc_autoreleaseReturnValue, delete the pair and return true. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1210 | bool |
| 1211 | ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) { |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1212 | // Check for the argument being from an immediately preceding call or invoke. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1213 | const Value *Arg = GetObjCArg(RetainRV); |
| 1214 | ImmutableCallSite CS(Arg); |
| 1215 | if (const Instruction *Call = CS.getInstruction()) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1216 | if (Call->getParent() == RetainRV->getParent()) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1217 | BasicBlock::const_iterator I = Call; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1218 | ++I; |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1219 | while (IsNoopInstruction(I)) ++I; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1220 | if (&*I == RetainRV) |
| 1221 | return false; |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1222 | } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) { |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1223 | BasicBlock *RetainRVParent = RetainRV->getParent(); |
| 1224 | if (II->getNormalDest() == RetainRVParent) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1225 | BasicBlock::const_iterator I = RetainRVParent->begin(); |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1226 | while (IsNoopInstruction(I)) ++I; |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1227 | if (&*I == RetainRV) |
| 1228 | return false; |
| 1229 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1230 | } |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1231 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1232 | |
| 1233 | // Check for being preceded by an objc_autoreleaseReturnValue on the same |
| 1234 | // pointer. In this case, we can delete the pair. |
| 1235 | BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin(); |
| 1236 | if (I != Begin) { |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1237 | do --I; while (I != Begin && IsNoopInstruction(I)); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1238 | if (GetBasicInstructionClass(I) == IC_AutoreleaseRV && |
| 1239 | GetObjCArg(I) == Arg) { |
| 1240 | Changed = true; |
| 1241 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1242 | |
Michael Gottesman | 5c32ce9 | 2013-01-05 17:55:35 +0000 | [diff] [blame] | 1243 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n" |
| 1244 | << " Erasing " << *RetainRV |
| 1245 | << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1246 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1247 | EraseInstruction(I); |
| 1248 | EraseInstruction(RetainRV); |
| 1249 | return true; |
| 1250 | } |
| 1251 | } |
| 1252 | |
| 1253 | // Turn it to a plain objc_retain. |
| 1254 | Changed = true; |
| 1255 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1256 | |
Michael Gottesman | def07bb | 2013-01-05 17:55:42 +0000 | [diff] [blame] | 1257 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming " |
| 1258 | "objc_retainAutoreleasedReturnValue => " |
| 1259 | "objc_retain since the operand is not a return value.\n" |
| 1260 | " Old: " |
| 1261 | << *RetainRV << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1262 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1263 | cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent())); |
Michael Gottesman | def07bb | 2013-01-05 17:55:42 +0000 | [diff] [blame] | 1264 | |
| 1265 | DEBUG(dbgs() << " New: " |
| 1266 | << *RetainRV << "\n"); |
| 1267 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1268 | return false; |
| 1269 | } |
| 1270 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1271 | /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not |
| 1272 | /// used as a return value. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1273 | void |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1274 | ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV, |
| 1275 | InstructionClass &Class) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1276 | // Check for a return of the pointer value. |
| 1277 | const Value *Ptr = GetObjCArg(AutoreleaseRV); |
Dan Gohman | 10a18d5 | 2011-08-12 00:36:31 +0000 | [diff] [blame] | 1278 | SmallVector<const Value *, 2> Users; |
| 1279 | Users.push_back(Ptr); |
| 1280 | do { |
| 1281 | Ptr = Users.pop_back_val(); |
| 1282 | for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end(); |
| 1283 | UI != UE; ++UI) { |
| 1284 | const User *I = *UI; |
| 1285 | if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV) |
| 1286 | return; |
| 1287 | if (isa<BitCastInst>(I)) |
| 1288 | Users.push_back(I); |
| 1289 | } |
| 1290 | } while (!Users.empty()); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1291 | |
| 1292 | Changed = true; |
| 1293 | ++NumPeeps; |
Michael Gottesman | 1bf6908 | 2013-01-06 21:07:11 +0000 | [diff] [blame] | 1294 | |
| 1295 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming " |
| 1296 | "objc_autoreleaseReturnValue => " |
| 1297 | "objc_autorelease since its operand is not used as a return " |
| 1298 | "value.\n" |
| 1299 | " Old: " |
| 1300 | << *AutoreleaseRV << "\n"); |
| 1301 | |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1302 | CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV); |
| 1303 | AutoreleaseRVCI-> |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1304 | setCalledFunction(getAutoreleaseCallee(F.getParent())); |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1305 | AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease. |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1306 | Class = IC_Autorelease; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1307 | |
Michael Gottesman | 1bf6908 | 2013-01-06 21:07:11 +0000 | [diff] [blame] | 1308 | DEBUG(dbgs() << " New: " |
| 1309 | << *AutoreleaseRV << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1310 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1311 | } |
| 1312 | |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1313 | // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain |
| 1314 | // calls. |
| 1315 | // |
| 1316 | // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and |
| 1317 | // does not escape (following the rules of block escaping), strength reduce the |
| 1318 | // objc_retainBlock to an objc_retain. |
| 1319 | // |
| 1320 | // TODO: If an objc_retainBlock call is dominated period by a previous |
| 1321 | // objc_retainBlock call, strength reduce the objc_retainBlock to an |
| 1322 | // objc_retain. |
| 1323 | bool |
| 1324 | ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst, |
| 1325 | InstructionClass &Class) { |
| 1326 | assert(GetBasicInstructionClass(Inst) == Class); |
| 1327 | assert(IC_RetainBlock == Class); |
| 1328 | |
| 1329 | // If we can not optimize Inst, return false. |
| 1330 | if (!IsRetainBlockOptimizable(Inst)) |
| 1331 | return false; |
| 1332 | |
| 1333 | CallInst *RetainBlock = cast<CallInst>(Inst); |
| 1334 | RetainBlock->setCalledFunction(getRetainCallee(F.getParent())); |
| 1335 | // Remove copy_on_escape metadata. |
| 1336 | RetainBlock->setMetadata(CopyOnEscapeMDKind, 0); |
| 1337 | Class = IC_Retain; |
| 1338 | |
| 1339 | return true; |
| 1340 | } |
| 1341 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1342 | /// Visit each call, one at a time, and make simplifications without doing any |
| 1343 | /// additional analysis. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1344 | void ObjCARCOpt::OptimizeIndividualCalls(Function &F) { |
| 1345 | // Reset all the flags in preparation for recomputing them. |
| 1346 | UsedInThisFunction = 0; |
| 1347 | |
| 1348 | // Visit all objc_* calls in F. |
| 1349 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 1350 | Instruction *Inst = &*I++; |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 1351 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1352 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 1353 | |
Michael Gottesman | d359e06 | 2013-01-18 03:08:39 +0000 | [diff] [blame] | 1354 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: " |
| 1355 | << Class << "; " << *Inst << "\n"); |
Michael Gottesman | 782e344 | 2013-01-17 18:32:34 +0000 | [diff] [blame] | 1356 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1357 | switch (Class) { |
| 1358 | default: break; |
| 1359 | |
| 1360 | // Delete no-op casts. These function calls have special semantics, but |
| 1361 | // the semantics are entirely implemented via lowering in the front-end, |
| 1362 | // so by the time they reach the optimizer, they are just no-op calls |
| 1363 | // which return their argument. |
| 1364 | // |
| 1365 | // There are gray areas here, as the ability to cast reference-counted |
| 1366 | // pointers to raw void* and back allows code to break ARC assumptions, |
| 1367 | // however these are currently considered to be unimportant. |
| 1368 | case IC_NoopCast: |
| 1369 | Changed = true; |
| 1370 | ++NumNoops; |
Michael Gottesman | dc042f0 | 2013-01-06 21:07:15 +0000 | [diff] [blame] | 1371 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:" |
| 1372 | " " << *Inst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1373 | EraseInstruction(Inst); |
| 1374 | continue; |
| 1375 | |
| 1376 | // If the pointer-to-weak-pointer is null, it's undefined behavior. |
| 1377 | case IC_StoreWeak: |
| 1378 | case IC_LoadWeak: |
| 1379 | case IC_LoadWeakRetained: |
| 1380 | case IC_InitWeak: |
| 1381 | case IC_DestroyWeak: { |
| 1382 | CallInst *CI = cast<CallInst>(Inst); |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1383 | if (IsNullOrUndef(CI->getArgOperand(0))) { |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 1384 | Changed = true; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1385 | Type *Ty = CI->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1386 | new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), |
| 1387 | Constant::getNullValue(Ty), |
| 1388 | CI); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1389 | llvm::Value *NewValue = UndefValue::get(CI->getType()); |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 1390 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null " |
| 1391 | "pointer-to-weak-pointer is undefined behavior.\n" |
| 1392 | " Old = " << *CI << |
| 1393 | "\n New = " << |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1394 | *NewValue << "\n"); |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 1395 | CI->replaceAllUsesWith(NewValue); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1396 | CI->eraseFromParent(); |
| 1397 | continue; |
| 1398 | } |
| 1399 | break; |
| 1400 | } |
| 1401 | case IC_CopyWeak: |
| 1402 | case IC_MoveWeak: { |
| 1403 | CallInst *CI = cast<CallInst>(Inst); |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1404 | if (IsNullOrUndef(CI->getArgOperand(0)) || |
| 1405 | IsNullOrUndef(CI->getArgOperand(1))) { |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 1406 | Changed = true; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1407 | Type *Ty = CI->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1408 | new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), |
| 1409 | Constant::getNullValue(Ty), |
| 1410 | CI); |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 1411 | |
| 1412 | llvm::Value *NewValue = UndefValue::get(CI->getType()); |
| 1413 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null " |
| 1414 | "pointer-to-weak-pointer is undefined behavior.\n" |
| 1415 | " Old = " << *CI << |
| 1416 | "\n New = " << |
| 1417 | *NewValue << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1418 | |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 1419 | CI->replaceAllUsesWith(NewValue); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1420 | CI->eraseFromParent(); |
| 1421 | continue; |
| 1422 | } |
| 1423 | break; |
| 1424 | } |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1425 | case IC_RetainBlock: |
| 1426 | // If we strength reduce an objc_retainBlock to amn objc_retain, continue |
| 1427 | // onto the objc_retain peephole optimizations. Otherwise break. |
| 1428 | if (!OptimizeRetainBlockCall(F, Inst, Class)) |
| 1429 | break; |
| 1430 | // FALLTHROUGH |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1431 | case IC_Retain: |
| 1432 | OptimizeRetainCall(F, Inst); |
| 1433 | break; |
| 1434 | case IC_RetainRV: |
| 1435 | if (OptimizeRetainRVCall(F, Inst)) |
| 1436 | continue; |
| 1437 | break; |
| 1438 | case IC_AutoreleaseRV: |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1439 | OptimizeAutoreleaseRVCall(F, Inst, Class); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1440 | break; |
| 1441 | } |
| 1442 | |
| 1443 | // objc_autorelease(x) -> objc_release(x) if x is otherwise unused. |
| 1444 | if (IsAutorelease(Class) && Inst->use_empty()) { |
| 1445 | CallInst *Call = cast<CallInst>(Inst); |
| 1446 | const Value *Arg = Call->getArgOperand(0); |
| 1447 | Arg = FindSingleUseIdentifiedObject(Arg); |
| 1448 | if (Arg) { |
| 1449 | Changed = true; |
| 1450 | ++NumAutoreleases; |
| 1451 | |
| 1452 | // Create the declaration lazily. |
| 1453 | LLVMContext &C = Inst->getContext(); |
| 1454 | CallInst *NewCall = |
| 1455 | CallInst::Create(getReleaseCallee(F.getParent()), |
| 1456 | Call->getArgOperand(0), "", Call); |
| 1457 | NewCall->setMetadata(ImpreciseReleaseMDKind, |
| 1458 | MDNode::get(C, ArrayRef<Value *>())); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1459 | |
Michael Gottesman | a6a1dad | 2013-01-06 22:56:50 +0000 | [diff] [blame] | 1460 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing " |
| 1461 | "objc_autorelease(x) with objc_release(x) since x is " |
| 1462 | "otherwise unused.\n" |
Michael Gottesman | 4bf6e75 | 2013-01-06 22:56:54 +0000 | [diff] [blame] | 1463 | " Old: " << *Call << |
Michael Gottesman | a6a1dad | 2013-01-06 22:56:50 +0000 | [diff] [blame] | 1464 | "\n New: " << |
| 1465 | *NewCall << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1466 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1467 | EraseInstruction(Call); |
| 1468 | Inst = NewCall; |
| 1469 | Class = IC_Release; |
| 1470 | } |
| 1471 | } |
| 1472 | |
| 1473 | // For functions which can never be passed stack arguments, add |
| 1474 | // a tail keyword. |
| 1475 | if (IsAlwaysTail(Class)) { |
| 1476 | Changed = true; |
Michael Gottesman | 2d76331 | 2013-01-06 23:39:09 +0000 | [diff] [blame] | 1477 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword" |
| 1478 | " to function since it can never be passed stack args: " << *Inst << |
| 1479 | "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1480 | cast<CallInst>(Inst)->setTailCall(); |
| 1481 | } |
| 1482 | |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1483 | // Ensure that functions that can never have a "tail" keyword due to the |
| 1484 | // semantics of ARC truly do not do so. |
| 1485 | if (IsNeverTail(Class)) { |
| 1486 | Changed = true; |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 1487 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail " |
| 1488 | "keyword from function: " << *Inst << |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1489 | "\n"); |
| 1490 | cast<CallInst>(Inst)->setTailCall(false); |
| 1491 | } |
| 1492 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1493 | // Set nounwind as needed. |
| 1494 | if (IsNoThrow(Class)) { |
| 1495 | Changed = true; |
Michael Gottesman | 8800a51 | 2013-01-06 23:39:13 +0000 | [diff] [blame] | 1496 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw" |
| 1497 | " class. Setting nounwind on: " << *Inst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1498 | cast<CallInst>(Inst)->setDoesNotThrow(); |
| 1499 | } |
| 1500 | |
| 1501 | if (!IsNoopOnNull(Class)) { |
| 1502 | UsedInThisFunction |= 1 << Class; |
| 1503 | continue; |
| 1504 | } |
| 1505 | |
| 1506 | const Value *Arg = GetObjCArg(Inst); |
| 1507 | |
| 1508 | // ARC calls with null are no-ops. Delete them. |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1509 | if (IsNullOrUndef(Arg)) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1510 | Changed = true; |
| 1511 | ++NumNoops; |
Michael Gottesman | 5b970e1 | 2013-01-07 00:04:52 +0000 | [diff] [blame] | 1512 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with " |
| 1513 | " null are no-ops. Erasing: " << *Inst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1514 | EraseInstruction(Inst); |
| 1515 | continue; |
| 1516 | } |
| 1517 | |
| 1518 | // Keep track of which of retain, release, autorelease, and retain_block |
| 1519 | // are actually present in this function. |
| 1520 | UsedInThisFunction |= 1 << Class; |
| 1521 | |
| 1522 | // If Arg is a PHI, and one or more incoming values to the |
| 1523 | // PHI are null, and the call is control-equivalent to the PHI, and there |
| 1524 | // are no relevant side effects between the PHI and the call, the call |
| 1525 | // could be pushed up to just those paths with non-null incoming values. |
| 1526 | // For now, don't bother splitting critical edges for this. |
| 1527 | SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist; |
| 1528 | Worklist.push_back(std::make_pair(Inst, Arg)); |
| 1529 | do { |
| 1530 | std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val(); |
| 1531 | Inst = Pair.first; |
| 1532 | Arg = Pair.second; |
| 1533 | |
| 1534 | const PHINode *PN = dyn_cast<PHINode>(Arg); |
| 1535 | if (!PN) continue; |
| 1536 | |
| 1537 | // Determine if the PHI has any null operands, or any incoming |
| 1538 | // critical edges. |
| 1539 | bool HasNull = false; |
| 1540 | bool HasCriticalEdges = false; |
| 1541 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 1542 | Value *Incoming = |
| 1543 | StripPointerCastsAndObjCCalls(PN->getIncomingValue(i)); |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1544 | if (IsNullOrUndef(Incoming)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1545 | HasNull = true; |
| 1546 | else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back()) |
| 1547 | .getNumSuccessors() != 1) { |
| 1548 | HasCriticalEdges = true; |
| 1549 | break; |
| 1550 | } |
| 1551 | } |
| 1552 | // If we have null operands and no critical edges, optimize. |
| 1553 | if (!HasCriticalEdges && HasNull) { |
| 1554 | SmallPtrSet<Instruction *, 4> DependingInstructions; |
| 1555 | SmallPtrSet<const BasicBlock *, 4> Visited; |
| 1556 | |
| 1557 | // Check that there is nothing that cares about the reference |
| 1558 | // count between the call and the phi. |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 1559 | switch (Class) { |
| 1560 | case IC_Retain: |
| 1561 | case IC_RetainBlock: |
| 1562 | // These can always be moved up. |
| 1563 | break; |
| 1564 | case IC_Release: |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1565 | // These can't be moved across things that care about the retain |
| 1566 | // count. |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 1567 | FindDependencies(NeedsPositiveRetainCount, Arg, |
| 1568 | Inst->getParent(), Inst, |
| 1569 | DependingInstructions, Visited, PA); |
| 1570 | break; |
| 1571 | case IC_Autorelease: |
| 1572 | // These can't be moved across autorelease pool scope boundaries. |
| 1573 | FindDependencies(AutoreleasePoolBoundary, Arg, |
| 1574 | Inst->getParent(), Inst, |
| 1575 | DependingInstructions, Visited, PA); |
| 1576 | break; |
| 1577 | case IC_RetainRV: |
| 1578 | case IC_AutoreleaseRV: |
| 1579 | // Don't move these; the RV optimization depends on the autoreleaseRV |
| 1580 | // being tail called, and the retainRV being immediately after a call |
| 1581 | // (which might still happen if we get lucky with codegen layout, but |
| 1582 | // it's not worth taking the chance). |
| 1583 | continue; |
| 1584 | default: |
| 1585 | llvm_unreachable("Invalid dependence flavor"); |
| 1586 | } |
| 1587 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1588 | if (DependingInstructions.size() == 1 && |
| 1589 | *DependingInstructions.begin() == PN) { |
| 1590 | Changed = true; |
| 1591 | ++NumPartialNoops; |
| 1592 | // Clone the call into each predecessor that has a non-null value. |
| 1593 | CallInst *CInst = cast<CallInst>(Inst); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1594 | Type *ParamTy = CInst->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1595 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 1596 | Value *Incoming = |
| 1597 | StripPointerCastsAndObjCCalls(PN->getIncomingValue(i)); |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1598 | if (!IsNullOrUndef(Incoming)) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1599 | CallInst *Clone = cast<CallInst>(CInst->clone()); |
| 1600 | Value *Op = PN->getIncomingValue(i); |
| 1601 | Instruction *InsertPos = &PN->getIncomingBlock(i)->back(); |
| 1602 | if (Op->getType() != ParamTy) |
| 1603 | Op = new BitCastInst(Op, ParamTy, "", InsertPos); |
| 1604 | Clone->setArgOperand(0, Op); |
| 1605 | Clone->insertBefore(InsertPos); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 1606 | |
| 1607 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning " |
| 1608 | << *CInst << "\n" |
| 1609 | " And inserting " |
| 1610 | "clone at " << *InsertPos << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1611 | Worklist.push_back(std::make_pair(Clone, Incoming)); |
| 1612 | } |
| 1613 | } |
| 1614 | // Erase the original call. |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 1615 | DEBUG(dbgs() << "Erasing: " << *CInst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1616 | EraseInstruction(CInst); |
| 1617 | continue; |
| 1618 | } |
| 1619 | } |
| 1620 | } while (!Worklist.empty()); |
| 1621 | } |
Michael Gottesman | b24bdef | 2013-01-12 02:57:16 +0000 | [diff] [blame] | 1622 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1623 | } |
| 1624 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1625 | /// Check for critical edges, loop boundaries, irreducible control flow, or |
| 1626 | /// other CFG structures where moving code across the edge would result in it |
| 1627 | /// being executed more. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1628 | void |
| 1629 | ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB, |
| 1630 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1631 | BBState &MyStates) const { |
| 1632 | // If any top-down local-use or possible-dec has a succ which is earlier in |
| 1633 | // the sequence, forget it. |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 1634 | for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(), |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1635 | E = MyStates.top_down_ptr_end(); I != E; ++I) |
| 1636 | switch (I->second.GetSeq()) { |
| 1637 | default: break; |
| 1638 | case S_Use: { |
| 1639 | const Value *Arg = I->first; |
| 1640 | const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); |
| 1641 | bool SomeSuccHasSame = false; |
| 1642 | bool AllSuccsHaveSame = true; |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 1643 | PtrState &S = I->second; |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 1644 | succ_const_iterator SI(TI), SE(TI, false); |
| 1645 | |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 1646 | for (; SI != SE; ++SI) { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 1647 | Sequence SuccSSeq = S_None; |
| 1648 | bool SuccSRRIKnownSafe = false; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1649 | // If VisitBottomUp has pointer information for this successor, take |
| 1650 | // what we know about it. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1651 | DenseMap<const BasicBlock *, BBState>::iterator BBI = |
| 1652 | BBStates.find(*SI); |
| 1653 | assert(BBI != BBStates.end()); |
| 1654 | const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg); |
| 1655 | SuccSSeq = SuccS.GetSeq(); |
| 1656 | SuccSRRIKnownSafe = SuccS.RRI.KnownSafe; |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 1657 | switch (SuccSSeq) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1658 | case S_None: |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1659 | case S_CanRelease: { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 1660 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) { |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1661 | S.ClearSequenceProgress(); |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 1662 | break; |
| 1663 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1664 | continue; |
| 1665 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1666 | case S_Use: |
| 1667 | SomeSuccHasSame = true; |
| 1668 | break; |
| 1669 | case S_Stop: |
| 1670 | case S_Release: |
| 1671 | case S_MovableRelease: |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 1672 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1673 | AllSuccsHaveSame = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1674 | break; |
| 1675 | case S_Retain: |
| 1676 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 1677 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1678 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1679 | // If the state at the other end of any of the successor edges |
| 1680 | // matches the current state, require all edges to match. This |
| 1681 | // guards against loops in the middle of a sequence. |
| 1682 | if (SomeSuccHasSame && !AllSuccsHaveSame) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1683 | S.ClearSequenceProgress(); |
Dan Gohman | 04443706 | 2011-12-12 18:13:53 +0000 | [diff] [blame] | 1684 | break; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1685 | } |
| 1686 | case S_CanRelease: { |
| 1687 | const Value *Arg = I->first; |
| 1688 | const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); |
| 1689 | bool SomeSuccHasSame = false; |
| 1690 | bool AllSuccsHaveSame = true; |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 1691 | PtrState &S = I->second; |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 1692 | succ_const_iterator SI(TI), SE(TI, false); |
| 1693 | |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 1694 | for (; SI != SE; ++SI) { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 1695 | Sequence SuccSSeq = S_None; |
| 1696 | bool SuccSRRIKnownSafe = false; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1697 | // If VisitBottomUp has pointer information for this successor, take |
| 1698 | // what we know about it. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1699 | DenseMap<const BasicBlock *, BBState>::iterator BBI = |
| 1700 | BBStates.find(*SI); |
| 1701 | assert(BBI != BBStates.end()); |
| 1702 | const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg); |
| 1703 | SuccSSeq = SuccS.GetSeq(); |
| 1704 | SuccSRRIKnownSafe = SuccS.RRI.KnownSafe; |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 1705 | switch (SuccSSeq) { |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1706 | case S_None: { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 1707 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) { |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1708 | S.ClearSequenceProgress(); |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 1709 | break; |
| 1710 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1711 | continue; |
| 1712 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1713 | case S_CanRelease: |
| 1714 | SomeSuccHasSame = true; |
| 1715 | break; |
| 1716 | case S_Stop: |
| 1717 | case S_Release: |
| 1718 | case S_MovableRelease: |
| 1719 | case S_Use: |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 1720 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1721 | AllSuccsHaveSame = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1722 | break; |
| 1723 | case S_Retain: |
| 1724 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 1725 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1726 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1727 | // If the state at the other end of any of the successor edges |
| 1728 | // matches the current state, require all edges to match. This |
| 1729 | // guards against loops in the middle of a sequence. |
| 1730 | if (SomeSuccHasSame && !AllSuccsHaveSame) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1731 | S.ClearSequenceProgress(); |
Dan Gohman | 04443706 | 2011-12-12 18:13:53 +0000 | [diff] [blame] | 1732 | break; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1733 | } |
| 1734 | } |
| 1735 | } |
| 1736 | |
| 1737 | bool |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1738 | ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst, |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 1739 | BasicBlock *BB, |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1740 | MapVector<Value *, RRInfo> &Retains, |
| 1741 | BBState &MyStates) { |
| 1742 | bool NestingDetected = false; |
| 1743 | InstructionClass Class = GetInstructionClass(Inst); |
| 1744 | const Value *Arg = 0; |
| 1745 | |
| 1746 | switch (Class) { |
| 1747 | case IC_Release: { |
| 1748 | Arg = GetObjCArg(Inst); |
| 1749 | |
| 1750 | PtrState &S = MyStates.getPtrBottomUpState(Arg); |
| 1751 | |
| 1752 | // If we see two releases in a row on the same pointer. If so, make |
| 1753 | // a note, and we'll cicle back to revisit it after we've |
| 1754 | // hopefully eliminated the second release, which may allow us to |
| 1755 | // eliminate the first release too. |
| 1756 | // Theoretically we could implement removal of nested retain+release |
| 1757 | // pairs by making PtrState hold a stack of states, but this is |
| 1758 | // simple and avoids adding overhead for the non-nested case. |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 1759 | if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) { |
| 1760 | DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested " |
| 1761 | "releases (i.e. a release pair)\n"); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1762 | NestingDetected = true; |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 1763 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1764 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1765 | MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1766 | Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release; |
| 1767 | ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq); |
| 1768 | S.ResetSequenceProgress(NewSeq); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1769 | S.RRI.ReleaseMetadata = ReleaseMetadata; |
Michael Gottesman | 07beea4 | 2013-03-23 05:31:01 +0000 | [diff] [blame] | 1770 | S.RRI.KnownSafe = S.HasKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1771 | S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall(); |
| 1772 | S.RRI.Calls.insert(Inst); |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 1773 | S.SetKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1774 | break; |
| 1775 | } |
| 1776 | case IC_RetainBlock: |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1777 | // In OptimizeIndividualCalls, we have strength reduced all optimizable |
| 1778 | // objc_retainBlocks to objc_retains. Thus at this point any |
| 1779 | // objc_retainBlocks that we see are not optimizable. |
| 1780 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1781 | case IC_Retain: |
| 1782 | case IC_RetainRV: { |
| 1783 | Arg = GetObjCArg(Inst); |
| 1784 | |
| 1785 | PtrState &S = MyStates.getPtrBottomUpState(Arg); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1786 | S.SetKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1787 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1788 | Sequence OldSeq = S.GetSeq(); |
| 1789 | switch (OldSeq) { |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1790 | case S_Stop: |
| 1791 | case S_Release: |
| 1792 | case S_MovableRelease: |
| 1793 | case S_Use: |
| 1794 | S.RRI.ReverseInsertPts.clear(); |
| 1795 | // FALL THROUGH |
| 1796 | case S_CanRelease: |
| 1797 | // Don't do retain+release tracking for IC_RetainRV, because it's |
| 1798 | // better to let it remain as the first instruction after a call. |
Michael Gottesman | ba64859 | 2013-03-28 23:08:44 +0000 | [diff] [blame^] | 1799 | if (Class != IC_RetainRV) |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1800 | Retains[Inst] = S.RRI; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1801 | S.ClearSequenceProgress(); |
| 1802 | break; |
| 1803 | case S_None: |
| 1804 | break; |
| 1805 | case S_Retain: |
| 1806 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 1807 | } |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1808 | ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq()); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1809 | return NestingDetected; |
| 1810 | } |
| 1811 | case IC_AutoreleasepoolPop: |
| 1812 | // Conservatively, clear MyStates for all known pointers. |
| 1813 | MyStates.clearBottomUpPointers(); |
| 1814 | return NestingDetected; |
| 1815 | case IC_AutoreleasepoolPush: |
| 1816 | case IC_None: |
| 1817 | // These are irrelevant. |
| 1818 | return NestingDetected; |
| 1819 | default: |
| 1820 | break; |
| 1821 | } |
| 1822 | |
| 1823 | // Consider any other possible effects of this instruction on each |
| 1824 | // pointer being tracked. |
| 1825 | for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(), |
| 1826 | ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) { |
| 1827 | const Value *Ptr = MI->first; |
| 1828 | if (Ptr == Arg) |
| 1829 | continue; // Handled above. |
| 1830 | PtrState &S = MI->second; |
| 1831 | Sequence Seq = S.GetSeq(); |
| 1832 | |
| 1833 | // Check for possible releases. |
| 1834 | if (CanAlterRefCount(Inst, Ptr, PA, Class)) { |
Michael Gottesman | 764b1cf | 2013-03-23 05:46:19 +0000 | [diff] [blame] | 1835 | S.ClearKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1836 | switch (Seq) { |
| 1837 | case S_Use: |
| 1838 | S.SetSeq(S_CanRelease); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1839 | ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq()); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1840 | continue; |
| 1841 | case S_CanRelease: |
| 1842 | case S_Release: |
| 1843 | case S_MovableRelease: |
| 1844 | case S_Stop: |
| 1845 | case S_None: |
| 1846 | break; |
| 1847 | case S_Retain: |
| 1848 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 1849 | } |
| 1850 | } |
| 1851 | |
| 1852 | // Check for possible direct uses. |
| 1853 | switch (Seq) { |
| 1854 | case S_Release: |
| 1855 | case S_MovableRelease: |
| 1856 | if (CanUse(Inst, Ptr, PA, Class)) { |
| 1857 | assert(S.RRI.ReverseInsertPts.empty()); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 1858 | // If this is an invoke instruction, we're scanning it as part of |
| 1859 | // one of its successor blocks, since we can't insert code after it |
| 1860 | // in its own block, and we don't want to split critical edges. |
| 1861 | if (isa<InvokeInst>(Inst)) |
| 1862 | S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt()); |
| 1863 | else |
Francois Pichet | 4b9ab74 | 2012-03-24 01:36:37 +0000 | [diff] [blame] | 1864 | S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst))); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1865 | S.SetSeq(S_Use); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1866 | ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use); |
John McCall | 20182ac | 2013-03-22 21:38:36 +0000 | [diff] [blame] | 1867 | } else if (Seq == S_Release && IsUser(Class)) { |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1868 | // Non-movable releases depend on any possible objc pointer use. |
| 1869 | S.SetSeq(S_Stop); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1870 | ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1871 | assert(S.RRI.ReverseInsertPts.empty()); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 1872 | // As above; handle invoke specially. |
| 1873 | if (isa<InvokeInst>(Inst)) |
| 1874 | S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt()); |
| 1875 | else |
Francois Pichet | 4b9ab74 | 2012-03-24 01:36:37 +0000 | [diff] [blame] | 1876 | S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst))); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1877 | } |
| 1878 | break; |
| 1879 | case S_Stop: |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1880 | if (CanUse(Inst, Ptr, PA, Class)) { |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1881 | S.SetSeq(S_Use); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1882 | ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use); |
| 1883 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1884 | break; |
| 1885 | case S_CanRelease: |
| 1886 | case S_Use: |
| 1887 | case S_None: |
| 1888 | break; |
| 1889 | case S_Retain: |
| 1890 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 1891 | } |
| 1892 | } |
| 1893 | |
| 1894 | return NestingDetected; |
| 1895 | } |
| 1896 | |
| 1897 | bool |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1898 | ObjCARCOpt::VisitBottomUp(BasicBlock *BB, |
| 1899 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1900 | MapVector<Value *, RRInfo> &Retains) { |
| 1901 | bool NestingDetected = false; |
| 1902 | BBState &MyStates = BBStates[BB]; |
| 1903 | |
| 1904 | // Merge the states from each successor to compute the initial state |
| 1905 | // for the current block. |
Dan Gohman | 10c82ce | 2012-08-27 18:31:36 +0000 | [diff] [blame] | 1906 | BBState::edge_iterator SI(MyStates.succ_begin()), |
| 1907 | SE(MyStates.succ_end()); |
| 1908 | if (SI != SE) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 1909 | const BasicBlock *Succ = *SI; |
| 1910 | DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ); |
| 1911 | assert(I != BBStates.end()); |
| 1912 | MyStates.InitFromSucc(I->second); |
| 1913 | ++SI; |
| 1914 | for (; SI != SE; ++SI) { |
| 1915 | Succ = *SI; |
| 1916 | I = BBStates.find(Succ); |
| 1917 | assert(I != BBStates.end()); |
| 1918 | MyStates.MergeSucc(I->second); |
| 1919 | } |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 1920 | } |
| 1921 | |
| 1922 | #ifdef ARC_ANNOTATIONS |
| 1923 | if (EnableARCAnnotations) { |
| 1924 | // If ARC Annotations are enabled, output the current state of pointers at the |
| 1925 | // bottom of the basic block. |
| 1926 | for(BBState::ptr_const_iterator I = MyStates.bottom_up_ptr_begin(), |
| 1927 | E = MyStates.bottom_up_ptr_end(); I != E; ++I) { |
| 1928 | Value *Ptr = const_cast<Value*>(I->first); |
| 1929 | Sequence Seq = I->second.GetSeq(); |
| 1930 | GenerateARCBBTerminatorAnnotation("llvm.arc.annotation.bottomup.bbend", |
| 1931 | BB, Ptr, Seq); |
| 1932 | } |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 1933 | } |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 1934 | #endif |
| 1935 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1936 | |
| 1937 | // Visit all the instructions, bottom-up. |
| 1938 | for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) { |
| 1939 | Instruction *Inst = llvm::prior(I); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 1940 | |
| 1941 | // Invoke instructions are visited as part of their successors (below). |
| 1942 | if (isa<InvokeInst>(Inst)) |
| 1943 | continue; |
| 1944 | |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 1945 | DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n"); |
| 1946 | |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 1947 | NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates); |
| 1948 | } |
| 1949 | |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1950 | // If there's a predecessor with an invoke, visit the invoke as if it were |
| 1951 | // part of this block, since we can't insert code after an invoke in its own |
| 1952 | // block, and we don't want to split critical edges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 1953 | for (BBState::edge_iterator PI(MyStates.pred_begin()), |
| 1954 | PE(MyStates.pred_end()); PI != PE; ++PI) { |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 1955 | BasicBlock *Pred = *PI; |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1956 | if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back())) |
| 1957 | NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1958 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1959 | |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 1960 | #ifdef ARC_ANNOTATIONS |
| 1961 | if (EnableARCAnnotations) { |
| 1962 | // If ARC Annotations are enabled, output the current state of pointers at the |
| 1963 | // top of the basic block. |
| 1964 | for(BBState::ptr_const_iterator I = MyStates.bottom_up_ptr_begin(), |
| 1965 | E = MyStates.bottom_up_ptr_end(); I != E; ++I) { |
| 1966 | Value *Ptr = const_cast<Value*>(I->first); |
| 1967 | Sequence Seq = I->second.GetSeq(); |
| 1968 | GenerateARCBBEntranceAnnotation("llvm.arc.annotation.bottomup.bbstart", |
| 1969 | BB, Ptr, Seq); |
| 1970 | } |
| 1971 | } |
| 1972 | #endif |
| 1973 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1974 | return NestingDetected; |
| 1975 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1976 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1977 | bool |
| 1978 | ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst, |
| 1979 | DenseMap<Value *, RRInfo> &Releases, |
| 1980 | BBState &MyStates) { |
| 1981 | bool NestingDetected = false; |
| 1982 | InstructionClass Class = GetInstructionClass(Inst); |
| 1983 | const Value *Arg = 0; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1984 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1985 | switch (Class) { |
| 1986 | case IC_RetainBlock: |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1987 | // In OptimizeIndividualCalls, we have strength reduced all optimizable |
| 1988 | // objc_retainBlocks to objc_retains. Thus at this point any |
| 1989 | // objc_retainBlocks that we see are not optimizable. |
| 1990 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1991 | case IC_Retain: |
| 1992 | case IC_RetainRV: { |
| 1993 | Arg = GetObjCArg(Inst); |
| 1994 | |
| 1995 | PtrState &S = MyStates.getPtrTopDownState(Arg); |
| 1996 | |
| 1997 | // Don't do retain+release tracking for IC_RetainRV, because it's |
| 1998 | // better to let it remain as the first instruction after a call. |
| 1999 | if (Class != IC_RetainRV) { |
| 2000 | // If we see two retains in a row on the same pointer. If so, make |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2001 | // a note, and we'll cicle back to revisit it after we've |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2002 | // hopefully eliminated the second retain, which may allow us to |
| 2003 | // eliminate the first retain too. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2004 | // Theoretically we could implement removal of nested retain+release |
| 2005 | // pairs by making PtrState hold a stack of states, but this is |
| 2006 | // simple and avoids adding overhead for the non-nested case. |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2007 | if (S.GetSeq() == S_Retain) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2008 | NestingDetected = true; |
| 2009 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2010 | ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 2011 | S.ResetSequenceProgress(S_Retain); |
Michael Gottesman | 07beea4 | 2013-03-23 05:31:01 +0000 | [diff] [blame] | 2012 | S.RRI.KnownSafe = S.HasKnownPositiveRefCount(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2013 | S.RRI.Calls.insert(Inst); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2014 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2015 | |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2016 | S.SetKnownPositiveRefCount(); |
Dan Gohman | f64ff8e | 2012-07-23 19:27:31 +0000 | [diff] [blame] | 2017 | |
| 2018 | // A retain can be a potential use; procede to the generic checking |
| 2019 | // code below. |
| 2020 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2021 | } |
| 2022 | case IC_Release: { |
| 2023 | Arg = GetObjCArg(Inst); |
| 2024 | |
| 2025 | PtrState &S = MyStates.getPtrTopDownState(Arg); |
Michael Gottesman | 764b1cf | 2013-03-23 05:46:19 +0000 | [diff] [blame] | 2026 | S.ClearKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2027 | |
| 2028 | switch (S.GetSeq()) { |
| 2029 | case S_Retain: |
| 2030 | case S_CanRelease: |
| 2031 | S.RRI.ReverseInsertPts.clear(); |
| 2032 | // FALL THROUGH |
| 2033 | case S_Use: |
| 2034 | S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind); |
| 2035 | S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall(); |
| 2036 | Releases[Inst] = S.RRI; |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2037 | ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2038 | S.ClearSequenceProgress(); |
| 2039 | break; |
| 2040 | case S_None: |
| 2041 | break; |
| 2042 | case S_Stop: |
| 2043 | case S_Release: |
| 2044 | case S_MovableRelease: |
| 2045 | llvm_unreachable("top-down pointer in release state!"); |
| 2046 | } |
| 2047 | break; |
| 2048 | } |
| 2049 | case IC_AutoreleasepoolPop: |
| 2050 | // Conservatively, clear MyStates for all known pointers. |
| 2051 | MyStates.clearTopDownPointers(); |
| 2052 | return NestingDetected; |
| 2053 | case IC_AutoreleasepoolPush: |
| 2054 | case IC_None: |
| 2055 | // These are irrelevant. |
| 2056 | return NestingDetected; |
| 2057 | default: |
| 2058 | break; |
| 2059 | } |
| 2060 | |
| 2061 | // Consider any other possible effects of this instruction on each |
| 2062 | // pointer being tracked. |
| 2063 | for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(), |
| 2064 | ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) { |
| 2065 | const Value *Ptr = MI->first; |
| 2066 | if (Ptr == Arg) |
| 2067 | continue; // Handled above. |
| 2068 | PtrState &S = MI->second; |
| 2069 | Sequence Seq = S.GetSeq(); |
| 2070 | |
| 2071 | // Check for possible releases. |
| 2072 | if (CanAlterRefCount(Inst, Ptr, PA, Class)) { |
Michael Gottesman | 764b1cf | 2013-03-23 05:46:19 +0000 | [diff] [blame] | 2073 | S.ClearKnownPositiveRefCount(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2074 | switch (Seq) { |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2075 | case S_Retain: |
| 2076 | S.SetSeq(S_CanRelease); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2077 | ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2078 | assert(S.RRI.ReverseInsertPts.empty()); |
| 2079 | S.RRI.ReverseInsertPts.insert(Inst); |
| 2080 | |
| 2081 | // One call can't cause a transition from S_Retain to S_CanRelease |
| 2082 | // and S_CanRelease to S_Use. If we've made the first transition, |
| 2083 | // we're done. |
| 2084 | continue; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2085 | case S_Use: |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2086 | case S_CanRelease: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2087 | case S_None: |
| 2088 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2089 | case S_Stop: |
| 2090 | case S_Release: |
| 2091 | case S_MovableRelease: |
| 2092 | llvm_unreachable("top-down pointer in release state!"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2093 | } |
| 2094 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2095 | |
| 2096 | // Check for possible direct uses. |
| 2097 | switch (Seq) { |
| 2098 | case S_CanRelease: |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2099 | if (CanUse(Inst, Ptr, PA, Class)) { |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2100 | S.SetSeq(S_Use); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2101 | ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use); |
| 2102 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2103 | break; |
| 2104 | case S_Retain: |
| 2105 | case S_Use: |
| 2106 | case S_None: |
| 2107 | break; |
| 2108 | case S_Stop: |
| 2109 | case S_Release: |
| 2110 | case S_MovableRelease: |
| 2111 | llvm_unreachable("top-down pointer in release state!"); |
| 2112 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2113 | } |
| 2114 | |
| 2115 | return NestingDetected; |
| 2116 | } |
| 2117 | |
| 2118 | bool |
| 2119 | ObjCARCOpt::VisitTopDown(BasicBlock *BB, |
| 2120 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 2121 | DenseMap<Value *, RRInfo> &Releases) { |
| 2122 | bool NestingDetected = false; |
| 2123 | BBState &MyStates = BBStates[BB]; |
| 2124 | |
| 2125 | // Merge the states from each predecessor to compute the initial state |
| 2126 | // for the current block. |
Dan Gohman | 10c82ce | 2012-08-27 18:31:36 +0000 | [diff] [blame] | 2127 | BBState::edge_iterator PI(MyStates.pred_begin()), |
| 2128 | PE(MyStates.pred_end()); |
| 2129 | if (PI != PE) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2130 | const BasicBlock *Pred = *PI; |
| 2131 | DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred); |
| 2132 | assert(I != BBStates.end()); |
| 2133 | MyStates.InitFromPred(I->second); |
| 2134 | ++PI; |
| 2135 | for (; PI != PE; ++PI) { |
| 2136 | Pred = *PI; |
| 2137 | I = BBStates.find(Pred); |
| 2138 | assert(I != BBStates.end()); |
| 2139 | MyStates.MergePred(I->second); |
| 2140 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2141 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2142 | |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 2143 | #ifdef ARC_ANNOTATIONS |
| 2144 | if (EnableARCAnnotations) { |
| 2145 | // If ARC Annotations are enabled, output the current state of pointers at the |
| 2146 | // top of the basic block. |
| 2147 | for(BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(), |
| 2148 | E = MyStates.top_down_ptr_end(); I != E; ++I) { |
| 2149 | Value *Ptr = const_cast<Value*>(I->first); |
| 2150 | Sequence Seq = I->second.GetSeq(); |
| 2151 | GenerateARCBBEntranceAnnotation("llvm.arc.annotation.topdown.bbstart", |
| 2152 | BB, Ptr, Seq); |
| 2153 | } |
| 2154 | } |
| 2155 | #endif |
| 2156 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2157 | // Visit all the instructions, top-down. |
| 2158 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 2159 | Instruction *Inst = I; |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 2160 | |
| 2161 | DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n"); |
| 2162 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2163 | NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2164 | } |
| 2165 | |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 2166 | #ifdef ARC_ANNOTATIONS |
| 2167 | if (EnableARCAnnotations) { |
| 2168 | // If ARC Annotations are enabled, output the current state of pointers at the |
| 2169 | // bottom of the basic block. |
| 2170 | for(BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(), |
| 2171 | E = MyStates.top_down_ptr_end(); I != E; ++I) { |
| 2172 | Value *Ptr = const_cast<Value*>(I->first); |
| 2173 | Sequence Seq = I->second.GetSeq(); |
| 2174 | GenerateARCBBTerminatorAnnotation("llvm.arc.annotation.topdown.bbend", |
| 2175 | BB, Ptr, Seq); |
| 2176 | } |
| 2177 | } |
| 2178 | #endif |
| 2179 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2180 | CheckForCFGHazards(BB, BBStates, MyStates); |
| 2181 | return NestingDetected; |
| 2182 | } |
| 2183 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2184 | static void |
| 2185 | ComputePostOrders(Function &F, |
| 2186 | SmallVectorImpl<BasicBlock *> &PostOrder, |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2187 | SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder, |
| 2188 | unsigned NoObjCARCExceptionsMDKind, |
| 2189 | DenseMap<const BasicBlock *, BBState> &BBStates) { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2190 | /// The visited set, for doing DFS walks. |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2191 | SmallPtrSet<BasicBlock *, 16> Visited; |
| 2192 | |
| 2193 | // Do DFS, computing the PostOrder. |
| 2194 | SmallPtrSet<BasicBlock *, 16> OnStack; |
| 2195 | SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2196 | |
| 2197 | // Functions always have exactly one entry block, and we don't have |
| 2198 | // any other block that we treat like an entry block. |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2199 | BasicBlock *EntryBB = &F.getEntryBlock(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2200 | BBState &MyStates = BBStates[EntryBB]; |
| 2201 | MyStates.SetAsEntry(); |
| 2202 | TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back()); |
| 2203 | SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI))); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2204 | Visited.insert(EntryBB); |
| 2205 | OnStack.insert(EntryBB); |
| 2206 | do { |
| 2207 | dfs_next_succ: |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2208 | BasicBlock *CurrBB = SuccStack.back().first; |
| 2209 | TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back()); |
| 2210 | succ_iterator SE(TI, false); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2211 | |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2212 | while (SuccStack.back().second != SE) { |
| 2213 | BasicBlock *SuccBB = *SuccStack.back().second++; |
| 2214 | if (Visited.insert(SuccBB)) { |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2215 | TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back()); |
| 2216 | SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI))); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2217 | BBStates[CurrBB].addSucc(SuccBB); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2218 | BBState &SuccStates = BBStates[SuccBB]; |
| 2219 | SuccStates.addPred(CurrBB); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2220 | OnStack.insert(SuccBB); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2221 | goto dfs_next_succ; |
| 2222 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2223 | |
| 2224 | if (!OnStack.count(SuccBB)) { |
| 2225 | BBStates[CurrBB].addSucc(SuccBB); |
| 2226 | BBStates[SuccBB].addPred(CurrBB); |
| 2227 | } |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2228 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2229 | OnStack.erase(CurrBB); |
| 2230 | PostOrder.push_back(CurrBB); |
| 2231 | SuccStack.pop_back(); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2232 | } while (!SuccStack.empty()); |
| 2233 | |
| 2234 | Visited.clear(); |
| 2235 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2236 | // Do reverse-CFG DFS, computing the reverse-CFG PostOrder. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2237 | // Functions may have many exits, and there also blocks which we treat |
| 2238 | // as exits due to ignored edges. |
| 2239 | SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack; |
| 2240 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { |
| 2241 | BasicBlock *ExitBB = I; |
| 2242 | BBState &MyStates = BBStates[ExitBB]; |
| 2243 | if (!MyStates.isExit()) |
| 2244 | continue; |
| 2245 | |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2246 | MyStates.SetAsExit(); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2247 | |
| 2248 | PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin())); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2249 | Visited.insert(ExitBB); |
| 2250 | while (!PredStack.empty()) { |
| 2251 | reverse_dfs_next_succ: |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2252 | BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end(); |
| 2253 | while (PredStack.back().second != PE) { |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2254 | BasicBlock *BB = *PredStack.back().second++; |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2255 | if (Visited.insert(BB)) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2256 | PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin())); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2257 | goto reverse_dfs_next_succ; |
| 2258 | } |
| 2259 | } |
| 2260 | ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first); |
| 2261 | } |
| 2262 | } |
| 2263 | } |
| 2264 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2265 | // Visit the function both top-down and bottom-up. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2266 | bool |
| 2267 | ObjCARCOpt::Visit(Function &F, |
| 2268 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 2269 | MapVector<Value *, RRInfo> &Retains, |
| 2270 | DenseMap<Value *, RRInfo> &Releases) { |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2271 | |
| 2272 | // Use reverse-postorder traversals, because we magically know that loops |
| 2273 | // will be well behaved, i.e. they won't repeatedly call retain on a single |
| 2274 | // pointer without doing a release. We can't use the ReversePostOrderTraversal |
| 2275 | // class here because we want the reverse-CFG postorder to consider each |
| 2276 | // function exit point, and we want to ignore selected cycle edges. |
| 2277 | SmallVector<BasicBlock *, 16> PostOrder; |
| 2278 | SmallVector<BasicBlock *, 16> ReverseCFGPostOrder; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2279 | ComputePostOrders(F, PostOrder, ReverseCFGPostOrder, |
| 2280 | NoObjCARCExceptionsMDKind, |
| 2281 | BBStates); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2282 | |
| 2283 | // Use reverse-postorder on the reverse CFG for bottom-up. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2284 | bool BottomUpNestingDetected = false; |
Dan Gohman | c57b58c | 2011-08-18 21:27:42 +0000 | [diff] [blame] | 2285 | for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I = |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2286 | ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend(); |
| 2287 | I != E; ++I) |
| 2288 | BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2289 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2290 | // Use reverse-postorder for top-down. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2291 | bool TopDownNestingDetected = false; |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2292 | for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I = |
| 2293 | PostOrder.rbegin(), E = PostOrder.rend(); |
| 2294 | I != E; ++I) |
| 2295 | TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2296 | |
| 2297 | return TopDownNestingDetected && BottomUpNestingDetected; |
| 2298 | } |
| 2299 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2300 | /// Move the calls in RetainsToMove and ReleasesToMove. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2301 | void ObjCARCOpt::MoveCalls(Value *Arg, |
| 2302 | RRInfo &RetainsToMove, |
| 2303 | RRInfo &ReleasesToMove, |
| 2304 | MapVector<Value *, RRInfo> &Retains, |
| 2305 | DenseMap<Value *, RRInfo> &Releases, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2306 | SmallVectorImpl<Instruction *> &DeadInsts, |
| 2307 | Module *M) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2308 | Type *ArgTy = Arg->getType(); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2309 | Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext())); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2310 | |
| 2311 | // Insert the new retain and release calls. |
| 2312 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2313 | PI = ReleasesToMove.ReverseInsertPts.begin(), |
| 2314 | PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) { |
| 2315 | Instruction *InsertPt = *PI; |
| 2316 | Value *MyArg = ArgTy == ParamTy ? Arg : |
| 2317 | new BitCastInst(Arg, ParamTy, "", InsertPt); |
| 2318 | CallInst *Call = |
Michael Gottesman | ba64859 | 2013-03-28 23:08:44 +0000 | [diff] [blame^] | 2319 | CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2320 | Call->setDoesNotThrow(); |
Michael Gottesman | ba64859 | 2013-03-28 23:08:44 +0000 | [diff] [blame^] | 2321 | Call->setTailCall(); |
| 2322 | |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2323 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call |
| 2324 | << "\n" |
| 2325 | " At insertion point: " << *InsertPt |
| 2326 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2327 | } |
| 2328 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2329 | PI = RetainsToMove.ReverseInsertPts.begin(), |
| 2330 | PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) { |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2331 | Instruction *InsertPt = *PI; |
| 2332 | Value *MyArg = ArgTy == ParamTy ? Arg : |
| 2333 | new BitCastInst(Arg, ParamTy, "", InsertPt); |
| 2334 | CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg, |
| 2335 | "", InsertPt); |
| 2336 | // Attach a clang.imprecise_release metadata tag, if appropriate. |
| 2337 | if (MDNode *M = ReleasesToMove.ReleaseMetadata) |
| 2338 | Call->setMetadata(ImpreciseReleaseMDKind, M); |
| 2339 | Call->setDoesNotThrow(); |
| 2340 | if (ReleasesToMove.IsTailCallRelease) |
| 2341 | Call->setTailCall(); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2342 | |
| 2343 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call |
| 2344 | << "\n" |
| 2345 | " At insertion point: " << *InsertPt |
| 2346 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2347 | } |
| 2348 | |
| 2349 | // Delete the original retain and release calls. |
| 2350 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2351 | AI = RetainsToMove.Calls.begin(), |
| 2352 | AE = RetainsToMove.Calls.end(); AI != AE; ++AI) { |
| 2353 | Instruction *OrigRetain = *AI; |
| 2354 | Retains.blot(OrigRetain); |
| 2355 | DeadInsts.push_back(OrigRetain); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2356 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain << |
| 2357 | "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2358 | } |
| 2359 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2360 | AI = ReleasesToMove.Calls.begin(), |
| 2361 | AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) { |
| 2362 | Instruction *OrigRelease = *AI; |
| 2363 | Releases.erase(OrigRelease); |
| 2364 | DeadInsts.push_back(OrigRelease); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2365 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease |
| 2366 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2367 | } |
| 2368 | } |
| 2369 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2370 | bool |
| 2371 | ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> |
| 2372 | &BBStates, |
| 2373 | MapVector<Value *, RRInfo> &Retains, |
| 2374 | DenseMap<Value *, RRInfo> &Releases, |
| 2375 | Module *M, |
| 2376 | SmallVector<Instruction *, 4> &NewRetains, |
| 2377 | SmallVector<Instruction *, 4> &NewReleases, |
| 2378 | SmallVector<Instruction *, 8> &DeadInsts, |
| 2379 | RRInfo &RetainsToMove, |
| 2380 | RRInfo &ReleasesToMove, |
| 2381 | Value *Arg, |
| 2382 | bool KnownSafe, |
| 2383 | bool &AnyPairsCompletelyEliminated) { |
| 2384 | // If a pair happens in a region where it is known that the reference count |
| 2385 | // is already incremented, we can similarly ignore possible decrements. |
| 2386 | bool KnownSafeTD = true, KnownSafeBU = true; |
| 2387 | |
| 2388 | // Connect the dots between the top-down-collected RetainsToMove and |
| 2389 | // bottom-up-collected ReleasesToMove to form sets of related calls. |
| 2390 | // This is an iterative process so that we connect multiple releases |
| 2391 | // to multiple retains if needed. |
| 2392 | unsigned OldDelta = 0; |
| 2393 | unsigned NewDelta = 0; |
| 2394 | unsigned OldCount = 0; |
| 2395 | unsigned NewCount = 0; |
| 2396 | bool FirstRelease = true; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2397 | for (;;) { |
| 2398 | for (SmallVectorImpl<Instruction *>::const_iterator |
| 2399 | NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) { |
| 2400 | Instruction *NewRetain = *NI; |
| 2401 | MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain); |
| 2402 | assert(It != Retains.end()); |
| 2403 | const RRInfo &NewRetainRRI = It->second; |
| 2404 | KnownSafeTD &= NewRetainRRI.KnownSafe; |
| 2405 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2406 | LI = NewRetainRRI.Calls.begin(), |
| 2407 | LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) { |
| 2408 | Instruction *NewRetainRelease = *LI; |
| 2409 | DenseMap<Value *, RRInfo>::const_iterator Jt = |
| 2410 | Releases.find(NewRetainRelease); |
| 2411 | if (Jt == Releases.end()) |
| 2412 | return false; |
| 2413 | const RRInfo &NewRetainReleaseRRI = Jt->second; |
| 2414 | assert(NewRetainReleaseRRI.Calls.count(NewRetain)); |
| 2415 | if (ReleasesToMove.Calls.insert(NewRetainRelease)) { |
| 2416 | OldDelta -= |
| 2417 | BBStates[NewRetainRelease->getParent()].GetAllPathCount(); |
| 2418 | |
| 2419 | // Merge the ReleaseMetadata and IsTailCallRelease values. |
| 2420 | if (FirstRelease) { |
| 2421 | ReleasesToMove.ReleaseMetadata = |
| 2422 | NewRetainReleaseRRI.ReleaseMetadata; |
| 2423 | ReleasesToMove.IsTailCallRelease = |
| 2424 | NewRetainReleaseRRI.IsTailCallRelease; |
| 2425 | FirstRelease = false; |
| 2426 | } else { |
| 2427 | if (ReleasesToMove.ReleaseMetadata != |
| 2428 | NewRetainReleaseRRI.ReleaseMetadata) |
| 2429 | ReleasesToMove.ReleaseMetadata = 0; |
| 2430 | if (ReleasesToMove.IsTailCallRelease != |
| 2431 | NewRetainReleaseRRI.IsTailCallRelease) |
| 2432 | ReleasesToMove.IsTailCallRelease = false; |
| 2433 | } |
| 2434 | |
| 2435 | // Collect the optimal insertion points. |
| 2436 | if (!KnownSafe) |
| 2437 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2438 | RI = NewRetainReleaseRRI.ReverseInsertPts.begin(), |
| 2439 | RE = NewRetainReleaseRRI.ReverseInsertPts.end(); |
| 2440 | RI != RE; ++RI) { |
| 2441 | Instruction *RIP = *RI; |
| 2442 | if (ReleasesToMove.ReverseInsertPts.insert(RIP)) |
| 2443 | NewDelta -= BBStates[RIP->getParent()].GetAllPathCount(); |
| 2444 | } |
| 2445 | NewReleases.push_back(NewRetainRelease); |
| 2446 | } |
| 2447 | } |
| 2448 | } |
| 2449 | NewRetains.clear(); |
| 2450 | if (NewReleases.empty()) break; |
| 2451 | |
| 2452 | // Back the other way. |
| 2453 | for (SmallVectorImpl<Instruction *>::const_iterator |
| 2454 | NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) { |
| 2455 | Instruction *NewRelease = *NI; |
| 2456 | DenseMap<Value *, RRInfo>::const_iterator It = |
| 2457 | Releases.find(NewRelease); |
| 2458 | assert(It != Releases.end()); |
| 2459 | const RRInfo &NewReleaseRRI = It->second; |
| 2460 | KnownSafeBU &= NewReleaseRRI.KnownSafe; |
| 2461 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2462 | LI = NewReleaseRRI.Calls.begin(), |
| 2463 | LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) { |
| 2464 | Instruction *NewReleaseRetain = *LI; |
| 2465 | MapVector<Value *, RRInfo>::const_iterator Jt = |
| 2466 | Retains.find(NewReleaseRetain); |
| 2467 | if (Jt == Retains.end()) |
| 2468 | return false; |
| 2469 | const RRInfo &NewReleaseRetainRRI = Jt->second; |
| 2470 | assert(NewReleaseRetainRRI.Calls.count(NewRelease)); |
| 2471 | if (RetainsToMove.Calls.insert(NewReleaseRetain)) { |
| 2472 | unsigned PathCount = |
| 2473 | BBStates[NewReleaseRetain->getParent()].GetAllPathCount(); |
| 2474 | OldDelta += PathCount; |
| 2475 | OldCount += PathCount; |
| 2476 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2477 | // Collect the optimal insertion points. |
| 2478 | if (!KnownSafe) |
| 2479 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2480 | RI = NewReleaseRetainRRI.ReverseInsertPts.begin(), |
| 2481 | RE = NewReleaseRetainRRI.ReverseInsertPts.end(); |
| 2482 | RI != RE; ++RI) { |
| 2483 | Instruction *RIP = *RI; |
| 2484 | if (RetainsToMove.ReverseInsertPts.insert(RIP)) { |
| 2485 | PathCount = BBStates[RIP->getParent()].GetAllPathCount(); |
| 2486 | NewDelta += PathCount; |
| 2487 | NewCount += PathCount; |
| 2488 | } |
| 2489 | } |
| 2490 | NewRetains.push_back(NewReleaseRetain); |
| 2491 | } |
| 2492 | } |
| 2493 | } |
| 2494 | NewReleases.clear(); |
| 2495 | if (NewRetains.empty()) break; |
| 2496 | } |
| 2497 | |
| 2498 | // If the pointer is known incremented or nested, we can safely delete the |
| 2499 | // pair regardless of what's between them. |
| 2500 | if (KnownSafeTD || KnownSafeBU) { |
| 2501 | RetainsToMove.ReverseInsertPts.clear(); |
| 2502 | ReleasesToMove.ReverseInsertPts.clear(); |
| 2503 | NewCount = 0; |
| 2504 | } else { |
| 2505 | // Determine whether the new insertion points we computed preserve the |
| 2506 | // balance of retain and release calls through the program. |
| 2507 | // TODO: If the fully aggressive solution isn't valid, try to find a |
| 2508 | // less aggressive solution which is. |
| 2509 | if (NewDelta != 0) |
| 2510 | return false; |
| 2511 | } |
| 2512 | |
| 2513 | // Determine whether the original call points are balanced in the retain and |
| 2514 | // release calls through the program. If not, conservatively don't touch |
| 2515 | // them. |
| 2516 | // TODO: It's theoretically possible to do code motion in this case, as |
| 2517 | // long as the existing imbalances are maintained. |
| 2518 | if (OldDelta != 0) |
| 2519 | return false; |
| 2520 | |
| 2521 | Changed = true; |
| 2522 | assert(OldCount != 0 && "Unreachable code?"); |
| 2523 | NumRRs += OldCount - NewCount; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2524 | // Set to true if we completely removed any RR pairs. |
Michael Gottesman | 8b5515f | 2013-01-22 21:53:43 +0000 | [diff] [blame] | 2525 | AnyPairsCompletelyEliminated = NewCount == 0; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2526 | |
| 2527 | // We can move calls! |
| 2528 | return true; |
| 2529 | } |
| 2530 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2531 | /// Identify pairings between the retains and releases, and delete and/or move |
| 2532 | /// them. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2533 | bool |
| 2534 | ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState> |
| 2535 | &BBStates, |
| 2536 | MapVector<Value *, RRInfo> &Retains, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2537 | DenseMap<Value *, RRInfo> &Releases, |
| 2538 | Module *M) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2539 | bool AnyPairsCompletelyEliminated = false; |
| 2540 | RRInfo RetainsToMove; |
| 2541 | RRInfo ReleasesToMove; |
| 2542 | SmallVector<Instruction *, 4> NewRetains; |
| 2543 | SmallVector<Instruction *, 4> NewReleases; |
| 2544 | SmallVector<Instruction *, 8> DeadInsts; |
| 2545 | |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 2546 | // Visit each retain. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2547 | for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(), |
Dan Gohman | 2053a5d | 2011-09-29 22:25:23 +0000 | [diff] [blame] | 2548 | E = Retains.end(); I != E; ++I) { |
| 2549 | Value *V = I->first; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2550 | if (!V) continue; // blotted |
| 2551 | |
| 2552 | Instruction *Retain = cast<Instruction>(V); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2553 | |
| 2554 | DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain |
| 2555 | << "\n"); |
| 2556 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2557 | Value *Arg = GetObjCArg(Retain); |
| 2558 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 2559 | // If the object being released is in static or stack storage, we know it's |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2560 | // not being managed by ObjC reference counting, so we can delete pairs |
| 2561 | // regardless of what possible decrements or uses lie between them. |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 2562 | bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2563 | |
Dan Gohman | 56e1cef | 2011-08-22 17:29:11 +0000 | [diff] [blame] | 2564 | // A constant pointer can't be pointing to an object on the heap. It may |
| 2565 | // be reference-counted, but it won't be deleted. |
| 2566 | if (const LoadInst *LI = dyn_cast<LoadInst>(Arg)) |
| 2567 | if (const GlobalVariable *GV = |
| 2568 | dyn_cast<GlobalVariable>( |
| 2569 | StripPointerCastsAndObjCCalls(LI->getPointerOperand()))) |
| 2570 | if (GV->isConstant()) |
| 2571 | KnownSafe = true; |
| 2572 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2573 | // Connect the dots between the top-down-collected RetainsToMove and |
| 2574 | // bottom-up-collected ReleasesToMove to form sets of related calls. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2575 | NewRetains.push_back(Retain); |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2576 | bool PerformMoveCalls = |
| 2577 | ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains, |
| 2578 | NewReleases, DeadInsts, RetainsToMove, |
| 2579 | ReleasesToMove, Arg, KnownSafe, |
| 2580 | AnyPairsCompletelyEliminated); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2581 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2582 | #ifdef ARC_ANNOTATIONS |
| 2583 | // Do not move calls if ARC annotations are requested. If we were to move |
| 2584 | // calls in this case, we would not be able |
| 2585 | PerformMoveCalls = PerformMoveCalls && !EnableARCAnnotations; |
| 2586 | #endif // ARC_ANNOTATIONS |
| 2587 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2588 | if (PerformMoveCalls) { |
| 2589 | // Ok, everything checks out and we're all set. Let's move/delete some |
| 2590 | // code! |
| 2591 | MoveCalls(Arg, RetainsToMove, ReleasesToMove, |
| 2592 | Retains, Releases, DeadInsts, M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2593 | } |
| 2594 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2595 | // Clean up state for next retain. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2596 | NewReleases.clear(); |
| 2597 | NewRetains.clear(); |
| 2598 | RetainsToMove.clear(); |
| 2599 | ReleasesToMove.clear(); |
| 2600 | } |
| 2601 | |
| 2602 | // Now that we're done moving everything, we can delete the newly dead |
| 2603 | // instructions, as we no longer need them as insert points. |
| 2604 | while (!DeadInsts.empty()) |
| 2605 | EraseInstruction(DeadInsts.pop_back_val()); |
| 2606 | |
| 2607 | return AnyPairsCompletelyEliminated; |
| 2608 | } |
| 2609 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2610 | /// Weak pointer optimizations. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2611 | void ObjCARCOpt::OptimizeWeakCalls(Function &F) { |
| 2612 | // First, do memdep-style RLE and S2L optimizations. We can't use memdep |
| 2613 | // itself because it uses AliasAnalysis and we need to do provenance |
| 2614 | // queries instead. |
| 2615 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 2616 | Instruction *Inst = &*I++; |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 2617 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 2618 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst << |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 2619 | "\n"); |
| 2620 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2621 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 2622 | if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained) |
| 2623 | continue; |
| 2624 | |
| 2625 | // Delete objc_loadWeak calls with no users. |
| 2626 | if (Class == IC_LoadWeak && Inst->use_empty()) { |
| 2627 | Inst->eraseFromParent(); |
| 2628 | continue; |
| 2629 | } |
| 2630 | |
| 2631 | // TODO: For now, just look for an earlier available version of this value |
| 2632 | // within the same block. Theoretically, we could do memdep-style non-local |
| 2633 | // analysis too, but that would want caching. A better approach would be to |
| 2634 | // use the technique that EarlyCSE uses. |
| 2635 | inst_iterator Current = llvm::prior(I); |
| 2636 | BasicBlock *CurrentBB = Current.getBasicBlockIterator(); |
| 2637 | for (BasicBlock::iterator B = CurrentBB->begin(), |
| 2638 | J = Current.getInstructionIterator(); |
| 2639 | J != B; --J) { |
| 2640 | Instruction *EarlierInst = &*llvm::prior(J); |
| 2641 | InstructionClass EarlierClass = GetInstructionClass(EarlierInst); |
| 2642 | switch (EarlierClass) { |
| 2643 | case IC_LoadWeak: |
| 2644 | case IC_LoadWeakRetained: { |
| 2645 | // If this is loading from the same pointer, replace this load's value |
| 2646 | // with that one. |
| 2647 | CallInst *Call = cast<CallInst>(Inst); |
| 2648 | CallInst *EarlierCall = cast<CallInst>(EarlierInst); |
| 2649 | Value *Arg = Call->getArgOperand(0); |
| 2650 | Value *EarlierArg = EarlierCall->getArgOperand(0); |
| 2651 | switch (PA.getAA()->alias(Arg, EarlierArg)) { |
| 2652 | case AliasAnalysis::MustAlias: |
| 2653 | Changed = true; |
| 2654 | // If the load has a builtin retain, insert a plain retain for it. |
| 2655 | if (Class == IC_LoadWeakRetained) { |
| 2656 | CallInst *CI = |
| 2657 | CallInst::Create(getRetainCallee(F.getParent()), EarlierCall, |
| 2658 | "", Call); |
| 2659 | CI->setTailCall(); |
| 2660 | } |
| 2661 | // Zap the fully redundant load. |
| 2662 | Call->replaceAllUsesWith(EarlierCall); |
| 2663 | Call->eraseFromParent(); |
| 2664 | goto clobbered; |
| 2665 | case AliasAnalysis::MayAlias: |
| 2666 | case AliasAnalysis::PartialAlias: |
| 2667 | goto clobbered; |
| 2668 | case AliasAnalysis::NoAlias: |
| 2669 | break; |
| 2670 | } |
| 2671 | break; |
| 2672 | } |
| 2673 | case IC_StoreWeak: |
| 2674 | case IC_InitWeak: { |
| 2675 | // If this is storing to the same pointer and has the same size etc. |
| 2676 | // replace this load's value with the stored value. |
| 2677 | CallInst *Call = cast<CallInst>(Inst); |
| 2678 | CallInst *EarlierCall = cast<CallInst>(EarlierInst); |
| 2679 | Value *Arg = Call->getArgOperand(0); |
| 2680 | Value *EarlierArg = EarlierCall->getArgOperand(0); |
| 2681 | switch (PA.getAA()->alias(Arg, EarlierArg)) { |
| 2682 | case AliasAnalysis::MustAlias: |
| 2683 | Changed = true; |
| 2684 | // If the load has a builtin retain, insert a plain retain for it. |
| 2685 | if (Class == IC_LoadWeakRetained) { |
| 2686 | CallInst *CI = |
| 2687 | CallInst::Create(getRetainCallee(F.getParent()), EarlierCall, |
| 2688 | "", Call); |
| 2689 | CI->setTailCall(); |
| 2690 | } |
| 2691 | // Zap the fully redundant load. |
| 2692 | Call->replaceAllUsesWith(EarlierCall->getArgOperand(1)); |
| 2693 | Call->eraseFromParent(); |
| 2694 | goto clobbered; |
| 2695 | case AliasAnalysis::MayAlias: |
| 2696 | case AliasAnalysis::PartialAlias: |
| 2697 | goto clobbered; |
| 2698 | case AliasAnalysis::NoAlias: |
| 2699 | break; |
| 2700 | } |
| 2701 | break; |
| 2702 | } |
| 2703 | case IC_MoveWeak: |
| 2704 | case IC_CopyWeak: |
| 2705 | // TOOD: Grab the copied value. |
| 2706 | goto clobbered; |
| 2707 | case IC_AutoreleasepoolPush: |
| 2708 | case IC_None: |
John McCall | 20182ac | 2013-03-22 21:38:36 +0000 | [diff] [blame] | 2709 | case IC_IntrinsicUser: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2710 | case IC_User: |
| 2711 | // Weak pointers are only modified through the weak entry points |
| 2712 | // (and arbitrary calls, which could call the weak entry points). |
| 2713 | break; |
| 2714 | default: |
| 2715 | // Anything else could modify the weak pointer. |
| 2716 | goto clobbered; |
| 2717 | } |
| 2718 | } |
| 2719 | clobbered:; |
| 2720 | } |
| 2721 | |
| 2722 | // Then, for each destroyWeak with an alloca operand, check to see if |
| 2723 | // the alloca and all its users can be zapped. |
| 2724 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 2725 | Instruction *Inst = &*I++; |
| 2726 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 2727 | if (Class != IC_DestroyWeak) |
| 2728 | continue; |
| 2729 | |
| 2730 | CallInst *Call = cast<CallInst>(Inst); |
| 2731 | Value *Arg = Call->getArgOperand(0); |
| 2732 | if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) { |
| 2733 | for (Value::use_iterator UI = Alloca->use_begin(), |
| 2734 | UE = Alloca->use_end(); UI != UE; ++UI) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2735 | const Instruction *UserInst = cast<Instruction>(*UI); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2736 | switch (GetBasicInstructionClass(UserInst)) { |
| 2737 | case IC_InitWeak: |
| 2738 | case IC_StoreWeak: |
| 2739 | case IC_DestroyWeak: |
| 2740 | continue; |
| 2741 | default: |
| 2742 | goto done; |
| 2743 | } |
| 2744 | } |
| 2745 | Changed = true; |
| 2746 | for (Value::use_iterator UI = Alloca->use_begin(), |
| 2747 | UE = Alloca->use_end(); UI != UE; ) { |
| 2748 | CallInst *UserInst = cast<CallInst>(*UI++); |
Dan Gohman | 14862c3 | 2012-05-18 22:17:29 +0000 | [diff] [blame] | 2749 | switch (GetBasicInstructionClass(UserInst)) { |
| 2750 | case IC_InitWeak: |
| 2751 | case IC_StoreWeak: |
| 2752 | // These functions return their second argument. |
| 2753 | UserInst->replaceAllUsesWith(UserInst->getArgOperand(1)); |
| 2754 | break; |
| 2755 | case IC_DestroyWeak: |
| 2756 | // No return value. |
| 2757 | break; |
| 2758 | default: |
Dan Gohman | 9c97eea0 | 2012-05-21 17:41:28 +0000 | [diff] [blame] | 2759 | llvm_unreachable("alloca really is used!"); |
Dan Gohman | 14862c3 | 2012-05-18 22:17:29 +0000 | [diff] [blame] | 2760 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2761 | UserInst->eraseFromParent(); |
| 2762 | } |
| 2763 | Alloca->eraseFromParent(); |
| 2764 | done:; |
| 2765 | } |
| 2766 | } |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2767 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 2768 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2769 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2770 | } |
| 2771 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2772 | /// Identify program paths which execute sequences of retains and releases which |
| 2773 | /// can be eliminated. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2774 | bool ObjCARCOpt::OptimizeSequences(Function &F) { |
| 2775 | /// Releases, Retains - These are used to store the results of the main flow |
| 2776 | /// analysis. These use Value* as the key instead of Instruction* so that the |
| 2777 | /// map stays valid when we get around to rewriting code and calls get |
| 2778 | /// replaced by arguments. |
| 2779 | DenseMap<Value *, RRInfo> Releases; |
| 2780 | MapVector<Value *, RRInfo> Retains; |
| 2781 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2782 | /// This is used during the traversal of the function to track the |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2783 | /// states for each identified object at each block. |
| 2784 | DenseMap<const BasicBlock *, BBState> BBStates; |
| 2785 | |
| 2786 | // Analyze the CFG of the function, and all instructions. |
| 2787 | bool NestingDetected = Visit(F, BBStates, Retains, Releases); |
| 2788 | |
| 2789 | // Transform. |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2790 | return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) && |
| 2791 | NestingDetected; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2792 | } |
| 2793 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2794 | /// Look for this pattern: |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 2795 | /// \code |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2796 | /// %call = call i8* @something(...) |
| 2797 | /// %2 = call i8* @objc_retain(i8* %call) |
| 2798 | /// %3 = call i8* @objc_autorelease(i8* %2) |
| 2799 | /// ret i8* %3 |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 2800 | /// \endcode |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2801 | /// And delete the retain and autorelease. |
| 2802 | /// |
| 2803 | /// Otherwise if it's just this: |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 2804 | /// \code |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2805 | /// %3 = call i8* @objc_autorelease(i8* %2) |
| 2806 | /// ret i8* %3 |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 2807 | /// \endcode |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2808 | /// convert the autorelease to autoreleaseRV. |
| 2809 | void ObjCARCOpt::OptimizeReturns(Function &F) { |
| 2810 | if (!F.getReturnType()->isPointerTy()) |
| 2811 | return; |
| 2812 | |
| 2813 | SmallPtrSet<Instruction *, 4> DependingInstructions; |
| 2814 | SmallPtrSet<const BasicBlock *, 4> Visited; |
| 2815 | for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { |
| 2816 | BasicBlock *BB = FI; |
| 2817 | ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back()); |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 2818 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 2819 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n"); |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 2820 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2821 | if (!Ret) continue; |
| 2822 | |
| 2823 | const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0)); |
| 2824 | FindDependencies(NeedsPositiveRetainCount, Arg, |
| 2825 | BB, Ret, DependingInstructions, Visited, PA); |
| 2826 | if (DependingInstructions.size() != 1) |
| 2827 | goto next_block; |
| 2828 | |
| 2829 | { |
| 2830 | CallInst *Autorelease = |
| 2831 | dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); |
| 2832 | if (!Autorelease) |
| 2833 | goto next_block; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2834 | InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2835 | if (!IsAutorelease(AutoreleaseClass)) |
| 2836 | goto next_block; |
| 2837 | if (GetObjCArg(Autorelease) != Arg) |
| 2838 | goto next_block; |
| 2839 | |
| 2840 | DependingInstructions.clear(); |
| 2841 | Visited.clear(); |
| 2842 | |
| 2843 | // Check that there is nothing that can affect the reference |
| 2844 | // count between the autorelease and the retain. |
| 2845 | FindDependencies(CanChangeRetainCount, Arg, |
| 2846 | BB, Autorelease, DependingInstructions, Visited, PA); |
| 2847 | if (DependingInstructions.size() != 1) |
| 2848 | goto next_block; |
| 2849 | |
| 2850 | { |
| 2851 | CallInst *Retain = |
| 2852 | dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); |
| 2853 | |
| 2854 | // Check that we found a retain with the same argument. |
| 2855 | if (!Retain || |
| 2856 | !IsRetain(GetBasicInstructionClass(Retain)) || |
| 2857 | GetObjCArg(Retain) != Arg) |
| 2858 | goto next_block; |
| 2859 | |
| 2860 | DependingInstructions.clear(); |
| 2861 | Visited.clear(); |
| 2862 | |
| 2863 | // Convert the autorelease to an autoreleaseRV, since it's |
| 2864 | // returning the value. |
| 2865 | if (AutoreleaseClass == IC_Autorelease) { |
Michael Gottesman | a6cb018 | 2013-01-10 02:03:50 +0000 | [diff] [blame] | 2866 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease " |
| 2867 | "=> autoreleaseRV since it's returning a value.\n" |
| 2868 | " In: " << *Autorelease |
| 2869 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2870 | Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent())); |
Michael Gottesman | a6cb018 | 2013-01-10 02:03:50 +0000 | [diff] [blame] | 2871 | DEBUG(dbgs() << " Out: " << *Autorelease |
| 2872 | << "\n"); |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 2873 | Autorelease->setTailCall(); // Always tail call autoreleaseRV. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2874 | AutoreleaseClass = IC_AutoreleaseRV; |
| 2875 | } |
| 2876 | |
| 2877 | // Check that there is nothing that can affect the reference |
| 2878 | // count between the retain and the call. |
Dan Gohman | 4ac148d | 2011-09-29 22:27:34 +0000 | [diff] [blame] | 2879 | // Note that Retain need not be in BB. |
| 2880 | FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain, |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2881 | DependingInstructions, Visited, PA); |
| 2882 | if (DependingInstructions.size() != 1) |
| 2883 | goto next_block; |
| 2884 | |
| 2885 | { |
| 2886 | CallInst *Call = |
| 2887 | dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); |
| 2888 | |
| 2889 | // Check that the pointer is the return value of the call. |
| 2890 | if (!Call || Arg != Call) |
| 2891 | goto next_block; |
| 2892 | |
| 2893 | // Check that the call is a regular call. |
| 2894 | InstructionClass Class = GetBasicInstructionClass(Call); |
| 2895 | if (Class != IC_CallOrUser && Class != IC_Call) |
| 2896 | goto next_block; |
| 2897 | |
| 2898 | // If so, we can zap the retain and autorelease. |
| 2899 | Changed = true; |
| 2900 | ++NumRets; |
Michael Gottesman | d61a3b2 | 2013-01-07 00:04:56 +0000 | [diff] [blame] | 2901 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain |
| 2902 | << "\n Erasing: " |
| 2903 | << *Autorelease << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2904 | EraseInstruction(Retain); |
| 2905 | EraseInstruction(Autorelease); |
| 2906 | } |
| 2907 | } |
| 2908 | } |
| 2909 | |
| 2910 | next_block: |
| 2911 | DependingInstructions.clear(); |
| 2912 | Visited.clear(); |
| 2913 | } |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2914 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 2915 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2916 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2917 | } |
| 2918 | |
| 2919 | bool ObjCARCOpt::doInitialization(Module &M) { |
| 2920 | if (!EnableARCOpts) |
| 2921 | return false; |
| 2922 | |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 2923 | // If nothing in the Module uses ARC, don't do anything. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 2924 | Run = ModuleHasARC(M); |
| 2925 | if (!Run) |
| 2926 | return false; |
| 2927 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2928 | // Identify the imprecise release metadata kind. |
| 2929 | ImpreciseReleaseMDKind = |
| 2930 | M.getContext().getMDKindID("clang.imprecise_release"); |
Dan Gohman | a7107f9 | 2011-10-17 22:53:25 +0000 | [diff] [blame] | 2931 | CopyOnEscapeMDKind = |
| 2932 | M.getContext().getMDKindID("clang.arc.copy_on_escape"); |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 2933 | NoObjCARCExceptionsMDKind = |
| 2934 | M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions"); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2935 | #ifdef ARC_ANNOTATIONS |
| 2936 | ARCAnnotationBottomUpMDKind = |
| 2937 | M.getContext().getMDKindID("llvm.arc.annotation.bottomup"); |
| 2938 | ARCAnnotationTopDownMDKind = |
| 2939 | M.getContext().getMDKindID("llvm.arc.annotation.topdown"); |
| 2940 | ARCAnnotationProvenanceSourceMDKind = |
| 2941 | M.getContext().getMDKindID("llvm.arc.annotation.provenancesource"); |
| 2942 | #endif // ARC_ANNOTATIONS |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2943 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2944 | // Intuitively, objc_retain and others are nocapture, however in practice |
| 2945 | // they are not, because they return their argument value. And objc_release |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2946 | // calls finalizers which can have arbitrary side effects. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2947 | |
| 2948 | // These are initialized lazily. |
| 2949 | RetainRVCallee = 0; |
| 2950 | AutoreleaseRVCallee = 0; |
| 2951 | ReleaseCallee = 0; |
| 2952 | RetainCallee = 0; |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2953 | RetainBlockCallee = 0; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2954 | AutoreleaseCallee = 0; |
| 2955 | |
| 2956 | return false; |
| 2957 | } |
| 2958 | |
| 2959 | bool ObjCARCOpt::runOnFunction(Function &F) { |
| 2960 | if (!EnableARCOpts) |
| 2961 | return false; |
| 2962 | |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 2963 | // If nothing in the Module uses ARC, don't do anything. |
| 2964 | if (!Run) |
| 2965 | return false; |
| 2966 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2967 | Changed = false; |
| 2968 | |
Michael Gottesman | b24bdef | 2013-01-12 02:57:16 +0000 | [diff] [blame] | 2969 | DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n"); |
| 2970 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2971 | PA.setAA(&getAnalysis<AliasAnalysis>()); |
| 2972 | |
| 2973 | // This pass performs several distinct transformations. As a compile-time aid |
| 2974 | // when compiling code that isn't ObjC, skip these if the relevant ObjC |
| 2975 | // library functions aren't declared. |
| 2976 | |
| 2977 | // Preliminary optimizations. This also computs UsedInThisFunction. |
| 2978 | OptimizeIndividualCalls(F); |
| 2979 | |
| 2980 | // Optimizations for weak pointers. |
| 2981 | if (UsedInThisFunction & ((1 << IC_LoadWeak) | |
| 2982 | (1 << IC_LoadWeakRetained) | |
| 2983 | (1 << IC_StoreWeak) | |
| 2984 | (1 << IC_InitWeak) | |
| 2985 | (1 << IC_CopyWeak) | |
| 2986 | (1 << IC_MoveWeak) | |
| 2987 | (1 << IC_DestroyWeak))) |
| 2988 | OptimizeWeakCalls(F); |
| 2989 | |
| 2990 | // Optimizations for retain+release pairs. |
| 2991 | if (UsedInThisFunction & ((1 << IC_Retain) | |
| 2992 | (1 << IC_RetainRV) | |
| 2993 | (1 << IC_RetainBlock))) |
| 2994 | if (UsedInThisFunction & (1 << IC_Release)) |
| 2995 | // Run OptimizeSequences until it either stops making changes or |
| 2996 | // no retain+release pair nesting is detected. |
| 2997 | while (OptimizeSequences(F)) {} |
| 2998 | |
| 2999 | // Optimizations if objc_autorelease is used. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3000 | if (UsedInThisFunction & ((1 << IC_Autorelease) | |
| 3001 | (1 << IC_AutoreleaseRV))) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3002 | OptimizeReturns(F); |
| 3003 | |
Michael Gottesman | b24bdef | 2013-01-12 02:57:16 +0000 | [diff] [blame] | 3004 | DEBUG(dbgs() << "\n"); |
| 3005 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3006 | return Changed; |
| 3007 | } |
| 3008 | |
| 3009 | void ObjCARCOpt::releaseMemory() { |
| 3010 | PA.clear(); |
| 3011 | } |
| 3012 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3013 | /// @} |
| 3014 | /// |