LLVM API Documentation

ScalarReplAggregates.cpp
Go to the documentation of this file.
00001 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This transformation implements the well known scalar replacement of
00011 // aggregates transformation.  This xform breaks up alloca instructions of
00012 // aggregate type (structure or array) into individual alloca instructions for
00013 // each member (if possible).  Then, if possible, it transforms the individual
00014 // alloca instructions into nice clean scalar SSA form.
00015 //
00016 // This combines a simple SRoA algorithm with the Mem2Reg algorithm because they
00017 // often interact, especially for C++ programs.  As such, iterating between
00018 // SRoA, then Mem2Reg until we run out of things to promote works well.
00019 //
00020 //===----------------------------------------------------------------------===//
00021 
00022 #include "llvm/Transforms/Scalar.h"
00023 #include "llvm/ADT/SetVector.h"
00024 #include "llvm/ADT/SmallVector.h"
00025 #include "llvm/ADT/Statistic.h"
00026 #include "llvm/Analysis/Loads.h"
00027 #include "llvm/Analysis/ValueTracking.h"
00028 #include "llvm/IR/CallSite.h"
00029 #include "llvm/IR/Constants.h"
00030 #include "llvm/IR/DIBuilder.h"
00031 #include "llvm/IR/DataLayout.h"
00032 #include "llvm/IR/DebugInfo.h"
00033 #include "llvm/IR/DerivedTypes.h"
00034 #include "llvm/IR/Dominators.h"
00035 #include "llvm/IR/Function.h"
00036 #include "llvm/IR/GetElementPtrTypeIterator.h"
00037 #include "llvm/IR/GlobalVariable.h"
00038 #include "llvm/IR/IRBuilder.h"
00039 #include "llvm/IR/Instructions.h"
00040 #include "llvm/IR/IntrinsicInst.h"
00041 #include "llvm/IR/LLVMContext.h"
00042 #include "llvm/IR/Module.h"
00043 #include "llvm/IR/Operator.h"
00044 #include "llvm/Pass.h"
00045 #include "llvm/Support/Debug.h"
00046 #include "llvm/Support/ErrorHandling.h"
00047 #include "llvm/Support/MathExtras.h"
00048 #include "llvm/Support/raw_ostream.h"
00049 #include "llvm/Transforms/Utils/Local.h"
00050 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
00051 #include "llvm/Transforms/Utils/SSAUpdater.h"
00052 using namespace llvm;
00053 
00054 #define DEBUG_TYPE "scalarrepl"
00055 
00056 STATISTIC(NumReplaced,  "Number of allocas broken up");
00057 STATISTIC(NumPromoted,  "Number of allocas promoted");
00058 STATISTIC(NumAdjusted,  "Number of scalar allocas adjusted to allow promotion");
00059 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
00060 
00061 namespace {
00062   struct SROA : public FunctionPass {
00063     SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
00064       : FunctionPass(ID), HasDomTree(hasDT) {
00065       if (T == -1)
00066         SRThreshold = 128;
00067       else
00068         SRThreshold = T;
00069       if (ST == -1)
00070         StructMemberThreshold = 32;
00071       else
00072         StructMemberThreshold = ST;
00073       if (AT == -1)
00074         ArrayElementThreshold = 8;
00075       else
00076         ArrayElementThreshold = AT;
00077       if (SLT == -1)
00078         // Do not limit the scalar integer load size if no threshold is given.
00079         ScalarLoadThreshold = -1;
00080       else
00081         ScalarLoadThreshold = SLT;
00082     }
00083 
00084     bool runOnFunction(Function &F) override;
00085 
00086     bool performScalarRepl(Function &F);
00087     bool performPromotion(Function &F);
00088 
00089   private:
00090     bool HasDomTree;
00091     const DataLayout *DL;
00092 
00093     /// DeadInsts - Keep track of instructions we have made dead, so that
00094     /// we can remove them after we are done working.
00095     SmallVector<Value*, 32> DeadInsts;
00096 
00097     /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
00098     /// information about the uses.  All these fields are initialized to false
00099     /// and set to true when something is learned.
00100     struct AllocaInfo {
00101       /// The alloca to promote.
00102       AllocaInst *AI;
00103 
00104       /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
00105       /// looping and avoid redundant work.
00106       SmallPtrSet<PHINode*, 8> CheckedPHIs;
00107 
00108       /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
00109       bool isUnsafe : 1;
00110 
00111       /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
00112       bool isMemCpySrc : 1;
00113 
00114       /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
00115       bool isMemCpyDst : 1;
00116 
00117       /// hasSubelementAccess - This is true if a subelement of the alloca is
00118       /// ever accessed, or false if the alloca is only accessed with mem
00119       /// intrinsics or load/store that only access the entire alloca at once.
00120       bool hasSubelementAccess : 1;
00121 
00122       /// hasALoadOrStore - This is true if there are any loads or stores to it.
00123       /// The alloca may just be accessed with memcpy, for example, which would
00124       /// not set this.
00125       bool hasALoadOrStore : 1;
00126 
00127       explicit AllocaInfo(AllocaInst *ai)
00128         : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
00129           hasSubelementAccess(false), hasALoadOrStore(false) {}
00130     };
00131 
00132     /// SRThreshold - The maximum alloca size to considered for SROA.
00133     unsigned SRThreshold;
00134 
00135     /// StructMemberThreshold - The maximum number of members a struct can
00136     /// contain to be considered for SROA.
00137     unsigned StructMemberThreshold;
00138 
00139     /// ArrayElementThreshold - The maximum number of elements an array can
00140     /// have to be considered for SROA.
00141     unsigned ArrayElementThreshold;
00142 
00143     /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
00144     /// converting to scalar
00145     unsigned ScalarLoadThreshold;
00146 
00147     void MarkUnsafe(AllocaInfo &I, Instruction *User) {
00148       I.isUnsafe = true;
00149       DEBUG(dbgs() << "  Transformation preventing inst: " << *User << '\n');
00150     }
00151 
00152     bool isSafeAllocaToScalarRepl(AllocaInst *AI);
00153 
00154     void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
00155     void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
00156                                          AllocaInfo &Info);
00157     void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
00158     void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
00159                          Type *MemOpType, bool isStore, AllocaInfo &Info,
00160                          Instruction *TheAccess, bool AllowWholeAccess);
00161     bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
00162     uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
00163                                   Type *&IdxTy);
00164 
00165     void DoScalarReplacement(AllocaInst *AI,
00166                              std::vector<AllocaInst*> &WorkList);
00167     void DeleteDeadInstructions();
00168 
00169     void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
00170                               SmallVectorImpl<AllocaInst *> &NewElts);
00171     void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
00172                         SmallVectorImpl<AllocaInst *> &NewElts);
00173     void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
00174                     SmallVectorImpl<AllocaInst *> &NewElts);
00175     void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
00176                                   uint64_t Offset,
00177                                   SmallVectorImpl<AllocaInst *> &NewElts);
00178     void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
00179                                       AllocaInst *AI,
00180                                       SmallVectorImpl<AllocaInst *> &NewElts);
00181     void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
00182                                        SmallVectorImpl<AllocaInst *> &NewElts);
00183     void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
00184                                       SmallVectorImpl<AllocaInst *> &NewElts);
00185     bool ShouldAttemptScalarRepl(AllocaInst *AI);
00186   };
00187 
00188   // SROA_DT - SROA that uses DominatorTree.
00189   struct SROA_DT : public SROA {
00190     static char ID;
00191   public:
00192     SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
00193         SROA(T, true, ID, ST, AT, SLT) {
00194       initializeSROA_DTPass(*PassRegistry::getPassRegistry());
00195     }
00196 
00197     // getAnalysisUsage - This pass does not require any passes, but we know it
00198     // will not alter the CFG, so say so.
00199     void getAnalysisUsage(AnalysisUsage &AU) const override {
00200       AU.addRequired<DominatorTreeWrapperPass>();
00201       AU.setPreservesCFG();
00202     }
00203   };
00204 
00205   // SROA_SSAUp - SROA that uses SSAUpdater.
00206   struct SROA_SSAUp : public SROA {
00207     static char ID;
00208   public:
00209     SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
00210         SROA(T, false, ID, ST, AT, SLT) {
00211       initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
00212     }
00213 
00214     // getAnalysisUsage - This pass does not require any passes, but we know it
00215     // will not alter the CFG, so say so.
00216     void getAnalysisUsage(AnalysisUsage &AU) const override {
00217       AU.setPreservesCFG();
00218     }
00219   };
00220 
00221 }
00222 
00223 char SROA_DT::ID = 0;
00224 char SROA_SSAUp::ID = 0;
00225 
00226 INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
00227                 "Scalar Replacement of Aggregates (DT)", false, false)
00228 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00229 INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
00230                 "Scalar Replacement of Aggregates (DT)", false, false)
00231 
00232 INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
00233                       "Scalar Replacement of Aggregates (SSAUp)", false, false)
00234 INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
00235                     "Scalar Replacement of Aggregates (SSAUp)", false, false)
00236 
00237 // Public interface to the ScalarReplAggregates pass
00238 FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
00239                                                    bool UseDomTree,
00240                                                    int StructMemberThreshold,
00241                                                    int ArrayElementThreshold,
00242                                                    int ScalarLoadThreshold) {
00243   if (UseDomTree)
00244     return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
00245                        ScalarLoadThreshold);
00246   return new SROA_SSAUp(Threshold, StructMemberThreshold,
00247                         ArrayElementThreshold, ScalarLoadThreshold);
00248 }
00249 
00250 
00251 //===----------------------------------------------------------------------===//
00252 // Convert To Scalar Optimization.
00253 //===----------------------------------------------------------------------===//
00254 
00255 namespace {
00256 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
00257 /// optimization, which scans the uses of an alloca and determines if it can
00258 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
00259 class ConvertToScalarInfo {
00260   /// AllocaSize - The size of the alloca being considered in bytes.
00261   unsigned AllocaSize;
00262   const DataLayout &DL;
00263   unsigned ScalarLoadThreshold;
00264 
00265   /// IsNotTrivial - This is set to true if there is some access to the object
00266   /// which means that mem2reg can't promote it.
00267   bool IsNotTrivial;
00268 
00269   /// ScalarKind - Tracks the kind of alloca being considered for promotion,
00270   /// computed based on the uses of the alloca rather than the LLVM type system.
00271   enum {
00272     Unknown,
00273 
00274     // Accesses via GEPs that are consistent with element access of a vector
00275     // type. This will not be converted into a vector unless there is a later
00276     // access using an actual vector type.
00277     ImplicitVector,
00278 
00279     // Accesses via vector operations and GEPs that are consistent with the
00280     // layout of a vector type.
00281     Vector,
00282 
00283     // An integer bag-of-bits with bitwise operations for insertion and
00284     // extraction. Any combination of types can be converted into this kind
00285     // of scalar.
00286     Integer
00287   } ScalarKind;
00288 
00289   /// VectorTy - This tracks the type that we should promote the vector to if
00290   /// it is possible to turn it into a vector.  This starts out null, and if it
00291   /// isn't possible to turn into a vector type, it gets set to VoidTy.
00292   VectorType *VectorTy;
00293 
00294   /// HadNonMemTransferAccess - True if there is at least one access to the
00295   /// alloca that is not a MemTransferInst.  We don't want to turn structs into
00296   /// large integers unless there is some potential for optimization.
00297   bool HadNonMemTransferAccess;
00298 
00299   /// HadDynamicAccess - True if some element of this alloca was dynamic.
00300   /// We don't yet have support for turning a dynamic access into a large
00301   /// integer.
00302   bool HadDynamicAccess;
00303 
00304 public:
00305   explicit ConvertToScalarInfo(unsigned Size, const DataLayout &DL,
00306                                unsigned SLT)
00307     : AllocaSize(Size), DL(DL), ScalarLoadThreshold(SLT), IsNotTrivial(false),
00308     ScalarKind(Unknown), VectorTy(nullptr), HadNonMemTransferAccess(false),
00309     HadDynamicAccess(false) { }
00310 
00311   AllocaInst *TryConvert(AllocaInst *AI);
00312 
00313 private:
00314   bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
00315   void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
00316   bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
00317   void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
00318                            Value *NonConstantIdx);
00319 
00320   Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
00321                                     uint64_t Offset, Value* NonConstantIdx,
00322                                     IRBuilder<> &Builder);
00323   Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
00324                                    uint64_t Offset, Value* NonConstantIdx,
00325                                    IRBuilder<> &Builder);
00326 };
00327 } // end anonymous namespace.
00328 
00329 
00330 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
00331 /// rewrite it to be a new alloca which is mem2reg'able.  This returns the new
00332 /// alloca if possible or null if not.
00333 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
00334   // If we can't convert this scalar, or if mem2reg can trivially do it, bail
00335   // out.
00336   if (!CanConvertToScalar(AI, 0, nullptr) || !IsNotTrivial)
00337     return nullptr;
00338 
00339   // If an alloca has only memset / memcpy uses, it may still have an Unknown
00340   // ScalarKind. Treat it as an Integer below.
00341   if (ScalarKind == Unknown)
00342     ScalarKind = Integer;
00343 
00344   if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
00345     ScalarKind = Integer;
00346 
00347   // If we were able to find a vector type that can handle this with
00348   // insert/extract elements, and if there was at least one use that had
00349   // a vector type, promote this to a vector.  We don't want to promote
00350   // random stuff that doesn't use vectors (e.g. <9 x double>) because then
00351   // we just get a lot of insert/extracts.  If at least one vector is
00352   // involved, then we probably really do have a union of vector/array.
00353   Type *NewTy;
00354   if (ScalarKind == Vector) {
00355     assert(VectorTy && "Missing type for vector scalar.");
00356     DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n  TYPE = "
00357           << *VectorTy << '\n');
00358     NewTy = VectorTy;  // Use the vector type.
00359   } else {
00360     unsigned BitWidth = AllocaSize * 8;
00361 
00362     // Do not convert to scalar integer if the alloca size exceeds the
00363     // scalar load threshold.
00364     if (BitWidth > ScalarLoadThreshold)
00365       return nullptr;
00366 
00367     if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
00368         !HadNonMemTransferAccess && !DL.fitsInLegalInteger(BitWidth))
00369       return nullptr;
00370     // Dynamic accesses on integers aren't yet supported.  They need us to shift
00371     // by a dynamic amount which could be difficult to work out as we might not
00372     // know whether to use a left or right shift.
00373     if (ScalarKind == Integer && HadDynamicAccess)
00374       return nullptr;
00375 
00376     DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
00377     // Create and insert the integer alloca.
00378     NewTy = IntegerType::get(AI->getContext(), BitWidth);
00379   }
00380   AllocaInst *NewAI = new AllocaInst(NewTy, nullptr, "",
00381                                      AI->getParent()->begin());
00382   ConvertUsesToScalar(AI, NewAI, 0, nullptr);
00383   return NewAI;
00384 }
00385 
00386 /// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
00387 /// (VectorTy) so far at the offset specified by Offset (which is specified in
00388 /// bytes).
00389 ///
00390 /// There are two cases we handle here:
00391 ///   1) A union of vector types of the same size and potentially its elements.
00392 ///      Here we turn element accesses into insert/extract element operations.
00393 ///      This promotes a <4 x float> with a store of float to the third element
00394 ///      into a <4 x float> that uses insert element.
00395 ///   2) A fully general blob of memory, which we turn into some (potentially
00396 ///      large) integer type with extract and insert operations where the loads
00397 ///      and stores would mutate the memory.  We mark this by setting VectorTy
00398 ///      to VoidTy.
00399 void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
00400                                                     uint64_t Offset) {
00401   // If we already decided to turn this into a blob of integer memory, there is
00402   // nothing to be done.
00403   if (ScalarKind == Integer)
00404     return;
00405 
00406   // If this could be contributing to a vector, analyze it.
00407 
00408   // If the In type is a vector that is the same size as the alloca, see if it
00409   // matches the existing VecTy.
00410   if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
00411     if (MergeInVectorType(VInTy, Offset))
00412       return;
00413   } else if (In->isFloatTy() || In->isDoubleTy() ||
00414              (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
00415               isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
00416     // Full width accesses can be ignored, because they can always be turned
00417     // into bitcasts.
00418     unsigned EltSize = In->getPrimitiveSizeInBits()/8;
00419     if (EltSize == AllocaSize)
00420       return;
00421 
00422     // If we're accessing something that could be an element of a vector, see
00423     // if the implied vector agrees with what we already have and if Offset is
00424     // compatible with it.
00425     if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
00426         (!VectorTy || EltSize == VectorTy->getElementType()
00427                                          ->getPrimitiveSizeInBits()/8)) {
00428       if (!VectorTy) {
00429         ScalarKind = ImplicitVector;
00430         VectorTy = VectorType::get(In, AllocaSize/EltSize);
00431       }
00432       return;
00433     }
00434   }
00435 
00436   // Otherwise, we have a case that we can't handle with an optimized vector
00437   // form.  We can still turn this into a large integer.
00438   ScalarKind = Integer;
00439 }
00440 
00441 /// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
00442 /// returning true if the type was successfully merged and false otherwise.
00443 bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
00444                                             uint64_t Offset) {
00445   if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
00446     // If we're storing/loading a vector of the right size, allow it as a
00447     // vector.  If this the first vector we see, remember the type so that
00448     // we know the element size. If this is a subsequent access, ignore it
00449     // even if it is a differing type but the same size. Worst case we can
00450     // bitcast the resultant vectors.
00451     if (!VectorTy)
00452       VectorTy = VInTy;
00453     ScalarKind = Vector;
00454     return true;
00455   }
00456 
00457   return false;
00458 }
00459 
00460 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
00461 /// its accesses to a single vector type, return true and set VecTy to
00462 /// the new type.  If we could convert the alloca into a single promotable
00463 /// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
00464 /// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
00465 /// is the current offset from the base of the alloca being analyzed.
00466 ///
00467 /// If we see at least one access to the value that is as a vector type, set the
00468 /// SawVec flag.
00469 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
00470                                              Value* NonConstantIdx) {
00471   for (User *U : V->users()) {
00472     Instruction *UI = cast<Instruction>(U);
00473 
00474     if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
00475       // Don't break volatile loads.
00476       if (!LI->isSimple())
00477         return false;
00478       // Don't touch MMX operations.
00479       if (LI->getType()->isX86_MMXTy())
00480         return false;
00481       HadNonMemTransferAccess = true;
00482       MergeInTypeForLoadOrStore(LI->getType(), Offset);
00483       continue;
00484     }
00485 
00486     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
00487       // Storing the pointer, not into the value?
00488       if (SI->getOperand(0) == V || !SI->isSimple()) return false;
00489       // Don't touch MMX operations.
00490       if (SI->getOperand(0)->getType()->isX86_MMXTy())
00491         return false;
00492       HadNonMemTransferAccess = true;
00493       MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
00494       continue;
00495     }
00496 
00497     if (BitCastInst *BCI = dyn_cast<BitCastInst>(UI)) {
00498       if (!onlyUsedByLifetimeMarkers(BCI))
00499         IsNotTrivial = true;  // Can't be mem2reg'd.
00500       if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
00501         return false;
00502       continue;
00503     }
00504 
00505     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UI)) {
00506       // If this is a GEP with a variable indices, we can't handle it.
00507       PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
00508       if (!PtrTy)
00509         return false;
00510 
00511       // Compute the offset that this GEP adds to the pointer.
00512       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
00513       Value *GEPNonConstantIdx = nullptr;
00514       if (!GEP->hasAllConstantIndices()) {
00515         if (!isa<VectorType>(PtrTy->getElementType()))
00516           return false;
00517         if (NonConstantIdx)
00518           return false;
00519         GEPNonConstantIdx = Indices.pop_back_val();
00520         if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
00521           return false;
00522         HadDynamicAccess = true;
00523       } else
00524         GEPNonConstantIdx = NonConstantIdx;
00525       uint64_t GEPOffset = DL.getIndexedOffset(PtrTy,
00526                                                Indices);
00527       // See if all uses can be converted.
00528       if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
00529         return false;
00530       IsNotTrivial = true;  // Can't be mem2reg'd.
00531       HadNonMemTransferAccess = true;
00532       continue;
00533     }
00534 
00535     // If this is a constant sized memset of a constant value (e.g. 0) we can
00536     // handle it.
00537     if (MemSetInst *MSI = dyn_cast<MemSetInst>(UI)) {
00538       // Store to dynamic index.
00539       if (NonConstantIdx)
00540         return false;
00541       // Store of constant value.
00542       if (!isa<ConstantInt>(MSI->getValue()))
00543         return false;
00544 
00545       // Store of constant size.
00546       ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
00547       if (!Len)
00548         return false;
00549 
00550       // If the size differs from the alloca, we can only convert the alloca to
00551       // an integer bag-of-bits.
00552       // FIXME: This should handle all of the cases that are currently accepted
00553       // as vector element insertions.
00554       if (Len->getZExtValue() != AllocaSize || Offset != 0)
00555         ScalarKind = Integer;
00556 
00557       IsNotTrivial = true;  // Can't be mem2reg'd.
00558       HadNonMemTransferAccess = true;
00559       continue;
00560     }
00561 
00562     // If this is a memcpy or memmove into or out of the whole allocation, we
00563     // can handle it like a load or store of the scalar type.
00564     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(UI)) {
00565       // Store to dynamic index.
00566       if (NonConstantIdx)
00567         return false;
00568       ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
00569       if (!Len || Len->getZExtValue() != AllocaSize || Offset != 0)
00570         return false;
00571 
00572       IsNotTrivial = true;  // Can't be mem2reg'd.
00573       continue;
00574     }
00575 
00576     // If this is a lifetime intrinsic, we can handle it.
00577     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(UI)) {
00578       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
00579           II->getIntrinsicID() == Intrinsic::lifetime_end) {
00580         continue;
00581       }
00582     }
00583 
00584     // Otherwise, we cannot handle this!
00585     return false;
00586   }
00587 
00588   return true;
00589 }
00590 
00591 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
00592 /// directly.  This happens when we are converting an "integer union" to a
00593 /// single integer scalar, or when we are converting a "vector union" to a
00594 /// vector with insert/extractelement instructions.
00595 ///
00596 /// Offset is an offset from the original alloca, in bits that need to be
00597 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
00598 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
00599                                               uint64_t Offset,
00600                                               Value* NonConstantIdx) {
00601   while (!Ptr->use_empty()) {
00602     Instruction *User = cast<Instruction>(Ptr->user_back());
00603 
00604     if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
00605       ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
00606       CI->eraseFromParent();
00607       continue;
00608     }
00609 
00610     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
00611       // Compute the offset that this GEP adds to the pointer.
00612       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
00613       Value* GEPNonConstantIdx = nullptr;
00614       if (!GEP->hasAllConstantIndices()) {
00615         assert(!NonConstantIdx &&
00616                "Dynamic GEP reading from dynamic GEP unsupported");
00617         GEPNonConstantIdx = Indices.pop_back_val();
00618       } else
00619         GEPNonConstantIdx = NonConstantIdx;
00620       uint64_t GEPOffset = DL.getIndexedOffset(GEP->getPointerOperandType(),
00621                                                Indices);
00622       ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
00623       GEP->eraseFromParent();
00624       continue;
00625     }
00626 
00627     IRBuilder<> Builder(User);
00628 
00629     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
00630       // The load is a bit extract from NewAI shifted right by Offset bits.
00631       Value *LoadedVal = Builder.CreateLoad(NewAI);
00632       Value *NewLoadVal
00633         = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
00634                                      NonConstantIdx, Builder);
00635       LI->replaceAllUsesWith(NewLoadVal);
00636       LI->eraseFromParent();
00637       continue;
00638     }
00639 
00640     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
00641       assert(SI->getOperand(0) != Ptr && "Consistency error!");
00642       Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
00643       Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
00644                                              NonConstantIdx, Builder);
00645       Builder.CreateStore(New, NewAI);
00646       SI->eraseFromParent();
00647 
00648       // If the load we just inserted is now dead, then the inserted store
00649       // overwrote the entire thing.
00650       if (Old->use_empty())
00651         Old->eraseFromParent();
00652       continue;
00653     }
00654 
00655     // If this is a constant sized memset of a constant value (e.g. 0) we can
00656     // transform it into a store of the expanded constant value.
00657     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
00658       assert(MSI->getRawDest() == Ptr && "Consistency error!");
00659       assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
00660       int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
00661       if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
00662         unsigned NumBytes = static_cast<unsigned>(SNumBytes);
00663         unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
00664 
00665         // Compute the value replicated the right number of times.
00666         APInt APVal(NumBytes*8, Val);
00667 
00668         // Splat the value if non-zero.
00669         if (Val)
00670           for (unsigned i = 1; i != NumBytes; ++i)
00671             APVal |= APVal << 8;
00672 
00673         Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
00674         Value *New = ConvertScalar_InsertValue(
00675                                     ConstantInt::get(User->getContext(), APVal),
00676                                                Old, Offset, nullptr, Builder);
00677         Builder.CreateStore(New, NewAI);
00678 
00679         // If the load we just inserted is now dead, then the memset overwrote
00680         // the entire thing.
00681         if (Old->use_empty())
00682           Old->eraseFromParent();
00683       }
00684       MSI->eraseFromParent();
00685       continue;
00686     }
00687 
00688     // If this is a memcpy or memmove into or out of the whole allocation, we
00689     // can handle it like a load or store of the scalar type.
00690     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
00691       assert(Offset == 0 && "must be store to start of alloca");
00692       assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
00693 
00694       // If the source and destination are both to the same alloca, then this is
00695       // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
00696       // as appropriate.
00697       AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &DL, 0));
00698 
00699       if (GetUnderlyingObject(MTI->getSource(), &DL, 0) != OrigAI) {
00700         // Dest must be OrigAI, change this to be a load from the original
00701         // pointer (bitcasted), then a store to our new alloca.
00702         assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
00703         Value *SrcPtr = MTI->getSource();
00704         PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
00705         PointerType* AIPTy = cast<PointerType>(NewAI->getType());
00706         if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
00707           AIPTy = PointerType::get(AIPTy->getElementType(),
00708                                    SPTy->getAddressSpace());
00709         }
00710         SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
00711 
00712         LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
00713         SrcVal->setAlignment(MTI->getAlignment());
00714         Builder.CreateStore(SrcVal, NewAI);
00715       } else if (GetUnderlyingObject(MTI->getDest(), &DL, 0) != OrigAI) {
00716         // Src must be OrigAI, change this to be a load from NewAI then a store
00717         // through the original dest pointer (bitcasted).
00718         assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
00719         LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
00720 
00721         PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
00722         PointerType* AIPTy = cast<PointerType>(NewAI->getType());
00723         if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
00724           AIPTy = PointerType::get(AIPTy->getElementType(),
00725                                    DPTy->getAddressSpace());
00726         }
00727         Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
00728 
00729         StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
00730         NewStore->setAlignment(MTI->getAlignment());
00731       } else {
00732         // Noop transfer. Src == Dst
00733       }
00734 
00735       MTI->eraseFromParent();
00736       continue;
00737     }
00738 
00739     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
00740       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
00741           II->getIntrinsicID() == Intrinsic::lifetime_end) {
00742         // There's no need to preserve these, as the resulting alloca will be
00743         // converted to a register anyways.
00744         II->eraseFromParent();
00745         continue;
00746       }
00747     }
00748 
00749     llvm_unreachable("Unsupported operation!");
00750   }
00751 }
00752 
00753 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
00754 /// or vector value FromVal, extracting the bits from the offset specified by
00755 /// Offset.  This returns the value, which is of type ToType.
00756 ///
00757 /// This happens when we are converting an "integer union" to a single
00758 /// integer scalar, or when we are converting a "vector union" to a vector with
00759 /// insert/extractelement instructions.
00760 ///
00761 /// Offset is an offset from the original alloca, in bits that need to be
00762 /// shifted to the right.
00763 Value *ConvertToScalarInfo::
00764 ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
00765                            uint64_t Offset, Value* NonConstantIdx,
00766                            IRBuilder<> &Builder) {
00767   // If the load is of the whole new alloca, no conversion is needed.
00768   Type *FromType = FromVal->getType();
00769   if (FromType == ToType && Offset == 0)
00770     return FromVal;
00771 
00772   // If the result alloca is a vector type, this is either an element
00773   // access or a bitcast to another vector type of the same size.
00774   if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
00775     unsigned FromTypeSize = DL.getTypeAllocSize(FromType);
00776     unsigned ToTypeSize = DL.getTypeAllocSize(ToType);
00777     if (FromTypeSize == ToTypeSize)
00778         return Builder.CreateBitCast(FromVal, ToType);
00779 
00780     // Otherwise it must be an element access.
00781     unsigned Elt = 0;
00782     if (Offset) {
00783       unsigned EltSize = DL.getTypeAllocSizeInBits(VTy->getElementType());
00784       Elt = Offset/EltSize;
00785       assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
00786     }
00787     // Return the element extracted out of it.
00788     Value *Idx;
00789     if (NonConstantIdx) {
00790       if (Elt)
00791         Idx = Builder.CreateAdd(NonConstantIdx,
00792                                 Builder.getInt32(Elt),
00793                                 "dyn.offset");
00794       else
00795         Idx = NonConstantIdx;
00796     } else
00797       Idx = Builder.getInt32(Elt);
00798     Value *V = Builder.CreateExtractElement(FromVal, Idx);
00799     if (V->getType() != ToType)
00800       V = Builder.CreateBitCast(V, ToType);
00801     return V;
00802   }
00803 
00804   // If ToType is a first class aggregate, extract out each of the pieces and
00805   // use insertvalue's to form the FCA.
00806   if (StructType *ST = dyn_cast<StructType>(ToType)) {
00807     assert(!NonConstantIdx &&
00808            "Dynamic indexing into struct types not supported");
00809     const StructLayout &Layout = *DL.getStructLayout(ST);
00810     Value *Res = UndefValue::get(ST);
00811     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
00812       Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
00813                                         Offset+Layout.getElementOffsetInBits(i),
00814                                               nullptr, Builder);
00815       Res = Builder.CreateInsertValue(Res, Elt, i);
00816     }
00817     return Res;
00818   }
00819 
00820   if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
00821     assert(!NonConstantIdx &&
00822            "Dynamic indexing into array types not supported");
00823     uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
00824     Value *Res = UndefValue::get(AT);
00825     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
00826       Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
00827                                               Offset+i*EltSize, nullptr,
00828                                               Builder);
00829       Res = Builder.CreateInsertValue(Res, Elt, i);
00830     }
00831     return Res;
00832   }
00833 
00834   // Otherwise, this must be a union that was converted to an integer value.
00835   IntegerType *NTy = cast<IntegerType>(FromVal->getType());
00836 
00837   // If this is a big-endian system and the load is narrower than the
00838   // full alloca type, we need to do a shift to get the right bits.
00839   int ShAmt = 0;
00840   if (DL.isBigEndian()) {
00841     // On big-endian machines, the lowest bit is stored at the bit offset
00842     // from the pointer given by getTypeStoreSizeInBits.  This matters for
00843     // integers with a bitwidth that is not a multiple of 8.
00844     ShAmt = DL.getTypeStoreSizeInBits(NTy) -
00845             DL.getTypeStoreSizeInBits(ToType) - Offset;
00846   } else {
00847     ShAmt = Offset;
00848   }
00849 
00850   // Note: we support negative bitwidths (with shl) which are not defined.
00851   // We do this to support (f.e.) loads off the end of a structure where
00852   // only some bits are used.
00853   if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
00854     FromVal = Builder.CreateLShr(FromVal,
00855                                  ConstantInt::get(FromVal->getType(), ShAmt));
00856   else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
00857     FromVal = Builder.CreateShl(FromVal,
00858                                 ConstantInt::get(FromVal->getType(), -ShAmt));
00859 
00860   // Finally, unconditionally truncate the integer to the right width.
00861   unsigned LIBitWidth = DL.getTypeSizeInBits(ToType);
00862   if (LIBitWidth < NTy->getBitWidth())
00863     FromVal =
00864       Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
00865                                                     LIBitWidth));
00866   else if (LIBitWidth > NTy->getBitWidth())
00867     FromVal =
00868        Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
00869                                                     LIBitWidth));
00870 
00871   // If the result is an integer, this is a trunc or bitcast.
00872   if (ToType->isIntegerTy()) {
00873     // Should be done.
00874   } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
00875     // Just do a bitcast, we know the sizes match up.
00876     FromVal = Builder.CreateBitCast(FromVal, ToType);
00877   } else {
00878     // Otherwise must be a pointer.
00879     FromVal = Builder.CreateIntToPtr(FromVal, ToType);
00880   }
00881   assert(FromVal->getType() == ToType && "Didn't convert right?");
00882   return FromVal;
00883 }
00884 
00885 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
00886 /// or vector value "Old" at the offset specified by Offset.
00887 ///
00888 /// This happens when we are converting an "integer union" to a
00889 /// single integer scalar, or when we are converting a "vector union" to a
00890 /// vector with insert/extractelement instructions.
00891 ///
00892 /// Offset is an offset from the original alloca, in bits that need to be
00893 /// shifted to the right.
00894 ///
00895 /// NonConstantIdx is an index value if there was a GEP with a non-constant
00896 /// index value.  If this is 0 then all GEPs used to find this insert address
00897 /// are constant.
00898 Value *ConvertToScalarInfo::
00899 ConvertScalar_InsertValue(Value *SV, Value *Old,
00900                           uint64_t Offset, Value* NonConstantIdx,
00901                           IRBuilder<> &Builder) {
00902   // Convert the stored type to the actual type, shift it left to insert
00903   // then 'or' into place.
00904   Type *AllocaType = Old->getType();
00905   LLVMContext &Context = Old->getContext();
00906 
00907   if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
00908     uint64_t VecSize = DL.getTypeAllocSizeInBits(VTy);
00909     uint64_t ValSize = DL.getTypeAllocSizeInBits(SV->getType());
00910 
00911     // Changing the whole vector with memset or with an access of a different
00912     // vector type?
00913     if (ValSize == VecSize)
00914         return Builder.CreateBitCast(SV, AllocaType);
00915 
00916     // Must be an element insertion.
00917     Type *EltTy = VTy->getElementType();
00918     if (SV->getType() != EltTy)
00919       SV = Builder.CreateBitCast(SV, EltTy);
00920     uint64_t EltSize = DL.getTypeAllocSizeInBits(EltTy);
00921     unsigned Elt = Offset/EltSize;
00922     Value *Idx;
00923     if (NonConstantIdx) {
00924       if (Elt)
00925         Idx = Builder.CreateAdd(NonConstantIdx,
00926                                 Builder.getInt32(Elt),
00927                                 "dyn.offset");
00928       else
00929         Idx = NonConstantIdx;
00930     } else
00931       Idx = Builder.getInt32(Elt);
00932     return Builder.CreateInsertElement(Old, SV, Idx);
00933   }
00934 
00935   // If SV is a first-class aggregate value, insert each value recursively.
00936   if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
00937     assert(!NonConstantIdx &&
00938            "Dynamic indexing into struct types not supported");
00939     const StructLayout &Layout = *DL.getStructLayout(ST);
00940     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
00941       Value *Elt = Builder.CreateExtractValue(SV, i);
00942       Old = ConvertScalar_InsertValue(Elt, Old,
00943                                       Offset+Layout.getElementOffsetInBits(i),
00944                                       nullptr, Builder);
00945     }
00946     return Old;
00947   }
00948 
00949   if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
00950     assert(!NonConstantIdx &&
00951            "Dynamic indexing into array types not supported");
00952     uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
00953     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
00954       Value *Elt = Builder.CreateExtractValue(SV, i);
00955       Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, nullptr,
00956                                       Builder);
00957     }
00958     return Old;
00959   }
00960 
00961   // If SV is a float, convert it to the appropriate integer type.
00962   // If it is a pointer, do the same.
00963   unsigned SrcWidth = DL.getTypeSizeInBits(SV->getType());
00964   unsigned DestWidth = DL.getTypeSizeInBits(AllocaType);
00965   unsigned SrcStoreWidth = DL.getTypeStoreSizeInBits(SV->getType());
00966   unsigned DestStoreWidth = DL.getTypeStoreSizeInBits(AllocaType);
00967   if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
00968     SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
00969   else if (SV->getType()->isPointerTy())
00970     SV = Builder.CreatePtrToInt(SV, DL.getIntPtrType(SV->getType()));
00971 
00972   // Zero extend or truncate the value if needed.
00973   if (SV->getType() != AllocaType) {
00974     if (SV->getType()->getPrimitiveSizeInBits() <
00975              AllocaType->getPrimitiveSizeInBits())
00976       SV = Builder.CreateZExt(SV, AllocaType);
00977     else {
00978       // Truncation may be needed if storing more than the alloca can hold
00979       // (undefined behavior).
00980       SV = Builder.CreateTrunc(SV, AllocaType);
00981       SrcWidth = DestWidth;
00982       SrcStoreWidth = DestStoreWidth;
00983     }
00984   }
00985 
00986   // If this is a big-endian system and the store is narrower than the
00987   // full alloca type, we need to do a shift to get the right bits.
00988   int ShAmt = 0;
00989   if (DL.isBigEndian()) {
00990     // On big-endian machines, the lowest bit is stored at the bit offset
00991     // from the pointer given by getTypeStoreSizeInBits.  This matters for
00992     // integers with a bitwidth that is not a multiple of 8.
00993     ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
00994   } else {
00995     ShAmt = Offset;
00996   }
00997 
00998   // Note: we support negative bitwidths (with shr) which are not defined.
00999   // We do this to support (f.e.) stores off the end of a structure where
01000   // only some bits in the structure are set.
01001   APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
01002   if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
01003     SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
01004     Mask <<= ShAmt;
01005   } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
01006     SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
01007     Mask = Mask.lshr(-ShAmt);
01008   }
01009 
01010   // Mask out the bits we are about to insert from the old value, and or
01011   // in the new bits.
01012   if (SrcWidth != DestWidth) {
01013     assert(DestWidth > SrcWidth);
01014     Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
01015     SV = Builder.CreateOr(Old, SV, "ins");
01016   }
01017   return SV;
01018 }
01019 
01020 
01021 //===----------------------------------------------------------------------===//
01022 // SRoA Driver
01023 //===----------------------------------------------------------------------===//
01024 
01025 
01026 bool SROA::runOnFunction(Function &F) {
01027   if (skipOptnoneFunction(F))
01028     return false;
01029 
01030   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01031   DL = DLP ? &DLP->getDataLayout() : nullptr;
01032 
01033   bool Changed = performPromotion(F);
01034 
01035   // FIXME: ScalarRepl currently depends on DataLayout more than it
01036   // theoretically needs to. It should be refactored in order to support
01037   // target-independent IR. Until this is done, just skip the actual
01038   // scalar-replacement portion of this pass.
01039   if (!DL) return Changed;
01040 
01041   while (1) {
01042     bool LocalChange = performScalarRepl(F);
01043     if (!LocalChange) break;   // No need to repromote if no scalarrepl
01044     Changed = true;
01045     LocalChange = performPromotion(F);
01046     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
01047   }
01048 
01049   return Changed;
01050 }
01051 
01052 namespace {
01053 class AllocaPromoter : public LoadAndStorePromoter {
01054   AllocaInst *AI;
01055   DIBuilder *DIB;
01056   SmallVector<DbgDeclareInst *, 4> DDIs;
01057   SmallVector<DbgValueInst *, 4> DVIs;
01058 public:
01059   AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
01060                  DIBuilder *DB)
01061     : LoadAndStorePromoter(Insts, S), AI(nullptr), DIB(DB) {}
01062 
01063   void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
01064     // Remember which alloca we're promoting (for isInstInList).
01065     this->AI = AI;
01066     if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI)) {
01067       for (User *U : DebugNode->users())
01068         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
01069           DDIs.push_back(DDI);
01070         else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
01071           DVIs.push_back(DVI);
01072     }
01073 
01074     LoadAndStorePromoter::run(Insts);
01075     AI->eraseFromParent();
01076     for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
01077            E = DDIs.end(); I != E; ++I) {
01078       DbgDeclareInst *DDI = *I;
01079       DDI->eraseFromParent();
01080     }
01081     for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
01082            E = DVIs.end(); I != E; ++I) {
01083       DbgValueInst *DVI = *I;
01084       DVI->eraseFromParent();
01085     }
01086   }
01087 
01088   bool isInstInList(Instruction *I,
01089                     const SmallVectorImpl<Instruction*> &Insts) const override {
01090     if (LoadInst *LI = dyn_cast<LoadInst>(I))
01091       return LI->getOperand(0) == AI;
01092     return cast<StoreInst>(I)->getPointerOperand() == AI;
01093   }
01094 
01095   void updateDebugInfo(Instruction *Inst) const override {
01096     for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
01097            E = DDIs.end(); I != E; ++I) {
01098       DbgDeclareInst *DDI = *I;
01099       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
01100         ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
01101       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
01102         ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
01103     }
01104     for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
01105            E = DVIs.end(); I != E; ++I) {
01106       DbgValueInst *DVI = *I;
01107       Value *Arg = nullptr;
01108       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
01109         // If an argument is zero extended then use argument directly. The ZExt
01110         // may be zapped by an optimization pass in future.
01111         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
01112           Arg = dyn_cast<Argument>(ZExt->getOperand(0));
01113         if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
01114           Arg = dyn_cast<Argument>(SExt->getOperand(0));
01115         if (!Arg)
01116           Arg = SI->getOperand(0);
01117       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
01118         Arg = LI->getOperand(0);
01119       } else {
01120         continue;
01121       }
01122       Instruction *DbgVal =
01123         DIB->insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
01124                                      Inst);
01125       DbgVal->setDebugLoc(DVI->getDebugLoc());
01126     }
01127   }
01128 };
01129 } // end anon namespace
01130 
01131 /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
01132 /// subsequently loaded can be rewritten to load both input pointers and then
01133 /// select between the result, allowing the load of the alloca to be promoted.
01134 /// From this:
01135 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
01136 ///   %V = load i32* %P2
01137 /// to:
01138 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01139 ///   %V2 = load i32* %Other
01140 ///   %V = select i1 %cond, i32 %V1, i32 %V2
01141 ///
01142 /// We can do this to a select if its only uses are loads and if the operand to
01143 /// the select can be loaded unconditionally.
01144 static bool isSafeSelectToSpeculate(SelectInst *SI, const DataLayout *DL) {
01145   bool TDerefable = SI->getTrueValue()->isDereferenceablePointer(DL);
01146   bool FDerefable = SI->getFalseValue()->isDereferenceablePointer(DL);
01147 
01148   for (User *U : SI->users()) {
01149     LoadInst *LI = dyn_cast<LoadInst>(U);
01150     if (!LI || !LI->isSimple()) return false;
01151 
01152     // Both operands to the select need to be dereferencable, either absolutely
01153     // (e.g. allocas) or at this point because we can see other accesses to it.
01154     if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
01155                                                     LI->getAlignment(), DL))
01156       return false;
01157     if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
01158                                                     LI->getAlignment(), DL))
01159       return false;
01160   }
01161 
01162   return true;
01163 }
01164 
01165 /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
01166 /// subsequently loaded can be rewritten to load both input pointers in the pred
01167 /// blocks and then PHI the results, allowing the load of the alloca to be
01168 /// promoted.
01169 /// From this:
01170 ///   %P2 = phi [i32* %Alloca, i32* %Other]
01171 ///   %V = load i32* %P2
01172 /// to:
01173 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01174 ///   ...
01175 ///   %V2 = load i32* %Other
01176 ///   ...
01177 ///   %V = phi [i32 %V1, i32 %V2]
01178 ///
01179 /// We can do this to a select if its only uses are loads and if the operand to
01180 /// the select can be loaded unconditionally.
01181 static bool isSafePHIToSpeculate(PHINode *PN, const DataLayout *DL) {
01182   // For now, we can only do this promotion if the load is in the same block as
01183   // the PHI, and if there are no stores between the phi and load.
01184   // TODO: Allow recursive phi users.
01185   // TODO: Allow stores.
01186   BasicBlock *BB = PN->getParent();
01187   unsigned MaxAlign = 0;
01188   for (User *U : PN->users()) {
01189     LoadInst *LI = dyn_cast<LoadInst>(U);
01190     if (!LI || !LI->isSimple()) return false;
01191 
01192     // For now we only allow loads in the same block as the PHI.  This is a
01193     // common case that happens when instcombine merges two loads through a PHI.
01194     if (LI->getParent() != BB) return false;
01195 
01196     // Ensure that there are no instructions between the PHI and the load that
01197     // could store.
01198     for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
01199       if (BBI->mayWriteToMemory())
01200         return false;
01201 
01202     MaxAlign = std::max(MaxAlign, LI->getAlignment());
01203   }
01204 
01205   // Okay, we know that we have one or more loads in the same block as the PHI.
01206   // We can transform this if it is safe to push the loads into the predecessor
01207   // blocks.  The only thing to watch out for is that we can't put a possibly
01208   // trapping load in the predecessor if it is a critical edge.
01209   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01210     BasicBlock *Pred = PN->getIncomingBlock(i);
01211     Value *InVal = PN->getIncomingValue(i);
01212 
01213     // If the terminator of the predecessor has side-effects (an invoke),
01214     // there is no safe place to put a load in the predecessor.
01215     if (Pred->getTerminator()->mayHaveSideEffects())
01216       return false;
01217 
01218     // If the value is produced by the terminator of the predecessor
01219     // (an invoke), there is no valid place to put a load in the predecessor.
01220     if (Pred->getTerminator() == InVal)
01221       return false;
01222 
01223     // If the predecessor has a single successor, then the edge isn't critical.
01224     if (Pred->getTerminator()->getNumSuccessors() == 1)
01225       continue;
01226 
01227     // If this pointer is always safe to load, or if we can prove that there is
01228     // already a load in the block, then we can move the load to the pred block.
01229     if (InVal->isDereferenceablePointer(DL) ||
01230         isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, DL))
01231       continue;
01232 
01233     return false;
01234   }
01235 
01236   return true;
01237 }
01238 
01239 
01240 /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
01241 /// direct (non-volatile) loads and stores to it.  If the alloca is close but
01242 /// not quite there, this will transform the code to allow promotion.  As such,
01243 /// it is a non-pure predicate.
01244 static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout *DL) {
01245   SetVector<Instruction*, SmallVector<Instruction*, 4>,
01246             SmallPtrSet<Instruction*, 4> > InstsToRewrite;
01247   for (User *U : AI->users()) {
01248     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
01249       if (!LI->isSimple())
01250         return false;
01251       continue;
01252     }
01253 
01254     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
01255       if (SI->getOperand(0) == AI || !SI->isSimple())
01256         return false;   // Don't allow a store OF the AI, only INTO the AI.
01257       continue;
01258     }
01259 
01260     if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
01261       // If the condition being selected on is a constant, fold the select, yes
01262       // this does (rarely) happen early on.
01263       if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
01264         Value *Result = SI->getOperand(1+CI->isZero());
01265         SI->replaceAllUsesWith(Result);
01266         SI->eraseFromParent();
01267 
01268         // This is very rare and we just scrambled the use list of AI, start
01269         // over completely.
01270         return tryToMakeAllocaBePromotable(AI, DL);
01271       }
01272 
01273       // If it is safe to turn "load (select c, AI, ptr)" into a select of two
01274       // loads, then we can transform this by rewriting the select.
01275       if (!isSafeSelectToSpeculate(SI, DL))
01276         return false;
01277 
01278       InstsToRewrite.insert(SI);
01279       continue;
01280     }
01281 
01282     if (PHINode *PN = dyn_cast<PHINode>(U)) {
01283       if (PN->use_empty()) {  // Dead PHIs can be stripped.
01284         InstsToRewrite.insert(PN);
01285         continue;
01286       }
01287 
01288       // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
01289       // in the pred blocks, then we can transform this by rewriting the PHI.
01290       if (!isSafePHIToSpeculate(PN, DL))
01291         return false;
01292 
01293       InstsToRewrite.insert(PN);
01294       continue;
01295     }
01296 
01297     if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
01298       if (onlyUsedByLifetimeMarkers(BCI)) {
01299         InstsToRewrite.insert(BCI);
01300         continue;
01301       }
01302     }
01303 
01304     return false;
01305   }
01306 
01307   // If there are no instructions to rewrite, then all uses are load/stores and
01308   // we're done!
01309   if (InstsToRewrite.empty())
01310     return true;
01311 
01312   // If we have instructions that need to be rewritten for this to be promotable
01313   // take care of it now.
01314   for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
01315     if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
01316       // This could only be a bitcast used by nothing but lifetime intrinsics.
01317       for (BitCastInst::user_iterator I = BCI->user_begin(), E = BCI->user_end();
01318            I != E;)
01319         cast<Instruction>(*I++)->eraseFromParent();
01320       BCI->eraseFromParent();
01321       continue;
01322     }
01323 
01324     if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
01325       // Selects in InstsToRewrite only have load uses.  Rewrite each as two
01326       // loads with a new select.
01327       while (!SI->use_empty()) {
01328         LoadInst *LI = cast<LoadInst>(SI->user_back());
01329 
01330         IRBuilder<> Builder(LI);
01331         LoadInst *TrueLoad =
01332           Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
01333         LoadInst *FalseLoad =
01334           Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
01335 
01336         // Transfer alignment and TBAA info if present.
01337         TrueLoad->setAlignment(LI->getAlignment());
01338         FalseLoad->setAlignment(LI->getAlignment());
01339         if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
01340           TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
01341           FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
01342         }
01343 
01344         Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
01345         V->takeName(LI);
01346         LI->replaceAllUsesWith(V);
01347         LI->eraseFromParent();
01348       }
01349 
01350       // Now that all the loads are gone, the select is gone too.
01351       SI->eraseFromParent();
01352       continue;
01353     }
01354 
01355     // Otherwise, we have a PHI node which allows us to push the loads into the
01356     // predecessors.
01357     PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
01358     if (PN->use_empty()) {
01359       PN->eraseFromParent();
01360       continue;
01361     }
01362 
01363     Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
01364     PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
01365                                      PN->getName()+".ld", PN);
01366 
01367     // Get the TBAA tag and alignment to use from one of the loads.  It doesn't
01368     // matter which one we get and if any differ, it doesn't matter.
01369     LoadInst *SomeLoad = cast<LoadInst>(PN->user_back());
01370     MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
01371     unsigned Align = SomeLoad->getAlignment();
01372 
01373     // Rewrite all loads of the PN to use the new PHI.
01374     while (!PN->use_empty()) {
01375       LoadInst *LI = cast<LoadInst>(PN->user_back());
01376       LI->replaceAllUsesWith(NewPN);
01377       LI->eraseFromParent();
01378     }
01379 
01380     // Inject loads into all of the pred blocks.  Keep track of which blocks we
01381     // insert them into in case we have multiple edges from the same block.
01382     DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
01383 
01384     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01385       BasicBlock *Pred = PN->getIncomingBlock(i);
01386       LoadInst *&Load = InsertedLoads[Pred];
01387       if (!Load) {
01388         Load = new LoadInst(PN->getIncomingValue(i),
01389                             PN->getName() + "." + Pred->getName(),
01390                             Pred->getTerminator());
01391         Load->setAlignment(Align);
01392         if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
01393       }
01394 
01395       NewPN->addIncoming(Load, Pred);
01396     }
01397 
01398     PN->eraseFromParent();
01399   }
01400 
01401   ++NumAdjusted;
01402   return true;
01403 }
01404 
01405 bool SROA::performPromotion(Function &F) {
01406   std::vector<AllocaInst*> Allocas;
01407   DominatorTree *DT = nullptr;
01408   if (HasDomTree)
01409     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
01410 
01411   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
01412   DIBuilder DIB(*F.getParent());
01413   bool Changed = false;
01414   SmallVector<Instruction*, 64> Insts;
01415   while (1) {
01416     Allocas.clear();
01417 
01418     // Find allocas that are safe to promote, by looking at all instructions in
01419     // the entry node
01420     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
01421       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
01422         if (tryToMakeAllocaBePromotable(AI, DL))
01423           Allocas.push_back(AI);
01424 
01425     if (Allocas.empty()) break;
01426 
01427     if (HasDomTree)
01428       PromoteMemToReg(Allocas, *DT);
01429     else {
01430       SSAUpdater SSA;
01431       for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
01432         AllocaInst *AI = Allocas[i];
01433 
01434         // Build list of instructions to promote.
01435         for (User *U : AI->users())
01436           Insts.push_back(cast<Instruction>(U));
01437         AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
01438         Insts.clear();
01439       }
01440     }
01441     NumPromoted += Allocas.size();
01442     Changed = true;
01443   }
01444 
01445   return Changed;
01446 }
01447 
01448 
01449 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
01450 /// SROA.  It must be a struct or array type with a small number of elements.
01451 bool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) {
01452   Type *T = AI->getAllocatedType();
01453   // Do not promote any struct that has too many members.
01454   if (StructType *ST = dyn_cast<StructType>(T))
01455     return ST->getNumElements() <= StructMemberThreshold;
01456   // Do not promote any array that has too many elements.
01457   if (ArrayType *AT = dyn_cast<ArrayType>(T))
01458     return AT->getNumElements() <= ArrayElementThreshold;
01459   return false;
01460 }
01461 
01462 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
01463 // which runs on all of the alloca instructions in the entry block, removing
01464 // them if they are only used by getelementptr instructions.
01465 //
01466 bool SROA::performScalarRepl(Function &F) {
01467   std::vector<AllocaInst*> WorkList;
01468 
01469   // Scan the entry basic block, adding allocas to the worklist.
01470   BasicBlock &BB = F.getEntryBlock();
01471   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
01472     if (AllocaInst *A = dyn_cast<AllocaInst>(I))
01473       WorkList.push_back(A);
01474 
01475   // Process the worklist
01476   bool Changed = false;
01477   while (!WorkList.empty()) {
01478     AllocaInst *AI = WorkList.back();
01479     WorkList.pop_back();
01480 
01481     // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
01482     // with unused elements.
01483     if (AI->use_empty()) {
01484       AI->eraseFromParent();
01485       Changed = true;
01486       continue;
01487     }
01488 
01489     // If this alloca is impossible for us to promote, reject it early.
01490     if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
01491       continue;
01492 
01493     // Check to see if we can perform the core SROA transformation.  We cannot
01494     // transform the allocation instruction if it is an array allocation
01495     // (allocations OF arrays are ok though), and an allocation of a scalar
01496     // value cannot be decomposed at all.
01497     uint64_t AllocaSize = DL->getTypeAllocSize(AI->getAllocatedType());
01498 
01499     // Do not promote [0 x %struct].
01500     if (AllocaSize == 0) continue;
01501 
01502     // Do not promote any struct whose size is too big.
01503     if (AllocaSize > SRThreshold) continue;
01504 
01505     // If the alloca looks like a good candidate for scalar replacement, and if
01506     // all its users can be transformed, then split up the aggregate into its
01507     // separate elements.
01508     if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
01509       DoScalarReplacement(AI, WorkList);
01510       Changed = true;
01511       continue;
01512     }
01513 
01514     // If we can turn this aggregate value (potentially with casts) into a
01515     // simple scalar value that can be mem2reg'd into a register value.
01516     // IsNotTrivial tracks whether this is something that mem2reg could have
01517     // promoted itself.  If so, we don't want to transform it needlessly.  Note
01518     // that we can't just check based on the type: the alloca may be of an i32
01519     // but that has pointer arithmetic to set byte 3 of it or something.
01520     if (AllocaInst *NewAI = ConvertToScalarInfo(
01521               (unsigned)AllocaSize, *DL, ScalarLoadThreshold).TryConvert(AI)) {
01522       NewAI->takeName(AI);
01523       AI->eraseFromParent();
01524       ++NumConverted;
01525       Changed = true;
01526       continue;
01527     }
01528 
01529     // Otherwise, couldn't process this alloca.
01530   }
01531 
01532   return Changed;
01533 }
01534 
01535 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
01536 /// predicate, do SROA now.
01537 void SROA::DoScalarReplacement(AllocaInst *AI,
01538                                std::vector<AllocaInst*> &WorkList) {
01539   DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
01540   SmallVector<AllocaInst*, 32> ElementAllocas;
01541   if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
01542     ElementAllocas.reserve(ST->getNumContainedTypes());
01543     for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
01544       AllocaInst *NA = new AllocaInst(ST->getContainedType(i), nullptr,
01545                                       AI->getAlignment(),
01546                                       AI->getName() + "." + Twine(i), AI);
01547       ElementAllocas.push_back(NA);
01548       WorkList.push_back(NA);  // Add to worklist for recursive processing
01549     }
01550   } else {
01551     ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
01552     ElementAllocas.reserve(AT->getNumElements());
01553     Type *ElTy = AT->getElementType();
01554     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
01555       AllocaInst *NA = new AllocaInst(ElTy, nullptr, AI->getAlignment(),
01556                                       AI->getName() + "." + Twine(i), AI);
01557       ElementAllocas.push_back(NA);
01558       WorkList.push_back(NA);  // Add to worklist for recursive processing
01559     }
01560   }
01561 
01562   // Now that we have created the new alloca instructions, rewrite all the
01563   // uses of the old alloca.
01564   RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
01565 
01566   // Now erase any instructions that were made dead while rewriting the alloca.
01567   DeleteDeadInstructions();
01568   AI->eraseFromParent();
01569 
01570   ++NumReplaced;
01571 }
01572 
01573 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
01574 /// recursively including all their operands that become trivially dead.
01575 void SROA::DeleteDeadInstructions() {
01576   while (!DeadInsts.empty()) {
01577     Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
01578 
01579     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
01580       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
01581         // Zero out the operand and see if it becomes trivially dead.
01582         // (But, don't add allocas to the dead instruction list -- they are
01583         // already on the worklist and will be deleted separately.)
01584         *OI = nullptr;
01585         if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
01586           DeadInsts.push_back(U);
01587       }
01588 
01589     I->eraseFromParent();
01590   }
01591 }
01592 
01593 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
01594 /// performing scalar replacement of alloca AI.  The results are flagged in
01595 /// the Info parameter.  Offset indicates the position within AI that is
01596 /// referenced by this instruction.
01597 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
01598                                AllocaInfo &Info) {
01599   for (Use &U : I->uses()) {
01600     Instruction *User = cast<Instruction>(U.getUser());
01601 
01602     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
01603       isSafeForScalarRepl(BC, Offset, Info);
01604     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
01605       uint64_t GEPOffset = Offset;
01606       isSafeGEP(GEPI, GEPOffset, Info);
01607       if (!Info.isUnsafe)
01608         isSafeForScalarRepl(GEPI, GEPOffset, Info);
01609     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
01610       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
01611       if (!Length || Length->isNegative())
01612         return MarkUnsafe(Info, User);
01613 
01614       isSafeMemAccess(Offset, Length->getZExtValue(), nullptr,
01615                       U.getOperandNo() == 0, Info, MI,
01616                       true /*AllowWholeAccess*/);
01617     } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
01618       if (!LI->isSimple())
01619         return MarkUnsafe(Info, User);
01620       Type *LIType = LI->getType();
01621       isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
01622                       LIType, false, Info, LI, true /*AllowWholeAccess*/);
01623       Info.hasALoadOrStore = true;
01624 
01625     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
01626       // Store is ok if storing INTO the pointer, not storing the pointer
01627       if (!SI->isSimple() || SI->getOperand(0) == I)
01628         return MarkUnsafe(Info, User);
01629 
01630       Type *SIType = SI->getOperand(0)->getType();
01631       isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
01632                       SIType, true, Info, SI, true /*AllowWholeAccess*/);
01633       Info.hasALoadOrStore = true;
01634     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
01635       if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
01636           II->getIntrinsicID() != Intrinsic::lifetime_end)
01637         return MarkUnsafe(Info, User);
01638     } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
01639       isSafePHISelectUseForScalarRepl(User, Offset, Info);
01640     } else {
01641       return MarkUnsafe(Info, User);
01642     }
01643     if (Info.isUnsafe) return;
01644   }
01645 }
01646 
01647 
01648 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
01649 /// derived from the alloca, we can often still split the alloca into elements.
01650 /// This is useful if we have a large alloca where one element is phi'd
01651 /// together somewhere: we can SRoA and promote all the other elements even if
01652 /// we end up not being able to promote this one.
01653 ///
01654 /// All we require is that the uses of the PHI do not index into other parts of
01655 /// the alloca.  The most important use case for this is single load and stores
01656 /// that are PHI'd together, which can happen due to code sinking.
01657 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
01658                                            AllocaInfo &Info) {
01659   // If we've already checked this PHI, don't do it again.
01660   if (PHINode *PN = dyn_cast<PHINode>(I))
01661     if (!Info.CheckedPHIs.insert(PN))
01662       return;
01663 
01664   for (User *U : I->users()) {
01665     Instruction *UI = cast<Instruction>(U);
01666 
01667     if (BitCastInst *BC = dyn_cast<BitCastInst>(UI)) {
01668       isSafePHISelectUseForScalarRepl(BC, Offset, Info);
01669     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
01670       // Only allow "bitcast" GEPs for simplicity.  We could generalize this,
01671       // but would have to prove that we're staying inside of an element being
01672       // promoted.
01673       if (!GEPI->hasAllZeroIndices())
01674         return MarkUnsafe(Info, UI);
01675       isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
01676     } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
01677       if (!LI->isSimple())
01678         return MarkUnsafe(Info, UI);
01679       Type *LIType = LI->getType();
01680       isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
01681                       LIType, false, Info, LI, false /*AllowWholeAccess*/);
01682       Info.hasALoadOrStore = true;
01683 
01684     } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
01685       // Store is ok if storing INTO the pointer, not storing the pointer
01686       if (!SI->isSimple() || SI->getOperand(0) == I)
01687         return MarkUnsafe(Info, UI);
01688 
01689       Type *SIType = SI->getOperand(0)->getType();
01690       isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
01691                       SIType, true, Info, SI, false /*AllowWholeAccess*/);
01692       Info.hasALoadOrStore = true;
01693     } else if (isa<PHINode>(UI) || isa<SelectInst>(UI)) {
01694       isSafePHISelectUseForScalarRepl(UI, Offset, Info);
01695     } else {
01696       return MarkUnsafe(Info, UI);
01697     }
01698     if (Info.isUnsafe) return;
01699   }
01700 }
01701 
01702 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
01703 /// replacement.  It is safe when all the indices are constant, in-bounds
01704 /// references, and when the resulting offset corresponds to an element within
01705 /// the alloca type.  The results are flagged in the Info parameter.  Upon
01706 /// return, Offset is adjusted as specified by the GEP indices.
01707 void SROA::isSafeGEP(GetElementPtrInst *GEPI,
01708                      uint64_t &Offset, AllocaInfo &Info) {
01709   gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
01710   if (GEPIt == E)
01711     return;
01712   bool NonConstant = false;
01713   unsigned NonConstantIdxSize = 0;
01714 
01715   // Walk through the GEP type indices, checking the types that this indexes
01716   // into.
01717   for (; GEPIt != E; ++GEPIt) {
01718     // Ignore struct elements, no extra checking needed for these.
01719     if ((*GEPIt)->isStructTy())
01720       continue;
01721 
01722     ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
01723     if (!IdxVal)
01724       return MarkUnsafe(Info, GEPI);
01725   }
01726 
01727   // Compute the offset due to this GEP and check if the alloca has a
01728   // component element at that offset.
01729   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
01730   // If this GEP is non-constant then the last operand must have been a
01731   // dynamic index into a vector.  Pop this now as it has no impact on the
01732   // constant part of the offset.
01733   if (NonConstant)
01734     Indices.pop_back();
01735   Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
01736   if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset,
01737                         NonConstantIdxSize))
01738     MarkUnsafe(Info, GEPI);
01739 }
01740 
01741 /// isHomogeneousAggregate - Check if type T is a struct or array containing
01742 /// elements of the same type (which is always true for arrays).  If so,
01743 /// return true with NumElts and EltTy set to the number of elements and the
01744 /// element type, respectively.
01745 static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
01746                                    Type *&EltTy) {
01747   if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
01748     NumElts = AT->getNumElements();
01749     EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
01750     return true;
01751   }
01752   if (StructType *ST = dyn_cast<StructType>(T)) {
01753     NumElts = ST->getNumContainedTypes();
01754     EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
01755     for (unsigned n = 1; n < NumElts; ++n) {
01756       if (ST->getContainedType(n) != EltTy)
01757         return false;
01758     }
01759     return true;
01760   }
01761   return false;
01762 }
01763 
01764 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
01765 /// "homogeneous" aggregates with the same element type and number of elements.
01766 static bool isCompatibleAggregate(Type *T1, Type *T2) {
01767   if (T1 == T2)
01768     return true;
01769 
01770   unsigned NumElts1, NumElts2;
01771   Type *EltTy1, *EltTy2;
01772   if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
01773       isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
01774       NumElts1 == NumElts2 &&
01775       EltTy1 == EltTy2)
01776     return true;
01777 
01778   return false;
01779 }
01780 
01781 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
01782 /// alloca or has an offset and size that corresponds to a component element
01783 /// within it.  The offset checked here may have been formed from a GEP with a
01784 /// pointer bitcasted to a different type.
01785 ///
01786 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
01787 /// unit.  If false, it only allows accesses known to be in a single element.
01788 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
01789                            Type *MemOpType, bool isStore,
01790                            AllocaInfo &Info, Instruction *TheAccess,
01791                            bool AllowWholeAccess) {
01792   // Check if this is a load/store of the entire alloca.
01793   if (Offset == 0 && AllowWholeAccess &&
01794       MemSize == DL->getTypeAllocSize(Info.AI->getAllocatedType())) {
01795     // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
01796     // loads/stores (which are essentially the same as the MemIntrinsics with
01797     // regard to copying padding between elements).  But, if an alloca is
01798     // flagged as both a source and destination of such operations, we'll need
01799     // to check later for padding between elements.
01800     if (!MemOpType || MemOpType->isIntegerTy()) {
01801       if (isStore)
01802         Info.isMemCpyDst = true;
01803       else
01804         Info.isMemCpySrc = true;
01805       return;
01806     }
01807     // This is also safe for references using a type that is compatible with
01808     // the type of the alloca, so that loads/stores can be rewritten using
01809     // insertvalue/extractvalue.
01810     if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
01811       Info.hasSubelementAccess = true;
01812       return;
01813     }
01814   }
01815   // Check if the offset/size correspond to a component within the alloca type.
01816   Type *T = Info.AI->getAllocatedType();
01817   if (TypeHasComponent(T, Offset, MemSize)) {
01818     Info.hasSubelementAccess = true;
01819     return;
01820   }
01821 
01822   return MarkUnsafe(Info, TheAccess);
01823 }
01824 
01825 /// TypeHasComponent - Return true if T has a component type with the
01826 /// specified offset and size.  If Size is zero, do not check the size.
01827 bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
01828   Type *EltTy;
01829   uint64_t EltSize;
01830   if (StructType *ST = dyn_cast<StructType>(T)) {
01831     const StructLayout *Layout = DL->getStructLayout(ST);
01832     unsigned EltIdx = Layout->getElementContainingOffset(Offset);
01833     EltTy = ST->getContainedType(EltIdx);
01834     EltSize = DL->getTypeAllocSize(EltTy);
01835     Offset -= Layout->getElementOffset(EltIdx);
01836   } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
01837     EltTy = AT->getElementType();
01838     EltSize = DL->getTypeAllocSize(EltTy);
01839     if (Offset >= AT->getNumElements() * EltSize)
01840       return false;
01841     Offset %= EltSize;
01842   } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
01843     EltTy = VT->getElementType();
01844     EltSize = DL->getTypeAllocSize(EltTy);
01845     if (Offset >= VT->getNumElements() * EltSize)
01846       return false;
01847     Offset %= EltSize;
01848   } else {
01849     return false;
01850   }
01851   if (Offset == 0 && (Size == 0 || EltSize == Size))
01852     return true;
01853   // Check if the component spans multiple elements.
01854   if (Offset + Size > EltSize)
01855     return false;
01856   return TypeHasComponent(EltTy, Offset, Size);
01857 }
01858 
01859 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
01860 /// the instruction I, which references it, to use the separate elements.
01861 /// Offset indicates the position within AI that is referenced by this
01862 /// instruction.
01863 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
01864                                 SmallVectorImpl<AllocaInst *> &NewElts) {
01865   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
01866     Use &TheUse = *UI++;
01867     Instruction *User = cast<Instruction>(TheUse.getUser());
01868 
01869     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
01870       RewriteBitCast(BC, AI, Offset, NewElts);
01871       continue;
01872     }
01873 
01874     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
01875       RewriteGEP(GEPI, AI, Offset, NewElts);
01876       continue;
01877     }
01878 
01879     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
01880       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
01881       uint64_t MemSize = Length->getZExtValue();
01882       if (Offset == 0 &&
01883           MemSize == DL->getTypeAllocSize(AI->getAllocatedType()))
01884         RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
01885       // Otherwise the intrinsic can only touch a single element and the
01886       // address operand will be updated, so nothing else needs to be done.
01887       continue;
01888     }
01889 
01890     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
01891       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
01892           II->getIntrinsicID() == Intrinsic::lifetime_end) {
01893         RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
01894       }
01895       continue;
01896     }
01897 
01898     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
01899       Type *LIType = LI->getType();
01900 
01901       if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
01902         // Replace:
01903         //   %res = load { i32, i32 }* %alloc
01904         // with:
01905         //   %load.0 = load i32* %alloc.0
01906         //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
01907         //   %load.1 = load i32* %alloc.1
01908         //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
01909         // (Also works for arrays instead of structs)
01910         Value *Insert = UndefValue::get(LIType);
01911         IRBuilder<> Builder(LI);
01912         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
01913           Value *Load = Builder.CreateLoad(NewElts[i], "load");
01914           Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
01915         }
01916         LI->replaceAllUsesWith(Insert);
01917         DeadInsts.push_back(LI);
01918       } else if (LIType->isIntegerTy() &&
01919                  DL->getTypeAllocSize(LIType) ==
01920                  DL->getTypeAllocSize(AI->getAllocatedType())) {
01921         // If this is a load of the entire alloca to an integer, rewrite it.
01922         RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
01923       }
01924       continue;
01925     }
01926 
01927     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
01928       Value *Val = SI->getOperand(0);
01929       Type *SIType = Val->getType();
01930       if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
01931         // Replace:
01932         //   store { i32, i32 } %val, { i32, i32 }* %alloc
01933         // with:
01934         //   %val.0 = extractvalue { i32, i32 } %val, 0
01935         //   store i32 %val.0, i32* %alloc.0
01936         //   %val.1 = extractvalue { i32, i32 } %val, 1
01937         //   store i32 %val.1, i32* %alloc.1
01938         // (Also works for arrays instead of structs)
01939         IRBuilder<> Builder(SI);
01940         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
01941           Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
01942           Builder.CreateStore(Extract, NewElts[i]);
01943         }
01944         DeadInsts.push_back(SI);
01945       } else if (SIType->isIntegerTy() &&
01946                  DL->getTypeAllocSize(SIType) ==
01947                  DL->getTypeAllocSize(AI->getAllocatedType())) {
01948         // If this is a store of the entire alloca from an integer, rewrite it.
01949         RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
01950       }
01951       continue;
01952     }
01953 
01954     if (isa<SelectInst>(User) || isa<PHINode>(User)) {
01955       // If we have a PHI user of the alloca itself (as opposed to a GEP or
01956       // bitcast) we have to rewrite it.  GEP and bitcast uses will be RAUW'd to
01957       // the new pointer.
01958       if (!isa<AllocaInst>(I)) continue;
01959 
01960       assert(Offset == 0 && NewElts[0] &&
01961              "Direct alloca use should have a zero offset");
01962 
01963       // If we have a use of the alloca, we know the derived uses will be
01964       // utilizing just the first element of the scalarized result.  Insert a
01965       // bitcast of the first alloca before the user as required.
01966       AllocaInst *NewAI = NewElts[0];
01967       BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
01968       NewAI->moveBefore(BCI);
01969       TheUse = BCI;
01970       continue;
01971     }
01972   }
01973 }
01974 
01975 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
01976 /// and recursively continue updating all of its uses.
01977 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
01978                           SmallVectorImpl<AllocaInst *> &NewElts) {
01979   RewriteForScalarRepl(BC, AI, Offset, NewElts);
01980   if (BC->getOperand(0) != AI)
01981     return;
01982 
01983   // The bitcast references the original alloca.  Replace its uses with
01984   // references to the alloca containing offset zero (which is normally at
01985   // index zero, but might not be in cases involving structs with elements
01986   // of size zero).
01987   Type *T = AI->getAllocatedType();
01988   uint64_t EltOffset = 0;
01989   Type *IdxTy;
01990   uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
01991   Instruction *Val = NewElts[Idx];
01992   if (Val->getType() != BC->getDestTy()) {
01993     Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
01994     Val->takeName(BC);
01995   }
01996   BC->replaceAllUsesWith(Val);
01997   DeadInsts.push_back(BC);
01998 }
01999 
02000 /// FindElementAndOffset - Return the index of the element containing Offset
02001 /// within the specified type, which must be either a struct or an array.
02002 /// Sets T to the type of the element and Offset to the offset within that
02003 /// element.  IdxTy is set to the type of the index result to be used in a
02004 /// GEP instruction.
02005 uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
02006                                     Type *&IdxTy) {
02007   uint64_t Idx = 0;
02008   if (StructType *ST = dyn_cast<StructType>(T)) {
02009     const StructLayout *Layout = DL->getStructLayout(ST);
02010     Idx = Layout->getElementContainingOffset(Offset);
02011     T = ST->getContainedType(Idx);
02012     Offset -= Layout->getElementOffset(Idx);
02013     IdxTy = Type::getInt32Ty(T->getContext());
02014     return Idx;
02015   } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
02016     T = AT->getElementType();
02017     uint64_t EltSize = DL->getTypeAllocSize(T);
02018     Idx = Offset / EltSize;
02019     Offset -= Idx * EltSize;
02020     IdxTy = Type::getInt64Ty(T->getContext());
02021     return Idx;
02022   }
02023   VectorType *VT = cast<VectorType>(T);
02024   T = VT->getElementType();
02025   uint64_t EltSize = DL->getTypeAllocSize(T);
02026   Idx = Offset / EltSize;
02027   Offset -= Idx * EltSize;
02028   IdxTy = Type::getInt64Ty(T->getContext());
02029   return Idx;
02030 }
02031 
02032 /// RewriteGEP - Check if this GEP instruction moves the pointer across
02033 /// elements of the alloca that are being split apart, and if so, rewrite
02034 /// the GEP to be relative to the new element.
02035 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
02036                       SmallVectorImpl<AllocaInst *> &NewElts) {
02037   uint64_t OldOffset = Offset;
02038   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
02039   // If the GEP was dynamic then it must have been a dynamic vector lookup.
02040   // In this case, it must be the last GEP operand which is dynamic so keep that
02041   // aside until we've found the constant GEP offset then add it back in at the
02042   // end.
02043   Value* NonConstantIdx = nullptr;
02044   if (!GEPI->hasAllConstantIndices())
02045     NonConstantIdx = Indices.pop_back_val();
02046   Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
02047 
02048   RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
02049 
02050   Type *T = AI->getAllocatedType();
02051   Type *IdxTy;
02052   uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
02053   if (GEPI->getOperand(0) == AI)
02054     OldIdx = ~0ULL; // Force the GEP to be rewritten.
02055 
02056   T = AI->getAllocatedType();
02057   uint64_t EltOffset = Offset;
02058   uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
02059 
02060   // If this GEP does not move the pointer across elements of the alloca
02061   // being split, then it does not needs to be rewritten.
02062   if (Idx == OldIdx)
02063     return;
02064 
02065   Type *i32Ty = Type::getInt32Ty(AI->getContext());
02066   SmallVector<Value*, 8> NewArgs;
02067   NewArgs.push_back(Constant::getNullValue(i32Ty));
02068   while (EltOffset != 0) {
02069     uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
02070     NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
02071   }
02072   if (NonConstantIdx) {
02073     Type* GepTy = T;
02074     // This GEP has a dynamic index.  We need to add "i32 0" to index through
02075     // any structs or arrays in the original type until we get to the vector
02076     // to index.
02077     while (!isa<VectorType>(GepTy)) {
02078       NewArgs.push_back(Constant::getNullValue(i32Ty));
02079       GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
02080     }
02081     NewArgs.push_back(NonConstantIdx);
02082   }
02083   Instruction *Val = NewElts[Idx];
02084   if (NewArgs.size() > 1) {
02085     Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
02086     Val->takeName(GEPI);
02087   }
02088   if (Val->getType() != GEPI->getType())
02089     Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
02090   GEPI->replaceAllUsesWith(Val);
02091   DeadInsts.push_back(GEPI);
02092 }
02093 
02094 /// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
02095 /// to mark the lifetime of the scalarized memory.
02096 void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
02097                                     uint64_t Offset,
02098                                     SmallVectorImpl<AllocaInst *> &NewElts) {
02099   ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
02100   // Put matching lifetime markers on everything from Offset up to
02101   // Offset+OldSize.
02102   Type *AIType = AI->getAllocatedType();
02103   uint64_t NewOffset = Offset;
02104   Type *IdxTy;
02105   uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
02106 
02107   IRBuilder<> Builder(II);
02108   uint64_t Size = OldSize->getLimitedValue();
02109 
02110   if (NewOffset) {
02111     // Splice the first element and index 'NewOffset' bytes in.  SROA will
02112     // split the alloca again later.
02113     unsigned AS = AI->getType()->getAddressSpace();
02114     Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy(AS));
02115     V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
02116 
02117     IdxTy = NewElts[Idx]->getAllocatedType();
02118     uint64_t EltSize = DL->getTypeAllocSize(IdxTy) - NewOffset;
02119     if (EltSize > Size) {
02120       EltSize = Size;
02121       Size = 0;
02122     } else {
02123       Size -= EltSize;
02124     }
02125     if (II->getIntrinsicID() == Intrinsic::lifetime_start)
02126       Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
02127     else
02128       Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
02129     ++Idx;
02130   }
02131 
02132   for (; Idx != NewElts.size() && Size; ++Idx) {
02133     IdxTy = NewElts[Idx]->getAllocatedType();
02134     uint64_t EltSize = DL->getTypeAllocSize(IdxTy);
02135     if (EltSize > Size) {
02136       EltSize = Size;
02137       Size = 0;
02138     } else {
02139       Size -= EltSize;
02140     }
02141     if (II->getIntrinsicID() == Intrinsic::lifetime_start)
02142       Builder.CreateLifetimeStart(NewElts[Idx],
02143                                   Builder.getInt64(EltSize));
02144     else
02145       Builder.CreateLifetimeEnd(NewElts[Idx],
02146                                 Builder.getInt64(EltSize));
02147   }
02148   DeadInsts.push_back(II);
02149 }
02150 
02151 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
02152 /// Rewrite it to copy or set the elements of the scalarized memory.
02153 void
02154 SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
02155                                    AllocaInst *AI,
02156                                    SmallVectorImpl<AllocaInst *> &NewElts) {
02157   // If this is a memcpy/memmove, construct the other pointer as the
02158   // appropriate type.  The "Other" pointer is the pointer that goes to memory
02159   // that doesn't have anything to do with the alloca that we are promoting. For
02160   // memset, this Value* stays null.
02161   Value *OtherPtr = nullptr;
02162   unsigned MemAlignment = MI->getAlignment();
02163   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
02164     if (Inst == MTI->getRawDest())
02165       OtherPtr = MTI->getRawSource();
02166     else {
02167       assert(Inst == MTI->getRawSource());
02168       OtherPtr = MTI->getRawDest();
02169     }
02170   }
02171 
02172   // If there is an other pointer, we want to convert it to the same pointer
02173   // type as AI has, so we can GEP through it safely.
02174   if (OtherPtr) {
02175     unsigned AddrSpace =
02176       cast<PointerType>(OtherPtr->getType())->getAddressSpace();
02177 
02178     // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
02179     // optimization, but it's also required to detect the corner case where
02180     // both pointer operands are referencing the same memory, and where
02181     // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
02182     // function is only called for mem intrinsics that access the whole
02183     // aggregate, so non-zero GEPs are not an issue here.)
02184     OtherPtr = OtherPtr->stripPointerCasts();
02185 
02186     // Copying the alloca to itself is a no-op: just delete it.
02187     if (OtherPtr == AI || OtherPtr == NewElts[0]) {
02188       // This code will run twice for a no-op memcpy -- once for each operand.
02189       // Put only one reference to MI on the DeadInsts list.
02190       for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
02191              E = DeadInsts.end(); I != E; ++I)
02192         if (*I == MI) return;
02193       DeadInsts.push_back(MI);
02194       return;
02195     }
02196 
02197     // If the pointer is not the right type, insert a bitcast to the right
02198     // type.
02199     Type *NewTy =
02200       PointerType::get(AI->getType()->getElementType(), AddrSpace);
02201 
02202     if (OtherPtr->getType() != NewTy)
02203       OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
02204   }
02205 
02206   // Process each element of the aggregate.
02207   bool SROADest = MI->getRawDest() == Inst;
02208 
02209   Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
02210 
02211   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02212     // If this is a memcpy/memmove, emit a GEP of the other element address.
02213     Value *OtherElt = nullptr;
02214     unsigned OtherEltAlign = MemAlignment;
02215 
02216     if (OtherPtr) {
02217       Value *Idx[2] = { Zero,
02218                       ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
02219       OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
02220                                               OtherPtr->getName()+"."+Twine(i),
02221                                                    MI);
02222       uint64_t EltOffset;
02223       PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
02224       Type *OtherTy = OtherPtrTy->getElementType();
02225       if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
02226         EltOffset = DL->getStructLayout(ST)->getElementOffset(i);
02227       } else {
02228         Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
02229         EltOffset = DL->getTypeAllocSize(EltTy)*i;
02230       }
02231 
02232       // The alignment of the other pointer is the guaranteed alignment of the
02233       // element, which is affected by both the known alignment of the whole
02234       // mem intrinsic and the alignment of the element.  If the alignment of
02235       // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
02236       // known alignment is just 4 bytes.
02237       OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
02238     }
02239 
02240     Value *EltPtr = NewElts[i];
02241     Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
02242 
02243     // If we got down to a scalar, insert a load or store as appropriate.
02244     if (EltTy->isSingleValueType()) {
02245       if (isa<MemTransferInst>(MI)) {
02246         if (SROADest) {
02247           // From Other to Alloca.
02248           Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
02249           new StoreInst(Elt, EltPtr, MI);
02250         } else {
02251           // From Alloca to Other.
02252           Value *Elt = new LoadInst(EltPtr, "tmp", MI);
02253           new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
02254         }
02255         continue;
02256       }
02257       assert(isa<MemSetInst>(MI));
02258 
02259       // If the stored element is zero (common case), just store a null
02260       // constant.
02261       Constant *StoreVal;
02262       if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
02263         if (CI->isZero()) {
02264           StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
02265         } else {
02266           // If EltTy is a vector type, get the element type.
02267           Type *ValTy = EltTy->getScalarType();
02268 
02269           // Construct an integer with the right value.
02270           unsigned EltSize = DL->getTypeSizeInBits(ValTy);
02271           APInt OneVal(EltSize, CI->getZExtValue());
02272           APInt TotalVal(OneVal);
02273           // Set each byte.
02274           for (unsigned i = 0; 8*i < EltSize; ++i) {
02275             TotalVal = TotalVal.shl(8);
02276             TotalVal |= OneVal;
02277           }
02278 
02279           // Convert the integer value to the appropriate type.
02280           StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
02281           if (ValTy->isPointerTy())
02282             StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
02283           else if (ValTy->isFloatingPointTy())
02284             StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
02285           assert(StoreVal->getType() == ValTy && "Type mismatch!");
02286 
02287           // If the requested value was a vector constant, create it.
02288           if (EltTy->isVectorTy()) {
02289             unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
02290             StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
02291           }
02292         }
02293         new StoreInst(StoreVal, EltPtr, MI);
02294         continue;
02295       }
02296       // Otherwise, if we're storing a byte variable, use a memset call for
02297       // this element.
02298     }
02299 
02300     unsigned EltSize = DL->getTypeAllocSize(EltTy);
02301     if (!EltSize)
02302       continue;
02303 
02304     IRBuilder<> Builder(MI);
02305 
02306     // Finally, insert the meminst for this element.
02307     if (isa<MemSetInst>(MI)) {
02308       Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
02309                            MI->isVolatile());
02310     } else {
02311       assert(isa<MemTransferInst>(MI));
02312       Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
02313       Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
02314 
02315       if (isa<MemCpyInst>(MI))
02316         Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
02317       else
02318         Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
02319     }
02320   }
02321   DeadInsts.push_back(MI);
02322 }
02323 
02324 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
02325 /// overwrites the entire allocation.  Extract out the pieces of the stored
02326 /// integer and store them individually.
02327 void
02328 SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
02329                                     SmallVectorImpl<AllocaInst *> &NewElts) {
02330   // Extract each element out of the integer according to its structure offset
02331   // and store the element value to the individual alloca.
02332   Value *SrcVal = SI->getOperand(0);
02333   Type *AllocaEltTy = AI->getAllocatedType();
02334   uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
02335 
02336   IRBuilder<> Builder(SI);
02337 
02338   // Handle tail padding by extending the operand
02339   if (DL->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
02340     SrcVal = Builder.CreateZExt(SrcVal,
02341                             IntegerType::get(SI->getContext(), AllocaSizeBits));
02342 
02343   DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
02344                << '\n');
02345 
02346   // There are two forms here: AI could be an array or struct.  Both cases
02347   // have different ways to compute the element offset.
02348   if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
02349     const StructLayout *Layout = DL->getStructLayout(EltSTy);
02350 
02351     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02352       // Get the number of bits to shift SrcVal to get the value.
02353       Type *FieldTy = EltSTy->getElementType(i);
02354       uint64_t Shift = Layout->getElementOffsetInBits(i);
02355 
02356       if (DL->isBigEndian())
02357         Shift = AllocaSizeBits-Shift-DL->getTypeAllocSizeInBits(FieldTy);
02358 
02359       Value *EltVal = SrcVal;
02360       if (Shift) {
02361         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
02362         EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
02363       }
02364 
02365       // Truncate down to an integer of the right size.
02366       uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
02367 
02368       // Ignore zero sized fields like {}, they obviously contain no data.
02369       if (FieldSizeBits == 0) continue;
02370 
02371       if (FieldSizeBits != AllocaSizeBits)
02372         EltVal = Builder.CreateTrunc(EltVal,
02373                              IntegerType::get(SI->getContext(), FieldSizeBits));
02374       Value *DestField = NewElts[i];
02375       if (EltVal->getType() == FieldTy) {
02376         // Storing to an integer field of this size, just do it.
02377       } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
02378         // Bitcast to the right element type (for fp/vector values).
02379         EltVal = Builder.CreateBitCast(EltVal, FieldTy);
02380       } else {
02381         // Otherwise, bitcast the dest pointer (for aggregates).
02382         DestField = Builder.CreateBitCast(DestField,
02383                                      PointerType::getUnqual(EltVal->getType()));
02384       }
02385       new StoreInst(EltVal, DestField, SI);
02386     }
02387 
02388   } else {
02389     ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
02390     Type *ArrayEltTy = ATy->getElementType();
02391     uint64_t ElementOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
02392     uint64_t ElementSizeBits = DL->getTypeSizeInBits(ArrayEltTy);
02393 
02394     uint64_t Shift;
02395 
02396     if (DL->isBigEndian())
02397       Shift = AllocaSizeBits-ElementOffset;
02398     else
02399       Shift = 0;
02400 
02401     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02402       // Ignore zero sized fields like {}, they obviously contain no data.
02403       if (ElementSizeBits == 0) continue;
02404 
02405       Value *EltVal = SrcVal;
02406       if (Shift) {
02407         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
02408         EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
02409       }
02410 
02411       // Truncate down to an integer of the right size.
02412       if (ElementSizeBits != AllocaSizeBits)
02413         EltVal = Builder.CreateTrunc(EltVal,
02414                                      IntegerType::get(SI->getContext(),
02415                                                       ElementSizeBits));
02416       Value *DestField = NewElts[i];
02417       if (EltVal->getType() == ArrayEltTy) {
02418         // Storing to an integer field of this size, just do it.
02419       } else if (ArrayEltTy->isFloatingPointTy() ||
02420                  ArrayEltTy->isVectorTy()) {
02421         // Bitcast to the right element type (for fp/vector values).
02422         EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
02423       } else {
02424         // Otherwise, bitcast the dest pointer (for aggregates).
02425         DestField = Builder.CreateBitCast(DestField,
02426                                      PointerType::getUnqual(EltVal->getType()));
02427       }
02428       new StoreInst(EltVal, DestField, SI);
02429 
02430       if (DL->isBigEndian())
02431         Shift -= ElementOffset;
02432       else
02433         Shift += ElementOffset;
02434     }
02435   }
02436 
02437   DeadInsts.push_back(SI);
02438 }
02439 
02440 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
02441 /// an integer.  Load the individual pieces to form the aggregate value.
02442 void
02443 SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
02444                                    SmallVectorImpl<AllocaInst *> &NewElts) {
02445   // Extract each element out of the NewElts according to its structure offset
02446   // and form the result value.
02447   Type *AllocaEltTy = AI->getAllocatedType();
02448   uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
02449 
02450   DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
02451                << '\n');
02452 
02453   // There are two forms here: AI could be an array or struct.  Both cases
02454   // have different ways to compute the element offset.
02455   const StructLayout *Layout = nullptr;
02456   uint64_t ArrayEltBitOffset = 0;
02457   if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
02458     Layout = DL->getStructLayout(EltSTy);
02459   } else {
02460     Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
02461     ArrayEltBitOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
02462   }
02463 
02464   Value *ResultVal =
02465     Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
02466 
02467   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02468     // Load the value from the alloca.  If the NewElt is an aggregate, cast
02469     // the pointer to an integer of the same size before doing the load.
02470     Value *SrcField = NewElts[i];
02471     Type *FieldTy =
02472       cast<PointerType>(SrcField->getType())->getElementType();
02473     uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
02474 
02475     // Ignore zero sized fields like {}, they obviously contain no data.
02476     if (FieldSizeBits == 0) continue;
02477 
02478     IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
02479                                                      FieldSizeBits);
02480     if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
02481         !FieldTy->isVectorTy())
02482       SrcField = new BitCastInst(SrcField,
02483                                  PointerType::getUnqual(FieldIntTy),
02484                                  "", LI);
02485     SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
02486 
02487     // If SrcField is a fp or vector of the right size but that isn't an
02488     // integer type, bitcast to an integer so we can shift it.
02489     if (SrcField->getType() != FieldIntTy)
02490       SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
02491 
02492     // Zero extend the field to be the same size as the final alloca so that
02493     // we can shift and insert it.
02494     if (SrcField->getType() != ResultVal->getType())
02495       SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
02496 
02497     // Determine the number of bits to shift SrcField.
02498     uint64_t Shift;
02499     if (Layout) // Struct case.
02500       Shift = Layout->getElementOffsetInBits(i);
02501     else  // Array case.
02502       Shift = i*ArrayEltBitOffset;
02503 
02504     if (DL->isBigEndian())
02505       Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
02506 
02507     if (Shift) {
02508       Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
02509       SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
02510     }
02511 
02512     // Don't create an 'or x, 0' on the first iteration.
02513     if (!isa<Constant>(ResultVal) ||
02514         !cast<Constant>(ResultVal)->isNullValue())
02515       ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
02516     else
02517       ResultVal = SrcField;
02518   }
02519 
02520   // Handle tail padding by truncating the result
02521   if (DL->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
02522     ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
02523 
02524   LI->replaceAllUsesWith(ResultVal);
02525   DeadInsts.push_back(LI);
02526 }
02527 
02528 /// HasPadding - Return true if the specified type has any structure or
02529 /// alignment padding in between the elements that would be split apart
02530 /// by SROA; return false otherwise.
02531 static bool HasPadding(Type *Ty, const DataLayout &DL) {
02532   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
02533     Ty = ATy->getElementType();
02534     return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
02535   }
02536 
02537   // SROA currently handles only Arrays and Structs.
02538   StructType *STy = cast<StructType>(Ty);
02539   const StructLayout *SL = DL.getStructLayout(STy);
02540   unsigned PrevFieldBitOffset = 0;
02541   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
02542     unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
02543 
02544     // Check to see if there is any padding between this element and the
02545     // previous one.
02546     if (i) {
02547       unsigned PrevFieldEnd =
02548         PrevFieldBitOffset+DL.getTypeSizeInBits(STy->getElementType(i-1));
02549       if (PrevFieldEnd < FieldBitOffset)
02550         return true;
02551     }
02552     PrevFieldBitOffset = FieldBitOffset;
02553   }
02554   // Check for tail padding.
02555   if (unsigned EltCount = STy->getNumElements()) {
02556     unsigned PrevFieldEnd = PrevFieldBitOffset +
02557       DL.getTypeSizeInBits(STy->getElementType(EltCount-1));
02558     if (PrevFieldEnd < SL->getSizeInBits())
02559       return true;
02560   }
02561   return false;
02562 }
02563 
02564 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
02565 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
02566 /// or 1 if safe after canonicalization has been performed.
02567 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
02568   // Loop over the use list of the alloca.  We can only transform it if all of
02569   // the users are safe to transform.
02570   AllocaInfo Info(AI);
02571 
02572   isSafeForScalarRepl(AI, 0, Info);
02573   if (Info.isUnsafe) {
02574     DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
02575     return false;
02576   }
02577 
02578   // Okay, we know all the users are promotable.  If the aggregate is a memcpy
02579   // source and destination, we have to be careful.  In particular, the memcpy
02580   // could be moving around elements that live in structure padding of the LLVM
02581   // types, but may actually be used.  In these cases, we refuse to promote the
02582   // struct.
02583   if (Info.isMemCpySrc && Info.isMemCpyDst &&
02584       HasPadding(AI->getAllocatedType(), *DL))
02585     return false;
02586 
02587   // If the alloca never has an access to just *part* of it, but is accessed
02588   // via loads and stores, then we should use ConvertToScalarInfo to promote
02589   // the alloca instead of promoting each piece at a time and inserting fission
02590   // and fusion code.
02591   if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
02592     // If the struct/array just has one element, use basic SRoA.
02593     if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
02594       if (ST->getNumElements() > 1) return false;
02595     } else {
02596       if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
02597         return false;
02598     }
02599   }
02600 
02601   return true;
02602 }