blob: a424f5323b90fcce9bad8f5a6bbc312edf53d01f [file] [log] [blame]
Michael Gottesman1e29ca12013-01-29 05:07:18 +00001//===- ObjCARCContract.cpp - ObjC ARC Optimization ------------------------===//
Michael Gottesman778138e2013-01-29 03:03:03 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Michael Gottesman778138e2013-01-29 03:03:03 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file defines late ObjC ARC optimizations. ARC stands for Automatic
10/// Reference Counting and is a system for managing reference counts for objects
11/// in Objective C.
12///
Michael Gottesman697d8b92013-02-07 04:12:57 +000013/// This specific file mainly deals with ``contracting'' multiple lower level
14/// operations into singular higher level operations through pattern matching.
15///
Michael Gottesman778138e2013-01-29 03:03:03 +000016/// WARNING: This file knows about certain library functions. It recognizes them
17/// by name, and hardwires knowledge of their semantics.
18///
19/// WARNING: This file knows about how certain Objective-C library functions are
20/// used. Naive LLVM IR transformations which would otherwise be
21/// behavior-preserving may break these assumptions.
22///
23//===----------------------------------------------------------------------===//
24
25// TODO: ObjCARCContract could insert PHI nodes when uses aren't
26// dominated by single calls.
27
Michael Gottesman0b912b22013-07-06 01:39:26 +000028#include "ARCRuntimeEntryPoints.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000029#include "DependencyAnalysis.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000030#include "ObjCARC.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000031#include "ProvenanceAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000032#include "llvm/ADT/Statistic.h"
Shoaib Meenai3f689c82018-03-20 20:45:41 +000033#include "llvm/Analysis/EHPersonalities.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"
Benjamin Kramer799003b2015-03-23 19:32:43 +000038#include "llvm/Support/raw_ostream.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000039
40using namespace llvm;
41using namespace llvm::objcarc;
42
Chandler Carruth964daaa2014-04-22 02:55:47 +000043#define DEBUG_TYPE "objc-arc-contract"
44
Michael Gottesman778138e2013-01-29 03:03:03 +000045STATISTIC(NumPeeps, "Number of calls peephole-optimized");
46STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
47
Michael Gottesman56bd6a02015-02-19 00:42:27 +000048//===----------------------------------------------------------------------===//
49// Declarations
50//===----------------------------------------------------------------------===//
51
Michael Gottesman778138e2013-01-29 03:03:03 +000052namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000053 /// Late ARC optimizations
Michael Gottesman778138e2013-01-29 03:03:03 +000054 ///
55 /// These change the IR in a way that makes it difficult to be analyzed by
56 /// ObjCARCOpt, so it's run late.
57 class ObjCARCContract : public FunctionPass {
58 bool Changed;
59 AliasAnalysis *AA;
60 DominatorTree *DT;
61 ProvenanceAnalysis PA;
Michael Gottesman0b912b22013-07-06 01:39:26 +000062 ARCRuntimeEntryPoints EP;
Michael Gottesman778138e2013-01-29 03:03:03 +000063
64 /// A flag indicating whether this optimization pass should run.
65 bool Run;
66
Michael Gottesman778138e2013-01-29 03:03:03 +000067 /// The inline asm string to insert between calls and RetainRV calls to make
68 /// the optimization work on targets which need it.
John McCall3fe604f2016-01-27 19:05:08 +000069 const MDString *RVInstMarker;
Michael Gottesman778138e2013-01-29 03:03:03 +000070
71 /// The set of inserted objc_storeStrong calls. If at the end of walking the
72 /// function we have found no alloca instructions, these calls can be marked
73 /// "tail".
74 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
75
Michael Gottesman18279732015-02-19 00:42:30 +000076 /// Returns true if we eliminated Inst.
Shoaib Meenai106df7d2018-04-20 22:14:45 +000077 bool tryToPeepholeInstruction(
78 Function &F, Instruction *Inst, inst_iterator &Iter,
79 SmallPtrSetImpl<Instruction *> &DepInsts,
80 SmallPtrSetImpl<const BasicBlock *> &Visited,
81 bool &TailOkForStoreStrong,
82 const DenseMap<BasicBlock *, ColorVector> &BlockColors);
Michael Gottesman18279732015-02-19 00:42:30 +000083
Michael Gottesman56bd6a02015-02-19 00:42:27 +000084 bool optimizeRetainCall(Function &F, Instruction *Retain);
Michael Gottesman214ca902013-04-29 06:53:53 +000085
Michael Gottesman56bd6a02015-02-19 00:42:27 +000086 bool
87 contractAutorelease(Function &F, Instruction *Autorelease,
Michael Gottesman6f729fa2015-02-19 19:51:32 +000088 ARCInstKind Class,
Michael Gottesman56bd6a02015-02-19 00:42:27 +000089 SmallPtrSetImpl<Instruction *> &DependingInstructions,
90 SmallPtrSetImpl<const BasicBlock *> &Visited);
Michael Gottesman778138e2013-01-29 03:03:03 +000091
Shoaib Meenaid64b8322018-04-20 22:11:03 +000092 void tryToContractReleaseIntoStoreStrong(
93 Instruction *Release, inst_iterator &Iter,
94 const DenseMap<BasicBlock *, ColorVector> &BlockColors);
Michael Gottesman778138e2013-01-29 03:03:03 +000095
Craig Topper3e4c6972014-03-05 09:10:37 +000096 void getAnalysisUsage(AnalysisUsage &AU) const override;
97 bool doInitialization(Module &M) override;
98 bool runOnFunction(Function &F) override;
Michael Gottesman778138e2013-01-29 03:03:03 +000099
100 public:
101 static char ID;
102 ObjCARCContract() : FunctionPass(ID) {
103 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
104 }
105 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000106}
Michael Gottesman778138e2013-01-29 03:03:03 +0000107
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000108//===----------------------------------------------------------------------===//
109// Implementation
110//===----------------------------------------------------------------------===//
Michael Gottesman778138e2013-01-29 03:03:03 +0000111
Michael Gottesman214ca902013-04-29 06:53:53 +0000112/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
113/// return value. We do this late so we do not disrupt the dataflow analysis in
114/// ObjCARCOpt.
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000115bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000116 ImmutableCallSite CS(GetArgRCIdentityRoot(Retain));
Michael Gottesman214ca902013-04-29 06:53:53 +0000117 const Instruction *Call = CS.getInstruction();
118 if (!Call)
119 return false;
120 if (Call->getParent() != Retain->getParent())
121 return false;
122
123 // Check that the call is next to the retain.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000124 BasicBlock::const_iterator I = ++Call->getIterator();
125 while (IsNoopInstruction(&*I))
126 ++I;
Michael Gottesman214ca902013-04-29 06:53:53 +0000127 if (&*I != Retain)
128 return false;
129
130 // Turn it to an objc_retainAutoreleasedReturnValue.
131 Changed = true;
132 ++NumPeeps;
133
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000134 LLVM_DEBUG(
135 dbgs() << "Transforming objc_retain => "
136 "objc_retainAutoreleasedReturnValue since the operand is a "
137 "return value.\nOld: "
138 << *Retain << "\n");
Michael Gottesman214ca902013-04-29 06:53:53 +0000139
140 // We do not have to worry about tail calls/does not throw since
141 // retain/retainRV have the same properties.
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000142 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::RetainRV);
Michael Gottesman0b912b22013-07-06 01:39:26 +0000143 cast<CallInst>(Retain)->setCalledFunction(Decl);
Michael Gottesman214ca902013-04-29 06:53:53 +0000144
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000145 LLVM_DEBUG(dbgs() << "New: " << *Retain << "\n");
Michael Gottesman214ca902013-04-29 06:53:53 +0000146 return true;
147}
148
Michael Gottesman778138e2013-01-29 03:03:03 +0000149/// Merge an autorelease with a retain into a fused call.
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000150bool ObjCARCContract::contractAutorelease(
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000151 Function &F, Instruction *Autorelease, ARCInstKind Class,
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000152 SmallPtrSetImpl<Instruction *> &DependingInstructions,
153 SmallPtrSetImpl<const BasicBlock *> &Visited) {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000154 const Value *Arg = GetArgRCIdentityRoot(Autorelease);
Michael Gottesman778138e2013-01-29 03:03:03 +0000155
156 // Check that there are no instructions between the retain and the autorelease
157 // (such as an autorelease_pop) which may change the count.
Craig Topperf40110f2014-04-25 05:29:35 +0000158 CallInst *Retain = nullptr;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000159 if (Class == ARCInstKind::AutoreleaseRV)
Michael Gottesman778138e2013-01-29 03:03:03 +0000160 FindDependencies(RetainAutoreleaseRVDep, Arg,
161 Autorelease->getParent(), Autorelease,
162 DependingInstructions, Visited, PA);
163 else
164 FindDependencies(RetainAutoreleaseDep, Arg,
165 Autorelease->getParent(), Autorelease,
166 DependingInstructions, Visited, PA);
167
168 Visited.clear();
169 if (DependingInstructions.size() != 1) {
170 DependingInstructions.clear();
171 return false;
172 }
173
174 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
175 DependingInstructions.clear();
176
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000177 if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000178 GetArgRCIdentityRoot(Retain) != Arg)
Michael Gottesman778138e2013-01-29 03:03:03 +0000179 return false;
180
181 Changed = true;
182 ++NumPeeps;
183
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000184 LLVM_DEBUG(dbgs() << " Fusing retain/autorelease!\n"
185 " Autorelease:"
186 << *Autorelease
187 << "\n"
188 " Retain: "
189 << *Retain << "\n");
Michael Gottesman778138e2013-01-29 03:03:03 +0000190
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000191 Constant *Decl = EP.get(Class == ARCInstKind::AutoreleaseRV
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000192 ? ARCRuntimeEntryPointKind::RetainAutoreleaseRV
193 : ARCRuntimeEntryPointKind::RetainAutorelease);
Michael Gottesman0b912b22013-07-06 01:39:26 +0000194 Retain->setCalledFunction(Decl);
Michael Gottesman778138e2013-01-29 03:03:03 +0000195
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000196 LLVM_DEBUG(dbgs() << " New RetainAutorelease: " << *Retain << "\n");
Michael Gottesman778138e2013-01-29 03:03:03 +0000197
198 EraseInstruction(Autorelease);
199 return true;
200}
201
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000202static StoreInst *findSafeStoreForStoreStrongContraction(LoadInst *Load,
203 Instruction *Release,
204 ProvenanceAnalysis &PA,
205 AliasAnalysis *AA) {
Craig Topperf40110f2014-04-25 05:29:35 +0000206 StoreInst *Store = nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000207 bool SawRelease = false;
Michael Gottesman778138e2013-01-29 03:03:03 +0000208
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000209 // Get the location associated with Load.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000210 MemoryLocation Loc = MemoryLocation::get(Load);
Pete Cooper1929b552016-05-27 02:13:53 +0000211 auto *LocPtr = Loc.Ptr->stripPointerCasts();
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000212
213 // Walk down to find the store and the release, which may be in either order.
214 for (auto I = std::next(BasicBlock::iterator(Load)),
215 E = Load->getParent()->end();
216 I != E; ++I) {
217 // If we found the store we were looking for and saw the release,
218 // break. There is no more work to be done.
219 if (Store && SawRelease)
220 break;
221
222 // Now we know that we have not seen either the store or the release. If I
Eric Christopher572e03a2015-06-19 01:53:21 +0000223 // is the release, mark that we saw the release and continue.
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000224 Instruction *Inst = &*I;
Michael Gottesman778138e2013-01-29 03:03:03 +0000225 if (Inst == Release) {
226 SawRelease = true;
227 continue;
228 }
229
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000230 // Otherwise, we check if Inst is a "good" store. Grab the instruction class
231 // of Inst.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000232 ARCInstKind Class = GetBasicARCInstKind(Inst);
Michael Gottesman778138e2013-01-29 03:03:03 +0000233
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000234 // If Inst is an unrelated retain, we don't care about it.
235 //
236 // TODO: This is one area where the optimization could be made more
237 // aggressive.
Michael Gottesman778138e2013-01-29 03:03:03 +0000238 if (IsRetain(Class))
239 continue;
240
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000241 // If we have seen the store, but not the release...
Michael Gottesman778138e2013-01-29 03:03:03 +0000242 if (Store) {
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000243 // We need to make sure that it is safe to move the release from its
244 // current position to the store. This implies proving that any
245 // instruction in between Store and the Release conservatively can not use
246 // the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
247 // continue...
248 if (!CanUse(Inst, Load, PA, Class)) {
249 continue;
250 }
251
252 // Otherwise, be conservative and return nullptr.
253 return nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000254 }
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000255
256 // Ok, now we know we have not seen a store yet. See if Inst can write to
257 // our load location, if it can not, just ignore the instruction.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000258 if (!isModSet(AA->getModRefInfo(Inst, Loc)))
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000259 continue;
260
261 Store = dyn_cast<StoreInst>(Inst);
262
263 // If Inst can, then check if Inst is a simple store. If Inst is not a
264 // store or a store that is not simple, then we have some we do not
265 // understand writing to this memory implying we can not move the load
266 // over the write to any subsequent store that we may find.
267 if (!Store || !Store->isSimple())
268 return nullptr;
269
270 // Then make sure that the pointer we are storing to is Ptr. If so, we
271 // found our Store!
Pete Cooper1929b552016-05-27 02:13:53 +0000272 if (Store->getPointerOperand()->stripPointerCasts() == LocPtr)
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000273 continue;
274
275 // Otherwise, we have an unknown store to some other ptr that clobbers
276 // Loc.Ptr. Bail!
277 return nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000278 }
279
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000280 // If we did not find the store or did not see the release, fail.
281 if (!Store || !SawRelease)
282 return nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000283
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000284 // We succeeded!
285 return Store;
286}
287
288static Instruction *
289findRetainForStoreStrongContraction(Value *New, StoreInst *Store,
290 Instruction *Release,
291 ProvenanceAnalysis &PA) {
292 // Walk up from the Store to find the retain.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000293 BasicBlock::iterator I = Store->getIterator();
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000294 BasicBlock::iterator Begin = Store->getParent()->begin();
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000295 while (I != Begin && GetBasicARCInstKind(&*I) != ARCInstKind::Retain) {
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000296 Instruction *Inst = &*I;
297
298 // It is only safe to move the retain to the store if we can prove
299 // conservatively that nothing besides the release can decrement reference
300 // counts in between the retain and the store.
301 if (CanDecrementRefCount(Inst, New, PA) && Inst != Release)
302 return nullptr;
Michael Gottesman778138e2013-01-29 03:03:03 +0000303 --I;
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000304 }
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000305 Instruction *Retain = &*I;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000306 if (GetBasicARCInstKind(Retain) != ARCInstKind::Retain)
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000307 return nullptr;
308 if (GetArgRCIdentityRoot(Retain) != New)
309 return nullptr;
310 return Retain;
311}
312
Shoaib Meenaid64b8322018-04-20 22:11:03 +0000313/// Create a call instruction with the correct funclet token. Should be used
314/// instead of calling CallInst::Create directly.
315static CallInst *
James Y Knight7976eb52019-02-01 20:43:25 +0000316createCallInst(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
317 const Twine &NameStr, Instruction *InsertBefore,
Shoaib Meenaid64b8322018-04-20 22:11:03 +0000318 const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
319 SmallVector<OperandBundleDef, 1> OpBundles;
320 if (!BlockColors.empty()) {
321 const ColorVector &CV = BlockColors.find(InsertBefore->getParent())->second;
322 assert(CV.size() == 1 && "non-unique color for block!");
323 Instruction *EHPad = CV.front()->getFirstNonPHI();
324 if (EHPad->isEHPad())
325 OpBundles.emplace_back("funclet", EHPad);
326 }
327
James Y Knight7976eb52019-02-01 20:43:25 +0000328 return CallInst::Create(FTy, Func, Args, OpBundles, NameStr, InsertBefore);
329}
330
331static CallInst *
332createCallInst(FunctionCallee Func, ArrayRef<Value *> Args, const Twine &NameStr,
333 Instruction *InsertBefore,
334 const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
335 return createCallInst(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
336 InsertBefore, BlockColors);
Shoaib Meenaid64b8322018-04-20 22:11:03 +0000337}
338
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000339/// Attempt to merge an objc_release with a store, load, and objc_retain to form
340/// an objc_storeStrong. An objc_storeStrong:
341///
342/// objc_storeStrong(i8** %old_ptr, i8* new_value)
343///
344/// is equivalent to the following IR sequence:
345///
346/// ; Load old value.
347/// %old_value = load i8** %old_ptr (1)
348///
349/// ; Increment the new value and then release the old value. This must occur
350/// ; in order in case old_value releases new_value in its destructor causing
351/// ; us to potentially have a dangling ptr.
352/// tail call i8* @objc_retain(i8* %new_value) (2)
353/// tail call void @objc_release(i8* %old_value) (3)
354///
355/// ; Store the new_value into old_ptr
356/// store i8* %new_value, i8** %old_ptr (4)
357///
358/// The safety of this optimization is based around the following
359/// considerations:
360///
361/// 1. We are forming the store strong at the store. Thus to perform this
362/// optimization it must be safe to move the retain, load, and release to
363/// (4).
364/// 2. We need to make sure that any re-orderings of (1), (2), (3), (4) are
365/// safe.
Shoaib Meenaid64b8322018-04-20 22:11:03 +0000366void ObjCARCContract::tryToContractReleaseIntoStoreStrong(
367 Instruction *Release, inst_iterator &Iter,
368 const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000369 // See if we are releasing something that we just loaded.
370 auto *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
371 if (!Load || !Load->isSimple())
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000372 return;
Michael Gottesman0fc2acc2015-02-20 00:02:49 +0000373
374 // For now, require everything to be in one basic block.
375 BasicBlock *BB = Release->getParent();
376 if (Load->getParent() != BB)
377 return;
378
379 // First scan down the BB from Load, looking for a store of the RCIdentityRoot
380 // of Load's
381 StoreInst *Store =
382 findSafeStoreForStoreStrongContraction(Load, Release, PA, AA);
383 // If we fail, bail.
384 if (!Store)
385 return;
386
387 // Then find what new_value's RCIdentity Root is.
388 Value *New = GetRCIdentityRoot(Store->getValueOperand());
389
390 // Then walk up the BB and look for a retain on New without any intervening
391 // instructions which conservatively might decrement ref counts.
392 Instruction *Retain =
393 findRetainForStoreStrongContraction(New, Store, Release, PA);
394
395 // If we fail, bail.
396 if (!Retain)
397 return;
Michael Gottesman778138e2013-01-29 03:03:03 +0000398
399 Changed = true;
400 ++NumStoreStrongs;
401
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000402 LLVM_DEBUG(
Michael Gottesman18279732015-02-19 00:42:30 +0000403 llvm::dbgs() << " Contracting retain, release into objc_storeStrong.\n"
404 << " Old:\n"
405 << " Store: " << *Store << "\n"
406 << " Release: " << *Release << "\n"
407 << " Retain: " << *Retain << "\n"
408 << " Load: " << *Load << "\n");
409
Michael Gottesman778138e2013-01-29 03:03:03 +0000410 LLVMContext &C = Release->getContext();
411 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
412 Type *I8XX = PointerType::getUnqual(I8X);
413
414 Value *Args[] = { Load->getPointerOperand(), New };
415 if (Args[0]->getType() != I8XX)
416 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
417 if (Args[1]->getType() != I8X)
418 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
James Y Knight7976eb52019-02-01 20:43:25 +0000419 Function *Decl = EP.get(ARCRuntimeEntryPointKind::StoreStrong);
Shoaib Meenaid64b8322018-04-20 22:11:03 +0000420 CallInst *StoreStrong = createCallInst(Decl, Args, "", Store, BlockColors);
Michael Gottesman778138e2013-01-29 03:03:03 +0000421 StoreStrong->setDoesNotThrow();
422 StoreStrong->setDebugLoc(Store->getDebugLoc());
423
424 // We can't set the tail flag yet, because we haven't yet determined
425 // whether there are any escaping allocas. Remember this call, so that
426 // we can set the tail flag once we know it's safe.
427 StoreStrongCalls.insert(StoreStrong);
428
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000429 LLVM_DEBUG(llvm::dbgs() << " New Store Strong: " << *StoreStrong
430 << "\n");
Michael Gottesman18279732015-02-19 00:42:30 +0000431
Akira Hatanaka75be84f2017-04-05 03:44:09 +0000432 if (&*Iter == Retain) ++Iter;
Michael Gottesman778138e2013-01-29 03:03:03 +0000433 if (&*Iter == Store) ++Iter;
434 Store->eraseFromParent();
435 Release->eraseFromParent();
436 EraseInstruction(Retain);
437 if (Load->use_empty())
438 Load->eraseFromParent();
439}
440
Michael Gottesman18279732015-02-19 00:42:30 +0000441bool ObjCARCContract::tryToPeepholeInstruction(
442 Function &F, Instruction *Inst, inst_iterator &Iter,
443 SmallPtrSetImpl<Instruction *> &DependingInsts,
444 SmallPtrSetImpl<const BasicBlock *> &Visited,
Shoaib Meenai3f689c82018-03-20 20:45:41 +0000445 bool &TailOkForStoreStrongs,
Shoaib Meenai106df7d2018-04-20 22:14:45 +0000446 const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000447 // Only these library routines return their argument. In particular,
448 // objc_retainBlock does not necessarily return its argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000449 ARCInstKind Class = GetBasicARCInstKind(Inst);
Michael Gottesman778138e2013-01-29 03:03:03 +0000450 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000451 case ARCInstKind::FusedRetainAutorelease:
452 case ARCInstKind::FusedRetainAutoreleaseRV:
Michael Gottesman18279732015-02-19 00:42:30 +0000453 return false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000454 case ARCInstKind::Autorelease:
455 case ARCInstKind::AutoreleaseRV:
Michael Gottesman18279732015-02-19 00:42:30 +0000456 return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000457 case ARCInstKind::Retain:
Michael Gottesman214ca902013-04-29 06:53:53 +0000458 // Attempt to convert retains to retainrvs if they are next to function
459 // calls.
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000460 if (!optimizeRetainCall(F, Inst))
Michael Gottesman18279732015-02-19 00:42:30 +0000461 return false;
Michael Gottesman214ca902013-04-29 06:53:53 +0000462 // If we succeed in our optimization, fall through.
Justin Bognerb03fd122016-08-17 05:10:15 +0000463 LLVM_FALLTHROUGH;
John McCall3fe604f2016-01-27 19:05:08 +0000464 case ARCInstKind::RetainRV:
465 case ARCInstKind::ClaimRV: {
Michael Gottesman778138e2013-01-29 03:03:03 +0000466 // If we're compiling for a target which needs a special inline-asm
John McCall3fe604f2016-01-27 19:05:08 +0000467 // marker to do the return value optimization, insert it now.
468 if (!RVInstMarker)
Michael Gottesman18279732015-02-19 00:42:30 +0000469 return false;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000470 BasicBlock::iterator BBI = Inst->getIterator();
Michael Gottesman778138e2013-01-29 03:03:03 +0000471 BasicBlock *InstParent = Inst->getParent();
472
John McCall3fe604f2016-01-27 19:05:08 +0000473 // Step up to see if the call immediately precedes the RV call.
Michael Gottesman778138e2013-01-29 03:03:03 +0000474 // If it's an invoke, we have to cross a block boundary. And we have
475 // to carefully dodge no-op instructions.
476 do {
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +0000477 if (BBI == InstParent->begin()) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000478 BasicBlock *Pred = InstParent->getSinglePredecessor();
479 if (!Pred)
480 goto decline_rv_optimization;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000481 BBI = Pred->getTerminator()->getIterator();
Michael Gottesman778138e2013-01-29 03:03:03 +0000482 break;
483 }
484 --BBI;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000485 } while (IsNoopInstruction(&*BBI));
Michael Gottesman778138e2013-01-29 03:03:03 +0000486
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000487 if (&*BBI == GetArgRCIdentityRoot(Inst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000488 LLVM_DEBUG(dbgs() << "Adding inline asm marker for the return value "
489 "optimization.\n");
Michael Gottesman778138e2013-01-29 03:03:03 +0000490 Changed = true;
John McCall3fe604f2016-01-27 19:05:08 +0000491 InlineAsm *IA = InlineAsm::get(
492 FunctionType::get(Type::getVoidTy(Inst->getContext()),
493 /*isVarArg=*/false),
494 RVInstMarker->getString(),
495 /*Constraints=*/"", /*hasSideEffects=*/true);
Shoaib Meenai3f689c82018-03-20 20:45:41 +0000496
Shoaib Meenaid64b8322018-04-20 22:11:03 +0000497 createCallInst(IA, None, "", Inst, BlockColors);
Michael Gottesman778138e2013-01-29 03:03:03 +0000498 }
499 decline_rv_optimization:
Michael Gottesman18279732015-02-19 00:42:30 +0000500 return false;
Michael Gottesman778138e2013-01-29 03:03:03 +0000501 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000502 case ARCInstKind::InitWeak: {
Michael Gottesman778138e2013-01-29 03:03:03 +0000503 // objc_initWeak(p, null) => *p = null
504 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000505 if (IsNullOrUndef(CI->getArgOperand(1))) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000506 Value *Null =
507 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
508 Changed = true;
509 new StoreInst(Null, CI->getArgOperand(0), CI);
510
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000511 LLVM_DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
512 << " New = " << *Null << "\n");
Michael Gottesman778138e2013-01-29 03:03:03 +0000513
514 CI->replaceAllUsesWith(Null);
515 CI->eraseFromParent();
516 }
Michael Gottesman18279732015-02-19 00:42:30 +0000517 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000518 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000519 case ARCInstKind::Release:
Michael Gottesmandfa3e4b2015-02-19 00:42:34 +0000520 // Try to form an objc store strong from our release. If we fail, there is
521 // nothing further to do below, so continue.
Shoaib Meenaid64b8322018-04-20 22:11:03 +0000522 tryToContractReleaseIntoStoreStrong(Inst, Iter, BlockColors);
Michael Gottesman18279732015-02-19 00:42:30 +0000523 return true;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000524 case ARCInstKind::User:
Michael Gottesman778138e2013-01-29 03:03:03 +0000525 // Be conservative if the function has any alloca instructions.
526 // Technically we only care about escaping alloca instructions,
527 // but this is sufficient to handle some interesting cases.
528 if (isa<AllocaInst>(Inst))
529 TailOkForStoreStrongs = false;
Michael Gottesman18279732015-02-19 00:42:30 +0000530 return true;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000531 case ARCInstKind::IntrinsicUser:
Pete Cooperbe4f5712018-12-18 20:32:49 +0000532 // Remove calls to @llvm.objc.clang.arc.use(...).
John McCall20182ac2013-03-22 21:38:36 +0000533 Inst->eraseFromParent();
Michael Gottesman18279732015-02-19 00:42:30 +0000534 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000535 default:
Michael Gottesman18279732015-02-19 00:42:30 +0000536 return true;
Michael Gottesman778138e2013-01-29 03:03:03 +0000537 }
Michael Gottesman18279732015-02-19 00:42:30 +0000538}
Michael Gottesman778138e2013-01-29 03:03:03 +0000539
Michael Gottesman18279732015-02-19 00:42:30 +0000540//===----------------------------------------------------------------------===//
541// Top Level Driver
542//===----------------------------------------------------------------------===//
543
544bool ObjCARCContract::runOnFunction(Function &F) {
545 if (!EnableARCOpts)
546 return false;
547
548 // If nothing in the Module uses ARC, don't do anything.
549 if (!Run)
550 return false;
551
552 Changed = false;
Chandler Carruth7b560d42015-09-09 17:55:00 +0000553 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Michael Gottesman18279732015-02-19 00:42:30 +0000554 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
555
Chandler Carruth7b560d42015-09-09 17:55:00 +0000556 PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
Michael Gottesman18279732015-02-19 00:42:30 +0000557
Shoaib Meenai3f689c82018-03-20 20:45:41 +0000558 DenseMap<BasicBlock *, ColorVector> BlockColors;
559 if (F.hasPersonalityFn() &&
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000560 isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
Shoaib Meenai3f689c82018-03-20 20:45:41 +0000561 BlockColors = colorEHFunclets(F);
562
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000563 LLVM_DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
Michael Gottesman18279732015-02-19 00:42:30 +0000564
565 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
566 // keyword. Be conservative if the function has variadic arguments.
567 // It seems that functions which "return twice" are also unsafe for the
568 // "tail" argument, because they are setjmp, which could need to
569 // return to an earlier stack state.
570 bool TailOkForStoreStrongs =
571 !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
572
573 // For ObjC library calls which return their argument, replace uses of the
574 // argument with uses of the call return value, if it dominates the use. This
575 // reduces register pressure.
576 SmallPtrSet<Instruction *, 4> DependingInstructions;
577 SmallPtrSet<const BasicBlock *, 4> Visited;
578 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
579 Instruction *Inst = &*I++;
580
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000581 LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman18279732015-02-19 00:42:30 +0000582
583 // First try to peephole Inst. If there is nothing further we can do in
584 // terms of undoing objc-arc-expand, process the next inst.
585 if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
Shoaib Meenai3f689c82018-03-20 20:45:41 +0000586 TailOkForStoreStrongs, BlockColors))
Michael Gottesman18279732015-02-19 00:42:30 +0000587 continue;
588
589 // Otherwise, try to undo objc-arc-expand.
Michael Gottesman778138e2013-01-29 03:03:03 +0000590
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000591 // Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
Michael Gottesman778138e2013-01-29 03:03:03 +0000592 // and such; to do the replacement, the argument must have type i8*.
Michael Gottesman18279732015-02-19 00:42:30 +0000593
Akira Hatanakadea090e2016-09-13 23:43:11 +0000594 // Function for replacing uses of Arg dominated by Inst.
595 auto ReplaceArgUses = [Inst, this](Value *Arg) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000596 // If we're compiling bugpointed code, don't get in trouble.
597 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
Akira Hatanakadea090e2016-09-13 23:43:11 +0000598 return;
599
Michael Gottesman778138e2013-01-29 03:03:03 +0000600 // Look through the uses of the pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000601 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
Michael Gottesman778138e2013-01-29 03:03:03 +0000602 UI != UE; ) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000603 // Increment UI now, because we may unlink its element.
604 Use &U = *UI++;
605 unsigned OperandNo = U.getOperandNo();
Michael Gottesman778138e2013-01-29 03:03:03 +0000606
607 // If the call's return value dominates a use of the call's argument
608 // value, rewrite the use to use the return value. We check for
609 // reachability here because an unreachable call is considered to
610 // trivially dominate itself, which would lead us to rewriting its
611 // argument in terms of its return value, which would lead to
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000612 // infinite loops in GetArgRCIdentityRoot.
Shoaib Meenaia07295f2018-05-03 01:20:36 +0000613 if (!DT->isReachableFromEntry(U) || !DT->dominates(Inst, U))
614 continue;
615
616 Changed = true;
617 Instruction *Replacement = Inst;
618 Type *UseTy = U.get()->getType();
619 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
620 // For PHI nodes, insert the bitcast in the predecessor block.
621 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
Shoaib Meenai57fadab2018-05-04 19:03:11 +0000622 BasicBlock *IncomingBB = PHI->getIncomingBlock(ValNo);
623 if (Replacement->getType() != UseTy) {
624 // A catchswitch is both a pad and a terminator, meaning a basic
625 // block with a catchswitch has no insertion point. Keep going up
626 // the dominator tree until we find a non-catchswitch.
627 BasicBlock *InsertBB = IncomingBB;
628 while (isa<CatchSwitchInst>(InsertBB->getFirstNonPHI())) {
629 InsertBB = DT->getNode(InsertBB)->getIDom()->getBlock();
630 }
631
632 assert(DT->dominates(Inst, &InsertBB->back()) &&
633 "Invalid insertion point for bitcast");
634 Replacement =
635 new BitCastInst(Replacement, UseTy, "", &InsertBB->back());
636 }
637
Shoaib Meenaia07295f2018-05-03 01:20:36 +0000638 // While we're here, rewrite all edges for this PHI, rather
639 // than just one use at a time, to minimize the number of
640 // bitcasts we emit.
641 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Shoaib Meenai57fadab2018-05-04 19:03:11 +0000642 if (PHI->getIncomingBlock(i) == IncomingBB) {
Shoaib Meenaia07295f2018-05-03 01:20:36 +0000643 // Keep the UI iterator valid.
644 if (UI != UE &&
645 &PHI->getOperandUse(
646 PHINode::getOperandNumForIncomingValue(i)) == &*UI)
647 ++UI;
648 PHI->setIncomingValue(i, Replacement);
649 }
650 } else {
651 if (Replacement->getType() != UseTy)
652 Replacement = new BitCastInst(Replacement, UseTy, "",
653 cast<Instruction>(U.getUser()));
654 U.set(Replacement);
Michael Gottesman778138e2013-01-29 03:03:03 +0000655 }
656 }
Akira Hatanakadea090e2016-09-13 23:43:11 +0000657 };
658
659
Akira Hatanaka6d5a2942016-09-13 23:53:43 +0000660 Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
661 Value *OrigArg = Arg;
Akira Hatanakadea090e2016-09-13 23:43:11 +0000662
663 // TODO: Change this to a do-while.
664 for (;;) {
665 ReplaceArgUses(Arg);
Michael Gottesman778138e2013-01-29 03:03:03 +0000666
667 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
668 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
669 Arg = BI->getOperand(0);
670 else if (isa<GEPOperator>(Arg) &&
671 cast<GEPOperator>(Arg)->hasAllZeroIndices())
672 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
673 else if (isa<GlobalAlias>(Arg) &&
Sanjoy Das5ce32722016-04-08 00:48:30 +0000674 !cast<GlobalAlias>(Arg)->isInterposable())
Michael Gottesman778138e2013-01-29 03:03:03 +0000675 Arg = cast<GlobalAlias>(Arg)->getAliasee();
Akira Hatanaka73ceb502018-01-19 23:51:13 +0000676 else {
677 // If Arg is a PHI node, get PHIs that are equivalent to it and replace
678 // their uses.
679 if (PHINode *PN = dyn_cast<PHINode>(Arg)) {
680 SmallVector<Value *, 1> PHIList;
681 getEquivalentPHIs(*PN, PHIList);
682 for (Value *PHI : PHIList)
683 ReplaceArgUses(PHI);
684 }
Michael Gottesman778138e2013-01-29 03:03:03 +0000685 break;
Akira Hatanaka73ceb502018-01-19 23:51:13 +0000686 }
Michael Gottesman778138e2013-01-29 03:03:03 +0000687 }
Akira Hatanakadea090e2016-09-13 23:43:11 +0000688
689 // Replace bitcast users of Arg that are dominated by Inst.
690 SmallVector<BitCastInst *, 2> BitCastUsers;
691
692 // Add all bitcast users of the function argument first.
693 for (User *U : OrigArg->users())
694 if (auto *BC = dyn_cast<BitCastInst>(U))
695 BitCastUsers.push_back(BC);
696
697 // Replace the bitcasts with the call return. Iterate until list is empty.
698 while (!BitCastUsers.empty()) {
699 auto *BC = BitCastUsers.pop_back_val();
700 for (User *U : BC->users())
701 if (auto *B = dyn_cast<BitCastInst>(U))
702 BitCastUsers.push_back(B);
703
704 ReplaceArgUses(BC);
705 }
Michael Gottesman778138e2013-01-29 03:03:03 +0000706 }
707
708 // If this function has no escaping allocas or suspicious vararg usage,
709 // objc_storeStrong calls can be marked with the "tail" keyword.
710 if (TailOkForStoreStrongs)
Craig Topper46276792014-08-24 23:23:06 +0000711 for (CallInst *CI : StoreStrongCalls)
712 CI->setTailCall();
Michael Gottesman778138e2013-01-29 03:03:03 +0000713 StoreStrongCalls.clear();
714
715 return Changed;
716}
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000717
718//===----------------------------------------------------------------------===//
719// Misc Pass Manager
720//===----------------------------------------------------------------------===//
721
722char ObjCARCContract::ID = 0;
723INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract",
724 "ObjC ARC contraction", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000725INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000726INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
727INITIALIZE_PASS_END(ObjCARCContract, "objc-arc-contract",
728 "ObjC ARC contraction", false, false)
729
730void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000731 AU.addRequired<AAResultsWrapperPass>();
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000732 AU.addRequired<DominatorTreeWrapperPass>();
733 AU.setPreservesCFG();
734}
735
736Pass *llvm::createObjCARCContractPass() { return new ObjCARCContract(); }
737
738bool ObjCARCContract::doInitialization(Module &M) {
739 // If nothing in the Module uses ARC, don't do anything.
740 Run = ModuleHasARC(M);
741 if (!Run)
742 return false;
743
Michael Gottesman65cb7372015-03-16 07:02:27 +0000744 EP.init(&M);
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000745
John McCall3fe604f2016-01-27 19:05:08 +0000746 // Initialize RVInstMarker.
747 RVInstMarker = nullptr;
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000748 if (NamedMDNode *NMD =
749 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
750 if (NMD->getNumOperands() == 1) {
751 const MDNode *N = NMD->getOperand(0);
752 if (N->getNumOperands() == 1)
753 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
John McCall3fe604f2016-01-27 19:05:08 +0000754 RVInstMarker = S;
Michael Gottesman56bd6a02015-02-19 00:42:27 +0000755 }
756
757 return false;
758}