Home | History | Annotate | Download | only in Scalar
      1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
      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 //
     10 // This transformation implements the well known scalar replacement of
     11 // aggregates transformation.  This xform breaks up alloca instructions of
     12 // aggregate type (structure or array) into individual alloca instructions for
     13 // each member (if possible).  Then, if possible, it transforms the individual
     14 // alloca instructions into nice clean scalar SSA form.
     15 //
     16 // This combines a simple SRoA algorithm with the Mem2Reg algorithm because
     17 // often interact, especially for C++ programs.  As such, iterating between
     18 // SRoA, then Mem2Reg until we run out of things to promote works well.
     19 //
     20 //===----------------------------------------------------------------------===//
     21 
     22 #define DEBUG_TYPE "scalarrepl"
     23 #include "llvm/Transforms/Scalar.h"
     24 #include "llvm/Constants.h"
     25 #include "llvm/DerivedTypes.h"
     26 #include "llvm/Function.h"
     27 #include "llvm/GlobalVariable.h"
     28 #include "llvm/Instructions.h"
     29 #include "llvm/IntrinsicInst.h"
     30 #include "llvm/LLVMContext.h"
     31 #include "llvm/Module.h"
     32 #include "llvm/Pass.h"
     33 #include "llvm/Analysis/DebugInfo.h"
     34 #include "llvm/Analysis/DIBuilder.h"
     35 #include "llvm/Analysis/Dominators.h"
     36 #include "llvm/Analysis/Loads.h"
     37 #include "llvm/Analysis/ValueTracking.h"
     38 #include "llvm/Target/TargetData.h"
     39 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
     40 #include "llvm/Transforms/Utils/Local.h"
     41 #include "llvm/Transforms/Utils/SSAUpdater.h"
     42 #include "llvm/Support/CallSite.h"
     43 #include "llvm/Support/Debug.h"
     44 #include "llvm/Support/ErrorHandling.h"
     45 #include "llvm/Support/GetElementPtrTypeIterator.h"
     46 #include "llvm/Support/IRBuilder.h"
     47 #include "llvm/Support/MathExtras.h"
     48 #include "llvm/Support/raw_ostream.h"
     49 #include "llvm/ADT/SetVector.h"
     50 #include "llvm/ADT/SmallVector.h"
     51 #include "llvm/ADT/Statistic.h"
     52 using namespace llvm;
     53 
     54 STATISTIC(NumReplaced,  "Number of allocas broken up");
     55 STATISTIC(NumPromoted,  "Number of allocas promoted");
     56 STATISTIC(NumAdjusted,  "Number of scalar allocas adjusted to allow promotion");
     57 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
     58 STATISTIC(NumGlobals,   "Number of allocas copied from constant global");
     59 
     60 namespace {
     61   struct SROA : public FunctionPass {
     62     SROA(int T, bool hasDT, char &ID)
     63       : FunctionPass(ID), HasDomTree(hasDT) {
     64       if (T == -1)
     65         SRThreshold = 128;
     66       else
     67         SRThreshold = T;
     68     }
     69 
     70     bool runOnFunction(Function &F);
     71 
     72     bool performScalarRepl(Function &F);
     73     bool performPromotion(Function &F);
     74 
     75   private:
     76     bool HasDomTree;
     77     TargetData *TD;
     78 
     79     /// DeadInsts - Keep track of instructions we have made dead, so that
     80     /// we can remove them after we are done working.
     81     SmallVector<Value*, 32> DeadInsts;
     82 
     83     /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
     84     /// information about the uses.  All these fields are initialized to false
     85     /// and set to true when something is learned.
     86     struct AllocaInfo {
     87       /// The alloca to promote.
     88       AllocaInst *AI;
     89 
     90       /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
     91       /// looping and avoid redundant work.
     92       SmallPtrSet<PHINode*, 8> CheckedPHIs;
     93 
     94       /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
     95       bool isUnsafe : 1;
     96 
     97       /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
     98       bool isMemCpySrc : 1;
     99 
    100       /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
    101       bool isMemCpyDst : 1;
    102 
    103       /// hasSubelementAccess - This is true if a subelement of the alloca is
    104       /// ever accessed, or false if the alloca is only accessed with mem
    105       /// intrinsics or load/store that only access the entire alloca at once.
    106       bool hasSubelementAccess : 1;
    107 
    108       /// hasALoadOrStore - This is true if there are any loads or stores to it.
    109       /// The alloca may just be accessed with memcpy, for example, which would
    110       /// not set this.
    111       bool hasALoadOrStore : 1;
    112 
    113       explicit AllocaInfo(AllocaInst *ai)
    114         : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
    115           hasSubelementAccess(false), hasALoadOrStore(false) {}
    116     };
    117 
    118     unsigned SRThreshold;
    119 
    120     void MarkUnsafe(AllocaInfo &I, Instruction *User) {
    121       I.isUnsafe = true;
    122       DEBUG(dbgs() << "  Transformation preventing inst: " << *User << '\n');
    123     }
    124 
    125     bool isSafeAllocaToScalarRepl(AllocaInst *AI);
    126 
    127     void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
    128     void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
    129                                          AllocaInfo &Info);
    130     void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
    131     void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
    132                          Type *MemOpType, bool isStore, AllocaInfo &Info,
    133                          Instruction *TheAccess, bool AllowWholeAccess);
    134     bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
    135     uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
    136                                   Type *&IdxTy);
    137 
    138     void DoScalarReplacement(AllocaInst *AI,
    139                              std::vector<AllocaInst*> &WorkList);
    140     void DeleteDeadInstructions();
    141 
    142     void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
    143                               SmallVector<AllocaInst*, 32> &NewElts);
    144     void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
    145                         SmallVector<AllocaInst*, 32> &NewElts);
    146     void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
    147                     SmallVector<AllocaInst*, 32> &NewElts);
    148     void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
    149                                   uint64_t Offset,
    150                                   SmallVector<AllocaInst*, 32> &NewElts);
    151     void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
    152                                       AllocaInst *AI,
    153                                       SmallVector<AllocaInst*, 32> &NewElts);
    154     void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
    155                                        SmallVector<AllocaInst*, 32> &NewElts);
    156     void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
    157                                       SmallVector<AllocaInst*, 32> &NewElts);
    158 
    159     static MemTransferInst *isOnlyCopiedFromConstantGlobal(
    160         AllocaInst *AI, SmallVector<Instruction*, 4> &ToDelete);
    161   };
    162 
    163   // SROA_DT - SROA that uses DominatorTree.
    164   struct SROA_DT : public SROA {
    165     static char ID;
    166   public:
    167     SROA_DT(int T = -1) : SROA(T, true, ID) {
    168       initializeSROA_DTPass(*PassRegistry::getPassRegistry());
    169     }
    170 
    171     // getAnalysisUsage - This pass does not require any passes, but we know it
    172     // will not alter the CFG, so say so.
    173     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    174       AU.addRequired<DominatorTree>();
    175       AU.setPreservesCFG();
    176     }
    177   };
    178 
    179   // SROA_SSAUp - SROA that uses SSAUpdater.
    180   struct SROA_SSAUp : public SROA {
    181     static char ID;
    182   public:
    183     SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
    184       initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
    185     }
    186 
    187     // getAnalysisUsage - This pass does not require any passes, but we know it
    188     // will not alter the CFG, so say so.
    189     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    190       AU.setPreservesCFG();
    191     }
    192   };
    193 
    194 }
    195 
    196 char SROA_DT::ID = 0;
    197 char SROA_SSAUp::ID = 0;
    198 
    199 INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
    200                 "Scalar Replacement of Aggregates (DT)", false, false)
    201 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
    202 INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
    203                 "Scalar Replacement of Aggregates (DT)", false, false)
    204 
    205 INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
    206                       "Scalar Replacement of Aggregates (SSAUp)", false, false)
    207 INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
    208                     "Scalar Replacement of Aggregates (SSAUp)", false, false)
    209 
    210 // Public interface to the ScalarReplAggregates pass
    211 FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
    212                                                    bool UseDomTree) {
    213   if (UseDomTree)
    214     return new SROA_DT(Threshold);
    215   return new SROA_SSAUp(Threshold);
    216 }
    217 
    218 
    219 //===----------------------------------------------------------------------===//
    220 // Convert To Scalar Optimization.
    221 //===----------------------------------------------------------------------===//
    222 
    223 namespace {
    224 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
    225 /// optimization, which scans the uses of an alloca and determines if it can
    226 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
    227 class ConvertToScalarInfo {
    228   /// AllocaSize - The size of the alloca being considered in bytes.
    229   unsigned AllocaSize;
    230   const TargetData &TD;
    231 
    232   /// IsNotTrivial - This is set to true if there is some access to the object
    233   /// which means that mem2reg can't promote it.
    234   bool IsNotTrivial;
    235 
    236   /// ScalarKind - Tracks the kind of alloca being considered for promotion,
    237   /// computed based on the uses of the alloca rather than the LLVM type system.
    238   enum {
    239     Unknown,
    240 
    241     // Accesses via GEPs that are consistent with element access of a vector
    242     // type. This will not be converted into a vector unless there is a later
    243     // access using an actual vector type.
    244     ImplicitVector,
    245 
    246     // Accesses via vector operations and GEPs that are consistent with the
    247     // layout of a vector type.
    248     Vector,
    249 
    250     // An integer bag-of-bits with bitwise operations for insertion and
    251     // extraction. Any combination of types can be converted into this kind
    252     // of scalar.
    253     Integer
    254   } ScalarKind;
    255 
    256   /// VectorTy - This tracks the type that we should promote the vector to if
    257   /// it is possible to turn it into a vector.  This starts out null, and if it
    258   /// isn't possible to turn into a vector type, it gets set to VoidTy.
    259   VectorType *VectorTy;
    260 
    261   /// HadNonMemTransferAccess - True if there is at least one access to the
    262   /// alloca that is not a MemTransferInst.  We don't want to turn structs into
    263   /// large integers unless there is some potential for optimization.
    264   bool HadNonMemTransferAccess;
    265 
    266 public:
    267   explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
    268     : AllocaSize(Size), TD(td), IsNotTrivial(false), ScalarKind(Unknown),
    269       VectorTy(0), HadNonMemTransferAccess(false) { }
    270 
    271   AllocaInst *TryConvert(AllocaInst *AI);
    272 
    273 private:
    274   bool CanConvertToScalar(Value *V, uint64_t Offset);
    275   void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
    276   bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
    277   void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
    278 
    279   Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
    280                                     uint64_t Offset, IRBuilder<> &Builder);
    281   Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
    282                                    uint64_t Offset, IRBuilder<> &Builder);
    283 };
    284 } // end anonymous namespace.
    285 
    286 
    287 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
    288 /// rewrite it to be a new alloca which is mem2reg'able.  This returns the new
    289 /// alloca if possible or null if not.
    290 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
    291   // If we can't convert this scalar, or if mem2reg can trivially do it, bail
    292   // out.
    293   if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
    294     return 0;
    295 
    296   // If an alloca has only memset / memcpy uses, it may still have an Unknown
    297   // ScalarKind. Treat it as an Integer below.
    298   if (ScalarKind == Unknown)
    299     ScalarKind = Integer;
    300 
    301   if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
    302     ScalarKind = Integer;
    303 
    304   // If we were able to find a vector type that can handle this with
    305   // insert/extract elements, and if there was at least one use that had
    306   // a vector type, promote this to a vector.  We don't want to promote
    307   // random stuff that doesn't use vectors (e.g. <9 x double>) because then
    308   // we just get a lot of insert/extracts.  If at least one vector is
    309   // involved, then we probably really do have a union of vector/array.
    310   Type *NewTy;
    311   if (ScalarKind == Vector) {
    312     assert(VectorTy && "Missing type for vector scalar.");
    313     DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n  TYPE = "
    314           << *VectorTy << '\n');
    315     NewTy = VectorTy;  // Use the vector type.
    316   } else {
    317     unsigned BitWidth = AllocaSize * 8;
    318     if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
    319         !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
    320       return 0;
    321 
    322     DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
    323     // Create and insert the integer alloca.
    324     NewTy = IntegerType::get(AI->getContext(), BitWidth);
    325   }
    326   AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
    327   ConvertUsesToScalar(AI, NewAI, 0);
    328   return NewAI;
    329 }
    330 
    331 /// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
    332 /// (VectorTy) so far at the offset specified by Offset (which is specified in
    333 /// bytes).
    334 ///
    335 /// There are two cases we handle here:
    336 ///   1) A union of vector types of the same size and potentially its elements.
    337 ///      Here we turn element accesses into insert/extract element operations.
    338 ///      This promotes a <4 x float> with a store of float to the third element
    339 ///      into a <4 x float> that uses insert element.
    340 ///   2) A fully general blob of memory, which we turn into some (potentially
    341 ///      large) integer type with extract and insert operations where the loads
    342 ///      and stores would mutate the memory.  We mark this by setting VectorTy
    343 ///      to VoidTy.
    344 void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
    345                                                     uint64_t Offset) {
    346   // If we already decided to turn this into a blob of integer memory, there is
    347   // nothing to be done.
    348   if (ScalarKind == Integer)
    349     return;
    350 
    351   // If this could be contributing to a vector, analyze it.
    352 
    353   // If the In type is a vector that is the same size as the alloca, see if it
    354   // matches the existing VecTy.
    355   if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
    356     if (MergeInVectorType(VInTy, Offset))
    357       return;
    358   } else if (In->isFloatTy() || In->isDoubleTy() ||
    359              (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
    360               isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
    361     // Full width accesses can be ignored, because they can always be turned
    362     // into bitcasts.
    363     unsigned EltSize = In->getPrimitiveSizeInBits()/8;
    364     if (EltSize == AllocaSize)
    365       return;
    366 
    367     // If we're accessing something that could be an element of a vector, see
    368     // if the implied vector agrees with what we already have and if Offset is
    369     // compatible with it.
    370     if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
    371         (!VectorTy || EltSize == VectorTy->getElementType()
    372                                          ->getPrimitiveSizeInBits()/8)) {
    373       if (!VectorTy) {
    374         ScalarKind = ImplicitVector;
    375         VectorTy = VectorType::get(In, AllocaSize/EltSize);
    376       }
    377       return;
    378     }
    379   }
    380 
    381   // Otherwise, we have a case that we can't handle with an optimized vector
    382   // form.  We can still turn this into a large integer.
    383   ScalarKind = Integer;
    384 }
    385 
    386 /// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
    387 /// returning true if the type was successfully merged and false otherwise.
    388 bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
    389                                             uint64_t Offset) {
    390   if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
    391     // If we're storing/loading a vector of the right size, allow it as a
    392     // vector.  If this the first vector we see, remember the type so that
    393     // we know the element size. If this is a subsequent access, ignore it
    394     // even if it is a differing type but the same size. Worst case we can
    395     // bitcast the resultant vectors.
    396     if (!VectorTy)
    397       VectorTy = VInTy;
    398     ScalarKind = Vector;
    399     return true;
    400   }
    401 
    402   return false;
    403 }
    404 
    405 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
    406 /// its accesses to a single vector type, return true and set VecTy to
    407 /// the new type.  If we could convert the alloca into a single promotable
    408 /// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
    409 /// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
    410 /// is the current offset from the base of the alloca being analyzed.
    411 ///
    412 /// If we see at least one access to the value that is as a vector type, set the
    413 /// SawVec flag.
    414 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
    415   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
    416     Instruction *User = cast<Instruction>(*UI);
    417 
    418     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
    419       // Don't break volatile loads.
    420       if (!LI->isSimple())
    421         return false;
    422       // Don't touch MMX operations.
    423       if (LI->getType()->isX86_MMXTy())
    424         return false;
    425       HadNonMemTransferAccess = true;
    426       MergeInTypeForLoadOrStore(LI->getType(), Offset);
    427       continue;
    428     }
    429 
    430     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
    431       // Storing the pointer, not into the value?
    432       if (SI->getOperand(0) == V || !SI->isSimple()) return false;
    433       // Don't touch MMX operations.
    434       if (SI->getOperand(0)->getType()->isX86_MMXTy())
    435         return false;
    436       HadNonMemTransferAccess = true;
    437       MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
    438       continue;
    439     }
    440 
    441     if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
    442       if (!onlyUsedByLifetimeMarkers(BCI))
    443         IsNotTrivial = true;  // Can't be mem2reg'd.
    444       if (!CanConvertToScalar(BCI, Offset))
    445         return false;
    446       continue;
    447     }
    448 
    449     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
    450       // If this is a GEP with a variable indices, we can't handle it.
    451       if (!GEP->hasAllConstantIndices())
    452         return false;
    453 
    454       // Compute the offset that this GEP adds to the pointer.
    455       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
    456       uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
    457                                                Indices);
    458       // See if all uses can be converted.
    459       if (!CanConvertToScalar(GEP, Offset+GEPOffset))
    460         return false;
    461       IsNotTrivial = true;  // Can't be mem2reg'd.
    462       HadNonMemTransferAccess = true;
    463       continue;
    464     }
    465 
    466     // If this is a constant sized memset of a constant value (e.g. 0) we can
    467     // handle it.
    468     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
    469       // Store of constant value.
    470       if (!isa<ConstantInt>(MSI->getValue()))
    471         return false;
    472 
    473       // Store of constant size.
    474       ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
    475       if (!Len)
    476         return false;
    477 
    478       // If the size differs from the alloca, we can only convert the alloca to
    479       // an integer bag-of-bits.
    480       // FIXME: This should handle all of the cases that are currently accepted
    481       // as vector element insertions.
    482       if (Len->getZExtValue() != AllocaSize || Offset != 0)
    483         ScalarKind = Integer;
    484 
    485       IsNotTrivial = true;  // Can't be mem2reg'd.
    486       HadNonMemTransferAccess = true;
    487       continue;
    488     }
    489 
    490     // If this is a memcpy or memmove into or out of the whole allocation, we
    491     // can handle it like a load or store of the scalar type.
    492     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
    493       ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
    494       if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
    495         return false;
    496 
    497       IsNotTrivial = true;  // Can't be mem2reg'd.
    498       continue;
    499     }
    500 
    501     // If this is a lifetime intrinsic, we can handle it.
    502     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
    503       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
    504           II->getIntrinsicID() == Intrinsic::lifetime_end) {
    505         continue;
    506       }
    507     }
    508 
    509     // Otherwise, we cannot handle this!
    510     return false;
    511   }
    512 
    513   return true;
    514 }
    515 
    516 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
    517 /// directly.  This happens when we are converting an "integer union" to a
    518 /// single integer scalar, or when we are converting a "vector union" to a
    519 /// vector with insert/extractelement instructions.
    520 ///
    521 /// Offset is an offset from the original alloca, in bits that need to be
    522 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
    523 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
    524                                               uint64_t Offset) {
    525   while (!Ptr->use_empty()) {
    526     Instruction *User = cast<Instruction>(Ptr->use_back());
    527 
    528     if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
    529       ConvertUsesToScalar(CI, NewAI, Offset);
    530       CI->eraseFromParent();
    531       continue;
    532     }
    533 
    534     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
    535       // Compute the offset that this GEP adds to the pointer.
    536       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
    537       uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
    538                                                Indices);
    539       ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
    540       GEP->eraseFromParent();
    541       continue;
    542     }
    543 
    544     IRBuilder<> Builder(User);
    545 
    546     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
    547       // The load is a bit extract from NewAI shifted right by Offset bits.
    548       Value *LoadedVal = Builder.CreateLoad(NewAI);
    549       Value *NewLoadVal
    550         = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
    551       LI->replaceAllUsesWith(NewLoadVal);
    552       LI->eraseFromParent();
    553       continue;
    554     }
    555 
    556     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
    557       assert(SI->getOperand(0) != Ptr && "Consistency error!");
    558       Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
    559       Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
    560                                              Builder);
    561       Builder.CreateStore(New, NewAI);
    562       SI->eraseFromParent();
    563 
    564       // If the load we just inserted is now dead, then the inserted store
    565       // overwrote the entire thing.
    566       if (Old->use_empty())
    567         Old->eraseFromParent();
    568       continue;
    569     }
    570 
    571     // If this is a constant sized memset of a constant value (e.g. 0) we can
    572     // transform it into a store of the expanded constant value.
    573     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
    574       assert(MSI->getRawDest() == Ptr && "Consistency error!");
    575       unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
    576       if (NumBytes != 0) {
    577         unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
    578 
    579         // Compute the value replicated the right number of times.
    580         APInt APVal(NumBytes*8, Val);
    581 
    582         // Splat the value if non-zero.
    583         if (Val)
    584           for (unsigned i = 1; i != NumBytes; ++i)
    585             APVal |= APVal << 8;
    586 
    587         Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
    588         Value *New = ConvertScalar_InsertValue(
    589                                     ConstantInt::get(User->getContext(), APVal),
    590                                                Old, Offset, Builder);
    591         Builder.CreateStore(New, NewAI);
    592 
    593         // If the load we just inserted is now dead, then the memset overwrote
    594         // the entire thing.
    595         if (Old->use_empty())
    596           Old->eraseFromParent();
    597       }
    598       MSI->eraseFromParent();
    599       continue;
    600     }
    601 
    602     // If this is a memcpy or memmove into or out of the whole allocation, we
    603     // can handle it like a load or store of the scalar type.
    604     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
    605       assert(Offset == 0 && "must be store to start of alloca");
    606 
    607       // If the source and destination are both to the same alloca, then this is
    608       // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
    609       // as appropriate.
    610       AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
    611 
    612       if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
    613         // Dest must be OrigAI, change this to be a load from the original
    614         // pointer (bitcasted), then a store to our new alloca.
    615         assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
    616         Value *SrcPtr = MTI->getSource();
    617         PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
    618         PointerType* AIPTy = cast<PointerType>(NewAI->getType());
    619         if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
    620           AIPTy = PointerType::get(AIPTy->getElementType(),
    621                                    SPTy->getAddressSpace());
    622         }
    623         SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
    624 
    625         LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
    626         SrcVal->setAlignment(MTI->getAlignment());
    627         Builder.CreateStore(SrcVal, NewAI);
    628       } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
    629         // Src must be OrigAI, change this to be a load from NewAI then a store
    630         // through the original dest pointer (bitcasted).
    631         assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
    632         LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
    633 
    634         PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
    635         PointerType* AIPTy = cast<PointerType>(NewAI->getType());
    636         if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
    637           AIPTy = PointerType::get(AIPTy->getElementType(),
    638                                    DPTy->getAddressSpace());
    639         }
    640         Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
    641 
    642         StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
    643         NewStore->setAlignment(MTI->getAlignment());
    644       } else {
    645         // Noop transfer. Src == Dst
    646       }
    647 
    648       MTI->eraseFromParent();
    649       continue;
    650     }
    651 
    652     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
    653       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
    654           II->getIntrinsicID() == Intrinsic::lifetime_end) {
    655         // There's no need to preserve these, as the resulting alloca will be
    656         // converted to a register anyways.
    657         II->eraseFromParent();
    658         continue;
    659       }
    660     }
    661 
    662     llvm_unreachable("Unsupported operation!");
    663   }
    664 }
    665 
    666 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
    667 /// or vector value FromVal, extracting the bits from the offset specified by
    668 /// Offset.  This returns the value, which is of type ToType.
    669 ///
    670 /// This happens when we are converting an "integer union" to a single
    671 /// integer scalar, or when we are converting a "vector union" to a vector with
    672 /// insert/extractelement instructions.
    673 ///
    674 /// Offset is an offset from the original alloca, in bits that need to be
    675 /// shifted to the right.
    676 Value *ConvertToScalarInfo::
    677 ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
    678                            uint64_t Offset, IRBuilder<> &Builder) {
    679   // If the load is of the whole new alloca, no conversion is needed.
    680   Type *FromType = FromVal->getType();
    681   if (FromType == ToType && Offset == 0)
    682     return FromVal;
    683 
    684   // If the result alloca is a vector type, this is either an element
    685   // access or a bitcast to another vector type of the same size.
    686   if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
    687     unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
    688     unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
    689     if (FromTypeSize == ToTypeSize)
    690         return Builder.CreateBitCast(FromVal, ToType);
    691 
    692     // Otherwise it must be an element access.
    693     unsigned Elt = 0;
    694     if (Offset) {
    695       unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
    696       Elt = Offset/EltSize;
    697       assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
    698     }
    699     // Return the element extracted out of it.
    700     Value *V = Builder.CreateExtractElement(FromVal, Builder.getInt32(Elt));
    701     if (V->getType() != ToType)
    702       V = Builder.CreateBitCast(V, ToType);
    703     return V;
    704   }
    705 
    706   // If ToType is a first class aggregate, extract out each of the pieces and
    707   // use insertvalue's to form the FCA.
    708   if (StructType *ST = dyn_cast<StructType>(ToType)) {
    709     const StructLayout &Layout = *TD.getStructLayout(ST);
    710     Value *Res = UndefValue::get(ST);
    711     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
    712       Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
    713                                         Offset+Layout.getElementOffsetInBits(i),
    714                                               Builder);
    715       Res = Builder.CreateInsertValue(Res, Elt, i);
    716     }
    717     return Res;
    718   }
    719 
    720   if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
    721     uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
    722     Value *Res = UndefValue::get(AT);
    723     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
    724       Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
    725                                               Offset+i*EltSize, Builder);
    726       Res = Builder.CreateInsertValue(Res, Elt, i);
    727     }
    728     return Res;
    729   }
    730 
    731   // Otherwise, this must be a union that was converted to an integer value.
    732   IntegerType *NTy = cast<IntegerType>(FromVal->getType());
    733 
    734   // If this is a big-endian system and the load is narrower than the
    735   // full alloca type, we need to do a shift to get the right bits.
    736   int ShAmt = 0;
    737   if (TD.isBigEndian()) {
    738     // On big-endian machines, the lowest bit is stored at the bit offset
    739     // from the pointer given by getTypeStoreSizeInBits.  This matters for
    740     // integers with a bitwidth that is not a multiple of 8.
    741     ShAmt = TD.getTypeStoreSizeInBits(NTy) -
    742             TD.getTypeStoreSizeInBits(ToType) - Offset;
    743   } else {
    744     ShAmt = Offset;
    745   }
    746 
    747   // Note: we support negative bitwidths (with shl) which are not defined.
    748   // We do this to support (f.e.) loads off the end of a structure where
    749   // only some bits are used.
    750   if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
    751     FromVal = Builder.CreateLShr(FromVal,
    752                                  ConstantInt::get(FromVal->getType(), ShAmt));
    753   else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
    754     FromVal = Builder.CreateShl(FromVal,
    755                                 ConstantInt::get(FromVal->getType(), -ShAmt));
    756 
    757   // Finally, unconditionally truncate the integer to the right width.
    758   unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
    759   if (LIBitWidth < NTy->getBitWidth())
    760     FromVal =
    761       Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
    762                                                     LIBitWidth));
    763   else if (LIBitWidth > NTy->getBitWidth())
    764     FromVal =
    765        Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
    766                                                     LIBitWidth));
    767 
    768   // If the result is an integer, this is a trunc or bitcast.
    769   if (ToType->isIntegerTy()) {
    770     // Should be done.
    771   } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
    772     // Just do a bitcast, we know the sizes match up.
    773     FromVal = Builder.CreateBitCast(FromVal, ToType);
    774   } else {
    775     // Otherwise must be a pointer.
    776     FromVal = Builder.CreateIntToPtr(FromVal, ToType);
    777   }
    778   assert(FromVal->getType() == ToType && "Didn't convert right?");
    779   return FromVal;
    780 }
    781 
    782 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
    783 /// or vector value "Old" at the offset specified by Offset.
    784 ///
    785 /// This happens when we are converting an "integer union" to a
    786 /// single integer scalar, or when we are converting a "vector union" to a
    787 /// vector with insert/extractelement instructions.
    788 ///
    789 /// Offset is an offset from the original alloca, in bits that need to be
    790 /// shifted to the right.
    791 Value *ConvertToScalarInfo::
    792 ConvertScalar_InsertValue(Value *SV, Value *Old,
    793                           uint64_t Offset, IRBuilder<> &Builder) {
    794   // Convert the stored type to the actual type, shift it left to insert
    795   // then 'or' into place.
    796   Type *AllocaType = Old->getType();
    797   LLVMContext &Context = Old->getContext();
    798 
    799   if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
    800     uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
    801     uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
    802 
    803     // Changing the whole vector with memset or with an access of a different
    804     // vector type?
    805     if (ValSize == VecSize)
    806         return Builder.CreateBitCast(SV, AllocaType);
    807 
    808     // Must be an element insertion.
    809     assert(SV->getType() == VTy->getElementType());
    810     uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
    811     unsigned Elt = Offset/EltSize;
    812     return Builder.CreateInsertElement(Old, SV, Builder.getInt32(Elt));
    813   }
    814 
    815   // If SV is a first-class aggregate value, insert each value recursively.
    816   if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
    817     const StructLayout &Layout = *TD.getStructLayout(ST);
    818     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
    819       Value *Elt = Builder.CreateExtractValue(SV, i);
    820       Old = ConvertScalar_InsertValue(Elt, Old,
    821                                       Offset+Layout.getElementOffsetInBits(i),
    822                                       Builder);
    823     }
    824     return Old;
    825   }
    826 
    827   if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
    828     uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
    829     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
    830       Value *Elt = Builder.CreateExtractValue(SV, i);
    831       Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
    832     }
    833     return Old;
    834   }
    835 
    836   // If SV is a float, convert it to the appropriate integer type.
    837   // If it is a pointer, do the same.
    838   unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
    839   unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
    840   unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
    841   unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
    842   if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
    843     SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
    844   else if (SV->getType()->isPointerTy())
    845     SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()));
    846 
    847   // Zero extend or truncate the value if needed.
    848   if (SV->getType() != AllocaType) {
    849     if (SV->getType()->getPrimitiveSizeInBits() <
    850              AllocaType->getPrimitiveSizeInBits())
    851       SV = Builder.CreateZExt(SV, AllocaType);
    852     else {
    853       // Truncation may be needed if storing more than the alloca can hold
    854       // (undefined behavior).
    855       SV = Builder.CreateTrunc(SV, AllocaType);
    856       SrcWidth = DestWidth;
    857       SrcStoreWidth = DestStoreWidth;
    858     }
    859   }
    860 
    861   // If this is a big-endian system and the store is narrower than the
    862   // full alloca type, we need to do a shift to get the right bits.
    863   int ShAmt = 0;
    864   if (TD.isBigEndian()) {
    865     // On big-endian machines, the lowest bit is stored at the bit offset
    866     // from the pointer given by getTypeStoreSizeInBits.  This matters for
    867     // integers with a bitwidth that is not a multiple of 8.
    868     ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
    869   } else {
    870     ShAmt = Offset;
    871   }
    872 
    873   // Note: we support negative bitwidths (with shr) which are not defined.
    874   // We do this to support (f.e.) stores off the end of a structure where
    875   // only some bits in the structure are set.
    876   APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
    877   if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
    878     SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
    879     Mask <<= ShAmt;
    880   } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
    881     SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
    882     Mask = Mask.lshr(-ShAmt);
    883   }
    884 
    885   // Mask out the bits we are about to insert from the old value, and or
    886   // in the new bits.
    887   if (SrcWidth != DestWidth) {
    888     assert(DestWidth > SrcWidth);
    889     Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
    890     SV = Builder.CreateOr(Old, SV, "ins");
    891   }
    892   return SV;
    893 }
    894 
    895 
    896 //===----------------------------------------------------------------------===//
    897 // SRoA Driver
    898 //===----------------------------------------------------------------------===//
    899 
    900 
    901 bool SROA::runOnFunction(Function &F) {
    902   TD = getAnalysisIfAvailable<TargetData>();
    903 
    904   bool Changed = performPromotion(F);
    905 
    906   // FIXME: ScalarRepl currently depends on TargetData more than it
    907   // theoretically needs to. It should be refactored in order to support
    908   // target-independent IR. Until this is done, just skip the actual
    909   // scalar-replacement portion of this pass.
    910   if (!TD) return Changed;
    911 
    912   while (1) {
    913     bool LocalChange = performScalarRepl(F);
    914     if (!LocalChange) break;   // No need to repromote if no scalarrepl
    915     Changed = true;
    916     LocalChange = performPromotion(F);
    917     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
    918   }
    919 
    920   return Changed;
    921 }
    922 
    923 namespace {
    924 class AllocaPromoter : public LoadAndStorePromoter {
    925   AllocaInst *AI;
    926   DIBuilder *DIB;
    927   SmallVector<DbgDeclareInst *, 4> DDIs;
    928   SmallVector<DbgValueInst *, 4> DVIs;
    929 public:
    930   AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
    931                  DIBuilder *DB)
    932     : LoadAndStorePromoter(Insts, S), AI(0), DIB(DB) {}
    933 
    934   void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
    935     // Remember which alloca we're promoting (for isInstInList).
    936     this->AI = AI;
    937     if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI))
    938       for (Value::use_iterator UI = DebugNode->use_begin(),
    939              E = DebugNode->use_end(); UI != E; ++UI)
    940         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
    941           DDIs.push_back(DDI);
    942         else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
    943           DVIs.push_back(DVI);
    944 
    945     LoadAndStorePromoter::run(Insts);
    946     AI->eraseFromParent();
    947     for (SmallVector<DbgDeclareInst *, 4>::iterator I = DDIs.begin(),
    948            E = DDIs.end(); I != E; ++I) {
    949       DbgDeclareInst *DDI = *I;
    950       DDI->eraseFromParent();
    951     }
    952     for (SmallVector<DbgValueInst *, 4>::iterator I = DVIs.begin(),
    953            E = DVIs.end(); I != E; ++I) {
    954       DbgValueInst *DVI = *I;
    955       DVI->eraseFromParent();
    956     }
    957   }
    958 
    959   virtual bool isInstInList(Instruction *I,
    960                             const SmallVectorImpl<Instruction*> &Insts) const {
    961     if (LoadInst *LI = dyn_cast<LoadInst>(I))
    962       return LI->getOperand(0) == AI;
    963     return cast<StoreInst>(I)->getPointerOperand() == AI;
    964   }
    965 
    966   virtual void updateDebugInfo(Instruction *Inst) const {
    967     for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
    968            E = DDIs.end(); I != E; ++I) {
    969       DbgDeclareInst *DDI = *I;
    970       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
    971         ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
    972       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
    973         ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
    974     }
    975     for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
    976            E = DVIs.end(); I != E; ++I) {
    977       DbgValueInst *DVI = *I;
    978       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
    979         Instruction *DbgVal = NULL;
    980         // If an argument is zero extended then use argument directly. The ZExt
    981         // may be zapped by an optimization pass in future.
    982         Argument *ExtendedArg = NULL;
    983         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
    984           ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
    985         if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
    986           ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
    987         if (ExtendedArg)
    988           DbgVal = DIB->insertDbgValueIntrinsic(ExtendedArg, 0,
    989                                                 DIVariable(DVI->getVariable()),
    990                                                 SI);
    991         else
    992           DbgVal = DIB->insertDbgValueIntrinsic(SI->getOperand(0), 0,
    993                                                 DIVariable(DVI->getVariable()),
    994                                                 SI);
    995         DbgVal->setDebugLoc(DVI->getDebugLoc());
    996       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
    997         Instruction *DbgVal =
    998           DIB->insertDbgValueIntrinsic(LI->getOperand(0), 0,
    999                                        DIVariable(DVI->getVariable()), LI);
   1000         DbgVal->setDebugLoc(DVI->getDebugLoc());
   1001       }
   1002     }
   1003   }
   1004 };
   1005 } // end anon namespace
   1006 
   1007 /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
   1008 /// subsequently loaded can be rewritten to load both input pointers and then
   1009 /// select between the result, allowing the load of the alloca to be promoted.
   1010 /// From this:
   1011 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
   1012 ///   %V = load i32* %P2
   1013 /// to:
   1014 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
   1015 ///   %V2 = load i32* %Other
   1016 ///   %V = select i1 %cond, i32 %V1, i32 %V2
   1017 ///
   1018 /// We can do this to a select if its only uses are loads and if the operand to
   1019 /// the select can be loaded unconditionally.
   1020 static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
   1021   bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
   1022   bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
   1023 
   1024   for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
   1025        UI != UE; ++UI) {
   1026     LoadInst *LI = dyn_cast<LoadInst>(*UI);
   1027     if (LI == 0 || !LI->isSimple()) return false;
   1028 
   1029     // Both operands to the select need to be dereferencable, either absolutely
   1030     // (e.g. allocas) or at this point because we can see other accesses to it.
   1031     if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
   1032                                                     LI->getAlignment(), TD))
   1033       return false;
   1034     if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
   1035                                                     LI->getAlignment(), TD))
   1036       return false;
   1037   }
   1038 
   1039   return true;
   1040 }
   1041 
   1042 /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
   1043 /// subsequently loaded can be rewritten to load both input pointers in the pred
   1044 /// blocks and then PHI the results, allowing the load of the alloca to be
   1045 /// promoted.
   1046 /// From this:
   1047 ///   %P2 = phi [i32* %Alloca, i32* %Other]
   1048 ///   %V = load i32* %P2
   1049 /// to:
   1050 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
   1051 ///   ...
   1052 ///   %V2 = load i32* %Other
   1053 ///   ...
   1054 ///   %V = phi [i32 %V1, i32 %V2]
   1055 ///
   1056 /// We can do this to a select if its only uses are loads and if the operand to
   1057 /// the select can be loaded unconditionally.
   1058 static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
   1059   // For now, we can only do this promotion if the load is in the same block as
   1060   // the PHI, and if there are no stores between the phi and load.
   1061   // TODO: Allow recursive phi users.
   1062   // TODO: Allow stores.
   1063   BasicBlock *BB = PN->getParent();
   1064   unsigned MaxAlign = 0;
   1065   for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
   1066        UI != UE; ++UI) {
   1067     LoadInst *LI = dyn_cast<LoadInst>(*UI);
   1068     if (LI == 0 || !LI->isSimple()) return false;
   1069 
   1070     // For now we only allow loads in the same block as the PHI.  This is a
   1071     // common case that happens when instcombine merges two loads through a PHI.
   1072     if (LI->getParent() != BB) return false;
   1073 
   1074     // Ensure that there are no instructions between the PHI and the load that
   1075     // could store.
   1076     for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
   1077       if (BBI->mayWriteToMemory())
   1078         return false;
   1079 
   1080     MaxAlign = std::max(MaxAlign, LI->getAlignment());
   1081   }
   1082 
   1083   // Okay, we know that we have one or more loads in the same block as the PHI.
   1084   // We can transform this if it is safe to push the loads into the predecessor
   1085   // blocks.  The only thing to watch out for is that we can't put a possibly
   1086   // trapping load in the predecessor if it is a critical edge.
   1087   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
   1088     BasicBlock *Pred = PN->getIncomingBlock(i);
   1089     Value *InVal = PN->getIncomingValue(i);
   1090 
   1091     // If the terminator of the predecessor has side-effects (an invoke),
   1092     // there is no safe place to put a load in the predecessor.
   1093     if (Pred->getTerminator()->mayHaveSideEffects())
   1094       return false;
   1095 
   1096     // If the value is produced by the terminator of the predecessor
   1097     // (an invoke), there is no valid place to put a load in the predecessor.
   1098     if (Pred->getTerminator() == InVal)
   1099       return false;
   1100 
   1101     // If the predecessor has a single successor, then the edge isn't critical.
   1102     if (Pred->getTerminator()->getNumSuccessors() == 1)
   1103       continue;
   1104 
   1105     // If this pointer is always safe to load, or if we can prove that there is
   1106     // already a load in the block, then we can move the load to the pred block.
   1107     if (InVal->isDereferenceablePointer() ||
   1108         isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
   1109       continue;
   1110 
   1111     return false;
   1112   }
   1113 
   1114   return true;
   1115 }
   1116 
   1117 
   1118 /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
   1119 /// direct (non-volatile) loads and stores to it.  If the alloca is close but
   1120 /// not quite there, this will transform the code to allow promotion.  As such,
   1121 /// it is a non-pure predicate.
   1122 static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
   1123   SetVector<Instruction*, SmallVector<Instruction*, 4>,
   1124             SmallPtrSet<Instruction*, 4> > InstsToRewrite;
   1125 
   1126   for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
   1127        UI != UE; ++UI) {
   1128     User *U = *UI;
   1129     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
   1130       if (!LI->isSimple())
   1131         return false;
   1132       continue;
   1133     }
   1134 
   1135     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
   1136       if (SI->getOperand(0) == AI || !SI->isSimple())
   1137         return false;   // Don't allow a store OF the AI, only INTO the AI.
   1138       continue;
   1139     }
   1140 
   1141     if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
   1142       // If the condition being selected on is a constant, fold the select, yes
   1143       // this does (rarely) happen early on.
   1144       if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
   1145         Value *Result = SI->getOperand(1+CI->isZero());
   1146         SI->replaceAllUsesWith(Result);
   1147         SI->eraseFromParent();
   1148 
   1149         // This is very rare and we just scrambled the use list of AI, start
   1150         // over completely.
   1151         return tryToMakeAllocaBePromotable(AI, TD);
   1152       }
   1153 
   1154       // If it is safe to turn "load (select c, AI, ptr)" into a select of two
   1155       // loads, then we can transform this by rewriting the select.
   1156       if (!isSafeSelectToSpeculate(SI, TD))
   1157         return false;
   1158 
   1159       InstsToRewrite.insert(SI);
   1160       continue;
   1161     }
   1162 
   1163     if (PHINode *PN = dyn_cast<PHINode>(U)) {
   1164       if (PN->use_empty()) {  // Dead PHIs can be stripped.
   1165         InstsToRewrite.insert(PN);
   1166         continue;
   1167       }
   1168 
   1169       // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
   1170       // in the pred blocks, then we can transform this by rewriting the PHI.
   1171       if (!isSafePHIToSpeculate(PN, TD))
   1172         return false;
   1173 
   1174       InstsToRewrite.insert(PN);
   1175       continue;
   1176     }
   1177 
   1178     if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
   1179       if (onlyUsedByLifetimeMarkers(BCI)) {
   1180         InstsToRewrite.insert(BCI);
   1181         continue;
   1182       }
   1183     }
   1184 
   1185     return false;
   1186   }
   1187 
   1188   // If there are no instructions to rewrite, then all uses are load/stores and
   1189   // we're done!
   1190   if (InstsToRewrite.empty())
   1191     return true;
   1192 
   1193   // If we have instructions that need to be rewritten for this to be promotable
   1194   // take care of it now.
   1195   for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
   1196     if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
   1197       // This could only be a bitcast used by nothing but lifetime intrinsics.
   1198       for (BitCastInst::use_iterator I = BCI->use_begin(), E = BCI->use_end();
   1199            I != E;) {
   1200         Use &U = I.getUse();
   1201         ++I;
   1202         cast<Instruction>(U.getUser())->eraseFromParent();
   1203       }
   1204       BCI->eraseFromParent();
   1205       continue;
   1206     }
   1207 
   1208     if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
   1209       // Selects in InstsToRewrite only have load uses.  Rewrite each as two
   1210       // loads with a new select.
   1211       while (!SI->use_empty()) {
   1212         LoadInst *LI = cast<LoadInst>(SI->use_back());
   1213 
   1214         IRBuilder<> Builder(LI);
   1215         LoadInst *TrueLoad =
   1216           Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
   1217         LoadInst *FalseLoad =
   1218           Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
   1219 
   1220         // Transfer alignment and TBAA info if present.
   1221         TrueLoad->setAlignment(LI->getAlignment());
   1222         FalseLoad->setAlignment(LI->getAlignment());
   1223         if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
   1224           TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
   1225           FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
   1226         }
   1227 
   1228         Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
   1229         V->takeName(LI);
   1230         LI->replaceAllUsesWith(V);
   1231         LI->eraseFromParent();
   1232       }
   1233 
   1234       // Now that all the loads are gone, the select is gone too.
   1235       SI->eraseFromParent();
   1236       continue;
   1237     }
   1238 
   1239     // Otherwise, we have a PHI node which allows us to push the loads into the
   1240     // predecessors.
   1241     PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
   1242     if (PN->use_empty()) {
   1243       PN->eraseFromParent();
   1244       continue;
   1245     }
   1246 
   1247     Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
   1248     PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
   1249                                      PN->getName()+".ld", PN);
   1250 
   1251     // Get the TBAA tag and alignment to use from one of the loads.  It doesn't
   1252     // matter which one we get and if any differ, it doesn't matter.
   1253     LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
   1254     MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
   1255     unsigned Align = SomeLoad->getAlignment();
   1256 
   1257     // Rewrite all loads of the PN to use the new PHI.
   1258     while (!PN->use_empty()) {
   1259       LoadInst *LI = cast<LoadInst>(PN->use_back());
   1260       LI->replaceAllUsesWith(NewPN);
   1261       LI->eraseFromParent();
   1262     }
   1263 
   1264     // Inject loads into all of the pred blocks.  Keep track of which blocks we
   1265     // insert them into in case we have multiple edges from the same block.
   1266     DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
   1267 
   1268     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
   1269       BasicBlock *Pred = PN->getIncomingBlock(i);
   1270       LoadInst *&Load = InsertedLoads[Pred];
   1271       if (Load == 0) {
   1272         Load = new LoadInst(PN->getIncomingValue(i),
   1273                             PN->getName() + "." + Pred->getName(),
   1274                             Pred->getTerminator());
   1275         Load->setAlignment(Align);
   1276         if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
   1277       }
   1278 
   1279       NewPN->addIncoming(Load, Pred);
   1280     }
   1281 
   1282     PN->eraseFromParent();
   1283   }
   1284 
   1285   ++NumAdjusted;
   1286   return true;
   1287 }
   1288 
   1289 bool SROA::performPromotion(Function &F) {
   1290   std::vector<AllocaInst*> Allocas;
   1291   DominatorTree *DT = 0;
   1292   if (HasDomTree)
   1293     DT = &getAnalysis<DominatorTree>();
   1294 
   1295   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
   1296   DIBuilder DIB(*F.getParent());
   1297   bool Changed = false;
   1298   SmallVector<Instruction*, 64> Insts;
   1299   while (1) {
   1300     Allocas.clear();
   1301 
   1302     // Find allocas that are safe to promote, by looking at all instructions in
   1303     // the entry node
   1304     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
   1305       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
   1306         if (tryToMakeAllocaBePromotable(AI, TD))
   1307           Allocas.push_back(AI);
   1308 
   1309     if (Allocas.empty()) break;
   1310 
   1311     if (HasDomTree)
   1312       PromoteMemToReg(Allocas, *DT);
   1313     else {
   1314       SSAUpdater SSA;
   1315       for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
   1316         AllocaInst *AI = Allocas[i];
   1317 
   1318         // Build list of instructions to promote.
   1319         for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
   1320              UI != E; ++UI)
   1321           Insts.push_back(cast<Instruction>(*UI));
   1322         AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
   1323         Insts.clear();
   1324       }
   1325     }
   1326     NumPromoted += Allocas.size();
   1327     Changed = true;
   1328   }
   1329 
   1330   return Changed;
   1331 }
   1332 
   1333 
   1334 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
   1335 /// SROA.  It must be a struct or array type with a small number of elements.
   1336 static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
   1337   Type *T = AI->getAllocatedType();
   1338   // Do not promote any struct into more than 32 separate vars.
   1339   if (StructType *ST = dyn_cast<StructType>(T))
   1340     return ST->getNumElements() <= 32;
   1341   // Arrays are much less likely to be safe for SROA; only consider
   1342   // them if they are very small.
   1343   if (ArrayType *AT = dyn_cast<ArrayType>(T))
   1344     return AT->getNumElements() <= 8;
   1345   return false;
   1346 }
   1347 
   1348 
   1349 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
   1350 // which runs on all of the alloca instructions in the function, removing them
   1351 // if they are only used by getelementptr instructions.
   1352 //
   1353 bool SROA::performScalarRepl(Function &F) {
   1354   std::vector<AllocaInst*> WorkList;
   1355 
   1356   // Scan the entry basic block, adding allocas to the worklist.
   1357   BasicBlock &BB = F.getEntryBlock();
   1358   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
   1359     if (AllocaInst *A = dyn_cast<AllocaInst>(I))
   1360       WorkList.push_back(A);
   1361 
   1362   // Process the worklist
   1363   bool Changed = false;
   1364   while (!WorkList.empty()) {
   1365     AllocaInst *AI = WorkList.back();
   1366     WorkList.pop_back();
   1367 
   1368     // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
   1369     // with unused elements.
   1370     if (AI->use_empty()) {
   1371       AI->eraseFromParent();
   1372       Changed = true;
   1373       continue;
   1374     }
   1375 
   1376     // If this alloca is impossible for us to promote, reject it early.
   1377     if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
   1378       continue;
   1379 
   1380     // Check to see if this allocation is only modified by a memcpy/memmove from
   1381     // a constant global.  If this is the case, we can change all users to use
   1382     // the constant global instead.  This is commonly produced by the CFE by
   1383     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
   1384     // is only subsequently read.
   1385     SmallVector<Instruction *, 4> ToDelete;
   1386     if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(AI, ToDelete)) {
   1387       DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
   1388       DEBUG(dbgs() << "  memcpy = " << *Copy << '\n');
   1389       for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
   1390         ToDelete[i]->eraseFromParent();
   1391       Constant *TheSrc = cast<Constant>(Copy->getSource());
   1392       AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
   1393       Copy->eraseFromParent();  // Don't mutate the global.
   1394       AI->eraseFromParent();
   1395       ++NumGlobals;
   1396       Changed = true;
   1397       continue;
   1398     }
   1399 
   1400     // Check to see if we can perform the core SROA transformation.  We cannot
   1401     // transform the allocation instruction if it is an array allocation
   1402     // (allocations OF arrays are ok though), and an allocation of a scalar
   1403     // value cannot be decomposed at all.
   1404     uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
   1405 
   1406     // Do not promote [0 x %struct].
   1407     if (AllocaSize == 0) continue;
   1408 
   1409     // Do not promote any struct whose size is too big.
   1410     if (AllocaSize > SRThreshold) continue;
   1411 
   1412     // If the alloca looks like a good candidate for scalar replacement, and if
   1413     // all its users can be transformed, then split up the aggregate into its
   1414     // separate elements.
   1415     if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
   1416       DoScalarReplacement(AI, WorkList);
   1417       Changed = true;
   1418       continue;
   1419     }
   1420 
   1421     // If we can turn this aggregate value (potentially with casts) into a
   1422     // simple scalar value that can be mem2reg'd into a register value.
   1423     // IsNotTrivial tracks whether this is something that mem2reg could have
   1424     // promoted itself.  If so, we don't want to transform it needlessly.  Note
   1425     // that we can't just check based on the type: the alloca may be of an i32
   1426     // but that has pointer arithmetic to set byte 3 of it or something.
   1427     if (AllocaInst *NewAI =
   1428           ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
   1429       NewAI->takeName(AI);
   1430       AI->eraseFromParent();
   1431       ++NumConverted;
   1432       Changed = true;
   1433       continue;
   1434     }
   1435 
   1436     // Otherwise, couldn't process this alloca.
   1437   }
   1438 
   1439   return Changed;
   1440 }
   1441 
   1442 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
   1443 /// predicate, do SROA now.
   1444 void SROA::DoScalarReplacement(AllocaInst *AI,
   1445                                std::vector<AllocaInst*> &WorkList) {
   1446   DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
   1447   SmallVector<AllocaInst*, 32> ElementAllocas;
   1448   if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
   1449     ElementAllocas.reserve(ST->getNumContainedTypes());
   1450     for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
   1451       AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
   1452                                       AI->getAlignment(),
   1453                                       AI->getName() + "." + Twine(i), AI);
   1454       ElementAllocas.push_back(NA);
   1455       WorkList.push_back(NA);  // Add to worklist for recursive processing
   1456     }
   1457   } else {
   1458     ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
   1459     ElementAllocas.reserve(AT->getNumElements());
   1460     Type *ElTy = AT->getElementType();
   1461     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
   1462       AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
   1463                                       AI->getName() + "." + Twine(i), AI);
   1464       ElementAllocas.push_back(NA);
   1465       WorkList.push_back(NA);  // Add to worklist for recursive processing
   1466     }
   1467   }
   1468 
   1469   // Now that we have created the new alloca instructions, rewrite all the
   1470   // uses of the old alloca.
   1471   RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
   1472 
   1473   // Now erase any instructions that were made dead while rewriting the alloca.
   1474   DeleteDeadInstructions();
   1475   AI->eraseFromParent();
   1476 
   1477   ++NumReplaced;
   1478 }
   1479 
   1480 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
   1481 /// recursively including all their operands that become trivially dead.
   1482 void SROA::DeleteDeadInstructions() {
   1483   while (!DeadInsts.empty()) {
   1484     Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
   1485 
   1486     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
   1487       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
   1488         // Zero out the operand and see if it becomes trivially dead.
   1489         // (But, don't add allocas to the dead instruction list -- they are
   1490         // already on the worklist and will be deleted separately.)
   1491         *OI = 0;
   1492         if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
   1493           DeadInsts.push_back(U);
   1494       }
   1495 
   1496     I->eraseFromParent();
   1497   }
   1498 }
   1499 
   1500 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
   1501 /// performing scalar replacement of alloca AI.  The results are flagged in
   1502 /// the Info parameter.  Offset indicates the position within AI that is
   1503 /// referenced by this instruction.
   1504 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
   1505                                AllocaInfo &Info) {
   1506   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
   1507     Instruction *User = cast<Instruction>(*UI);
   1508 
   1509     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
   1510       isSafeForScalarRepl(BC, Offset, Info);
   1511     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
   1512       uint64_t GEPOffset = Offset;
   1513       isSafeGEP(GEPI, GEPOffset, Info);
   1514       if (!Info.isUnsafe)
   1515         isSafeForScalarRepl(GEPI, GEPOffset, Info);
   1516     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
   1517       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
   1518       if (Length == 0)
   1519         return MarkUnsafe(Info, User);
   1520       isSafeMemAccess(Offset, Length->getZExtValue(), 0,
   1521                       UI.getOperandNo() == 0, Info, MI,
   1522                       true /*AllowWholeAccess*/);
   1523     } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
   1524       if (!LI->isSimple())
   1525         return MarkUnsafe(Info, User);
   1526       Type *LIType = LI->getType();
   1527       isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
   1528                       LIType, false, Info, LI, true /*AllowWholeAccess*/);
   1529       Info.hasALoadOrStore = true;
   1530 
   1531     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
   1532       // Store is ok if storing INTO the pointer, not storing the pointer
   1533       if (!SI->isSimple() || SI->getOperand(0) == I)
   1534         return MarkUnsafe(Info, User);
   1535 
   1536       Type *SIType = SI->getOperand(0)->getType();
   1537       isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
   1538                       SIType, true, Info, SI, true /*AllowWholeAccess*/);
   1539       Info.hasALoadOrStore = true;
   1540     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
   1541       if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
   1542           II->getIntrinsicID() != Intrinsic::lifetime_end)
   1543         return MarkUnsafe(Info, User);
   1544     } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
   1545       isSafePHISelectUseForScalarRepl(User, Offset, Info);
   1546     } else {
   1547       return MarkUnsafe(Info, User);
   1548     }
   1549     if (Info.isUnsafe) return;
   1550   }
   1551 }
   1552 
   1553 
   1554 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
   1555 /// derived from the alloca, we can often still split the alloca into elements.
   1556 /// This is useful if we have a large alloca where one element is phi'd
   1557 /// together somewhere: we can SRoA and promote all the other elements even if
   1558 /// we end up not being able to promote this one.
   1559 ///
   1560 /// All we require is that the uses of the PHI do not index into other parts of
   1561 /// the alloca.  The most important use case for this is single load and stores
   1562 /// that are PHI'd together, which can happen due to code sinking.
   1563 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
   1564                                            AllocaInfo &Info) {
   1565   // If we've already checked this PHI, don't do it again.
   1566   if (PHINode *PN = dyn_cast<PHINode>(I))
   1567     if (!Info.CheckedPHIs.insert(PN))
   1568       return;
   1569 
   1570   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
   1571     Instruction *User = cast<Instruction>(*UI);
   1572 
   1573     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
   1574       isSafePHISelectUseForScalarRepl(BC, Offset, Info);
   1575     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
   1576       // Only allow "bitcast" GEPs for simplicity.  We could generalize this,
   1577       // but would have to prove that we're staying inside of an element being
   1578       // promoted.
   1579       if (!GEPI->hasAllZeroIndices())
   1580         return MarkUnsafe(Info, User);
   1581       isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
   1582     } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
   1583       if (!LI->isSimple())
   1584         return MarkUnsafe(Info, User);
   1585       Type *LIType = LI->getType();
   1586       isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
   1587                       LIType, false, Info, LI, false /*AllowWholeAccess*/);
   1588       Info.hasALoadOrStore = true;
   1589 
   1590     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
   1591       // Store is ok if storing INTO the pointer, not storing the pointer
   1592       if (!SI->isSimple() || SI->getOperand(0) == I)
   1593         return MarkUnsafe(Info, User);
   1594 
   1595       Type *SIType = SI->getOperand(0)->getType();
   1596       isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
   1597                       SIType, true, Info, SI, false /*AllowWholeAccess*/);
   1598       Info.hasALoadOrStore = true;
   1599     } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
   1600       isSafePHISelectUseForScalarRepl(User, Offset, Info);
   1601     } else {
   1602       return MarkUnsafe(Info, User);
   1603     }
   1604     if (Info.isUnsafe) return;
   1605   }
   1606 }
   1607 
   1608 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
   1609 /// replacement.  It is safe when all the indices are constant, in-bounds
   1610 /// references, and when the resulting offset corresponds to an element within
   1611 /// the alloca type.  The results are flagged in the Info parameter.  Upon
   1612 /// return, Offset is adjusted as specified by the GEP indices.
   1613 void SROA::isSafeGEP(GetElementPtrInst *GEPI,
   1614                      uint64_t &Offset, AllocaInfo &Info) {
   1615   gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
   1616   if (GEPIt == E)
   1617     return;
   1618 
   1619   // Walk through the GEP type indices, checking the types that this indexes
   1620   // into.
   1621   for (; GEPIt != E; ++GEPIt) {
   1622     // Ignore struct elements, no extra checking needed for these.
   1623     if ((*GEPIt)->isStructTy())
   1624       continue;
   1625 
   1626     ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
   1627     if (!IdxVal)
   1628       return MarkUnsafe(Info, GEPI);
   1629   }
   1630 
   1631   // Compute the offset due to this GEP and check if the alloca has a
   1632   // component element at that offset.
   1633   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
   1634   Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
   1635   if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
   1636     MarkUnsafe(Info, GEPI);
   1637 }
   1638 
   1639 /// isHomogeneousAggregate - Check if type T is a struct or array containing
   1640 /// elements of the same type (which is always true for arrays).  If so,
   1641 /// return true with NumElts and EltTy set to the number of elements and the
   1642 /// element type, respectively.
   1643 static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
   1644                                    Type *&EltTy) {
   1645   if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
   1646     NumElts = AT->getNumElements();
   1647     EltTy = (NumElts == 0 ? 0 : AT->getElementType());
   1648     return true;
   1649   }
   1650   if (StructType *ST = dyn_cast<StructType>(T)) {
   1651     NumElts = ST->getNumContainedTypes();
   1652     EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
   1653     for (unsigned n = 1; n < NumElts; ++n) {
   1654       if (ST->getContainedType(n) != EltTy)
   1655         return false;
   1656     }
   1657     return true;
   1658   }
   1659   return false;
   1660 }
   1661 
   1662 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
   1663 /// "homogeneous" aggregates with the same element type and number of elements.
   1664 static bool isCompatibleAggregate(Type *T1, Type *T2) {
   1665   if (T1 == T2)
   1666     return true;
   1667 
   1668   unsigned NumElts1, NumElts2;
   1669   Type *EltTy1, *EltTy2;
   1670   if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
   1671       isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
   1672       NumElts1 == NumElts2 &&
   1673       EltTy1 == EltTy2)
   1674     return true;
   1675 
   1676   return false;
   1677 }
   1678 
   1679 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
   1680 /// alloca or has an offset and size that corresponds to a component element
   1681 /// within it.  The offset checked here may have been formed from a GEP with a
   1682 /// pointer bitcasted to a different type.
   1683 ///
   1684 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
   1685 /// unit.  If false, it only allows accesses known to be in a single element.
   1686 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
   1687                            Type *MemOpType, bool isStore,
   1688                            AllocaInfo &Info, Instruction *TheAccess,
   1689                            bool AllowWholeAccess) {
   1690   // Check if this is a load/store of the entire alloca.
   1691   if (Offset == 0 && AllowWholeAccess &&
   1692       MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
   1693     // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
   1694     // loads/stores (which are essentially the same as the MemIntrinsics with
   1695     // regard to copying padding between elements).  But, if an alloca is
   1696     // flagged as both a source and destination of such operations, we'll need
   1697     // to check later for padding between elements.
   1698     if (!MemOpType || MemOpType->isIntegerTy()) {
   1699       if (isStore)
   1700         Info.isMemCpyDst = true;
   1701       else
   1702         Info.isMemCpySrc = true;
   1703       return;
   1704     }
   1705     // This is also safe for references using a type that is compatible with
   1706     // the type of the alloca, so that loads/stores can be rewritten using
   1707     // insertvalue/extractvalue.
   1708     if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
   1709       Info.hasSubelementAccess = true;
   1710       return;
   1711     }
   1712   }
   1713   // Check if the offset/size correspond to a component within the alloca type.
   1714   Type *T = Info.AI->getAllocatedType();
   1715   if (TypeHasComponent(T, Offset, MemSize)) {
   1716     Info.hasSubelementAccess = true;
   1717     return;
   1718   }
   1719 
   1720   return MarkUnsafe(Info, TheAccess);
   1721 }
   1722 
   1723 /// TypeHasComponent - Return true if T has a component type with the
   1724 /// specified offset and size.  If Size is zero, do not check the size.
   1725 bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
   1726   Type *EltTy;
   1727   uint64_t EltSize;
   1728   if (StructType *ST = dyn_cast<StructType>(T)) {
   1729     const StructLayout *Layout = TD->getStructLayout(ST);
   1730     unsigned EltIdx = Layout->getElementContainingOffset(Offset);
   1731     EltTy = ST->getContainedType(EltIdx);
   1732     EltSize = TD->getTypeAllocSize(EltTy);
   1733     Offset -= Layout->getElementOffset(EltIdx);
   1734   } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
   1735     EltTy = AT->getElementType();
   1736     EltSize = TD->getTypeAllocSize(EltTy);
   1737     if (Offset >= AT->getNumElements() * EltSize)
   1738       return false;
   1739     Offset %= EltSize;
   1740   } else {
   1741     return false;
   1742   }
   1743   if (Offset == 0 && (Size == 0 || EltSize == Size))
   1744     return true;
   1745   // Check if the component spans multiple elements.
   1746   if (Offset + Size > EltSize)
   1747     return false;
   1748   return TypeHasComponent(EltTy, Offset, Size);
   1749 }
   1750 
   1751 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
   1752 /// the instruction I, which references it, to use the separate elements.
   1753 /// Offset indicates the position within AI that is referenced by this
   1754 /// instruction.
   1755 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
   1756                                 SmallVector<AllocaInst*, 32> &NewElts) {
   1757   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
   1758     Use &TheUse = UI.getUse();
   1759     Instruction *User = cast<Instruction>(*UI++);
   1760 
   1761     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
   1762       RewriteBitCast(BC, AI, Offset, NewElts);
   1763       continue;
   1764     }
   1765 
   1766     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
   1767       RewriteGEP(GEPI, AI, Offset, NewElts);
   1768       continue;
   1769     }
   1770 
   1771     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
   1772       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
   1773       uint64_t MemSize = Length->getZExtValue();
   1774       if (Offset == 0 &&
   1775           MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
   1776         RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
   1777       // Otherwise the intrinsic can only touch a single element and the
   1778       // address operand will be updated, so nothing else needs to be done.
   1779       continue;
   1780     }
   1781 
   1782     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
   1783       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
   1784           II->getIntrinsicID() == Intrinsic::lifetime_end) {
   1785         RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
   1786       }
   1787       continue;
   1788     }
   1789 
   1790     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
   1791       Type *LIType = LI->getType();
   1792 
   1793       if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
   1794         // Replace:
   1795         //   %res = load { i32, i32 }* %alloc
   1796         // with:
   1797         //   %load.0 = load i32* %alloc.0
   1798         //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
   1799         //   %load.1 = load i32* %alloc.1
   1800         //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
   1801         // (Also works for arrays instead of structs)
   1802         Value *Insert = UndefValue::get(LIType);
   1803         IRBuilder<> Builder(LI);
   1804         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
   1805           Value *Load = Builder.CreateLoad(NewElts[i], "load");
   1806           Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
   1807         }
   1808         LI->replaceAllUsesWith(Insert);
   1809         DeadInsts.push_back(LI);
   1810       } else if (LIType->isIntegerTy() &&
   1811                  TD->getTypeAllocSize(LIType) ==
   1812                  TD->getTypeAllocSize(AI->getAllocatedType())) {
   1813         // If this is a load of the entire alloca to an integer, rewrite it.
   1814         RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
   1815       }
   1816       continue;
   1817     }
   1818 
   1819     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
   1820       Value *Val = SI->getOperand(0);
   1821       Type *SIType = Val->getType();
   1822       if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
   1823         // Replace:
   1824         //   store { i32, i32 } %val, { i32, i32 }* %alloc
   1825         // with:
   1826         //   %val.0 = extractvalue { i32, i32 } %val, 0
   1827         //   store i32 %val.0, i32* %alloc.0
   1828         //   %val.1 = extractvalue { i32, i32 } %val, 1
   1829         //   store i32 %val.1, i32* %alloc.1
   1830         // (Also works for arrays instead of structs)
   1831         IRBuilder<> Builder(SI);
   1832         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
   1833           Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
   1834           Builder.CreateStore(Extract, NewElts[i]);
   1835         }
   1836         DeadInsts.push_back(SI);
   1837       } else if (SIType->isIntegerTy() &&
   1838                  TD->getTypeAllocSize(SIType) ==
   1839                  TD->getTypeAllocSize(AI->getAllocatedType())) {
   1840         // If this is a store of the entire alloca from an integer, rewrite it.
   1841         RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
   1842       }
   1843       continue;
   1844     }
   1845 
   1846     if (isa<SelectInst>(User) || isa<PHINode>(User)) {
   1847       // If we have a PHI user of the alloca itself (as opposed to a GEP or
   1848       // bitcast) we have to rewrite it.  GEP and bitcast uses will be RAUW'd to
   1849       // the new pointer.
   1850       if (!isa<AllocaInst>(I)) continue;
   1851 
   1852       assert(Offset == 0 && NewElts[0] &&
   1853              "Direct alloca use should have a zero offset");
   1854 
   1855       // If we have a use of the alloca, we know the derived uses will be
   1856       // utilizing just the first element of the scalarized result.  Insert a
   1857       // bitcast of the first alloca before the user as required.
   1858       AllocaInst *NewAI = NewElts[0];
   1859       BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
   1860       NewAI->moveBefore(BCI);
   1861       TheUse = BCI;
   1862       continue;
   1863     }
   1864   }
   1865 }
   1866 
   1867 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
   1868 /// and recursively continue updating all of its uses.
   1869 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
   1870                           SmallVector<AllocaInst*, 32> &NewElts) {
   1871   RewriteForScalarRepl(BC, AI, Offset, NewElts);
   1872   if (BC->getOperand(0) != AI)
   1873     return;
   1874 
   1875   // The bitcast references the original alloca.  Replace its uses with
   1876   // references to the first new element alloca.
   1877   Instruction *Val = NewElts[0];
   1878   if (Val->getType() != BC->getDestTy()) {
   1879     Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
   1880     Val->takeName(BC);
   1881   }
   1882   BC->replaceAllUsesWith(Val);
   1883   DeadInsts.push_back(BC);
   1884 }
   1885 
   1886 /// FindElementAndOffset - Return the index of the element containing Offset
   1887 /// within the specified type, which must be either a struct or an array.
   1888 /// Sets T to the type of the element and Offset to the offset within that
   1889 /// element.  IdxTy is set to the type of the index result to be used in a
   1890 /// GEP instruction.
   1891 uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
   1892                                     Type *&IdxTy) {
   1893   uint64_t Idx = 0;
   1894   if (StructType *ST = dyn_cast<StructType>(T)) {
   1895     const StructLayout *Layout = TD->getStructLayout(ST);
   1896     Idx = Layout->getElementContainingOffset(Offset);
   1897     T = ST->getContainedType(Idx);
   1898     Offset -= Layout->getElementOffset(Idx);
   1899     IdxTy = Type::getInt32Ty(T->getContext());
   1900     return Idx;
   1901   }
   1902   ArrayType *AT = cast<ArrayType>(T);
   1903   T = AT->getElementType();
   1904   uint64_t EltSize = TD->getTypeAllocSize(T);
   1905   Idx = Offset / EltSize;
   1906   Offset -= Idx * EltSize;
   1907   IdxTy = Type::getInt64Ty(T->getContext());
   1908   return Idx;
   1909 }
   1910 
   1911 /// RewriteGEP - Check if this GEP instruction moves the pointer across
   1912 /// elements of the alloca that are being split apart, and if so, rewrite
   1913 /// the GEP to be relative to the new element.
   1914 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
   1915                       SmallVector<AllocaInst*, 32> &NewElts) {
   1916   uint64_t OldOffset = Offset;
   1917   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
   1918   Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
   1919 
   1920   RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
   1921 
   1922   Type *T = AI->getAllocatedType();
   1923   Type *IdxTy;
   1924   uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
   1925   if (GEPI->getOperand(0) == AI)
   1926     OldIdx = ~0ULL; // Force the GEP to be rewritten.
   1927 
   1928   T = AI->getAllocatedType();
   1929   uint64_t EltOffset = Offset;
   1930   uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
   1931 
   1932   // If this GEP does not move the pointer across elements of the alloca
   1933   // being split, then it does not needs to be rewritten.
   1934   if (Idx == OldIdx)
   1935     return;
   1936 
   1937   Type *i32Ty = Type::getInt32Ty(AI->getContext());
   1938   SmallVector<Value*, 8> NewArgs;
   1939   NewArgs.push_back(Constant::getNullValue(i32Ty));
   1940   while (EltOffset != 0) {
   1941     uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
   1942     NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
   1943   }
   1944   Instruction *Val = NewElts[Idx];
   1945   if (NewArgs.size() > 1) {
   1946     Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
   1947     Val->takeName(GEPI);
   1948   }
   1949   if (Val->getType() != GEPI->getType())
   1950     Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
   1951   GEPI->replaceAllUsesWith(Val);
   1952   DeadInsts.push_back(GEPI);
   1953 }
   1954 
   1955 /// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
   1956 /// to mark the lifetime of the scalarized memory.
   1957 void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
   1958                                     uint64_t Offset,
   1959                                     SmallVector<AllocaInst*, 32> &NewElts) {
   1960   ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
   1961   // Put matching lifetime markers on everything from Offset up to
   1962   // Offset+OldSize.
   1963   Type *AIType = AI->getAllocatedType();
   1964   uint64_t NewOffset = Offset;
   1965   Type *IdxTy;
   1966   uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
   1967 
   1968   IRBuilder<> Builder(II);
   1969   uint64_t Size = OldSize->getLimitedValue();
   1970 
   1971   if (NewOffset) {
   1972     // Splice the first element and index 'NewOffset' bytes in.  SROA will
   1973     // split the alloca again later.
   1974     Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy());
   1975     V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
   1976 
   1977     IdxTy = NewElts[Idx]->getAllocatedType();
   1978     uint64_t EltSize = TD->getTypeAllocSize(IdxTy) - NewOffset;
   1979     if (EltSize > Size) {
   1980       EltSize = Size;
   1981       Size = 0;
   1982     } else {
   1983       Size -= EltSize;
   1984     }
   1985     if (II->getIntrinsicID() == Intrinsic::lifetime_start)
   1986       Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
   1987     else
   1988       Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
   1989     ++Idx;
   1990   }
   1991 
   1992   for (; Idx != NewElts.size() && Size; ++Idx) {
   1993     IdxTy = NewElts[Idx]->getAllocatedType();
   1994     uint64_t EltSize = TD->getTypeAllocSize(IdxTy);
   1995     if (EltSize > Size) {
   1996       EltSize = Size;
   1997       Size = 0;
   1998     } else {
   1999       Size -= EltSize;
   2000     }
   2001     if (II->getIntrinsicID() == Intrinsic::lifetime_start)
   2002       Builder.CreateLifetimeStart(NewElts[Idx],
   2003                                   Builder.getInt64(EltSize));
   2004     else
   2005       Builder.CreateLifetimeEnd(NewElts[Idx],
   2006                                 Builder.getInt64(EltSize));
   2007   }
   2008   DeadInsts.push_back(II);
   2009 }
   2010 
   2011 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
   2012 /// Rewrite it to copy or set the elements of the scalarized memory.
   2013 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
   2014                                         AllocaInst *AI,
   2015                                         SmallVector<AllocaInst*, 32> &NewElts) {
   2016   // If this is a memcpy/memmove, construct the other pointer as the
   2017   // appropriate type.  The "Other" pointer is the pointer that goes to memory
   2018   // that doesn't have anything to do with the alloca that we are promoting. For
   2019   // memset, this Value* stays null.
   2020   Value *OtherPtr = 0;
   2021   unsigned MemAlignment = MI->getAlignment();
   2022   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
   2023     if (Inst == MTI->getRawDest())
   2024       OtherPtr = MTI->getRawSource();
   2025     else {
   2026       assert(Inst == MTI->getRawSource());
   2027       OtherPtr = MTI->getRawDest();
   2028     }
   2029   }
   2030 
   2031   // If there is an other pointer, we want to convert it to the same pointer
   2032   // type as AI has, so we can GEP through it safely.
   2033   if (OtherPtr) {
   2034     unsigned AddrSpace =
   2035       cast<PointerType>(OtherPtr->getType())->getAddressSpace();
   2036 
   2037     // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
   2038     // optimization, but it's also required to detect the corner case where
   2039     // both pointer operands are referencing the same memory, and where
   2040     // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
   2041     // function is only called for mem intrinsics that access the whole
   2042     // aggregate, so non-zero GEPs are not an issue here.)
   2043     OtherPtr = OtherPtr->stripPointerCasts();
   2044 
   2045     // Copying the alloca to itself is a no-op: just delete it.
   2046     if (OtherPtr == AI || OtherPtr == NewElts[0]) {
   2047       // This code will run twice for a no-op memcpy -- once for each operand.
   2048       // Put only one reference to MI on the DeadInsts list.
   2049       for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
   2050              E = DeadInsts.end(); I != E; ++I)
   2051         if (*I == MI) return;
   2052       DeadInsts.push_back(MI);
   2053       return;
   2054     }
   2055 
   2056     // If the pointer is not the right type, insert a bitcast to the right
   2057     // type.
   2058     Type *NewTy =
   2059       PointerType::get(AI->getType()->getElementType(), AddrSpace);
   2060 
   2061     if (OtherPtr->getType() != NewTy)
   2062       OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
   2063   }
   2064 
   2065   // Process each element of the aggregate.
   2066   bool SROADest = MI->getRawDest() == Inst;
   2067 
   2068   Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
   2069 
   2070   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
   2071     // If this is a memcpy/memmove, emit a GEP of the other element address.
   2072     Value *OtherElt = 0;
   2073     unsigned OtherEltAlign = MemAlignment;
   2074 
   2075     if (OtherPtr) {
   2076       Value *Idx[2] = { Zero,
   2077                       ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
   2078       OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
   2079                                               OtherPtr->getName()+"."+Twine(i),
   2080                                                    MI);
   2081       uint64_t EltOffset;
   2082       PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
   2083       Type *OtherTy = OtherPtrTy->getElementType();
   2084       if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
   2085         EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
   2086       } else {
   2087         Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
   2088         EltOffset = TD->getTypeAllocSize(EltTy)*i;
   2089       }
   2090 
   2091       // The alignment of the other pointer is the guaranteed alignment of the
   2092       // element, which is affected by both the known alignment of the whole
   2093       // mem intrinsic and the alignment of the element.  If the alignment of
   2094       // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
   2095       // known alignment is just 4 bytes.
   2096       OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
   2097     }
   2098 
   2099     Value *EltPtr = NewElts[i];
   2100     Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
   2101 
   2102     // If we got down to a scalar, insert a load or store as appropriate.
   2103     if (EltTy->isSingleValueType()) {
   2104       if (isa<MemTransferInst>(MI)) {
   2105         if (SROADest) {
   2106           // From Other to Alloca.
   2107           Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
   2108           new StoreInst(Elt, EltPtr, MI);
   2109         } else {
   2110           // From Alloca to Other.
   2111           Value *Elt = new LoadInst(EltPtr, "tmp", MI);
   2112           new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
   2113         }
   2114         continue;
   2115       }
   2116       assert(isa<MemSetInst>(MI));
   2117 
   2118       // If the stored element is zero (common case), just store a null
   2119       // constant.
   2120       Constant *StoreVal;
   2121       if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
   2122         if (CI->isZero()) {
   2123           StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
   2124         } else {
   2125           // If EltTy is a vector type, get the element type.
   2126           Type *ValTy = EltTy->getScalarType();
   2127 
   2128           // Construct an integer with the right value.
   2129           unsigned EltSize = TD->getTypeSizeInBits(ValTy);
   2130           APInt OneVal(EltSize, CI->getZExtValue());
   2131           APInt TotalVal(OneVal);
   2132           // Set each byte.
   2133           for (unsigned i = 0; 8*i < EltSize; ++i) {
   2134             TotalVal = TotalVal.shl(8);
   2135             TotalVal |= OneVal;
   2136           }
   2137 
   2138           // Convert the integer value to the appropriate type.
   2139           StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
   2140           if (ValTy->isPointerTy())
   2141             StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
   2142           else if (ValTy->isFloatingPointTy())
   2143             StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
   2144           assert(StoreVal->getType() == ValTy && "Type mismatch!");
   2145 
   2146           // If the requested value was a vector constant, create it.
   2147           if (EltTy->isVectorTy()) {
   2148             unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
   2149             SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
   2150             StoreVal = ConstantVector::get(Elts);
   2151           }
   2152         }
   2153         new StoreInst(StoreVal, EltPtr, MI);
   2154         continue;
   2155       }
   2156       // Otherwise, if we're storing a byte variable, use a memset call for
   2157       // this element.
   2158     }
   2159 
   2160     unsigned EltSize = TD->getTypeAllocSize(EltTy);
   2161 
   2162     IRBuilder<> Builder(MI);
   2163 
   2164     // Finally, insert the meminst for this element.
   2165     if (isa<MemSetInst>(MI)) {
   2166       Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
   2167                            MI->isVolatile());
   2168     } else {
   2169       assert(isa<MemTransferInst>(MI));
   2170       Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
   2171       Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
   2172 
   2173       if (isa<MemCpyInst>(MI))
   2174         Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
   2175       else
   2176         Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
   2177     }
   2178   }
   2179   DeadInsts.push_back(MI);
   2180 }
   2181 
   2182 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
   2183 /// overwrites the entire allocation.  Extract out the pieces of the stored
   2184 /// integer and store them individually.
   2185 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
   2186                                          SmallVector<AllocaInst*, 32> &NewElts){
   2187   // Extract each element out of the integer according to its structure offset
   2188   // and store the element value to the individual alloca.
   2189   Value *SrcVal = SI->getOperand(0);
   2190   Type *AllocaEltTy = AI->getAllocatedType();
   2191   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
   2192 
   2193   IRBuilder<> Builder(SI);
   2194 
   2195   // Handle tail padding by extending the operand
   2196   if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
   2197     SrcVal = Builder.CreateZExt(SrcVal,
   2198                             IntegerType::get(SI->getContext(), AllocaSizeBits));
   2199 
   2200   DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
   2201                << '\n');
   2202 
   2203   // There are two forms here: AI could be an array or struct.  Both cases
   2204   // have different ways to compute the element offset.
   2205   if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
   2206     const StructLayout *Layout = TD->getStructLayout(EltSTy);
   2207 
   2208     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
   2209       // Get the number of bits to shift SrcVal to get the value.
   2210       Type *FieldTy = EltSTy->getElementType(i);
   2211       uint64_t Shift = Layout->getElementOffsetInBits(i);
   2212 
   2213       if (TD->isBigEndian())
   2214         Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
   2215 
   2216       Value *EltVal = SrcVal;
   2217       if (Shift) {
   2218         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
   2219         EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
   2220       }
   2221 
   2222       // Truncate down to an integer of the right size.
   2223       uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
   2224 
   2225       // Ignore zero sized fields like {}, they obviously contain no data.
   2226       if (FieldSizeBits == 0) continue;
   2227 
   2228       if (FieldSizeBits != AllocaSizeBits)
   2229         EltVal = Builder.CreateTrunc(EltVal,
   2230                              IntegerType::get(SI->getContext(), FieldSizeBits));
   2231       Value *DestField = NewElts[i];
   2232       if (EltVal->getType() == FieldTy) {
   2233         // Storing to an integer field of this size, just do it.
   2234       } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
   2235         // Bitcast to the right element type (for fp/vector values).
   2236         EltVal = Builder.CreateBitCast(EltVal, FieldTy);
   2237       } else {
   2238         // Otherwise, bitcast the dest pointer (for aggregates).
   2239         DestField = Builder.CreateBitCast(DestField,
   2240                                      PointerType::getUnqual(EltVal->getType()));
   2241       }
   2242       new StoreInst(EltVal, DestField, SI);
   2243     }
   2244 
   2245   } else {
   2246     ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
   2247     Type *ArrayEltTy = ATy->getElementType();
   2248     uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
   2249     uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
   2250 
   2251     uint64_t Shift;
   2252 
   2253     if (TD->isBigEndian())
   2254       Shift = AllocaSizeBits-ElementOffset;
   2255     else
   2256       Shift = 0;
   2257 
   2258     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
   2259       // Ignore zero sized fields like {}, they obviously contain no data.
   2260       if (ElementSizeBits == 0) continue;
   2261 
   2262       Value *EltVal = SrcVal;
   2263       if (Shift) {
   2264         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
   2265         EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
   2266       }
   2267 
   2268       // Truncate down to an integer of the right size.
   2269       if (ElementSizeBits != AllocaSizeBits)
   2270         EltVal = Builder.CreateTrunc(EltVal,
   2271                                      IntegerType::get(SI->getContext(),
   2272                                                       ElementSizeBits));
   2273       Value *DestField = NewElts[i];
   2274       if (EltVal->getType() == ArrayEltTy) {
   2275         // Storing to an integer field of this size, just do it.
   2276       } else if (ArrayEltTy->isFloatingPointTy() ||
   2277                  ArrayEltTy->isVectorTy()) {
   2278         // Bitcast to the right element type (for fp/vector values).
   2279         EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
   2280       } else {
   2281         // Otherwise, bitcast the dest pointer (for aggregates).
   2282         DestField = Builder.CreateBitCast(DestField,
   2283                                      PointerType::getUnqual(EltVal->getType()));
   2284       }
   2285       new StoreInst(EltVal, DestField, SI);
   2286 
   2287       if (TD->isBigEndian())
   2288         Shift -= ElementOffset;
   2289       else
   2290         Shift += ElementOffset;
   2291     }
   2292   }
   2293 
   2294   DeadInsts.push_back(SI);
   2295 }
   2296 
   2297 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
   2298 /// an integer.  Load the individual pieces to form the aggregate value.
   2299 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
   2300                                         SmallVector<AllocaInst*, 32> &NewElts) {
   2301   // Extract each element out of the NewElts according to its structure offset
   2302   // and form the result value.
   2303   Type *AllocaEltTy = AI->getAllocatedType();
   2304   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
   2305 
   2306   DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
   2307                << '\n');
   2308 
   2309   // There are two forms here: AI could be an array or struct.  Both cases
   2310   // have different ways to compute the element offset.
   2311   const StructLayout *Layout = 0;
   2312   uint64_t ArrayEltBitOffset = 0;
   2313   if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
   2314     Layout = TD->getStructLayout(EltSTy);
   2315   } else {
   2316     Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
   2317     ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
   2318   }
   2319 
   2320   Value *ResultVal =
   2321     Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
   2322 
   2323   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
   2324     // Load the value from the alloca.  If the NewElt is an aggregate, cast
   2325     // the pointer to an integer of the same size before doing the load.
   2326     Value *SrcField = NewElts[i];
   2327     Type *FieldTy =
   2328       cast<PointerType>(SrcField->getType())->getElementType();
   2329     uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
   2330 
   2331     // Ignore zero sized fields like {}, they obviously contain no data.
   2332     if (FieldSizeBits == 0) continue;
   2333 
   2334     IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
   2335                                                      FieldSizeBits);
   2336     if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
   2337         !FieldTy->isVectorTy())
   2338       SrcField = new BitCastInst(SrcField,
   2339                                  PointerType::getUnqual(FieldIntTy),
   2340                                  "", LI);
   2341     SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
   2342 
   2343     // If SrcField is a fp or vector of the right size but that isn't an
   2344     // integer type, bitcast to an integer so we can shift it.
   2345     if (SrcField->getType() != FieldIntTy)
   2346       SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
   2347 
   2348     // Zero extend the field to be the same size as the final alloca so that
   2349     // we can shift and insert it.
   2350     if (SrcField->getType() != ResultVal->getType())
   2351       SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
   2352 
   2353     // Determine the number of bits to shift SrcField.
   2354     uint64_t Shift;
   2355     if (Layout) // Struct case.
   2356       Shift = Layout->getElementOffsetInBits(i);
   2357     else  // Array case.
   2358       Shift = i*ArrayEltBitOffset;
   2359 
   2360     if (TD->isBigEndian())
   2361       Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
   2362 
   2363     if (Shift) {
   2364       Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
   2365       SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
   2366     }
   2367 
   2368     // Don't create an 'or x, 0' on the first iteration.
   2369     if (!isa<Constant>(ResultVal) ||
   2370         !cast<Constant>(ResultVal)->isNullValue())
   2371       ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
   2372     else
   2373       ResultVal = SrcField;
   2374   }
   2375 
   2376   // Handle tail padding by truncating the result
   2377   if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
   2378     ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
   2379 
   2380   LI->replaceAllUsesWith(ResultVal);
   2381   DeadInsts.push_back(LI);
   2382 }
   2383 
   2384 /// HasPadding - Return true if the specified type has any structure or
   2385 /// alignment padding in between the elements that would be split apart
   2386 /// by SROA; return false otherwise.
   2387 static bool HasPadding(Type *Ty, const TargetData &TD) {
   2388   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
   2389     Ty = ATy->getElementType();
   2390     return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
   2391   }
   2392 
   2393   // SROA currently handles only Arrays and Structs.
   2394   StructType *STy = cast<StructType>(Ty);
   2395   const StructLayout *SL = TD.getStructLayout(STy);
   2396   unsigned PrevFieldBitOffset = 0;
   2397   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
   2398     unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
   2399 
   2400     // Check to see if there is any padding between this element and the
   2401     // previous one.
   2402     if (i) {
   2403       unsigned PrevFieldEnd =
   2404         PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
   2405       if (PrevFieldEnd < FieldBitOffset)
   2406         return true;
   2407     }
   2408     PrevFieldBitOffset = FieldBitOffset;
   2409   }
   2410   // Check for tail padding.
   2411   if (unsigned EltCount = STy->getNumElements()) {
   2412     unsigned PrevFieldEnd = PrevFieldBitOffset +
   2413       TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
   2414     if (PrevFieldEnd < SL->getSizeInBits())
   2415       return true;
   2416   }
   2417   return false;
   2418 }
   2419 
   2420 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
   2421 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
   2422 /// or 1 if safe after canonicalization has been performed.
   2423 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
   2424   // Loop over the use list of the alloca.  We can only transform it if all of
   2425   // the users are safe to transform.
   2426   AllocaInfo Info(AI);
   2427 
   2428   isSafeForScalarRepl(AI, 0, Info);
   2429   if (Info.isUnsafe) {
   2430     DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
   2431     return false;
   2432   }
   2433 
   2434   // Okay, we know all the users are promotable.  If the aggregate is a memcpy
   2435   // source and destination, we have to be careful.  In particular, the memcpy
   2436   // could be moving around elements that live in structure padding of the LLVM
   2437   // types, but may actually be used.  In these cases, we refuse to promote the
   2438   // struct.
   2439   if (Info.isMemCpySrc && Info.isMemCpyDst &&
   2440       HasPadding(AI->getAllocatedType(), *TD))
   2441     return false;
   2442 
   2443   // If the alloca never has an access to just *part* of it, but is accessed
   2444   // via loads and stores, then we should use ConvertToScalarInfo to promote
   2445   // the alloca instead of promoting each piece at a time and inserting fission
   2446   // and fusion code.
   2447   if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
   2448     // If the struct/array just has one element, use basic SRoA.
   2449     if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
   2450       if (ST->getNumElements() > 1) return false;
   2451     } else {
   2452       if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
   2453         return false;
   2454     }
   2455   }
   2456 
   2457   return true;
   2458 }
   2459 
   2460 
   2461 
   2462 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
   2463 /// some part of a constant global variable.  This intentionally only accepts
   2464 /// constant expressions because we don't can't rewrite arbitrary instructions.
   2465 static bool PointsToConstantGlobal(Value *V) {
   2466   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
   2467     return GV->isConstant();
   2468   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
   2469     if (CE->getOpcode() == Instruction::BitCast ||
   2470         CE->getOpcode() == Instruction::GetElementPtr)
   2471       return PointsToConstantGlobal(CE->getOperand(0));
   2472   return false;
   2473 }
   2474 
   2475 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
   2476 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
   2477 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
   2478 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
   2479 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
   2480 /// the alloca, and if the source pointer is a pointer to a constant global, we
   2481 /// can optimize this.
   2482 static bool
   2483 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
   2484                                bool isOffset,
   2485                                SmallVector<Instruction *, 4> &LifetimeMarkers) {
   2486   // We track lifetime intrinsics as we encounter them.  If we decide to go
   2487   // ahead and replace the value with the global, this lets the caller quickly
   2488   // eliminate the markers.
   2489 
   2490   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
   2491     User *U = cast<Instruction>(*UI);
   2492 
   2493     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
   2494       // Ignore non-volatile loads, they are always ok.
   2495       if (!LI->isSimple()) return false;
   2496       continue;
   2497     }
   2498 
   2499     if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
   2500       // If uses of the bitcast are ok, we are ok.
   2501       if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset,
   2502                                           LifetimeMarkers))
   2503         return false;
   2504       continue;
   2505     }
   2506     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
   2507       // If the GEP has all zero indices, it doesn't offset the pointer.  If it
   2508       // doesn't, it does.
   2509       if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
   2510                                           isOffset || !GEP->hasAllZeroIndices(),
   2511                                           LifetimeMarkers))
   2512         return false;
   2513       continue;
   2514     }
   2515 
   2516     if (CallSite CS = U) {
   2517       // If this is the function being called then we treat it like a load and
   2518       // ignore it.
   2519       if (CS.isCallee(UI))
   2520         continue;
   2521 
   2522       // If this is a readonly/readnone call site, then we know it is just a
   2523       // load (but one that potentially returns the value itself), so we can
   2524       // ignore it if we know that the value isn't captured.
   2525       unsigned ArgNo = CS.getArgumentNo(UI);
   2526       if (CS.onlyReadsMemory() &&
   2527           (CS.getInstruction()->use_empty() ||
   2528            CS.paramHasAttr(ArgNo+1, Attribute::NoCapture)))
   2529         continue;
   2530 
   2531       // If this is being passed as a byval argument, the caller is making a
   2532       // copy, so it is only a read of the alloca.
   2533       if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
   2534         continue;
   2535     }
   2536 
   2537     // Lifetime intrinsics can be handled by the caller.
   2538     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
   2539       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
   2540           II->getIntrinsicID() == Intrinsic::lifetime_end) {
   2541         assert(II->use_empty() && "Lifetime markers have no result to use!");
   2542         LifetimeMarkers.push_back(II);
   2543         continue;
   2544       }
   2545     }
   2546 
   2547     // If this is isn't our memcpy/memmove, reject it as something we can't
   2548     // handle.
   2549     MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
   2550     if (MI == 0)
   2551       return false;
   2552 
   2553     // If the transfer is using the alloca as a source of the transfer, then
   2554     // ignore it since it is a load (unless the transfer is volatile).
   2555     if (UI.getOperandNo() == 1) {
   2556       if (MI->isVolatile()) return false;
   2557       continue;
   2558     }
   2559 
   2560     // If we already have seen a copy, reject the second one.
   2561     if (TheCopy) return false;
   2562 
   2563     // If the pointer has been offset from the start of the alloca, we can't
   2564     // safely handle this.
   2565     if (isOffset) return false;
   2566 
   2567     // If the memintrinsic isn't using the alloca as the dest, reject it.
   2568     if (UI.getOperandNo() != 0) return false;
   2569 
   2570     // If the source of the memcpy/move is not a constant global, reject it.
   2571     if (!PointsToConstantGlobal(MI->getSource()))
   2572       return false;
   2573 
   2574     // Otherwise, the transform is safe.  Remember the copy instruction.
   2575     TheCopy = MI;
   2576   }
   2577   return true;
   2578 }
   2579 
   2580 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
   2581 /// modified by a copy from a constant global.  If we can prove this, we can
   2582 /// replace any uses of the alloca with uses of the global directly.
   2583 MemTransferInst *
   2584 SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
   2585                                      SmallVector<Instruction*, 4> &ToDelete) {
   2586   MemTransferInst *TheCopy = 0;
   2587   if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false, ToDelete))
   2588     return TheCopy;
   2589   return 0;
   2590 }
   2591