blob: 19fcd001f8fce05cd6f6780f1cdf7ecd092971bf [file] [log] [blame]
Michael Gottesman1e29ca12013-01-29 05:07:18 +00001//===- ObjCARCContract.cpp - ObjC ARC Optimization ------------------------===//
Michael Gottesman778138e2013-01-29 03:03:03 +00002//
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/// \file
10/// This file defines late ObjC ARC optimizations. ARC stands for Automatic
11/// Reference Counting and is a system for managing reference counts for objects
12/// in Objective C.
13///
Michael Gottesman697d8b92013-02-07 04:12:57 +000014/// This specific file mainly deals with ``contracting'' multiple lower level
15/// operations into singular higher level operations through pattern matching.
16///
Michael Gottesman778138e2013-01-29 03:03:03 +000017/// WARNING: This file knows about certain library functions. It recognizes them
18/// by name, and hardwires knowledge of their semantics.
19///
20/// WARNING: This file knows about how certain Objective-C library functions are
21/// used. Naive LLVM IR transformations which would otherwise be
22/// behavior-preserving may break these assumptions.
23///
24//===----------------------------------------------------------------------===//
25
26// TODO: ObjCARCContract could insert PHI nodes when uses aren't
27// dominated by single calls.
28
Michael Gottesman778138e2013-01-29 03:03:03 +000029#include "ObjCARC.h"
Michael Gottesman0b912b22013-07-06 01:39:26 +000030#include "ARCRuntimeEntryPoints.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000031#include "DependencyAnalysis.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000032#include "ProvenanceAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000033#include "llvm/ADT/Statistic.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000034#include "llvm/IR/Dominators.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000035#include "llvm/IR/InlineAsm.h"
36#include "llvm/IR/Operator.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000037#include "llvm/Support/Debug.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000038
39using namespace llvm;
40using namespace llvm::objcarc;
41
Chandler Carruth964daaa2014-04-22 02:55:47 +000042#define DEBUG_TYPE "objc-arc-contract"
43
Michael Gottesman778138e2013-01-29 03:03:03 +000044STATISTIC(NumPeeps, "Number of calls peephole-optimized");
45STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
46
Michael Gottesman56bd6a02015-02-19 00:42:27 +000047//===----------------------------------------------------------------------===//
48// Declarations
49//===----------------------------------------------------------------------===//
50
Michael Gottesman778138e2013-01-29 03:03:03 +000051namespace {
52 /// \brief Late ARC optimizations
53 ///
54 /// These change the IR in a way that makes it difficult to be analyzed by
55 /// ObjCARCOpt, so it's run late.
56 class ObjCARCContract : public FunctionPass {
57 bool Changed;
58 AliasAnalysis *AA;
59 DominatorTree *DT;
60 ProvenanceAnalysis PA;
Michael Gottesman0b912b22013-07-06 01:39:26 +000061 ARCRuntimeEntryPoints EP;
Michael Gottesman778138e2013-01-29 03:03:03 +000062
63 /// A flag indicating whether this optimization pass should run.
64 bool Run;
65
Michael Gottesman778138e2013-01-29 03:03:03 +000066 /// The inline asm string to insert between calls and RetainRV calls to make
67 /// the optimization work on targets which need it.
68 const MDString *RetainRVMarker;
69
70 /// The set of inserted objc_storeStrong calls. If at the end of walking the
71 /// function we have found no alloca instructions, these calls can be marked
72 /// "tail".
73 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
74
Michael Gottesman18279732015-02-19 00:42:30 +000075 /// Returns true if we eliminated Inst.
76 bool tryToPeepholeInstruction(Function &F, Instruction *Inst,
77 inst_iterator &Iter,
78 SmallPtrSetImpl<Instruction *> &DepInsts,
79 SmallPtrSetImpl<const BasicBlock *> &Visited,
80 bool &TailOkForStoreStrong);
81
Michael Gottesman56bd6a02015-02-19 00:42:27 +000082 bool optimizeRetainCall(Function &F, Instruction *Retain);
Michael Gottesman214ca902013-04-29 06:53:53 +000083
Michael Gottesman56bd6a02015-02-19 00:42:27 +000084 bool
85 contractAutorelease(Function &F, Instruction *Autorelease,
86 InstructionClass Class,
87 SmallPtrSetImpl<Instruction *> &DependingInstructions,
88 SmallPtrSetImpl<const BasicBlock *> &Visited);
Michael Gottesman778138e2013-01-29 03:03:03 +000089
Michael Gottesmandfa3e4b2015-02-19 00:42:34 +000090 void tryToContractReleaseIntoStoreStrong(Instruction *Release,
91 inst_iterator &Iter);
Michael Gottesman778138e2013-01-29 03:03:03 +000092
Craig Topper3e4c6972014-03-05 09:10:37 +000093 void getAnalysisUsage(AnalysisUsage &AU) const override;
94 bool doInitialization(Module &M) override;
95 bool runOnFunction(Function &F) override;
Michael Gottesman778138e2013-01-29 03:03:03 +000096
97 public:
98 static char ID;
99 ObjCARCContract() : FunctionPass(ID) {
100 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
101 }
102 };
103}
104
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000105//===----------------------------------------------------------------------===//
106// Implementation
107//===----------------------------------------------------------------------===//
Michael Gottesman778138e2013-01-29 03:03:03 +0000108
Michael Gottesman214ca902013-04-29 06:53:53 +0000109/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
110/// return value. We do this late so we do not disrupt the dataflow analysis in
111/// ObjCARCOpt.
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000112bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000113 ImmutableCallSite CS(GetArgRCIdentityRoot(Retain));
Michael Gottesman214ca902013-04-29 06:53:53 +0000114 const Instruction *Call = CS.getInstruction();
115 if (!Call)
116 return false;
117 if (Call->getParent() != Retain->getParent())
118 return false;
119
120 // Check that the call is next to the retain.
121 BasicBlock::const_iterator I = Call;
122 ++I;
123 while (IsNoopInstruction(I)) ++I;
124 if (&*I != Retain)
125 return false;
126
127 // Turn it to an objc_retainAutoreleasedReturnValue.
128 Changed = true;
129 ++NumPeeps;
130
131 DEBUG(dbgs() << "Transforming objc_retain => "
132 "objc_retainAutoreleasedReturnValue since the operand is a "
133 "return value.\nOld: "<< *Retain << "\n");
134
135 // We do not have to worry about tail calls/does not throw since
136 // retain/retainRV have the same properties.
Michael Gottesman0b912b22013-07-06 01:39:26 +0000137 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_RetainRV);
138 cast<CallInst>(Retain)->setCalledFunction(Decl);
Michael Gottesman214ca902013-04-29 06:53:53 +0000139
140 DEBUG(dbgs() << "New: " << *Retain << "\n");
141 return true;
142}
143
Michael Gottesman778138e2013-01-29 03:03:03 +0000144/// Merge an autorelease with a retain into a fused call.
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000145bool ObjCARCContract::contractAutorelease(
146 Function &F, Instruction *Autorelease, InstructionClass Class,
147 SmallPtrSetImpl<Instruction *> &DependingInstructions,
148 SmallPtrSetImpl<const BasicBlock *> &Visited) {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000149 const Value *Arg = GetArgRCIdentityRoot(Autorelease);
Michael Gottesman778138e2013-01-29 03:03:03 +0000150
151 // Check that there are no instructions between the retain and the autorelease
152 // (such as an autorelease_pop) which may change the count.
Craig Topperf40110f2014-04-25 05:29:35 +0000153 CallInst *Retain = nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000154 if (Class == IC_AutoreleaseRV)
155 FindDependencies(RetainAutoreleaseRVDep, Arg,
156 Autorelease->getParent(), Autorelease,
157 DependingInstructions, Visited, PA);
158 else
159 FindDependencies(RetainAutoreleaseDep, Arg,
160 Autorelease->getParent(), Autorelease,
161 DependingInstructions, Visited, PA);
162
163 Visited.clear();
164 if (DependingInstructions.size() != 1) {
165 DependingInstructions.clear();
166 return false;
167 }
168
169 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
170 DependingInstructions.clear();
171
172 if (!Retain ||
173 GetBasicInstructionClass(Retain) != IC_Retain ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000174 GetArgRCIdentityRoot(Retain) != Arg)
Michael Gottesman778138e2013-01-29 03:03:03 +0000175 return false;
176
177 Changed = true;
178 ++NumPeeps;
179
Michael Gottesman18279732015-02-19 00:42:30 +0000180 DEBUG(dbgs() << " Fusing retain/autorelease!\n"
181 " Autorelease:" << *Autorelease << "\n"
182 " Retain: " << *Retain << "\n");
Michael Gottesman778138e2013-01-29 03:03:03 +0000183
Michael Gottesman0b912b22013-07-06 01:39:26 +0000184 Constant *Decl = EP.get(Class == IC_AutoreleaseRV ?
185 ARCRuntimeEntryPoints::EPT_RetainAutoreleaseRV :
186 ARCRuntimeEntryPoints::EPT_RetainAutorelease);
187 Retain->setCalledFunction(Decl);
Michael Gottesman778138e2013-01-29 03:03:03 +0000188
Michael Gottesman18279732015-02-19 00:42:30 +0000189 DEBUG(dbgs() << " New RetainAutorelease: " << *Retain << "\n");
Michael Gottesman778138e2013-01-29 03:03:03 +0000190
191 EraseInstruction(Autorelease);
192 return true;
193}
194
195/// Attempt to merge an objc_release with a store, load, and objc_retain to form
196/// an objc_storeStrong. This can be a little tricky because the instructions
197/// don't always appear in order, and there may be unrelated intervening
198/// instructions.
Michael Gottesmandfa3e4b2015-02-19 00:42:34 +0000199void
200ObjCARCContract::
201tryToContractReleaseIntoStoreStrong(Instruction *Release, inst_iterator &Iter) {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000202 LoadInst *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
Michael Gottesman778138e2013-01-29 03:03:03 +0000203 if (!Load || !Load->isSimple()) return;
204
205 // For now, require everything to be in one basic block.
206 BasicBlock *BB = Release->getParent();
207 if (Load->getParent() != BB) return;
208
209 // Walk down to find the store and the release, which may be in either order.
210 BasicBlock::iterator I = Load, End = BB->end();
211 ++I;
212 AliasAnalysis::Location Loc = AA->getLocation(Load);
Craig Topperf40110f2014-04-25 05:29:35 +0000213 StoreInst *Store = nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000214 bool SawRelease = false;
215 for (; !Store || !SawRelease; ++I) {
216 if (I == End)
217 return;
218
219 Instruction *Inst = I;
220 if (Inst == Release) {
221 SawRelease = true;
222 continue;
223 }
224
225 InstructionClass Class = GetBasicInstructionClass(Inst);
226
227 // Unrelated retains are harmless.
228 if (IsRetain(Class))
229 continue;
230
231 if (Store) {
232 // The store is the point where we're going to put the objc_storeStrong,
233 // so make sure there are no uses after it.
234 if (CanUse(Inst, Load, PA, Class))
235 return;
236 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
237 // We are moving the load down to the store, so check for anything
238 // else which writes to the memory between the load and the store.
239 Store = dyn_cast<StoreInst>(Inst);
240 if (!Store || !Store->isSimple()) return;
241 if (Store->getPointerOperand() != Loc.Ptr) return;
242 }
243 }
244
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000245 Value *New = GetRCIdentityRoot(Store->getValueOperand());
Michael Gottesman778138e2013-01-29 03:03:03 +0000246
247 // Walk up to find the retain.
248 I = Store;
249 BasicBlock::iterator Begin = BB->begin();
250 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
251 --I;
252 Instruction *Retain = I;
253 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000254 if (GetArgRCIdentityRoot(Retain) != New) return;
Michael Gottesman778138e2013-01-29 03:03:03 +0000255
256 Changed = true;
257 ++NumStoreStrongs;
258
Michael Gottesman18279732015-02-19 00:42:30 +0000259 DEBUG(
260 llvm::dbgs() << " Contracting retain, release into objc_storeStrong.\n"
261 << " Old:\n"
262 << " Store: " << *Store << "\n"
263 << " Release: " << *Release << "\n"
264 << " Retain: " << *Retain << "\n"
265 << " Load: " << *Load << "\n");
266
Michael Gottesman778138e2013-01-29 03:03:03 +0000267 LLVMContext &C = Release->getContext();
268 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
269 Type *I8XX = PointerType::getUnqual(I8X);
270
271 Value *Args[] = { Load->getPointerOperand(), New };
272 if (Args[0]->getType() != I8XX)
273 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
274 if (Args[1]->getType() != I8X)
275 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
Michael Gottesman0b912b22013-07-06 01:39:26 +0000276 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_StoreStrong);
277 CallInst *StoreStrong = CallInst::Create(Decl, Args, "", Store);
Michael Gottesman778138e2013-01-29 03:03:03 +0000278 StoreStrong->setDoesNotThrow();
279 StoreStrong->setDebugLoc(Store->getDebugLoc());
280
281 // We can't set the tail flag yet, because we haven't yet determined
282 // whether there are any escaping allocas. Remember this call, so that
283 // we can set the tail flag once we know it's safe.
284 StoreStrongCalls.insert(StoreStrong);
285
Michael Gottesman18279732015-02-19 00:42:30 +0000286 DEBUG(llvm::dbgs() << " New Store Strong: " << *StoreStrong << "\n");
287
Michael Gottesman778138e2013-01-29 03:03:03 +0000288 if (&*Iter == Store) ++Iter;
289 Store->eraseFromParent();
290 Release->eraseFromParent();
291 EraseInstruction(Retain);
292 if (Load->use_empty())
293 Load->eraseFromParent();
294}
295
Michael Gottesman18279732015-02-19 00:42:30 +0000296bool ObjCARCContract::tryToPeepholeInstruction(
297 Function &F, Instruction *Inst, inst_iterator &Iter,
298 SmallPtrSetImpl<Instruction *> &DependingInsts,
299 SmallPtrSetImpl<const BasicBlock *> &Visited,
300 bool &TailOkForStoreStrongs) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000301 // Only these library routines return their argument. In particular,
302 // objc_retainBlock does not necessarily return its argument.
303 InstructionClass Class = GetBasicInstructionClass(Inst);
304 switch (Class) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000305 case IC_FusedRetainAutorelease:
306 case IC_FusedRetainAutoreleaseRV:
Michael Gottesman18279732015-02-19 00:42:30 +0000307 return false;
Michael Gottesman778138e2013-01-29 03:03:03 +0000308 case IC_Autorelease:
309 case IC_AutoreleaseRV:
Michael Gottesman18279732015-02-19 00:42:30 +0000310 return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
Michael Gottesman214ca902013-04-29 06:53:53 +0000311 case IC_Retain:
312 // Attempt to convert retains to retainrvs if they are next to function
313 // calls.
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000314 if (!optimizeRetainCall(F, Inst))
Michael Gottesman18279732015-02-19 00:42:30 +0000315 return false;
Michael Gottesman214ca902013-04-29 06:53:53 +0000316 // If we succeed in our optimization, fall through.
317 // FALLTHROUGH
Michael Gottesman778138e2013-01-29 03:03:03 +0000318 case IC_RetainRV: {
319 // If we're compiling for a target which needs a special inline-asm
320 // marker to do the retainAutoreleasedReturnValue optimization,
321 // insert it now.
322 if (!RetainRVMarker)
Michael Gottesman18279732015-02-19 00:42:30 +0000323 return false;
Michael Gottesman778138e2013-01-29 03:03:03 +0000324 BasicBlock::iterator BBI = Inst;
325 BasicBlock *InstParent = Inst->getParent();
326
327 // Step up to see if the call immediately precedes the RetainRV call.
328 // If it's an invoke, we have to cross a block boundary. And we have
329 // to carefully dodge no-op instructions.
330 do {
331 if (&*BBI == InstParent->begin()) {
332 BasicBlock *Pred = InstParent->getSinglePredecessor();
333 if (!Pred)
334 goto decline_rv_optimization;
335 BBI = Pred->getTerminator();
336 break;
337 }
338 --BBI;
Michael Gottesman65c24812013-03-25 09:27:43 +0000339 } while (IsNoopInstruction(BBI));
Michael Gottesman778138e2013-01-29 03:03:03 +0000340
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000341 if (&*BBI == GetArgRCIdentityRoot(Inst)) {
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000342 DEBUG(dbgs() << "Adding inline asm marker for "
Michael Gottesman778138e2013-01-29 03:03:03 +0000343 "retainAutoreleasedReturnValue optimization.\n");
344 Changed = true;
345 InlineAsm *IA =
346 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
347 /*isVarArg=*/false),
348 RetainRVMarker->getString(),
349 /*Constraints=*/"", /*hasSideEffects=*/true);
350 CallInst::Create(IA, "", Inst);
351 }
352 decline_rv_optimization:
Michael Gottesman18279732015-02-19 00:42:30 +0000353 return false;
Michael Gottesman778138e2013-01-29 03:03:03 +0000354 }
355 case IC_InitWeak: {
356 // objc_initWeak(p, null) => *p = null
357 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000358 if (IsNullOrUndef(CI->getArgOperand(1))) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000359 Value *Null =
360 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
361 Changed = true;
362 new StoreInst(Null, CI->getArgOperand(0), CI);
363
364 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
365 << " New = " << *Null << "\n");
366
367 CI->replaceAllUsesWith(Null);
368 CI->eraseFromParent();
369 }
Michael Gottesman18279732015-02-19 00:42:30 +0000370 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000371 }
372 case IC_Release:
Michael Gottesmandfa3e4b2015-02-19 00:42:34 +0000373 // Try to form an objc store strong from our release. If we fail, there is
374 // nothing further to do below, so continue.
375 tryToContractReleaseIntoStoreStrong(Inst, Iter);
Michael Gottesman18279732015-02-19 00:42:30 +0000376 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000377 case IC_User:
378 // Be conservative if the function has any alloca instructions.
379 // Technically we only care about escaping alloca instructions,
380 // but this is sufficient to handle some interesting cases.
381 if (isa<AllocaInst>(Inst))
382 TailOkForStoreStrongs = false;
Michael Gottesman18279732015-02-19 00:42:30 +0000383 return true;
John McCall20182ac2013-03-22 21:38:36 +0000384 case IC_IntrinsicUser:
385 // Remove calls to @clang.arc.use(...).
386 Inst->eraseFromParent();
Michael Gottesman18279732015-02-19 00:42:30 +0000387 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000388 default:
Michael Gottesman18279732015-02-19 00:42:30 +0000389 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000390 }
Michael Gottesman18279732015-02-19 00:42:30 +0000391}
Michael Gottesman778138e2013-01-29 03:03:03 +0000392
Michael Gottesman18279732015-02-19 00:42:30 +0000393//===----------------------------------------------------------------------===//
394// Top Level Driver
395//===----------------------------------------------------------------------===//
396
397bool ObjCARCContract::runOnFunction(Function &F) {
398 if (!EnableARCOpts)
399 return false;
400
401 // If nothing in the Module uses ARC, don't do anything.
402 if (!Run)
403 return false;
404
405 Changed = false;
406 AA = &getAnalysis<AliasAnalysis>();
407 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
408
409 PA.setAA(&getAnalysis<AliasAnalysis>());
410
411 DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
412
413 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
414 // keyword. Be conservative if the function has variadic arguments.
415 // It seems that functions which "return twice" are also unsafe for the
416 // "tail" argument, because they are setjmp, which could need to
417 // return to an earlier stack state.
418 bool TailOkForStoreStrongs =
419 !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
420
421 // For ObjC library calls which return their argument, replace uses of the
422 // argument with uses of the call return value, if it dominates the use. This
423 // reduces register pressure.
424 SmallPtrSet<Instruction *, 4> DependingInstructions;
425 SmallPtrSet<const BasicBlock *, 4> Visited;
426 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
427 Instruction *Inst = &*I++;
428
429 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
430
431 // First try to peephole Inst. If there is nothing further we can do in
432 // terms of undoing objc-arc-expand, process the next inst.
433 if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
434 TailOkForStoreStrongs))
435 continue;
436
437 // Otherwise, try to undo objc-arc-expand.
Michael Gottesman778138e2013-01-29 03:03:03 +0000438
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000439 // Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
Michael Gottesman778138e2013-01-29 03:03:03 +0000440 // and such; to do the replacement, the argument must have type i8*.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000441 Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
Michael Gottesman18279732015-02-19 00:42:30 +0000442
443 // TODO: Change this to a do-while.
Michael Gottesman778138e2013-01-29 03:03:03 +0000444 for (;;) {
445 // If we're compiling bugpointed code, don't get in trouble.
446 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
447 break;
448 // Look through the uses of the pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000449 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
Michael Gottesman778138e2013-01-29 03:03:03 +0000450 UI != UE; ) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000451 // Increment UI now, because we may unlink its element.
452 Use &U = *UI++;
453 unsigned OperandNo = U.getOperandNo();
Michael Gottesman778138e2013-01-29 03:03:03 +0000454
455 // If the call's return value dominates a use of the call's argument
456 // value, rewrite the use to use the return value. We check for
457 // reachability here because an unreachable call is considered to
458 // trivially dominate itself, which would lead us to rewriting its
459 // argument in terms of its return value, which would lead to
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000460 // infinite loops in GetArgRCIdentityRoot.
Michael Gottesman778138e2013-01-29 03:03:03 +0000461 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
462 Changed = true;
463 Instruction *Replacement = Inst;
464 Type *UseTy = U.get()->getType();
465 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
466 // For PHI nodes, insert the bitcast in the predecessor block.
467 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
468 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
469 if (Replacement->getType() != UseTy)
470 Replacement = new BitCastInst(Replacement, UseTy, "",
471 &BB->back());
472 // While we're here, rewrite all edges for this PHI, rather
473 // than just one use at a time, to minimize the number of
474 // bitcasts we emit.
475 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
476 if (PHI->getIncomingBlock(i) == BB) {
477 // Keep the UI iterator valid.
Duncan P. N. Exon Smithcb1c81a2014-03-18 22:32:43 +0000478 if (UI != UE &&
479 &PHI->getOperandUse(
480 PHINode::getOperandNumForIncomingValue(i)) == &*UI)
Michael Gottesman778138e2013-01-29 03:03:03 +0000481 ++UI;
482 PHI->setIncomingValue(i, Replacement);
483 }
484 } else {
485 if (Replacement->getType() != UseTy)
486 Replacement = new BitCastInst(Replacement, UseTy, "",
487 cast<Instruction>(U.getUser()));
488 U.set(Replacement);
489 }
490 }
491 }
492
493 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
494 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
495 Arg = BI->getOperand(0);
496 else if (isa<GEPOperator>(Arg) &&
497 cast<GEPOperator>(Arg)->hasAllZeroIndices())
498 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
499 else if (isa<GlobalAlias>(Arg) &&
500 !cast<GlobalAlias>(Arg)->mayBeOverridden())
501 Arg = cast<GlobalAlias>(Arg)->getAliasee();
502 else
503 break;
504 }
505 }
506
507 // If this function has no escaping allocas or suspicious vararg usage,
508 // objc_storeStrong calls can be marked with the "tail" keyword.
509 if (TailOkForStoreStrongs)
Craig Topper46276792014-08-24 23:23:06 +0000510 for (CallInst *CI : StoreStrongCalls)
511 CI->setTailCall();
Michael Gottesman778138e2013-01-29 03:03:03 +0000512 StoreStrongCalls.clear();
513
514 return Changed;
515}
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000516
517//===----------------------------------------------------------------------===//
518// Misc Pass Manager
519//===----------------------------------------------------------------------===//
520
521char ObjCARCContract::ID = 0;
522INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract",
523 "ObjC ARC contraction", false, false)
524INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
525INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
526INITIALIZE_PASS_END(ObjCARCContract, "objc-arc-contract",
527 "ObjC ARC contraction", false, false)
528
529void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
530 AU.addRequired<AliasAnalysis>();
531 AU.addRequired<DominatorTreeWrapperPass>();
532 AU.setPreservesCFG();
533}
534
535Pass *llvm::createObjCARCContractPass() { return new ObjCARCContract(); }
536
537bool ObjCARCContract::doInitialization(Module &M) {
538 // If nothing in the Module uses ARC, don't do anything.
539 Run = ModuleHasARC(M);
540 if (!Run)
541 return false;
542
543 EP.Initialize(&M);
544
545 // Initialize RetainRVMarker.
546 RetainRVMarker = nullptr;
547 if (NamedMDNode *NMD =
548 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
549 if (NMD->getNumOperands() == 1) {
550 const MDNode *N = NMD->getOperand(0);
551 if (N->getNumOperands() == 1)
552 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
553 RetainRVMarker = S;
554 }
555
556 return false;
557}