PageRenderTime 134ms CodeModel.GetById 16ms app.highlight 107ms RepoModel.GetById 1ms app.codeStats 1ms

/3rd_party/llvm/lib/Transforms/Scalar/ObjCARC.cpp

https://code.google.com/p/softart/
C++ | 4200 lines | 2932 code | 476 blank | 792 comment | 735 complexity | aa4c947e6cc65c3b84e595323f9f8c9a MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, JSON, MPL-2.0-no-copyleft-exception, GPL-2.0, GPL-3.0, LGPL-3.0, BSD-2-Clause

Large files files are truncated, but you can click here to view the full file

   1//===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
   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//===----------------------------------------------------------------------===//
   9//
  10// This file defines ObjC ARC optimizations. ARC stands for
  11// Automatic Reference Counting and is a system for managing reference counts
  12// for objects 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//
  29//===----------------------------------------------------------------------===//
  30
  31#define DEBUG_TYPE "objc-arc"
  32#include "llvm/Support/CommandLine.h"
  33#include "llvm/ADT/DenseMap.h"
  34using namespace llvm;
  35
  36// A handy option to enable/disable all optimizations in this file.
  37static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
  38
  39//===----------------------------------------------------------------------===//
  40// Misc. Utilities
  41//===----------------------------------------------------------------------===//
  42
  43namespace {
  44  /// MapVector - An associative container with fast insertion-order
  45  /// (deterministic) iteration over its elements. Plus the special
  46  /// blot operation.
  47  template<class KeyT, class ValueT>
  48  class MapVector {
  49    /// Map - Map keys to indices in Vector.
  50    typedef DenseMap<KeyT, size_t> MapTy;
  51    MapTy Map;
  52
  53    /// Vector - Keys and values.
  54    typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
  55    VectorTy Vector;
  56
  57  public:
  58    typedef typename VectorTy::iterator iterator;
  59    typedef typename VectorTy::const_iterator const_iterator;
  60    iterator begin() { return Vector.begin(); }
  61    iterator end() { return Vector.end(); }
  62    const_iterator begin() const { return Vector.begin(); }
  63    const_iterator end() const { return Vector.end(); }
  64
  65#ifdef XDEBUG
  66    ~MapVector() {
  67      assert(Vector.size() >= Map.size()); // May differ due to blotting.
  68      for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
  69           I != E; ++I) {
  70        assert(I->second < Vector.size());
  71        assert(Vector[I->second].first == I->first);
  72      }
  73      for (typename VectorTy::const_iterator I = Vector.begin(),
  74           E = Vector.end(); I != E; ++I)
  75        assert(!I->first ||
  76               (Map.count(I->first) &&
  77                Map[I->first] == size_t(I - Vector.begin())));
  78    }
  79#endif
  80
  81    ValueT &operator[](const KeyT &Arg) {
  82      std::pair<typename MapTy::iterator, bool> Pair =
  83        Map.insert(std::make_pair(Arg, size_t(0)));
  84      if (Pair.second) {
  85        size_t Num = Vector.size();
  86        Pair.first->second = Num;
  87        Vector.push_back(std::make_pair(Arg, ValueT()));
  88        return Vector[Num].second;
  89      }
  90      return Vector[Pair.first->second].second;
  91    }
  92
  93    std::pair<iterator, bool>
  94    insert(const std::pair<KeyT, ValueT> &InsertPair) {
  95      std::pair<typename MapTy::iterator, bool> Pair =
  96        Map.insert(std::make_pair(InsertPair.first, size_t(0)));
  97      if (Pair.second) {
  98        size_t Num = Vector.size();
  99        Pair.first->second = Num;
 100        Vector.push_back(InsertPair);
 101        return std::make_pair(Vector.begin() + Num, true);
 102      }
 103      return std::make_pair(Vector.begin() + Pair.first->second, false);
 104    }
 105
 106    const_iterator find(const KeyT &Key) const {
 107      typename MapTy::const_iterator It = Map.find(Key);
 108      if (It == Map.end()) return Vector.end();
 109      return Vector.begin() + It->second;
 110    }
 111
 112    /// blot - This is similar to erase, but instead of removing the element
 113    /// from the vector, it just zeros out the key in the vector. This leaves
 114    /// iterators intact, but clients must be prepared for zeroed-out keys when
 115    /// iterating.
 116    void blot(const KeyT &Key) {
 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
 130//===----------------------------------------------------------------------===//
 131// ARC Utilities.
 132//===----------------------------------------------------------------------===//
 133
 134#include "llvm/Intrinsics.h"
 135#include "llvm/Module.h"
 136#include "llvm/Analysis/ValueTracking.h"
 137#include "llvm/Transforms/Utils/Local.h"
 138#include "llvm/Support/CallSite.h"
 139#include "llvm/ADT/StringSwitch.h"
 140
 141namespace {
 142  /// InstructionClass - A simple classification for instructions.
 143  enum InstructionClass {
 144    IC_Retain,              ///< objc_retain
 145    IC_RetainRV,            ///< objc_retainAutoreleasedReturnValue
 146    IC_RetainBlock,         ///< objc_retainBlock
 147    IC_Release,             ///< objc_release
 148    IC_Autorelease,         ///< objc_autorelease
 149    IC_AutoreleaseRV,       ///< objc_autoreleaseReturnValue
 150    IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
 151    IC_AutoreleasepoolPop,  ///< objc_autoreleasePoolPop
 152    IC_NoopCast,            ///< objc_retainedObject, etc.
 153    IC_FusedRetainAutorelease, ///< objc_retainAutorelease
 154    IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
 155    IC_LoadWeakRetained,    ///< objc_loadWeakRetained (primitive)
 156    IC_StoreWeak,           ///< objc_storeWeak (primitive)
 157    IC_InitWeak,            ///< objc_initWeak (derived)
 158    IC_LoadWeak,            ///< objc_loadWeak (derived)
 159    IC_MoveWeak,            ///< objc_moveWeak (derived)
 160    IC_CopyWeak,            ///< objc_copyWeak (derived)
 161    IC_DestroyWeak,         ///< objc_destroyWeak (derived)
 162    IC_StoreStrong,         ///< objc_storeStrong (derived)
 163    IC_CallOrUser,          ///< could call objc_release and/or "use" pointers
 164    IC_Call,                ///< could call objc_release
 165    IC_User,                ///< could "use" a pointer
 166    IC_None                 ///< anything else
 167  };
 168}
 169
 170/// IsPotentialUse - Test whether the given value is possible a
 171/// reference-counted pointer.
 172static bool IsPotentialUse(const Value *Op) {
 173  // Pointers to static or stack storage are not reference-counted pointers.
 174  if (isa<Constant>(Op) || isa<AllocaInst>(Op))
 175    return false;
 176  // Special arguments are not reference-counted.
 177  if (const Argument *Arg = dyn_cast<Argument>(Op))
 178    if (Arg->hasByValAttr() ||
 179        Arg->hasNestAttr() ||
 180        Arg->hasStructRetAttr())
 181      return false;
 182  // Only consider values with pointer types.
 183  // It seemes intuitive to exclude function pointer types as well, since
 184  // functions are never reference-counted, however clang occasionally
 185  // bitcasts reference-counted pointers to function-pointer type
 186  // temporarily.
 187  PointerType *Ty = dyn_cast<PointerType>(Op->getType());
 188  if (!Ty)
 189    return false;
 190  // Conservatively assume anything else is a potential use.
 191  return true;
 192}
 193
 194/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
 195/// of construct CS is.
 196static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
 197  for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
 198       I != E; ++I)
 199    if (IsPotentialUse(*I))
 200      return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
 201
 202  return CS.onlyReadsMemory() ? IC_None : IC_Call;
 203}
 204
 205/// GetFunctionClass - Determine if F is one of the special known Functions.
 206/// If it isn't, return IC_CallOrUser.
 207static InstructionClass GetFunctionClass(const Function *F) {
 208  Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
 209
 210  // No arguments.
 211  if (AI == AE)
 212    return StringSwitch<InstructionClass>(F->getName())
 213      .Case("objc_autoreleasePoolPush",  IC_AutoreleasepoolPush)
 214      .Default(IC_CallOrUser);
 215
 216  // One argument.
 217  const Argument *A0 = AI++;
 218  if (AI == AE)
 219    // Argument is a pointer.
 220    if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
 221      Type *ETy = PTy->getElementType();
 222      // Argument is i8*.
 223      if (ETy->isIntegerTy(8))
 224        return StringSwitch<InstructionClass>(F->getName())
 225          .Case("objc_retain",                IC_Retain)
 226          .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
 227          .Case("objc_retainBlock",           IC_RetainBlock)
 228          .Case("objc_release",               IC_Release)
 229          .Case("objc_autorelease",           IC_Autorelease)
 230          .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
 231          .Case("objc_autoreleasePoolPop",    IC_AutoreleasepoolPop)
 232          .Case("objc_retainedObject",        IC_NoopCast)
 233          .Case("objc_unretainedObject",      IC_NoopCast)
 234          .Case("objc_unretainedPointer",     IC_NoopCast)
 235          .Case("objc_retain_autorelease",    IC_FusedRetainAutorelease)
 236          .Case("objc_retainAutorelease",     IC_FusedRetainAutorelease)
 237          .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
 238          .Default(IC_CallOrUser);
 239
 240      // Argument is i8**
 241      if (PointerType *Pte = dyn_cast<PointerType>(ETy))
 242        if (Pte->getElementType()->isIntegerTy(8))
 243          return StringSwitch<InstructionClass>(F->getName())
 244            .Case("objc_loadWeakRetained",      IC_LoadWeakRetained)
 245            .Case("objc_loadWeak",              IC_LoadWeak)
 246            .Case("objc_destroyWeak",           IC_DestroyWeak)
 247            .Default(IC_CallOrUser);
 248    }
 249
 250  // Two arguments, first is i8**.
 251  const Argument *A1 = AI++;
 252  if (AI == AE)
 253    if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
 254      if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
 255        if (Pte->getElementType()->isIntegerTy(8))
 256          if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
 257            Type *ETy1 = PTy1->getElementType();
 258            // Second argument is i8*
 259            if (ETy1->isIntegerTy(8))
 260              return StringSwitch<InstructionClass>(F->getName())
 261                     .Case("objc_storeWeak",             IC_StoreWeak)
 262                     .Case("objc_initWeak",              IC_InitWeak)
 263                     .Case("objc_storeStrong",           IC_StoreStrong)
 264                     .Default(IC_CallOrUser);
 265            // Second argument is i8**.
 266            if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
 267              if (Pte1->getElementType()->isIntegerTy(8))
 268                return StringSwitch<InstructionClass>(F->getName())
 269                       .Case("objc_moveWeak",              IC_MoveWeak)
 270                       .Case("objc_copyWeak",              IC_CopyWeak)
 271                       .Default(IC_CallOrUser);
 272          }
 273
 274  // Anything else.
 275  return IC_CallOrUser;
 276}
 277
 278/// GetInstructionClass - Determine what kind of construct V is.
 279static InstructionClass GetInstructionClass(const Value *V) {
 280  if (const Instruction *I = dyn_cast<Instruction>(V)) {
 281    // Any instruction other than bitcast and gep with a pointer operand have a
 282    // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
 283    // to a subsequent use, rather than using it themselves, in this sense.
 284    // As a short cut, several other opcodes are known to have no pointer
 285    // operands of interest. And ret is never followed by a release, so it's
 286    // not interesting to examine.
 287    switch (I->getOpcode()) {
 288    case Instruction::Call: {
 289      const CallInst *CI = cast<CallInst>(I);
 290      // Check for calls to special functions.
 291      if (const Function *F = CI->getCalledFunction()) {
 292        InstructionClass Class = GetFunctionClass(F);
 293        if (Class != IC_CallOrUser)
 294          return Class;
 295
 296        // None of the intrinsic functions do objc_release. For intrinsics, the
 297        // only question is whether or not they may be users.
 298        switch (F->getIntrinsicID()) {
 299        case Intrinsic::returnaddress: case Intrinsic::frameaddress:
 300        case Intrinsic::stacksave: case Intrinsic::stackrestore:
 301        case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
 302        case Intrinsic::objectsize: case Intrinsic::prefetch:
 303        case Intrinsic::stackprotector:
 304        case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
 305        case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
 306        case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
 307        case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
 308        case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
 309        case Intrinsic::invariant_start: case Intrinsic::invariant_end:
 310        // Don't let dbg info affect our results.
 311        case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
 312          // Short cut: Some intrinsics obviously don't use ObjC pointers.
 313          return IC_None;
 314        default:
 315          break;
 316        }
 317      }
 318      return GetCallSiteClass(CI);
 319    }
 320    case Instruction::Invoke:
 321      return GetCallSiteClass(cast<InvokeInst>(I));
 322    case Instruction::BitCast:
 323    case Instruction::GetElementPtr:
 324    case Instruction::Select: case Instruction::PHI:
 325    case Instruction::Ret: case Instruction::Br:
 326    case Instruction::Switch: case Instruction::IndirectBr:
 327    case Instruction::Alloca: case Instruction::VAArg:
 328    case Instruction::Add: case Instruction::FAdd:
 329    case Instruction::Sub: case Instruction::FSub:
 330    case Instruction::Mul: case Instruction::FMul:
 331    case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
 332    case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
 333    case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
 334    case Instruction::And: case Instruction::Or: case Instruction::Xor:
 335    case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
 336    case Instruction::IntToPtr: case Instruction::FCmp:
 337    case Instruction::FPTrunc: case Instruction::FPExt:
 338    case Instruction::FPToUI: case Instruction::FPToSI:
 339    case Instruction::UIToFP: case Instruction::SIToFP:
 340    case Instruction::InsertElement: case Instruction::ExtractElement:
 341    case Instruction::ShuffleVector:
 342    case Instruction::ExtractValue:
 343      break;
 344    case Instruction::ICmp:
 345      // Comparing a pointer with null, or any other constant, isn't an
 346      // interesting use, because we don't care what the pointer points to, or
 347      // about the values of any other dynamic reference-counted pointers.
 348      if (IsPotentialUse(I->getOperand(1)))
 349        return IC_User;
 350      break;
 351    default:
 352      // For anything else, check all the operands.
 353      // Note that this includes both operands of a Store: while the first
 354      // operand isn't actually being dereferenced, it is being stored to
 355      // memory where we can no longer track who might read it and dereference
 356      // it, so we have to consider it potentially used.
 357      for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
 358           OI != OE; ++OI)
 359        if (IsPotentialUse(*OI))
 360          return IC_User;
 361    }
 362  }
 363
 364  // Otherwise, it's totally inert for ARC purposes.
 365  return IC_None;
 366}
 367
 368/// GetBasicInstructionClass - Determine what kind of construct V is. This is
 369/// similar to GetInstructionClass except that it only detects objc runtine
 370/// calls. This allows it to be faster.
 371static InstructionClass GetBasicInstructionClass(const Value *V) {
 372  if (const CallInst *CI = dyn_cast<CallInst>(V)) {
 373    if (const Function *F = CI->getCalledFunction())
 374      return GetFunctionClass(F);
 375    // Otherwise, be conservative.
 376    return IC_CallOrUser;
 377  }
 378
 379  // Otherwise, be conservative.
 380  return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
 381}
 382
 383/// IsRetain - Test if the given class is objc_retain or
 384/// equivalent.
 385static bool IsRetain(InstructionClass Class) {
 386  return Class == IC_Retain ||
 387         Class == IC_RetainRV;
 388}
 389
 390/// IsAutorelease - Test if the given class is objc_autorelease or
 391/// equivalent.
 392static bool IsAutorelease(InstructionClass Class) {
 393  return Class == IC_Autorelease ||
 394         Class == IC_AutoreleaseRV;
 395}
 396
 397/// IsForwarding - Test if the given class represents instructions which return
 398/// their argument verbatim.
 399static bool IsForwarding(InstructionClass Class) {
 400  // objc_retainBlock technically doesn't always return its argument
 401  // verbatim, but it doesn't matter for our purposes here.
 402  return Class == IC_Retain ||
 403         Class == IC_RetainRV ||
 404         Class == IC_Autorelease ||
 405         Class == IC_AutoreleaseRV ||
 406         Class == IC_RetainBlock ||
 407         Class == IC_NoopCast;
 408}
 409
 410/// IsNoopOnNull - Test if the given class represents instructions which do
 411/// nothing if passed a null pointer.
 412static bool IsNoopOnNull(InstructionClass Class) {
 413  return Class == IC_Retain ||
 414         Class == IC_RetainRV ||
 415         Class == IC_Release ||
 416         Class == IC_Autorelease ||
 417         Class == IC_AutoreleaseRV ||
 418         Class == IC_RetainBlock;
 419}
 420
 421/// IsAlwaysTail - Test if the given class represents instructions which are
 422/// always safe to mark with the "tail" keyword.
 423static bool IsAlwaysTail(InstructionClass Class) {
 424  // IC_RetainBlock may be given a stack argument.
 425  return Class == IC_Retain ||
 426         Class == IC_RetainRV ||
 427         Class == IC_Autorelease ||
 428         Class == IC_AutoreleaseRV;
 429}
 430
 431/// IsNoThrow - Test if the given class represents instructions which are always
 432/// safe to mark with the nounwind attribute..
 433static bool IsNoThrow(InstructionClass Class) {
 434  // objc_retainBlock is not nounwind because it calls user copy constructors
 435  // which could theoretically throw.
 436  return Class == IC_Retain ||
 437         Class == IC_RetainRV ||
 438         Class == IC_Release ||
 439         Class == IC_Autorelease ||
 440         Class == IC_AutoreleaseRV ||
 441         Class == IC_AutoreleasepoolPush ||
 442         Class == IC_AutoreleasepoolPop;
 443}
 444
 445/// EraseInstruction - Erase the given instruction. Many ObjC calls return their
 446/// argument verbatim, so if it's such a call and the return value has users,
 447/// replace them with the argument value.
 448static void EraseInstruction(Instruction *CI) {
 449  Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
 450
 451  bool Unused = CI->use_empty();
 452
 453  if (!Unused) {
 454    // Replace the return value with the argument.
 455    assert(IsForwarding(GetBasicInstructionClass(CI)) &&
 456           "Can't delete non-forwarding instruction with users!");
 457    CI->replaceAllUsesWith(OldArg);
 458  }
 459
 460  CI->eraseFromParent();
 461
 462  if (Unused)
 463    RecursivelyDeleteTriviallyDeadInstructions(OldArg);
 464}
 465
 466/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
 467/// also knows how to look through objc_retain and objc_autorelease calls, which
 468/// we know to return their argument verbatim.
 469static const Value *GetUnderlyingObjCPtr(const Value *V) {
 470  for (;;) {
 471    V = GetUnderlyingObject(V);
 472    if (!IsForwarding(GetBasicInstructionClass(V)))
 473      break;
 474    V = cast<CallInst>(V)->getArgOperand(0);
 475  }
 476
 477  return V;
 478}
 479
 480/// StripPointerCastsAndObjCCalls - This is a wrapper around
 481/// Value::stripPointerCasts which also knows how to look through objc_retain
 482/// and objc_autorelease calls, which we know to return their argument verbatim.
 483static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
 484  for (;;) {
 485    V = V->stripPointerCasts();
 486    if (!IsForwarding(GetBasicInstructionClass(V)))
 487      break;
 488    V = cast<CallInst>(V)->getArgOperand(0);
 489  }
 490  return V;
 491}
 492
 493/// StripPointerCastsAndObjCCalls - This is a wrapper around
 494/// Value::stripPointerCasts which also knows how to look through objc_retain
 495/// and objc_autorelease calls, which we know to return their argument verbatim.
 496static Value *StripPointerCastsAndObjCCalls(Value *V) {
 497  for (;;) {
 498    V = V->stripPointerCasts();
 499    if (!IsForwarding(GetBasicInstructionClass(V)))
 500      break;
 501    V = cast<CallInst>(V)->getArgOperand(0);
 502  }
 503  return V;
 504}
 505
 506/// GetObjCArg - Assuming the given instruction is one of the special calls such
 507/// as objc_retain or objc_release, return the argument value, stripped of no-op
 508/// casts and forwarding calls.
 509static Value *GetObjCArg(Value *Inst) {
 510  return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
 511}
 512
 513/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
 514/// isObjCIdentifiedObject, except that it uses special knowledge of
 515/// ObjC conventions...
 516static bool IsObjCIdentifiedObject(const Value *V) {
 517  // Assume that call results and arguments have their own "provenance".
 518  // Constants (including GlobalVariables) and Allocas are never
 519  // reference-counted.
 520  if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
 521      isa<Argument>(V) || isa<Constant>(V) ||
 522      isa<AllocaInst>(V))
 523    return true;
 524
 525  if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
 526    const Value *Pointer =
 527      StripPointerCastsAndObjCCalls(LI->getPointerOperand());
 528    if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
 529      // A constant pointer can't be pointing to an object on the heap. It may
 530      // be reference-counted, but it won't be deleted.
 531      if (GV->isConstant())
 532        return true;
 533      StringRef Name = GV->getName();
 534      // These special variables are known to hold values which are not
 535      // reference-counted pointers.
 536      if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
 537          Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
 538          Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
 539          Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
 540          Name.startswith("\01l_objc_msgSend_fixup_"))
 541        return true;
 542    }
 543  }
 544
 545  return false;
 546}
 547
 548/// FindSingleUseIdentifiedObject - This is similar to
 549/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
 550/// with multiple uses.
 551static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
 552  if (Arg->hasOneUse()) {
 553    if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
 554      return FindSingleUseIdentifiedObject(BC->getOperand(0));
 555    if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
 556      if (GEP->hasAllZeroIndices())
 557        return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
 558    if (IsForwarding(GetBasicInstructionClass(Arg)))
 559      return FindSingleUseIdentifiedObject(
 560               cast<CallInst>(Arg)->getArgOperand(0));
 561    if (!IsObjCIdentifiedObject(Arg))
 562      return 0;
 563    return Arg;
 564  }
 565
 566  // If we found an identifiable object but it has multiple uses, but they are
 567  // trivial uses, we can still consider this to be a single-use value.
 568  if (IsObjCIdentifiedObject(Arg)) {
 569    for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
 570         UI != UE; ++UI) {
 571      const User *U = *UI;
 572      if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
 573         return 0;
 574    }
 575
 576    return Arg;
 577  }
 578
 579  return 0;
 580}
 581
 582/// ModuleHasARC - Test if the given module looks interesting to run ARC
 583/// optimization on.
 584static bool ModuleHasARC(const Module &M) {
 585  return
 586    M.getNamedValue("objc_retain") ||
 587    M.getNamedValue("objc_release") ||
 588    M.getNamedValue("objc_autorelease") ||
 589    M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
 590    M.getNamedValue("objc_retainBlock") ||
 591    M.getNamedValue("objc_autoreleaseReturnValue") ||
 592    M.getNamedValue("objc_autoreleasePoolPush") ||
 593    M.getNamedValue("objc_loadWeakRetained") ||
 594    M.getNamedValue("objc_loadWeak") ||
 595    M.getNamedValue("objc_destroyWeak") ||
 596    M.getNamedValue("objc_storeWeak") ||
 597    M.getNamedValue("objc_initWeak") ||
 598    M.getNamedValue("objc_moveWeak") ||
 599    M.getNamedValue("objc_copyWeak") ||
 600    M.getNamedValue("objc_retainedObject") ||
 601    M.getNamedValue("objc_unretainedObject") ||
 602    M.getNamedValue("objc_unretainedPointer");
 603}
 604
 605/// DoesObjCBlockEscape - Test whether the given pointer, which is an
 606/// Objective C block pointer, does not "escape". This differs from regular
 607/// escape analysis in that a use as an argument to a call is not considered
 608/// an escape.
 609static bool DoesObjCBlockEscape(const Value *BlockPtr) {
 610  // Walk the def-use chains.
 611  SmallVector<const Value *, 4> Worklist;
 612  Worklist.push_back(BlockPtr);
 613  do {
 614    const Value *V = Worklist.pop_back_val();
 615    for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
 616         UI != UE; ++UI) {
 617      const User *UUser = *UI;
 618      // Special - Use by a call (callee or argument) is not considered
 619      // to be an escape.
 620      switch (GetBasicInstructionClass(UUser)) {
 621      case IC_StoreWeak:
 622      case IC_InitWeak:
 623      case IC_StoreStrong:
 624      case IC_Autorelease:
 625      case IC_AutoreleaseRV:
 626        // These special functions make copies of their pointer arguments.
 627        return true;
 628      case IC_User:
 629      case IC_None:
 630        // Use by an instruction which copies the value is an escape if the
 631        // result is an escape.
 632        if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
 633            isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
 634          Worklist.push_back(UUser);
 635          continue;
 636        }
 637        // Use by a load is not an escape.
 638        if (isa<LoadInst>(UUser))
 639          continue;
 640        // Use by a store is not an escape if the use is the address.
 641        if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
 642          if (V != SI->getValueOperand())
 643            continue;
 644        break;
 645      default:
 646        // Regular calls and other stuff are not considered escapes.
 647        continue;
 648      }
 649      // Otherwise, conservatively assume an escape.
 650      return true;
 651    }
 652  } while (!Worklist.empty());
 653
 654  // No escapes found.
 655  return false;
 656}
 657
 658//===----------------------------------------------------------------------===//
 659// ARC AliasAnalysis.
 660//===----------------------------------------------------------------------===//
 661
 662#include "llvm/Pass.h"
 663#include "llvm/Analysis/AliasAnalysis.h"
 664#include "llvm/Analysis/Passes.h"
 665
 666namespace {
 667  /// ObjCARCAliasAnalysis - This is a simple alias analysis
 668  /// implementation that uses knowledge of ARC constructs to answer queries.
 669  ///
 670  /// TODO: This class could be generalized to know about other ObjC-specific
 671  /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
 672  /// even though their offsets are dynamic.
 673  class ObjCARCAliasAnalysis : public ImmutablePass,
 674                               public AliasAnalysis {
 675  public:
 676    static char ID; // Class identification, replacement for typeinfo
 677    ObjCARCAliasAnalysis() : ImmutablePass(ID) {
 678      initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
 679    }
 680
 681  private:
 682    virtual void initializePass() {
 683      InitializeAliasAnalysis(this);
 684    }
 685
 686    /// getAdjustedAnalysisPointer - This method is used when a pass implements
 687    /// an analysis interface through multiple inheritance.  If needed, it
 688    /// should override this to adjust the this pointer as needed for the
 689    /// specified pass info.
 690    virtual void *getAdjustedAnalysisPointer(const void *PI) {
 691      if (PI == &AliasAnalysis::ID)
 692        return static_cast<AliasAnalysis *>(this);
 693      return this;
 694    }
 695
 696    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
 697    virtual AliasResult alias(const Location &LocA, const Location &LocB);
 698    virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
 699    virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
 700    virtual ModRefBehavior getModRefBehavior(const Function *F);
 701    virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
 702                                       const Location &Loc);
 703    virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
 704                                       ImmutableCallSite CS2);
 705  };
 706}  // End of anonymous namespace
 707
 708// Register this pass...
 709char ObjCARCAliasAnalysis::ID = 0;
 710INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
 711                   "ObjC-ARC-Based Alias Analysis", false, true, false)
 712
 713ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
 714  return new ObjCARCAliasAnalysis();
 715}
 716
 717void
 718ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
 719  AU.setPreservesAll();
 720  AliasAnalysis::getAnalysisUsage(AU);
 721}
 722
 723AliasAnalysis::AliasResult
 724ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
 725  if (!EnableARCOpts)
 726    return AliasAnalysis::alias(LocA, LocB);
 727
 728  // First, strip off no-ops, including ObjC-specific no-ops, and try making a
 729  // precise alias query.
 730  const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
 731  const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
 732  AliasResult Result =
 733    AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
 734                         Location(SB, LocB.Size, LocB.TBAATag));
 735  if (Result != MayAlias)
 736    return Result;
 737
 738  // If that failed, climb to the underlying object, including climbing through
 739  // ObjC-specific no-ops, and try making an imprecise alias query.
 740  const Value *UA = GetUnderlyingObjCPtr(SA);
 741  const Value *UB = GetUnderlyingObjCPtr(SB);
 742  if (UA != SA || UB != SB) {
 743    Result = AliasAnalysis::alias(Location(UA), Location(UB));
 744    // We can't use MustAlias or PartialAlias results here because
 745    // GetUnderlyingObjCPtr may return an offsetted pointer value.
 746    if (Result == NoAlias)
 747      return NoAlias;
 748  }
 749
 750  // If that failed, fail. We don't need to chain here, since that's covered
 751  // by the earlier precise query.
 752  return MayAlias;
 753}
 754
 755bool
 756ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
 757                                             bool OrLocal) {
 758  if (!EnableARCOpts)
 759    return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
 760
 761  // First, strip off no-ops, including ObjC-specific no-ops, and try making
 762  // a precise alias query.
 763  const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
 764  if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
 765                                            OrLocal))
 766    return true;
 767
 768  // If that failed, climb to the underlying object, including climbing through
 769  // ObjC-specific no-ops, and try making an imprecise alias query.
 770  const Value *U = GetUnderlyingObjCPtr(S);
 771  if (U != S)
 772    return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
 773
 774  // If that failed, fail. We don't need to chain here, since that's covered
 775  // by the earlier precise query.
 776  return false;
 777}
 778
 779AliasAnalysis::ModRefBehavior
 780ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
 781  // We have nothing to do. Just chain to the next AliasAnalysis.
 782  return AliasAnalysis::getModRefBehavior(CS);
 783}
 784
 785AliasAnalysis::ModRefBehavior
 786ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
 787  if (!EnableARCOpts)
 788    return AliasAnalysis::getModRefBehavior(F);
 789
 790  switch (GetFunctionClass(F)) {
 791  case IC_NoopCast:
 792    return DoesNotAccessMemory;
 793  default:
 794    break;
 795  }
 796
 797  return AliasAnalysis::getModRefBehavior(F);
 798}
 799
 800AliasAnalysis::ModRefResult
 801ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
 802  if (!EnableARCOpts)
 803    return AliasAnalysis::getModRefInfo(CS, Loc);
 804
 805  switch (GetBasicInstructionClass(CS.getInstruction())) {
 806  case IC_Retain:
 807  case IC_RetainRV:
 808  case IC_Autorelease:
 809  case IC_AutoreleaseRV:
 810  case IC_NoopCast:
 811  case IC_AutoreleasepoolPush:
 812  case IC_FusedRetainAutorelease:
 813  case IC_FusedRetainAutoreleaseRV:
 814    // These functions don't access any memory visible to the compiler.
 815    // Note that this doesn't include objc_retainBlock, because it updates
 816    // pointers when it copies block data.
 817    return NoModRef;
 818  default:
 819    break;
 820  }
 821
 822  return AliasAnalysis::getModRefInfo(CS, Loc);
 823}
 824
 825AliasAnalysis::ModRefResult
 826ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
 827                                    ImmutableCallSite CS2) {
 828  // TODO: Theoretically we could check for dependencies between objc_* calls
 829  // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
 830  return AliasAnalysis::getModRefInfo(CS1, CS2);
 831}
 832
 833//===----------------------------------------------------------------------===//
 834// ARC expansion.
 835//===----------------------------------------------------------------------===//
 836
 837#include "llvm/Support/InstIterator.h"
 838#include "llvm/Transforms/Scalar.h"
 839
 840namespace {
 841  /// ObjCARCExpand - Early ARC transformations.
 842  class ObjCARCExpand : public FunctionPass {
 843    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
 844    virtual bool doInitialization(Module &M);
 845    virtual bool runOnFunction(Function &F);
 846
 847    /// Run - A flag indicating whether this optimization pass should run.
 848    bool Run;
 849
 850  public:
 851    static char ID;
 852    ObjCARCExpand() : FunctionPass(ID) {
 853      initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
 854    }
 855  };
 856}
 857
 858char ObjCARCExpand::ID = 0;
 859INITIALIZE_PASS(ObjCARCExpand,
 860                "objc-arc-expand", "ObjC ARC expansion", false, false)
 861
 862Pass *llvm::createObjCARCExpandPass() {
 863  return new ObjCARCExpand();
 864}
 865
 866void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
 867  AU.setPreservesCFG();
 868}
 869
 870bool ObjCARCExpand::doInitialization(Module &M) {
 871  Run = ModuleHasARC(M);
 872  return false;
 873}
 874
 875bool ObjCARCExpand::runOnFunction(Function &F) {
 876  if (!EnableARCOpts)
 877    return false;
 878
 879  // If nothing in the Module uses ARC, don't do anything.
 880  if (!Run)
 881    return false;
 882
 883  bool Changed = false;
 884
 885  for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
 886    Instruction *Inst = &*I;
 887
 888    switch (GetBasicInstructionClass(Inst)) {
 889    case IC_Retain:
 890    case IC_RetainRV:
 891    case IC_Autorelease:
 892    case IC_AutoreleaseRV:
 893    case IC_FusedRetainAutorelease:
 894    case IC_FusedRetainAutoreleaseRV:
 895      // These calls return their argument verbatim, as a low-level
 896      // optimization. However, this makes high-level optimizations
 897      // harder. Undo any uses of this optimization that the front-end
 898      // emitted here. We'll redo them in the contract pass.
 899      Changed = true;
 900      Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
 901      break;
 902    default:
 903      break;
 904    }
 905  }
 906
 907  return Changed;
 908}
 909
 910//===----------------------------------------------------------------------===//
 911// ARC autorelease pool elimination.
 912//===----------------------------------------------------------------------===//
 913
 914#include "llvm/Constants.h"
 915#include "llvm/ADT/STLExtras.h"
 916
 917namespace {
 918  /// ObjCARCAPElim - Autorelease pool elimination.
 919  class ObjCARCAPElim : public ModulePass {
 920    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
 921    virtual bool runOnModule(Module &M);
 922
 923    static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
 924    static bool OptimizeBB(BasicBlock *BB);
 925
 926  public:
 927    static char ID;
 928    ObjCARCAPElim() : ModulePass(ID) {
 929      initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
 930    }
 931  };
 932}
 933
 934char ObjCARCAPElim::ID = 0;
 935INITIALIZE_PASS(ObjCARCAPElim,
 936                "objc-arc-apelim",
 937                "ObjC ARC autorelease pool elimination",
 938                false, false)
 939
 940Pass *llvm::createObjCARCAPElimPass() {
 941  return new ObjCARCAPElim();
 942}
 943
 944void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
 945  AU.setPreservesCFG();
 946}
 947
 948/// MayAutorelease - Interprocedurally determine if calls made by the
 949/// given call site can possibly produce autoreleases.
 950bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
 951  if (const Function *Callee = CS.getCalledFunction()) {
 952    if (Callee->isDeclaration() || Callee->mayBeOverridden())
 953      return true;
 954    for (Function::const_iterator I = Callee->begin(), E = Callee->end();
 955         I != E; ++I) {
 956      const BasicBlock *BB = I;
 957      for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
 958           J != F; ++J)
 959        if (ImmutableCallSite JCS = ImmutableCallSite(J))
 960          // This recursion depth limit is arbitrary. It's just great
 961          // enough to cover known interesting testcases.
 962          if (Depth < 3 &&
 963              !JCS.onlyReadsMemory() &&
 964              MayAutorelease(JCS, Depth + 1))
 965            return true;
 966    }
 967    return false;
 968  }
 969
 970  return true;
 971}
 972
 973bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
 974  bool Changed = false;
 975
 976  Instruction *Push = 0;
 977  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
 978    Instruction *Inst = I++;
 979    switch (GetBasicInstructionClass(Inst)) {
 980    case IC_AutoreleasepoolPush:
 981      Push = Inst;
 982      break;
 983    case IC_AutoreleasepoolPop:
 984      // If this pop matches a push and nothing in between can autorelease,
 985      // zap the pair.
 986      if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
 987        Changed = true;
 988        Inst->eraseFromParent();
 989        Push->eraseFromParent();
 990      }
 991      Push = 0;
 992      break;
 993    case IC_CallOrUser:
 994      if (MayAutorelease(ImmutableCallSite(Inst)))
 995        Push = 0;
 996      break;
 997    default:
 998      break;
 999    }
