1 //===- ObjCARCContract.cpp - ObjC ARC Optimization ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file defines late ObjC ARC optimizations. ARC stands for Automatic
10 /// Reference Counting and is a system for managing reference counts for objects
11 /// in Objective C.
12 ///
13 /// This specific file mainly deals with ``contracting'' multiple lower level
14 /// operations into singular higher level operations through pattern matching.
15 ///
16 /// WARNING: This file knows about certain library functions. It recognizes them
17 /// by name, and hardwires knowledge of their semantics.
18 ///
19 /// WARNING: This file knows about how certain Objective-C library functions are
20 /// used. Naive LLVM IR transformations which would otherwise be
21 /// behavior-preserving may break these assumptions.
22 ///
23 //===----------------------------------------------------------------------===//
24 
25 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
26 // dominated by single calls.
27 
28 #include "ARCRuntimeEntryPoints.h"
29 #include "DependencyAnalysis.h"
30 #include "ObjCARC.h"
31 #include "ProvenanceAnalysis.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/InlineAsm.h"
36 #include "llvm/IR/InstIterator.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/IR/PassManager.h"
39 #include "llvm/InitializePasses.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Transforms/ObjCARC.h"
44 
45 using namespace llvm;
46 using namespace llvm::objcarc;
47 
48 #define DEBUG_TYPE "objc-arc-contract"
49 
50 STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
51 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
52 
53 //===----------------------------------------------------------------------===//
54 //                                Declarations
55 //===----------------------------------------------------------------------===//
56 
57 namespace {
58 /// Late ARC optimizations
59 ///
60 /// These change the IR in a way that makes it difficult to be analyzed by
61 /// ObjCARCOpt, so it's run late.
62 
63 class ObjCARCContract {
64   bool Changed;
65   AliasAnalysis *AA;
66   DominatorTree *DT;
67   ProvenanceAnalysis PA;
68   ARCRuntimeEntryPoints EP;
69 
70   /// A flag indicating whether this optimization pass should run.
71   bool Run;
72 
73   /// The inline asm string to insert between calls and RetainRV calls to make
74   /// the optimization work on targets which need it.
75   const MDString *RVInstMarker;
76 
77   /// The set of inserted objc_storeStrong calls. If at the end of walking the
78   /// function we have found no alloca instructions, these calls can be marked
79   /// "tail".
80   SmallPtrSet<CallInst *, 8> StoreStrongCalls;
81 
82   /// Returns true if we eliminated Inst.
83   bool tryToPeepholeInstruction(
84       Function &F, Instruction *Inst, inst_iterator &Iter,
85       bool &TailOkForStoreStrong,
86       const DenseMap<BasicBlock *, ColorVector> &BlockColors);
87 
88   bool optimizeRetainCall(Function &F, Instruction *Retain);
89 
90   bool contractAutorelease(Function &F, Instruction *Autorelease,
91                            ARCInstKind Class);
92 
93   void tryToContractReleaseIntoStoreStrong(
94       Instruction *Release, inst_iterator &Iter,
95       const DenseMap<BasicBlock *, ColorVector> &BlockColors);
96 
97 public:
98   bool init(Module &M);
99   bool run(Function &F, AAResults *AA, DominatorTree *DT);
100 };
101 
102 class ObjCARCContractLegacyPass : public FunctionPass {
103   ObjCARCContract OCARCC;
104 
105 public:
106   void getAnalysisUsage(AnalysisUsage &AU) const override;
107   bool doInitialization(Module &M) override;
108   bool runOnFunction(Function &F) override;
109 
110   static char ID;
111   ObjCARCContractLegacyPass() : FunctionPass(ID) {
112     initializeObjCARCContractLegacyPassPass(*PassRegistry::getPassRegistry());
113   }
114 };
115 }
116 
117 //===----------------------------------------------------------------------===//
118 //                               Implementation
119 //===----------------------------------------------------------------------===//
120 
121 /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
122 /// return value. We do this late so we do not disrupt the dataflow analysis in
123 /// ObjCARCOpt.
124 bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
125   const auto *Call = dyn_cast<CallBase>(GetArgRCIdentityRoot(Retain));
126   if (!Call)
127     return false;
128   if (Call->getParent() != Retain->getParent())
129     return false;
130 
131   // Check that the call is next to the retain.
132   BasicBlock::const_iterator I = ++Call->getIterator();
133   while (IsNoopInstruction(&*I))
134     ++I;
135   if (&*I != Retain)
136     return false;
137 
138   // Turn it to an objc_retainAutoreleasedReturnValue.
139   Changed = true;
140   ++NumPeeps;
141 
142   LLVM_DEBUG(
143       dbgs() << "Transforming objc_retain => "
144                 "objc_retainAutoreleasedReturnValue since the operand is a "
145                 "return value.\nOld: "
146              << *Retain << "\n");
147 
148   // We do not have to worry about tail calls/does not throw since
149   // retain/retainRV have the same properties.
150   Function *Decl = EP.get(ARCRuntimeEntryPointKind::RetainRV);
151   cast<CallInst>(Retain)->setCalledFunction(Decl);
152 
153   LLVM_DEBUG(dbgs() << "New: " << *Retain << "\n");
154   return true;
155 }
156 
157 /// Merge an autorelease with a retain into a fused call.
158 bool ObjCARCContract::contractAutorelease(Function &F, Instruction *Autorelease,
159                                           ARCInstKind Class) {
160   const Value *Arg = GetArgRCIdentityRoot(Autorelease);
161 
162   // Check that there are no instructions between the retain and the autorelease
163   // (such as an autorelease_pop) which may change the count.
164   DependenceKind DK = Class == ARCInstKind::AutoreleaseRV
165                           ? RetainAutoreleaseRVDep
166                           : RetainAutoreleaseDep;
167   auto *Retain = dyn_cast_or_null<CallInst>(
168       findSingleDependency(DK, Arg, Autorelease->getParent(), Autorelease, PA));
169 
170   if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
171       GetArgRCIdentityRoot(Retain) != Arg)
172     return false;
173 
174   Changed = true;
175   ++NumPeeps;
176 
177   LLVM_DEBUG(dbgs() << "    Fusing retain/autorelease!\n"
178                        "        Autorelease:"
179                     << *Autorelease
180                     << "\n"
181                        "        Retain: "
182                     << *Retain << "\n");
183 
184   Function *Decl = EP.get(Class == ARCInstKind::AutoreleaseRV
185                               ? ARCRuntimeEntryPointKind::RetainAutoreleaseRV
186                               : ARCRuntimeEntryPointKind::RetainAutorelease);
187   Retain->setCalledFunction(Decl);
188 
189   LLVM_DEBUG(dbgs() << "        New RetainAutorelease: " << *Retain << "\n");
190 
191   EraseInstruction(Autorelease);
192   return true;
193 }
194 
195 static StoreInst *findSafeStoreForStoreStrongContraction(LoadInst *Load,
196                                                          Instruction *Release,
197                                                          ProvenanceAnalysis &PA,
198                                                          AliasAnalysis *AA) {
199   StoreInst *Store = nullptr;
200   bool SawRelease = false;
201 
202   // Get the location associated with Load.
203   MemoryLocation Loc = MemoryLocation::get(Load);
204   auto *LocPtr = Loc.Ptr->stripPointerCasts();
205 
206   // Walk down to find the store and the release, which may be in either order.
207   for (auto I = std::next(BasicBlock::iterator(Load)),
208             E = Load->getParent()->end();
209        I != E; ++I) {
210     // If we found the store we were looking for and saw the release,
211     // break. There is no more work to be done.
212     if (Store && SawRelease)
213       break;
214 
215     // Now we know that we have not seen either the store or the release. If I
216     // is the release, mark that we saw the release and continue.
217     Instruction *Inst = &*I;
218     if (Inst == Release) {
219       SawRelease = true;
220       continue;
221     }
222 
223     // Otherwise, we check if Inst is a "good" store. Grab the instruction class
224     // of Inst.
225     ARCInstKind Class = GetBasicARCInstKind(Inst);
226 
227     // If Inst is an unrelated retain, we don't care about it.
228     //
229     // TODO: This is one area where the optimization could be made more
230     // aggressive.
231     if (IsRetain(Class))
232       continue;
233 
234     // If we have seen the store, but not the release...
235     if (Store) {
236       // We need to make sure that it is safe to move the release from its
237       // current position to the store. This implies proving that any
238       // instruction in between Store and the Release conservatively can not use
239       // the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
240       // continue...
241       if (!CanUse(Inst, Load, PA, Class)) {
242         continue;
243       }
244 
245       // Otherwise, be conservative and return nullptr.
246       return nullptr;
247     }
248 
249     // Ok, now we know we have not seen a store yet. See if Inst can write to
250     // our load location, if it can not, just ignore the instruction.
251     if (!isModSet(AA->getModRefInfo(Inst, Loc)))
252       continue;
253 
254     Store = dyn_cast<StoreInst>(Inst);
255 
256     // If Inst can, then check if Inst is a simple store. If Inst is not a
257     // store or a store that is not simple, then we have some we do not
258     // understand writing to this memory implying we can not move the load
259     // over the write to any subsequent store that we may find.
260     if (!Store || !Store->isSimple())
261       return nullptr;
262 
263     // Then make sure that the pointer we are storing to is Ptr. If so, we
264     // found our Store!
265     if (Store->getPointerOperand()->stripPointerCasts() == LocPtr)
266       continue;
267 
268     // Otherwise, we have an unknown store to some other ptr that clobbers
269     // Loc.Ptr. Bail!
270     return nullptr;
271   }
272 
273   // If we did not find the store or did not see the release, fail.
274   if (!Store || !SawRelease)
275     return nullptr;
276 
277   // We succeeded!
278   return Store;
279 }
280 
281 static Instruction *
282 findRetainForStoreStrongContraction(Value *New, StoreInst *Store,
283                                     Instruction *Release,
284                                     ProvenanceAnalysis &PA) {
285   // Walk up from the Store to find the retain.
286   BasicBlock::iterator I = Store->getIterator();
287   BasicBlock::iterator Begin = Store->getParent()->begin();
288   while (I != Begin && GetBasicARCInstKind(&*I) != ARCInstKind::Retain) {
289     Instruction *Inst = &*I;
290 
291     // It is only safe to move the retain to the store if we can prove
292     // conservatively that nothing besides the release can decrement reference
293     // counts in between the retain and the store.
294     if (CanDecrementRefCount(Inst, New, PA) && Inst != Release)
295       return nullptr;
296     --I;
297   }
298   Instruction *Retain = &*I;
299   if (GetBasicARCInstKind(Retain) != ARCInstKind::Retain)
300     return nullptr;
301   if (GetArgRCIdentityRoot(Retain) != New)
302     return nullptr;
303   return Retain;
304 }
305 
306 /// Create a call instruction with the correct funclet token. Should be used
307 /// instead of calling CallInst::Create directly.
308 static CallInst *
309 createCallInst(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
310                const Twine &NameStr, Instruction *InsertBefore,
311                const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
312   SmallVector<OperandBundleDef, 1> OpBundles;
313   if (!BlockColors.empty()) {
314     const ColorVector &CV = BlockColors.find(InsertBefore->getParent())->second;
315     assert(CV.size() == 1 && "non-unique color for block!");
316     Instruction *EHPad = CV.front()->getFirstNonPHI();
317     if (EHPad->isEHPad())
318       OpBundles.emplace_back("funclet", EHPad);
319   }
320 
321   return CallInst::Create(FTy, Func, Args, OpBundles, NameStr, InsertBefore);
322 }
323 
324 static CallInst *
325 createCallInst(FunctionCallee Func, ArrayRef<Value *> Args, const Twine &NameStr,
326                Instruction *InsertBefore,
327                const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
328   return createCallInst(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
329                         InsertBefore, BlockColors);
330 }
331 
332 /// Attempt to merge an objc_release with a store, load, and objc_retain to form
333 /// an objc_storeStrong. An objc_storeStrong:
334 ///
335 ///   objc_storeStrong(i8** %old_ptr, i8* new_value)
336 ///
337 /// is equivalent to the following IR sequence:
338 ///
339 ///   ; Load old value.
340 ///   %old_value = load i8** %old_ptr               (1)
341 ///
342 ///   ; Increment the new value and then release the old value. This must occur
343 ///   ; in order in case old_value releases new_value in its destructor causing
344 ///   ; us to potentially have a dangling ptr.
345 ///   tail call i8* @objc_retain(i8* %new_value)    (2)
346 ///   tail call void @objc_release(i8* %old_value)  (3)
347 ///
348 ///   ; Store the new_value into old_ptr
349 ///   store i8* %new_value, i8** %old_ptr           (4)
350 ///
351 /// The safety of this optimization is based around the following
352 /// considerations:
353 ///
354 ///  1. We are forming the store strong at the store. Thus to perform this
355 ///     optimization it must be safe to move the retain, load, and release to
356 ///     (4).
357 ///  2. We need to make sure that any re-orderings of (1), (2), (3), (4) are
358 ///     safe.
359 void ObjCARCContract::tryToContractReleaseIntoStoreStrong(
360     Instruction *Release, inst_iterator &Iter,
361     const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
362   // See if we are releasing something that we just loaded.
363   auto *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
364   if (!Load || !Load->isSimple())
365     return;
366 
367   // For now, require everything to be in one basic block.
368   BasicBlock *BB = Release->getParent();
369   if (Load->getParent() != BB)
370     return;
371 
372   // First scan down the BB from Load, looking for a store of the RCIdentityRoot
373   // of Load's
374   StoreInst *Store =
375       findSafeStoreForStoreStrongContraction(Load, Release, PA, AA);
376   // If we fail, bail.
377   if (!Store)
378     return;
379 
380   // Then find what new_value's RCIdentity Root is.
381   Value *New = GetRCIdentityRoot(Store->getValueOperand());
382 
383   // Then walk up the BB and look for a retain on New without any intervening
384   // instructions which conservatively might decrement ref counts.
385   Instruction *Retain =
386       findRetainForStoreStrongContraction(New, Store, Release, PA);
387 
388   // If we fail, bail.
389   if (!Retain)
390     return;
391 
392   Changed = true;
393   ++NumStoreStrongs;
394 
395   LLVM_DEBUG(
396       llvm::dbgs() << "    Contracting retain, release into objc_storeStrong.\n"
397                    << "        Old:\n"
398                    << "            Store:   " << *Store << "\n"
399                    << "            Release: " << *Release << "\n"
400                    << "            Retain:  " << *Retain << "\n"
401                    << "            Load:    " << *Load << "\n");
402 
403   LLVMContext &C = Release->getContext();
404   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
405   Type *I8XX = PointerType::getUnqual(I8X);
406 
407   Value *Args[] = { Load->getPointerOperand(), New };
408   if (Args[0]->getType() != I8XX)
409     Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
410   if (Args[1]->getType() != I8X)
411     Args[1] = new BitCastInst(Args[1], I8X, "", Store);
412   Function *Decl = EP.get(ARCRuntimeEntryPointKind::StoreStrong);
413   CallInst *StoreStrong = createCallInst(Decl, Args, "", Store, BlockColors);
414   StoreStrong->setDoesNotThrow();
415   StoreStrong->setDebugLoc(Store->getDebugLoc());
416 
417   // We can't set the tail flag yet, because we haven't yet determined
418   // whether there are any escaping allocas. Remember this call, so that
419   // we can set the tail flag once we know it's safe.
420   StoreStrongCalls.insert(StoreStrong);
421 
422   LLVM_DEBUG(llvm::dbgs() << "        New Store Strong: " << *StoreStrong
423                           << "\n");
424 
425   if (&*Iter == Retain) ++Iter;
426   if (&*Iter == Store) ++Iter;
427   Store->eraseFromParent();
428   Release->eraseFromParent();
429   EraseInstruction(Retain);
430   if (Load->use_empty())
431     Load->eraseFromParent();
432 }
433 
434 bool ObjCARCContract::tryToPeepholeInstruction(
435     Function &F, Instruction *Inst, inst_iterator &Iter,
436     bool &TailOkForStoreStrongs,
437     const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
438   // Only these library routines return their argument. In particular,
439   // objc_retainBlock does not necessarily return its argument.
440   ARCInstKind Class = GetBasicARCInstKind(Inst);
441   switch (Class) {
442   case ARCInstKind::FusedRetainAutorelease:
443   case ARCInstKind::FusedRetainAutoreleaseRV:
444     return false;
445   case ARCInstKind::Autorelease:
446   case ARCInstKind::AutoreleaseRV:
447     return contractAutorelease(F, Inst, Class);
448   case ARCInstKind::Retain:
449     // Attempt to convert retains to retainrvs if they are next to function
450     // calls.
451     if (!optimizeRetainCall(F, Inst))
452       return false;
453     // If we succeed in our optimization, fall through.
454     LLVM_FALLTHROUGH;
455   case ARCInstKind::RetainRV:
456   case ARCInstKind::ClaimRV: {
457     // If we're compiling for a target which needs a special inline-asm
458     // marker to do the return value optimization, insert it now.
459     if (!RVInstMarker)
460       return false;
461     BasicBlock::iterator BBI = Inst->getIterator();
462     BasicBlock *InstParent = Inst->getParent();
463 
464     // Step up to see if the call immediately precedes the RV call.
465     // If it's an invoke, we have to cross a block boundary. And we have
466     // to carefully dodge no-op instructions.
467     do {
468       if (BBI == InstParent->begin()) {
469         BasicBlock *Pred = InstParent->getSinglePredecessor();
470         if (!Pred)
471           goto decline_rv_optimization;
472         BBI = Pred->getTerminator()->getIterator();
473         break;
474       }
475       --BBI;
476     } while (IsNoopInstruction(&*BBI));
477 
478     if (&*BBI == GetArgRCIdentityRoot(Inst)) {
479       LLVM_DEBUG(dbgs() << "Adding inline asm marker for the return value "
480                            "optimization.\n");
481       Changed = true;
482       InlineAsm *IA =
483           InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
484                                            /*isVarArg=*/false),
485                          RVInstMarker->getString(),
486                          /*Constraints=*/"", /*hasSideEffects=*/true);
487 
488       createCallInst(IA, None, "", Inst, BlockColors);
489     }
490   decline_rv_optimization:
491     return false;
492   }
493   case ARCInstKind::InitWeak: {
494     // objc_initWeak(p, null) => *p = null
495     CallInst *CI = cast<CallInst>(Inst);
496     if (IsNullOrUndef(CI->getArgOperand(1))) {
497       Value *Null = ConstantPointerNull::get(cast<PointerType>(CI->getType()));
498       Changed = true;
499       new StoreInst(Null, CI->getArgOperand(0), CI);
500 
501       LLVM_DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
502                         << "                 New = " << *Null << "\n");
503 
504       CI->replaceAllUsesWith(Null);
505       CI->eraseFromParent();
506     }
507     return true;
508   }
509   case ARCInstKind::Release:
510     // Try to form an objc store strong from our release. If we fail, there is
511     // nothing further to do below, so continue.
512     tryToContractReleaseIntoStoreStrong(Inst, Iter, BlockColors);
513     return true;
514   case ARCInstKind::User:
515     // Be conservative if the function has any alloca instructions.
516     // Technically we only care about escaping alloca instructions,
517     // but this is sufficient to handle some interesting cases.
518     if (isa<AllocaInst>(Inst))
519       TailOkForStoreStrongs = false;
520     return true;
521   case ARCInstKind::IntrinsicUser:
522     // Remove calls to @llvm.objc.clang.arc.use(...).
523     Changed = true;
524     Inst->eraseFromParent();
525     return true;
526   default:
527     return true;
528   }
529 }
530 
531 //===----------------------------------------------------------------------===//
532 //                              Top Level Driver
533 //===----------------------------------------------------------------------===//
534 
535 bool ObjCARCContract::init(Module &M) {
536   // If nothing in the Module uses ARC, don't do anything.
537   Run = ModuleHasARC(M);
538   if (!Run)
539     return false;
540 
541   EP.init(&M);
542 
543   // Initialize RVInstMarker.
544   const char *MarkerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
545   RVInstMarker = dyn_cast_or_null<MDString>(M.getModuleFlag(MarkerKey));
546 
547   return false;
548 }
549 
550 bool ObjCARCContract::run(Function &F, AAResults *A, DominatorTree *D) {
551   if (!EnableARCOpts)
552     return false;
553 
554   // If nothing in the Module uses ARC, don't do anything.
555   if (!Run)
556     return false;
557 
558   Changed = false;
559   AA = A;
560   DT = D;
561   PA.setAA(A);
562 
563   DenseMap<BasicBlock *, ColorVector> BlockColors;
564   if (F.hasPersonalityFn() &&
565       isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
566     BlockColors = colorEHFunclets(F);
567 
568   LLVM_DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
569 
570   // Track whether it's ok to mark objc_storeStrong calls with the "tail"
571   // keyword. Be conservative if the function has variadic arguments.
572   // It seems that functions which "return twice" are also unsafe for the
573   // "tail" argument, because they are setjmp, which could need to
574   // return to an earlier stack state.
575   bool TailOkForStoreStrongs =
576       !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
577 
578   // For ObjC library calls which return their argument, replace uses of the
579   // argument with uses of the call return value, if it dominates the use. This
580   // reduces register pressure.
581   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
582     Instruction *Inst = &*I++;
583 
584     LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
585 
586     // First try to peephole Inst. If there is nothing further we can do in
587     // terms of undoing objc-arc-expand, process the next inst.
588     if (tryToPeepholeInstruction(F, Inst, I, TailOkForStoreStrongs,
589                                  BlockColors))
590       continue;
591 
592     // Otherwise, try to undo objc-arc-expand.
593 
594     // Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
595     // and such; to do the replacement, the argument must have type i8*.
596 
597     // Function for replacing uses of Arg dominated by Inst.
598     auto ReplaceArgUses = [Inst, this](Value *Arg) {
599       // If we're compiling bugpointed code, don't get in trouble.
600       if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
601         return;
602 
603       // Look through the uses of the pointer.
604       for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
605            UI != UE; ) {
606         // Increment UI now, because we may unlink its element.
607         Use &U = *UI++;
608         unsigned OperandNo = U.getOperandNo();
609 
610         // If the call's return value dominates a use of the call's argument
611         // value, rewrite the use to use the return value. We check for
612         // reachability here because an unreachable call is considered to
613         // trivially dominate itself, which would lead us to rewriting its
614         // argument in terms of its return value, which would lead to
615         // infinite loops in GetArgRCIdentityRoot.
616         if (!DT->isReachableFromEntry(U) || !DT->dominates(Inst, U))
617           continue;
618 
619         Changed = true;
620         Instruction *Replacement = Inst;
621         Type *UseTy = U.get()->getType();
622         if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
623           // For PHI nodes, insert the bitcast in the predecessor block.
624           unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
625           BasicBlock *IncomingBB = PHI->getIncomingBlock(ValNo);
626           if (Replacement->getType() != UseTy) {
627             // A catchswitch is both a pad and a terminator, meaning a basic
628             // block with a catchswitch has no insertion point. Keep going up
629             // the dominator tree until we find a non-catchswitch.
630             BasicBlock *InsertBB = IncomingBB;
631             while (isa<CatchSwitchInst>(InsertBB->getFirstNonPHI())) {
632               InsertBB = DT->getNode(InsertBB)->getIDom()->getBlock();
633             }
634 
635             assert(DT->dominates(Inst, &InsertBB->back()) &&
636                    "Invalid insertion point for bitcast");
637             Replacement =
638                 new BitCastInst(Replacement, UseTy, "", &InsertBB->back());
639           }
640 
641           // While we're here, rewrite all edges for this PHI, rather
642           // than just one use at a time, to minimize the number of
643           // bitcasts we emit.
644           for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
645             if (PHI->getIncomingBlock(i) == IncomingBB) {
646               // Keep the UI iterator valid.
647               if (UI != UE &&
648                   &PHI->getOperandUse(
649                       PHINode::getOperandNumForIncomingValue(i)) == &*UI)
650                 ++UI;
651               PHI->setIncomingValue(i, Replacement);
652             }
653         } else {
654           if (Replacement->getType() != UseTy)
655             Replacement = new BitCastInst(Replacement, UseTy, "",
656                                           cast<Instruction>(U.getUser()));
657           U.set(Replacement);
658         }
659       }
660     };
661 
662     Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
663     Value *OrigArg = Arg;
664 
665     // TODO: Change this to a do-while.
666     for (;;) {
667       ReplaceArgUses(Arg);
668 
669       // If Arg is a no-op casted pointer, strip one level of casts and iterate.
670       if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
671         Arg = BI->getOperand(0);
672       else if (isa<GEPOperator>(Arg) &&
673                cast<GEPOperator>(Arg)->hasAllZeroIndices())
674         Arg = cast<GEPOperator>(Arg)->getPointerOperand();
675       else if (isa<GlobalAlias>(Arg) &&
676                !cast<GlobalAlias>(Arg)->isInterposable())
677         Arg = cast<GlobalAlias>(Arg)->getAliasee();
678       else {
679         // If Arg is a PHI node, get PHIs that are equivalent to it and replace
680         // their uses.
681         if (PHINode *PN = dyn_cast<PHINode>(Arg)) {
682           SmallVector<Value *, 1> PHIList;
683           getEquivalentPHIs(*PN, PHIList);
684           for (Value *PHI : PHIList)
685             ReplaceArgUses(PHI);
686         }
687         break;
688       }
689     }
690 
691     // Replace bitcast users of Arg that are dominated by Inst.
692     SmallVector<BitCastInst *, 2> BitCastUsers;
693 
694     // Add all bitcast users of the function argument first.
695     for (User *U : OrigArg->users())
696       if (auto *BC = dyn_cast<BitCastInst>(U))
697         BitCastUsers.push_back(BC);
698 
699     // Replace the bitcasts with the call return. Iterate until list is empty.
700     while (!BitCastUsers.empty()) {
701       auto *BC = BitCastUsers.pop_back_val();
702       for (User *U : BC->users())
703         if (auto *B = dyn_cast<BitCastInst>(U))
704           BitCastUsers.push_back(B);
705 
706       ReplaceArgUses(BC);
707     }
708   }
709 
710   // If this function has no escaping allocas or suspicious vararg usage,
711   // objc_storeStrong calls can be marked with the "tail" keyword.
712   if (TailOkForStoreStrongs)
713     for (CallInst *CI : StoreStrongCalls)
714       CI->setTailCall();
715   StoreStrongCalls.clear();
716 
717   return Changed;
718 }
719 
720 //===----------------------------------------------------------------------===//
721 //                             Misc Pass Manager
722 //===----------------------------------------------------------------------===//
723 
724 char ObjCARCContractLegacyPass::ID = 0;
725 INITIALIZE_PASS_BEGIN(ObjCARCContractLegacyPass, "objc-arc-contract",
726                       "ObjC ARC contraction", false, false)
727 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
728 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
729 INITIALIZE_PASS_END(ObjCARCContractLegacyPass, "objc-arc-contract",
730                     "ObjC ARC contraction", false, false)
731 
732 void ObjCARCContractLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
733   AU.addRequired<AAResultsWrapperPass>();
734   AU.addRequired<DominatorTreeWrapperPass>();
735   AU.setPreservesCFG();
736 }
737 
738 Pass *llvm::createObjCARCContractPass() {
739   return new ObjCARCContractLegacyPass();
740 }
741 
742 bool ObjCARCContractLegacyPass::doInitialization(Module &M) {
743   return OCARCC.init(M);
744 }
745 
746 bool ObjCARCContractLegacyPass::runOnFunction(Function &F) {
747   auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
748   auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
749   return OCARCC.run(F, AA, DT);
750 }
751 
752 PreservedAnalyses ObjCARCContractPass::run(Module &M,
753                                            ModuleAnalysisManager &AM) {
754   ObjCARCContract OCAC;
755   OCAC.init(M);
756 
757   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
758   bool Changed = false;
759   for (Function &F : M) {
760     if (F.isDeclaration())
761       continue;
762     Changed |= OCAC.run(F, &FAM.getResult<AAManager>(F),
763                         &FAM.getResult<DominatorTreeAnalysis>(F));
764   }
765   if (Changed) {
766     PreservedAnalyses PA;
767     PA.preserveSet<CFGAnalyses>();
768     return PA;
769   }
770   return PreservedAnalyses::all();
771 }
772