[yaml2obj/obj2yaml] - Add support for .stack_sizes sections.
[llvm-complete.git] / lib / Transforms / ObjCARC / ObjCARCAPElim.cpp
blobb341dd807508c20e31c7d250876e1db86eb16f1a
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 //===----------------------------------------------------------------------===//
26 #include "ObjCARC.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
33 using namespace llvm::objcarc;
35 #define DEBUG_TYPE "objc-arc-ap-elim"
37 namespace {
38 /// Autorelease pool elimination.
39 class ObjCARCAPElim : public ModulePass {
40 void getAnalysisUsage(AnalysisUsage &AU) const override;
41 bool runOnModule(Module &M) override;
43 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
44 static bool OptimizeBB(BasicBlock *BB);
46 public:
47 static char ID;
48 ObjCARCAPElim() : ModulePass(ID) {
49 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
54 char ObjCARCAPElim::ID = 0;
55 INITIALIZE_PASS(ObjCARCAPElim,
56 "objc-arc-apelim",
57 "ObjC ARC autorelease pool elimination",
58 false, false)
60 Pass *llvm::createObjCARCAPElimPass() {
61 return new ObjCARCAPElim();
64 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.setPreservesCFG();
68 /// Interprocedurally determine if calls made by the given call site can
69 /// possibly produce autoreleases.
70 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
71 if (const Function *Callee = CS.getCalledFunction()) {
72 if (!Callee->hasExactDefinition())
73 return true;
74 for (const BasicBlock &BB : *Callee) {
75 for (const Instruction &I : BB)
76 if (ImmutableCallSite JCS = ImmutableCallSite(&I))
77 // This recursion depth limit is arbitrary. It's just great
78 // enough to cover known interesting testcases.
79 if (Depth < 3 &&
80 !JCS.onlyReadsMemory() &&
81 MayAutorelease(JCS, Depth + 1))
82 return true;
84 return false;
87 return true;
90 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
91 bool Changed = false;
93 Instruction *Push = nullptr;
94 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
95 Instruction *Inst = &*I++;
96 switch (GetBasicARCInstKind(Inst)) {
97 case ARCInstKind::AutoreleasepoolPush:
98 Push = Inst;
99 break;
100 case ARCInstKind::AutoreleasepoolPop:
101 // If this pop matches a push and nothing in between can autorelease,
102 // zap the pair.
103 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
104 Changed = true;
105 LLVM_DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
106 "autorelease pair:\n"
107 " Pop: "
108 << *Inst << "\n"
109 << " Push: " << *Push
110 << "\n");
111 Inst->eraseFromParent();
112 Push->eraseFromParent();
114 Push = nullptr;
115 break;
116 case ARCInstKind::CallOrUser:
117 if (MayAutorelease(ImmutableCallSite(Inst)))
118 Push = nullptr;
119 break;
120 default:
121 break;
125 return Changed;
128 bool ObjCARCAPElim::runOnModule(Module &M) {
129 if (!EnableARCOpts)
130 return false;
132 // If nothing in the Module uses ARC, don't do anything.
133 if (!ModuleHasARC(M))
134 return false;
136 if (skipModule(M))
137 return false;
139 // Find the llvm.global_ctors variable, as the first step in
140 // identifying the global constructors. In theory, unnecessary autorelease
141 // pools could occur anywhere, but in practice it's pretty rare. Global
142 // ctors are a place where autorelease pools get inserted automatically,
143 // so it's pretty common for them to be unnecessary, and it's pretty
144 // profitable to eliminate them.
145 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
146 if (!GV)
147 return false;
149 assert(GV->hasDefinitiveInitializer() &&
150 "llvm.global_ctors is uncooperative!");
152 bool Changed = false;
154 // Dig the constructor functions out of GV's initializer.
155 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
156 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
157 OI != OE; ++OI) {
158 Value *Op = *OI;
159 // llvm.global_ctors is an array of three-field structs where the second
160 // members are constructor functions.
161 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
162 // If the user used a constructor function with the wrong signature and
163 // it got bitcasted or whatever, look the other way.
164 if (!F)
165 continue;
166 // Only look at function definitions.
167 if (F->isDeclaration())
168 continue;
169 // Only look at functions with one basic block.
170 if (std::next(F->begin()) != F->end())
171 continue;
172 // Ok, a single-block constructor function definition. Try to optimize it.
173 Changed |= OptimizeBB(&F->front());
176 return Changed;