1000  }
1001
1002  return Changed;
1003}
1004
1005bool ObjCARCAPElim::runOnModule(Module &M) {
1006  if (!EnableARCOpts)
1007    return false;
1008
1009  // If nothing in the Module uses ARC, don't do anything.
1010  if (!ModuleHasARC(M))
1011    return false;
1012
1013  // Find the llvm.global_ctors variable, as the first step in
1014  // identifying the global constructors. In theory, unnecessary autorelease
1015  // pools could occur anywhere, but in practice it's pretty rare. Global
1016  // ctors are a place where autorelease pools get inserted automatically,
1017  // so it's pretty common for them to be unnecessary, and it's pretty
1018  // profitable to eliminate them.
1019  GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1020  if (!GV)
1021    return false;
1022
1023  assert(GV->hasDefinitiveInitializer() &&
1024         "llvm.global_ctors is uncooperative!");
1025
1026  bool Changed = false;
1027
1028  // Dig the constructor functions out of GV's initializer.
1029  ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1030  for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1031       OI != OE; ++OI) {
1032    Value *Op = *OI;
1033    // llvm.global_ctors is an array of pairs where the second members
1034    // are constructor functions.
1035    Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1036    // If the user used a constructor function with the wrong signature and
1037    // it got bitcasted or whatever, look the other way.
1038    if (!F)
1039      continue;
1040    // Only look at function definitions.
1041    if (F->isDeclaration())
1042      continue;
1043    // Only look at functions with one basic block.
1044    if (llvm::next(F->begin()) != F->end())
1045      continue;
1046    // Ok, a single-block constructor function definition. Try to optimize it.
1047    Changed |= OptimizeBB(F->begin());
1048  }
1049
1050  return Changed;
1051}
1052
1053//===----------------------------------------------------------------------===//
1054// ARC optimization.
1055//===----------------------------------------------------------------------===//
1056
1057// TODO: On code like this:
1058//
1059// objc_retain(%x)
1060// stuff_that_cannot_release()
1061// objc_autorelease(%x)
1062// stuff_that_cannot_release()
1063// objc_retain(%x)
1064// stuff_that_cannot_release()
1065// objc_autorelease(%x)
1066//
1067// The second retain and autorelease can be deleted.
1068
1069// TODO: It should be possible to delete
1070// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1071// pairs if nothing is actually autoreleased between them. Also, autorelease
1072// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1073// after inlining) can be turned into plain release calls.
1074
1075// TODO: Critical-edge splitting. If the optimial insertion point is
1076// a critical edge, the current algorithm has to fail, because it doesn't
1077// know how to split edges. It should be possible to make the optimizer
1078// think in terms of edges, rather than blocks, and then split critical
1079// edges on demand.
1080
1081// TODO: OptimizeSequences could generalized to be Interprocedural.
1082
1083// TODO: Recognize that a bunch of other objc runtime calls have
1084// non-escaping arguments and non-releasing arguments, and may be
1085// non-autoreleasing.
1086
1087// TODO: Sink autorelease calls as far as possible. Unfortunately we
1088// usually can't sink them past other calls, which would be the main
1089// case where it would be useful.
1090
1091// TODO: The pointer returned from objc_loadWeakRetained is retained.
1092
1093// TODO: Delete release+retain pairs (rare).
1094
1095#include "llvm/LLVMContext.h"
1096#include "llvm/Support/CFG.h"
1097#include "llvm/ADT/Statistic.h"
1098#include "llvm/ADT/SmallPtrSet.h"
1099
1100STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
1101STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1102STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1103STATISTIC(NumRets,        "Number of return value forwarding "
1104                          "retain+autoreleaes eliminated");
1105STATISTIC(NumRRs,         "Number of retain+release paths eliminated");
1106STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
1107
1108namespace {
1109  /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1110  /// uses many of the same techniques, except it uses special ObjC-specific
1111  /// reasoning about pointer relationships.
1112  class ProvenanceAnalysis {
1113    AliasAnalysis *AA;
1114
1115    typedef std::pair<const Value *, const Value *> ValuePairTy;
1116    typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1117    CachedResultsTy CachedResults;
1118
1119    bool relatedCheck(const Value *A, const Value *B);
1120    bool relatedSelect(const SelectInst *A, const Value *B);
1121    bool relatedPHI(const PHINode *A, const Value *B);
1122
1123    // Do not implement.
1124    void operator=(const ProvenanceAnalysis &);
1125    ProvenanceAnalysis(const ProvenanceAnalysis &);
1126
1127  public:
1128    ProvenanceAnalysis() {}
1129
1130    void setAA(AliasAnalysis *aa) { AA = aa; }
1131
1132    AliasAnalysis *getAA() const { return AA; }
1133
1134    bool related(const Value *A, const Value *B);
1135
1136    void clear() {
1137      CachedResults.clear();
1138    }
1139  };
1140}
1141
1142bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1143  // If the values are Selects with the same condition, we can do a more precise
1144  // check: just check for relations between the values on corresponding arms.
1145  if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1146    if (A->getCondition() == SB->getCondition())
1147      return related(A->getTrueValue(), SB->getTrueValue()) ||
1148             related(A->getFalseValue(), SB->getFalseValue());
1149
1150  // Check both arms of the Select node individually.
1151  return related(A->getTrueValue(), B) ||
1152         related(A->getFalseValue(), B);
1153}
1154
1155bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1156  // If the values are PHIs in the same block, we can do a more precise as well
1157  // as efficient check: just check for relations between the values on
1158  // corresponding edges.
1159  if (const PHINode *PNB = dyn_cast<PHINode>(B))
1160    if (PNB->getParent() == A->getParent()) {
1161      for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1162        if (related(A->getIncomingValue(i),
1163                    PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1164          return true;
1165      return false;
1166    }
1167
1168  // Check each unique source of the PHI node against B.
1169  SmallPtrSet<const Value *, 4> UniqueSrc;
1170  for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1171    const Value *PV1 = A->getIncomingValue(i);
1172    if (UniqueSrc.insert(PV1) && related(PV1, B))
1173      return true;
1174  }
1175
1176  // All of the arms checked out.
1177  return false;
1178}
1179
1180/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1181/// provenance, is ever stored within the function (not counting callees).
1182static bool isStoredObjCPointer(const Value *P) {
1183  SmallPtrSet<const Value *, 8> Visited;
1184  SmallVector<const Value *, 8> Worklist;
1185  Worklist.push_back(P);
1186  Visited.insert(P);
1187  do {
1188    P = Worklist.pop_back_val();
1189    for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1190         UI != UE; ++UI) {
1191      const User *Ur = *UI;
1192      if (isa<StoreInst>(Ur)) {
1193        if (UI.getOperandNo() == 0)
1194          // The pointer is stored.
1195          return true;
1196        // The pointed is stored through.
1197        continue;
1198      }
1199      if (isa<CallInst>(Ur))
1200        // The pointer is passed as an argument, ignore this.
1201        continue;
1202      if (isa<PtrToIntInst>(P))
1203        // Assume the worst.
1204        return true;
1205      if (Visited.insert(Ur))
1206        Worklist.push_back(Ur);
1207    }
1208  } while (!Worklist.empty());
1209
1210  // Everything checked out.
1211  return false;
1212}
1213
1214bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1215  // Skip past provenance pass-throughs.
1216  A = GetUnderlyingObjCPtr(A);
1217  B = GetUnderlyingObjCPtr(B);
1218
1219  // Quick check.
1220  if (A == B)
1221    return true;
1222
1223  // Ask regular AliasAnalysis, for a first approximation.
1224  switch (AA->alias(A, B)) {
1225  case AliasAnalysis::NoAlias:
1226    return false;
1227  case AliasAnalysis::MustAlias:
1228  case AliasAnalysis::PartialAlias:
1229    return true;
1230  case AliasAnalysis::MayAlias:
1231    break;
1232  }
1233
1234  bool AIsIdentified = IsObjCIdentifiedObject(A);
1235  bool BIsIdentified = IsObjCIdentifiedObject(B);
1236
1237  // An ObjC-Identified object can't alias a load if it is never locally stored.
1238  if (AIsIdentified) {
1239    if (BIsIdentified) {
1240      // If both pointers have provenance, they can be directly compared.
1241      if (A != B)
1242        return false;
1243    } else {
1244      if (isa<LoadInst>(B))
1245        return isStoredObjCPointer(A);
1246    }
1247  } else {
1248    if (BIsIdentified && isa<LoadInst>(A))
1249      return isStoredObjCPointer(B);
1250  }
1251
1252   // Special handling for PHI and Select.
1253  if (const PHINode *PN = dyn_cast<PHINode>(A))
1254    return relatedPHI(PN, B);
1255  if (const PHINode *PN = dyn_cast<PHINode>(B))
1256    return relatedPHI(PN, A);
1257  if (const SelectInst *S = dyn_cast<SelectInst>(A))
1258    return relatedSelect(S, B);
1259  if (const SelectInst *S = dyn_cast<SelectInst>(B))
1260    return relatedSelect(S, A);
1261
1262  // Conservative.
1263  return true;
1264}
1265
1266bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1267  // Begin by inserting a conservative value into the map. If the insertion
1268  // fails, we have the answer already. If it succeeds, leave it there until we
1269  // compute the real answer to guard against recursive queries.
1270  if (A > B) std::swap(A, B);
1271  std::pair<CachedResultsTy::iterator, bool> Pair =
1272    CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1273  if (!Pair.second)
1274    return Pair.first->second;
1275
1276  bool Result = relatedCheck(A, B);
1277  CachedResults[ValuePairTy(A, B)] = Result;
1278  return Result;
1279}
1280
1281namespace {
1282  // Sequence - A sequence of states that a pointer may go through in which an
1283  // objc_retain and objc_release are actually needed.
1284  enum Sequence {
1285    S_None,
1286    S_Retain,         ///< objc_retain(x)
1287    S_CanRelease,     ///< foo(x) -- x could possibly see a ref count decrement
1288    S_Use,            ///< any use of x
1289    S_Stop,           ///< like S_Release, but code motion is stopped
1290    S_Release,        ///< objc_release(x)
1291    S_MovableRelease  ///< objc_release(x), !clang.imprecise_release
1292  };
1293}
1294
1295static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1296  // The easy cases.
1297  if (A == B)
1298    return A;
1299  if (A == S_None || B == S_None)
1300    return S_None;
1301
1302  if (A > B) std::swap(A, B);
1303  if (TopDown) {
1304    // Choose the side which is further along in the sequence.
1305    if ((A == S_Retain || A == S_CanRelease) &&
1306        (B == S_CanRelease || B == S_Use))
1307      return B;
1308  } else {
1309    // Choose the side which is further along in the sequence.
1310    if ((A == S_Use || A == S_CanRelease) &&
1311        (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1312      return A;
1313    // If both sides are releases, choose the more conservative one.
1314    if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1315      return A;
1316    if (A == S_Release && B == S_MovableRelease)
1317      return A;
1318  }
1319
1320  return S_None;
1321}
1322
1323namespace {
1324  /// RRInfo - Unidirectional information about either a
1325  /// retain-decrement-use-release sequence or release-use-decrement-retain
1326  /// reverese sequence.
1327  struct RRInfo {
1328    /// KnownSafe - After an objc_retain, the reference count of the referenced
1329    /// object is known to be positive. Similarly, before an objc_release, the
1330    /// reference count of the referenced object is known to be positive. If
1331    /// there are retain-release pairs in code regions where the retain count
1332    /// is known to be positive, they can be eliminated, regardless of any side
1333    /// effects between them.
1334    ///
1335    /// Also, a retain+release pair nested within another retain+release
1336    /// pair all on the known same pointer value can be eliminated, regardless
1337    /// of any intervening side effects.
1338    ///
1339    /// KnownSafe is true when either of these conditions is satisfied.
1340    bool KnownSafe;
1341
1342    /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1343    /// opposed to objc_retain calls).
1344    bool IsRetainBlock;
1345
1346    /// IsTailCallRelease - True of the objc_release calls are all marked
1347    /// with the "tail" keyword.
1348    bool IsTailCallRelease;
1349
1350    /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1351    /// a clang.imprecise_release tag, this is the metadata tag.
1352    MDNode *ReleaseMetadata;
1353
1354    /// Calls - For a top-down sequence, the set of objc_retains or
1355    /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1356    SmallPtrSet<Instruction *, 2> Calls;
1357
1358    /// ReverseInsertPts - The set of optimal insert positions for
1359    /// moving calls in the opposite sequence.
1360    SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1361
1362    RRInfo() 

Large files files are truncated, but you can click here to view the full file