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