LLVM API Documentation

DependencyAnalysis.cpp
Go to the documentation of this file.
00001 //===- DependencyAnalysis.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 special dependency analysis routines used in Objective C
00012 /// ARC Optimizations.
00013 ///
00014 /// WARNING: This file knows about certain library functions. It recognizes them
00015 /// by name, and hardwires knowledge of their semantics.
00016 ///
00017 /// WARNING: This file knows about how certain Objective-C library functions are
00018 /// used. Naive LLVM IR transformations which would otherwise be
00019 /// behavior-preserving may break these assumptions.
00020 ///
00021 //===----------------------------------------------------------------------===//
00022 
00023 #include "ObjCARC.h"
00024 #include "DependencyAnalysis.h"
00025 #include "ProvenanceAnalysis.h"
00026 #include "llvm/IR/CFG.h"
00027 
00028 using namespace llvm;
00029 using namespace llvm::objcarc;
00030 
00031 #define DEBUG_TYPE "objc-arc-dependency"
00032 
00033 /// Test whether the given instruction can result in a reference count
00034 /// modification (positive or negative) for the pointer's object.
00035 bool llvm::objcarc::CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
00036                                      ProvenanceAnalysis &PA,
00037                                      ARCInstKind Class) {
00038   switch (Class) {
00039   case ARCInstKind::Autorelease:
00040   case ARCInstKind::AutoreleaseRV:
00041   case ARCInstKind::IntrinsicUser:
00042   case ARCInstKind::User:
00043     // These operations never directly modify a reference count.
00044     return false;
00045   default: break;
00046   }
00047 
00048   ImmutableCallSite CS = static_cast<const Value *>(Inst);
00049   assert(CS && "Only calls can alter reference counts!");
00050 
00051   // See if AliasAnalysis can help us with the call.
00052   AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
00053   if (AliasAnalysis::onlyReadsMemory(MRB))
00054     return false;
00055   if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
00056     for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
00057          I != E; ++I) {
00058       const Value *Op = *I;
00059       if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
00060         return true;
00061     }
00062     return false;
00063   }
00064 
00065   // Assume the worst.
00066   return true;
00067 }
00068 
00069 bool llvm::objcarc::CanDecrementRefCount(const Instruction *Inst,
00070                                          const Value *Ptr,
00071                                          ProvenanceAnalysis &PA,
00072                                          ARCInstKind Class) {
00073   // First perform a quick check if Class can not touch ref counts.
00074   if (!CanDecrementRefCount(Class))
00075     return false;
00076 
00077   // Otherwise, just use CanAlterRefCount for now.
00078   return CanAlterRefCount(Inst, Ptr, PA, Class);
00079 }
00080 
00081 /// Test whether the given instruction can "use" the given pointer's object in a
00082 /// way that requires the reference count to be positive.
00083 bool llvm::objcarc::CanUse(const Instruction *Inst, const Value *Ptr,
00084                            ProvenanceAnalysis &PA, ARCInstKind Class) {
00085   // ARCInstKind::Call operations (as opposed to
00086   // ARCInstKind::CallOrUser) never "use" objc pointers.
00087   if (Class == ARCInstKind::Call)
00088     return false;
00089 
00090   // Consider various instructions which may have pointer arguments which are
00091   // not "uses".
00092   if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
00093     // Comparing a pointer with null, or any other constant, isn't really a use,
00094     // because we don't care what the pointer points to, or about the values
00095     // of any other dynamic reference-counted pointers.
00096     if (!IsPotentialRetainableObjPtr(ICI->getOperand(1), *PA.getAA()))
00097       return false;
00098   } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
00099     // For calls, just check the arguments (and not the callee operand).
00100     for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
00101          OE = CS.arg_end(); OI != OE; ++OI) {
00102       const Value *Op = *OI;
00103       if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
00104         return true;
00105     }
00106     return false;
00107   } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00108     // Special-case stores, because we don't care about the stored value, just
00109     // the store address.
00110     const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
00111     // If we can't tell what the underlying object was, assume there is a
00112     // dependence.
00113     return IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Op, Ptr);
00114   }
00115 
00116   // Check each operand for a match.
00117   for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
00118        OI != OE; ++OI) {
00119     const Value *Op = *OI;
00120     if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
00121       return true;
00122   }
00123   return false;
00124 }
00125 
00126 /// Test if there can be dependencies on Inst through Arg. This function only
00127 /// tests dependencies relevant for removing pairs of calls.
00128 bool
00129 llvm::objcarc::Depends(DependenceKind Flavor, Instruction *Inst,
00130                        const Value *Arg, ProvenanceAnalysis &PA) {
00131   // If we've reached the definition of Arg, stop.
00132   if (Inst == Arg)
00133     return true;
00134 
00135   switch (Flavor) {
00136   case NeedsPositiveRetainCount: {
00137     ARCInstKind Class = GetARCInstKind(Inst);
00138     switch (Class) {
00139     case ARCInstKind::AutoreleasepoolPop:
00140     case ARCInstKind::AutoreleasepoolPush:
00141     case ARCInstKind::None:
00142       return false;
00143     default:
00144       return CanUse(Inst, Arg, PA, Class);
00145     }
00146   }
00147 
00148   case AutoreleasePoolBoundary: {
00149     ARCInstKind Class = GetARCInstKind(Inst);
00150     switch (Class) {
00151     case ARCInstKind::AutoreleasepoolPop:
00152     case ARCInstKind::AutoreleasepoolPush:
00153       // These mark the end and begin of an autorelease pool scope.
00154       return true;
00155     default:
00156       // Nothing else does this.
00157       return false;
00158     }
00159   }
00160 
00161   case CanChangeRetainCount: {
00162     ARCInstKind Class = GetARCInstKind(Inst);
00163     switch (Class) {
00164     case ARCInstKind::AutoreleasepoolPop:
00165       // Conservatively assume this can decrement any count.
00166       return true;
00167     case ARCInstKind::AutoreleasepoolPush:
00168     case ARCInstKind::None:
00169       return false;
00170     default:
00171       return CanAlterRefCount(Inst, Arg, PA, Class);
00172     }
00173   }
00174 
00175   case RetainAutoreleaseDep:
00176     switch (GetBasicARCInstKind(Inst)) {
00177     case ARCInstKind::AutoreleasepoolPop:
00178     case ARCInstKind::AutoreleasepoolPush:
00179       // Don't merge an objc_autorelease with an objc_retain inside a different
00180       // autoreleasepool scope.
00181       return true;
00182     case ARCInstKind::Retain:
00183     case ARCInstKind::RetainRV:
00184       // Check for a retain of the same pointer for merging.
00185       return GetArgRCIdentityRoot(Inst) == Arg;
00186     default:
00187       // Nothing else matters for objc_retainAutorelease formation.
00188       return false;
00189     }
00190 
00191   case RetainAutoreleaseRVDep: {
00192     ARCInstKind Class = GetBasicARCInstKind(Inst);
00193     switch (Class) {
00194     case ARCInstKind::Retain:
00195     case ARCInstKind::RetainRV:
00196       // Check for a retain of the same pointer for merging.
00197       return GetArgRCIdentityRoot(Inst) == Arg;
00198     default:
00199       // Anything that can autorelease interrupts
00200       // retainAutoreleaseReturnValue formation.
00201       return CanInterruptRV(Class);
00202     }
00203   }
00204 
00205   case RetainRVDep:
00206     return CanInterruptRV(GetBasicARCInstKind(Inst));
00207   }
00208 
00209   llvm_unreachable("Invalid dependence flavor");
00210 }
00211 
00212 /// Walk up the CFG from StartPos (which is in StartBB) and find local and
00213 /// non-local dependencies on Arg.
00214 ///
00215 /// TODO: Cache results?
00216 void
00217 llvm::objcarc::FindDependencies(DependenceKind Flavor,
00218                                 const Value *Arg,
00219                                 BasicBlock *StartBB, Instruction *StartInst,
00220                                 SmallPtrSetImpl<Instruction *> &DependingInsts,
00221                                 SmallPtrSetImpl<const BasicBlock *> &Visited,
00222                                 ProvenanceAnalysis &PA) {
00223   BasicBlock::iterator StartPos = StartInst;
00224 
00225   SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
00226   Worklist.push_back(std::make_pair(StartBB, StartPos));
00227   do {
00228     std::pair<BasicBlock *, BasicBlock::iterator> Pair =
00229       Worklist.pop_back_val();
00230     BasicBlock *LocalStartBB = Pair.first;
00231     BasicBlock::iterator LocalStartPos = Pair.second;
00232     BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
00233     for (;;) {
00234       if (LocalStartPos == StartBBBegin) {
00235         pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
00236         if (PI == PE)
00237           // If we've reached the function entry, produce a null dependence.
00238           DependingInsts.insert(nullptr);
00239         else
00240           // Add the predecessors to the worklist.
00241           do {
00242             BasicBlock *PredBB = *PI;
00243             if (Visited.insert(PredBB).second)
00244               Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
00245           } while (++PI != PE);
00246         break;
00247       }
00248 
00249       Instruction *Inst = --LocalStartPos;
00250       if (Depends(Flavor, Inst, Arg, PA)) {
00251         DependingInsts.insert(Inst);
00252         break;
00253       }
00254     }
00255   } while (!Worklist.empty());
00256 
00257   // Determine whether the original StartBB post-dominates all of the blocks we
00258   // visited. If not, insert a sentinal indicating that most optimizations are
00259   // not safe.
00260   for (const BasicBlock *BB : Visited) {
00261     if (BB == StartBB)
00262       continue;
00263     const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
00264     for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
00265       const BasicBlock *Succ = *SI;
00266       if (Succ != StartBB && !Visited.count(Succ)) {
00267         DependingInsts.insert(reinterpret_cast<Instruction *>(-1));
00268         return;
00269       }
00270     }
00271   }
00272 }