blob: 741f5291536ba78c6afbeec67328b62f93b74f26 [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,
Michael Gottesman6f729fa2015-02-19 19:51:32 +000086 ARCInstKind Class,
Michael Gottesman56bd6a02015-02-19 00:42:27 +000087 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 Gottesmanca3a4722015-03-16 07:02:24 +0000137 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::RetainRV);
Michael Gottesman0b912b22013-07-06 01:39:26 +0000138 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(
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000146 Function &F, Instruction *Autorelease, ARCInstKind Class,
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000147 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 Gottesman6f729fa2015-02-19 19:51:32 +0000154 if (Class == ARCInstKind::AutoreleaseRV)
Michael Gottesman778138e2013-01-29 03:03:03 +0000155 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
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000172 if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000173 GetArgRCIdentityRoot(Retain) != Arg)
Michael Gottesman778138e2013-01-29 03:03:03 +0000174 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 Gottesman6f729fa2015-02-19 19:51:32 +0000183 Constant *Decl = EP.get(Class == ARCInstKind::AutoreleaseRV
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000184 ? ARCRuntimeEntryPointKind::RetainAutoreleaseRV
185 : ARCRuntimeEntryPointKind::RetainAutorelease);
Michael Gottesman0b912b22013-07-06 01:39:26 +0000186 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
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000194static StoreInst *findSafeStoreForStoreStrongContraction(LoadInst *Load,
195 Instruction *Release,
196 ProvenanceAnalysis &PA,
197 AliasAnalysis *AA) {
Craig Topperf40110f2014-04-25 05:29:35 +0000198 StoreInst *Store = nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000199 bool SawRelease = false;
Michael Gottesman778138e2013-01-29 03:03:03 +0000200
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000201 // Get the location associated with Load.
202 AliasAnalysis::Location Loc = AA->getLocation(Load);
203
204 // Walk down to find the store and the release, which may be in either order.
205 for (auto I = std::next(BasicBlock::iterator(Load)),
206 E = Load->getParent()->end();
207 I != E; ++I) {
208 // If we found the store we were looking for and saw the release,
209 // break. There is no more work to be done.
210 if (Store && SawRelease)
211 break;
212
213 // Now we know that we have not seen either the store or the release. If I
214 // is the the release, mark that we saw the release and continue.
215 Instruction *Inst = &*I;
Michael Gottesman778138e2013-01-29 03:03:03 +0000216 if (Inst == Release) {
217 SawRelease = true;
218 continue;
219 }
220
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000221 // Otherwise, we check if Inst is a "good" store. Grab the instruction class
222 // of Inst.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000223 ARCInstKind Class = GetBasicARCInstKind(Inst);
Michael Gottesman778138e2013-01-29 03:03:03 +0000224
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000225 // If Inst is an unrelated retain, we don't care about it.
226 //
227 // TODO: This is one area where the optimization could be made more
228 // aggressive.
Michael Gottesman778138e2013-01-29 03:03:03 +0000229 if (IsRetain(Class))
230 continue;
231
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000232 // If we have seen the store, but not the release...
Michael Gottesman778138e2013-01-29 03:03:03 +0000233 if (Store) {
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000234 // We need to make sure that it is safe to move the release from its
235 // current position to the store. This implies proving that any
236 // instruction in between Store and the Release conservatively can not use
237 // the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
238 // continue...
239 if (!CanUse(Inst, Load, PA, Class)) {
240 continue;
241 }
242
243 // Otherwise, be conservative and return nullptr.
244 return nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000245 }
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000246
247 // Ok, now we know we have not seen a store yet. See if Inst can write to
248 // our load location, if it can not, just ignore the instruction.
249 if (!(AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod))
250 continue;
251
252 Store = dyn_cast<StoreInst>(Inst);
253
254 // If Inst can, then check if Inst is a simple store. If Inst is not a
255 // store or a store that is not simple, then we have some we do not
256 // understand writing to this memory implying we can not move the load
257 // over the write to any subsequent store that we may find.
258 if (!Store || !Store->isSimple())
259 return nullptr;
260
261 // Then make sure that the pointer we are storing to is Ptr. If so, we
262 // found our Store!
263 if (Store->getPointerOperand() == Loc.Ptr)
264 continue;
265
266 // Otherwise, we have an unknown store to some other ptr that clobbers
267 // Loc.Ptr. Bail!
268 return nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000269 }
270
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000271 // If we did not find the store or did not see the release, fail.
272 if (!Store || !SawRelease)
273 return nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000274
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000275 // We succeeded!
276 return Store;
277}
278
279static Instruction *
280findRetainForStoreStrongContraction(Value *New, StoreInst *Store,
281 Instruction *Release,
282 ProvenanceAnalysis &PA) {
283 // Walk up from the Store to find the retain.
284 BasicBlock::iterator I = Store;
285 BasicBlock::iterator Begin = Store->getParent()->begin();
286 while (I != Begin && GetBasicARCInstKind(I) != ARCInstKind::Retain) {
287 Instruction *Inst = &*I;
288
289 // It is only safe to move the retain to the store if we can prove
290 // conservatively that nothing besides the release can decrement reference
291 // counts in between the retain and the store.
292 if (CanDecrementRefCount(Inst, New, PA) && Inst != Release)
293 return nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000294 --I;
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000295 }
Michael Gottesman778138e2013-01-29 03:03:03 +0000296 Instruction *Retain = I;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000297 if (GetBasicARCInstKind(Retain) != ARCInstKind::Retain)
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000298 return nullptr;
299 if (GetArgRCIdentityRoot(Retain) != New)
300 return nullptr;
301 return Retain;
302}
303
304/// Attempt to merge an objc_release with a store, load, and objc_retain to form
305/// an objc_storeStrong. An objc_storeStrong:
306///
307/// objc_storeStrong(i8** %old_ptr, i8* new_value)
308///
309/// is equivalent to the following IR sequence:
310///
311/// ; Load old value.
312/// %old_value = load i8** %old_ptr (1)
313///
314/// ; Increment the new value and then release the old value. This must occur
315/// ; in order in case old_value releases new_value in its destructor causing
316/// ; us to potentially have a dangling ptr.
317/// tail call i8* @objc_retain(i8* %new_value) (2)
318/// tail call void @objc_release(i8* %old_value) (3)
319///
320/// ; Store the new_value into old_ptr
321/// store i8* %new_value, i8** %old_ptr (4)
322///
323/// The safety of this optimization is based around the following
324/// considerations:
325///
326/// 1. We are forming the store strong at the store. Thus to perform this
327/// optimization it must be safe to move the retain, load, and release to
328/// (4).
329/// 2. We need to make sure that any re-orderings of (1), (2), (3), (4) are
330/// safe.
331void ObjCARCContract::tryToContractReleaseIntoStoreStrong(Instruction *Release,
332 inst_iterator &Iter) {
333 // See if we are releasing something that we just loaded.
334 auto *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
335 if (!Load || !Load->isSimple())
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000336 return;
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000337
338 // For now, require everything to be in one basic block.
339 BasicBlock *BB = Release->getParent();
340 if (Load->getParent() != BB)
341 return;
342
343 // First scan down the BB from Load, looking for a store of the RCIdentityRoot
344 // of Load's
345 StoreInst *Store =
346 findSafeStoreForStoreStrongContraction(Load, Release, PA, AA);
347 // If we fail, bail.
348 if (!Store)
349 return;
350
351 // Then find what new_value's RCIdentity Root is.
352 Value *New = GetRCIdentityRoot(Store->getValueOperand());
353
354 // Then walk up the BB and look for a retain on New without any intervening
355 // instructions which conservatively might decrement ref counts.
356 Instruction *Retain =
357 findRetainForStoreStrongContraction(New, Store, Release, PA);
358
359 // If we fail, bail.
360 if (!Retain)
361 return;
Michael Gottesman778138e2013-01-29 03:03:03 +0000362
363 Changed = true;
364 ++NumStoreStrongs;
365
Michael Gottesman18279732015-02-19 00:42:30 +0000366 DEBUG(
367 llvm::dbgs() << " Contracting retain, release into objc_storeStrong.\n"
368 << " Old:\n"
369 << " Store: " << *Store << "\n"
370 << " Release: " << *Release << "\n"
371 << " Retain: " << *Retain << "\n"
372 << " Load: " << *Load << "\n");
373
Michael Gottesman778138e2013-01-29 03:03:03 +0000374 LLVMContext &C = Release->getContext();
375 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
376 Type *I8XX = PointerType::getUnqual(I8X);
377
378 Value *Args[] = { Load->getPointerOperand(), New };
379 if (Args[0]->getType() != I8XX)
380 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
381 if (Args[1]->getType() != I8X)
382 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000383 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::StoreStrong);
Michael Gottesman0b912b22013-07-06 01:39:26 +0000384 CallInst *StoreStrong = CallInst::Create(Decl, Args, "", Store);
Michael Gottesman778138e2013-01-29 03:03:03 +0000385 StoreStrong->setDoesNotThrow();
386 StoreStrong->setDebugLoc(Store->getDebugLoc());
387
388 // We can't set the tail flag yet, because we haven't yet determined
389 // whether there are any escaping allocas. Remember this call, so that
390 // we can set the tail flag once we know it's safe.
391 StoreStrongCalls.insert(StoreStrong);
392
Michael Gottesman18279732015-02-19 00:42:30 +0000393 DEBUG(llvm::dbgs() << " New Store Strong: " << *StoreStrong << "\n");
394
Michael Gottesman778138e2013-01-29 03:03:03 +0000395 if (&*Iter == Store) ++Iter;
396 Store->eraseFromParent();
397 Release->eraseFromParent();
398 EraseInstruction(Retain);
399 if (Load->use_empty())
400 Load->eraseFromParent();
401}
402
Michael Gottesman18279732015-02-19 00:42:30 +0000403bool ObjCARCContract::tryToPeepholeInstruction(
404 Function &F, Instruction *Inst, inst_iterator &Iter,
405 SmallPtrSetImpl<Instruction *> &DependingInsts,
406 SmallPtrSetImpl<const BasicBlock *> &Visited,
407 bool &TailOkForStoreStrongs) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000408 // Only these library routines return their argument. In particular,
409 // objc_retainBlock does not necessarily return its argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000410 ARCInstKind Class = GetBasicARCInstKind(Inst);
Michael Gottesman778138e2013-01-29 03:03:03 +0000411 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000412 case ARCInstKind::FusedRetainAutorelease:
413 case ARCInstKind::FusedRetainAutoreleaseRV:
Michael Gottesman18279732015-02-19 00:42:30 +0000414 return false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000415 case ARCInstKind::Autorelease:
416 case ARCInstKind::AutoreleaseRV:
Michael Gottesman18279732015-02-19 00:42:30 +0000417 return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000418 case ARCInstKind::Retain:
Michael Gottesman214ca902013-04-29 06:53:53 +0000419 // Attempt to convert retains to retainrvs if they are next to function
420 // calls.
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000421 if (!optimizeRetainCall(F, Inst))
Michael Gottesman18279732015-02-19 00:42:30 +0000422 return false;
Michael Gottesman214ca902013-04-29 06:53:53 +0000423 // If we succeed in our optimization, fall through.
424 // FALLTHROUGH
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000425 case ARCInstKind::RetainRV: {
Michael Gottesman778138e2013-01-29 03:03:03 +0000426 // If we're compiling for a target which needs a special inline-asm
427 // marker to do the retainAutoreleasedReturnValue optimization,
428 // insert it now.
429 if (!RetainRVMarker)
Michael Gottesman18279732015-02-19 00:42:30 +0000430 return false;
Michael Gottesman778138e2013-01-29 03:03:03 +0000431 BasicBlock::iterator BBI = Inst;
432 BasicBlock *InstParent = Inst->getParent();
433
434 // Step up to see if the call immediately precedes the RetainRV call.
435 // If it's an invoke, we have to cross a block boundary. And we have
436 // to carefully dodge no-op instructions.
437 do {
438 if (&*BBI == InstParent->begin()) {
439 BasicBlock *Pred = InstParent->getSinglePredecessor();
440 if (!Pred)
441 goto decline_rv_optimization;
442 BBI = Pred->getTerminator();
443 break;
444 }
445 --BBI;
Michael Gottesman65c24812013-03-25 09:27:43 +0000446 } while (IsNoopInstruction(BBI));
Michael Gottesman778138e2013-01-29 03:03:03 +0000447
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000448 if (&*BBI == GetArgRCIdentityRoot(Inst)) {
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000449 DEBUG(dbgs() << "Adding inline asm marker for "
Michael Gottesman778138e2013-01-29 03:03:03 +0000450 "retainAutoreleasedReturnValue optimization.\n");
451 Changed = true;
452 InlineAsm *IA =
453 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
454 /*isVarArg=*/false),
455 RetainRVMarker->getString(),
456 /*Constraints=*/"", /*hasSideEffects=*/true);
457 CallInst::Create(IA, "", Inst);
458 }
459 decline_rv_optimization:
Michael Gottesman18279732015-02-19 00:42:30 +0000460 return false;
Michael Gottesman778138e2013-01-29 03:03:03 +0000461 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000462 case ARCInstKind::InitWeak: {
Michael Gottesman778138e2013-01-29 03:03:03 +0000463 // objc_initWeak(p, null) => *p = null
464 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000465 if (IsNullOrUndef(CI->getArgOperand(1))) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000466 Value *Null =
467 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
468 Changed = true;
469 new StoreInst(Null, CI->getArgOperand(0), CI);
470
471 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
472 << " New = " << *Null << "\n");
473
474 CI->replaceAllUsesWith(Null);
475 CI->eraseFromParent();
476 }
Michael Gottesman18279732015-02-19 00:42:30 +0000477 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000478 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000479 case ARCInstKind::Release:
Michael Gottesmandfa3e4b2015-02-19 00:42:34 +0000480 // Try to form an objc store strong from our release. If we fail, there is
481 // nothing further to do below, so continue.
482 tryToContractReleaseIntoStoreStrong(Inst, Iter);
Michael Gottesman18279732015-02-19 00:42:30 +0000483 return true;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000484 case ARCInstKind::User:
Michael Gottesman778138e2013-01-29 03:03:03 +0000485 // Be conservative if the function has any alloca instructions.
486 // Technically we only care about escaping alloca instructions,
487 // but this is sufficient to handle some interesting cases.
488 if (isa<AllocaInst>(Inst))
489 TailOkForStoreStrongs = false;
Michael Gottesman18279732015-02-19 00:42:30 +0000490 return true;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000491 case ARCInstKind::IntrinsicUser:
John McCall20182ac2013-03-22 21:38:36 +0000492 // Remove calls to @clang.arc.use(...).
493 Inst->eraseFromParent();
Michael Gottesman18279732015-02-19 00:42:30 +0000494 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000495 default:
Michael Gottesman18279732015-02-19 00:42:30 +0000496 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000497 }
Michael Gottesman18279732015-02-19 00:42:30 +0000498}
Michael Gottesman778138e2013-01-29 03:03:03 +0000499
Michael Gottesman18279732015-02-19 00:42:30 +0000500//===----------------------------------------------------------------------===//
501// Top Level Driver
502//===----------------------------------------------------------------------===//
503
504bool ObjCARCContract::runOnFunction(Function &F) {
505 if (!EnableARCOpts)
506 return false;
507
508 // If nothing in the Module uses ARC, don't do anything.
509 if (!Run)
510 return false;
511
512 Changed = false;
513 AA = &getAnalysis<AliasAnalysis>();
514 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
515
516 PA.setAA(&getAnalysis<AliasAnalysis>());
517
518 DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
519
520 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
521 // keyword. Be conservative if the function has variadic arguments.
522 // It seems that functions which "return twice" are also unsafe for the
523 // "tail" argument, because they are setjmp, which could need to
524 // return to an earlier stack state.
525 bool TailOkForStoreStrongs =
526 !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
527
528 // For ObjC library calls which return their argument, replace uses of the
529 // argument with uses of the call return value, if it dominates the use. This
530 // reduces register pressure.
531 SmallPtrSet<Instruction *, 4> DependingInstructions;
532 SmallPtrSet<const BasicBlock *, 4> Visited;
533 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
534 Instruction *Inst = &*I++;
535
536 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
537
538 // First try to peephole Inst. If there is nothing further we can do in
539 // terms of undoing objc-arc-expand, process the next inst.
540 if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
541 TailOkForStoreStrongs))
542 continue;
543
544 // Otherwise, try to undo objc-arc-expand.
Michael Gottesman778138e2013-01-29 03:03:03 +0000545
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000546 // Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
Michael Gottesman778138e2013-01-29 03:03:03 +0000547 // and such; to do the replacement, the argument must have type i8*.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000548 Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
Michael Gottesman18279732015-02-19 00:42:30 +0000549
550 // TODO: Change this to a do-while.
Michael Gottesman778138e2013-01-29 03:03:03 +0000551 for (;;) {
552 // If we're compiling bugpointed code, don't get in trouble.
553 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
554 break;
555 // Look through the uses of the pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000556 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
Michael Gottesman778138e2013-01-29 03:03:03 +0000557 UI != UE; ) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000558 // Increment UI now, because we may unlink its element.
559 Use &U = *UI++;
560 unsigned OperandNo = U.getOperandNo();
Michael Gottesman778138e2013-01-29 03:03:03 +0000561
562 // If the call's return value dominates a use of the call's argument
563 // value, rewrite the use to use the return value. We check for
564 // reachability here because an unreachable call is considered to
565 // trivially dominate itself, which would lead us to rewriting its
566 // argument in terms of its return value, which would lead to
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000567 // infinite loops in GetArgRCIdentityRoot.
Michael Gottesman778138e2013-01-29 03:03:03 +0000568 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
569 Changed = true;
570 Instruction *Replacement = Inst;
571 Type *UseTy = U.get()->getType();
572 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
573 // For PHI nodes, insert the bitcast in the predecessor block.
574 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
575 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
576 if (Replacement->getType() != UseTy)
577 Replacement = new BitCastInst(Replacement, UseTy, "",
578 &BB->back());
579 // While we're here, rewrite all edges for this PHI, rather
580 // than just one use at a time, to minimize the number of
581 // bitcasts we emit.
582 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
583 if (PHI->getIncomingBlock(i) == BB) {
584 // Keep the UI iterator valid.
Duncan P. N. Exon Smithcb1c81a2014-03-18 22:32:43 +0000585 if (UI != UE &&
586 &PHI->getOperandUse(
587 PHINode::getOperandNumForIncomingValue(i)) == &*UI)
Michael Gottesman778138e2013-01-29 03:03:03 +0000588 ++UI;
589 PHI->setIncomingValue(i, Replacement);
590 }
591 } else {
592 if (Replacement->getType() != UseTy)
593 Replacement = new BitCastInst(Replacement, UseTy, "",
594 cast<Instruction>(U.getUser()));
595 U.set(Replacement);
596 }
597 }
598 }
599
600 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
601 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
602 Arg = BI->getOperand(0);
603 else if (isa<GEPOperator>(Arg) &&
604 cast<GEPOperator>(Arg)->hasAllZeroIndices())
605 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
606 else if (isa<GlobalAlias>(Arg) &&
607 !cast<GlobalAlias>(Arg)->mayBeOverridden())
608 Arg = cast<GlobalAlias>(Arg)->getAliasee();
609 else
610 break;
611 }
612 }
613
614 // If this function has no escaping allocas or suspicious vararg usage,
615 // objc_storeStrong calls can be marked with the "tail" keyword.
616 if (TailOkForStoreStrongs)
Craig Topper46276792014-08-24 23:23:06 +0000617 for (CallInst *CI : StoreStrongCalls)
618 CI->setTailCall();
Michael Gottesman778138e2013-01-29 03:03:03 +0000619 StoreStrongCalls.clear();
620
621 return Changed;
622}
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000623
624//===----------------------------------------------------------------------===//
625// Misc Pass Manager
626//===----------------------------------------------------------------------===//
627
628char ObjCARCContract::ID = 0;
629INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract",
630 "ObjC ARC contraction", false, false)
631INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
632INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
633INITIALIZE_PASS_END(ObjCARCContract, "objc-arc-contract",
634 "ObjC ARC contraction", false, false)
635
636void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
637 AU.addRequired<AliasAnalysis>();
638 AU.addRequired<DominatorTreeWrapperPass>();
639 AU.setPreservesCFG();
640}
641
642Pass *llvm::createObjCARCContractPass() { return new ObjCARCContract(); }
643
644bool ObjCARCContract::doInitialization(Module &M) {
645 // If nothing in the Module uses ARC, don't do anything.
646 Run = ModuleHasARC(M);
647 if (!Run)
648 return false;
649
Michael Gottesman65cb7372015-03-16 07:02:27 +0000650 EP.init(&M);
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000651
652 // Initialize RetainRVMarker.
653 RetainRVMarker = nullptr;
654 if (NamedMDNode *NMD =
655 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
656 if (NMD->getNumOperands() == 1) {
657 const MDNode *N = NMD->getOperand(0);
658 if (N->getNumOperands() == 1)
659 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
660 RetainRVMarker = S;
661 }
662
663 return false;
664}