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