LLVM  mainline
ObjCARCAPElim.cpp
Go to the documentation of this file.
00001 //===- ObjCARCAPElim.cpp - ObjC ARC Optimization --------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 /// \file
00010 ///
00011 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
00012 /// Reference Counting and is a system for managing reference counts for objects
00013 /// in Objective C.
00014 ///
00015 /// This specific file implements optimizations which remove extraneous
00016 /// autorelease pools.
00017 ///
00018 /// WARNING: This file knows about certain library functions. It recognizes them
00019 /// by name, and hardwires knowledge of their semantics.
00020 ///
00021 /// WARNING: This file knows about how certain Objective-C library functions are
00022 /// used. Naive LLVM IR transformations which would otherwise be
00023 /// behavior-preserving may break these assumptions.
00024 ///
00025 //===----------------------------------------------------------------------===//
00026 
00027 #include "ObjCARC.h"
00028 #include "llvm/ADT/STLExtras.h"
00029 #include "llvm/IR/Constants.h"
00030 #include "llvm/Support/Debug.h"
00031 #include "llvm/Support/raw_ostream.h"
00032 
00033 using namespace llvm;
00034 using namespace llvm::objcarc;
00035 
00036 #define DEBUG_TYPE "objc-arc-ap-elim"
00037 
00038 namespace {
00039   /// \brief Autorelease pool elimination.
00040   class ObjCARCAPElim : public ModulePass {
00041     void getAnalysisUsage(AnalysisUsage &AU) const override;
00042     bool runOnModule(Module &M) override;
00043 
00044     static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
00045     static bool OptimizeBB(BasicBlock *BB);
00046 
00047   public:
00048     static char ID;
00049     ObjCARCAPElim() : ModulePass(ID) {
00050       initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
00051     }
00052   };
00053 }
00054 
00055 char ObjCARCAPElim::ID = 0;
00056 INITIALIZE_PASS(ObjCARCAPElim,
00057                 "objc-arc-apelim",
00058                 "ObjC ARC autorelease pool elimination",
00059                 false, false)
00060 
00061 Pass *llvm::createObjCARCAPElimPass() {
00062   return new ObjCARCAPElim();
00063 }
00064 
00065 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
00066   AU.setPreservesCFG();
00067 }
00068 
00069 /// Interprocedurally determine if calls made by the given call site can
00070 /// possibly produce autoreleases.
00071 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
00072   if (const Function *Callee = CS.getCalledFunction()) {
00073     if (Callee->isDeclaration() || Callee->mayBeOverridden())
00074       return true;
00075     for (const BasicBlock &BB : *Callee) {
00076       for (const Instruction &I : BB)
00077         if (ImmutableCallSite JCS = ImmutableCallSite(&I))
00078           // This recursion depth limit is arbitrary. It's just great
00079           // enough to cover known interesting testcases.
00080           if (Depth < 3 &&
00081               !JCS.onlyReadsMemory() &&
00082               MayAutorelease(JCS, Depth + 1))
00083             return true;
00084     }
00085     return false;
00086   }
00087 
00088   return true;
00089 }
00090 
00091 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
00092   bool Changed = false;
00093 
00094   Instruction *Push = nullptr;
00095   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
00096     Instruction *Inst = &*I++;
00097     switch (GetBasicARCInstKind(Inst)) {
00098     case ARCInstKind::AutoreleasepoolPush:
00099       Push = Inst;
00100       break;
00101     case ARCInstKind::AutoreleasepoolPop:
00102       // If this pop matches a push and nothing in between can autorelease,
00103       // zap the pair.
00104       if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
00105         Changed = true;
00106         DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
00107                         "autorelease pair:\n"
00108                         "                           Pop: " << *Inst << "\n"
00109                      << "                           Push: " << *Push << "\n");
00110         Inst->eraseFromParent();
00111         Push->eraseFromParent();
00112       }
00113       Push = nullptr;
00114       break;
00115     case ARCInstKind::CallOrUser:
00116       if (MayAutorelease(ImmutableCallSite(Inst)))
00117         Push = nullptr;
00118       break;
00119     default:
00120       break;
00121     }
00122   }
00123 
00124   return Changed;
00125 }
00126 
00127 bool ObjCARCAPElim::runOnModule(Module &M) {
00128   if (!EnableARCOpts)
00129     return false;
00130 
00131   // If nothing in the Module uses ARC, don't do anything.
00132   if (!ModuleHasARC(M))
00133     return false;
00134 
00135   // Find the llvm.global_ctors variable, as the first step in
00136   // identifying the global constructors. In theory, unnecessary autorelease
00137   // pools could occur anywhere, but in practice it's pretty rare. Global
00138   // ctors are a place where autorelease pools get inserted automatically,
00139   // so it's pretty common for them to be unnecessary, and it's pretty
00140   // profitable to eliminate them.
00141   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
00142   if (!GV)
00143     return false;
00144 
00145   assert(GV->hasDefinitiveInitializer() &&
00146          "llvm.global_ctors is uncooperative!");
00147 
00148   bool Changed = false;
00149 
00150   // Dig the constructor functions out of GV's initializer.
00151   ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
00152   for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
00153        OI != OE; ++OI) {
00154     Value *Op = *OI;
00155     // llvm.global_ctors is an array of three-field structs where the second
00156     // members are constructor functions.
00157     Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
00158     // If the user used a constructor function with the wrong signature and
00159     // it got bitcasted or whatever, look the other way.
00160     if (!F)
00161       continue;
00162     // Only look at function definitions.
00163     if (F->isDeclaration())
00164       continue;
00165     // Only look at functions with one basic block.
00166     if (std::next(F->begin()) != F->end())
00167       continue;
00168     // Ok, a single-block constructor function definition. Try to optimize it.
00169     Changed |= OptimizeBB(&F->front());
00170   }
00171 
00172   return Changed;
00173 }