LLVM API Documentation

ObjCARCContract.cpp
Go to the documentation of this file.
00001 //===- ObjCARCContract.cpp - ObjC ARC Optimization ------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 /// \file
00010 /// This file defines late ObjC ARC optimizations. ARC stands for Automatic
00011 /// Reference Counting and is a system for managing reference counts for objects
00012 /// in Objective C.
00013 ///
00014 /// This specific file mainly deals with ``contracting'' multiple lower level
00015 /// operations into singular higher level operations through pattern matching.
00016 ///
00017 /// WARNING: This file knows about certain library functions. It recognizes them
00018 /// by name, and hardwires knowledge of their semantics.
00019 ///
00020 /// WARNING: This file knows about how certain Objective-C library functions are
00021 /// used. Naive LLVM IR transformations which would otherwise be
00022 /// behavior-preserving may break these assumptions.
00023 ///
00024 //===----------------------------------------------------------------------===//
00025 
00026 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
00027 // dominated by single calls.
00028 
00029 #include "ObjCARC.h"
00030 #include "ARCRuntimeEntryPoints.h"
00031 #include "DependencyAnalysis.h"
00032 #include "ProvenanceAnalysis.h"
00033 #include "llvm/ADT/Statistic.h"
00034 #include "llvm/IR/Dominators.h"
00035 #include "llvm/IR/InlineAsm.h"
00036 #include "llvm/IR/Operator.h"
00037 #include "llvm/Support/Debug.h"
00038 
00039 using namespace llvm;
00040 using namespace llvm::objcarc;
00041 
00042 #define DEBUG_TYPE "objc-arc-contract"
00043 
00044 STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
00045 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
00046 
00047 //===----------------------------------------------------------------------===//
00048 //                                Declarations
00049 //===----------------------------------------------------------------------===//
00050 
00051 namespace {
00052   /// \brief Late ARC optimizations
00053   ///
00054   /// These change the IR in a way that makes it difficult to be analyzed by
00055   /// ObjCARCOpt, so it's run late.
00056   class ObjCARCContract : public FunctionPass {
00057     bool Changed;
00058     AliasAnalysis *AA;
00059     DominatorTree *DT;
00060     ProvenanceAnalysis PA;
00061     ARCRuntimeEntryPoints EP;
00062 
00063     /// A flag indicating whether this optimization pass should run.
00064     bool Run;
00065 
00066     /// The inline asm string to insert between calls and RetainRV calls to make
00067     /// the optimization work on targets which need it.
00068     const MDString *RetainRVMarker;
00069 
00070     /// The set of inserted objc_storeStrong calls. If at the end of walking the
00071     /// function we have found no alloca instructions, these calls can be marked
00072     /// "tail".
00073     SmallPtrSet<CallInst *, 8> StoreStrongCalls;
00074 
00075     /// Returns true if we eliminated Inst.
00076     bool tryToPeepholeInstruction(Function &F, Instruction *Inst,
00077                                   inst_iterator &Iter,
00078                                   SmallPtrSetImpl<Instruction *> &DepInsts,
00079                                   SmallPtrSetImpl<const BasicBlock *> &Visited,
00080                                   bool &TailOkForStoreStrong);
00081 
00082     bool optimizeRetainCall(Function &F, Instruction *Retain);
00083 
00084     bool
00085     contractAutorelease(Function &F, Instruction *Autorelease,
00086                         ARCInstKind Class,
00087                         SmallPtrSetImpl<Instruction *> &DependingInstructions,
00088                         SmallPtrSetImpl<const BasicBlock *> &Visited);
00089 
00090     void tryToContractReleaseIntoStoreStrong(Instruction *Release,
00091                                              inst_iterator &Iter);
00092 
00093     void getAnalysisUsage(AnalysisUsage &AU) const override;
00094     bool doInitialization(Module &M) override;
00095     bool runOnFunction(Function &F) override;
00096 
00097   public:
00098     static char ID;
00099     ObjCARCContract() : FunctionPass(ID) {
00100       initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
00101     }
00102   };
00103 }
00104 
00105 //===----------------------------------------------------------------------===//
00106 //                               Implementation
00107 //===----------------------------------------------------------------------===//
00108 
00109 /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
00110 /// return value. We do this late so we do not disrupt the dataflow analysis in
00111 /// ObjCARCOpt.
00112 bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
00113   ImmutableCallSite CS(GetArgRCIdentityRoot(Retain));
00114   const Instruction *Call = CS.getInstruction();
00115   if (!Call)
00116     return false;
00117   if (Call->getParent() != Retain->getParent())
00118     return false;
00119 
00120   // Check that the call is next to the retain.
00121   BasicBlock::const_iterator I = Call;
00122   ++I;
00123   while (IsNoopInstruction(I)) ++I;
00124   if (&*I != Retain)
00125     return false;
00126 
00127   // Turn it to an objc_retainAutoreleasedReturnValue.
00128   Changed = true;
00129   ++NumPeeps;
00130 
00131   DEBUG(dbgs() << "Transforming objc_retain => "
00132                   "objc_retainAutoreleasedReturnValue since the operand is a "
00133                   "return value.\nOld: "<< *Retain << "\n");
00134 
00135   // We do not have to worry about tail calls/does not throw since
00136   // retain/retainRV have the same properties.
00137   Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_RetainRV);
00138   cast<CallInst>(Retain)->setCalledFunction(Decl);
00139 
00140   DEBUG(dbgs() << "New: " << *Retain << "\n");
00141   return true;
00142 }
00143 
00144 /// Merge an autorelease with a retain into a fused call.
00145 bool ObjCARCContract::contractAutorelease(
00146     Function &F, Instruction *Autorelease, ARCInstKind Class,
00147     SmallPtrSetImpl<Instruction *> &DependingInstructions,
00148     SmallPtrSetImpl<const BasicBlock *> &Visited) {
00149   const Value *Arg = GetArgRCIdentityRoot(Autorelease);
00150 
00151   // Check that there are no instructions between the retain and the autorelease
00152   // (such as an autorelease_pop) which may change the count.
00153   CallInst *Retain = nullptr;
00154   if (Class == ARCInstKind::AutoreleaseRV)
00155     FindDependencies(RetainAutoreleaseRVDep, Arg,
00156                      Autorelease->getParent(), Autorelease,
00157                      DependingInstructions, Visited, PA);
00158   else
00159     FindDependencies(RetainAutoreleaseDep, Arg,
00160                      Autorelease->getParent(), Autorelease,
00161                      DependingInstructions, Visited, PA);
00162 
00163   Visited.clear();
00164   if (DependingInstructions.size() != 1) {
00165     DependingInstructions.clear();
00166     return false;
00167   }
00168 
00169   Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
00170   DependingInstructions.clear();
00171 
00172   if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
00173       GetArgRCIdentityRoot(Retain) != Arg)
00174     return false;
00175 
00176   Changed = true;
00177   ++NumPeeps;
00178 
00179   DEBUG(dbgs() << "    Fusing retain/autorelease!\n"
00180                   "        Autorelease:" << *Autorelease << "\n"
00181                   "        Retain: " << *Retain << "\n");
00182 
00183   Constant *Decl = EP.get(Class == ARCInstKind::AutoreleaseRV
00184                               ? ARCRuntimeEntryPoints::EPT_RetainAutoreleaseRV
00185                               : ARCRuntimeEntryPoints::EPT_RetainAutorelease);
00186   Retain->setCalledFunction(Decl);
00187 
00188   DEBUG(dbgs() << "        New RetainAutorelease: " << *Retain << "\n");
00189 
00190   EraseInstruction(Autorelease);
00191   return true;
00192 }
00193 
00194 static StoreInst *findSafeStoreForStoreStrongContraction(LoadInst *Load,
00195                                                          Instruction *Release,
00196                                                          ProvenanceAnalysis &PA,
00197                                                          AliasAnalysis *AA) {
00198   StoreInst *Store = nullptr;
00199   bool SawRelease = false;
00200 
00201   // Get the location associated with Load.
00202   AliasAnalysis::Location Loc = AA->getLocation(Load);
00203 
00204   // Walk down to find the store and the release, which may be in either order.
00205   for (auto I = std::next(BasicBlock::iterator(Load)),
00206             E = Load->getParent()->end();
00207        I != E; ++I) {
00208     // If we found the store we were looking for and saw the release,
00209     // break. There is no more work to be done.
00210     if (Store && SawRelease)
00211       break;
00212 
00213     // Now we know that we have not seen either the store or the release. If I
00214     // is the the release, mark that we saw the release and continue.
00215     Instruction *Inst = &*I;
00216     if (Inst == Release) {
00217       SawRelease = true;
00218       continue;
00219     }
00220 
00221     // Otherwise, we check if Inst is a "good" store. Grab the instruction class
00222     // of Inst.
00223     ARCInstKind Class = GetBasicARCInstKind(Inst);
00224 
00225     // If Inst is an unrelated retain, we don't care about it.
00226     //
00227     // TODO: This is one area where the optimization could be made more
00228     // aggressive.
00229     if (IsRetain(Class))
00230       continue;
00231 
00232     // If we have seen the store, but not the release...
00233     if (Store) {
00234       // We need to make sure that it is safe to move the release from its
00235       // current position to the store. This implies proving that any
00236       // instruction in between Store and the Release conservatively can not use
00237       // the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
00238       // continue...
00239       if (!CanUse(Inst, Load, PA, Class)) {
00240         continue;
00241       }
00242 
00243       // Otherwise, be conservative and return nullptr.
00244       return nullptr;
00245     }
00246 
00247     // Ok, now we know we have not seen a store yet. See if Inst can write to
00248     // our load location, if it can not, just ignore the instruction.
00249     if (!(AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod))
00250       continue;
00251 
00252     Store = dyn_cast<StoreInst>(Inst);
00253 
00254     // If Inst can, then check if Inst is a simple store. If Inst is not a
00255     // store or a store that is not simple, then we have some we do not
00256     // understand writing to this memory implying we can not move the load
00257     // over the write to any subsequent store that we may find.
00258     if (!Store || !Store->isSimple())
00259       return nullptr;
00260 
00261     // Then make sure that the pointer we are storing to is Ptr. If so, we
00262     // found our Store!
00263     if (Store->getPointerOperand() == Loc.Ptr)
00264       continue;
00265 
00266     // Otherwise, we have an unknown store to some other ptr that clobbers
00267     // Loc.Ptr. Bail!
00268     return nullptr;
00269   }
00270 
00271   // If we did not find the store or did not see the release, fail.
00272   if (!Store || !SawRelease)
00273     return nullptr;
00274 
00275   // We succeeded!
00276   return Store;
00277 }
00278 
00279 static Instruction *
00280 findRetainForStoreStrongContraction(Value *New, StoreInst *Store,
00281                                     Instruction *Release,
00282                                     ProvenanceAnalysis &PA) {
00283   // Walk up from the Store to find the retain.
00284   BasicBlock::iterator I = Store;
00285   BasicBlock::iterator Begin = Store->getParent()->begin();
00286   while (I != Begin && GetBasicARCInstKind(I) != ARCInstKind::Retain) {
00287     Instruction *Inst = &*I;
00288 
00289     // It is only safe to move the retain to the store if we can prove
00290     // conservatively that nothing besides the release can decrement reference
00291     // counts in between the retain and the store.
00292     if (CanDecrementRefCount(Inst, New, PA) && Inst != Release)
00293       return nullptr;
00294     --I;
00295   }
00296   Instruction *Retain = I;
00297   if (GetBasicARCInstKind(Retain) != ARCInstKind::Retain)
00298     return nullptr;
00299   if (GetArgRCIdentityRoot(Retain) != New)
00300     return nullptr;
00301   return Retain;
00302 }
00303 
00304 /// Attempt to merge an objc_release with a store, load, and objc_retain to form
00305 /// an objc_storeStrong. An objc_storeStrong:
00306 ///
00307 ///   objc_storeStrong(i8** %old_ptr, i8* new_value)
00308 ///
00309 /// is equivalent to the following IR sequence:
00310 ///
00311 ///   ; Load old value.
00312 ///   %old_value = load i8** %old_ptr               (1)
00313 ///
00314 ///   ; Increment the new value and then release the old value. This must occur
00315 ///   ; in order in case old_value releases new_value in its destructor causing
00316 ///   ; us to potentially have a dangling ptr.
00317 ///   tail call i8* @objc_retain(i8* %new_value)    (2)
00318 ///   tail call void @objc_release(i8* %old_value)  (3)
00319 ///
00320 ///   ; Store the new_value into old_ptr
00321 ///   store i8* %new_value, i8** %old_ptr           (4)
00322 ///
00323 /// The safety of this optimization is based around the following
00324 /// considerations:
00325 ///
00326 ///  1. We are forming the store strong at the store. Thus to perform this
00327 ///     optimization it must be safe to move the retain, load, and release to
00328 ///     (4).
00329 ///  2. We need to make sure that any re-orderings of (1), (2), (3), (4) are
00330 ///     safe.
00331 void ObjCARCContract::tryToContractReleaseIntoStoreStrong(Instruction *Release,
00332                                                           inst_iterator &Iter) {
00333   // See if we are releasing something that we just loaded.
00334   auto *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
00335   if (!Load || !Load->isSimple())
00336     return;
00337 
00338   // For now, require everything to be in one basic block.
00339   BasicBlock *BB = Release->getParent();
00340   if (Load->getParent() != BB)
00341     return;
00342 
00343   // First scan down the BB from Load, looking for a store of the RCIdentityRoot
00344   // of Load's
00345   StoreInst *Store =
00346       findSafeStoreForStoreStrongContraction(Load, Release, PA, AA);
00347   // If we fail, bail.
00348   if (!Store)
00349     return;
00350 
00351   // Then find what new_value's RCIdentity Root is.
00352   Value *New = GetRCIdentityRoot(Store->getValueOperand());
00353 
00354   // Then walk up the BB and look for a retain on New without any intervening
00355   // instructions which conservatively might decrement ref counts.
00356   Instruction *Retain =
00357       findRetainForStoreStrongContraction(New, Store, Release, PA);
00358 
00359   // If we fail, bail.
00360   if (!Retain)
00361     return;
00362 
00363   Changed = true;
00364   ++NumStoreStrongs;
00365 
00366   DEBUG(
00367       llvm::dbgs() << "    Contracting retain, release into objc_storeStrong.\n"
00368                    << "        Old:\n"
00369                    << "            Store:   " << *Store << "\n"
00370                    << "            Release: " << *Release << "\n"
00371                    << "            Retain:  " << *Retain << "\n"
00372                    << "            Load:    " << *Load << "\n");
00373 
00374   LLVMContext &C = Release->getContext();
00375   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
00376   Type *I8XX = PointerType::getUnqual(I8X);
00377 
00378   Value *Args[] = { Load->getPointerOperand(), New };
00379   if (Args[0]->getType() != I8XX)
00380     Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
00381   if (Args[1]->getType() != I8X)
00382     Args[1] = new BitCastInst(Args[1], I8X, "", Store);
00383   Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_StoreStrong);
00384   CallInst *StoreStrong = CallInst::Create(Decl, Args, "", Store);
00385   StoreStrong->setDoesNotThrow();
00386   StoreStrong->setDebugLoc(Store->getDebugLoc());
00387 
00388   // We can't set the tail flag yet, because we haven't yet determined
00389   // whether there are any escaping allocas. Remember this call, so that
00390   // we can set the tail flag once we know it's safe.
00391   StoreStrongCalls.insert(StoreStrong);
00392 
00393   DEBUG(llvm::dbgs() << "        New Store Strong: " << *StoreStrong << "\n");
00394 
00395   if (&*Iter == Store) ++Iter;
00396   Store->eraseFromParent();
00397   Release->eraseFromParent();
00398   EraseInstruction(Retain);
00399   if (Load->use_empty())
00400     Load->eraseFromParent();
00401 }
00402 
00403 bool ObjCARCContract::tryToPeepholeInstruction(
00404   Function &F, Instruction *Inst, inst_iterator &Iter,
00405   SmallPtrSetImpl<Instruction *> &DependingInsts,
00406   SmallPtrSetImpl<const BasicBlock *> &Visited,
00407   bool &TailOkForStoreStrongs) {
00408     // Only these library routines return their argument. In particular,
00409     // objc_retainBlock does not necessarily return its argument.
00410   ARCInstKind Class = GetBasicARCInstKind(Inst);
00411     switch (Class) {
00412     case ARCInstKind::FusedRetainAutorelease:
00413     case ARCInstKind::FusedRetainAutoreleaseRV:
00414       return false;
00415     case ARCInstKind::Autorelease:
00416     case ARCInstKind::AutoreleaseRV:
00417       return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
00418     case ARCInstKind::Retain:
00419       // Attempt to convert retains to retainrvs if they are next to function
00420       // calls.
00421       if (!optimizeRetainCall(F, Inst))
00422         return false;
00423       // If we succeed in our optimization, fall through.
00424       // FALLTHROUGH
00425     case ARCInstKind::RetainRV: {
00426       // If we're compiling for a target which needs a special inline-asm
00427       // marker to do the retainAutoreleasedReturnValue optimization,
00428       // insert it now.
00429       if (!RetainRVMarker)
00430         return false;
00431       BasicBlock::iterator BBI = Inst;
00432       BasicBlock *InstParent = Inst->getParent();
00433 
00434       // Step up to see if the call immediately precedes the RetainRV call.
00435       // If it's an invoke, we have to cross a block boundary. And we have
00436       // to carefully dodge no-op instructions.
00437       do {
00438         if (&*BBI == InstParent->begin()) {
00439           BasicBlock *Pred = InstParent->getSinglePredecessor();
00440           if (!Pred)
00441             goto decline_rv_optimization;
00442           BBI = Pred->getTerminator();
00443           break;
00444         }
00445         --BBI;
00446       } while (IsNoopInstruction(BBI));
00447 
00448       if (&*BBI == GetArgRCIdentityRoot(Inst)) {
00449         DEBUG(dbgs() << "Adding inline asm marker for "
00450                         "retainAutoreleasedReturnValue optimization.\n");
00451         Changed = true;
00452         InlineAsm *IA =
00453           InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
00454                                            /*isVarArg=*/false),
00455                          RetainRVMarker->getString(),
00456                          /*Constraints=*/"", /*hasSideEffects=*/true);
00457         CallInst::Create(IA, "", Inst);
00458       }
00459     decline_rv_optimization:
00460       return false;
00461     }
00462     case ARCInstKind::InitWeak: {
00463       // objc_initWeak(p, null) => *p = null
00464       CallInst *CI = cast<CallInst>(Inst);
00465       if (IsNullOrUndef(CI->getArgOperand(1))) {
00466         Value *Null =
00467           ConstantPointerNull::get(cast<PointerType>(CI->getType()));
00468         Changed = true;
00469         new StoreInst(Null, CI->getArgOperand(0), CI);
00470 
00471         DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
00472                      << "                 New = " << *Null << "\n");
00473 
00474         CI->replaceAllUsesWith(Null);
00475         CI->eraseFromParent();
00476       }
00477       return true;
00478     }
00479     case ARCInstKind::Release:
00480       // Try to form an objc store strong from our release. If we fail, there is
00481       // nothing further to do below, so continue.
00482       tryToContractReleaseIntoStoreStrong(Inst, Iter);
00483       return true;
00484     case ARCInstKind::User:
00485       // Be conservative if the function has any alloca instructions.
00486       // Technically we only care about escaping alloca instructions,
00487       // but this is sufficient to handle some interesting cases.
00488       if (isa<AllocaInst>(Inst))
00489         TailOkForStoreStrongs = false;
00490       return true;
00491     case ARCInstKind::IntrinsicUser:
00492       // Remove calls to @clang.arc.use(...).
00493       Inst->eraseFromParent();
00494       return true;
00495     default:
00496       return true;
00497     }
00498 }
00499 
00500 //===----------------------------------------------------------------------===//
00501 //                              Top Level Driver
00502 //===----------------------------------------------------------------------===//
00503 
00504 bool ObjCARCContract::runOnFunction(Function &F) {
00505   if (!EnableARCOpts)
00506     return false;
00507 
00508   // If nothing in the Module uses ARC, don't do anything.
00509   if (!Run)
00510     return false;
00511 
00512   Changed = false;
00513   AA = &getAnalysis<AliasAnalysis>();
00514   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00515 
00516   PA.setAA(&getAnalysis<AliasAnalysis>());
00517 
00518   DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
00519 
00520   // Track whether it's ok to mark objc_storeStrong calls with the "tail"
00521   // keyword. Be conservative if the function has variadic arguments.
00522   // It seems that functions which "return twice" are also unsafe for the
00523   // "tail" argument, because they are setjmp, which could need to
00524   // return to an earlier stack state.
00525   bool TailOkForStoreStrongs =
00526       !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
00527 
00528   // For ObjC library calls which return their argument, replace uses of the
00529   // argument with uses of the call return value, if it dominates the use. This
00530   // reduces register pressure.
00531   SmallPtrSet<Instruction *, 4> DependingInstructions;
00532   SmallPtrSet<const BasicBlock *, 4> Visited;
00533   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
00534     Instruction *Inst = &*I++;
00535 
00536     DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
00537 
00538     // First try to peephole Inst. If there is nothing further we can do in
00539     // terms of undoing objc-arc-expand, process the next inst.
00540     if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
00541                                  TailOkForStoreStrongs))
00542       continue;
00543 
00544     // Otherwise, try to undo objc-arc-expand.
00545 
00546     // Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
00547     // and such; to do the replacement, the argument must have type i8*.
00548     Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
00549 
00550     // TODO: Change this to a do-while.
00551     for (;;) {
00552       // If we're compiling bugpointed code, don't get in trouble.
00553       if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
00554         break;
00555       // Look through the uses of the pointer.
00556       for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
00557            UI != UE; ) {
00558         // Increment UI now, because we may unlink its element.
00559         Use &U = *UI++;
00560         unsigned OperandNo = U.getOperandNo();
00561 
00562         // If the call's return value dominates a use of the call's argument
00563         // value, rewrite the use to use the return value. We check for
00564         // reachability here because an unreachable call is considered to
00565         // trivially dominate itself, which would lead us to rewriting its
00566         // argument in terms of its return value, which would lead to
00567         // infinite loops in GetArgRCIdentityRoot.
00568         if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
00569           Changed = true;
00570           Instruction *Replacement = Inst;
00571           Type *UseTy = U.get()->getType();
00572           if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
00573             // For PHI nodes, insert the bitcast in the predecessor block.
00574             unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
00575             BasicBlock *BB = PHI->getIncomingBlock(ValNo);
00576             if (Replacement->getType() != UseTy)
00577               Replacement = new BitCastInst(Replacement, UseTy, "",
00578                                             &BB->back());
00579             // While we're here, rewrite all edges for this PHI, rather
00580             // than just one use at a time, to minimize the number of
00581             // bitcasts we emit.
00582             for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
00583               if (PHI->getIncomingBlock(i) == BB) {
00584                 // Keep the UI iterator valid.
00585                 if (UI != UE &&
00586                     &PHI->getOperandUse(
00587                         PHINode::getOperandNumForIncomingValue(i)) == &*UI)
00588                   ++UI;
00589                 PHI->setIncomingValue(i, Replacement);
00590               }
00591           } else {
00592             if (Replacement->getType() != UseTy)
00593               Replacement = new BitCastInst(Replacement, UseTy, "",
00594                                             cast<Instruction>(U.getUser()));
00595             U.set(Replacement);
00596           }
00597         }
00598       }
00599 
00600       // If Arg is a no-op casted pointer, strip one level of casts and iterate.
00601       if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
00602         Arg = BI->getOperand(0);
00603       else if (isa<GEPOperator>(Arg) &&
00604                cast<GEPOperator>(Arg)->hasAllZeroIndices())
00605         Arg = cast<GEPOperator>(Arg)->getPointerOperand();
00606       else if (isa<GlobalAlias>(Arg) &&
00607                !cast<GlobalAlias>(Arg)->mayBeOverridden())
00608         Arg = cast<GlobalAlias>(Arg)->getAliasee();
00609       else
00610         break;
00611     }
00612   }
00613 
00614   // If this function has no escaping allocas or suspicious vararg usage,
00615   // objc_storeStrong calls can be marked with the "tail" keyword.
00616   if (TailOkForStoreStrongs)
00617     for (CallInst *CI : StoreStrongCalls)
00618       CI->setTailCall();
00619   StoreStrongCalls.clear();
00620 
00621   return Changed;
00622 }
00623 
00624 //===----------------------------------------------------------------------===//
00625 //                             Misc Pass Manager
00626 //===----------------------------------------------------------------------===//
00627 
00628 char ObjCARCContract::ID = 0;
00629 INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract",
00630                       "ObjC ARC contraction", false, false)
00631 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00632 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00633 INITIALIZE_PASS_END(ObjCARCContract, "objc-arc-contract",
00634                     "ObjC ARC contraction", false, false)
00635 
00636 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
00637   AU.addRequired<AliasAnalysis>();
00638   AU.addRequired<DominatorTreeWrapperPass>();
00639   AU.setPreservesCFG();
00640 }
00641 
00642 Pass *llvm::createObjCARCContractPass() { return new ObjCARCContract(); }
00643 
00644 bool ObjCARCContract::doInitialization(Module &M) {
00645   // If nothing in the Module uses ARC, don't do anything.
00646   Run = ModuleHasARC(M);
00647   if (!Run)
00648     return false;
00649 
00650   EP.Initialize(&M);
00651 
00652   // Initialize RetainRVMarker.
00653   RetainRVMarker = nullptr;
00654   if (NamedMDNode *NMD =
00655           M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
00656     if (NMD->getNumOperands() == 1) {
00657       const MDNode *N = NMD->getOperand(0);
00658       if (N->getNumOperands() == 1)
00659         if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
00660           RetainRVMarker = S;
00661     }
00662 
00663   return false;
00664 }