Michael Gottesman | 79d8d81 | 2013-01-28 01:35:51 +0000 | [diff] [blame] | 1 | //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 9 | /// \file |
| 10 | /// This file defines ObjC ARC optimizations. ARC stands for Automatic |
| 11 | /// Reference Counting and is a system for managing reference counts for objects |
| 12 | /// in Objective C. |
| 13 | /// |
| 14 | /// The optimizations performed include elimination of redundant, partially |
| 15 | /// redundant, and inconsequential reference count operations, elimination of |
| 16 | /// redundant weak pointer operations, pattern-matching and replacement of |
| 17 | /// low-level operations into higher-level operations, and numerous minor |
| 18 | /// simplifications. |
| 19 | /// |
| 20 | /// This file also defines a simple ARC-aware AliasAnalysis. |
| 21 | /// |
| 22 | /// WARNING: This file knows about certain library functions. It recognizes them |
| 23 | /// by name, and hardwires knowledge of their semantics. |
| 24 | /// |
| 25 | /// WARNING: This file knows about how certain Objective-C library functions are |
| 26 | /// used. Naive LLVM IR transformations which would otherwise be |
| 27 | /// behavior-preserving may break these assumptions. |
| 28 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 29 | //===----------------------------------------------------------------------===// |
| 30 | |
Michael Gottesman | 08904e3 | 2013-01-28 03:28:38 +0000 | [diff] [blame] | 31 | #define DEBUG_TYPE "objc-arc-opts" |
| 32 | #include "ObjCARC.h" |
Michael Gottesman | 294e7da | 2013-01-28 05:51:54 +0000 | [diff] [blame^] | 33 | #include "ObjCARCAliasAnalysis.h" |
Michael Gottesman | fa0939f | 2013-01-28 04:12:07 +0000 | [diff] [blame] | 34 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 35 | #include "llvm/ADT/DenseMap.h" |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 36 | #include "llvm/ADT/SmallPtrSet.h" |
Michael Gottesman | fa0939f | 2013-01-28 04:12:07 +0000 | [diff] [blame] | 37 | #include "llvm/ADT/STLExtras.h" |
| 38 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 39 | using namespace llvm; |
Michael Gottesman | 08904e3 | 2013-01-28 03:28:38 +0000 | [diff] [blame] | 40 | using namespace llvm::objcarc; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 41 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 42 | /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific. |
| 43 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 44 | |
| 45 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 46 | /// \brief An associative container with fast insertion-order (deterministic) |
| 47 | /// iteration over its elements. Plus the special blot operation. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 48 | template<class KeyT, class ValueT> |
| 49 | class MapVector { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 50 | /// Map keys to indices in Vector. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 51 | typedef DenseMap<KeyT, size_t> MapTy; |
| 52 | MapTy Map; |
| 53 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 54 | typedef std::vector<std::pair<KeyT, ValueT> > VectorTy; |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 55 | /// Keys and values. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 56 | VectorTy Vector; |
| 57 | |
| 58 | public: |
| 59 | typedef typename VectorTy::iterator iterator; |
| 60 | typedef typename VectorTy::const_iterator const_iterator; |
| 61 | iterator begin() { return Vector.begin(); } |
| 62 | iterator end() { return Vector.end(); } |
| 63 | const_iterator begin() const { return Vector.begin(); } |
| 64 | const_iterator end() const { return Vector.end(); } |
| 65 | |
| 66 | #ifdef XDEBUG |
| 67 | ~MapVector() { |
| 68 | assert(Vector.size() >= Map.size()); // May differ due to blotting. |
| 69 | for (typename MapTy::const_iterator I = Map.begin(), E = Map.end(); |
| 70 | I != E; ++I) { |
| 71 | assert(I->second < Vector.size()); |
| 72 | assert(Vector[I->second].first == I->first); |
| 73 | } |
| 74 | for (typename VectorTy::const_iterator I = Vector.begin(), |
| 75 | E = Vector.end(); I != E; ++I) |
| 76 | assert(!I->first || |
| 77 | (Map.count(I->first) && |
| 78 | Map[I->first] == size_t(I - Vector.begin()))); |
| 79 | } |
| 80 | #endif |
| 81 | |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 82 | ValueT &operator[](const KeyT &Arg) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 83 | std::pair<typename MapTy::iterator, bool> Pair = |
| 84 | Map.insert(std::make_pair(Arg, size_t(0))); |
| 85 | if (Pair.second) { |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 86 | size_t Num = Vector.size(); |
| 87 | Pair.first->second = Num; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 88 | Vector.push_back(std::make_pair(Arg, ValueT())); |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 89 | return Vector[Num].second; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 90 | } |
| 91 | return Vector[Pair.first->second].second; |
| 92 | } |
| 93 | |
| 94 | std::pair<iterator, bool> |
| 95 | insert(const std::pair<KeyT, ValueT> &InsertPair) { |
| 96 | std::pair<typename MapTy::iterator, bool> Pair = |
| 97 | Map.insert(std::make_pair(InsertPair.first, size_t(0))); |
| 98 | if (Pair.second) { |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 99 | size_t Num = Vector.size(); |
| 100 | Pair.first->second = Num; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 101 | Vector.push_back(InsertPair); |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 102 | return std::make_pair(Vector.begin() + Num, true); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 103 | } |
| 104 | return std::make_pair(Vector.begin() + Pair.first->second, false); |
| 105 | } |
| 106 | |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 107 | const_iterator find(const KeyT &Key) const { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 108 | typename MapTy::const_iterator It = Map.find(Key); |
| 109 | if (It == Map.end()) return Vector.end(); |
| 110 | return Vector.begin() + It->second; |
| 111 | } |
| 112 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 113 | /// This is similar to erase, but instead of removing the element from the |
| 114 | /// vector, it just zeros out the key in the vector. This leaves iterators |
| 115 | /// intact, but clients must be prepared for zeroed-out keys when iterating. |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 116 | void blot(const KeyT &Key) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 117 | typename MapTy::iterator It = Map.find(Key); |
| 118 | if (It == Map.end()) return; |
| 119 | Vector[It->second].first = KeyT(); |
| 120 | Map.erase(It); |
| 121 | } |
| 122 | |
| 123 | void clear() { |
| 124 | Map.clear(); |
| 125 | Vector.clear(); |
| 126 | } |
| 127 | }; |
| 128 | } |
| 129 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 130 | /// @} |
| 131 | /// |
| 132 | /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC. |
| 133 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 134 | |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 135 | #include "llvm/IR/Intrinsics.h" |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 136 | #include "llvm/Support/CallSite.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 137 | #include "llvm/Transforms/Utils/Local.h" |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 138 | |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 139 | /// \brief Test whether the given value is possible a retainable object pointer. |
| 140 | static bool IsPotentialRetainableObjPtr(const Value *Op) { |
| 141 | // Pointers to static or stack storage are not valid retainable object pointers. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 142 | if (isa<Constant>(Op) || isa<AllocaInst>(Op)) |
| 143 | return false; |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 144 | // Special arguments can not be a valid retainable object pointer. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 145 | if (const Argument *Arg = dyn_cast<Argument>(Op)) |
| 146 | if (Arg->hasByValAttr() || |
| 147 | Arg->hasNestAttr() || |
| 148 | Arg->hasStructRetAttr()) |
| 149 | return false; |
Dan Gohman | bd944b4 | 2011-12-14 19:10:53 +0000 | [diff] [blame] | 150 | // Only consider values with pointer types. |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 151 | // |
Dan Gohman | bd944b4 | 2011-12-14 19:10:53 +0000 | [diff] [blame] | 152 | // It seemes intuitive to exclude function pointer types as well, since |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 153 | // functions are never retainable object pointers, however clang occasionally |
| 154 | // bitcasts retainable object pointers to function-pointer type temporarily. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 155 | PointerType *Ty = dyn_cast<PointerType>(Op->getType()); |
Dan Gohman | bd944b4 | 2011-12-14 19:10:53 +0000 | [diff] [blame] | 156 | if (!Ty) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 157 | return false; |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 158 | // Conservatively assume anything else is a potential retainable object pointer. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 159 | return true; |
| 160 | } |
| 161 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 162 | /// \brief Helper for GetInstructionClass. Determines what kind of construct CS |
| 163 | /// is. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 164 | static InstructionClass GetCallSiteClass(ImmutableCallSite CS) { |
| 165 | for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); |
| 166 | I != E; ++I) |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 167 | if (IsPotentialRetainableObjPtr(*I)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 168 | return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser; |
| 169 | |
| 170 | return CS.onlyReadsMemory() ? IC_None : IC_Call; |
| 171 | } |
| 172 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 173 | /// \brief Determine what kind of construct V is. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 174 | static InstructionClass GetInstructionClass(const Value *V) { |
| 175 | if (const Instruction *I = dyn_cast<Instruction>(V)) { |
| 176 | // Any instruction other than bitcast and gep with a pointer operand have a |
| 177 | // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer |
| 178 | // to a subsequent use, rather than using it themselves, in this sense. |
| 179 | // As a short cut, several other opcodes are known to have no pointer |
| 180 | // operands of interest. And ret is never followed by a release, so it's |
| 181 | // not interesting to examine. |
| 182 | switch (I->getOpcode()) { |
| 183 | case Instruction::Call: { |
| 184 | const CallInst *CI = cast<CallInst>(I); |
| 185 | // Check for calls to special functions. |
| 186 | if (const Function *F = CI->getCalledFunction()) { |
| 187 | InstructionClass Class = GetFunctionClass(F); |
| 188 | if (Class != IC_CallOrUser) |
| 189 | return Class; |
| 190 | |
| 191 | // None of the intrinsic functions do objc_release. For intrinsics, the |
| 192 | // only question is whether or not they may be users. |
| 193 | switch (F->getIntrinsicID()) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 194 | case Intrinsic::returnaddress: case Intrinsic::frameaddress: |
| 195 | case Intrinsic::stacksave: case Intrinsic::stackrestore: |
| 196 | case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend: |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 197 | case Intrinsic::objectsize: case Intrinsic::prefetch: |
| 198 | case Intrinsic::stackprotector: |
| 199 | case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64: |
| 200 | case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa: |
| 201 | case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext: |
| 202 | case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline: |
| 203 | case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: |
| 204 | case Intrinsic::invariant_start: case Intrinsic::invariant_end: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 205 | // Don't let dbg info affect our results. |
| 206 | case Intrinsic::dbg_declare: case Intrinsic::dbg_value: |
| 207 | // Short cut: Some intrinsics obviously don't use ObjC pointers. |
| 208 | return IC_None; |
| 209 | default: |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 210 | break; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 211 | } |
| 212 | } |
| 213 | return GetCallSiteClass(CI); |
| 214 | } |
| 215 | case Instruction::Invoke: |
| 216 | return GetCallSiteClass(cast<InvokeInst>(I)); |
| 217 | case Instruction::BitCast: |
| 218 | case Instruction::GetElementPtr: |
| 219 | case Instruction::Select: case Instruction::PHI: |
| 220 | case Instruction::Ret: case Instruction::Br: |
| 221 | case Instruction::Switch: case Instruction::IndirectBr: |
| 222 | case Instruction::Alloca: case Instruction::VAArg: |
| 223 | case Instruction::Add: case Instruction::FAdd: |
| 224 | case Instruction::Sub: case Instruction::FSub: |
| 225 | case Instruction::Mul: case Instruction::FMul: |
| 226 | case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv: |
| 227 | case Instruction::SRem: case Instruction::URem: case Instruction::FRem: |
| 228 | case Instruction::Shl: case Instruction::LShr: case Instruction::AShr: |
| 229 | case Instruction::And: case Instruction::Or: case Instruction::Xor: |
| 230 | case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc: |
| 231 | case Instruction::IntToPtr: case Instruction::FCmp: |
| 232 | case Instruction::FPTrunc: case Instruction::FPExt: |
| 233 | case Instruction::FPToUI: case Instruction::FPToSI: |
| 234 | case Instruction::UIToFP: case Instruction::SIToFP: |
| 235 | case Instruction::InsertElement: case Instruction::ExtractElement: |
| 236 | case Instruction::ShuffleVector: |
| 237 | case Instruction::ExtractValue: |
| 238 | break; |
| 239 | case Instruction::ICmp: |
| 240 | // Comparing a pointer with null, or any other constant, isn't an |
| 241 | // interesting use, because we don't care what the pointer points to, or |
| 242 | // about the values of any other dynamic reference-counted pointers. |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 243 | if (IsPotentialRetainableObjPtr(I->getOperand(1))) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 244 | return IC_User; |
| 245 | break; |
| 246 | default: |
| 247 | // For anything else, check all the operands. |
Dan Gohman | 4b8e8ce | 2011-08-22 17:29:37 +0000 | [diff] [blame] | 248 | // Note that this includes both operands of a Store: while the first |
| 249 | // operand isn't actually being dereferenced, it is being stored to |
| 250 | // memory where we can no longer track who might read it and dereference |
| 251 | // it, so we have to consider it potentially used. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 252 | for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end(); |
| 253 | OI != OE; ++OI) |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 254 | if (IsPotentialRetainableObjPtr(*OI)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 255 | return IC_User; |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | // Otherwise, it's totally inert for ARC purposes. |
| 260 | return IC_None; |
| 261 | } |
| 262 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 263 | /// \brief Erase the given instruction. |
| 264 | /// |
| 265 | /// Many ObjC calls return their argument verbatim, |
| 266 | /// so if it's such a call and the return value has users, replace them with the |
| 267 | /// argument value. |
| 268 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 269 | static void EraseInstruction(Instruction *CI) { |
| 270 | Value *OldArg = cast<CallInst>(CI)->getArgOperand(0); |
| 271 | |
| 272 | bool Unused = CI->use_empty(); |
| 273 | |
| 274 | if (!Unused) { |
| 275 | // Replace the return value with the argument. |
| 276 | assert(IsForwarding(GetBasicInstructionClass(CI)) && |
| 277 | "Can't delete non-forwarding instruction with users!"); |
| 278 | CI->replaceAllUsesWith(OldArg); |
| 279 | } |
| 280 | |
| 281 | CI->eraseFromParent(); |
| 282 | |
| 283 | if (Unused) |
| 284 | RecursivelyDeleteTriviallyDeadInstructions(OldArg); |
| 285 | } |
| 286 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 287 | /// \brief Assuming the given instruction is one of the special calls such as |
| 288 | /// objc_retain or objc_release, return the argument value, stripped of no-op |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 289 | /// casts and forwarding calls. |
| 290 | static Value *GetObjCArg(Value *Inst) { |
| 291 | return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0)); |
| 292 | } |
| 293 | |
Michael Gottesman | 87db3575 | 2013-01-18 23:02:45 +0000 | [diff] [blame] | 294 | /// \brief Return true if this value refers to a distinct and identifiable |
| 295 | /// object. |
| 296 | /// |
| 297 | /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses |
| 298 | /// special knowledge of ObjC conventions. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 299 | static bool IsObjCIdentifiedObject(const Value *V) { |
| 300 | // Assume that call results and arguments have their own "provenance". |
| 301 | // Constants (including GlobalVariables) and Allocas are never |
| 302 | // reference-counted. |
| 303 | if (isa<CallInst>(V) || isa<InvokeInst>(V) || |
| 304 | isa<Argument>(V) || isa<Constant>(V) || |
| 305 | isa<AllocaInst>(V)) |
| 306 | return true; |
| 307 | |
| 308 | if (const LoadInst *LI = dyn_cast<LoadInst>(V)) { |
| 309 | const Value *Pointer = |
| 310 | StripPointerCastsAndObjCCalls(LI->getPointerOperand()); |
| 311 | if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) { |
Dan Gohman | 56e1cef | 2011-08-22 17:29:11 +0000 | [diff] [blame] | 312 | // A constant pointer can't be pointing to an object on the heap. It may |
| 313 | // be reference-counted, but it won't be deleted. |
| 314 | if (GV->isConstant()) |
| 315 | return true; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 316 | StringRef Name = GV->getName(); |
| 317 | // These special variables are known to hold values which are not |
| 318 | // reference-counted pointers. |
| 319 | if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") || |
| 320 | Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") || |
| 321 | Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") || |
| 322 | Name.startswith("\01L_OBJC_METH_VAR_NAME_") || |
| 323 | Name.startswith("\01l_objc_msgSend_fixup_")) |
| 324 | return true; |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | return false; |
| 329 | } |
| 330 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 331 | /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon |
| 332 | /// as it finds a value with multiple uses. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 333 | static const Value *FindSingleUseIdentifiedObject(const Value *Arg) { |
| 334 | if (Arg->hasOneUse()) { |
| 335 | if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg)) |
| 336 | return FindSingleUseIdentifiedObject(BC->getOperand(0)); |
| 337 | if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg)) |
| 338 | if (GEP->hasAllZeroIndices()) |
| 339 | return FindSingleUseIdentifiedObject(GEP->getPointerOperand()); |
| 340 | if (IsForwarding(GetBasicInstructionClass(Arg))) |
| 341 | return FindSingleUseIdentifiedObject( |
| 342 | cast<CallInst>(Arg)->getArgOperand(0)); |
| 343 | if (!IsObjCIdentifiedObject(Arg)) |
| 344 | return 0; |
| 345 | return Arg; |
| 346 | } |
| 347 | |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 348 | // If we found an identifiable object but it has multiple uses, but they are |
| 349 | // 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] | 350 | if (IsObjCIdentifiedObject(Arg)) { |
| 351 | for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end(); |
| 352 | UI != UE; ++UI) { |
| 353 | const User *U = *UI; |
| 354 | if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg) |
| 355 | return 0; |
| 356 | } |
| 357 | |
| 358 | return Arg; |
| 359 | } |
| 360 | |
| 361 | return 0; |
| 362 | } |
| 363 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 364 | /// \brief Test whether the given pointer, which is an Objective C block |
| 365 | /// pointer, does not "escape". |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 366 | /// |
| 367 | /// This differs from regular escape analysis in that a use as an |
| 368 | /// argument to a call is not considered an escape. |
| 369 | /// |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 370 | static bool DoesObjCBlockEscape(const Value *BlockPtr) { |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 371 | |
| 372 | DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n"); |
| 373 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 374 | // Walk the def-use chains. |
| 375 | SmallVector<const Value *, 4> Worklist; |
| 376 | Worklist.push_back(BlockPtr); |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 377 | |
| 378 | // Ensure we do not visit any value twice. |
| 379 | SmallPtrSet<const Value *, 4> VisitedSet; |
| 380 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 381 | do { |
| 382 | const Value *V = Worklist.pop_back_val(); |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 383 | |
| 384 | DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n"); |
| 385 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 386 | for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end(); |
| 387 | UI != UE; ++UI) { |
| 388 | const User *UUser = *UI; |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 389 | |
| 390 | DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n"); |
| 391 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 392 | // Special - Use by a call (callee or argument) is not considered |
| 393 | // to be an escape. |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 394 | switch (GetBasicInstructionClass(UUser)) { |
| 395 | case IC_StoreWeak: |
| 396 | case IC_InitWeak: |
| 397 | case IC_StoreStrong: |
| 398 | case IC_Autorelease: |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 399 | case IC_AutoreleaseRV: { |
| 400 | DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. " |
| 401 | "Block Escapes!\n"); |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 402 | // These special functions make copies of their pointer arguments. |
| 403 | return true; |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 404 | } |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 405 | case IC_User: |
| 406 | case IC_None: |
| 407 | // Use by an instruction which copies the value is an escape if the |
| 408 | // result is an escape. |
| 409 | if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) || |
| 410 | isa<PHINode>(UUser) || isa<SelectInst>(UUser)) { |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 411 | |
Michael Gottesman | e9145d3 | 2013-01-14 19:18:39 +0000 | [diff] [blame] | 412 | if (!VisitedSet.insert(UUser)) { |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 413 | DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes " |
| 414 | "if result escapes. Adding to list.\n"); |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 415 | Worklist.push_back(UUser); |
| 416 | } else { |
| 417 | DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n"); |
| 418 | } |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 419 | continue; |
| 420 | } |
| 421 | // Use by a load is not an escape. |
| 422 | if (isa<LoadInst>(UUser)) |
| 423 | continue; |
| 424 | // Use by a store is not an escape if the use is the address. |
| 425 | if (const StoreInst *SI = dyn_cast<StoreInst>(UUser)) |
| 426 | if (V != SI->getValueOperand()) |
| 427 | continue; |
| 428 | break; |
| 429 | default: |
| 430 | // Regular calls and other stuff are not considered escapes. |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 431 | continue; |
| 432 | } |
Dan Gohman | eb6e015 | 2012-02-13 22:57:02 +0000 | [diff] [blame] | 433 | // Otherwise, conservatively assume an escape. |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 434 | DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n"); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 435 | return true; |
| 436 | } |
| 437 | } while (!Worklist.empty()); |
| 438 | |
| 439 | // No escapes found. |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 440 | DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n"); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 441 | return false; |
| 442 | } |
| 443 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 444 | /// @} |
| 445 | /// |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 446 | /// \defgroup ARCOpt ARC Optimization. |
| 447 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 448 | |
| 449 | // TODO: On code like this: |
| 450 | // |
| 451 | // objc_retain(%x) |
| 452 | // stuff_that_cannot_release() |
| 453 | // objc_autorelease(%x) |
| 454 | // stuff_that_cannot_release() |
| 455 | // objc_retain(%x) |
| 456 | // stuff_that_cannot_release() |
| 457 | // objc_autorelease(%x) |
| 458 | // |
| 459 | // The second retain and autorelease can be deleted. |
| 460 | |
| 461 | // TODO: It should be possible to delete |
| 462 | // objc_autoreleasePoolPush and objc_autoreleasePoolPop |
| 463 | // pairs if nothing is actually autoreleased between them. Also, autorelease |
| 464 | // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code |
| 465 | // after inlining) can be turned into plain release calls. |
| 466 | |
| 467 | // TODO: Critical-edge splitting. If the optimial insertion point is |
| 468 | // a critical edge, the current algorithm has to fail, because it doesn't |
| 469 | // know how to split edges. It should be possible to make the optimizer |
| 470 | // think in terms of edges, rather than blocks, and then split critical |
| 471 | // edges on demand. |
| 472 | |
| 473 | // TODO: OptimizeSequences could generalized to be Interprocedural. |
| 474 | |
| 475 | // TODO: Recognize that a bunch of other objc runtime calls have |
| 476 | // non-escaping arguments and non-releasing arguments, and may be |
| 477 | // non-autoreleasing. |
| 478 | |
| 479 | // TODO: Sink autorelease calls as far as possible. Unfortunately we |
| 480 | // usually can't sink them past other calls, which would be the main |
| 481 | // case where it would be useful. |
| 482 | |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 483 | // TODO: The pointer returned from objc_loadWeakRetained is retained. |
| 484 | |
| 485 | // TODO: Delete release+retain pairs (rare). |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 486 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 487 | #include "llvm/ADT/SmallPtrSet.h" |
| 488 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 489 | #include "llvm/IR/LLVMContext.h" |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 490 | #include "llvm/Support/CFG.h" |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 491 | |
| 492 | STATISTIC(NumNoops, "Number of no-op objc calls eliminated"); |
| 493 | STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated"); |
| 494 | STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases"); |
| 495 | STATISTIC(NumRets, "Number of return value forwarding " |
| 496 | "retain+autoreleaes eliminated"); |
| 497 | STATISTIC(NumRRs, "Number of retain+release paths eliminated"); |
| 498 | STATISTIC(NumPeeps, "Number of calls peephole-optimized"); |
| 499 | |
| 500 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 501 | /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same |
| 502 | /// techniques, except it uses special ObjC-specific reasoning about pointer |
| 503 | /// relationships. |
Michael Gottesman | 12780c2d | 2013-01-24 21:35:00 +0000 | [diff] [blame] | 504 | /// |
| 505 | /// In this context ``Provenance'' is defined as the history of an object's |
| 506 | /// ownership. Thus ``Provenance Analysis'' is defined by using the notion of |
| 507 | /// an ``independent provenance source'' of a pointer to determine whether or |
| 508 | /// not two pointers have the same provenance source and thus could |
| 509 | /// potentially be related. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 510 | class ProvenanceAnalysis { |
| 511 | AliasAnalysis *AA; |
| 512 | |
| 513 | typedef std::pair<const Value *, const Value *> ValuePairTy; |
| 514 | typedef DenseMap<ValuePairTy, bool> CachedResultsTy; |
| 515 | CachedResultsTy CachedResults; |
| 516 | |
| 517 | bool relatedCheck(const Value *A, const Value *B); |
| 518 | bool relatedSelect(const SelectInst *A, const Value *B); |
| 519 | bool relatedPHI(const PHINode *A, const Value *B); |
| 520 | |
Craig Topper | b1d83e8 | 2012-09-18 02:01:41 +0000 | [diff] [blame] | 521 | void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION; |
| 522 | ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 523 | |
| 524 | public: |
| 525 | ProvenanceAnalysis() {} |
| 526 | |
| 527 | void setAA(AliasAnalysis *aa) { AA = aa; } |
| 528 | |
| 529 | AliasAnalysis *getAA() const { return AA; } |
| 530 | |
| 531 | bool related(const Value *A, const Value *B); |
| 532 | |
| 533 | void clear() { |
| 534 | CachedResults.clear(); |
| 535 | } |
| 536 | }; |
| 537 | } |
| 538 | |
| 539 | bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) { |
| 540 | // If the values are Selects with the same condition, we can do a more precise |
| 541 | // check: just check for relations between the values on corresponding arms. |
| 542 | if (const SelectInst *SB = dyn_cast<SelectInst>(B)) |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 543 | if (A->getCondition() == SB->getCondition()) |
| 544 | return related(A->getTrueValue(), SB->getTrueValue()) || |
| 545 | related(A->getFalseValue(), SB->getFalseValue()); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 546 | |
| 547 | // Check both arms of the Select node individually. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 548 | return related(A->getTrueValue(), B) || |
| 549 | related(A->getFalseValue(), B); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 550 | } |
| 551 | |
| 552 | bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) { |
| 553 | // If the values are PHIs in the same block, we can do a more precise as well |
| 554 | // as efficient check: just check for relations between the values on |
| 555 | // corresponding edges. |
| 556 | if (const PHINode *PNB = dyn_cast<PHINode>(B)) |
| 557 | if (PNB->getParent() == A->getParent()) { |
| 558 | for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) |
| 559 | if (related(A->getIncomingValue(i), |
| 560 | PNB->getIncomingValueForBlock(A->getIncomingBlock(i)))) |
| 561 | return true; |
| 562 | return false; |
| 563 | } |
| 564 | |
| 565 | // Check each unique source of the PHI node against B. |
| 566 | SmallPtrSet<const Value *, 4> UniqueSrc; |
| 567 | for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) { |
| 568 | const Value *PV1 = A->getIncomingValue(i); |
| 569 | if (UniqueSrc.insert(PV1) && related(PV1, B)) |
| 570 | return true; |
| 571 | } |
| 572 | |
| 573 | // All of the arms checked out. |
| 574 | return false; |
| 575 | } |
| 576 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 577 | /// Test if the value of P, or any value covered by its provenance, is ever |
| 578 | /// stored within the function (not counting callees). |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 579 | static bool isStoredObjCPointer(const Value *P) { |
| 580 | SmallPtrSet<const Value *, 8> Visited; |
| 581 | SmallVector<const Value *, 8> Worklist; |
| 582 | Worklist.push_back(P); |
| 583 | Visited.insert(P); |
| 584 | do { |
| 585 | P = Worklist.pop_back_val(); |
| 586 | for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end(); |
| 587 | UI != UE; ++UI) { |
| 588 | const User *Ur = *UI; |
| 589 | if (isa<StoreInst>(Ur)) { |
| 590 | if (UI.getOperandNo() == 0) |
| 591 | // The pointer is stored. |
| 592 | return true; |
| 593 | // The pointed is stored through. |
| 594 | continue; |
| 595 | } |
| 596 | if (isa<CallInst>(Ur)) |
| 597 | // The pointer is passed as an argument, ignore this. |
| 598 | continue; |
| 599 | if (isa<PtrToIntInst>(P)) |
| 600 | // Assume the worst. |
| 601 | return true; |
| 602 | if (Visited.insert(Ur)) |
| 603 | Worklist.push_back(Ur); |
| 604 | } |
| 605 | } while (!Worklist.empty()); |
| 606 | |
| 607 | // Everything checked out. |
| 608 | return false; |
| 609 | } |
| 610 | |
| 611 | bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) { |
| 612 | // Skip past provenance pass-throughs. |
| 613 | A = GetUnderlyingObjCPtr(A); |
| 614 | B = GetUnderlyingObjCPtr(B); |
| 615 | |
| 616 | // Quick check. |
| 617 | if (A == B) |
| 618 | return true; |
| 619 | |
| 620 | // Ask regular AliasAnalysis, for a first approximation. |
| 621 | switch (AA->alias(A, B)) { |
| 622 | case AliasAnalysis::NoAlias: |
| 623 | return false; |
| 624 | case AliasAnalysis::MustAlias: |
| 625 | case AliasAnalysis::PartialAlias: |
| 626 | return true; |
| 627 | case AliasAnalysis::MayAlias: |
| 628 | break; |
| 629 | } |
| 630 | |
| 631 | bool AIsIdentified = IsObjCIdentifiedObject(A); |
| 632 | bool BIsIdentified = IsObjCIdentifiedObject(B); |
| 633 | |
| 634 | // An ObjC-Identified object can't alias a load if it is never locally stored. |
| 635 | if (AIsIdentified) { |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 636 | // Check for an obvious escape. |
| 637 | if (isa<LoadInst>(B)) |
| 638 | return isStoredObjCPointer(A); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 639 | if (BIsIdentified) { |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 640 | // Check for an obvious escape. |
| 641 | if (isa<LoadInst>(A)) |
| 642 | return isStoredObjCPointer(B); |
| 643 | // Both pointers are identified and escapes aren't an evident problem. |
| 644 | return false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 645 | } |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 646 | } else if (BIsIdentified) { |
| 647 | // Check for an obvious escape. |
| 648 | if (isa<LoadInst>(A)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 649 | return isStoredObjCPointer(B); |
| 650 | } |
| 651 | |
| 652 | // Special handling for PHI and Select. |
| 653 | if (const PHINode *PN = dyn_cast<PHINode>(A)) |
| 654 | return relatedPHI(PN, B); |
| 655 | if (const PHINode *PN = dyn_cast<PHINode>(B)) |
| 656 | return relatedPHI(PN, A); |
| 657 | if (const SelectInst *S = dyn_cast<SelectInst>(A)) |
| 658 | return relatedSelect(S, B); |
| 659 | if (const SelectInst *S = dyn_cast<SelectInst>(B)) |
| 660 | return relatedSelect(S, A); |
| 661 | |
| 662 | // Conservative. |
| 663 | return true; |
| 664 | } |
| 665 | |
| 666 | bool ProvenanceAnalysis::related(const Value *A, const Value *B) { |
| 667 | // Begin by inserting a conservative value into the map. If the insertion |
| 668 | // fails, we have the answer already. If it succeeds, leave it there until we |
| 669 | // compute the real answer to guard against recursive queries. |
| 670 | if (A > B) std::swap(A, B); |
| 671 | std::pair<CachedResultsTy::iterator, bool> Pair = |
| 672 | CachedResults.insert(std::make_pair(ValuePairTy(A, B), true)); |
| 673 | if (!Pair.second) |
| 674 | return Pair.first->second; |
| 675 | |
| 676 | bool Result = relatedCheck(A, B); |
| 677 | CachedResults[ValuePairTy(A, B)] = Result; |
| 678 | return Result; |
| 679 | } |
| 680 | |
| 681 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 682 | /// \enum Sequence |
| 683 | /// |
| 684 | /// \brief A sequence of states that a pointer may go through in which an |
| 685 | /// objc_retain and objc_release are actually needed. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 686 | enum Sequence { |
| 687 | S_None, |
| 688 | S_Retain, ///< objc_retain(x) |
| 689 | S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement |
| 690 | S_Use, ///< any use of x |
| 691 | S_Stop, ///< like S_Release, but code motion is stopped |
| 692 | S_Release, ///< objc_release(x) |
| 693 | S_MovableRelease ///< objc_release(x), !clang.imprecise_release |
| 694 | }; |
| 695 | } |
| 696 | |
| 697 | static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) { |
| 698 | // The easy cases. |
| 699 | if (A == B) |
| 700 | return A; |
| 701 | if (A == S_None || B == S_None) |
| 702 | return S_None; |
| 703 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 704 | if (A > B) std::swap(A, B); |
| 705 | if (TopDown) { |
| 706 | // Choose the side which is further along in the sequence. |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 707 | if ((A == S_Retain || A == S_CanRelease) && |
| 708 | (B == S_CanRelease || B == S_Use)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 709 | return B; |
| 710 | } else { |
| 711 | // Choose the side which is further along in the sequence. |
| 712 | if ((A == S_Use || A == S_CanRelease) && |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 713 | (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 714 | return A; |
| 715 | // If both sides are releases, choose the more conservative one. |
| 716 | if (A == S_Stop && (B == S_Release || B == S_MovableRelease)) |
| 717 | return A; |
| 718 | if (A == S_Release && B == S_MovableRelease) |
| 719 | return A; |
| 720 | } |
| 721 | |
| 722 | return S_None; |
| 723 | } |
| 724 | |
| 725 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 726 | /// \brief Unidirectional information about either a |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 727 | /// retain-decrement-use-release sequence or release-use-decrement-retain |
| 728 | /// reverese sequence. |
| 729 | struct RRInfo { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 730 | /// After an objc_retain, the reference count of the referenced |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 731 | /// object is known to be positive. Similarly, before an objc_release, the |
| 732 | /// reference count of the referenced object is known to be positive. If |
| 733 | /// there are retain-release pairs in code regions where the retain count |
| 734 | /// is known to be positive, they can be eliminated, regardless of any side |
| 735 | /// effects between them. |
| 736 | /// |
| 737 | /// Also, a retain+release pair nested within another retain+release |
| 738 | /// pair all on the known same pointer value can be eliminated, regardless |
| 739 | /// of any intervening side effects. |
| 740 | /// |
| 741 | /// KnownSafe is true when either of these conditions is satisfied. |
| 742 | bool KnownSafe; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 743 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 744 | /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain |
| 745 | /// calls). |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 746 | bool IsRetainBlock; |
| 747 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 748 | /// 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] | 749 | bool IsTailCallRelease; |
| 750 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 751 | /// If the Calls are objc_release calls and they all have a |
| 752 | /// clang.imprecise_release tag, this is the metadata tag. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 753 | MDNode *ReleaseMetadata; |
| 754 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 755 | /// For a top-down sequence, the set of objc_retains or |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 756 | /// objc_retainBlocks. For bottom-up, the set of objc_releases. |
| 757 | SmallPtrSet<Instruction *, 2> Calls; |
| 758 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 759 | /// The set of optimal insert positions for moving calls in the opposite |
| 760 | /// sequence. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 761 | SmallPtrSet<Instruction *, 2> ReverseInsertPts; |
| 762 | |
| 763 | RRInfo() : |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 764 | KnownSafe(false), IsRetainBlock(false), |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 765 | IsTailCallRelease(false), |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 766 | ReleaseMetadata(0) {} |
| 767 | |
| 768 | void clear(); |
| 769 | }; |
| 770 | } |
| 771 | |
| 772 | void RRInfo::clear() { |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 773 | KnownSafe = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 774 | IsRetainBlock = false; |
| 775 | IsTailCallRelease = false; |
| 776 | ReleaseMetadata = 0; |
| 777 | Calls.clear(); |
| 778 | ReverseInsertPts.clear(); |
| 779 | } |
| 780 | |
| 781 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 782 | /// \brief This class summarizes several per-pointer runtime properties which |
| 783 | /// are propogated through the flow graph. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 784 | class PtrState { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 785 | /// True if the reference count is known to be incremented. |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 786 | bool KnownPositiveRefCount; |
| 787 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 788 | /// True of we've seen an opportunity for partial RR elimination, such as |
| 789 | /// 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] | 790 | bool Partial; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 791 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 792 | /// The current position in the sequence. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 793 | Sequence Seq : 8; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 794 | |
| 795 | public: |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 796 | /// Unidirectional information about the current sequence. |
| 797 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 798 | /// TODO: Encapsulate this better. |
| 799 | RRInfo RRI; |
| 800 | |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 801 | PtrState() : KnownPositiveRefCount(false), Partial(false), |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 802 | Seq(S_None) {} |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 803 | |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 804 | void SetKnownPositiveRefCount() { |
| 805 | KnownPositiveRefCount = true; |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 806 | } |
| 807 | |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 808 | void ClearRefCount() { |
| 809 | KnownPositiveRefCount = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 810 | } |
| 811 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 812 | bool IsKnownIncremented() const { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 813 | return KnownPositiveRefCount; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 814 | } |
| 815 | |
| 816 | void SetSeq(Sequence NewSeq) { |
| 817 | Seq = NewSeq; |
| 818 | } |
| 819 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 820 | Sequence GetSeq() const { |
| 821 | return Seq; |
| 822 | } |
| 823 | |
| 824 | void ClearSequenceProgress() { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 825 | ResetSequenceProgress(S_None); |
| 826 | } |
| 827 | |
| 828 | void ResetSequenceProgress(Sequence NewSeq) { |
| 829 | Seq = NewSeq; |
| 830 | Partial = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 831 | RRI.clear(); |
| 832 | } |
| 833 | |
| 834 | void Merge(const PtrState &Other, bool TopDown); |
| 835 | }; |
| 836 | } |
| 837 | |
| 838 | void |
| 839 | PtrState::Merge(const PtrState &Other, bool TopDown) { |
| 840 | Seq = MergeSeqs(Seq, Other.Seq, TopDown); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 841 | KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 842 | |
| 843 | // We can't merge a plain objc_retain with an objc_retainBlock. |
| 844 | if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock) |
| 845 | Seq = S_None; |
| 846 | |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 847 | // If we're not in a sequence (anymore), drop all associated state. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 848 | if (Seq == S_None) { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 849 | Partial = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 850 | RRI.clear(); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 851 | } else if (Partial || Other.Partial) { |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 852 | // If we're doing a merge on a path that's previously seen a partial |
| 853 | // merge, conservatively drop the sequence, to avoid doing partial |
| 854 | // RR elimination. If the branch predicates for the two merge differ, |
| 855 | // mixing them is unsafe. |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 856 | ClearSequenceProgress(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 857 | } else { |
| 858 | // Conservatively merge the ReleaseMetadata information. |
| 859 | if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata) |
| 860 | RRI.ReleaseMetadata = 0; |
| 861 | |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 862 | RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 863 | RRI.IsTailCallRelease = RRI.IsTailCallRelease && |
| 864 | Other.RRI.IsTailCallRelease; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 865 | RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end()); |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 866 | |
| 867 | // Merge the insert point sets. If there are any differences, |
| 868 | // that makes this a partial merge. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 869 | Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size(); |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 870 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 871 | I = Other.RRI.ReverseInsertPts.begin(), |
| 872 | E = Other.RRI.ReverseInsertPts.end(); I != E; ++I) |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 873 | Partial |= RRI.ReverseInsertPts.insert(*I); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 874 | } |
| 875 | } |
| 876 | |
| 877 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 878 | /// \brief Per-BasicBlock state. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 879 | class BBState { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 880 | /// The number of unique control paths from the entry which can reach this |
| 881 | /// block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 882 | unsigned TopDownPathCount; |
| 883 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 884 | /// The number of unique control paths to exits from this block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 885 | unsigned BottomUpPathCount; |
| 886 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 887 | /// A type for PerPtrTopDown and PerPtrBottomUp. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 888 | typedef MapVector<const Value *, PtrState> MapTy; |
| 889 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 890 | /// The top-down traversal uses this to record information known about a |
| 891 | /// pointer at the bottom of each block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 892 | MapTy PerPtrTopDown; |
| 893 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 894 | /// The bottom-up traversal uses this to record information known about a |
| 895 | /// pointer at the top of each block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 896 | MapTy PerPtrBottomUp; |
| 897 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 898 | /// Effective predecessors of the current block ignoring ignorable edges and |
| 899 | /// ignored backedges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 900 | SmallVector<BasicBlock *, 2> Preds; |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 901 | /// Effective successors of the current block ignoring ignorable edges and |
| 902 | /// ignored backedges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 903 | SmallVector<BasicBlock *, 2> Succs; |
| 904 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 905 | public: |
| 906 | BBState() : TopDownPathCount(0), BottomUpPathCount(0) {} |
| 907 | |
| 908 | typedef MapTy::iterator ptr_iterator; |
| 909 | typedef MapTy::const_iterator ptr_const_iterator; |
| 910 | |
| 911 | ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); } |
| 912 | ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); } |
| 913 | ptr_const_iterator top_down_ptr_begin() const { |
| 914 | return PerPtrTopDown.begin(); |
| 915 | } |
| 916 | ptr_const_iterator top_down_ptr_end() const { |
| 917 | return PerPtrTopDown.end(); |
| 918 | } |
| 919 | |
| 920 | ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); } |
| 921 | ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); } |
| 922 | ptr_const_iterator bottom_up_ptr_begin() const { |
| 923 | return PerPtrBottomUp.begin(); |
| 924 | } |
| 925 | ptr_const_iterator bottom_up_ptr_end() const { |
| 926 | return PerPtrBottomUp.end(); |
| 927 | } |
| 928 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 929 | /// Mark this block as being an entry block, which has one path from the |
| 930 | /// entry by definition. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 931 | void SetAsEntry() { TopDownPathCount = 1; } |
| 932 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 933 | /// Mark this block as being an exit block, which has one path to an exit by |
| 934 | /// definition. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 935 | void SetAsExit() { BottomUpPathCount = 1; } |
| 936 | |
| 937 | PtrState &getPtrTopDownState(const Value *Arg) { |
| 938 | return PerPtrTopDown[Arg]; |
| 939 | } |
| 940 | |
| 941 | PtrState &getPtrBottomUpState(const Value *Arg) { |
| 942 | return PerPtrBottomUp[Arg]; |
| 943 | } |
| 944 | |
| 945 | void clearBottomUpPointers() { |
Evan Cheng | e4df6a2 | 2011-08-04 18:40:26 +0000 | [diff] [blame] | 946 | PerPtrBottomUp.clear(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 947 | } |
| 948 | |
| 949 | void clearTopDownPointers() { |
| 950 | PerPtrTopDown.clear(); |
| 951 | } |
| 952 | |
| 953 | void InitFromPred(const BBState &Other); |
| 954 | void InitFromSucc(const BBState &Other); |
| 955 | void MergePred(const BBState &Other); |
| 956 | void MergeSucc(const BBState &Other); |
| 957 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 958 | /// Return the number of possible unique paths from an entry to an exit |
| 959 | /// which pass through this block. This is only valid after both the |
| 960 | /// top-down and bottom-up traversals are complete. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 961 | unsigned GetAllPathCount() const { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 962 | assert(TopDownPathCount != 0); |
| 963 | assert(BottomUpPathCount != 0); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 964 | return TopDownPathCount * BottomUpPathCount; |
| 965 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 966 | |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 967 | // Specialized CFG utilities. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 968 | typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 969 | edge_iterator pred_begin() { return Preds.begin(); } |
| 970 | edge_iterator pred_end() { return Preds.end(); } |
| 971 | edge_iterator succ_begin() { return Succs.begin(); } |
| 972 | edge_iterator succ_end() { return Succs.end(); } |
| 973 | |
| 974 | void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); } |
| 975 | void addPred(BasicBlock *Pred) { Preds.push_back(Pred); } |
| 976 | |
| 977 | bool isExit() const { return Succs.empty(); } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 978 | }; |
| 979 | } |
| 980 | |
| 981 | void BBState::InitFromPred(const BBState &Other) { |
| 982 | PerPtrTopDown = Other.PerPtrTopDown; |
| 983 | TopDownPathCount = Other.TopDownPathCount; |
| 984 | } |
| 985 | |
| 986 | void BBState::InitFromSucc(const BBState &Other) { |
| 987 | PerPtrBottomUp = Other.PerPtrBottomUp; |
| 988 | BottomUpPathCount = Other.BottomUpPathCount; |
| 989 | } |
| 990 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 991 | /// The top-down traversal uses this to merge information about predecessors to |
| 992 | /// form the initial state for a new block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 993 | void BBState::MergePred(const BBState &Other) { |
| 994 | // Other.TopDownPathCount can be 0, in which case it is either dead or a |
| 995 | // loop backedge. Loop backedges are special. |
| 996 | TopDownPathCount += Other.TopDownPathCount; |
| 997 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 998 | // Check for overflow. If we have overflow, fall back to conservative |
| 999 | // behavior. |
Dan Gohman | 7c84dad | 2012-09-12 20:45:17 +0000 | [diff] [blame] | 1000 | if (TopDownPathCount < Other.TopDownPathCount) { |
| 1001 | clearTopDownPointers(); |
| 1002 | return; |
| 1003 | } |
| 1004 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1005 | // For each entry in the other set, if our set has an entry with the same key, |
| 1006 | // merge the entries. Otherwise, copy the entry and merge it with an empty |
| 1007 | // entry. |
| 1008 | for (ptr_const_iterator MI = Other.top_down_ptr_begin(), |
| 1009 | ME = Other.top_down_ptr_end(); MI != ME; ++MI) { |
| 1010 | std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI); |
| 1011 | Pair.first->second.Merge(Pair.second ? PtrState() : MI->second, |
| 1012 | /*TopDown=*/true); |
| 1013 | } |
| 1014 | |
Dan Gohman | 7e315fc3 | 2011-08-11 21:06:32 +0000 | [diff] [blame] | 1015 | // 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] | 1016 | // same key, force it to merge with an empty entry. |
| 1017 | for (ptr_iterator MI = top_down_ptr_begin(), |
| 1018 | ME = top_down_ptr_end(); MI != ME; ++MI) |
| 1019 | if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end()) |
| 1020 | MI->second.Merge(PtrState(), /*TopDown=*/true); |
| 1021 | } |
| 1022 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1023 | /// The bottom-up traversal uses this to merge information about successors to |
| 1024 | /// form the initial state for a new block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1025 | void BBState::MergeSucc(const BBState &Other) { |
| 1026 | // Other.BottomUpPathCount can be 0, in which case it is either dead or a |
| 1027 | // loop backedge. Loop backedges are special. |
| 1028 | BottomUpPathCount += Other.BottomUpPathCount; |
| 1029 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 1030 | // Check for overflow. If we have overflow, fall back to conservative |
| 1031 | // behavior. |
Dan Gohman | 7c84dad | 2012-09-12 20:45:17 +0000 | [diff] [blame] | 1032 | if (BottomUpPathCount < Other.BottomUpPathCount) { |
| 1033 | clearBottomUpPointers(); |
| 1034 | return; |
| 1035 | } |
| 1036 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1037 | // For each entry in the other set, if our set has an entry with the |
| 1038 | // same key, merge the entries. Otherwise, copy the entry and merge |
| 1039 | // it with an empty entry. |
| 1040 | for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(), |
| 1041 | ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) { |
| 1042 | std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI); |
| 1043 | Pair.first->second.Merge(Pair.second ? PtrState() : MI->second, |
| 1044 | /*TopDown=*/false); |
| 1045 | } |
| 1046 | |
Dan Gohman | 7e315fc3 | 2011-08-11 21:06:32 +0000 | [diff] [blame] | 1047 | // 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] | 1048 | // with the same key, force it to merge with an empty entry. |
| 1049 | for (ptr_iterator MI = bottom_up_ptr_begin(), |
| 1050 | ME = bottom_up_ptr_end(); MI != ME; ++MI) |
| 1051 | if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end()) |
| 1052 | MI->second.Merge(PtrState(), /*TopDown=*/false); |
| 1053 | } |
| 1054 | |
| 1055 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1056 | /// \brief The main ARC optimization pass. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1057 | class ObjCARCOpt : public FunctionPass { |
| 1058 | bool Changed; |
| 1059 | ProvenanceAnalysis PA; |
| 1060 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1061 | /// A flag indicating whether this optimization pass should run. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 1062 | bool Run; |
| 1063 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1064 | /// Declarations for ObjC runtime functions, for use in creating calls to |
| 1065 | /// them. These are initialized lazily to avoid cluttering up the Module |
| 1066 | /// with unused declarations. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1067 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1068 | /// Declaration for ObjC runtime function |
| 1069 | /// objc_retainAutoreleasedReturnValue. |
| 1070 | Constant *RetainRVCallee; |
| 1071 | /// Declaration for ObjC runtime function objc_autoreleaseReturnValue. |
| 1072 | Constant *AutoreleaseRVCallee; |
| 1073 | /// Declaration for ObjC runtime function objc_release. |
| 1074 | Constant *ReleaseCallee; |
| 1075 | /// Declaration for ObjC runtime function objc_retain. |
| 1076 | Constant *RetainCallee; |
| 1077 | /// Declaration for ObjC runtime function objc_retainBlock. |
| 1078 | Constant *RetainBlockCallee; |
| 1079 | /// Declaration for ObjC runtime function objc_autorelease. |
| 1080 | Constant *AutoreleaseCallee; |
| 1081 | |
| 1082 | /// Flags which determine whether each of the interesting runtine functions |
| 1083 | /// is in fact used in the current function. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1084 | unsigned UsedInThisFunction; |
| 1085 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1086 | /// The Metadata Kind for clang.imprecise_release metadata. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1087 | unsigned ImpreciseReleaseMDKind; |
| 1088 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1089 | /// The Metadata Kind for clang.arc.copy_on_escape metadata. |
Dan Gohman | a7107f9 | 2011-10-17 22:53:25 +0000 | [diff] [blame] | 1090 | unsigned CopyOnEscapeMDKind; |
| 1091 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1092 | /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata. |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 1093 | unsigned NoObjCARCExceptionsMDKind; |
| 1094 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1095 | Constant *getRetainRVCallee(Module *M); |
| 1096 | Constant *getAutoreleaseRVCallee(Module *M); |
| 1097 | Constant *getReleaseCallee(Module *M); |
| 1098 | Constant *getRetainCallee(Module *M); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1099 | Constant *getRetainBlockCallee(Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1100 | Constant *getAutoreleaseCallee(Module *M); |
| 1101 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 1102 | bool IsRetainBlockOptimizable(const Instruction *Inst); |
| 1103 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1104 | void OptimizeRetainCall(Function &F, Instruction *Retain); |
| 1105 | bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV); |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1106 | void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV, |
| 1107 | InstructionClass &Class); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1108 | void OptimizeIndividualCalls(Function &F); |
| 1109 | |
| 1110 | void CheckForCFGHazards(const BasicBlock *BB, |
| 1111 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1112 | BBState &MyStates) const; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1113 | bool VisitInstructionBottomUp(Instruction *Inst, |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 1114 | BasicBlock *BB, |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1115 | MapVector<Value *, RRInfo> &Retains, |
| 1116 | BBState &MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1117 | bool VisitBottomUp(BasicBlock *BB, |
| 1118 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1119 | MapVector<Value *, RRInfo> &Retains); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1120 | bool VisitInstructionTopDown(Instruction *Inst, |
| 1121 | DenseMap<Value *, RRInfo> &Releases, |
| 1122 | BBState &MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1123 | bool VisitTopDown(BasicBlock *BB, |
| 1124 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1125 | DenseMap<Value *, RRInfo> &Releases); |
| 1126 | bool Visit(Function &F, |
| 1127 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1128 | MapVector<Value *, RRInfo> &Retains, |
| 1129 | DenseMap<Value *, RRInfo> &Releases); |
| 1130 | |
| 1131 | void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove, |
| 1132 | MapVector<Value *, RRInfo> &Retains, |
| 1133 | DenseMap<Value *, RRInfo> &Releases, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1134 | SmallVectorImpl<Instruction *> &DeadInsts, |
| 1135 | Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1136 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 1137 | bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1138 | MapVector<Value *, RRInfo> &Retains, |
| 1139 | DenseMap<Value *, RRInfo> &Releases, |
| 1140 | Module *M, |
| 1141 | SmallVector<Instruction *, 4> &NewRetains, |
| 1142 | SmallVector<Instruction *, 4> &NewReleases, |
| 1143 | SmallVector<Instruction *, 8> &DeadInsts, |
| 1144 | RRInfo &RetainsToMove, |
| 1145 | RRInfo &ReleasesToMove, |
| 1146 | Value *Arg, |
| 1147 | bool KnownSafe, |
| 1148 | bool &AnyPairsCompletelyEliminated); |
| 1149 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1150 | bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1151 | MapVector<Value *, RRInfo> &Retains, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1152 | DenseMap<Value *, RRInfo> &Releases, |
| 1153 | Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1154 | |
| 1155 | void OptimizeWeakCalls(Function &F); |
| 1156 | |
| 1157 | bool OptimizeSequences(Function &F); |
| 1158 | |
| 1159 | void OptimizeReturns(Function &F); |
| 1160 | |
| 1161 | virtual void getAnalysisUsage(AnalysisUsage &AU) const; |
| 1162 | virtual bool doInitialization(Module &M); |
| 1163 | virtual bool runOnFunction(Function &F); |
| 1164 | virtual void releaseMemory(); |
| 1165 | |
| 1166 | public: |
| 1167 | static char ID; |
| 1168 | ObjCARCOpt() : FunctionPass(ID) { |
| 1169 | initializeObjCARCOptPass(*PassRegistry::getPassRegistry()); |
| 1170 | } |
| 1171 | }; |
| 1172 | } |
| 1173 | |
| 1174 | char ObjCARCOpt::ID = 0; |
| 1175 | INITIALIZE_PASS_BEGIN(ObjCARCOpt, |
| 1176 | "objc-arc", "ObjC ARC optimization", false, false) |
| 1177 | INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis) |
| 1178 | INITIALIZE_PASS_END(ObjCARCOpt, |
| 1179 | "objc-arc", "ObjC ARC optimization", false, false) |
| 1180 | |
| 1181 | Pass *llvm::createObjCARCOptPass() { |
| 1182 | return new ObjCARCOpt(); |
| 1183 | } |
| 1184 | |
| 1185 | void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const { |
| 1186 | AU.addRequired<ObjCARCAliasAnalysis>(); |
| 1187 | AU.addRequired<AliasAnalysis>(); |
| 1188 | // ARC optimization doesn't currently split critical edges. |
| 1189 | AU.setPreservesCFG(); |
| 1190 | } |
| 1191 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 1192 | bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) { |
| 1193 | // Without the magic metadata tag, we have to assume this might be an |
| 1194 | // objc_retainBlock call inserted to convert a block pointer to an id, |
| 1195 | // in which case it really is needed. |
| 1196 | if (!Inst->getMetadata(CopyOnEscapeMDKind)) |
| 1197 | return false; |
| 1198 | |
| 1199 | // If the pointer "escapes" (not including being used in a call), |
| 1200 | // the copy may be needed. |
| 1201 | if (DoesObjCBlockEscape(Inst)) |
| 1202 | return false; |
| 1203 | |
| 1204 | // Otherwise, it's not needed. |
| 1205 | return true; |
| 1206 | } |
| 1207 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1208 | Constant *ObjCARCOpt::getRetainRVCallee(Module *M) { |
| 1209 | if (!RetainRVCallee) { |
| 1210 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 1211 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1212 | Type *Params[] = { I8X }; |
| 1213 | FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false); |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1214 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1215 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1216 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1217 | RetainRVCallee = |
| 1218 | M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy, |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1219 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1220 | } |
| 1221 | return RetainRVCallee; |
| 1222 | } |
| 1223 | |
| 1224 | Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) { |
| 1225 | if (!AutoreleaseRVCallee) { |
| 1226 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 1227 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1228 | Type *Params[] = { I8X }; |
| 1229 | FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false); |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1230 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1231 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1232 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1233 | AutoreleaseRVCallee = |
| 1234 | M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy, |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1235 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1236 | } |
| 1237 | return AutoreleaseRVCallee; |
| 1238 | } |
| 1239 | |
| 1240 | Constant *ObjCARCOpt::getReleaseCallee(Module *M) { |
| 1241 | if (!ReleaseCallee) { |
| 1242 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1243 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1244 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1245 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1246 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1247 | ReleaseCallee = |
| 1248 | M->getOrInsertFunction( |
| 1249 | "objc_release", |
| 1250 | FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1251 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1252 | } |
| 1253 | return ReleaseCallee; |
| 1254 | } |
| 1255 | |
| 1256 | Constant *ObjCARCOpt::getRetainCallee(Module *M) { |
| 1257 | if (!RetainCallee) { |
| 1258 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1259 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1260 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1261 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1262 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1263 | RetainCallee = |
| 1264 | M->getOrInsertFunction( |
| 1265 | "objc_retain", |
| 1266 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1267 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1268 | } |
| 1269 | return RetainCallee; |
| 1270 | } |
| 1271 | |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1272 | Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) { |
| 1273 | if (!RetainBlockCallee) { |
| 1274 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1275 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Dan Gohman | fca43c2 | 2011-09-14 18:33:34 +0000 | [diff] [blame] | 1276 | // objc_retainBlock is not nounwind because it calls user copy constructors |
| 1277 | // which could theoretically throw. |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1278 | RetainBlockCallee = |
| 1279 | M->getOrInsertFunction( |
| 1280 | "objc_retainBlock", |
| 1281 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | e94d843 | 2012-12-07 23:16:57 +0000 | [diff] [blame] | 1282 | AttributeSet()); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1283 | } |
| 1284 | return RetainBlockCallee; |
| 1285 | } |
| 1286 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1287 | Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) { |
| 1288 | if (!AutoreleaseCallee) { |
| 1289 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1290 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1291 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1292 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1293 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1294 | AutoreleaseCallee = |
| 1295 | M->getOrInsertFunction( |
| 1296 | "objc_autorelease", |
| 1297 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1298 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1299 | } |
| 1300 | return AutoreleaseCallee; |
| 1301 | } |
| 1302 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1303 | /// Test whether the given value is possible a reference-counted pointer, |
| 1304 | /// including tests which utilize AliasAnalysis. |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 1305 | static bool IsPotentialRetainableObjPtr(const Value *Op, AliasAnalysis &AA) { |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 1306 | // First make the rudimentary check. |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 1307 | if (!IsPotentialRetainableObjPtr(Op)) |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 1308 | return false; |
| 1309 | |
| 1310 | // Objects in constant memory are not reference-counted. |
| 1311 | if (AA.pointsToConstantMemory(Op)) |
| 1312 | return false; |
| 1313 | |
| 1314 | // Pointers in constant memory are not pointing to reference-counted objects. |
| 1315 | if (const LoadInst *LI = dyn_cast<LoadInst>(Op)) |
| 1316 | if (AA.pointsToConstantMemory(LI->getPointerOperand())) |
| 1317 | return false; |
| 1318 | |
| 1319 | // Otherwise assume the worst. |
| 1320 | return true; |
| 1321 | } |
| 1322 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1323 | /// Test whether the given instruction can result in a reference count |
| 1324 | /// modification (positive or negative) for the pointer's object. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1325 | static bool |
| 1326 | CanAlterRefCount(const Instruction *Inst, const Value *Ptr, |
| 1327 | ProvenanceAnalysis &PA, InstructionClass Class) { |
| 1328 | switch (Class) { |
| 1329 | case IC_Autorelease: |
| 1330 | case IC_AutoreleaseRV: |
| 1331 | case IC_User: |
| 1332 | // These operations never directly modify a reference count. |
| 1333 | return false; |
| 1334 | default: break; |
| 1335 | } |
| 1336 | |
| 1337 | ImmutableCallSite CS = static_cast<const Value *>(Inst); |
| 1338 | assert(CS && "Only calls can alter reference counts!"); |
| 1339 | |
| 1340 | // See if AliasAnalysis can help us with the call. |
| 1341 | AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS); |
| 1342 | if (AliasAnalysis::onlyReadsMemory(MRB)) |
| 1343 | return false; |
| 1344 | if (AliasAnalysis::onlyAccessesArgPointees(MRB)) { |
| 1345 | for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); |
| 1346 | I != E; ++I) { |
| 1347 | const Value *Op = *I; |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 1348 | if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1349 | return true; |
| 1350 | } |
| 1351 | return false; |
| 1352 | } |
| 1353 | |
| 1354 | // Assume the worst. |
| 1355 | return true; |
| 1356 | } |
| 1357 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1358 | /// Test whether the given instruction can "use" the given pointer's object in a |
| 1359 | /// way that requires the reference count to be positive. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1360 | static bool |
| 1361 | CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA, |
| 1362 | InstructionClass Class) { |
| 1363 | // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers. |
| 1364 | if (Class == IC_Call) |
| 1365 | return false; |
| 1366 | |
| 1367 | // Consider various instructions which may have pointer arguments which are |
| 1368 | // not "uses". |
| 1369 | if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) { |
| 1370 | // Comparing a pointer with null, or any other constant, isn't really a use, |
| 1371 | // because we don't care what the pointer points to, or about the values |
| 1372 | // of any other dynamic reference-counted pointers. |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 1373 | if (!IsPotentialRetainableObjPtr(ICI->getOperand(1), *PA.getAA())) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1374 | return false; |
| 1375 | } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) { |
| 1376 | // For calls, just check the arguments (and not the callee operand). |
| 1377 | for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(), |
| 1378 | OE = CS.arg_end(); OI != OE; ++OI) { |
| 1379 | const Value *Op = *OI; |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 1380 | if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1381 | return true; |
| 1382 | } |
| 1383 | return false; |
| 1384 | } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { |
| 1385 | // Special-case stores, because we don't care about the stored value, just |
| 1386 | // the store address. |
| 1387 | const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand()); |
| 1388 | // If we can't tell what the underlying object was, assume there is a |
| 1389 | // dependence. |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 1390 | return IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Op, Ptr); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1391 | } |
| 1392 | |
| 1393 | // Check each operand for a match. |
| 1394 | for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end(); |
| 1395 | OI != OE; ++OI) { |
| 1396 | const Value *Op = *OI; |
Michael Gottesman | 5300cdd | 2013-01-27 06:19:48 +0000 | [diff] [blame] | 1397 | if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1398 | return true; |
| 1399 | } |
| 1400 | return false; |
| 1401 | } |
| 1402 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1403 | /// Test whether the given instruction can autorelease any pointer or cause an |
| 1404 | /// autoreleasepool pop. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1405 | static bool |
| 1406 | CanInterruptRV(InstructionClass Class) { |
| 1407 | switch (Class) { |
| 1408 | case IC_AutoreleasepoolPop: |
| 1409 | case IC_CallOrUser: |
| 1410 | case IC_Call: |
| 1411 | case IC_Autorelease: |
| 1412 | case IC_AutoreleaseRV: |
| 1413 | case IC_FusedRetainAutorelease: |
| 1414 | case IC_FusedRetainAutoreleaseRV: |
| 1415 | return true; |
| 1416 | default: |
| 1417 | return false; |
| 1418 | } |
| 1419 | } |
| 1420 | |
| 1421 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1422 | /// \enum DependenceKind |
| 1423 | /// \brief Defines different dependence kinds among various ARC constructs. |
| 1424 | /// |
| 1425 | /// There are several kinds of dependence-like concepts in use here. |
| 1426 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1427 | enum DependenceKind { |
| 1428 | NeedsPositiveRetainCount, |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 1429 | AutoreleasePoolBoundary, |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1430 | CanChangeRetainCount, |
| 1431 | RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease. |
| 1432 | RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue. |
| 1433 | RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue. |
| 1434 | }; |
| 1435 | } |
| 1436 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1437 | /// Test if there can be dependencies on Inst through Arg. This function only |
| 1438 | /// tests dependencies relevant for removing pairs of calls. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1439 | static bool |
| 1440 | Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg, |
| 1441 | ProvenanceAnalysis &PA) { |
| 1442 | // If we've reached the definition of Arg, stop. |
| 1443 | if (Inst == Arg) |
| 1444 | return true; |
| 1445 | |
| 1446 | switch (Flavor) { |
| 1447 | case NeedsPositiveRetainCount: { |
| 1448 | InstructionClass Class = GetInstructionClass(Inst); |
| 1449 | switch (Class) { |
| 1450 | case IC_AutoreleasepoolPop: |
| 1451 | case IC_AutoreleasepoolPush: |
| 1452 | case IC_None: |
| 1453 | return false; |
| 1454 | default: |
| 1455 | return CanUse(Inst, Arg, PA, Class); |
| 1456 | } |
| 1457 | } |
| 1458 | |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 1459 | case AutoreleasePoolBoundary: { |
| 1460 | InstructionClass Class = GetInstructionClass(Inst); |
| 1461 | switch (Class) { |
| 1462 | case IC_AutoreleasepoolPop: |
| 1463 | case IC_AutoreleasepoolPush: |
| 1464 | // These mark the end and begin of an autorelease pool scope. |
| 1465 | return true; |
| 1466 | default: |
| 1467 | // Nothing else does this. |
| 1468 | return false; |
| 1469 | } |
| 1470 | } |
| 1471 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1472 | case CanChangeRetainCount: { |
| 1473 | InstructionClass Class = GetInstructionClass(Inst); |
| 1474 | switch (Class) { |
| 1475 | case IC_AutoreleasepoolPop: |
| 1476 | // Conservatively assume this can decrement any count. |
| 1477 | return true; |
| 1478 | case IC_AutoreleasepoolPush: |
| 1479 | case IC_None: |
| 1480 | return false; |
| 1481 | default: |
| 1482 | return CanAlterRefCount(Inst, Arg, PA, Class); |
| 1483 | } |
| 1484 | } |
| 1485 | |
| 1486 | case RetainAutoreleaseDep: |
| 1487 | switch (GetBasicInstructionClass(Inst)) { |
| 1488 | case IC_AutoreleasepoolPop: |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 1489 | case IC_AutoreleasepoolPush: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1490 | // Don't merge an objc_autorelease with an objc_retain inside a different |
| 1491 | // autoreleasepool scope. |
| 1492 | return true; |
| 1493 | case IC_Retain: |
| 1494 | case IC_RetainRV: |
| 1495 | // Check for a retain of the same pointer for merging. |
| 1496 | return GetObjCArg(Inst) == Arg; |
| 1497 | default: |
| 1498 | // Nothing else matters for objc_retainAutorelease formation. |
| 1499 | return false; |
| 1500 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1501 | |
| 1502 | case RetainAutoreleaseRVDep: { |
| 1503 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 1504 | switch (Class) { |
| 1505 | case IC_Retain: |
| 1506 | case IC_RetainRV: |
| 1507 | // Check for a retain of the same pointer for merging. |
| 1508 | return GetObjCArg(Inst) == Arg; |
| 1509 | default: |
| 1510 | // Anything that can autorelease interrupts |
| 1511 | // retainAutoreleaseReturnValue formation. |
| 1512 | return CanInterruptRV(Class); |
| 1513 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1514 | } |
| 1515 | |
| 1516 | case RetainRVDep: |
| 1517 | return CanInterruptRV(GetBasicInstructionClass(Inst)); |
| 1518 | } |
| 1519 | |
| 1520 | llvm_unreachable("Invalid dependence flavor"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1521 | } |
| 1522 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1523 | /// Walk up the CFG from StartPos (which is in StartBB) and find local and |
| 1524 | /// non-local dependencies on Arg. |
| 1525 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1526 | /// TODO: Cache results? |
| 1527 | static void |
| 1528 | FindDependencies(DependenceKind Flavor, |
| 1529 | const Value *Arg, |
| 1530 | BasicBlock *StartBB, Instruction *StartInst, |
| 1531 | SmallPtrSet<Instruction *, 4> &DependingInstructions, |
| 1532 | SmallPtrSet<const BasicBlock *, 4> &Visited, |
| 1533 | ProvenanceAnalysis &PA) { |
| 1534 | BasicBlock::iterator StartPos = StartInst; |
| 1535 | |
| 1536 | SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist; |
| 1537 | Worklist.push_back(std::make_pair(StartBB, StartPos)); |
| 1538 | do { |
| 1539 | std::pair<BasicBlock *, BasicBlock::iterator> Pair = |
| 1540 | Worklist.pop_back_val(); |
| 1541 | BasicBlock *LocalStartBB = Pair.first; |
| 1542 | BasicBlock::iterator LocalStartPos = Pair.second; |
| 1543 | BasicBlock::iterator StartBBBegin = LocalStartBB->begin(); |
| 1544 | for (;;) { |
| 1545 | if (LocalStartPos == StartBBBegin) { |
| 1546 | pred_iterator PI(LocalStartBB), PE(LocalStartBB, false); |
| 1547 | if (PI == PE) |
| 1548 | // If we've reached the function entry, produce a null dependence. |
| 1549 | DependingInstructions.insert(0); |
| 1550 | else |
| 1551 | // Add the predecessors to the worklist. |
| 1552 | do { |
| 1553 | BasicBlock *PredBB = *PI; |
| 1554 | if (Visited.insert(PredBB)) |
| 1555 | Worklist.push_back(std::make_pair(PredBB, PredBB->end())); |
| 1556 | } while (++PI != PE); |
| 1557 | break; |
| 1558 | } |
| 1559 | |
| 1560 | Instruction *Inst = --LocalStartPos; |
| 1561 | if (Depends(Flavor, Inst, Arg, PA)) { |
| 1562 | DependingInstructions.insert(Inst); |
| 1563 | break; |
| 1564 | } |
| 1565 | } |
| 1566 | } while (!Worklist.empty()); |
| 1567 | |
| 1568 | // Determine whether the original StartBB post-dominates all of the blocks we |
| 1569 | // visited. If not, insert a sentinal indicating that most optimizations are |
| 1570 | // not safe. |
| 1571 | for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(), |
| 1572 | E = Visited.end(); I != E; ++I) { |
| 1573 | const BasicBlock *BB = *I; |
| 1574 | if (BB == StartBB) |
| 1575 | continue; |
| 1576 | const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); |
| 1577 | for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) { |
| 1578 | const BasicBlock *Succ = *SI; |
| 1579 | if (Succ != StartBB && !Visited.count(Succ)) { |
| 1580 | DependingInstructions.insert(reinterpret_cast<Instruction *>(-1)); |
| 1581 | return; |
| 1582 | } |
| 1583 | } |
| 1584 | } |
| 1585 | } |
| 1586 | |
| 1587 | static bool isNullOrUndef(const Value *V) { |
| 1588 | return isa<ConstantPointerNull>(V) || isa<UndefValue>(V); |
| 1589 | } |
| 1590 | |
| 1591 | static bool isNoopInstruction(const Instruction *I) { |
| 1592 | return isa<BitCastInst>(I) || |
| 1593 | (isa<GetElementPtrInst>(I) && |
| 1594 | cast<GetElementPtrInst>(I)->hasAllZeroIndices()); |
| 1595 | } |
| 1596 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1597 | /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a |
| 1598 | /// return value. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1599 | void |
| 1600 | ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1601 | ImmutableCallSite CS(GetObjCArg(Retain)); |
| 1602 | const Instruction *Call = CS.getInstruction(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1603 | if (!Call) return; |
| 1604 | if (Call->getParent() != Retain->getParent()) return; |
| 1605 | |
| 1606 | // Check that the call is next to the retain. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1607 | BasicBlock::const_iterator I = Call; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1608 | ++I; |
| 1609 | while (isNoopInstruction(I)) ++I; |
| 1610 | if (&*I != Retain) |
| 1611 | return; |
| 1612 | |
| 1613 | // Turn it to an objc_retainAutoreleasedReturnValue.. |
| 1614 | Changed = true; |
| 1615 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1616 | |
Michael Gottesman | 1e00ac6 | 2013-01-04 21:30:38 +0000 | [diff] [blame] | 1617 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming " |
Michael Gottesman | 9f1be68 | 2013-01-12 03:45:49 +0000 | [diff] [blame] | 1618 | "objc_retain => objc_retainAutoreleasedReturnValue" |
| 1619 | " since the operand is a return value.\n" |
Michael Gottesman | 1e00ac6 | 2013-01-04 21:30:38 +0000 | [diff] [blame] | 1620 | " Old: " |
| 1621 | << *Retain << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1622 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1623 | cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent())); |
Michael Gottesman | 1e00ac6 | 2013-01-04 21:30:38 +0000 | [diff] [blame] | 1624 | |
| 1625 | DEBUG(dbgs() << " New: " |
| 1626 | << *Retain << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1627 | } |
| 1628 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1629 | /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is |
| 1630 | /// not a return value. Or, if it can be paired with an |
| 1631 | /// objc_autoreleaseReturnValue, delete the pair and return true. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1632 | bool |
| 1633 | ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) { |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1634 | // Check for the argument being from an immediately preceding call or invoke. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1635 | const Value *Arg = GetObjCArg(RetainRV); |
| 1636 | ImmutableCallSite CS(Arg); |
| 1637 | if (const Instruction *Call = CS.getInstruction()) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1638 | if (Call->getParent() == RetainRV->getParent()) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1639 | BasicBlock::const_iterator I = Call; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1640 | ++I; |
| 1641 | while (isNoopInstruction(I)) ++I; |
| 1642 | if (&*I == RetainRV) |
| 1643 | return false; |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1644 | } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) { |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1645 | BasicBlock *RetainRVParent = RetainRV->getParent(); |
| 1646 | if (II->getNormalDest() == RetainRVParent) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1647 | BasicBlock::const_iterator I = RetainRVParent->begin(); |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1648 | while (isNoopInstruction(I)) ++I; |
| 1649 | if (&*I == RetainRV) |
| 1650 | return false; |
| 1651 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1652 | } |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1653 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1654 | |
| 1655 | // Check for being preceded by an objc_autoreleaseReturnValue on the same |
| 1656 | // pointer. In this case, we can delete the pair. |
| 1657 | BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin(); |
| 1658 | if (I != Begin) { |
| 1659 | do --I; while (I != Begin && isNoopInstruction(I)); |
| 1660 | if (GetBasicInstructionClass(I) == IC_AutoreleaseRV && |
| 1661 | GetObjCArg(I) == Arg) { |
| 1662 | Changed = true; |
| 1663 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1664 | |
Michael Gottesman | 5c32ce9 | 2013-01-05 17:55:35 +0000 | [diff] [blame] | 1665 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n" |
| 1666 | << " Erasing " << *RetainRV |
| 1667 | << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1668 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1669 | EraseInstruction(I); |
| 1670 | EraseInstruction(RetainRV); |
| 1671 | return true; |
| 1672 | } |
| 1673 | } |
| 1674 | |
| 1675 | // Turn it to a plain objc_retain. |
| 1676 | Changed = true; |
| 1677 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1678 | |
Michael Gottesman | def07bb | 2013-01-05 17:55:42 +0000 | [diff] [blame] | 1679 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming " |
| 1680 | "objc_retainAutoreleasedReturnValue => " |
| 1681 | "objc_retain since the operand is not a return value.\n" |
| 1682 | " Old: " |
| 1683 | << *RetainRV << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1684 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1685 | cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent())); |
Michael Gottesman | def07bb | 2013-01-05 17:55:42 +0000 | [diff] [blame] | 1686 | |
| 1687 | DEBUG(dbgs() << " New: " |
| 1688 | << *RetainRV << "\n"); |
| 1689 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1690 | return false; |
| 1691 | } |
| 1692 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1693 | /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not |
| 1694 | /// used as a return value. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1695 | void |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1696 | ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV, |
| 1697 | InstructionClass &Class) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1698 | // Check for a return of the pointer value. |
| 1699 | const Value *Ptr = GetObjCArg(AutoreleaseRV); |
Dan Gohman | 10a18d5 | 2011-08-12 00:36:31 +0000 | [diff] [blame] | 1700 | SmallVector<const Value *, 2> Users; |
| 1701 | Users.push_back(Ptr); |
| 1702 | do { |
| 1703 | Ptr = Users.pop_back_val(); |
| 1704 | for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end(); |
| 1705 | UI != UE; ++UI) { |
| 1706 | const User *I = *UI; |
| 1707 | if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV) |
| 1708 | return; |
| 1709 | if (isa<BitCastInst>(I)) |
| 1710 | Users.push_back(I); |
| 1711 | } |
| 1712 | } while (!Users.empty()); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1713 | |
| 1714 | Changed = true; |
| 1715 | ++NumPeeps; |
Michael Gottesman | 1bf6908 | 2013-01-06 21:07:11 +0000 | [diff] [blame] | 1716 | |
| 1717 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming " |
| 1718 | "objc_autoreleaseReturnValue => " |
| 1719 | "objc_autorelease since its operand is not used as a return " |
| 1720 | "value.\n" |
| 1721 | " Old: " |
| 1722 | << *AutoreleaseRV << "\n"); |
| 1723 | |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1724 | CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV); |
| 1725 | AutoreleaseRVCI-> |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1726 | setCalledFunction(getAutoreleaseCallee(F.getParent())); |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1727 | AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease. |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1728 | Class = IC_Autorelease; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1729 | |
Michael Gottesman | 1bf6908 | 2013-01-06 21:07:11 +0000 | [diff] [blame] | 1730 | DEBUG(dbgs() << " New: " |
| 1731 | << *AutoreleaseRV << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1732 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1733 | } |
| 1734 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1735 | /// Visit each call, one at a time, and make simplifications without doing any |
| 1736 | /// additional analysis. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1737 | void ObjCARCOpt::OptimizeIndividualCalls(Function &F) { |
| 1738 | // Reset all the flags in preparation for recomputing them. |
| 1739 | UsedInThisFunction = 0; |
| 1740 | |
| 1741 | // Visit all objc_* calls in F. |
| 1742 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 1743 | Instruction *Inst = &*I++; |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 1744 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1745 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 1746 | |
Michael Gottesman | d359e06 | 2013-01-18 03:08:39 +0000 | [diff] [blame] | 1747 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: " |
| 1748 | << Class << "; " << *Inst << "\n"); |
Michael Gottesman | 782e344 | 2013-01-17 18:32:34 +0000 | [diff] [blame] | 1749 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1750 | switch (Class) { |
| 1751 | default: break; |
| 1752 | |
| 1753 | // Delete no-op casts. These function calls have special semantics, but |
| 1754 | // the semantics are entirely implemented via lowering in the front-end, |
| 1755 | // so by the time they reach the optimizer, they are just no-op calls |
| 1756 | // which return their argument. |
| 1757 | // |
| 1758 | // There are gray areas here, as the ability to cast reference-counted |
| 1759 | // pointers to raw void* and back allows code to break ARC assumptions, |
| 1760 | // however these are currently considered to be unimportant. |
| 1761 | case IC_NoopCast: |
| 1762 | Changed = true; |
| 1763 | ++NumNoops; |
Michael Gottesman | dc042f0 | 2013-01-06 21:07:15 +0000 | [diff] [blame] | 1764 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:" |
| 1765 | " " << *Inst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1766 | EraseInstruction(Inst); |
| 1767 | continue; |
| 1768 | |
| 1769 | // If the pointer-to-weak-pointer is null, it's undefined behavior. |
| 1770 | case IC_StoreWeak: |
| 1771 | case IC_LoadWeak: |
| 1772 | case IC_LoadWeakRetained: |
| 1773 | case IC_InitWeak: |
| 1774 | case IC_DestroyWeak: { |
| 1775 | CallInst *CI = cast<CallInst>(Inst); |
| 1776 | if (isNullOrUndef(CI->getArgOperand(0))) { |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 1777 | Changed = true; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1778 | Type *Ty = CI->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1779 | new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), |
| 1780 | Constant::getNullValue(Ty), |
| 1781 | CI); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1782 | llvm::Value *NewValue = UndefValue::get(CI->getType()); |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 1783 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null " |
| 1784 | "pointer-to-weak-pointer is undefined behavior.\n" |
| 1785 | " Old = " << *CI << |
| 1786 | "\n New = " << |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1787 | *NewValue << "\n"); |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 1788 | CI->replaceAllUsesWith(NewValue); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1789 | CI->eraseFromParent(); |
| 1790 | continue; |
| 1791 | } |
| 1792 | break; |
| 1793 | } |
| 1794 | case IC_CopyWeak: |
| 1795 | case IC_MoveWeak: { |
| 1796 | CallInst *CI = cast<CallInst>(Inst); |
| 1797 | if (isNullOrUndef(CI->getArgOperand(0)) || |
| 1798 | isNullOrUndef(CI->getArgOperand(1))) { |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 1799 | Changed = true; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1800 | Type *Ty = CI->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1801 | new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), |
| 1802 | Constant::getNullValue(Ty), |
| 1803 | CI); |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 1804 | |
| 1805 | llvm::Value *NewValue = UndefValue::get(CI->getType()); |
| 1806 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null " |
| 1807 | "pointer-to-weak-pointer is undefined behavior.\n" |
| 1808 | " Old = " << *CI << |
| 1809 | "\n New = " << |
| 1810 | *NewValue << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1811 | |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 1812 | CI->replaceAllUsesWith(NewValue); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1813 | CI->eraseFromParent(); |
| 1814 | continue; |
| 1815 | } |
| 1816 | break; |
| 1817 | } |
| 1818 | case IC_Retain: |
| 1819 | OptimizeRetainCall(F, Inst); |
| 1820 | break; |
| 1821 | case IC_RetainRV: |
| 1822 | if (OptimizeRetainRVCall(F, Inst)) |
| 1823 | continue; |
| 1824 | break; |
| 1825 | case IC_AutoreleaseRV: |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1826 | OptimizeAutoreleaseRVCall(F, Inst, Class); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1827 | break; |
| 1828 | } |
| 1829 | |
| 1830 | // objc_autorelease(x) -> objc_release(x) if x is otherwise unused. |
| 1831 | if (IsAutorelease(Class) && Inst->use_empty()) { |
| 1832 | CallInst *Call = cast<CallInst>(Inst); |
| 1833 | const Value *Arg = Call->getArgOperand(0); |
| 1834 | Arg = FindSingleUseIdentifiedObject(Arg); |
| 1835 | if (Arg) { |
| 1836 | Changed = true; |
| 1837 | ++NumAutoreleases; |
| 1838 | |
| 1839 | // Create the declaration lazily. |
| 1840 | LLVMContext &C = Inst->getContext(); |
| 1841 | CallInst *NewCall = |
| 1842 | CallInst::Create(getReleaseCallee(F.getParent()), |
| 1843 | Call->getArgOperand(0), "", Call); |
| 1844 | NewCall->setMetadata(ImpreciseReleaseMDKind, |
| 1845 | MDNode::get(C, ArrayRef<Value *>())); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1846 | |
Michael Gottesman | a6a1dad | 2013-01-06 22:56:50 +0000 | [diff] [blame] | 1847 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing " |
| 1848 | "objc_autorelease(x) with objc_release(x) since x is " |
| 1849 | "otherwise unused.\n" |
Michael Gottesman | 4bf6e75 | 2013-01-06 22:56:54 +0000 | [diff] [blame] | 1850 | " Old: " << *Call << |
Michael Gottesman | a6a1dad | 2013-01-06 22:56:50 +0000 | [diff] [blame] | 1851 | "\n New: " << |
| 1852 | *NewCall << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1853 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1854 | EraseInstruction(Call); |
| 1855 | Inst = NewCall; |
| 1856 | Class = IC_Release; |
| 1857 | } |
| 1858 | } |
| 1859 | |
| 1860 | // For functions which can never be passed stack arguments, add |
| 1861 | // a tail keyword. |
| 1862 | if (IsAlwaysTail(Class)) { |
| 1863 | Changed = true; |
Michael Gottesman | 2d76331 | 2013-01-06 23:39:09 +0000 | [diff] [blame] | 1864 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword" |
| 1865 | " to function since it can never be passed stack args: " << *Inst << |
| 1866 | "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1867 | cast<CallInst>(Inst)->setTailCall(); |
| 1868 | } |
| 1869 | |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1870 | // Ensure that functions that can never have a "tail" keyword due to the |
| 1871 | // semantics of ARC truly do not do so. |
| 1872 | if (IsNeverTail(Class)) { |
| 1873 | Changed = true; |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 1874 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail " |
| 1875 | "keyword from function: " << *Inst << |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1876 | "\n"); |
| 1877 | cast<CallInst>(Inst)->setTailCall(false); |
| 1878 | } |
| 1879 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1880 | // Set nounwind as needed. |
| 1881 | if (IsNoThrow(Class)) { |
| 1882 | Changed = true; |
Michael Gottesman | 8800a51 | 2013-01-06 23:39:13 +0000 | [diff] [blame] | 1883 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw" |
| 1884 | " class. Setting nounwind on: " << *Inst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1885 | cast<CallInst>(Inst)->setDoesNotThrow(); |
| 1886 | } |
| 1887 | |
| 1888 | if (!IsNoopOnNull(Class)) { |
| 1889 | UsedInThisFunction |= 1 << Class; |
| 1890 | continue; |
| 1891 | } |
| 1892 | |
| 1893 | const Value *Arg = GetObjCArg(Inst); |
| 1894 | |
| 1895 | // ARC calls with null are no-ops. Delete them. |
| 1896 | if (isNullOrUndef(Arg)) { |
| 1897 | Changed = true; |
| 1898 | ++NumNoops; |
Michael Gottesman | 5b970e1 | 2013-01-07 00:04:52 +0000 | [diff] [blame] | 1899 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with " |
| 1900 | " null are no-ops. Erasing: " << *Inst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1901 | EraseInstruction(Inst); |
| 1902 | continue; |
| 1903 | } |
| 1904 | |
| 1905 | // Keep track of which of retain, release, autorelease, and retain_block |
| 1906 | // are actually present in this function. |
| 1907 | UsedInThisFunction |= 1 << Class; |
| 1908 | |
| 1909 | // If Arg is a PHI, and one or more incoming values to the |
| 1910 | // PHI are null, and the call is control-equivalent to the PHI, and there |
| 1911 | // are no relevant side effects between the PHI and the call, the call |
| 1912 | // could be pushed up to just those paths with non-null incoming values. |
| 1913 | // For now, don't bother splitting critical edges for this. |
| 1914 | SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist; |
| 1915 | Worklist.push_back(std::make_pair(Inst, Arg)); |
| 1916 | do { |
| 1917 | std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val(); |
| 1918 | Inst = Pair.first; |
| 1919 | Arg = Pair.second; |
| 1920 | |
| 1921 | const PHINode *PN = dyn_cast<PHINode>(Arg); |
| 1922 | if (!PN) continue; |
| 1923 | |
| 1924 | // Determine if the PHI has any null operands, or any incoming |
| 1925 | // critical edges. |
| 1926 | bool HasNull = false; |
| 1927 | bool HasCriticalEdges = false; |
| 1928 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 1929 | Value *Incoming = |
| 1930 | StripPointerCastsAndObjCCalls(PN->getIncomingValue(i)); |
| 1931 | if (isNullOrUndef(Incoming)) |
| 1932 | HasNull = true; |
| 1933 | else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back()) |
| 1934 | .getNumSuccessors() != 1) { |
| 1935 | HasCriticalEdges = true; |
| 1936 | break; |
| 1937 | } |
| 1938 | } |
| 1939 | // If we have null operands and no critical edges, optimize. |
| 1940 | if (!HasCriticalEdges && HasNull) { |
| 1941 | SmallPtrSet<Instruction *, 4> DependingInstructions; |
| 1942 | SmallPtrSet<const BasicBlock *, 4> Visited; |
| 1943 | |
| 1944 | // Check that there is nothing that cares about the reference |
| 1945 | // count between the call and the phi. |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 1946 | switch (Class) { |
| 1947 | case IC_Retain: |
| 1948 | case IC_RetainBlock: |
| 1949 | // These can always be moved up. |
| 1950 | break; |
| 1951 | case IC_Release: |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1952 | // These can't be moved across things that care about the retain |
| 1953 | // count. |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 1954 | FindDependencies(NeedsPositiveRetainCount, Arg, |
| 1955 | Inst->getParent(), Inst, |
| 1956 | DependingInstructions, Visited, PA); |
| 1957 | break; |
| 1958 | case IC_Autorelease: |
| 1959 | // These can't be moved across autorelease pool scope boundaries. |
| 1960 | FindDependencies(AutoreleasePoolBoundary, Arg, |
| 1961 | Inst->getParent(), Inst, |
| 1962 | DependingInstructions, Visited, PA); |
| 1963 | break; |
| 1964 | case IC_RetainRV: |
| 1965 | case IC_AutoreleaseRV: |
| 1966 | // Don't move these; the RV optimization depends on the autoreleaseRV |
| 1967 | // being tail called, and the retainRV being immediately after a call |
| 1968 | // (which might still happen if we get lucky with codegen layout, but |
| 1969 | // it's not worth taking the chance). |
| 1970 | continue; |
| 1971 | default: |
| 1972 | llvm_unreachable("Invalid dependence flavor"); |
| 1973 | } |
| 1974 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1975 | if (DependingInstructions.size() == 1 && |
| 1976 | *DependingInstructions.begin() == PN) { |
| 1977 | Changed = true; |
| 1978 | ++NumPartialNoops; |
| 1979 | // Clone the call into each predecessor that has a non-null value. |
| 1980 | CallInst *CInst = cast<CallInst>(Inst); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1981 | Type *ParamTy = CInst->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1982 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 1983 | Value *Incoming = |
| 1984 | StripPointerCastsAndObjCCalls(PN->getIncomingValue(i)); |
| 1985 | if (!isNullOrUndef(Incoming)) { |
| 1986 | CallInst *Clone = cast<CallInst>(CInst->clone()); |
| 1987 | Value *Op = PN->getIncomingValue(i); |
| 1988 | Instruction *InsertPos = &PN->getIncomingBlock(i)->back(); |
| 1989 | if (Op->getType() != ParamTy) |
| 1990 | Op = new BitCastInst(Op, ParamTy, "", InsertPos); |
| 1991 | Clone->setArgOperand(0, Op); |
| 1992 | Clone->insertBefore(InsertPos); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 1993 | |
| 1994 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning " |
| 1995 | << *CInst << "\n" |
| 1996 | " And inserting " |
| 1997 | "clone at " << *InsertPos << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1998 | Worklist.push_back(std::make_pair(Clone, Incoming)); |
| 1999 | } |
| 2000 | } |
| 2001 | // Erase the original call. |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2002 | DEBUG(dbgs() << "Erasing: " << *CInst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2003 | EraseInstruction(CInst); |
| 2004 | continue; |
| 2005 | } |
| 2006 | } |
| 2007 | } while (!Worklist.empty()); |
| 2008 | } |
Michael Gottesman | b24bdef | 2013-01-12 02:57:16 +0000 | [diff] [blame] | 2009 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2010 | } |
| 2011 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2012 | /// Check for critical edges, loop boundaries, irreducible control flow, or |
| 2013 | /// other CFG structures where moving code across the edge would result in it |
| 2014 | /// being executed more. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2015 | void |
| 2016 | ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB, |
| 2017 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 2018 | BBState &MyStates) const { |
| 2019 | // If any top-down local-use or possible-dec has a succ which is earlier in |
| 2020 | // the sequence, forget it. |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 2021 | for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(), |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2022 | E = MyStates.top_down_ptr_end(); I != E; ++I) |
| 2023 | switch (I->second.GetSeq()) { |
| 2024 | default: break; |
| 2025 | case S_Use: { |
| 2026 | const Value *Arg = I->first; |
| 2027 | const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); |
| 2028 | bool SomeSuccHasSame = false; |
| 2029 | bool AllSuccsHaveSame = true; |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 2030 | PtrState &S = I->second; |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 2031 | succ_const_iterator SI(TI), SE(TI, false); |
| 2032 | |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 2033 | for (; SI != SE; ++SI) { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2034 | Sequence SuccSSeq = S_None; |
| 2035 | bool SuccSRRIKnownSafe = false; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2036 | // If VisitBottomUp has pointer information for this successor, take |
| 2037 | // what we know about it. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2038 | DenseMap<const BasicBlock *, BBState>::iterator BBI = |
| 2039 | BBStates.find(*SI); |
| 2040 | assert(BBI != BBStates.end()); |
| 2041 | const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg); |
| 2042 | SuccSSeq = SuccS.GetSeq(); |
| 2043 | SuccSRRIKnownSafe = SuccS.RRI.KnownSafe; |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2044 | switch (SuccSSeq) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2045 | case S_None: |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2046 | case S_CanRelease: { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2047 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) { |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2048 | S.ClearSequenceProgress(); |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2049 | break; |
| 2050 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2051 | continue; |
| 2052 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2053 | case S_Use: |
| 2054 | SomeSuccHasSame = true; |
| 2055 | break; |
| 2056 | case S_Stop: |
| 2057 | case S_Release: |
| 2058 | case S_MovableRelease: |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2059 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2060 | AllSuccsHaveSame = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2061 | break; |
| 2062 | case S_Retain: |
| 2063 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 2064 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2065 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2066 | // If the state at the other end of any of the successor edges |
| 2067 | // matches the current state, require all edges to match. This |
| 2068 | // guards against loops in the middle of a sequence. |
| 2069 | if (SomeSuccHasSame && !AllSuccsHaveSame) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2070 | S.ClearSequenceProgress(); |
Dan Gohman | 04443706 | 2011-12-12 18:13:53 +0000 | [diff] [blame] | 2071 | break; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2072 | } |
| 2073 | case S_CanRelease: { |
| 2074 | const Value *Arg = I->first; |
| 2075 | const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); |
| 2076 | bool SomeSuccHasSame = false; |
| 2077 | bool AllSuccsHaveSame = true; |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 2078 | PtrState &S = I->second; |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 2079 | succ_const_iterator SI(TI), SE(TI, false); |
| 2080 | |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 2081 | for (; SI != SE; ++SI) { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2082 | Sequence SuccSSeq = S_None; |
| 2083 | bool SuccSRRIKnownSafe = false; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2084 | // If VisitBottomUp has pointer information for this successor, take |
| 2085 | // what we know about it. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2086 | DenseMap<const BasicBlock *, BBState>::iterator BBI = |
| 2087 | BBStates.find(*SI); |
| 2088 | assert(BBI != BBStates.end()); |
| 2089 | const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg); |
| 2090 | SuccSSeq = SuccS.GetSeq(); |
| 2091 | SuccSRRIKnownSafe = SuccS.RRI.KnownSafe; |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2092 | switch (SuccSSeq) { |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2093 | case S_None: { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2094 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) { |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2095 | S.ClearSequenceProgress(); |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2096 | break; |
| 2097 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2098 | continue; |
| 2099 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2100 | case S_CanRelease: |
| 2101 | SomeSuccHasSame = true; |
| 2102 | break; |
| 2103 | case S_Stop: |
| 2104 | case S_Release: |
| 2105 | case S_MovableRelease: |
| 2106 | case S_Use: |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2107 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2108 | AllSuccsHaveSame = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2109 | break; |
| 2110 | case S_Retain: |
| 2111 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 2112 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2113 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2114 | // If the state at the other end of any of the successor edges |
| 2115 | // matches the current state, require all edges to match. This |
| 2116 | // guards against loops in the middle of a sequence. |
| 2117 | if (SomeSuccHasSame && !AllSuccsHaveSame) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2118 | S.ClearSequenceProgress(); |
Dan Gohman | 04443706 | 2011-12-12 18:13:53 +0000 | [diff] [blame] | 2119 | break; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2120 | } |
| 2121 | } |
| 2122 | } |
| 2123 | |
| 2124 | bool |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2125 | ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst, |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2126 | BasicBlock *BB, |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2127 | MapVector<Value *, RRInfo> &Retains, |
| 2128 | BBState &MyStates) { |
| 2129 | bool NestingDetected = false; |
| 2130 | InstructionClass Class = GetInstructionClass(Inst); |
| 2131 | const Value *Arg = 0; |
| 2132 | |
| 2133 | switch (Class) { |
| 2134 | case IC_Release: { |
| 2135 | Arg = GetObjCArg(Inst); |
| 2136 | |
| 2137 | PtrState &S = MyStates.getPtrBottomUpState(Arg); |
| 2138 | |
| 2139 | // If we see two releases in a row on the same pointer. If so, make |
| 2140 | // a note, and we'll cicle back to revisit it after we've |
| 2141 | // hopefully eliminated the second release, which may allow us to |
| 2142 | // eliminate the first release too. |
| 2143 | // Theoretically we could implement removal of nested retain+release |
| 2144 | // pairs by making PtrState hold a stack of states, but this is |
| 2145 | // simple and avoids adding overhead for the non-nested case. |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 2146 | if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) { |
| 2147 | DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested " |
| 2148 | "releases (i.e. a release pair)\n"); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2149 | NestingDetected = true; |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 2150 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2151 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2152 | MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 2153 | S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2154 | S.RRI.ReleaseMetadata = ReleaseMetadata; |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2155 | S.RRI.KnownSafe = S.IsKnownIncremented(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2156 | S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall(); |
| 2157 | S.RRI.Calls.insert(Inst); |
| 2158 | |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2159 | S.SetKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2160 | break; |
| 2161 | } |
| 2162 | case IC_RetainBlock: |
| 2163 | // An objc_retainBlock call with just a use may need to be kept, |
| 2164 | // because it may be copying a block from the stack to the heap. |
| 2165 | if (!IsRetainBlockOptimizable(Inst)) |
| 2166 | break; |
| 2167 | // FALLTHROUGH |
| 2168 | case IC_Retain: |
| 2169 | case IC_RetainRV: { |
| 2170 | Arg = GetObjCArg(Inst); |
| 2171 | |
| 2172 | PtrState &S = MyStates.getPtrBottomUpState(Arg); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 2173 | S.SetKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2174 | |
| 2175 | switch (S.GetSeq()) { |
| 2176 | case S_Stop: |
| 2177 | case S_Release: |
| 2178 | case S_MovableRelease: |
| 2179 | case S_Use: |
| 2180 | S.RRI.ReverseInsertPts.clear(); |
| 2181 | // FALL THROUGH |
| 2182 | case S_CanRelease: |
| 2183 | // Don't do retain+release tracking for IC_RetainRV, because it's |
| 2184 | // better to let it remain as the first instruction after a call. |
| 2185 | if (Class != IC_RetainRV) { |
| 2186 | S.RRI.IsRetainBlock = Class == IC_RetainBlock; |
| 2187 | Retains[Inst] = S.RRI; |
| 2188 | } |
| 2189 | S.ClearSequenceProgress(); |
| 2190 | break; |
| 2191 | case S_None: |
| 2192 | break; |
| 2193 | case S_Retain: |
| 2194 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 2195 | } |
| 2196 | return NestingDetected; |
| 2197 | } |
| 2198 | case IC_AutoreleasepoolPop: |
| 2199 | // Conservatively, clear MyStates for all known pointers. |
| 2200 | MyStates.clearBottomUpPointers(); |
| 2201 | return NestingDetected; |
| 2202 | case IC_AutoreleasepoolPush: |
| 2203 | case IC_None: |
| 2204 | // These are irrelevant. |
| 2205 | return NestingDetected; |
| 2206 | default: |
| 2207 | break; |
| 2208 | } |
| 2209 | |
| 2210 | // Consider any other possible effects of this instruction on each |
| 2211 | // pointer being tracked. |
| 2212 | for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(), |
| 2213 | ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) { |
| 2214 | const Value *Ptr = MI->first; |
| 2215 | if (Ptr == Arg) |
| 2216 | continue; // Handled above. |
| 2217 | PtrState &S = MI->second; |
| 2218 | Sequence Seq = S.GetSeq(); |
| 2219 | |
| 2220 | // Check for possible releases. |
| 2221 | if (CanAlterRefCount(Inst, Ptr, PA, Class)) { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 2222 | S.ClearRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2223 | switch (Seq) { |
| 2224 | case S_Use: |
| 2225 | S.SetSeq(S_CanRelease); |
| 2226 | continue; |
| 2227 | case S_CanRelease: |
| 2228 | case S_Release: |
| 2229 | case S_MovableRelease: |
| 2230 | case S_Stop: |
| 2231 | case S_None: |
| 2232 | break; |
| 2233 | case S_Retain: |
| 2234 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 2235 | } |
| 2236 | } |
| 2237 | |
| 2238 | // Check for possible direct uses. |
| 2239 | switch (Seq) { |
| 2240 | case S_Release: |
| 2241 | case S_MovableRelease: |
| 2242 | if (CanUse(Inst, Ptr, PA, Class)) { |
| 2243 | assert(S.RRI.ReverseInsertPts.empty()); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2244 | // If this is an invoke instruction, we're scanning it as part of |
| 2245 | // one of its successor blocks, since we can't insert code after it |
| 2246 | // in its own block, and we don't want to split critical edges. |
| 2247 | if (isa<InvokeInst>(Inst)) |
| 2248 | S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt()); |
| 2249 | else |
Francois Pichet | 4b9ab74 | 2012-03-24 01:36:37 +0000 | [diff] [blame] | 2250 | S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst))); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2251 | S.SetSeq(S_Use); |
| 2252 | } else if (Seq == S_Release && |
| 2253 | (Class == IC_User || Class == IC_CallOrUser)) { |
| 2254 | // Non-movable releases depend on any possible objc pointer use. |
| 2255 | S.SetSeq(S_Stop); |
| 2256 | assert(S.RRI.ReverseInsertPts.empty()); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2257 | // As above; handle invoke specially. |
| 2258 | if (isa<InvokeInst>(Inst)) |
| 2259 | S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt()); |
| 2260 | else |
Francois Pichet | 4b9ab74 | 2012-03-24 01:36:37 +0000 | [diff] [blame] | 2261 | S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst))); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2262 | } |
| 2263 | break; |
| 2264 | case S_Stop: |
| 2265 | if (CanUse(Inst, Ptr, PA, Class)) |
| 2266 | S.SetSeq(S_Use); |
| 2267 | break; |
| 2268 | case S_CanRelease: |
| 2269 | case S_Use: |
| 2270 | case S_None: |
| 2271 | break; |
| 2272 | case S_Retain: |
| 2273 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 2274 | } |
| 2275 | } |
| 2276 | |
| 2277 | return NestingDetected; |
| 2278 | } |
| 2279 | |
| 2280 | bool |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2281 | ObjCARCOpt::VisitBottomUp(BasicBlock *BB, |
| 2282 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 2283 | MapVector<Value *, RRInfo> &Retains) { |
| 2284 | bool NestingDetected = false; |
| 2285 | BBState &MyStates = BBStates[BB]; |
| 2286 | |
| 2287 | // Merge the states from each successor to compute the initial state |
| 2288 | // for the current block. |
Dan Gohman | 10c82ce | 2012-08-27 18:31:36 +0000 | [diff] [blame] | 2289 | BBState::edge_iterator SI(MyStates.succ_begin()), |
| 2290 | SE(MyStates.succ_end()); |
| 2291 | if (SI != SE) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2292 | const BasicBlock *Succ = *SI; |
| 2293 | DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ); |
| 2294 | assert(I != BBStates.end()); |
| 2295 | MyStates.InitFromSucc(I->second); |
| 2296 | ++SI; |
| 2297 | for (; SI != SE; ++SI) { |
| 2298 | Succ = *SI; |
| 2299 | I = BBStates.find(Succ); |
| 2300 | assert(I != BBStates.end()); |
| 2301 | MyStates.MergeSucc(I->second); |
| 2302 | } |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 2303 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2304 | |
| 2305 | // Visit all the instructions, bottom-up. |
| 2306 | for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) { |
| 2307 | Instruction *Inst = llvm::prior(I); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2308 | |
| 2309 | // Invoke instructions are visited as part of their successors (below). |
| 2310 | if (isa<InvokeInst>(Inst)) |
| 2311 | continue; |
| 2312 | |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 2313 | DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n"); |
| 2314 | |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2315 | NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates); |
| 2316 | } |
| 2317 | |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2318 | // If there's a predecessor with an invoke, visit the invoke as if it were |
| 2319 | // part of this block, since we can't insert code after an invoke in its own |
| 2320 | // block, and we don't want to split critical edges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2321 | for (BBState::edge_iterator PI(MyStates.pred_begin()), |
| 2322 | PE(MyStates.pred_end()); PI != PE; ++PI) { |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2323 | BasicBlock *Pred = *PI; |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2324 | if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back())) |
| 2325 | NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2326 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2327 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2328 | return NestingDetected; |
| 2329 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2330 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2331 | bool |
| 2332 | ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst, |
| 2333 | DenseMap<Value *, RRInfo> &Releases, |
| 2334 | BBState &MyStates) { |
| 2335 | bool NestingDetected = false; |
| 2336 | InstructionClass Class = GetInstructionClass(Inst); |
| 2337 | const Value *Arg = 0; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2338 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2339 | switch (Class) { |
| 2340 | case IC_RetainBlock: |
| 2341 | // An objc_retainBlock call with just a use may need to be kept, |
| 2342 | // because it may be copying a block from the stack to the heap. |
| 2343 | if (!IsRetainBlockOptimizable(Inst)) |
| 2344 | break; |
| 2345 | // FALLTHROUGH |
| 2346 | case IC_Retain: |
| 2347 | case IC_RetainRV: { |
| 2348 | Arg = GetObjCArg(Inst); |
| 2349 | |
| 2350 | PtrState &S = MyStates.getPtrTopDownState(Arg); |
| 2351 | |
| 2352 | // Don't do retain+release tracking for IC_RetainRV, because it's |
| 2353 | // better to let it remain as the first instruction after a call. |
| 2354 | if (Class != IC_RetainRV) { |
| 2355 | // 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] | 2356 | // 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] | 2357 | // hopefully eliminated the second retain, which may allow us to |
| 2358 | // eliminate the first retain too. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2359 | // Theoretically we could implement removal of nested retain+release |
| 2360 | // pairs by making PtrState hold a stack of states, but this is |
| 2361 | // simple and avoids adding overhead for the non-nested case. |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2362 | if (S.GetSeq() == S_Retain) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2363 | NestingDetected = true; |
| 2364 | |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 2365 | S.ResetSequenceProgress(S_Retain); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2366 | S.RRI.IsRetainBlock = Class == IC_RetainBlock; |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2367 | S.RRI.KnownSafe = S.IsKnownIncremented(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2368 | S.RRI.Calls.insert(Inst); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2369 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2370 | |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2371 | S.SetKnownPositiveRefCount(); |
Dan Gohman | f64ff8e | 2012-07-23 19:27:31 +0000 | [diff] [blame] | 2372 | |
| 2373 | // A retain can be a potential use; procede to the generic checking |
| 2374 | // code below. |
| 2375 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2376 | } |
| 2377 | case IC_Release: { |
| 2378 | Arg = GetObjCArg(Inst); |
| 2379 | |
| 2380 | PtrState &S = MyStates.getPtrTopDownState(Arg); |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2381 | S.ClearRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2382 | |
| 2383 | switch (S.GetSeq()) { |
| 2384 | case S_Retain: |
| 2385 | case S_CanRelease: |
| 2386 | S.RRI.ReverseInsertPts.clear(); |
| 2387 | // FALL THROUGH |
| 2388 | case S_Use: |
| 2389 | S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind); |
| 2390 | S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall(); |
| 2391 | Releases[Inst] = S.RRI; |
| 2392 | S.ClearSequenceProgress(); |
| 2393 | break; |
| 2394 | case S_None: |
| 2395 | break; |
| 2396 | case S_Stop: |
| 2397 | case S_Release: |
| 2398 | case S_MovableRelease: |
| 2399 | llvm_unreachable("top-down pointer in release state!"); |
| 2400 | } |
| 2401 | break; |
| 2402 | } |
| 2403 | case IC_AutoreleasepoolPop: |
| 2404 | // Conservatively, clear MyStates for all known pointers. |
| 2405 | MyStates.clearTopDownPointers(); |
| 2406 | return NestingDetected; |
| 2407 | case IC_AutoreleasepoolPush: |
| 2408 | case IC_None: |
| 2409 | // These are irrelevant. |
| 2410 | return NestingDetected; |
| 2411 | default: |
| 2412 | break; |
| 2413 | } |
| 2414 | |
| 2415 | // Consider any other possible effects of this instruction on each |
| 2416 | // pointer being tracked. |
| 2417 | for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(), |
| 2418 | ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) { |
| 2419 | const Value *Ptr = MI->first; |
| 2420 | if (Ptr == Arg) |
| 2421 | continue; // Handled above. |
| 2422 | PtrState &S = MI->second; |
| 2423 | Sequence Seq = S.GetSeq(); |
| 2424 | |
| 2425 | // Check for possible releases. |
| 2426 | if (CanAlterRefCount(Inst, Ptr, PA, Class)) { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 2427 | S.ClearRefCount(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2428 | switch (Seq) { |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2429 | case S_Retain: |
| 2430 | S.SetSeq(S_CanRelease); |
| 2431 | assert(S.RRI.ReverseInsertPts.empty()); |
| 2432 | S.RRI.ReverseInsertPts.insert(Inst); |
| 2433 | |
| 2434 | // One call can't cause a transition from S_Retain to S_CanRelease |
| 2435 | // and S_CanRelease to S_Use. If we've made the first transition, |
| 2436 | // we're done. |
| 2437 | continue; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2438 | case S_Use: |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2439 | case S_CanRelease: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2440 | case S_None: |
| 2441 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2442 | case S_Stop: |
| 2443 | case S_Release: |
| 2444 | case S_MovableRelease: |
| 2445 | llvm_unreachable("top-down pointer in release state!"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2446 | } |
| 2447 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2448 | |
| 2449 | // Check for possible direct uses. |
| 2450 | switch (Seq) { |
| 2451 | case S_CanRelease: |
| 2452 | if (CanUse(Inst, Ptr, PA, Class)) |
| 2453 | S.SetSeq(S_Use); |
| 2454 | break; |
| 2455 | case S_Retain: |
| 2456 | case S_Use: |
| 2457 | case S_None: |
| 2458 | break; |
| 2459 | case S_Stop: |
| 2460 | case S_Release: |
| 2461 | case S_MovableRelease: |
| 2462 | llvm_unreachable("top-down pointer in release state!"); |
| 2463 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2464 | } |
| 2465 | |
| 2466 | return NestingDetected; |
| 2467 | } |
| 2468 | |
| 2469 | bool |
| 2470 | ObjCARCOpt::VisitTopDown(BasicBlock *BB, |
| 2471 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 2472 | DenseMap<Value *, RRInfo> &Releases) { |
| 2473 | bool NestingDetected = false; |
| 2474 | BBState &MyStates = BBStates[BB]; |
| 2475 | |
| 2476 | // Merge the states from each predecessor to compute the initial state |
| 2477 | // for the current block. |
Dan Gohman | 10c82ce | 2012-08-27 18:31:36 +0000 | [diff] [blame] | 2478 | BBState::edge_iterator PI(MyStates.pred_begin()), |
| 2479 | PE(MyStates.pred_end()); |
| 2480 | if (PI != PE) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2481 | const BasicBlock *Pred = *PI; |
| 2482 | DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred); |
| 2483 | assert(I != BBStates.end()); |
| 2484 | MyStates.InitFromPred(I->second); |
| 2485 | ++PI; |
| 2486 | for (; PI != PE; ++PI) { |
| 2487 | Pred = *PI; |
| 2488 | I = BBStates.find(Pred); |
| 2489 | assert(I != BBStates.end()); |
| 2490 | MyStates.MergePred(I->second); |
| 2491 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2492 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2493 | |
| 2494 | // Visit all the instructions, top-down. |
| 2495 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 2496 | Instruction *Inst = I; |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 2497 | |
| 2498 | DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n"); |
| 2499 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2500 | NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2501 | } |
| 2502 | |
| 2503 | CheckForCFGHazards(BB, BBStates, MyStates); |
| 2504 | return NestingDetected; |
| 2505 | } |
| 2506 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2507 | static void |
| 2508 | ComputePostOrders(Function &F, |
| 2509 | SmallVectorImpl<BasicBlock *> &PostOrder, |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2510 | SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder, |
| 2511 | unsigned NoObjCARCExceptionsMDKind, |
| 2512 | DenseMap<const BasicBlock *, BBState> &BBStates) { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2513 | /// The visited set, for doing DFS walks. |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2514 | SmallPtrSet<BasicBlock *, 16> Visited; |
| 2515 | |
| 2516 | // Do DFS, computing the PostOrder. |
| 2517 | SmallPtrSet<BasicBlock *, 16> OnStack; |
| 2518 | SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2519 | |
| 2520 | // Functions always have exactly one entry block, and we don't have |
| 2521 | // any other block that we treat like an entry block. |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2522 | BasicBlock *EntryBB = &F.getEntryBlock(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2523 | BBState &MyStates = BBStates[EntryBB]; |
| 2524 | MyStates.SetAsEntry(); |
| 2525 | TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back()); |
| 2526 | SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI))); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2527 | Visited.insert(EntryBB); |
| 2528 | OnStack.insert(EntryBB); |
| 2529 | do { |
| 2530 | dfs_next_succ: |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2531 | BasicBlock *CurrBB = SuccStack.back().first; |
| 2532 | TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back()); |
| 2533 | succ_iterator SE(TI, false); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2534 | |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2535 | while (SuccStack.back().second != SE) { |
| 2536 | BasicBlock *SuccBB = *SuccStack.back().second++; |
| 2537 | if (Visited.insert(SuccBB)) { |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2538 | TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back()); |
| 2539 | SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI))); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2540 | BBStates[CurrBB].addSucc(SuccBB); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2541 | BBState &SuccStates = BBStates[SuccBB]; |
| 2542 | SuccStates.addPred(CurrBB); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2543 | OnStack.insert(SuccBB); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2544 | goto dfs_next_succ; |
| 2545 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2546 | |
| 2547 | if (!OnStack.count(SuccBB)) { |
| 2548 | BBStates[CurrBB].addSucc(SuccBB); |
| 2549 | BBStates[SuccBB].addPred(CurrBB); |
| 2550 | } |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2551 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2552 | OnStack.erase(CurrBB); |
| 2553 | PostOrder.push_back(CurrBB); |
| 2554 | SuccStack.pop_back(); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2555 | } while (!SuccStack.empty()); |
| 2556 | |
| 2557 | Visited.clear(); |
| 2558 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2559 | // Do reverse-CFG DFS, computing the reverse-CFG PostOrder. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2560 | // Functions may have many exits, and there also blocks which we treat |
| 2561 | // as exits due to ignored edges. |
| 2562 | SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack; |
| 2563 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { |
| 2564 | BasicBlock *ExitBB = I; |
| 2565 | BBState &MyStates = BBStates[ExitBB]; |
| 2566 | if (!MyStates.isExit()) |
| 2567 | continue; |
| 2568 | |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2569 | MyStates.SetAsExit(); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2570 | |
| 2571 | PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin())); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2572 | Visited.insert(ExitBB); |
| 2573 | while (!PredStack.empty()) { |
| 2574 | reverse_dfs_next_succ: |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2575 | BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end(); |
| 2576 | while (PredStack.back().second != PE) { |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2577 | BasicBlock *BB = *PredStack.back().second++; |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2578 | if (Visited.insert(BB)) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2579 | PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin())); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2580 | goto reverse_dfs_next_succ; |
| 2581 | } |
| 2582 | } |
| 2583 | ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first); |
| 2584 | } |
| 2585 | } |
| 2586 | } |
| 2587 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2588 | // Visit the function both top-down and bottom-up. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2589 | bool |
| 2590 | ObjCARCOpt::Visit(Function &F, |
| 2591 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 2592 | MapVector<Value *, RRInfo> &Retains, |
| 2593 | DenseMap<Value *, RRInfo> &Releases) { |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2594 | |
| 2595 | // Use reverse-postorder traversals, because we magically know that loops |
| 2596 | // will be well behaved, i.e. they won't repeatedly call retain on a single |
| 2597 | // pointer without doing a release. We can't use the ReversePostOrderTraversal |
| 2598 | // class here because we want the reverse-CFG postorder to consider each |
| 2599 | // function exit point, and we want to ignore selected cycle edges. |
| 2600 | SmallVector<BasicBlock *, 16> PostOrder; |
| 2601 | SmallVector<BasicBlock *, 16> ReverseCFGPostOrder; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2602 | ComputePostOrders(F, PostOrder, ReverseCFGPostOrder, |
| 2603 | NoObjCARCExceptionsMDKind, |
| 2604 | BBStates); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2605 | |
| 2606 | // Use reverse-postorder on the reverse CFG for bottom-up. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2607 | bool BottomUpNestingDetected = false; |
Dan Gohman | c57b58c | 2011-08-18 21:27:42 +0000 | [diff] [blame] | 2608 | for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I = |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2609 | ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend(); |
| 2610 | I != E; ++I) |
| 2611 | BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2612 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2613 | // Use reverse-postorder for top-down. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2614 | bool TopDownNestingDetected = false; |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2615 | for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I = |
| 2616 | PostOrder.rbegin(), E = PostOrder.rend(); |
| 2617 | I != E; ++I) |
| 2618 | TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2619 | |
| 2620 | return TopDownNestingDetected && BottomUpNestingDetected; |
| 2621 | } |
| 2622 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2623 | /// Move the calls in RetainsToMove and ReleasesToMove. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2624 | void ObjCARCOpt::MoveCalls(Value *Arg, |
| 2625 | RRInfo &RetainsToMove, |
| 2626 | RRInfo &ReleasesToMove, |
| 2627 | MapVector<Value *, RRInfo> &Retains, |
| 2628 | DenseMap<Value *, RRInfo> &Releases, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2629 | SmallVectorImpl<Instruction *> &DeadInsts, |
| 2630 | Module *M) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2631 | Type *ArgTy = Arg->getType(); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2632 | Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext())); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2633 | |
| 2634 | // Insert the new retain and release calls. |
| 2635 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2636 | PI = ReleasesToMove.ReverseInsertPts.begin(), |
| 2637 | PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) { |
| 2638 | Instruction *InsertPt = *PI; |
| 2639 | Value *MyArg = ArgTy == ParamTy ? Arg : |
| 2640 | new BitCastInst(Arg, ParamTy, "", InsertPt); |
| 2641 | CallInst *Call = |
| 2642 | CallInst::Create(RetainsToMove.IsRetainBlock ? |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2643 | getRetainBlockCallee(M) : getRetainCallee(M), |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2644 | MyArg, "", InsertPt); |
| 2645 | Call->setDoesNotThrow(); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 2646 | if (RetainsToMove.IsRetainBlock) |
Dan Gohman | a7107f9 | 2011-10-17 22:53:25 +0000 | [diff] [blame] | 2647 | Call->setMetadata(CopyOnEscapeMDKind, |
| 2648 | MDNode::get(M->getContext(), ArrayRef<Value *>())); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 2649 | else |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2650 | Call->setTailCall(); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2651 | |
| 2652 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call |
| 2653 | << "\n" |
| 2654 | " At insertion point: " << *InsertPt |
| 2655 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2656 | } |
| 2657 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2658 | PI = RetainsToMove.ReverseInsertPts.begin(), |
| 2659 | PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) { |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2660 | Instruction *InsertPt = *PI; |
| 2661 | Value *MyArg = ArgTy == ParamTy ? Arg : |
| 2662 | new BitCastInst(Arg, ParamTy, "", InsertPt); |
| 2663 | CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg, |
| 2664 | "", InsertPt); |
| 2665 | // Attach a clang.imprecise_release metadata tag, if appropriate. |
| 2666 | if (MDNode *M = ReleasesToMove.ReleaseMetadata) |
| 2667 | Call->setMetadata(ImpreciseReleaseMDKind, M); |
| 2668 | Call->setDoesNotThrow(); |
| 2669 | if (ReleasesToMove.IsTailCallRelease) |
| 2670 | Call->setTailCall(); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2671 | |
| 2672 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call |
| 2673 | << "\n" |
| 2674 | " At insertion point: " << *InsertPt |
| 2675 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2676 | } |
| 2677 | |
| 2678 | // Delete the original retain and release calls. |
| 2679 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2680 | AI = RetainsToMove.Calls.begin(), |
| 2681 | AE = RetainsToMove.Calls.end(); AI != AE; ++AI) { |
| 2682 | Instruction *OrigRetain = *AI; |
| 2683 | Retains.blot(OrigRetain); |
| 2684 | DeadInsts.push_back(OrigRetain); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2685 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain << |
| 2686 | "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2687 | } |
| 2688 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2689 | AI = ReleasesToMove.Calls.begin(), |
| 2690 | AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) { |
| 2691 | Instruction *OrigRelease = *AI; |
| 2692 | Releases.erase(OrigRelease); |
| 2693 | DeadInsts.push_back(OrigRelease); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2694 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease |
| 2695 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2696 | } |
| 2697 | } |
| 2698 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2699 | bool |
| 2700 | ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> |
| 2701 | &BBStates, |
| 2702 | MapVector<Value *, RRInfo> &Retains, |
| 2703 | DenseMap<Value *, RRInfo> &Releases, |
| 2704 | Module *M, |
| 2705 | SmallVector<Instruction *, 4> &NewRetains, |
| 2706 | SmallVector<Instruction *, 4> &NewReleases, |
| 2707 | SmallVector<Instruction *, 8> &DeadInsts, |
| 2708 | RRInfo &RetainsToMove, |
| 2709 | RRInfo &ReleasesToMove, |
| 2710 | Value *Arg, |
| 2711 | bool KnownSafe, |
| 2712 | bool &AnyPairsCompletelyEliminated) { |
| 2713 | // If a pair happens in a region where it is known that the reference count |
| 2714 | // is already incremented, we can similarly ignore possible decrements. |
| 2715 | bool KnownSafeTD = true, KnownSafeBU = true; |
| 2716 | |
| 2717 | // Connect the dots between the top-down-collected RetainsToMove and |
| 2718 | // bottom-up-collected ReleasesToMove to form sets of related calls. |
| 2719 | // This is an iterative process so that we connect multiple releases |
| 2720 | // to multiple retains if needed. |
| 2721 | unsigned OldDelta = 0; |
| 2722 | unsigned NewDelta = 0; |
| 2723 | unsigned OldCount = 0; |
| 2724 | unsigned NewCount = 0; |
| 2725 | bool FirstRelease = true; |
| 2726 | bool FirstRetain = true; |
| 2727 | for (;;) { |
| 2728 | for (SmallVectorImpl<Instruction *>::const_iterator |
| 2729 | NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) { |
| 2730 | Instruction *NewRetain = *NI; |
| 2731 | MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain); |
| 2732 | assert(It != Retains.end()); |
| 2733 | const RRInfo &NewRetainRRI = It->second; |
| 2734 | KnownSafeTD &= NewRetainRRI.KnownSafe; |
| 2735 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2736 | LI = NewRetainRRI.Calls.begin(), |
| 2737 | LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) { |
| 2738 | Instruction *NewRetainRelease = *LI; |
| 2739 | DenseMap<Value *, RRInfo>::const_iterator Jt = |
| 2740 | Releases.find(NewRetainRelease); |
| 2741 | if (Jt == Releases.end()) |
| 2742 | return false; |
| 2743 | const RRInfo &NewRetainReleaseRRI = Jt->second; |
| 2744 | assert(NewRetainReleaseRRI.Calls.count(NewRetain)); |
| 2745 | if (ReleasesToMove.Calls.insert(NewRetainRelease)) { |
| 2746 | OldDelta -= |
| 2747 | BBStates[NewRetainRelease->getParent()].GetAllPathCount(); |
| 2748 | |
| 2749 | // Merge the ReleaseMetadata and IsTailCallRelease values. |
| 2750 | if (FirstRelease) { |
| 2751 | ReleasesToMove.ReleaseMetadata = |
| 2752 | NewRetainReleaseRRI.ReleaseMetadata; |
| 2753 | ReleasesToMove.IsTailCallRelease = |
| 2754 | NewRetainReleaseRRI.IsTailCallRelease; |
| 2755 | FirstRelease = false; |
| 2756 | } else { |
| 2757 | if (ReleasesToMove.ReleaseMetadata != |
| 2758 | NewRetainReleaseRRI.ReleaseMetadata) |
| 2759 | ReleasesToMove.ReleaseMetadata = 0; |
| 2760 | if (ReleasesToMove.IsTailCallRelease != |
| 2761 | NewRetainReleaseRRI.IsTailCallRelease) |
| 2762 | ReleasesToMove.IsTailCallRelease = false; |
| 2763 | } |
| 2764 | |
| 2765 | // Collect the optimal insertion points. |
| 2766 | if (!KnownSafe) |
| 2767 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2768 | RI = NewRetainReleaseRRI.ReverseInsertPts.begin(), |
| 2769 | RE = NewRetainReleaseRRI.ReverseInsertPts.end(); |
| 2770 | RI != RE; ++RI) { |
| 2771 | Instruction *RIP = *RI; |
| 2772 | if (ReleasesToMove.ReverseInsertPts.insert(RIP)) |
| 2773 | NewDelta -= BBStates[RIP->getParent()].GetAllPathCount(); |
| 2774 | } |
| 2775 | NewReleases.push_back(NewRetainRelease); |
| 2776 | } |
| 2777 | } |
| 2778 | } |
| 2779 | NewRetains.clear(); |
| 2780 | if (NewReleases.empty()) break; |
| 2781 | |
| 2782 | // Back the other way. |
| 2783 | for (SmallVectorImpl<Instruction *>::const_iterator |
| 2784 | NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) { |
| 2785 | Instruction *NewRelease = *NI; |
| 2786 | DenseMap<Value *, RRInfo>::const_iterator It = |
| 2787 | Releases.find(NewRelease); |
| 2788 | assert(It != Releases.end()); |
| 2789 | const RRInfo &NewReleaseRRI = It->second; |
| 2790 | KnownSafeBU &= NewReleaseRRI.KnownSafe; |
| 2791 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2792 | LI = NewReleaseRRI.Calls.begin(), |
| 2793 | LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) { |
| 2794 | Instruction *NewReleaseRetain = *LI; |
| 2795 | MapVector<Value *, RRInfo>::const_iterator Jt = |
| 2796 | Retains.find(NewReleaseRetain); |
| 2797 | if (Jt == Retains.end()) |
| 2798 | return false; |
| 2799 | const RRInfo &NewReleaseRetainRRI = Jt->second; |
| 2800 | assert(NewReleaseRetainRRI.Calls.count(NewRelease)); |
| 2801 | if (RetainsToMove.Calls.insert(NewReleaseRetain)) { |
| 2802 | unsigned PathCount = |
| 2803 | BBStates[NewReleaseRetain->getParent()].GetAllPathCount(); |
| 2804 | OldDelta += PathCount; |
| 2805 | OldCount += PathCount; |
| 2806 | |
| 2807 | // Merge the IsRetainBlock values. |
| 2808 | if (FirstRetain) { |
| 2809 | RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock; |
| 2810 | FirstRetain = false; |
| 2811 | } else if (ReleasesToMove.IsRetainBlock != |
| 2812 | NewReleaseRetainRRI.IsRetainBlock) |
| 2813 | // It's not possible to merge the sequences if one uses |
| 2814 | // objc_retain and the other uses objc_retainBlock. |
| 2815 | return false; |
| 2816 | |
| 2817 | // Collect the optimal insertion points. |
| 2818 | if (!KnownSafe) |
| 2819 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2820 | RI = NewReleaseRetainRRI.ReverseInsertPts.begin(), |
| 2821 | RE = NewReleaseRetainRRI.ReverseInsertPts.end(); |
| 2822 | RI != RE; ++RI) { |
| 2823 | Instruction *RIP = *RI; |
| 2824 | if (RetainsToMove.ReverseInsertPts.insert(RIP)) { |
| 2825 | PathCount = BBStates[RIP->getParent()].GetAllPathCount(); |
| 2826 | NewDelta += PathCount; |
| 2827 | NewCount += PathCount; |
| 2828 | } |
| 2829 | } |
| 2830 | NewRetains.push_back(NewReleaseRetain); |
| 2831 | } |
| 2832 | } |
| 2833 | } |
| 2834 | NewReleases.clear(); |
| 2835 | if (NewRetains.empty()) break; |
| 2836 | } |
| 2837 | |
| 2838 | // If the pointer is known incremented or nested, we can safely delete the |
| 2839 | // pair regardless of what's between them. |
| 2840 | if (KnownSafeTD || KnownSafeBU) { |
| 2841 | RetainsToMove.ReverseInsertPts.clear(); |
| 2842 | ReleasesToMove.ReverseInsertPts.clear(); |
| 2843 | NewCount = 0; |
| 2844 | } else { |
| 2845 | // Determine whether the new insertion points we computed preserve the |
| 2846 | // balance of retain and release calls through the program. |
| 2847 | // TODO: If the fully aggressive solution isn't valid, try to find a |
| 2848 | // less aggressive solution which is. |
| 2849 | if (NewDelta != 0) |
| 2850 | return false; |
| 2851 | } |
| 2852 | |
| 2853 | // Determine whether the original call points are balanced in the retain and |
| 2854 | // release calls through the program. If not, conservatively don't touch |
| 2855 | // them. |
| 2856 | // TODO: It's theoretically possible to do code motion in this case, as |
| 2857 | // long as the existing imbalances are maintained. |
| 2858 | if (OldDelta != 0) |
| 2859 | return false; |
| 2860 | |
| 2861 | Changed = true; |
| 2862 | assert(OldCount != 0 && "Unreachable code?"); |
| 2863 | NumRRs += OldCount - NewCount; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2864 | // Set to true if we completely removed any RR pairs. |
Michael Gottesman | 8b5515f | 2013-01-22 21:53:43 +0000 | [diff] [blame] | 2865 | AnyPairsCompletelyEliminated = NewCount == 0; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2866 | |
| 2867 | // We can move calls! |
| 2868 | return true; |
| 2869 | } |
| 2870 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2871 | /// Identify pairings between the retains and releases, and delete and/or move |
| 2872 | /// them. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2873 | bool |
| 2874 | ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState> |
| 2875 | &BBStates, |
| 2876 | MapVector<Value *, RRInfo> &Retains, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2877 | DenseMap<Value *, RRInfo> &Releases, |
| 2878 | Module *M) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2879 | bool AnyPairsCompletelyEliminated = false; |
| 2880 | RRInfo RetainsToMove; |
| 2881 | RRInfo ReleasesToMove; |
| 2882 | SmallVector<Instruction *, 4> NewRetains; |
| 2883 | SmallVector<Instruction *, 4> NewReleases; |
| 2884 | SmallVector<Instruction *, 8> DeadInsts; |
| 2885 | |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 2886 | // Visit each retain. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2887 | for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(), |
Dan Gohman | 2053a5d | 2011-09-29 22:25:23 +0000 | [diff] [blame] | 2888 | E = Retains.end(); I != E; ++I) { |
| 2889 | Value *V = I->first; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2890 | if (!V) continue; // blotted |
| 2891 | |
| 2892 | Instruction *Retain = cast<Instruction>(V); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2893 | |
| 2894 | DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain |
| 2895 | << "\n"); |
| 2896 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2897 | Value *Arg = GetObjCArg(Retain); |
| 2898 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 2899 | // 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] | 2900 | // not being managed by ObjC reference counting, so we can delete pairs |
| 2901 | // regardless of what possible decrements or uses lie between them. |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 2902 | bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2903 | |
Dan Gohman | 56e1cef | 2011-08-22 17:29:11 +0000 | [diff] [blame] | 2904 | // A constant pointer can't be pointing to an object on the heap. It may |
| 2905 | // be reference-counted, but it won't be deleted. |
| 2906 | if (const LoadInst *LI = dyn_cast<LoadInst>(Arg)) |
| 2907 | if (const GlobalVariable *GV = |
| 2908 | dyn_cast<GlobalVariable>( |
| 2909 | StripPointerCastsAndObjCCalls(LI->getPointerOperand()))) |
| 2910 | if (GV->isConstant()) |
| 2911 | KnownSafe = true; |
| 2912 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2913 | // Connect the dots between the top-down-collected RetainsToMove and |
| 2914 | // bottom-up-collected ReleasesToMove to form sets of related calls. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2915 | NewRetains.push_back(Retain); |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2916 | bool PerformMoveCalls = |
| 2917 | ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains, |
| 2918 | NewReleases, DeadInsts, RetainsToMove, |
| 2919 | ReleasesToMove, Arg, KnownSafe, |
| 2920 | AnyPairsCompletelyEliminated); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2921 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2922 | if (PerformMoveCalls) { |
| 2923 | // Ok, everything checks out and we're all set. Let's move/delete some |
| 2924 | // code! |
| 2925 | MoveCalls(Arg, RetainsToMove, ReleasesToMove, |
| 2926 | Retains, Releases, DeadInsts, M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2927 | } |
| 2928 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2929 | // Clean up state for next retain. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2930 | NewReleases.clear(); |
| 2931 | NewRetains.clear(); |
| 2932 | RetainsToMove.clear(); |
| 2933 | ReleasesToMove.clear(); |
| 2934 | } |
| 2935 | |
| 2936 | // Now that we're done moving everything, we can delete the newly dead |
| 2937 | // instructions, as we no longer need them as insert points. |
| 2938 | while (!DeadInsts.empty()) |
| 2939 | EraseInstruction(DeadInsts.pop_back_val()); |
| 2940 | |
| 2941 | return AnyPairsCompletelyEliminated; |
| 2942 | } |
| 2943 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2944 | /// Weak pointer optimizations. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2945 | void ObjCARCOpt::OptimizeWeakCalls(Function &F) { |
| 2946 | // First, do memdep-style RLE and S2L optimizations. We can't use memdep |
| 2947 | // itself because it uses AliasAnalysis and we need to do provenance |
| 2948 | // queries instead. |
| 2949 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 2950 | Instruction *Inst = &*I++; |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 2951 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 2952 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst << |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 2953 | "\n"); |
| 2954 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2955 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 2956 | if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained) |
| 2957 | continue; |
| 2958 | |
| 2959 | // Delete objc_loadWeak calls with no users. |
| 2960 | if (Class == IC_LoadWeak && Inst->use_empty()) { |
| 2961 | Inst->eraseFromParent(); |
| 2962 | continue; |
| 2963 | } |
| 2964 | |
| 2965 | // TODO: For now, just look for an earlier available version of this value |
| 2966 | // within the same block. Theoretically, we could do memdep-style non-local |
| 2967 | // analysis too, but that would want caching. A better approach would be to |
| 2968 | // use the technique that EarlyCSE uses. |
| 2969 | inst_iterator Current = llvm::prior(I); |
| 2970 | BasicBlock *CurrentBB = Current.getBasicBlockIterator(); |
| 2971 | for (BasicBlock::iterator B = CurrentBB->begin(), |
| 2972 | J = Current.getInstructionIterator(); |
| 2973 | J != B; --J) { |
| 2974 | Instruction *EarlierInst = &*llvm::prior(J); |
| 2975 | InstructionClass EarlierClass = GetInstructionClass(EarlierInst); |
| 2976 | switch (EarlierClass) { |
| 2977 | case IC_LoadWeak: |
| 2978 | case IC_LoadWeakRetained: { |
| 2979 | // If this is loading from the same pointer, replace this load's value |
| 2980 | // with that one. |
| 2981 | CallInst *Call = cast<CallInst>(Inst); |
| 2982 | CallInst *EarlierCall = cast<CallInst>(EarlierInst); |
| 2983 | Value *Arg = Call->getArgOperand(0); |
| 2984 | Value *EarlierArg = EarlierCall->getArgOperand(0); |
| 2985 | switch (PA.getAA()->alias(Arg, EarlierArg)) { |
| 2986 | case AliasAnalysis::MustAlias: |
| 2987 | Changed = true; |
| 2988 | // If the load has a builtin retain, insert a plain retain for it. |
| 2989 | if (Class == IC_LoadWeakRetained) { |
| 2990 | CallInst *CI = |
| 2991 | CallInst::Create(getRetainCallee(F.getParent()), EarlierCall, |
| 2992 | "", Call); |
| 2993 | CI->setTailCall(); |
| 2994 | } |
| 2995 | // Zap the fully redundant load. |
| 2996 | Call->replaceAllUsesWith(EarlierCall); |
| 2997 | Call->eraseFromParent(); |
| 2998 | goto clobbered; |
| 2999 | case AliasAnalysis::MayAlias: |
| 3000 | case AliasAnalysis::PartialAlias: |
| 3001 | goto clobbered; |
| 3002 | case AliasAnalysis::NoAlias: |
| 3003 | break; |
| 3004 | } |
| 3005 | break; |
| 3006 | } |
| 3007 | case IC_StoreWeak: |
| 3008 | case IC_InitWeak: { |
| 3009 | // If this is storing to the same pointer and has the same size etc. |
| 3010 | // replace this load's value with the stored value. |
| 3011 | CallInst *Call = cast<CallInst>(Inst); |
| 3012 | CallInst *EarlierCall = cast<CallInst>(EarlierInst); |
| 3013 | Value *Arg = Call->getArgOperand(0); |
| 3014 | Value *EarlierArg = EarlierCall->getArgOperand(0); |
| 3015 | switch (PA.getAA()->alias(Arg, EarlierArg)) { |
| 3016 | case AliasAnalysis::MustAlias: |
| 3017 | Changed = true; |
| 3018 | // If the load has a builtin retain, insert a plain retain for it. |
| 3019 | if (Class == IC_LoadWeakRetained) { |
| 3020 | CallInst *CI = |
| 3021 | CallInst::Create(getRetainCallee(F.getParent()), EarlierCall, |
| 3022 | "", Call); |
| 3023 | CI->setTailCall(); |
| 3024 | } |
| 3025 | // Zap the fully redundant load. |
| 3026 | Call->replaceAllUsesWith(EarlierCall->getArgOperand(1)); |
| 3027 | Call->eraseFromParent(); |
| 3028 | goto clobbered; |
| 3029 | case AliasAnalysis::MayAlias: |
| 3030 | case AliasAnalysis::PartialAlias: |
| 3031 | goto clobbered; |
| 3032 | case AliasAnalysis::NoAlias: |
| 3033 | break; |
| 3034 | } |
| 3035 | break; |
| 3036 | } |
| 3037 | case IC_MoveWeak: |
| 3038 | case IC_CopyWeak: |
| 3039 | // TOOD: Grab the copied value. |
| 3040 | goto clobbered; |
| 3041 | case IC_AutoreleasepoolPush: |
| 3042 | case IC_None: |
| 3043 | case IC_User: |
| 3044 | // Weak pointers are only modified through the weak entry points |
| 3045 | // (and arbitrary calls, which could call the weak entry points). |
| 3046 | break; |
| 3047 | default: |
| 3048 | // Anything else could modify the weak pointer. |
| 3049 | goto clobbered; |
| 3050 | } |
| 3051 | } |
| 3052 | clobbered:; |
| 3053 | } |
| 3054 | |
| 3055 | // Then, for each destroyWeak with an alloca operand, check to see if |
| 3056 | // the alloca and all its users can be zapped. |
| 3057 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 3058 | Instruction *Inst = &*I++; |
| 3059 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 3060 | if (Class != IC_DestroyWeak) |
| 3061 | continue; |
| 3062 | |
| 3063 | CallInst *Call = cast<CallInst>(Inst); |
| 3064 | Value *Arg = Call->getArgOperand(0); |
| 3065 | if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) { |
| 3066 | for (Value::use_iterator UI = Alloca->use_begin(), |
| 3067 | UE = Alloca->use_end(); UI != UE; ++UI) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 3068 | const Instruction *UserInst = cast<Instruction>(*UI); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3069 | switch (GetBasicInstructionClass(UserInst)) { |
| 3070 | case IC_InitWeak: |
| 3071 | case IC_StoreWeak: |
| 3072 | case IC_DestroyWeak: |
| 3073 | continue; |
| 3074 | default: |
| 3075 | goto done; |
| 3076 | } |
| 3077 | } |
| 3078 | Changed = true; |
| 3079 | for (Value::use_iterator UI = Alloca->use_begin(), |
| 3080 | UE = Alloca->use_end(); UI != UE; ) { |
| 3081 | CallInst *UserInst = cast<CallInst>(*UI++); |
Dan Gohman | 14862c3 | 2012-05-18 22:17:29 +0000 | [diff] [blame] | 3082 | switch (GetBasicInstructionClass(UserInst)) { |
| 3083 | case IC_InitWeak: |
| 3084 | case IC_StoreWeak: |
| 3085 | // These functions return their second argument. |
| 3086 | UserInst->replaceAllUsesWith(UserInst->getArgOperand(1)); |
| 3087 | break; |
| 3088 | case IC_DestroyWeak: |
| 3089 | // No return value. |
| 3090 | break; |
| 3091 | default: |
Dan Gohman | 9c97eea0 | 2012-05-21 17:41:28 +0000 | [diff] [blame] | 3092 | llvm_unreachable("alloca really is used!"); |
Dan Gohman | 14862c3 | 2012-05-18 22:17:29 +0000 | [diff] [blame] | 3093 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3094 | UserInst->eraseFromParent(); |
| 3095 | } |
| 3096 | Alloca->eraseFromParent(); |
| 3097 | done:; |
| 3098 | } |
| 3099 | } |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3100 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 3101 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3102 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3103 | } |
| 3104 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3105 | /// Identify program paths which execute sequences of retains and releases which |
| 3106 | /// can be eliminated. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3107 | bool ObjCARCOpt::OptimizeSequences(Function &F) { |
| 3108 | /// Releases, Retains - These are used to store the results of the main flow |
| 3109 | /// analysis. These use Value* as the key instead of Instruction* so that the |
| 3110 | /// map stays valid when we get around to rewriting code and calls get |
| 3111 | /// replaced by arguments. |
| 3112 | DenseMap<Value *, RRInfo> Releases; |
| 3113 | MapVector<Value *, RRInfo> Retains; |
| 3114 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3115 | /// This is used during the traversal of the function to track the |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3116 | /// states for each identified object at each block. |
| 3117 | DenseMap<const BasicBlock *, BBState> BBStates; |
| 3118 | |
| 3119 | // Analyze the CFG of the function, and all instructions. |
| 3120 | bool NestingDetected = Visit(F, BBStates, Retains, Releases); |
| 3121 | |
| 3122 | // Transform. |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 3123 | return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) && |
| 3124 | NestingDetected; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3125 | } |
| 3126 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3127 | /// Look for this pattern: |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 3128 | /// \code |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3129 | /// %call = call i8* @something(...) |
| 3130 | /// %2 = call i8* @objc_retain(i8* %call) |
| 3131 | /// %3 = call i8* @objc_autorelease(i8* %2) |
| 3132 | /// ret i8* %3 |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 3133 | /// \endcode |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3134 | /// And delete the retain and autorelease. |
| 3135 | /// |
| 3136 | /// Otherwise if it's just this: |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 3137 | /// \code |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3138 | /// %3 = call i8* @objc_autorelease(i8* %2) |
| 3139 | /// ret i8* %3 |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 3140 | /// \endcode |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3141 | /// convert the autorelease to autoreleaseRV. |
| 3142 | void ObjCARCOpt::OptimizeReturns(Function &F) { |
| 3143 | if (!F.getReturnType()->isPointerTy()) |
| 3144 | return; |
| 3145 | |
| 3146 | SmallPtrSet<Instruction *, 4> DependingInstructions; |
| 3147 | SmallPtrSet<const BasicBlock *, 4> Visited; |
| 3148 | for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { |
| 3149 | BasicBlock *BB = FI; |
| 3150 | ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back()); |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 3151 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 3152 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n"); |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 3153 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3154 | if (!Ret) continue; |
| 3155 | |
| 3156 | const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0)); |
| 3157 | FindDependencies(NeedsPositiveRetainCount, Arg, |
| 3158 | BB, Ret, DependingInstructions, Visited, PA); |
| 3159 | if (DependingInstructions.size() != 1) |
| 3160 | goto next_block; |
| 3161 | |
| 3162 | { |
| 3163 | CallInst *Autorelease = |
| 3164 | dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); |
| 3165 | if (!Autorelease) |
| 3166 | goto next_block; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3167 | InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3168 | if (!IsAutorelease(AutoreleaseClass)) |
| 3169 | goto next_block; |
| 3170 | if (GetObjCArg(Autorelease) != Arg) |
| 3171 | goto next_block; |
| 3172 | |
| 3173 | DependingInstructions.clear(); |
| 3174 | Visited.clear(); |
| 3175 | |
| 3176 | // Check that there is nothing that can affect the reference |
| 3177 | // count between the autorelease and the retain. |
| 3178 | FindDependencies(CanChangeRetainCount, Arg, |
| 3179 | BB, Autorelease, DependingInstructions, Visited, PA); |
| 3180 | if (DependingInstructions.size() != 1) |
| 3181 | goto next_block; |
| 3182 | |
| 3183 | { |
| 3184 | CallInst *Retain = |
| 3185 | dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); |
| 3186 | |
| 3187 | // Check that we found a retain with the same argument. |
| 3188 | if (!Retain || |
| 3189 | !IsRetain(GetBasicInstructionClass(Retain)) || |
| 3190 | GetObjCArg(Retain) != Arg) |
| 3191 | goto next_block; |
| 3192 | |
| 3193 | DependingInstructions.clear(); |
| 3194 | Visited.clear(); |
| 3195 | |
| 3196 | // Convert the autorelease to an autoreleaseRV, since it's |
| 3197 | // returning the value. |
| 3198 | if (AutoreleaseClass == IC_Autorelease) { |
Michael Gottesman | a6cb018 | 2013-01-10 02:03:50 +0000 | [diff] [blame] | 3199 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease " |
| 3200 | "=> autoreleaseRV since it's returning a value.\n" |
| 3201 | " In: " << *Autorelease |
| 3202 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3203 | Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent())); |
Michael Gottesman | a6cb018 | 2013-01-10 02:03:50 +0000 | [diff] [blame] | 3204 | DEBUG(dbgs() << " Out: " << *Autorelease |
| 3205 | << "\n"); |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 3206 | Autorelease->setTailCall(); // Always tail call autoreleaseRV. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3207 | AutoreleaseClass = IC_AutoreleaseRV; |
| 3208 | } |
| 3209 | |
| 3210 | // Check that there is nothing that can affect the reference |
| 3211 | // count between the retain and the call. |
Dan Gohman | 4ac148d | 2011-09-29 22:27:34 +0000 | [diff] [blame] | 3212 | // Note that Retain need not be in BB. |
| 3213 | FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain, |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3214 | DependingInstructions, Visited, PA); |
| 3215 | if (DependingInstructions.size() != 1) |
| 3216 | goto next_block; |
| 3217 | |
| 3218 | { |
| 3219 | CallInst *Call = |
| 3220 | dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); |
| 3221 | |
| 3222 | // Check that the pointer is the return value of the call. |
| 3223 | if (!Call || Arg != Call) |
| 3224 | goto next_block; |
| 3225 | |
| 3226 | // Check that the call is a regular call. |
| 3227 | InstructionClass Class = GetBasicInstructionClass(Call); |
| 3228 | if (Class != IC_CallOrUser && Class != IC_Call) |
| 3229 | goto next_block; |
| 3230 | |
| 3231 | // If so, we can zap the retain and autorelease. |
| 3232 | Changed = true; |
| 3233 | ++NumRets; |
Michael Gottesman | d61a3b2 | 2013-01-07 00:04:56 +0000 | [diff] [blame] | 3234 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain |
| 3235 | << "\n Erasing: " |
| 3236 | << *Autorelease << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3237 | EraseInstruction(Retain); |
| 3238 | EraseInstruction(Autorelease); |
| 3239 | } |
| 3240 | } |
| 3241 | } |
| 3242 | |
| 3243 | next_block: |
| 3244 | DependingInstructions.clear(); |
| 3245 | Visited.clear(); |
| 3246 | } |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3247 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 3248 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3249 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3250 | } |
| 3251 | |
| 3252 | bool ObjCARCOpt::doInitialization(Module &M) { |
| 3253 | if (!EnableARCOpts) |
| 3254 | return false; |
| 3255 | |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 3256 | // If nothing in the Module uses ARC, don't do anything. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 3257 | Run = ModuleHasARC(M); |
| 3258 | if (!Run) |
| 3259 | return false; |
| 3260 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3261 | // Identify the imprecise release metadata kind. |
| 3262 | ImpreciseReleaseMDKind = |
| 3263 | M.getContext().getMDKindID("clang.imprecise_release"); |
Dan Gohman | a7107f9 | 2011-10-17 22:53:25 +0000 | [diff] [blame] | 3264 | CopyOnEscapeMDKind = |
| 3265 | M.getContext().getMDKindID("clang.arc.copy_on_escape"); |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 3266 | NoObjCARCExceptionsMDKind = |
| 3267 | M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3268 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3269 | // Intuitively, objc_retain and others are nocapture, however in practice |
| 3270 | // they are not, because they return their argument value. And objc_release |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 3271 | // calls finalizers which can have arbitrary side effects. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3272 | |
| 3273 | // These are initialized lazily. |
| 3274 | RetainRVCallee = 0; |
| 3275 | AutoreleaseRVCallee = 0; |
| 3276 | ReleaseCallee = 0; |
| 3277 | RetainCallee = 0; |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 3278 | RetainBlockCallee = 0; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3279 | AutoreleaseCallee = 0; |
| 3280 | |
| 3281 | return false; |
| 3282 | } |
| 3283 | |
| 3284 | bool ObjCARCOpt::runOnFunction(Function &F) { |
| 3285 | if (!EnableARCOpts) |
| 3286 | return false; |
| 3287 | |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 3288 | // If nothing in the Module uses ARC, don't do anything. |
| 3289 | if (!Run) |
| 3290 | return false; |
| 3291 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3292 | Changed = false; |
| 3293 | |
Michael Gottesman | b24bdef | 2013-01-12 02:57:16 +0000 | [diff] [blame] | 3294 | DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n"); |
| 3295 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3296 | PA.setAA(&getAnalysis<AliasAnalysis>()); |
| 3297 | |
| 3298 | // This pass performs several distinct transformations. As a compile-time aid |
| 3299 | // when compiling code that isn't ObjC, skip these if the relevant ObjC |
| 3300 | // library functions aren't declared. |
| 3301 | |
| 3302 | // Preliminary optimizations. This also computs UsedInThisFunction. |
| 3303 | OptimizeIndividualCalls(F); |
| 3304 | |
| 3305 | // Optimizations for weak pointers. |
| 3306 | if (UsedInThisFunction & ((1 << IC_LoadWeak) | |
| 3307 | (1 << IC_LoadWeakRetained) | |
| 3308 | (1 << IC_StoreWeak) | |
| 3309 | (1 << IC_InitWeak) | |
| 3310 | (1 << IC_CopyWeak) | |
| 3311 | (1 << IC_MoveWeak) | |
| 3312 | (1 << IC_DestroyWeak))) |
| 3313 | OptimizeWeakCalls(F); |
| 3314 | |
| 3315 | // Optimizations for retain+release pairs. |
| 3316 | if (UsedInThisFunction & ((1 << IC_Retain) | |
| 3317 | (1 << IC_RetainRV) | |
| 3318 | (1 << IC_RetainBlock))) |
| 3319 | if (UsedInThisFunction & (1 << IC_Release)) |
| 3320 | // Run OptimizeSequences until it either stops making changes or |
| 3321 | // no retain+release pair nesting is detected. |
| 3322 | while (OptimizeSequences(F)) {} |
| 3323 | |
| 3324 | // Optimizations if objc_autorelease is used. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3325 | if (UsedInThisFunction & ((1 << IC_Autorelease) | |
| 3326 | (1 << IC_AutoreleaseRV))) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3327 | OptimizeReturns(F); |
| 3328 | |
Michael Gottesman | b24bdef | 2013-01-12 02:57:16 +0000 | [diff] [blame] | 3329 | DEBUG(dbgs() << "\n"); |
| 3330 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3331 | return Changed; |
| 3332 | } |
| 3333 | |
| 3334 | void ObjCARCOpt::releaseMemory() { |
| 3335 | PA.clear(); |
| 3336 | } |
| 3337 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3338 | /// @} |
| 3339 | /// |
| 3340 | /// \defgroup ARCContract ARC Contraction. |
| 3341 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3342 | |
| 3343 | // TODO: ObjCARCContract could insert PHI nodes when uses aren't |
| 3344 | // dominated by single calls. |
| 3345 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3346 | #include "llvm/Analysis/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 3347 | #include "llvm/IR/InlineAsm.h" |
| 3348 | #include "llvm/IR/Operator.h" |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3349 | |
| 3350 | STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed"); |
| 3351 | |
| 3352 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3353 | /// \brief Late ARC optimizations |
| 3354 | /// |
| 3355 | /// These change the IR in a way that makes it difficult to be analyzed by |
| 3356 | /// ObjCARCOpt, so it's run late. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3357 | class ObjCARCContract : public FunctionPass { |
| 3358 | bool Changed; |
| 3359 | AliasAnalysis *AA; |
| 3360 | DominatorTree *DT; |
| 3361 | ProvenanceAnalysis PA; |
| 3362 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3363 | /// A flag indicating whether this optimization pass should run. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 3364 | bool Run; |
| 3365 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3366 | /// Declarations for ObjC runtime functions, for use in creating calls to |
| 3367 | /// them. These are initialized lazily to avoid cluttering up the Module |
| 3368 | /// with unused declarations. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3369 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3370 | /// Declaration for objc_storeStrong(). |
| 3371 | Constant *StoreStrongCallee; |
| 3372 | /// Declaration for objc_retainAutorelease(). |
| 3373 | Constant *RetainAutoreleaseCallee; |
| 3374 | /// Declaration for objc_retainAutoreleaseReturnValue(). |
| 3375 | Constant *RetainAutoreleaseRVCallee; |
| 3376 | |
| 3377 | /// The inline asm string to insert between calls and RetainRV calls to make |
| 3378 | /// the optimization work on targets which need it. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3379 | const MDString *RetainRVMarker; |
| 3380 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3381 | /// The set of inserted objc_storeStrong calls. If at the end of walking the |
| 3382 | /// function we have found no alloca instructions, these calls can be marked |
| 3383 | /// "tail". |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3384 | SmallPtrSet<CallInst *, 8> StoreStrongCalls; |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 3385 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3386 | Constant *getStoreStrongCallee(Module *M); |
| 3387 | Constant *getRetainAutoreleaseCallee(Module *M); |
| 3388 | Constant *getRetainAutoreleaseRVCallee(Module *M); |
| 3389 | |
| 3390 | bool ContractAutorelease(Function &F, Instruction *Autorelease, |
| 3391 | InstructionClass Class, |
| 3392 | SmallPtrSet<Instruction *, 4> |
| 3393 | &DependingInstructions, |
| 3394 | SmallPtrSet<const BasicBlock *, 4> |
| 3395 | &Visited); |
| 3396 | |
| 3397 | void ContractRelease(Instruction *Release, |
| 3398 | inst_iterator &Iter); |
| 3399 | |
| 3400 | virtual void getAnalysisUsage(AnalysisUsage &AU) const; |
| 3401 | virtual bool doInitialization(Module &M); |
| 3402 | virtual bool runOnFunction(Function &F); |
| 3403 | |
| 3404 | public: |
| 3405 | static char ID; |
| 3406 | ObjCARCContract() : FunctionPass(ID) { |
| 3407 | initializeObjCARCContractPass(*PassRegistry::getPassRegistry()); |
| 3408 | } |
| 3409 | }; |
| 3410 | } |
| 3411 | |
| 3412 | char ObjCARCContract::ID = 0; |
| 3413 | INITIALIZE_PASS_BEGIN(ObjCARCContract, |
| 3414 | "objc-arc-contract", "ObjC ARC contraction", false, false) |
| 3415 | INITIALIZE_AG_DEPENDENCY(AliasAnalysis) |
| 3416 | INITIALIZE_PASS_DEPENDENCY(DominatorTree) |
| 3417 | INITIALIZE_PASS_END(ObjCARCContract, |
| 3418 | "objc-arc-contract", "ObjC ARC contraction", false, false) |
| 3419 | |
| 3420 | Pass *llvm::createObjCARCContractPass() { |
| 3421 | return new ObjCARCContract(); |
| 3422 | } |
| 3423 | |
| 3424 | void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const { |
| 3425 | AU.addRequired<AliasAnalysis>(); |
| 3426 | AU.addRequired<DominatorTree>(); |
| 3427 | AU.setPreservesCFG(); |
| 3428 | } |
| 3429 | |
| 3430 | Constant *ObjCARCContract::getStoreStrongCallee(Module *M) { |
| 3431 | if (!StoreStrongCallee) { |
| 3432 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 3433 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
| 3434 | Type *I8XX = PointerType::getUnqual(I8X); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3435 | Type *Params[] = { I8XX, I8X }; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3436 | |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 3437 | AttributeSet Attr = AttributeSet() |
| 3438 | .addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 3439 | Attribute::NoUnwind) |
| 3440 | .addAttribute(M->getContext(), 1, Attribute::NoCapture); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3441 | |
| 3442 | StoreStrongCallee = |
| 3443 | M->getOrInsertFunction( |
| 3444 | "objc_storeStrong", |
| 3445 | FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false), |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 3446 | Attr); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3447 | } |
| 3448 | return StoreStrongCallee; |
| 3449 | } |
| 3450 | |
| 3451 | Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) { |
| 3452 | if (!RetainAutoreleaseCallee) { |
| 3453 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 3454 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3455 | Type *Params[] = { I8X }; |
| 3456 | FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false); |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 3457 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 3458 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 3459 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3460 | RetainAutoreleaseCallee = |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 3461 | M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3462 | } |
| 3463 | return RetainAutoreleaseCallee; |
| 3464 | } |
| 3465 | |
| 3466 | Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) { |
| 3467 | if (!RetainAutoreleaseRVCallee) { |
| 3468 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 3469 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3470 | Type *Params[] = { I8X }; |
| 3471 | FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false); |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 3472 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 3473 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 3474 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3475 | RetainAutoreleaseRVCallee = |
| 3476 | M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy, |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 3477 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3478 | } |
| 3479 | return RetainAutoreleaseRVCallee; |
| 3480 | } |
| 3481 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3482 | /// Merge an autorelease with a retain into a fused call. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3483 | bool |
| 3484 | ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease, |
| 3485 | InstructionClass Class, |
| 3486 | SmallPtrSet<Instruction *, 4> |
| 3487 | &DependingInstructions, |
| 3488 | SmallPtrSet<const BasicBlock *, 4> |
| 3489 | &Visited) { |
| 3490 | const Value *Arg = GetObjCArg(Autorelease); |
| 3491 | |
| 3492 | // Check that there are no instructions between the retain and the autorelease |
| 3493 | // (such as an autorelease_pop) which may change the count. |
| 3494 | CallInst *Retain = 0; |
| 3495 | if (Class == IC_AutoreleaseRV) |
| 3496 | FindDependencies(RetainAutoreleaseRVDep, Arg, |
| 3497 | Autorelease->getParent(), Autorelease, |
| 3498 | DependingInstructions, Visited, PA); |
| 3499 | else |
| 3500 | FindDependencies(RetainAutoreleaseDep, Arg, |
| 3501 | Autorelease->getParent(), Autorelease, |
| 3502 | DependingInstructions, Visited, PA); |
| 3503 | |
| 3504 | Visited.clear(); |
| 3505 | if (DependingInstructions.size() != 1) { |
| 3506 | DependingInstructions.clear(); |
| 3507 | return false; |
| 3508 | } |
| 3509 | |
| 3510 | Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); |
| 3511 | DependingInstructions.clear(); |
| 3512 | |
| 3513 | if (!Retain || |
| 3514 | GetBasicInstructionClass(Retain) != IC_Retain || |
| 3515 | GetObjCArg(Retain) != Arg) |
| 3516 | return false; |
| 3517 | |
| 3518 | Changed = true; |
| 3519 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3520 | |
Michael Gottesman | add0847 | 2013-01-07 00:31:26 +0000 | [diff] [blame] | 3521 | DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing " |
| 3522 | "retain/autorelease. Erasing: " << *Autorelease << "\n" |
| 3523 | " Old Retain: " |
| 3524 | << *Retain << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3525 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3526 | if (Class == IC_AutoreleaseRV) |
| 3527 | Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent())); |
| 3528 | else |
| 3529 | Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent())); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3530 | |
Michael Gottesman | add0847 | 2013-01-07 00:31:26 +0000 | [diff] [blame] | 3531 | DEBUG(dbgs() << " New Retain: " |
| 3532 | << *Retain << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3533 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3534 | EraseInstruction(Autorelease); |
| 3535 | return true; |
| 3536 | } |
| 3537 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3538 | /// Attempt to merge an objc_release with a store, load, and objc_retain to form |
| 3539 | /// an objc_storeStrong. This can be a little tricky because the instructions |
| 3540 | /// don't always appear in order, and there may be unrelated intervening |
| 3541 | /// instructions. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3542 | void ObjCARCContract::ContractRelease(Instruction *Release, |
| 3543 | inst_iterator &Iter) { |
| 3544 | LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release)); |
Eli Friedman | 7c5dc12 | 2011-09-12 20:23:13 +0000 | [diff] [blame] | 3545 | if (!Load || !Load->isSimple()) return; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3546 | |
| 3547 | // For now, require everything to be in one basic block. |
| 3548 | BasicBlock *BB = Release->getParent(); |
| 3549 | if (Load->getParent() != BB) return; |
| 3550 | |
Dan Gohman | 61708d3 | 2012-05-08 23:34:08 +0000 | [diff] [blame] | 3551 | // Walk down to find the store and the release, which may be in either order. |
Dan Gohman | f8b19d0 | 2012-05-09 23:08:33 +0000 | [diff] [blame] | 3552 | BasicBlock::iterator I = Load, End = BB->end(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3553 | ++I; |
| 3554 | AliasAnalysis::Location Loc = AA->getLocation(Load); |
Dan Gohman | 61708d3 | 2012-05-08 23:34:08 +0000 | [diff] [blame] | 3555 | StoreInst *Store = 0; |
| 3556 | bool SawRelease = false; |
| 3557 | for (; !Store || !SawRelease; ++I) { |
Dan Gohman | f8b19d0 | 2012-05-09 23:08:33 +0000 | [diff] [blame] | 3558 | if (I == End) |
| 3559 | return; |
| 3560 | |
Dan Gohman | 61708d3 | 2012-05-08 23:34:08 +0000 | [diff] [blame] | 3561 | Instruction *Inst = I; |
| 3562 | if (Inst == Release) { |
| 3563 | SawRelease = true; |
| 3564 | continue; |
| 3565 | } |
| 3566 | |
| 3567 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 3568 | |
| 3569 | // Unrelated retains are harmless. |
| 3570 | if (IsRetain(Class)) |
| 3571 | continue; |
| 3572 | |
| 3573 | if (Store) { |
| 3574 | // The store is the point where we're going to put the objc_storeStrong, |
| 3575 | // so make sure there are no uses after it. |
| 3576 | if (CanUse(Inst, Load, PA, Class)) |
| 3577 | return; |
| 3578 | } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) { |
| 3579 | // We are moving the load down to the store, so check for anything |
| 3580 | // else which writes to the memory between the load and the store. |
| 3581 | Store = dyn_cast<StoreInst>(Inst); |
| 3582 | if (!Store || !Store->isSimple()) return; |
| 3583 | if (Store->getPointerOperand() != Loc.Ptr) return; |
| 3584 | } |
| 3585 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3586 | |
| 3587 | Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand()); |
| 3588 | |
| 3589 | // Walk up to find the retain. |
| 3590 | I = Store; |
| 3591 | BasicBlock::iterator Begin = BB->begin(); |
| 3592 | while (I != Begin && GetBasicInstructionClass(I) != IC_Retain) |
| 3593 | --I; |
| 3594 | Instruction *Retain = I; |
| 3595 | if (GetBasicInstructionClass(Retain) != IC_Retain) return; |
| 3596 | if (GetObjCArg(Retain) != New) return; |
| 3597 | |
| 3598 | Changed = true; |
| 3599 | ++NumStoreStrongs; |
| 3600 | |
| 3601 | LLVMContext &C = Release->getContext(); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3602 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
| 3603 | Type *I8XX = PointerType::getUnqual(I8X); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3604 | |
| 3605 | Value *Args[] = { Load->getPointerOperand(), New }; |
| 3606 | if (Args[0]->getType() != I8XX) |
| 3607 | Args[0] = new BitCastInst(Args[0], I8XX, "", Store); |
| 3608 | if (Args[1]->getType() != I8X) |
| 3609 | Args[1] = new BitCastInst(Args[1], I8X, "", Store); |
| 3610 | CallInst *StoreStrong = |
| 3611 | CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()), |
Jay Foad | 5bd375a | 2011-07-15 08:37:34 +0000 | [diff] [blame] | 3612 | Args, "", Store); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3613 | StoreStrong->setDoesNotThrow(); |
| 3614 | StoreStrong->setDebugLoc(Store->getDebugLoc()); |
| 3615 | |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 3616 | // We can't set the tail flag yet, because we haven't yet determined |
| 3617 | // whether there are any escaping allocas. Remember this call, so that |
| 3618 | // we can set the tail flag once we know it's safe. |
| 3619 | StoreStrongCalls.insert(StoreStrong); |
| 3620 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3621 | if (&*Iter == Store) ++Iter; |
| 3622 | Store->eraseFromParent(); |
| 3623 | Release->eraseFromParent(); |
| 3624 | EraseInstruction(Retain); |
| 3625 | if (Load->use_empty()) |
| 3626 | Load->eraseFromParent(); |
| 3627 | } |
| 3628 | |
| 3629 | bool ObjCARCContract::doInitialization(Module &M) { |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 3630 | // If nothing in the Module uses ARC, don't do anything. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 3631 | Run = ModuleHasARC(M); |
| 3632 | if (!Run) |
| 3633 | return false; |
| 3634 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3635 | // These are initialized lazily. |
| 3636 | StoreStrongCallee = 0; |
| 3637 | RetainAutoreleaseCallee = 0; |
| 3638 | RetainAutoreleaseRVCallee = 0; |
| 3639 | |
| 3640 | // Initialize RetainRVMarker. |
| 3641 | RetainRVMarker = 0; |
| 3642 | if (NamedMDNode *NMD = |
| 3643 | M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker")) |
| 3644 | if (NMD->getNumOperands() == 1) { |
| 3645 | const MDNode *N = NMD->getOperand(0); |
| 3646 | if (N->getNumOperands() == 1) |
| 3647 | if (const MDString *S = dyn_cast<MDString>(N->getOperand(0))) |
| 3648 | RetainRVMarker = S; |
| 3649 | } |
| 3650 | |
| 3651 | return false; |
| 3652 | } |
| 3653 | |
| 3654 | bool ObjCARCContract::runOnFunction(Function &F) { |
| 3655 | if (!EnableARCOpts) |
| 3656 | return false; |
| 3657 | |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 3658 | // If nothing in the Module uses ARC, don't do anything. |
| 3659 | if (!Run) |
| 3660 | return false; |
| 3661 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3662 | Changed = false; |
| 3663 | AA = &getAnalysis<AliasAnalysis>(); |
| 3664 | DT = &getAnalysis<DominatorTree>(); |
| 3665 | |
| 3666 | PA.setAA(&getAnalysis<AliasAnalysis>()); |
| 3667 | |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 3668 | // Track whether it's ok to mark objc_storeStrong calls with the "tail" |
| 3669 | // keyword. Be conservative if the function has variadic arguments. |
| 3670 | // It seems that functions which "return twice" are also unsafe for the |
| 3671 | // "tail" argument, because they are setjmp, which could need to |
| 3672 | // return to an earlier stack state. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3673 | bool TailOkForStoreStrongs = !F.isVarArg() && |
| 3674 | !F.callsFunctionThatReturnsTwice(); |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 3675 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3676 | // For ObjC library calls which return their argument, replace uses of the |
| 3677 | // argument with uses of the call return value, if it dominates the use. This |
| 3678 | // reduces register pressure. |
| 3679 | SmallPtrSet<Instruction *, 4> DependingInstructions; |
| 3680 | SmallPtrSet<const BasicBlock *, 4> Visited; |
| 3681 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 3682 | Instruction *Inst = &*I++; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3683 | |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 3684 | DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3685 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3686 | // Only these library routines return their argument. In particular, |
| 3687 | // objc_retainBlock does not necessarily return its argument. |
| 3688 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 3689 | switch (Class) { |
| 3690 | case IC_Retain: |
| 3691 | case IC_FusedRetainAutorelease: |
| 3692 | case IC_FusedRetainAutoreleaseRV: |
| 3693 | break; |
| 3694 | case IC_Autorelease: |
| 3695 | case IC_AutoreleaseRV: |
| 3696 | if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited)) |
| 3697 | continue; |
| 3698 | break; |
| 3699 | case IC_RetainRV: { |
| 3700 | // If we're compiling for a target which needs a special inline-asm |
| 3701 | // marker to do the retainAutoreleasedReturnValue optimization, |
| 3702 | // insert it now. |
| 3703 | if (!RetainRVMarker) |
| 3704 | break; |
| 3705 | BasicBlock::iterator BBI = Inst; |
Dan Gohman | 5f725cd | 2012-06-25 19:47:37 +0000 | [diff] [blame] | 3706 | BasicBlock *InstParent = Inst->getParent(); |
| 3707 | |
| 3708 | // Step up to see if the call immediately precedes the RetainRV call. |
| 3709 | // If it's an invoke, we have to cross a block boundary. And we have |
| 3710 | // to carefully dodge no-op instructions. |
| 3711 | do { |
| 3712 | if (&*BBI == InstParent->begin()) { |
| 3713 | BasicBlock *Pred = InstParent->getSinglePredecessor(); |
| 3714 | if (!Pred) |
| 3715 | goto decline_rv_optimization; |
| 3716 | BBI = Pred->getTerminator(); |
| 3717 | break; |
| 3718 | } |
| 3719 | --BBI; |
| 3720 | } while (isNoopInstruction(BBI)); |
| 3721 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3722 | if (&*BBI == GetObjCArg(Inst)) { |
Michael Gottesman | 00d1f96 | 2013-01-03 07:32:41 +0000 | [diff] [blame] | 3723 | DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for " |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 3724 | "retainAutoreleasedReturnValue optimization.\n"); |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 3725 | Changed = true; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3726 | InlineAsm *IA = |
| 3727 | InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()), |
| 3728 | /*isVarArg=*/false), |
| 3729 | RetainRVMarker->getString(), |
| 3730 | /*Constraints=*/"", /*hasSideEffects=*/true); |
| 3731 | CallInst::Create(IA, "", Inst); |
| 3732 | } |
Dan Gohman | 5f725cd | 2012-06-25 19:47:37 +0000 | [diff] [blame] | 3733 | decline_rv_optimization: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3734 | break; |
| 3735 | } |
| 3736 | case IC_InitWeak: { |
| 3737 | // objc_initWeak(p, null) => *p = null |
| 3738 | CallInst *CI = cast<CallInst>(Inst); |
| 3739 | if (isNullOrUndef(CI->getArgOperand(1))) { |
| 3740 | Value *Null = |
| 3741 | ConstantPointerNull::get(cast<PointerType>(CI->getType())); |
| 3742 | Changed = true; |
| 3743 | new StoreInst(Null, CI->getArgOperand(0), CI); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3744 | |
Michael Gottesman | 416dc00 | 2013-01-03 07:32:53 +0000 | [diff] [blame] | 3745 | DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n" |
| 3746 | << " New = " << *Null << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3747 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3748 | CI->replaceAllUsesWith(Null); |
| 3749 | CI->eraseFromParent(); |
| 3750 | } |
| 3751 | continue; |
| 3752 | } |
| 3753 | case IC_Release: |
| 3754 | ContractRelease(Inst, I); |
| 3755 | continue; |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 3756 | case IC_User: |
| 3757 | // Be conservative if the function has any alloca instructions. |
| 3758 | // Technically we only care about escaping alloca instructions, |
| 3759 | // but this is sufficient to handle some interesting cases. |
| 3760 | if (isa<AllocaInst>(Inst)) |
| 3761 | TailOkForStoreStrongs = false; |
| 3762 | continue; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3763 | default: |
| 3764 | continue; |
| 3765 | } |
| 3766 | |
Michael Gottesman | 50ae5b2 | 2013-01-03 08:09:27 +0000 | [diff] [blame] | 3767 | DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n"); |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 3768 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3769 | // Don't use GetObjCArg because we don't want to look through bitcasts |
| 3770 | // and such; to do the replacement, the argument must have type i8*. |
| 3771 | const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0); |
| 3772 | for (;;) { |
| 3773 | // If we're compiling bugpointed code, don't get in trouble. |
| 3774 | if (!isa<Instruction>(Arg) && !isa<Argument>(Arg)) |
| 3775 | break; |
| 3776 | // Look through the uses of the pointer. |
| 3777 | for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end(); |
| 3778 | UI != UE; ) { |
| 3779 | Use &U = UI.getUse(); |
| 3780 | unsigned OperandNo = UI.getOperandNo(); |
| 3781 | ++UI; // Increment UI now, because we may unlink its element. |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 3782 | |
| 3783 | // If the call's return value dominates a use of the call's argument |
| 3784 | // value, rewrite the use to use the return value. We check for |
| 3785 | // reachability here because an unreachable call is considered to |
| 3786 | // trivially dominate itself, which would lead us to rewriting its |
| 3787 | // argument in terms of its return value, which would lead to |
| 3788 | // infinite loops in GetObjCArg. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3789 | if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) { |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 3790 | Changed = true; |
| 3791 | Instruction *Replacement = Inst; |
| 3792 | Type *UseTy = U.get()->getType(); |
Dan Gohman | de8d2c4 | 2012-04-13 01:08:28 +0000 | [diff] [blame] | 3793 | if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) { |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 3794 | // For PHI nodes, insert the bitcast in the predecessor block. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3795 | unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo); |
| 3796 | BasicBlock *BB = PHI->getIncomingBlock(ValNo); |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 3797 | if (Replacement->getType() != UseTy) |
| 3798 | Replacement = new BitCastInst(Replacement, UseTy, "", |
| 3799 | &BB->back()); |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 3800 | // While we're here, rewrite all edges for this PHI, rather |
| 3801 | // than just one use at a time, to minimize the number of |
| 3802 | // bitcasts we emit. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 3803 | for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 3804 | if (PHI->getIncomingBlock(i) == BB) { |
| 3805 | // Keep the UI iterator valid. |
| 3806 | if (&PHI->getOperandUse( |
| 3807 | PHINode::getOperandNumForIncomingValue(i)) == |
| 3808 | &UI.getUse()) |
| 3809 | ++UI; |
| 3810 | PHI->setIncomingValue(i, Replacement); |
| 3811 | } |
| 3812 | } else { |
| 3813 | if (Replacement->getType() != UseTy) |
Dan Gohman | de8d2c4 | 2012-04-13 01:08:28 +0000 | [diff] [blame] | 3814 | Replacement = new BitCastInst(Replacement, UseTy, "", |
| 3815 | cast<Instruction>(U.getUser())); |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 3816 | U.set(Replacement); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3817 | } |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 3818 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3819 | } |
| 3820 | |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 3821 | // If Arg is a no-op casted pointer, strip one level of casts and iterate. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3822 | if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg)) |
| 3823 | Arg = BI->getOperand(0); |
| 3824 | else if (isa<GEPOperator>(Arg) && |
| 3825 | cast<GEPOperator>(Arg)->hasAllZeroIndices()) |
| 3826 | Arg = cast<GEPOperator>(Arg)->getPointerOperand(); |
| 3827 | else if (isa<GlobalAlias>(Arg) && |
| 3828 | !cast<GlobalAlias>(Arg)->mayBeOverridden()) |
| 3829 | Arg = cast<GlobalAlias>(Arg)->getAliasee(); |
| 3830 | else |
| 3831 | break; |
| 3832 | } |
| 3833 | } |
| 3834 | |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 3835 | // If this function has no escaping allocas or suspicious vararg usage, |
| 3836 | // objc_storeStrong calls can be marked with the "tail" keyword. |
| 3837 | if (TailOkForStoreStrongs) |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3838 | for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(), |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 3839 | E = StoreStrongCalls.end(); I != E; ++I) |
| 3840 | (*I)->setTailCall(); |
| 3841 | StoreStrongCalls.clear(); |
| 3842 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3843 | return Changed; |
| 3844 | } |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3845 | |
| 3846 | /// @} |
| 3847 | /// |