1 //===- ObjCARCContract.cpp - ObjC ARC Optimization ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 /// This specific file mainly deals with ``contracting'' multiple lower level
15 /// operations into singular higher level operations through pattern matching.
17 /// WARNING: This file knows about certain library functions. It recognizes them
18 /// by name, and hardwires knowledge of their semantics.
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.
24 //===----------------------------------------------------------------------===//
26 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
27 // dominated by single calls.
30 #include "ARCRuntimeEntryPoints.h"
31 #include "DependencyAnalysis.h"
32 #include "ProvenanceAnalysis.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/InlineAsm.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/Support/Debug.h"
40 using namespace llvm::objcarc;
42 #define DEBUG_TYPE "objc-arc-contract"
44 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
45 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
52 /// \brief Late ARC optimizations
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 {
60 ProvenanceAnalysis PA;
61 ARCRuntimeEntryPoints EP;
63 /// A flag indicating whether this optimization pass should run.
66 /// 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;
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
73 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
75 /// Returns true if we eliminated Inst.
76 bool tryToPeepholeInstruction(Function &F, Instruction *Inst,
78 SmallPtrSetImpl<Instruction *> &DepInsts,
79 SmallPtrSetImpl<const BasicBlock *> &Visited,
80 bool &TailOkForStoreStrong);
82 bool optimizeRetainCall(Function &F, Instruction *Retain);
85 contractAutorelease(Function &F, Instruction *Autorelease,
87 SmallPtrSetImpl<Instruction *> &DependingInstructions,
88 SmallPtrSetImpl<const BasicBlock *> &Visited);
90 void tryToContractReleaseIntoStoreStrong(Instruction *Release,
93 void getAnalysisUsage(AnalysisUsage &AU) const override;
94 bool doInitialization(Module &M) override;
95 bool runOnFunction(Function &F) override;
99 ObjCARCContract() : FunctionPass(ID) {
100 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
105 //===----------------------------------------------------------------------===//
107 //===----------------------------------------------------------------------===//
109 /// 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
112 bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
113 ImmutableCallSite CS(GetArgRCIdentityRoot(Retain));
114 const Instruction *Call = CS.getInstruction();
117 if (Call->getParent() != Retain->getParent())
120 // Check that the call is next to the retain.
121 BasicBlock::const_iterator I = Call;
123 while (IsNoopInstruction(I)) ++I;
127 // Turn it to an objc_retainAutoreleasedReturnValue.
131 DEBUG(dbgs() << "Transforming objc_retain => "
132 "objc_retainAutoreleasedReturnValue since the operand is a "
133 "return value.\nOld: "<< *Retain << "\n");
135 // We do not have to worry about tail calls/does not throw since
136 // retain/retainRV have the same properties.
137 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_RetainRV);
138 cast<CallInst>(Retain)->setCalledFunction(Decl);
140 DEBUG(dbgs() << "New: " << *Retain << "\n");
144 /// Merge an autorelease with a retain into a fused call.
145 bool ObjCARCContract::contractAutorelease(
146 Function &F, Instruction *Autorelease, ARCInstKind Class,
147 SmallPtrSetImpl<Instruction *> &DependingInstructions,
148 SmallPtrSetImpl<const BasicBlock *> &Visited) {
149 const Value *Arg = GetArgRCIdentityRoot(Autorelease);
151 // Check that there are no instructions between the retain and the autorelease
152 // (such as an autorelease_pop) which may change the count.
153 CallInst *Retain = nullptr;
154 if (Class == ARCInstKind::AutoreleaseRV)
155 FindDependencies(RetainAutoreleaseRVDep, Arg,
156 Autorelease->getParent(), Autorelease,
157 DependingInstructions, Visited, PA);
159 FindDependencies(RetainAutoreleaseDep, Arg,
160 Autorelease->getParent(), Autorelease,
161 DependingInstructions, Visited, PA);
164 if (DependingInstructions.size() != 1) {
165 DependingInstructions.clear();
169 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
170 DependingInstructions.clear();
172 if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
173 GetArgRCIdentityRoot(Retain) != Arg)
179 DEBUG(dbgs() << " Fusing retain/autorelease!\n"
180 " Autorelease:" << *Autorelease << "\n"
181 " Retain: " << *Retain << "\n");
183 Constant *Decl = EP.get(Class == ARCInstKind::AutoreleaseRV
184 ? ARCRuntimeEntryPoints::EPT_RetainAutoreleaseRV
185 : ARCRuntimeEntryPoints::EPT_RetainAutorelease);
186 Retain->setCalledFunction(Decl);
188 DEBUG(dbgs() << " New RetainAutorelease: " << *Retain << "\n");
190 EraseInstruction(Autorelease);
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
200 tryToContractReleaseIntoStoreStrong(Instruction *Release, inst_iterator &Iter) {
201 LoadInst *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
202 if (!Load || !Load->isSimple()) return;
204 // For now, require everything to be in one basic block.
205 BasicBlock *BB = Release->getParent();
206 if (Load->getParent() != BB) return;
208 // Walk down to find the store and the release, which may be in either order.
209 BasicBlock::iterator I = Load, End = BB->end();
211 AliasAnalysis::Location Loc = AA->getLocation(Load);
212 StoreInst *Store = nullptr;
213 bool SawRelease = false;
214 for (; !Store || !SawRelease; ++I) {
218 Instruction *Inst = I;
219 if (Inst == Release) {
224 ARCInstKind Class = GetBasicARCInstKind(Inst);
226 // Unrelated retains are harmless.
231 // The store is the point where we're going to put the objc_storeStrong,
232 // so make sure there are no uses after it.
233 if (CanUse(Inst, Load, PA, Class))
235 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
236 // We are moving the load down to the store, so check for anything
237 // else which writes to the memory between the load and the store.
238 Store = dyn_cast<StoreInst>(Inst);
239 if (!Store || !Store->isSimple()) return;
240 if (Store->getPointerOperand() != Loc.Ptr) return;
244 Value *New = GetRCIdentityRoot(Store->getValueOperand());
246 // Walk up to find the retain.
248 BasicBlock::iterator Begin = BB->begin();
249 while (I != Begin && GetBasicARCInstKind(I) != ARCInstKind::Retain)
251 Instruction *Retain = I;
252 if (GetBasicARCInstKind(Retain) != ARCInstKind::Retain)
254 if (GetArgRCIdentityRoot(Retain) != New) return;
260 llvm::dbgs() << " Contracting retain, release into objc_storeStrong.\n"
262 << " Store: " << *Store << "\n"
263 << " Release: " << *Release << "\n"
264 << " Retain: " << *Retain << "\n"
265 << " Load: " << *Load << "\n");
267 LLVMContext &C = Release->getContext();
268 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
269 Type *I8XX = PointerType::getUnqual(I8X);
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);
276 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_StoreStrong);
277 CallInst *StoreStrong = CallInst::Create(Decl, Args, "", Store);
278 StoreStrong->setDoesNotThrow();
279 StoreStrong->setDebugLoc(Store->getDebugLoc());
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);
286 DEBUG(llvm::dbgs() << " New Store Strong: " << *StoreStrong << "\n");
288 if (&*Iter == Store) ++Iter;
289 Store->eraseFromParent();
290 Release->eraseFromParent();
291 EraseInstruction(Retain);
292 if (Load->use_empty())
293 Load->eraseFromParent();
296 bool ObjCARCContract::tryToPeepholeInstruction(
297 Function &F, Instruction *Inst, inst_iterator &Iter,
298 SmallPtrSetImpl<Instruction *> &DependingInsts,
299 SmallPtrSetImpl<const BasicBlock *> &Visited,
300 bool &TailOkForStoreStrongs) {
301 // Only these library routines return their argument. In particular,
302 // objc_retainBlock does not necessarily return its argument.
303 ARCInstKind Class = GetBasicARCInstKind(Inst);
305 case ARCInstKind::FusedRetainAutorelease:
306 case ARCInstKind::FusedRetainAutoreleaseRV:
308 case ARCInstKind::Autorelease:
309 case ARCInstKind::AutoreleaseRV:
310 return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
311 case ARCInstKind::Retain:
312 // Attempt to convert retains to retainrvs if they are next to function
314 if (!optimizeRetainCall(F, Inst))
316 // If we succeed in our optimization, fall through.
318 case ARCInstKind::RetainRV: {
319 // If we're compiling for a target which needs a special inline-asm
320 // marker to do the retainAutoreleasedReturnValue optimization,
324 BasicBlock::iterator BBI = Inst;
325 BasicBlock *InstParent = Inst->getParent();
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.
331 if (&*BBI == InstParent->begin()) {
332 BasicBlock *Pred = InstParent->getSinglePredecessor();
334 goto decline_rv_optimization;
335 BBI = Pred->getTerminator();
339 } while (IsNoopInstruction(BBI));
341 if (&*BBI == GetArgRCIdentityRoot(Inst)) {
342 DEBUG(dbgs() << "Adding inline asm marker for "
343 "retainAutoreleasedReturnValue optimization.\n");
346 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
348 RetainRVMarker->getString(),
349 /*Constraints=*/"", /*hasSideEffects=*/true);
350 CallInst::Create(IA, "", Inst);
352 decline_rv_optimization:
355 case ARCInstKind::InitWeak: {
356 // objc_initWeak(p, null) => *p = null
357 CallInst *CI = cast<CallInst>(Inst);
358 if (IsNullOrUndef(CI->getArgOperand(1))) {
360 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
362 new StoreInst(Null, CI->getArgOperand(0), CI);
364 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
365 << " New = " << *Null << "\n");
367 CI->replaceAllUsesWith(Null);
368 CI->eraseFromParent();
372 case ARCInstKind::Release:
373 // 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);
377 case ARCInstKind::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;
384 case ARCInstKind::IntrinsicUser:
385 // Remove calls to @clang.arc.use(...).
386 Inst->eraseFromParent();
393 //===----------------------------------------------------------------------===//
395 //===----------------------------------------------------------------------===//
397 bool ObjCARCContract::runOnFunction(Function &F) {
401 // If nothing in the Module uses ARC, don't do anything.
406 AA = &getAnalysis<AliasAnalysis>();
407 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
409 PA.setAA(&getAnalysis<AliasAnalysis>());
411 DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
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();
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++;
429 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
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))
437 // Otherwise, try to undo objc-arc-expand.
439 // Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
440 // and such; to do the replacement, the argument must have type i8*.
441 Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
443 // TODO: Change this to a do-while.
445 // If we're compiling bugpointed code, don't get in trouble.
446 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
448 // Look through the uses of the pointer.
449 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
451 // Increment UI now, because we may unlink its element.
453 unsigned OperandNo = U.getOperandNo();
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
460 // infinite loops in GetArgRCIdentityRoot.
461 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
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, "",
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
475 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
476 if (PHI->getIncomingBlock(i) == BB) {
477 // Keep the UI iterator valid.
480 PHINode::getOperandNumForIncomingValue(i)) == &*UI)
482 PHI->setIncomingValue(i, Replacement);
485 if (Replacement->getType() != UseTy)
486 Replacement = new BitCastInst(Replacement, UseTy, "",
487 cast<Instruction>(U.getUser()));
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();
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)
510 for (CallInst *CI : StoreStrongCalls)
512 StoreStrongCalls.clear();
517 //===----------------------------------------------------------------------===//
519 //===----------------------------------------------------------------------===//
521 char ObjCARCContract::ID = 0;
522 INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract",
523 "ObjC ARC contraction", false, false)
524 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
525 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
526 INITIALIZE_PASS_END(ObjCARCContract, "objc-arc-contract",
527 "ObjC ARC contraction", false, false)
529 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
530 AU.addRequired<AliasAnalysis>();
531 AU.addRequired<DominatorTreeWrapperPass>();
532 AU.setPreservesCFG();
535 Pass *llvm::createObjCARCContractPass() { return new ObjCARCContract(); }
537 bool ObjCARCContract::doInitialization(Module &M) {
538 // If nothing in the Module uses ARC, don't do anything.
539 Run = ModuleHasARC(M);
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)))