LLVM 20.0.0git
ObjCARCContract.cpp
Go to the documentation of this file.
1//===- ObjCARCContract.cpp - ObjC ARC Optimization ------------------------===//
2//
3// 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
6//
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///
13/// This specific file mainly deals with ``contracting'' multiple lower level
14/// operations into singular higher level operations through pattern matching.
15///
16/// 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
29#include "DependencyAnalysis.h"
30#include "ObjCARC.h"
31#include "ProvenanceAnalysis.h"
32#include "llvm/ADT/Statistic.h"
36#include "llvm/IR/Dominators.h"
38#include "llvm/IR/InlineAsm.h"
40#include "llvm/IR/Operator.h"
41#include "llvm/IR/PassManager.h"
43#include "llvm/Support/Debug.h"
46
47using namespace llvm;
48using namespace llvm::objcarc;
49
50#define DEBUG_TYPE "objc-arc-contract"
51
52STATISTIC(NumPeeps, "Number of calls peephole-optimized");
53STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
54
55//===----------------------------------------------------------------------===//
56// Declarations
57//===----------------------------------------------------------------------===//
58
59namespace {
60/// Late ARC optimizations
61///
62/// These change the IR in a way that makes it difficult to be analyzed by
63/// ObjCARCOpt, so it's run late.
64
65class ObjCARCContract {
66 bool Changed;
67 bool CFGChanged;
68 AAResults *AA;
69 DominatorTree *DT;
72 BundledRetainClaimRVs *BundledInsts = nullptr;
73
74 /// A flag indicating whether this optimization pass should run.
75 bool Run;
76
77 /// The inline asm string to insert between calls and RetainRV calls to make
78 /// the optimization work on targets which need it.
79 const MDString *RVInstMarker;
80
81 /// The set of inserted objc_storeStrong calls. If at the end of walking the
82 /// function we have found no alloca instructions, these calls can be marked
83 /// "tail".
84 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
85
86 /// Returns true if we eliminated Inst.
87 bool tryToPeepholeInstruction(
88 Function &F, Instruction *Inst, inst_iterator &Iter,
89 bool &TailOkForStoreStrong,
90 const DenseMap<BasicBlock *, ColorVector> &BlockColors);
91
92 bool optimizeRetainCall(Function &F, Instruction *Retain);
93
94 bool contractAutorelease(Function &F, Instruction *Autorelease,
95 ARCInstKind Class);
96
97 void tryToContractReleaseIntoStoreStrong(
99 const DenseMap<BasicBlock *, ColorVector> &BlockColors);
100
101public:
102 bool init(Module &M);
103 bool run(Function &F, AAResults *AA, DominatorTree *DT);
104 bool hasCFGChanged() const { return CFGChanged; }
105};
106
107class ObjCARCContractLegacyPass : public FunctionPass {
108public:
109 void getAnalysisUsage(AnalysisUsage &AU) const override;
110 bool runOnFunction(Function &F) override;
111
112 static char ID;
113 ObjCARCContractLegacyPass() : FunctionPass(ID) {
115 }
116};
117}
118
119//===----------------------------------------------------------------------===//
120// Implementation
121//===----------------------------------------------------------------------===//
122
123/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
124/// return value. We do this late so we do not disrupt the dataflow analysis in
125/// ObjCARCOpt.
126bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
127 const auto *Call = dyn_cast<CallBase>(GetArgRCIdentityRoot(Retain));
128 if (!Call)
129 return false;
130 if (Call->getParent() != Retain->getParent())
131 return false;
132
133 // Check that the call is next to the retain.
134 BasicBlock::const_iterator I = ++Call->getIterator();
135 while (IsNoopInstruction(&*I))
136 ++I;
137 if (&*I != Retain)
138 return false;
139
140 // Turn it to an objc_retainAutoreleasedReturnValue.
141 Changed = true;
142 ++NumPeeps;
143
145 dbgs() << "Transforming objc_retain => "
146 "objc_retainAutoreleasedReturnValue since the operand is a "
147 "return value.\nOld: "
148 << *Retain << "\n");
149
150 // We do not have to worry about tail calls/does not throw since
151 // retain/retainRV have the same properties.
152 Function *Decl = EP.get(ARCRuntimeEntryPointKind::RetainRV);
153 cast<CallInst>(Retain)->setCalledFunction(Decl);
154
155 LLVM_DEBUG(dbgs() << "New: " << *Retain << "\n");
156 return true;
157}
158
159/// Merge an autorelease with a retain into a fused call.
160bool ObjCARCContract::contractAutorelease(Function &F, Instruction *Autorelease,
161 ARCInstKind Class) {
163
164 // Check that there are no instructions between the retain and the autorelease
165 // (such as an autorelease_pop) which may change the count.
166 DependenceKind DK = Class == ARCInstKind::AutoreleaseRV
169 auto *Retain = dyn_cast_or_null<CallInst>(
170 findSingleDependency(DK, Arg, Autorelease->getParent(), Autorelease, PA));
171
172 if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
174 return false;
175
176 Changed = true;
177 ++NumPeeps;
178
179 LLVM_DEBUG(dbgs() << " Fusing retain/autorelease!\n"
180 " Autorelease:"
181 << *Autorelease
182 << "\n"
183 " Retain: "
184 << *Retain << "\n");
185
186 Function *Decl = EP.get(Class == ARCInstKind::AutoreleaseRV
187 ? ARCRuntimeEntryPointKind::RetainAutoreleaseRV
188 : ARCRuntimeEntryPointKind::RetainAutorelease);
189 Retain->setCalledFunction(Decl);
190
191 LLVM_DEBUG(dbgs() << " New RetainAutorelease: " << *Retain << "\n");
192
194 return true;
195}
196
200 AAResults *AA) {
201 StoreInst *Store = nullptr;
202 bool SawRelease = false;
203
204 // Get the location associated with Load.
206 auto *LocPtr = Loc.Ptr->stripPointerCasts();
207
208 // Walk down to find the store and the release, which may be in either order.
209 for (auto I = std::next(BasicBlock::iterator(Load)),
210 E = Load->getParent()->end();
211 I != E; ++I) {
212 // If we found the store we were looking for and saw the release,
213 // break. There is no more work to be done.
214 if (Store && SawRelease)
215 break;
216
217 // Now we know that we have not seen either the store or the release. If I
218 // is the release, mark that we saw the release and continue.
219 Instruction *Inst = &*I;
220 if (Inst == Release) {
221 SawRelease = true;
222 continue;
223 }
224
225 // Otherwise, we check if Inst is a "good" store. Grab the instruction class
226 // of Inst.
227 ARCInstKind Class = GetBasicARCInstKind(Inst);
228
229 // If we have seen the store, but not the release...
230 if (Store) {
231 // We need to make sure that it is safe to move the release from its
232 // current position to the store. This implies proving that any
233 // instruction in between Store and the Release conservatively can not use
234 // the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
235 // continue...
236 if (!CanUse(Inst, Load, PA, Class)) {
237 continue;
238 }
239
240 // Otherwise, be conservative and return nullptr.
241 return nullptr;
242 }
243
244 // Ok, now we know we have not seen a store yet.
245
246 // If Inst is a retain, we don't care about it as it doesn't prevent moving
247 // the load to the store.
248 //
249 // TODO: This is one area where the optimization could be made more
250 // aggressive.
251 if (IsRetain(Class))
252 continue;
253
254 // See if Inst can write to our load location, if it can not, just ignore
255 // the instruction.
256 if (!isModSet(AA->getModRefInfo(Inst, Loc)))
257 continue;
258
259 Store = dyn_cast<StoreInst>(Inst);
260
261 // If Inst can, then check if Inst is a simple store. If Inst is not a
262 // store or a store that is not simple, then we have some we do not
263 // understand writing to this memory implying we can not move the load
264 // over the write to any subsequent store that we may find.
265 if (!Store || !Store->isSimple())
266 return nullptr;
267
268 // Then make sure that the pointer we are storing to is Ptr. If so, we
269 // found our Store!
270 if (Store->getPointerOperand()->stripPointerCasts() == LocPtr)
271 continue;
272
273 // Otherwise, we have an unknown store to some other ptr that clobbers
274 // Loc.Ptr. Bail!
275 return nullptr;
276 }
277
278 // If we did not find the store or did not see the release, fail.
279 if (!Store || !SawRelease)
280 return nullptr;
281
282 // We succeeded!
283 return Store;
284}
285
286static Instruction *
289 ProvenanceAnalysis &PA) {
290 // Walk up from the Store to find the retain.
291 BasicBlock::iterator I = Store->getIterator();
292 BasicBlock::iterator Begin = Store->getParent()->begin();
293 while (I != Begin && GetBasicARCInstKind(&*I) != ARCInstKind::Retain) {
294 Instruction *Inst = &*I;
295
296 // It is only safe to move the retain to the store if we can prove
297 // conservatively that nothing besides the release can decrement reference
298 // counts in between the retain and the store.
299 if (CanDecrementRefCount(Inst, New, PA) && Inst != Release)
300 return nullptr;
301 --I;
302 }
303 Instruction *Retain = &*I;
304 if (GetBasicARCInstKind(Retain) != ARCInstKind::Retain)
305 return nullptr;
306 if (GetArgRCIdentityRoot(Retain) != New)
307 return nullptr;
308 return Retain;
309}
310
311/// Attempt to merge an objc_release with a store, load, and objc_retain to form
312/// an objc_storeStrong. An objc_storeStrong:
313///
314/// objc_storeStrong(i8** %old_ptr, i8* new_value)
315///
316/// is equivalent to the following IR sequence:
317///
318/// ; Load old value.
319/// %old_value = load i8** %old_ptr (1)
320///
321/// ; Increment the new value and then release the old value. This must occur
322/// ; in order in case old_value releases new_value in its destructor causing
323/// ; us to potentially have a dangling ptr.
324/// tail call i8* @objc_retain(i8* %new_value) (2)
325/// tail call void @objc_release(i8* %old_value) (3)
326///
327/// ; Store the new_value into old_ptr
328/// store i8* %new_value, i8** %old_ptr (4)
329///
330/// The safety of this optimization is based around the following
331/// considerations:
332///
333/// 1. We are forming the store strong at the store. Thus to perform this
334/// optimization it must be safe to move the retain, load, and release to
335/// (4).
336/// 2. We need to make sure that any re-orderings of (1), (2), (3), (4) are
337/// safe.
338void ObjCARCContract::tryToContractReleaseIntoStoreStrong(
340 const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
341 // See if we are releasing something that we just loaded.
342 auto *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
343 if (!Load || !Load->isSimple())
344 return;
345
346 // For now, require everything to be in one basic block.
347 BasicBlock *BB = Release->getParent();
348 if (Load->getParent() != BB)
349 return;
350
351 // First scan down the BB from Load, looking for a store of the RCIdentityRoot
352 // of Load's
355 // If we fail, bail.
356 if (!Store)
357 return;
358
359 // Then find what new_value's RCIdentity Root is.
360 Value *New = GetRCIdentityRoot(Store->getValueOperand());
361
362 // Then walk up the BB and look for a retain on New without any intervening
363 // instructions which conservatively might decrement ref counts.
366
367 // If we fail, bail.
368 if (!Retain)
369 return;
370
371 Changed = true;
372 ++NumStoreStrongs;
373
375 llvm::dbgs() << " Contracting retain, release into objc_storeStrong.\n"
376 << " Old:\n"
377 << " Store: " << *Store << "\n"
378 << " Release: " << *Release << "\n"
379 << " Retain: " << *Retain << "\n"
380 << " Load: " << *Load << "\n");
381
382 LLVMContext &C = Release->getContext();
383 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
384 Type *I8XX = PointerType::getUnqual(I8X);
385
386 Value *Args[] = { Load->getPointerOperand(), New };
387 if (Args[0]->getType() != I8XX)
388 Args[0] = new BitCastInst(Args[0], I8XX, "", Store->getIterator());
389 if (Args[1]->getType() != I8X)
390 Args[1] = new BitCastInst(Args[1], I8X, "", Store->getIterator());
391 Function *Decl = EP.get(ARCRuntimeEntryPointKind::StoreStrong);
393 Decl, Args, "", Store->getIterator(), BlockColors);
394 StoreStrong->setDoesNotThrow();
395 StoreStrong->setDebugLoc(Store->getDebugLoc());
396
397 // We can't set the tail flag yet, because we haven't yet determined
398 // whether there are any escaping allocas. Remember this call, so that
399 // we can set the tail flag once we know it's safe.
400 StoreStrongCalls.insert(StoreStrong);
401
402 LLVM_DEBUG(llvm::dbgs() << " New Store Strong: " << *StoreStrong
403 << "\n");
404
405 if (&*Iter == Retain) ++Iter;
406 if (&*Iter == Store) ++Iter;
407 Store->eraseFromParent();
408 Release->eraseFromParent();
410 if (Load->use_empty())
411 Load->eraseFromParent();
412}
413
414bool ObjCARCContract::tryToPeepholeInstruction(
415 Function &F, Instruction *Inst, inst_iterator &Iter,
416 bool &TailOkForStoreStrongs,
417 const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
418 // Only these library routines return their argument. In particular,
419 // objc_retainBlock does not necessarily return its argument.
421 switch (Class) {
422 case ARCInstKind::FusedRetainAutorelease:
423 case ARCInstKind::FusedRetainAutoreleaseRV:
424 return false;
425 case ARCInstKind::Autorelease:
426 case ARCInstKind::AutoreleaseRV:
427 return contractAutorelease(F, Inst, Class);
428 case ARCInstKind::Retain:
429 // Attempt to convert retains to retainrvs if they are next to function
430 // calls.
431 if (!optimizeRetainCall(F, Inst))
432 return false;
433 // If we succeed in our optimization, fall through.
434 [[fallthrough]];
435 case ARCInstKind::RetainRV:
436 case ARCInstKind::UnsafeClaimRV: {
437 // Return true if this is a bundled retainRV/claimRV call, which is always
438 // redundant with the attachedcall in the bundle, and is going to be erased
439 // at the end of this pass. This avoids undoing objc-arc-expand and
440 // replacing uses of the retainRV/claimRV call's argument with its result.
441 if (BundledInsts->contains(Inst))
442 return true;
443
444 // If this isn't a bundled call, and the target doesn't need a special
445 // inline-asm marker, we're done: return now, and undo objc-arc-expand.
446 if (!RVInstMarker)
447 return false;
448
449 // The target needs a special inline-asm marker. Insert it.
450
451 BasicBlock::iterator BBI = Inst->getIterator();
452 BasicBlock *InstParent = Inst->getParent();
453
454 // Step up to see if the call immediately precedes the RV call.
455 // If it's an invoke, we have to cross a block boundary. And we have
456 // to carefully dodge no-op instructions.
457 do {
458 if (BBI == InstParent->begin()) {
459 BasicBlock *Pred = InstParent->getSinglePredecessor();
460 if (!Pred)
461 goto decline_rv_optimization;
462 BBI = Pred->getTerminator()->getIterator();
463 break;
464 }
465 --BBI;
466 } while (IsNoopInstruction(&*BBI));
467
468 if (GetRCIdentityRoot(&*BBI) == GetArgRCIdentityRoot(Inst)) {
469 LLVM_DEBUG(dbgs() << "Adding inline asm marker for the return value "
470 "optimization.\n");
471 Changed = true;
472 InlineAsm *IA =
473 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
474 /*isVarArg=*/false),
475 RVInstMarker->getString(),
476 /*Constraints=*/"", /*hasSideEffects=*/true);
477
479 BlockColors);
480 }
481 decline_rv_optimization:
482 return false;
483 }
484 case ARCInstKind::InitWeak: {
485 // objc_initWeak(p, null) => *p = null
486 CallInst *CI = cast<CallInst>(Inst);
487 if (IsNullOrUndef(CI->getArgOperand(1))) {
488 Value *Null = ConstantPointerNull::get(cast<PointerType>(CI->getType()));
489 Changed = true;
490 new StoreInst(Null, CI->getArgOperand(0), CI->getIterator());
491
492 LLVM_DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
493 << " New = " << *Null << "\n");
494
496 CI->eraseFromParent();
497 }
498 return true;
499 }
500 case ARCInstKind::Release:
501 // Try to form an objc store strong from our release. If we fail, there is
502 // nothing further to do below, so continue.
503 tryToContractReleaseIntoStoreStrong(Inst, Iter, BlockColors);
504 return true;
505 case ARCInstKind::User:
506 // Be conservative if the function has any alloca instructions.
507 // Technically we only care about escaping alloca instructions,
508 // but this is sufficient to handle some interesting cases.
509 if (isa<AllocaInst>(Inst))
510 TailOkForStoreStrongs = false;
511 return true;
512 case ARCInstKind::IntrinsicUser:
513 // Remove calls to @llvm.objc.clang.arc.use(...).
514 Changed = true;
515 Inst->eraseFromParent();
516 return true;
517 default:
518 if (auto *CI = dyn_cast<CallInst>(Inst))
519 if (CI->getIntrinsicID() == Intrinsic::objc_clang_arc_noop_use) {
520 // Remove calls to @llvm.objc.clang.arc.noop.use(...).
521 Changed = true;
522 CI->eraseFromParent();
523 }
524 return true;
525 }
526}
527
528//===----------------------------------------------------------------------===//
529// Top Level Driver
530//===----------------------------------------------------------------------===//
531
532bool ObjCARCContract::init(Module &M) {
533 Run = ModuleHasARC(M);
534 if (!Run)
535 return false;
536
537 EP.init(&M);
538
539 // Initialize RVInstMarker.
540 RVInstMarker = getRVInstMarker(M);
541
542 return false;
543}
544
545bool ObjCARCContract::run(Function &F, AAResults *A, DominatorTree *D) {
546 if (!Run)
547 return false;
548
549 if (!EnableARCOpts)
550 return false;
551
552 Changed = CFGChanged = false;
553 AA = A;
554 DT = D;
555 PA.setAA(A);
556 BundledRetainClaimRVs BRV(/*ContractPass=*/true);
557 BundledInsts = &BRV;
558
559 std::pair<bool, bool> R = BundledInsts->insertAfterInvokes(F, DT);
560 Changed |= R.first;
561 CFGChanged |= R.second;
562
564 if (F.hasPersonalityFn() &&
565 isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
566 BlockColors = colorEHFunclets(F);
567
568 LLVM_DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
569
570 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
571 // keyword. Be conservative if the function has variadic arguments.
572 // It seems that functions which "return twice" are also unsafe for the
573 // "tail" argument, because they are setjmp, which could need to
574 // return to an earlier stack state.
575 bool TailOkForStoreStrongs =
576 !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
577
578 // For ObjC library calls which return their argument, replace uses of the
579 // argument with uses of the call return value, if it dominates the use. This
580 // reduces register pressure.
581 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
582 Instruction *Inst = &*I++;
583
584 LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
585
586 if (auto *CI = dyn_cast<CallInst>(Inst))
588 BundledInsts->insertRVCallWithColors(I->getIterator(), CI, BlockColors);
589 --I;
590 Changed = true;
591 }
592
593 // First try to peephole Inst. If there is nothing further we can do in
594 // terms of undoing objc-arc-expand, process the next inst.
595 if (tryToPeepholeInstruction(F, Inst, I, TailOkForStoreStrongs,
596 BlockColors))
597 continue;
598
599 // Otherwise, try to undo objc-arc-expand.
600
601 // Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
602 // and such; to do the replacement, the argument must have type i8*.
603
604 // Function for replacing uses of Arg dominated by Inst.
605 auto ReplaceArgUses = [Inst, this](Value *Arg) {
606 // If we're compiling bugpointed code, don't get in trouble.
607 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
608 return;
609
610 // Look through the uses of the pointer.
611 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
612 UI != UE; ) {
613 // Increment UI now, because we may unlink its element.
614 Use &U = *UI++;
615 unsigned OperandNo = U.getOperandNo();
616
617 // If the call's return value dominates a use of the call's argument
618 // value, rewrite the use to use the return value. We check for
619 // reachability here because an unreachable call is considered to
620 // trivially dominate itself, which would lead us to rewriting its
621 // argument in terms of its return value, which would lead to
622 // infinite loops in GetArgRCIdentityRoot.
623 if (!DT->isReachableFromEntry(U) || !DT->dominates(Inst, U))
624 continue;
625
626 Changed = true;
627 Instruction *Replacement = Inst;
628 Type *UseTy = U.get()->getType();
629 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
630 // For PHI nodes, insert the bitcast in the predecessor block.
631 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
632 BasicBlock *IncomingBB = PHI->getIncomingBlock(ValNo);
633 if (Replacement->getType() != UseTy) {
634 // A catchswitch is both a pad and a terminator, meaning a basic
635 // block with a catchswitch has no insertion point. Keep going up
636 // the dominator tree until we find a non-catchswitch.
637 BasicBlock *InsertBB = IncomingBB;
638 while (isa<CatchSwitchInst>(InsertBB->getFirstNonPHI())) {
639 InsertBB = DT->getNode(InsertBB)->getIDom()->getBlock();
640 }
641
642 assert(DT->dominates(Inst, &InsertBB->back()) &&
643 "Invalid insertion point for bitcast");
644 Replacement = new BitCastInst(Replacement, UseTy, "",
645 InsertBB->back().getIterator());
646 }
647
648 // While we're here, rewrite all edges for this PHI, rather
649 // than just one use at a time, to minimize the number of
650 // bitcasts we emit.
651 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
652 if (PHI->getIncomingBlock(i) == IncomingBB) {
653 // Keep the UI iterator valid.
654 if (UI != UE &&
655 &PHI->getOperandUse(
657 ++UI;
658 PHI->setIncomingValue(i, Replacement);
659 }
660 } else {
661 if (Replacement->getType() != UseTy)
662 Replacement =
663 new BitCastInst(Replacement, UseTy, "",
664 cast<Instruction>(U.getUser())->getIterator());
665 U.set(Replacement);
666 }
667 }
668 };
669
670 Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
671 Value *OrigArg = Arg;
672
673 // TODO: Change this to a do-while.
674 for (;;) {
675 ReplaceArgUses(Arg);
676
677 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
678 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
679 Arg = BI->getOperand(0);
680 else if (isa<GEPOperator>(Arg) &&
681 cast<GEPOperator>(Arg)->hasAllZeroIndices())
682 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
683 else if (isa<GlobalAlias>(Arg) &&
684 !cast<GlobalAlias>(Arg)->isInterposable())
685 Arg = cast<GlobalAlias>(Arg)->getAliasee();
686 else {
687 // If Arg is a PHI node, get PHIs that are equivalent to it and replace
688 // their uses.
689 if (PHINode *PN = dyn_cast<PHINode>(Arg)) {
691 getEquivalentPHIs(*PN, PHIList);
692 for (Value *PHI : PHIList)
693 ReplaceArgUses(PHI);
694 }
695 break;
696 }
697 }
698
699 // Replace bitcast users of Arg that are dominated by Inst.
701
702 // Add all bitcast users of the function argument first.
703 for (User *U : OrigArg->users())
704 if (auto *BC = dyn_cast<BitCastInst>(U))
705 BitCastUsers.push_back(BC);
706
707 // Replace the bitcasts with the call return. Iterate until list is empty.
708 while (!BitCastUsers.empty()) {
709 auto *BC = BitCastUsers.pop_back_val();
710 for (User *U : BC->users())
711 if (auto *B = dyn_cast<BitCastInst>(U))
712 BitCastUsers.push_back(B);
713
714 ReplaceArgUses(BC);
715 }
716 }
717
718 // If this function has no escaping allocas or suspicious vararg usage,
719 // objc_storeStrong calls can be marked with the "tail" keyword.
720 if (TailOkForStoreStrongs)
721 for (CallInst *CI : StoreStrongCalls)
722 CI->setTailCall();
723 StoreStrongCalls.clear();
724
725 return Changed;
726}
727
728//===----------------------------------------------------------------------===//
729// Misc Pass Manager
730//===----------------------------------------------------------------------===//
731
732char ObjCARCContractLegacyPass::ID = 0;
733INITIALIZE_PASS_BEGIN(ObjCARCContractLegacyPass, "objc-arc-contract",
734 "ObjC ARC contraction", false, false)
737INITIALIZE_PASS_END(ObjCARCContractLegacyPass, "objc-arc-contract",
738 "ObjC ARC contraction", false, false)
739
740void ObjCARCContractLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
741 AU.addRequired<AAResultsWrapperPass>();
742 AU.addRequired<DominatorTreeWrapperPass>();
743 AU.addPreserved<AAResultsWrapperPass>();
744 AU.addPreserved<BasicAAWrapperPass>();
745 AU.addPreserved<DominatorTreeWrapperPass>();
746}
747
749 return new ObjCARCContractLegacyPass();
750}
751
752bool ObjCARCContractLegacyPass::runOnFunction(Function &F) {
753 ObjCARCContract OCARCC;
754 OCARCC.init(*F.getParent());
755 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
756 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
757 return OCARCC.run(F, AA, DT);
758}
759
762 ObjCARCContract OCAC;
763 OCAC.init(*F.getParent());
764
765 bool Changed = OCAC.run(F, &AM.getResult<AAManager>(F),
767 bool CFGChanged = OCAC.hasCFGChanged();
768 if (Changed) {
770 if (!CFGChanged)
772 return PA;
773 }
774 return PreservedAnalyses::all();
775}
Rewrite undef for PHI
This file contains a class ARCRuntimeEntryPoints for use in creating/managing references to entry poi...
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_DEBUG(...)
Definition: Debug.h:106
This file declares special dependency analysis routines used in Objective C ARC Optimizations.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static StoreInst * findSafeStoreForStoreStrongContraction(LoadInst *Load, Instruction *Release, ProvenanceAnalysis &PA, AAResults *AA)
static Instruction * findRetainForStoreStrongContraction(Value *New, StoreInst *Store, Instruction *Release, ProvenanceAnalysis &PA)
objc arc ObjC ARC contraction
objc arc contract
This file defines ARC utility functions which are used by various parts of the compiler.
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
This file declares a special form of Alias Analysis called Provenance Analysis''.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:39
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
Represent the analysis usage information of a pass.
Legacy wrapper pass to provide the BasicAAResult object.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:448
InstListType::const_iterator const_iterator
Definition: BasicBlock.h:178
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:367
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:459
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:239
const Instruction & back() const
Definition: BasicBlock.h:473
This class represents a no-op cast from one type to another.
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:72
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1294
Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
This class represents a function call, abstracting a target machine's calling convention.
void setTailCall(bool IsTc=true)
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1826
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:317
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:321
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:43
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:92
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:176
A single uniqued string.
Definition: Metadata.h:720
Representation for a specific memory location.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
const Value * Ptr
The address of the start of the location.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static unsigned getOperandNumForIncomingValue(unsigned i)
static unsigned getIncomingValueNumForOperand(unsigned i)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:146
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
bool empty() const
Definition: SmallVector.h:81
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
An instruction for storing to memory.
Definition: Instructions.h:292
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt8Ty(LLVMContext &C)
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< user_iterator > users()
Definition: Value.h:421
use_iterator use_begin()
Definition: Value.h:360
use_iterator_impl< Use > use_iterator
Definition: Value.h:353
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:694
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
use_iterator use_end()
Definition: Value.h:368
const ParentTy * getParent() const
Definition: ilist_node.h:32
self_iterator getIterator()
Definition: ilist_node.h:132
Declarations for ObjC runtime functions and constants.
This is similar to BasicAliasAnalysis, and it uses many of the same techniques, except it uses specia...
This file defines common definitions/declarations used by the ObjC ARC Optimizer.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
bool ModuleHasARC(const Module &M)
Test if the given module looks interesting to run ARC optimization on.
bool IsRetain(ARCInstKind Class)
Test if the given class is objc_retain or equivalent.
DependenceKind
Defines different dependence kinds among various ARC constructs.
@ RetainAutoreleaseDep
Blocks objc_retainAutorelease.
@ RetainAutoreleaseRVDep
Blocks objc_retainAutoreleaseReturnValue.
bool IsNullOrUndef(const Value *V)
ARCInstKind
Equivalence classes of instructions in the ARC Model.
@ StoreStrong
objc_storeStrong (derived)
@ Autorelease
objc_autorelease
@ Call
could call objc_release
bool EnableARCOpts
A handy option to enable/disable all ARC Optimizations.
CallInst * createCallInstWithColors(FunctionCallee Func, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore, const DenseMap< BasicBlock *, ColorVector > &BlockColors)
Create a call instruction with the correct funclet token.
Definition: ObjCARC.cpp:24
void getEquivalentPHIs(PHINodeTy &PN, VectorTy &PHIList)
Return the list of PHI nodes that are equivalent to PN.
Definition: ObjCARC.h:74
bool IsNoopInstruction(const Instruction *I)
llvm::Instruction * findSingleDependency(DependenceKind Flavor, const Value *Arg, BasicBlock *StartBB, Instruction *StartInst, ProvenanceAnalysis &PA)
Find dependent instructions.
ARCInstKind GetBasicARCInstKind(const Value *V)
Determine which objc runtime call instruction class V belongs to.
Value * GetArgRCIdentityRoot(Value *Inst)
Assuming the given instruction is one of the special calls such as objc_retain or objc_release,...
bool CanDecrementRefCount(ARCInstKind Kind)
Returns false if conservatively we can prove that any instruction mapped to this kind can not decreme...
const Value * GetRCIdentityRoot(const Value *V)
The RCIdentity root of a value V is a dominating value U for which retaining or releasing U is equiva...
static MDString * getRVInstMarker(Module &M)
Definition: ObjCARC.h:92
bool hasAttachedCallOpBundle(const CallBase *CB)
Definition: ObjCARCUtil.h:29
bool CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA, ARCInstKind Class)
Test whether the given instruction can "use" the given pointer's object in a way that requires the re...
static void EraseInstruction(Instruction *CI)
Erase the given instruction.
Definition: ObjCARC.h:39
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
inst_iterator inst_begin(Function *F)
Definition: InstIterator.h:129
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
inst_iterator inst_end(Function *F)
Definition: InstIterator.h:130
void initializeObjCARCContractLegacyPassPass(PassRegistry &)
Pass * createObjCARCContractPass()
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)