LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
ObjCARCAPElim.cpp
Go to the documentation of this file.
1 //===- ObjCARCAPElim.cpp - ObjC ARC Optimization --------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
11 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
12 /// Reference Counting and is a system for managing reference counts for objects
13 /// in Objective C.
14 ///
15 /// This specific file implements optimizations which remove extraneous
16 /// autorelease pools.
17 ///
18 /// WARNING: This file knows about certain library functions. It recognizes them
19 /// by name, and hardwires knowledge of their semantics.
20 ///
21 /// WARNING: This file knows about how certain Objective-C library functions are
22 /// used. Naive LLVM IR transformations which would otherwise be
23 /// behavior-preserving may break these assumptions.
24 ///
25 //===----------------------------------------------------------------------===//
26 
27 #define DEBUG_TYPE "objc-arc-ap-elim"
28 #include "ObjCARC.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/Support/Debug.h"
33 
34 using namespace llvm;
35 using namespace llvm::objcarc;
36 
37 namespace {
38  /// \brief Autorelease pool elimination.
39  class ObjCARCAPElim : public ModulePass {
40  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
41  virtual bool runOnModule(Module &M);
42 
43  static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
44  static bool OptimizeBB(BasicBlock *BB);
45 
46  public:
47  static char ID;
48  ObjCARCAPElim() : ModulePass(ID) {
50  }
51  };
52 }
53 
54 char ObjCARCAPElim::ID = 0;
55 INITIALIZE_PASS(ObjCARCAPElim,
56  "objc-arc-apelim",
57  "ObjC ARC autorelease pool elimination",
58  false, false)
59 
61  return new ObjCARCAPElim();
62 }
63 
64 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
65  AU.setPreservesCFG();
66 }
67 
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->isDeclaration() || Callee->mayBeOverridden())
73  return true;
74  for (Function::const_iterator I = Callee->begin(), E = Callee->end();
75  I != E; ++I) {
76  const BasicBlock *BB = I;
77  for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
78  J != F; ++J)
80  // This recursion depth limit is arbitrary. It's just great
81  // enough to cover known interesting testcases.
82  if (Depth < 3 &&
83  !JCS.onlyReadsMemory() &&
84  MayAutorelease(JCS, Depth + 1))
85  return true;
86  }
87  return false;
88  }
89 
90  return true;
91 }
92 
93 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
94  bool Changed = false;
95 
96  Instruction *Push = 0;
97  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
98  Instruction *Inst = I++;
99  switch (GetBasicInstructionClass(Inst)) {
101  Push = Inst;
102  break;
104  // If this pop matches a push and nothing in between can autorelease,
105  // zap the pair.
106  if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
107  Changed = true;
108  DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
109  "autorelease pair:\n"
110  " Pop: " << *Inst << "\n"
111  << " Push: " << *Push << "\n");
112  Inst->eraseFromParent();
113  Push->eraseFromParent();
114  }
115  Push = 0;
116  break;
117  case IC_CallOrUser:
118  if (MayAutorelease(ImmutableCallSite(Inst)))
119  Push = 0;
120  break;
121  default:
122  break;
123  }
124  }
125 
126  return Changed;
127 }
128 
129 bool ObjCARCAPElim::runOnModule(Module &M) {
130  if (!EnableARCOpts)
131  return false;
132 
133  // If nothing in the Module uses ARC, don't do anything.
134  if (!ModuleHasARC(M))
135  return false;
136 
137  // Find the llvm.global_ctors variable, as the first step in
138  // identifying the global constructors. In theory, unnecessary autorelease
139  // pools could occur anywhere, but in practice it's pretty rare. Global
140  // ctors are a place where autorelease pools get inserted automatically,
141  // so it's pretty common for them to be unnecessary, and it's pretty
142  // profitable to eliminate them.
143  GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
144  if (!GV)
145  return false;
146 
147  assert(GV->hasDefinitiveInitializer() &&
148  "llvm.global_ctors is uncooperative!");
149 
150  bool Changed = false;
151 
152  // Dig the constructor functions out of GV's initializer.
153  ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
154  for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
155  OI != OE; ++OI) {
156  Value *Op = *OI;
157  // llvm.global_ctors is an array of pairs where the second members
158  // are constructor functions.
159  Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
160  // If the user used a constructor function with the wrong signature and
161  // it got bitcasted or whatever, look the other way.
162  if (!F)
163  continue;
164  // Only look at function definitions.
165  if (F->isDeclaration())
166  continue;
167  // Only look at functions with one basic block.
168  if (llvm::next(F->begin()) != F->end())
169  continue;
170  // Ok, a single-block constructor function definition. Try to optimize it.
171  Changed |= OptimizeBB(F->begin());
172  }
173 
174  return Changed;
175 }
static PassRegistry * getPassRegistry()
void initializeObjCARCAPElimPass(PassRegistry &)
The main container class for the LLVM Intermediate Representation.
Definition: Module.h:112
iterator end()
Definition: Function.h:397
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:266
static InstructionClass GetBasicInstructionClass(const Value *V)
Determine which objc runtime call instruction class V belongs to.
F(f)
const Constant * getInitializer() const
op_iterator op_begin()
Definition: User.h:116
const GlobalVariable * getGlobalVariable(StringRef Name, bool AllowInternal=false) const
Definition: Module.h:355
iterator begin()
Definition: BasicBlock.h:193
Definition: Use.h:60
ID
LLVM Calling Convention Representation.
Definition: CallingConv.h:26
Pass * createObjCARCAPElimPass()
bool EnableARCOpts
A handy option to enable/disable all ARC Optimizations.
Definition: ObjCARC.cpp:30
bool hasDefinitiveInitializer() const
iterator begin()
Definition: Function.h:395
LLVM Basic Block Representation.
Definition: BasicBlock.h:72
op_iterator op_end()
Definition: User.h:118
ItTy next(ItTy it, Dist n)
Definition: STLExtras.h:154
iterator end()
Definition: BasicBlock.h:195
could call objc_release and/or "use" pointers
void setPreservesCFG()
Definition: Pass.cpp:249
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
Definition: Debug.cpp:101
bool isDeclaration() const
Definition: Globals.cpp:66
ImmutableCallSite - establish a view to a call site for examination.
Definition: CallSite.h:318
#define I(x, y, z)
Definition: MD5.cpp:54
LLVM Value Representation.
Definition: Value.h:66
#define DEBUG(X)
Definition: Debug.h:97
INITIALIZE_PASS(ObjCARCAPElim,"objc-arc-apelim","ObjC ARC autorelease pool elimination", false, false) Pass *llvm
static bool ModuleHasARC(const Module &M)
Test if the given module looks interesting to run ARC optimization on.
FunTy * getCalledFunction() const
Definition: CallSite.h:93