blob: 2a7039a96c57cd7c427d12111bc2579ae02e58fe [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 Gottesman56bd6a02015-02-19 00:42:27 +000090 void contractRelease(Instruction *Release, inst_iterator &Iter);
Michael Gottesman778138e2013-01-29 03:03:03 +000091
Craig Topper3e4c6972014-03-05 09:10:37 +000092 void getAnalysisUsage(AnalysisUsage &AU) const override;
93 bool doInitialization(Module &M) override;
94 bool runOnFunction(Function &F) override;
Michael Gottesman778138e2013-01-29 03:03:03 +000095
96 public:
97 static char ID;
98 ObjCARCContract() : FunctionPass(ID) {
99 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
100 }
101 };
102}
103
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000104//===----------------------------------------------------------------------===//
105// Implementation
106//===----------------------------------------------------------------------===//
Michael Gottesman778138e2013-01-29 03:03:03 +0000107
Michael Gottesman214ca902013-04-29 06:53:53 +0000108/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
109/// return value. We do this late so we do not disrupt the dataflow analysis in
110/// ObjCARCOpt.
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000111bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
Michael Gottesman214ca902013-04-29 06:53:53 +0000112 ImmutableCallSite CS(GetObjCArg(Retain));
113 const Instruction *Call = CS.getInstruction();
114 if (!Call)
115 return false;
116 if (Call->getParent() != Retain->getParent())
117 return false;
118
119 // Check that the call is next to the retain.
120 BasicBlock::const_iterator I = Call;
121 ++I;
122 while (IsNoopInstruction(I)) ++I;
123 if (&*I != Retain)
124 return false;
125
126 // Turn it to an objc_retainAutoreleasedReturnValue.
127 Changed = true;
128 ++NumPeeps;
129
130 DEBUG(dbgs() << "Transforming objc_retain => "
131 "objc_retainAutoreleasedReturnValue since the operand is a "
132 "return value.\nOld: "<< *Retain << "\n");
133
134 // We do not have to worry about tail calls/does not throw since
135 // retain/retainRV have the same properties.
Michael Gottesman0b912b22013-07-06 01:39:26 +0000136 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_RetainRV);
137 cast<CallInst>(Retain)->setCalledFunction(Decl);
Michael Gottesman214ca902013-04-29 06:53:53 +0000138
139 DEBUG(dbgs() << "New: " << *Retain << "\n");
140 return true;
141}
142
Michael Gottesman778138e2013-01-29 03:03:03 +0000143/// Merge an autorelease with a retain into a fused call.
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000144bool ObjCARCContract::contractAutorelease(
145 Function &F, Instruction *Autorelease, InstructionClass Class,
146 SmallPtrSetImpl<Instruction *> &DependingInstructions,
147 SmallPtrSetImpl<const BasicBlock *> &Visited) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000148 const Value *Arg = GetObjCArg(Autorelease);
149
150 // Check that there are no instructions between the retain and the autorelease
151 // (such as an autorelease_pop) which may change the count.
Craig Topperf40110f2014-04-25 05:29:35 +0000152 CallInst *Retain = nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000153 if (Class == IC_AutoreleaseRV)
154 FindDependencies(RetainAutoreleaseRVDep, Arg,
155 Autorelease->getParent(), Autorelease,
156 DependingInstructions, Visited, PA);
157 else
158 FindDependencies(RetainAutoreleaseDep, Arg,
159 Autorelease->getParent(), Autorelease,
160 DependingInstructions, Visited, PA);
161
162 Visited.clear();
163 if (DependingInstructions.size() != 1) {
164 DependingInstructions.clear();
165 return false;
166 }
167
168 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
169 DependingInstructions.clear();
170
171 if (!Retain ||
172 GetBasicInstructionClass(Retain) != IC_Retain ||
173 GetObjCArg(Retain) != Arg)
174 return false;
175
176 Changed = true;
177 ++NumPeeps;
178
Michael Gottesman18279732015-02-19 00:42:30 +0000179 DEBUG(dbgs() << " Fusing retain/autorelease!\n"
180 " Autorelease:" << *Autorelease << "\n"
181 " Retain: " << *Retain << "\n");
Michael Gottesman778138e2013-01-29 03:03:03 +0000182
Michael Gottesman0b912b22013-07-06 01:39:26 +0000183 Constant *Decl = EP.get(Class == IC_AutoreleaseRV ?
184 ARCRuntimeEntryPoints::EPT_RetainAutoreleaseRV :
185 ARCRuntimeEntryPoints::EPT_RetainAutorelease);
186 Retain->setCalledFunction(Decl);
Michael Gottesman778138e2013-01-29 03:03:03 +0000187
Michael Gottesman18279732015-02-19 00:42:30 +0000188 DEBUG(dbgs() << " New RetainAutorelease: " << *Retain << "\n");
Michael Gottesman778138e2013-01-29 03:03:03 +0000189
190 EraseInstruction(Autorelease);
191 return true;
192}
193
194/// Attempt to merge an objc_release with a store, load, and objc_retain to form
195/// an objc_storeStrong. This can be a little tricky because the instructions
196/// don't always appear in order, and there may be unrelated intervening
197/// instructions.
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000198void ObjCARCContract::contractRelease(Instruction *Release,
Michael Gottesman778138e2013-01-29 03:03:03 +0000199 inst_iterator &Iter) {
200 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
201 if (!Load || !Load->isSimple()) return;
202
203 // For now, require everything to be in one basic block.
204 BasicBlock *BB = Release->getParent();
205 if (Load->getParent() != BB) return;
206
207 // Walk down to find the store and the release, which may be in either order.
208 BasicBlock::iterator I = Load, End = BB->end();
209 ++I;
210 AliasAnalysis::Location Loc = AA->getLocation(Load);
Craig Topperf40110f2014-04-25 05:29:35 +0000211 StoreInst *Store = nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000212 bool SawRelease = false;
213 for (; !Store || !SawRelease; ++I) {
214 if (I == End)
215 return;
216
217 Instruction *Inst = I;
218 if (Inst == Release) {
219 SawRelease = true;
220 continue;
221 }
222
223 InstructionClass Class = GetBasicInstructionClass(Inst);
224
225 // Unrelated retains are harmless.
226 if (IsRetain(Class))
227 continue;
228
229 if (Store) {
230 // The store is the point where we're going to put the objc_storeStrong,
231 // so make sure there are no uses after it.
232 if (CanUse(Inst, Load, PA, Class))
233 return;
234 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
235 // We are moving the load down to the store, so check for anything
236 // else which writes to the memory between the load and the store.
237 Store = dyn_cast<StoreInst>(Inst);
238 if (!Store || !Store->isSimple()) return;
239 if (Store->getPointerOperand() != Loc.Ptr) return;
240 }
241 }
242
243 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
244
245 // Walk up to find the retain.
246 I = Store;
247 BasicBlock::iterator Begin = BB->begin();
248 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
249 --I;
250 Instruction *Retain = I;
251 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
252 if (GetObjCArg(Retain) != New) return;
253
254 Changed = true;
255 ++NumStoreStrongs;
256
Michael Gottesman18279732015-02-19 00:42:30 +0000257 DEBUG(
258 llvm::dbgs() << " Contracting retain, release into objc_storeStrong.\n"
259 << " Old:\n"
260 << " Store: " << *Store << "\n"
261 << " Release: " << *Release << "\n"
262 << " Retain: " << *Retain << "\n"
263 << " Load: " << *Load << "\n");
264
Michael Gottesman778138e2013-01-29 03:03:03 +0000265 LLVMContext &C = Release->getContext();
266 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
267 Type *I8XX = PointerType::getUnqual(I8X);
268
269 Value *Args[] = { Load->getPointerOperand(), New };
270 if (Args[0]->getType() != I8XX)
271 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
272 if (Args[1]->getType() != I8X)
273 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
Michael Gottesman0b912b22013-07-06 01:39:26 +0000274 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_StoreStrong);
275 CallInst *StoreStrong = CallInst::Create(Decl, Args, "", Store);
Michael Gottesman778138e2013-01-29 03:03:03 +0000276 StoreStrong->setDoesNotThrow();
277 StoreStrong->setDebugLoc(Store->getDebugLoc());
278
279 // We can't set the tail flag yet, because we haven't yet determined
280 // whether there are any escaping allocas. Remember this call, so that
281 // we can set the tail flag once we know it's safe.
282 StoreStrongCalls.insert(StoreStrong);
283
Michael Gottesman18279732015-02-19 00:42:30 +0000284 DEBUG(llvm::dbgs() << " New Store Strong: " << *StoreStrong << "\n");
285
Michael Gottesman778138e2013-01-29 03:03:03 +0000286 if (&*Iter == Store) ++Iter;
287 Store->eraseFromParent();
288 Release->eraseFromParent();
289 EraseInstruction(Retain);
290 if (Load->use_empty())
291 Load->eraseFromParent();
292}
293
Michael Gottesman18279732015-02-19 00:42:30 +0000294bool ObjCARCContract::tryToPeepholeInstruction(
295 Function &F, Instruction *Inst, inst_iterator &Iter,
296 SmallPtrSetImpl<Instruction *> &DependingInsts,
297 SmallPtrSetImpl<const BasicBlock *> &Visited,
298 bool &TailOkForStoreStrongs) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000299 // Only these library routines return their argument. In particular,
300 // objc_retainBlock does not necessarily return its argument.
301 InstructionClass Class = GetBasicInstructionClass(Inst);
302 switch (Class) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000303 case IC_FusedRetainAutorelease:
304 case IC_FusedRetainAutoreleaseRV:
Michael Gottesman18279732015-02-19 00:42:30 +0000305 return false;
Michael Gottesman778138e2013-01-29 03:03:03 +0000306 case IC_Autorelease:
307 case IC_AutoreleaseRV:
Michael Gottesman18279732015-02-19 00:42:30 +0000308 return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
Michael Gottesman214ca902013-04-29 06:53:53 +0000309 case IC_Retain:
310 // Attempt to convert retains to retainrvs if they are next to function
311 // calls.
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000312 if (!optimizeRetainCall(F, Inst))
Michael Gottesman18279732015-02-19 00:42:30 +0000313 return false;
Michael Gottesman214ca902013-04-29 06:53:53 +0000314 // If we succeed in our optimization, fall through.
315 // FALLTHROUGH
Michael Gottesman778138e2013-01-29 03:03:03 +0000316 case IC_RetainRV: {
317 // If we're compiling for a target which needs a special inline-asm
318 // marker to do the retainAutoreleasedReturnValue optimization,
319 // insert it now.
320 if (!RetainRVMarker)
Michael Gottesman18279732015-02-19 00:42:30 +0000321 return false;
Michael Gottesman778138e2013-01-29 03:03:03 +0000322 BasicBlock::iterator BBI = Inst;
323 BasicBlock *InstParent = Inst->getParent();
324
325 // Step up to see if the call immediately precedes the RetainRV call.
326 // If it's an invoke, we have to cross a block boundary. And we have
327 // to carefully dodge no-op instructions.
328 do {
329 if (&*BBI == InstParent->begin()) {
330 BasicBlock *Pred = InstParent->getSinglePredecessor();
331 if (!Pred)
332 goto decline_rv_optimization;
333 BBI = Pred->getTerminator();
334 break;
335 }
336 --BBI;
Michael Gottesman65c24812013-03-25 09:27:43 +0000337 } while (IsNoopInstruction(BBI));
Michael Gottesman778138e2013-01-29 03:03:03 +0000338
339 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000340 DEBUG(dbgs() << "Adding inline asm marker for "
Michael Gottesman778138e2013-01-29 03:03:03 +0000341 "retainAutoreleasedReturnValue optimization.\n");
342 Changed = true;
343 InlineAsm *IA =
344 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
345 /*isVarArg=*/false),
346 RetainRVMarker->getString(),
347 /*Constraints=*/"", /*hasSideEffects=*/true);
348 CallInst::Create(IA, "", Inst);
349 }
350 decline_rv_optimization:
Michael Gottesman18279732015-02-19 00:42:30 +0000351 return false;
Michael Gottesman778138e2013-01-29 03:03:03 +0000352 }
353 case IC_InitWeak: {
354 // objc_initWeak(p, null) => *p = null
355 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000356 if (IsNullOrUndef(CI->getArgOperand(1))) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000357 Value *Null =
358 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
359 Changed = true;
360 new StoreInst(Null, CI->getArgOperand(0), CI);
361
362 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
363 << " New = " << *Null << "\n");
364
365 CI->replaceAllUsesWith(Null);
366 CI->eraseFromParent();
367 }
Michael Gottesman18279732015-02-19 00:42:30 +0000368 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000369 }
370 case IC_Release:
Michael Gottesman18279732015-02-19 00:42:30 +0000371 contractRelease(Inst, Iter);
372 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000373 case IC_User:
374 // Be conservative if the function has any alloca instructions.
375 // Technically we only care about escaping alloca instructions,
376 // but this is sufficient to handle some interesting cases.
377 if (isa<AllocaInst>(Inst))
378 TailOkForStoreStrongs = false;
Michael Gottesman18279732015-02-19 00:42:30 +0000379 return true;
John McCall20182ac2013-03-22 21:38:36 +0000380 case IC_IntrinsicUser:
381 // Remove calls to @clang.arc.use(...).
382 Inst->eraseFromParent();
Michael Gottesman18279732015-02-19 00:42:30 +0000383 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000384 default:
Michael Gottesman18279732015-02-19 00:42:30 +0000385 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000386 }
Michael Gottesman18279732015-02-19 00:42:30 +0000387}
Michael Gottesman778138e2013-01-29 03:03:03 +0000388
Michael Gottesman18279732015-02-19 00:42:30 +0000389//===----------------------------------------------------------------------===//
390// Top Level Driver
391//===----------------------------------------------------------------------===//
392
393bool ObjCARCContract::runOnFunction(Function &F) {
394 if (!EnableARCOpts)
395 return false;
396
397 // If nothing in the Module uses ARC, don't do anything.
398 if (!Run)
399 return false;
400
401 Changed = false;
402 AA = &getAnalysis<AliasAnalysis>();
403 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
404
405 PA.setAA(&getAnalysis<AliasAnalysis>());
406
407 DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
408
409 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
410 // keyword. Be conservative if the function has variadic arguments.
411 // It seems that functions which "return twice" are also unsafe for the
412 // "tail" argument, because they are setjmp, which could need to
413 // return to an earlier stack state.
414 bool TailOkForStoreStrongs =
415 !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
416
417 // For ObjC library calls which return their argument, replace uses of the
418 // argument with uses of the call return value, if it dominates the use. This
419 // reduces register pressure.
420 SmallPtrSet<Instruction *, 4> DependingInstructions;
421 SmallPtrSet<const BasicBlock *, 4> Visited;
422 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
423 Instruction *Inst = &*I++;
424
425 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
426
427 // First try to peephole Inst. If there is nothing further we can do in
428 // terms of undoing objc-arc-expand, process the next inst.
429 if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
430 TailOkForStoreStrongs))
431 continue;
432
433 // Otherwise, try to undo objc-arc-expand.
Michael Gottesman778138e2013-01-29 03:03:03 +0000434
435 // Don't use GetObjCArg because we don't want to look through bitcasts
436 // and such; to do the replacement, the argument must have type i8*.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000437 Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
Michael Gottesman18279732015-02-19 00:42:30 +0000438
439 // TODO: Change this to a do-while.
Michael Gottesman778138e2013-01-29 03:03:03 +0000440 for (;;) {
441 // If we're compiling bugpointed code, don't get in trouble.
442 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
443 break;
444 // Look through the uses of the pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000445 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
Michael Gottesman778138e2013-01-29 03:03:03 +0000446 UI != UE; ) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000447 // Increment UI now, because we may unlink its element.
448 Use &U = *UI++;
449 unsigned OperandNo = U.getOperandNo();
Michael Gottesman778138e2013-01-29 03:03:03 +0000450
451 // If the call's return value dominates a use of the call's argument
452 // value, rewrite the use to use the return value. We check for
453 // reachability here because an unreachable call is considered to
454 // trivially dominate itself, which would lead us to rewriting its
455 // argument in terms of its return value, which would lead to
456 // infinite loops in GetObjCArg.
457 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
458 Changed = true;
459 Instruction *Replacement = Inst;
460 Type *UseTy = U.get()->getType();
461 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
462 // For PHI nodes, insert the bitcast in the predecessor block.
463 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
464 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
465 if (Replacement->getType() != UseTy)
466 Replacement = new BitCastInst(Replacement, UseTy, "",
467 &BB->back());
468 // While we're here, rewrite all edges for this PHI, rather
469 // than just one use at a time, to minimize the number of
470 // bitcasts we emit.
471 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
472 if (PHI->getIncomingBlock(i) == BB) {
473 // Keep the UI iterator valid.
Duncan P. N. Exon Smithcb1c81a2014-03-18 22:32:43 +0000474 if (UI != UE &&
475 &PHI->getOperandUse(
476 PHINode::getOperandNumForIncomingValue(i)) == &*UI)
Michael Gottesman778138e2013-01-29 03:03:03 +0000477 ++UI;
478 PHI->setIncomingValue(i, Replacement);
479 }
480 } else {
481 if (Replacement->getType() != UseTy)
482 Replacement = new BitCastInst(Replacement, UseTy, "",
483 cast<Instruction>(U.getUser()));
484 U.set(Replacement);
485 }
486 }
487 }
488
489 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
490 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
491 Arg = BI->getOperand(0);
492 else if (isa<GEPOperator>(Arg) &&
493 cast<GEPOperator>(Arg)->hasAllZeroIndices())
494 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
495 else if (isa<GlobalAlias>(Arg) &&
496 !cast<GlobalAlias>(Arg)->mayBeOverridden())
497 Arg = cast<GlobalAlias>(Arg)->getAliasee();
498 else
499 break;
500 }
501 }
502
503 // If this function has no escaping allocas or suspicious vararg usage,
504 // objc_storeStrong calls can be marked with the "tail" keyword.
505 if (TailOkForStoreStrongs)
Craig Topper46276792014-08-24 23:23:06 +0000506 for (CallInst *CI : StoreStrongCalls)
507 CI->setTailCall();
Michael Gottesman778138e2013-01-29 03:03:03 +0000508 StoreStrongCalls.clear();
509
510 return Changed;
511}
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000512
513//===----------------------------------------------------------------------===//
514// Misc Pass Manager
515//===----------------------------------------------------------------------===//
516
517char ObjCARCContract::ID = 0;
518INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract",
519 "ObjC ARC contraction", false, false)
520INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
521INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
522INITIALIZE_PASS_END(ObjCARCContract, "objc-arc-contract",
523 "ObjC ARC contraction", false, false)
524
525void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
526 AU.addRequired<AliasAnalysis>();
527 AU.addRequired<DominatorTreeWrapperPass>();
528 AU.setPreservesCFG();
529}
530
531Pass *llvm::createObjCARCContractPass() { return new ObjCARCContract(); }
532
533bool ObjCARCContract::doInitialization(Module &M) {
534 // If nothing in the Module uses ARC, don't do anything.
535 Run = ModuleHasARC(M);
536 if (!Run)
537 return false;
538
539 EP.Initialize(&M);
540
541 // Initialize RetainRVMarker.
542 RetainRVMarker = nullptr;
543 if (NamedMDNode *NMD =
544 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
545 if (NMD->getNumOperands() == 1) {
546 const MDNode *N = NMD->getOperand(0);
547 if (N->getNumOperands() == 1)
548 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
549 RetainRVMarker = S;
550 }
551
552 return false;
553}