1 //===- ObjCARCAPElim.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 ///
10 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
11 /// Reference Counting and is a system for managing reference counts for objects
12 /// in Objective C.
13 ///
14 /// This specific file implements optimizations which remove extraneous
15 /// autorelease pools.
16 ///
17 /// WARNING: This file knows about certain library functions. It recognizes them
18 /// by name, and hardwires knowledge of their semantics.
19 ///
20 /// WARNING: This file knows about how certain Objective-C library functions are
21 /// used. Naive LLVM IR transformations which would otherwise be
22 /// behavior-preserving may break these assumptions.
23 ///
24 //===----------------------------------------------------------------------===//
25
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Analysis/ObjCARCAnalysisUtils.h"
28 #include "llvm/Analysis/ObjCARCInstKind.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/InstrTypes.h"
31 #include "llvm/IR/PassManager.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/ObjCARC.h"
37
38 using namespace llvm;
39 using namespace llvm::objcarc;
40
41 #define DEBUG_TYPE "objc-arc-ap-elim"
42
43 namespace {
44
45 /// Interprocedurally determine if calls made by the given call site can
46 /// possibly produce autoreleases.
MayAutorelease(const CallBase & CB,unsigned Depth=0)47 bool MayAutorelease(const CallBase &CB, unsigned Depth = 0) {
48 if (const Function *Callee = CB.getCalledFunction()) {
49 if (!Callee->hasExactDefinition())
50 return true;
51 for (const BasicBlock &BB : *Callee) {
52 for (const Instruction &I : BB)
53 if (const CallBase *JCB = dyn_cast<CallBase>(&I))
54 // This recursion depth limit is arbitrary. It's just great
55 // enough to cover known interesting testcases.
56 if (Depth < 3 && !JCB->onlyReadsMemory() &&
57 MayAutorelease(*JCB, Depth + 1))
58 return true;
59 }
60 return false;
61 }
62
63 return true;
64 }
65
OptimizeBB(BasicBlock * BB)66 bool OptimizeBB(BasicBlock *BB) {
67 bool Changed = false;
68
69 Instruction *Push = nullptr;
70 for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
71 switch (GetBasicARCInstKind(&Inst)) {
72 case ARCInstKind::AutoreleasepoolPush:
73 Push = &Inst;
74 break;
75 case ARCInstKind::AutoreleasepoolPop:
76 // If this pop matches a push and nothing in between can autorelease,
77 // zap the pair.
78 if (Push && cast<CallInst>(&Inst)->getArgOperand(0) == Push) {
79 Changed = true;
80 LLVM_DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
81 "autorelease pair:\n"
82 " Pop: "
83 << Inst << "\n"
84 << " Push: " << *Push
85 << "\n");
86 Inst.eraseFromParent();
87 Push->eraseFromParent();
88 }
89 Push = nullptr;
90 break;
91 case ARCInstKind::CallOrUser:
92 if (MayAutorelease(cast<CallBase>(Inst)))
93 Push = nullptr;
94 break;
95 default:
96 break;
97 }
98 }
99
100 return Changed;
101 }
102
runImpl(Module & M)103 bool runImpl(Module &M) {
104 if (!EnableARCOpts)
105 return false;
106
107 // If nothing in the Module uses ARC, don't do anything.
108 if (!ModuleHasARC(M))
109 return false;
110 // Find the llvm.global_ctors variable, as the first step in
111 // identifying the global constructors. In theory, unnecessary autorelease
112 // pools could occur anywhere, but in practice it's pretty rare. Global
113 // ctors are a place where autorelease pools get inserted automatically,
114 // so it's pretty common for them to be unnecessary, and it's pretty
115 // profitable to eliminate them.
116 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
117 if (!GV)
118 return false;
119
120 assert(GV->hasDefinitiveInitializer() &&
121 "llvm.global_ctors is uncooperative!");
122
123 bool Changed = false;
124
125 // Dig the constructor functions out of GV's initializer.
126 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
127 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
128 OI != OE; ++OI) {
129 Value *Op = *OI;
130 // llvm.global_ctors is an array of three-field structs where the second
131 // members are constructor functions.
132 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
133 // If the user used a constructor function with the wrong signature and
134 // it got bitcasted or whatever, look the other way.
135 if (!F)
136 continue;
137 // Only look at function definitions.
138 if (F->isDeclaration())
139 continue;
140 // Only look at functions with one basic block.
141 if (std::next(F->begin()) != F->end())
142 continue;
143 // Ok, a single-block constructor function definition. Try to optimize it.
144 Changed |= OptimizeBB(&F->front());
145 }
146
147 return Changed;
148 }
149
150 /// Autorelease pool elimination.
151 class ObjCARCAPElim : public ModulePass {
152 void getAnalysisUsage(AnalysisUsage &AU) const override;
153 bool runOnModule(Module &M) override;
154
155 public:
156 static char ID;
ObjCARCAPElim()157 ObjCARCAPElim() : ModulePass(ID) {
158 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
159 }
160 };
161 } // namespace
162
163 char ObjCARCAPElim::ID = 0;
164 INITIALIZE_PASS(ObjCARCAPElim, "objc-arc-apelim",
165 "ObjC ARC autorelease pool elimination", false, false)
166
createObjCARCAPElimPass()167 Pass *llvm::createObjCARCAPElimPass() { return new ObjCARCAPElim(); }
168
getAnalysisUsage(AnalysisUsage & AU) const169 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
170 AU.setPreservesCFG();
171 }
172
runOnModule(Module & M)173 bool ObjCARCAPElim::runOnModule(Module &M) {
174 if (skipModule(M))
175 return false;
176 return runImpl(M);
177 }
178
run(Module & M,ModuleAnalysisManager & AM)179 PreservedAnalyses ObjCARCAPElimPass::run(Module &M, ModuleAnalysisManager &AM) {
180 if (!runImpl(M))
181 return PreservedAnalyses::all();
182 PreservedAnalyses PA;
183 PA.preserveSet<CFGAnalyses>();
184 return PA;
185 }
186