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