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 (auto *L = LocalAsMetadata::getIfExists(AI)) {
01072       if (auto *DebugNode = MetadataAsValue::getIfExists(AI->getContext(), L)) {
01073         for (User *U : DebugNode->users())
01074           if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
01075             DDIs.push_back(DDI);
01076           else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
01077             DVIs.push_back(DVI);
01078       }
01079     }
01080 
01081     LoadAndStorePromoter::run(Insts);
01082     AI->eraseFromParent();
01083     for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
01084            E = DDIs.end(); I != E; ++I) {
01085       DbgDeclareInst *DDI = *I;
01086       DDI->eraseFromParent();
01087     }
01088     for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
01089            E = DVIs.end(); I != E; ++I) {
01090       DbgValueInst *DVI = *I;
01091       DVI->eraseFromParent();
01092     }
01093   }
01094 
01095   bool isInstInList(Instruction *I,
01096                     const SmallVectorImpl<Instruction*> &Insts) const override {
01097     if (LoadInst *LI = dyn_cast<LoadInst>(I))
01098       return LI->getOperand(0) == AI;
01099     return cast<StoreInst>(I)->getPointerOperand() == AI;
01100   }
01101 
01102   void updateDebugInfo(Instruction *Inst) const override {
01103     for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
01104            E = DDIs.end(); I != E; ++I) {
01105       DbgDeclareInst *DDI = *I;
01106       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
01107         ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
01108       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
01109         ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
01110     }
01111     for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
01112            E = DVIs.end(); I != E; ++I) {
01113       DbgValueInst *DVI = *I;
01114       Value *Arg = nullptr;
01115       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
01116         // If an argument is zero extended then use argument directly. The ZExt
01117         // may be zapped by an optimization pass in future.
01118         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
01119           Arg = dyn_cast<Argument>(ZExt->getOperand(0));
01120         if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
01121           Arg = dyn_cast<Argument>(SExt->getOperand(0));
01122         if (!Arg)
01123           Arg = SI->getOperand(0);
01124       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
01125         Arg = LI->getOperand(0);
01126       } else {
01127         continue;
01128       }
01129       Instruction *DbgVal = DIB->insertDbgValueIntrinsic(
01130           Arg, 0, DIVariable(DVI->getVariable()),
01131           DIExpression(DVI->getExpression()), Inst);
01132       DbgVal->setDebugLoc(DVI->getDebugLoc());
01133     }
01134   }
01135 };
01136 } // end anon namespace
01137 
01138 /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
01139 /// subsequently loaded can be rewritten to load both input pointers and then
01140 /// select between the result, allowing the load of the alloca to be promoted.
01141 /// From this:
01142 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
01143 ///   %V = load i32* %P2
01144 /// to:
01145 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01146 ///   %V2 = load i32* %Other
01147 ///   %V = select i1 %cond, i32 %V1, i32 %V2
01148 ///
01149 /// We can do this to a select if its only uses are loads and if the operand to
01150 /// the select can be loaded unconditionally.
01151 static bool isSafeSelectToSpeculate(SelectInst *SI, const DataLayout *DL) {
01152   bool TDerefable = SI->getTrueValue()->isDereferenceablePointer(DL);
01153   bool FDerefable = SI->getFalseValue()->isDereferenceablePointer(DL);
01154 
01155   for (User *U : SI->users()) {
01156     LoadInst *LI = dyn_cast<LoadInst>(U);
01157     if (!LI || !LI->isSimple()) return false;
01158 
01159     // Both operands to the select need to be dereferencable, either absolutely
01160     // (e.g. allocas) or at this point because we can see other accesses to it.
01161     if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
01162                                                     LI->getAlignment(), DL))
01163       return false;
01164     if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
01165                                                     LI->getAlignment(), DL))
01166       return false;
01167   }
01168 
01169   return true;
01170 }
01171 
01172 /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
01173 /// subsequently loaded can be rewritten to load both input pointers in the pred
01174 /// blocks and then PHI the results, allowing the load of the alloca to be
01175 /// promoted.
01176 /// From this:
01177 ///   %P2 = phi [i32* %Alloca, i32* %Other]
01178 ///   %V = load i32* %P2
01179 /// to:
01180 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01181 ///   ...
01182 ///   %V2 = load i32* %Other
01183 ///   ...
01184 ///   %V = phi [i32 %V1, i32 %V2]
01185 ///
01186 /// We can do this to a select if its only uses are loads and if the operand to
01187 /// the select can be loaded unconditionally.
01188 static bool isSafePHIToSpeculate(PHINode *PN, const DataLayout *DL) {
01189   // For now, we can only do this promotion if the load is in the same block as
01190   // the PHI, and if there are no stores between the phi and load.
01191   // TODO: Allow recursive phi users.
01192   // TODO: Allow stores.
01193   BasicBlock *BB = PN->getParent();
01194   unsigned MaxAlign = 0;
01195   for (User *U : PN->users()) {
01196     LoadInst *LI = dyn_cast<LoadInst>(U);
01197     if (!LI || !LI->isSimple()) return false;
01198 
01199     // For now we only allow loads in the same block as the PHI.  This is a
01200     // common case that happens when instcombine merges two loads through a PHI.
01201     if (LI->getParent() != BB) return false;
01202 
01203     // Ensure that there are no instructions between the PHI and the load that
01204     // could store.
01205     for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
01206       if (BBI->mayWriteToMemory())
01207         return false;
01208 
01209     MaxAlign = std::max(MaxAlign, LI->getAlignment());
01210   }
01211 
01212   // Okay, we know that we have one or more loads in the same block as the PHI.
01213   // We can transform this if it is safe to push the loads into the predecessor
01214   // blocks.  The only thing to watch out for is that we can't put a possibly
01215   // trapping load in the predecessor if it is a critical edge.
01216   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01217     BasicBlock *Pred = PN->getIncomingBlock(i);
01218     Value *InVal = PN->getIncomingValue(i);
01219 
01220     // If the terminator of the predecessor has side-effects (an invoke),
01221     // there is no safe place to put a load in the predecessor.
01222     if (Pred->getTerminator()->mayHaveSideEffects())
01223       return false;
01224 
01225     // If the value is produced by the terminator of the predecessor
01226     // (an invoke), there is no valid place to put a load in the predecessor.
01227     if (Pred->getTerminator() == InVal)
01228       return false;
01229 
01230     // If the predecessor has a single successor, then the edge isn't critical.
01231     if (Pred->getTerminator()->getNumSuccessors() == 1)
01232       continue;
01233 
01234     // If this pointer is always safe to load, or if we can prove that there is
01235     // already a load in the block, then we can move the load to the pred block.
01236     if (InVal->isDereferenceablePointer(DL) ||
01237         isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, DL))
01238       continue;
01239 
01240     return false;
01241   }
01242 
01243   return true;
01244 }
01245 
01246 
01247 /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
01248 /// direct (non-volatile) loads and stores to it.  If the alloca is close but
01249 /// not quite there, this will transform the code to allow promotion.  As such,
01250 /// it is a non-pure predicate.
01251 static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout *DL) {
01252   SetVector<Instruction*, SmallVector<Instruction*, 4>,
01253             SmallPtrSet<Instruction*, 4> > InstsToRewrite;
01254   for (User *U : AI->users()) {
01255     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
01256       if (!LI->isSimple())
01257         return false;
01258       continue;
01259     }
01260 
01261     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
01262       if (SI->getOperand(0) == AI || !SI->isSimple())
01263         return false;   // Don't allow a store OF the AI, only INTO the AI.
01264       continue;
01265     }
01266 
01267     if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
01268       // If the condition being selected on is a constant, fold the select, yes
01269       // this does (rarely) happen early on.
01270       if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
01271         Value *Result = SI->getOperand(1+CI->isZero());
01272         SI->replaceAllUsesWith(Result);
01273         SI->eraseFromParent();
01274 
01275         // This is very rare and we just scrambled the use list of AI, start
01276         // over completely.
01277         return tryToMakeAllocaBePromotable(AI, DL);
01278       }
01279 
01280       // If it is safe to turn "load (select c, AI, ptr)" into a select of two
01281       // loads, then we can transform this by rewriting the select.
01282       if (!isSafeSelectToSpeculate(SI, DL))
01283         return false;
01284 
01285       InstsToRewrite.insert(SI);
01286       continue;
01287     }
01288 
01289     if (PHINode *PN = dyn_cast<PHINode>(U)) {
01290       if (PN->use_empty()) {  // Dead PHIs can be stripped.
01291         InstsToRewrite.insert(PN);
01292         continue;
01293       }
01294 
01295       // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
01296       // in the pred blocks, then we can transform this by rewriting the PHI.
01297       if (!isSafePHIToSpeculate(PN, DL))
01298         return false;
01299 
01300       InstsToRewrite.insert(PN);
01301       continue;
01302     }
01303 
01304     if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
01305       if (onlyUsedByLifetimeMarkers(BCI)) {
01306         InstsToRewrite.insert(BCI);
01307         continue;
01308       }
01309     }
01310 
01311     return false;
01312   }
01313 
01314   // If there are no instructions to rewrite, then all uses are load/stores and
01315   // we're done!
01316   if (InstsToRewrite.empty())
01317     return true;
01318 
01319   // If we have instructions that need to be rewritten for this to be promotable
01320   // take care of it now.
01321   for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
01322     if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
01323       // This could only be a bitcast used by nothing but lifetime intrinsics.
01324       for (BitCastInst::user_iterator I = BCI->user_begin(), E = BCI->user_end();
01325            I != E;)
01326         cast<Instruction>(*I++)->eraseFromParent();
01327       BCI->eraseFromParent();
01328       continue;
01329     }
01330 
01331     if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
01332       // Selects in InstsToRewrite only have load uses.  Rewrite each as two
01333       // loads with a new select.
01334       while (!SI->use_empty()) {
01335         LoadInst *LI = cast<LoadInst>(SI->user_back());
01336 
01337         IRBuilder<> Builder(LI);
01338         LoadInst *TrueLoad =
01339           Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
01340         LoadInst *FalseLoad =
01341           Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
01342 
01343         // Transfer alignment and AA info if present.
01344         TrueLoad->setAlignment(LI->getAlignment());
01345         FalseLoad->setAlignment(LI->getAlignment());
01346 
01347         AAMDNodes Tags;
01348         LI->getAAMetadata(Tags);
01349         if (Tags) {
01350           TrueLoad->setAAMetadata(Tags);
01351           FalseLoad->setAAMetadata(Tags);
01352         }
01353 
01354         Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
01355         V->takeName(LI);
01356         LI->replaceAllUsesWith(V);
01357         LI->eraseFromParent();
01358       }
01359 
01360       // Now that all the loads are gone, the select is gone too.
01361       SI->eraseFromParent();
01362       continue;
01363     }
01364 
01365     // Otherwise, we have a PHI node which allows us to push the loads into the
01366     // predecessors.
01367     PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
01368     if (PN->use_empty()) {
01369       PN->eraseFromParent();
01370       continue;
01371     }
01372 
01373     Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
01374     PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
01375                                      PN->getName()+".ld", PN);
01376 
01377     // Get the AA tags and alignment to use from one of the loads.  It doesn't
01378     // matter which one we get and if any differ, it doesn't matter.
01379     LoadInst *SomeLoad = cast<LoadInst>(PN->user_back());
01380 
01381     AAMDNodes AATags;
01382     SomeLoad->getAAMetadata(AATags);
01383     unsigned Align = SomeLoad->getAlignment();
01384 
01385     // Rewrite all loads of the PN to use the new PHI.
01386     while (!PN->use_empty()) {
01387       LoadInst *LI = cast<LoadInst>(PN->user_back());
01388       LI->replaceAllUsesWith(NewPN);
01389       LI->eraseFromParent();
01390     }
01391 
01392     // Inject loads into all of the pred blocks.  Keep track of which blocks we
01393     // insert them into in case we have multiple edges from the same block.
01394     DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
01395 
01396     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01397       BasicBlock *Pred = PN->getIncomingBlock(i);
01398       LoadInst *&Load = InsertedLoads[Pred];
01399       if (!Load) {
01400         Load = new LoadInst(PN->getIncomingValue(i),
01401                             PN->getName() + "." + Pred->getName(),
01402                             Pred->getTerminator());
01403         Load->setAlignment(Align);
01404         if (AATags) Load->setAAMetadata(AATags);
01405       }
01406 
01407       NewPN->addIncoming(Load, Pred);
01408     }
01409 
01410     PN->eraseFromParent();
01411   }
01412 
01413   ++NumAdjusted;
01414   return true;
01415 }
01416 
01417 bool SROA::performPromotion(Function &F) {
01418   std::vector<AllocaInst*> Allocas;
01419   DominatorTree *DT = nullptr;
01420   if (HasDomTree)
01421     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
01422   AssumptionTracker *AT = &getAnalysis<AssumptionTracker>();
01423 
01424   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
01425   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
01426   bool Changed = false;
01427   SmallVector<Instruction*, 64> Insts;
01428   while (1) {
01429     Allocas.clear();
01430 
01431     // Find allocas that are safe to promote, by looking at all instructions in
01432     // the entry node
01433     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
01434       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
01435         if (tryToMakeAllocaBePromotable(AI, DL))
01436           Allocas.push_back(AI);
01437 
01438     if (Allocas.empty()) break;
01439 
01440     if (HasDomTree)
01441       PromoteMemToReg(Allocas, *DT, nullptr, AT);
01442     else {
01443       SSAUpdater SSA;
01444       for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
01445         AllocaInst *AI = Allocas[i];
01446 
01447         // Build list of instructions to promote.
01448         for (User *U : AI->users())
01449           Insts.push_back(cast<Instruction>(U));
01450         AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
01451         Insts.clear();
01452       }
01453     }
01454     NumPromoted += Allocas.size();
01455     Changed = true;
01456   }
01457 
01458   return Changed;
01459 }
01460 
01461 
01462 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
01463 /// SROA.  It must be a struct or array type with a small number of elements.
01464 bool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) {
01465   Type *T = AI->getAllocatedType();
01466   // Do not promote any struct that has too many members.
01467   if (StructType *ST = dyn_cast<StructType>(T))
01468     return ST->getNumElements() <= StructMemberThreshold;
01469   // Do not promote any array that has too many elements.
01470   if (ArrayType *AT = dyn_cast<ArrayType>(T))
01471     return AT->getNumElements() <= ArrayElementThreshold;
01472   return false;
01473 }
01474 
01475 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
01476 // which runs on all of the alloca instructions in the entry block, removing
01477 // them if they are only used by getelementptr instructions.
01478 //
01479 bool SROA::performScalarRepl(Function &F) {
01480   std::vector<AllocaInst*> WorkList;
01481 
01482   // Scan the entry basic block, adding allocas to the worklist.
01483   BasicBlock &BB = F.getEntryBlock();
01484   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
01485     if (AllocaInst *A = dyn_cast<AllocaInst>(I))
01486       WorkList.push_back(A);
01487 
01488   // Process the worklist
01489   bool Changed = false;
01490   while (!WorkList.empty()) {
01491     AllocaInst *AI = WorkList.back();
01492     WorkList.pop_back();
01493 
01494     // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
01495     // with unused elements.
01496     if (AI->use_empty()) {
01497       AI->eraseFromParent();
01498       Changed = true;
01499       continue;
01500     }
01501 
01502     // If this alloca is impossible for us to promote, reject it early.
01503     if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
01504       continue;
01505 
01506     // Check to see if we can perform the core SROA transformation.  We cannot
01507     // transform the allocation instruction if it is an array allocation
01508     // (allocations OF arrays are ok though), and an allocation of a scalar
01509     // value cannot be decomposed at all.
01510     uint64_t AllocaSize = DL->getTypeAllocSize(AI->getAllocatedType());
01511 
01512     // Do not promote [0 x %struct].
01513     if (AllocaSize == 0) continue;
01514 
01515     // Do not promote any struct whose size is too big.
01516     if (AllocaSize > SRThreshold) continue;
01517 
01518     // If the alloca looks like a good candidate for scalar replacement, and if
01519     // all its users can be transformed, then split up the aggregate into its
01520     // separate elements.
01521     if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
01522       DoScalarReplacement(AI, WorkList);
01523       Changed = true;
01524       continue;
01525     }
01526 
01527     // If we can turn this aggregate value (potentially with casts) into a
01528     // simple scalar value that can be mem2reg'd into a register value.
01529     // IsNotTrivial tracks whether this is something that mem2reg could have
01530     // promoted itself.  If so, we don't want to transform it needlessly.  Note
01531     // that we can't just check based on the type: the alloca may be of an i32
01532     // but that has pointer arithmetic to set byte 3 of it or something.
01533     if (AllocaInst *NewAI = ConvertToScalarInfo(
01534               (unsigned)AllocaSize, *DL, ScalarLoadThreshold).TryConvert(AI)) {
01535       NewAI->takeName(AI);
01536       AI->eraseFromParent();
01537       ++NumConverted;
01538       Changed = true;
01539       continue;
01540     }
01541 
01542     // Otherwise, couldn't process this alloca.
01543   }
01544 
01545   return Changed;
01546 }
01547 
01548 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
01549 /// predicate, do SROA now.
01550 void SROA::DoScalarReplacement(AllocaInst *AI,
01551                                std::vector<AllocaInst*> &WorkList) {
01552   DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
01553   SmallVector<AllocaInst*, 32> ElementAllocas;
01554   if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
01555     ElementAllocas.reserve(ST->getNumContainedTypes());
01556     for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
01557       AllocaInst *NA = new AllocaInst(ST->getContainedType(i), nullptr,
01558                                       AI->getAlignment(),
01559                                       AI->getName() + "." + Twine(i), AI);
01560       ElementAllocas.push_back(NA);
01561       WorkList.push_back(NA);  // Add to worklist for recursive processing
01562     }
01563   } else {
01564     ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
01565     ElementAllocas.reserve(AT->getNumElements());
01566     Type *ElTy = AT->getElementType();
01567     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
01568       AllocaInst *NA = new AllocaInst(ElTy, nullptr, AI->getAlignment(),
01569                                       AI->getName() + "." + Twine(i), AI);
01570       ElementAllocas.push_back(NA);
01571       WorkList.push_back(NA);  // Add to worklist for recursive processing
01572     }
01573   }
01574 
01575   // Now that we have created the new alloca instructions, rewrite all the
01576   // uses of the old alloca.
01577   RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
01578 
01579   // Now erase any instructions that were made dead while rewriting the alloca.
01580   DeleteDeadInstructions();
01581   AI->eraseFromParent();
01582 
01583   ++NumReplaced;
01584 }
01585 
01586 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
01587 /// recursively including all their operands that become trivially dead.
01588 void SROA::DeleteDeadInstructions() {
01589   while (!DeadInsts.empty()) {
01590     Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
01591 
01592     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
01593       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
01594         // Zero out the operand and see if it becomes trivially dead.
01595         // (But, don't add allocas to the dead instruction list -- they are
01596         // already on the worklist and will be deleted separately.)
01597         *OI = nullptr;
01598         if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
01599           DeadInsts.push_back(U);
01600       }
01601 
01602     I->eraseFromParent();
01603   }
01604 }
01605 
01606 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
01607 /// performing scalar replacement of alloca AI.  The results are flagged in
01608 /// the Info parameter.  Offset indicates the position within AI that is
01609 /// referenced by this instruction.
01610 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
01611                                AllocaInfo &Info) {
01612   for (Use &U : I->uses()) {
01613     Instruction *User = cast<Instruction>(U.getUser());
01614 
01615     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
01616       isSafeForScalarRepl(BC, Offset, Info);
01617     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
01618       uint64_t GEPOffset = Offset;
01619       isSafeGEP(GEPI, GEPOffset, Info);
01620       if (!Info.isUnsafe)
01621         isSafeForScalarRepl(GEPI, GEPOffset, Info);
01622     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
01623       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
01624       if (!Length || Length->isNegative())
01625         return MarkUnsafe(Info, User);
01626 
01627       isSafeMemAccess(Offset, Length->getZExtValue(), nullptr,
01628                       U.getOperandNo() == 0, Info, MI,
01629                       true /*AllowWholeAccess*/);
01630     } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
01631       if (!LI->isSimple())
01632         return MarkUnsafe(Info, User);
01633       Type *LIType = LI->getType();
01634       isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
01635                       LIType, false, Info, LI, true /*AllowWholeAccess*/);
01636       Info.hasALoadOrStore = true;
01637 
01638     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
01639       // Store is ok if storing INTO the pointer, not storing the pointer
01640       if (!SI->isSimple() || SI->getOperand(0) == I)
01641         return MarkUnsafe(Info, User);
01642 
01643       Type *SIType = SI->getOperand(0)->getType();
01644       isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
01645                       SIType, true, Info, SI, true /*AllowWholeAccess*/);
01646       Info.hasALoadOrStore = true;
01647     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
01648       if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
01649           II->getIntrinsicID() != Intrinsic::lifetime_end)
01650         return MarkUnsafe(Info, User);
01651     } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
01652       isSafePHISelectUseForScalarRepl(User, Offset, Info);
01653     } else {
01654       return MarkUnsafe(Info, User);
01655     }
01656     if (Info.isUnsafe) return;
01657   }
01658 }
01659 
01660 
01661 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
01662 /// derived from the alloca, we can often still split the alloca into elements.
01663 /// This is useful if we have a large alloca where one element is phi'd
01664 /// together somewhere: we can SRoA and promote all the other elements even if
01665 /// we end up not being able to promote this one.
01666 ///
01667 /// All we require is that the uses of the PHI do not index into other parts of
01668 /// the alloca.  The most important use case for this is single load and stores
01669 /// that are PHI'd together, which can happen due to code sinking.
01670 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
01671                                            AllocaInfo &Info) {
01672   // If we've already checked this PHI, don't do it again.
01673   if (PHINode *PN = dyn_cast<PHINode>(I))
01674     if (!Info.CheckedPHIs.insert(PN).second)
01675       return;
01676 
01677   for (User *U : I->users()) {
01678     Instruction *UI = cast<Instruction>(U);
01679 
01680     if (BitCastInst *BC = dyn_cast<BitCastInst>(UI)) {
01681       isSafePHISelectUseForScalarRepl(BC, Offset, Info);
01682     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
01683       // Only allow "bitcast" GEPs for simplicity.  We could generalize this,
01684       // but would have to prove that we're staying inside of an element being
01685       // promoted.
01686       if (!GEPI->hasAllZeroIndices())
01687         return MarkUnsafe(Info, UI);
01688       isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
01689     } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
01690       if (!LI->isSimple())
01691         return MarkUnsafe(Info, UI);
01692       Type *LIType = LI->getType();
01693       isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
01694                       LIType, false, Info, LI, false /*AllowWholeAccess*/);
01695       Info.hasALoadOrStore = true;
01696 
01697     } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
01698       // Store is ok if storing INTO the pointer, not storing the pointer
01699       if (!SI->isSimple() || SI->getOperand(0) == I)
01700         return MarkUnsafe(Info, UI);
01701 
01702       Type *SIType = SI->getOperand(0)->getType();
01703       isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
01704                       SIType, true, Info, SI, false /*AllowWholeAccess*/);
01705       Info.hasALoadOrStore = true;
01706     } else if (isa<PHINode>(UI) || isa<SelectInst>(UI)) {
01707       isSafePHISelectUseForScalarRepl(UI, Offset, Info);
01708     } else {
01709       return MarkUnsafe(Info, UI);
01710     }
01711     if (Info.isUnsafe) return;
01712   }
01713 }
01714 
01715 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
01716 /// replacement.  It is safe when all the indices are constant, in-bounds
01717 /// references, and when the resulting offset corresponds to an element within
01718 /// the alloca type.  The results are flagged in the Info parameter.  Upon
01719 /// return, Offset is adjusted as specified by the GEP indices.
01720 void SROA::isSafeGEP(GetElementPtrInst *GEPI,
01721                      uint64_t &Offset, AllocaInfo &Info) {
01722   gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
01723   if (GEPIt == E)
01724     return;
01725   bool NonConstant = false;
01726   unsigned NonConstantIdxSize = 0;
01727 
01728   // Walk through the GEP type indices, checking the types that this indexes
01729   // into.
01730   for (; GEPIt != E; ++GEPIt) {
01731     // Ignore struct elements, no extra checking needed for these.
01732     if ((*GEPIt)->isStructTy())
01733       continue;
01734 
01735     ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
01736     if (!IdxVal)
01737       return MarkUnsafe(Info, GEPI);
01738   }
01739 
01740   // Compute the offset due to this GEP and check if the alloca has a
01741   // component element at that offset.
01742   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
01743   // If this GEP is non-constant then the last operand must have been a
01744   // dynamic index into a vector.  Pop this now as it has no impact on the
01745   // constant part of the offset.
01746   if (NonConstant)
01747     Indices.pop_back();
01748   Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
01749   if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset,
01750                         NonConstantIdxSize))
01751     MarkUnsafe(Info, GEPI);
01752 }
01753 
01754 /// isHomogeneousAggregate - Check if type T is a struct or array containing
01755 /// elements of the same type (which is always true for arrays).  If so,
01756 /// return true with NumElts and EltTy set to the number of elements and the
01757 /// element type, respectively.
01758 static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
01759                                    Type *&EltTy) {
01760   if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
01761     NumElts = AT->getNumElements();
01762     EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
01763     return true;
01764   }
01765   if (StructType *ST = dyn_cast<StructType>(T)) {
01766     NumElts = ST->getNumContainedTypes();
01767     EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
01768     for (unsigned n = 1; n < NumElts; ++n) {
01769       if (ST->getContainedType(n) != EltTy)
01770         return false;
01771     }
01772     return true;
01773   }
01774   return false;
01775 }
01776 
01777 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
01778 /// "homogeneous" aggregates with the same element type and number of elements.
01779 static bool isCompatibleAggregate(Type *T1, Type *T2) {
01780   if (T1 == T2)
01781     return true;
01782 
01783   unsigned NumElts1, NumElts2;
01784   Type *EltTy1, *EltTy2;
01785   if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
01786       isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
01787       NumElts1 == NumElts2 &&
01788       EltTy1 == EltTy2)
01789     return true;
01790 
01791   return false;
01792 }
01793 
01794 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
01795 /// alloca or has an offset and size that corresponds to a component element
01796 /// within it.  The offset checked here may have been formed from a GEP with a
01797 /// pointer bitcasted to a different type.
01798 ///
01799 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
01800 /// unit.  If false, it only allows accesses known to be in a single element.
01801 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
01802                            Type *MemOpType, bool isStore,
01803                            AllocaInfo &Info, Instruction *TheAccess,
01804                            bool AllowWholeAccess) {
01805   // Check if this is a load/store of the entire alloca.
01806   if (Offset == 0 && AllowWholeAccess &&
01807       MemSize == DL->getTypeAllocSize(Info.AI->getAllocatedType())) {
01808     // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
01809     // loads/stores (which are essentially the same as the MemIntrinsics with
01810     // regard to copying padding between elements).  But, if an alloca is
01811     // flagged as both a source and destination of such operations, we'll need
01812     // to check later for padding between elements.
01813     if (!MemOpType || MemOpType->isIntegerTy()) {
01814       if (isStore)
01815         Info.isMemCpyDst = true;
01816       else
01817         Info.isMemCpySrc = true;
01818       return;
01819     }
01820     // This is also safe for references using a type that is compatible with
01821     // the type of the alloca, so that loads/stores can be rewritten using
01822     // insertvalue/extractvalue.
01823     if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
01824       Info.hasSubelementAccess = true;
01825       return;
01826     }
01827   }
01828   // Check if the offset/size correspond to a component within the alloca type.
01829   Type *T = Info.AI->getAllocatedType();
01830   if (TypeHasComponent(T, Offset, MemSize)) {
01831     Info.hasSubelementAccess = true;
01832     return;
01833   }
01834 
01835   return MarkUnsafe(Info, TheAccess);
01836 }
01837 
01838 /// TypeHasComponent - Return true if T has a component type with the
01839 /// specified offset and size.  If Size is zero, do not check the size.
01840 bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
01841   Type *EltTy;
01842   uint64_t EltSize;
01843   if (StructType *ST = dyn_cast<StructType>(T)) {
01844     const StructLayout *Layout = DL->getStructLayout(ST);
01845     unsigned EltIdx = Layout->getElementContainingOffset(Offset);
01846     EltTy = ST->getContainedType(EltIdx);
01847     EltSize = DL->getTypeAllocSize(EltTy);
01848     Offset -= Layout->getElementOffset(EltIdx);
01849   } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
01850     EltTy = AT->getElementType();
01851     EltSize = DL->getTypeAllocSize(EltTy);
01852     if (Offset >= AT->getNumElements() * EltSize)
01853       return false;
01854     Offset %= EltSize;
01855   } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
01856     EltTy = VT->getElementType();
01857     EltSize = DL->getTypeAllocSize(EltTy);
01858     if (Offset >= VT->getNumElements() * EltSize)
01859       return false;
01860     Offset %= EltSize;
01861   } else {
01862     return false;
01863   }
01864   if (Offset == 0 && (Size == 0 || EltSize == Size))
01865     return true;
01866   // Check if the component spans multiple elements.
01867   if (Offset + Size > EltSize)
01868     return false;
01869   return TypeHasComponent(EltTy, Offset, Size);
01870 }
01871 
01872 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
01873 /// the instruction I, which references it, to use the separate elements.
01874 /// Offset indicates the position within AI that is referenced by this
01875 /// instruction.
01876 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
01877                                 SmallVectorImpl<AllocaInst *> &NewElts) {
01878   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
01879     Use &TheUse = *UI++;
01880     Instruction *User = cast<Instruction>(TheUse.getUser());
01881 
01882     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
01883       RewriteBitCast(BC, AI, Offset, NewElts);
01884       continue;
01885     }
01886 
01887     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
01888       RewriteGEP(GEPI, AI, Offset, NewElts);
01889       continue;
01890     }
01891 
01892     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
01893       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
01894       uint64_t MemSize = Length->getZExtValue();
01895       if (Offset == 0 &&
01896           MemSize == DL->getTypeAllocSize(AI->getAllocatedType()))
01897         RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
01898       // Otherwise the intrinsic can only touch a single element and the
01899       // address operand will be updated, so nothing else needs to be done.
01900       continue;
01901     }
01902 
01903     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
01904       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
01905           II->getIntrinsicID() == Intrinsic::lifetime_end) {
01906         RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
01907       }
01908       continue;
01909     }
01910 
01911     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
01912       Type *LIType = LI->getType();
01913 
01914       if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
01915         // Replace:
01916         //   %res = load { i32, i32 }* %alloc
01917         // with:
01918         //   %load.0 = load i32* %alloc.0
01919         //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
01920         //   %load.1 = load i32* %alloc.1
01921         //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
01922         // (Also works for arrays instead of structs)
01923         Value *Insert = UndefValue::get(LIType);
01924         IRBuilder<> Builder(LI);
01925         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
01926           Value *Load = Builder.CreateLoad(NewElts[i], "load");
01927           Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
01928         }
01929         LI->replaceAllUsesWith(Insert);
01930         DeadInsts.push_back(LI);
01931       } else if (LIType->isIntegerTy() &&
01932                  DL->getTypeAllocSize(LIType) ==
01933                  DL->getTypeAllocSize(AI->getAllocatedType())) {
01934         // If this is a load of the entire alloca to an integer, rewrite it.
01935         RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
01936       }
01937       continue;
01938     }
01939 
01940     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
01941       Value *Val = SI->getOperand(0);
01942       Type *SIType = Val->getType();
01943       if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
01944         // Replace:
01945         //   store { i32, i32 } %val, { i32, i32 }* %alloc
01946         // with:
01947         //   %val.0 = extractvalue { i32, i32 } %val, 0
01948         //   store i32 %val.0, i32* %alloc.0
01949         //   %val.1 = extractvalue { i32, i32 } %val, 1
01950         //   store i32 %val.1, i32* %alloc.1
01951         // (Also works for arrays instead of structs)
01952         IRBuilder<> Builder(SI);
01953         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
01954           Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
01955           Builder.CreateStore(Extract, NewElts[i]);
01956         }
01957         DeadInsts.push_back(SI);
01958       } else if (SIType->isIntegerTy() &&
01959                  DL->getTypeAllocSize(SIType) ==
01960                  DL->getTypeAllocSize(AI->getAllocatedType())) {
01961         // If this is a store of the entire alloca from an integer, rewrite it.
01962         RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
01963       }
01964       continue;
01965     }
01966 
01967     if (isa<SelectInst>(User) || isa<PHINode>(User)) {
01968       // If we have a PHI user of the alloca itself (as opposed to a GEP or
01969       // bitcast) we have to rewrite it.  GEP and bitcast uses will be RAUW'd to
01970       // the new pointer.
01971       if (!isa<AllocaInst>(I)) continue;
01972 
01973       assert(Offset == 0 && NewElts[0] &&
01974              "Direct alloca use should have a zero offset");
01975 
01976       // If we have a use of the alloca, we know the derived uses will be
01977       // utilizing just the first element of the scalarized result.  Insert a
01978       // bitcast of the first alloca before the user as required.
01979       AllocaInst *NewAI = NewElts[0];
01980       BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
01981       NewAI->moveBefore(BCI);
01982       TheUse = BCI;
01983       continue;
01984     }
01985   }
01986 }
01987 
01988 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
01989 /// and recursively continue updating all of its uses.
01990 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
01991                           SmallVectorImpl<AllocaInst *> &NewElts) {
01992   RewriteForScalarRepl(BC, AI, Offset, NewElts);
01993   if (BC->getOperand(0) != AI)
01994     return;
01995 
01996   // The bitcast references the original alloca.  Replace its uses with
01997   // references to the alloca containing offset zero (which is normally at
01998   // index zero, but might not be in cases involving structs with elements
01999   // of size zero).
02000   Type *T = AI->getAllocatedType();
02001   uint64_t EltOffset = 0;
02002   Type *IdxTy;
02003   uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
02004   Instruction *Val = NewElts[Idx];
02005   if (Val->getType() != BC->getDestTy()) {
02006     Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
02007     Val->takeName(BC);
02008   }
02009   BC->replaceAllUsesWith(Val);
02010   DeadInsts.push_back(BC);
02011 }
02012 
02013 /// FindElementAndOffset - Return the index of the element containing Offset
02014 /// within the specified type, which must be either a struct or an array.
02015 /// Sets T to the type of the element and Offset to the offset within that
02016 /// element.  IdxTy is set to the type of the index result to be used in a
02017 /// GEP instruction.
02018 uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
02019                                     Type *&IdxTy) {
02020   uint64_t Idx = 0;
02021   if (StructType *ST = dyn_cast<StructType>(T)) {
02022     const StructLayout *Layout = DL->getStructLayout(ST);
02023     Idx = Layout->getElementContainingOffset(Offset);
02024     T = ST->getContainedType(Idx);
02025     Offset -= Layout->getElementOffset(Idx);
02026     IdxTy = Type::getInt32Ty(T->getContext());
02027     return Idx;
02028   } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
02029     T = AT->getElementType();
02030     uint64_t EltSize = DL->getTypeAllocSize(T);
02031     Idx = Offset / EltSize;
02032     Offset -= Idx * EltSize;
02033     IdxTy = Type::getInt64Ty(T->getContext());
02034     return Idx;
02035   }
02036   VectorType *VT = cast<VectorType>(T);
02037   T = VT->getElementType();
02038   uint64_t EltSize = DL->getTypeAllocSize(T);
02039   Idx = Offset / EltSize;
02040   Offset -= Idx * EltSize;
02041   IdxTy = Type::getInt64Ty(T->getContext());
02042   return Idx;
02043 }
02044 
02045 /// RewriteGEP - Check if this GEP instruction moves the pointer across
02046 /// elements of the alloca that are being split apart, and if so, rewrite
02047 /// the GEP to be relative to the new element.
02048 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
02049                       SmallVectorImpl<AllocaInst *> &NewElts) {
02050   uint64_t OldOffset = Offset;
02051   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
02052   // If the GEP was dynamic then it must have been a dynamic vector lookup.
02053   // In this case, it must be the last GEP operand which is dynamic so keep that
02054   // aside until we've found the constant GEP offset then add it back in at the
02055   // end.
02056   Value* NonConstantIdx = nullptr;
02057   if (!GEPI->hasAllConstantIndices())
02058     NonConstantIdx = Indices.pop_back_val();
02059   Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
02060 
02061   RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
02062 
02063   Type *T = AI->getAllocatedType();
02064   Type *IdxTy;
02065   uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
02066   if (GEPI->getOperand(0) == AI)
02067     OldIdx = ~0ULL; // Force the GEP to be rewritten.
02068 
02069   T = AI->getAllocatedType();
02070   uint64_t EltOffset = Offset;
02071   uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
02072 
02073   // If this GEP does not move the pointer across elements of the alloca
02074   // being split, then it does not needs to be rewritten.
02075   if (Idx == OldIdx)
02076     return;
02077 
02078   Type *i32Ty = Type::getInt32Ty(AI->getContext());
02079   SmallVector<Value*, 8> NewArgs;
02080   NewArgs.push_back(Constant::getNullValue(i32Ty));
02081   while (EltOffset != 0) {
02082     uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
02083     NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
02084   }
02085   if (NonConstantIdx) {
02086     Type* GepTy = T;
02087     // This GEP has a dynamic index.  We need to add "i32 0" to index through
02088     // any structs or arrays in the original type until we get to the vector
02089     // to index.
02090     while (!isa<VectorType>(GepTy)) {
02091       NewArgs.push_back(Constant::getNullValue(i32Ty));
02092       GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
02093     }
02094     NewArgs.push_back(NonConstantIdx);
02095   }
02096   Instruction *Val = NewElts[Idx];
02097   if (NewArgs.size() > 1) {
02098     Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
02099     Val->takeName(GEPI);
02100   }
02101   if (Val->getType() != GEPI->getType())
02102     Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
02103   GEPI->replaceAllUsesWith(Val);
02104   DeadInsts.push_back(GEPI);
02105 }
02106 
02107 /// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
02108 /// to mark the lifetime of the scalarized memory.
02109 void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
02110                                     uint64_t Offset,
02111                                     SmallVectorImpl<AllocaInst *> &NewElts) {
02112   ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
02113   // Put matching lifetime markers on everything from Offset up to
02114   // Offset+OldSize.
02115   Type *AIType = AI->getAllocatedType();
02116   uint64_t NewOffset = Offset;
02117   Type *IdxTy;
02118   uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
02119 
02120   IRBuilder<> Builder(II);
02121   uint64_t Size = OldSize->getLimitedValue();
02122 
02123   if (NewOffset) {
02124     // Splice the first element and index 'NewOffset' bytes in.  SROA will
02125     // split the alloca again later.
02126     unsigned AS = AI->getType()->getAddressSpace();
02127     Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy(AS));
02128     V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
02129 
02130     IdxTy = NewElts[Idx]->getAllocatedType();
02131     uint64_t EltSize = DL->getTypeAllocSize(IdxTy) - NewOffset;
02132     if (EltSize > Size) {
02133       EltSize = Size;
02134       Size = 0;
02135     } else {
02136       Size -= EltSize;
02137     }
02138     if (II->getIntrinsicID() == Intrinsic::lifetime_start)
02139       Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
02140     else
02141       Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
02142     ++Idx;
02143   }
02144 
02145   for (; Idx != NewElts.size() && Size; ++Idx) {
02146     IdxTy = NewElts[Idx]->getAllocatedType();
02147     uint64_t EltSize = DL->getTypeAllocSize(IdxTy);
02148     if (EltSize > Size) {
02149       EltSize = Size;
02150       Size = 0;
02151     } else {
02152       Size -= EltSize;
02153     }
02154     if (II->getIntrinsicID() == Intrinsic::lifetime_start)
02155       Builder.CreateLifetimeStart(NewElts[Idx],
02156                                   Builder.getInt64(EltSize));
02157     else
02158       Builder.CreateLifetimeEnd(NewElts[Idx],
02159                                 Builder.getInt64(EltSize));
02160   }
02161   DeadInsts.push_back(II);
02162 }
02163 
02164 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
02165 /// Rewrite it to copy or set the elements of the scalarized memory.
02166 void
02167 SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
02168                                    AllocaInst *AI,
02169                                    SmallVectorImpl<AllocaInst *> &NewElts) {
02170   // If this is a memcpy/memmove, construct the other pointer as the
02171   // appropriate type.  The "Other" pointer is the pointer that goes to memory
02172   // that doesn't have anything to do with the alloca that we are promoting. For
02173   // memset, this Value* stays null.
02174   Value *OtherPtr = nullptr;
02175   unsigned MemAlignment = MI->getAlignment();
02176   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
02177     if (Inst == MTI->getRawDest())
02178       OtherPtr = MTI->getRawSource();
02179     else {
02180       assert(Inst == MTI->getRawSource());
02181       OtherPtr = MTI->getRawDest();
02182     }
02183   }
02184 
02185   // If there is an other pointer, we want to convert it to the same pointer
02186   // type as AI has, so we can GEP through it safely.
02187   if (OtherPtr) {
02188     unsigned AddrSpace =
02189       cast<PointerType>(OtherPtr->getType())->getAddressSpace();
02190 
02191     // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
02192     // optimization, but it's also required to detect the corner case where
02193     // both pointer operands are referencing the same memory, and where
02194     // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
02195     // function is only called for mem intrinsics that access the whole
02196     // aggregate, so non-zero GEPs are not an issue here.)
02197     OtherPtr = OtherPtr->stripPointerCasts();
02198 
02199     // Copying the alloca to itself is a no-op: just delete it.
02200     if (OtherPtr == AI || OtherPtr == NewElts[0]) {
02201       // This code will run twice for a no-op memcpy -- once for each operand.
02202       // Put only one reference to MI on the DeadInsts list.
02203       for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
02204              E = DeadInsts.end(); I != E; ++I)
02205         if (*I == MI) return;
02206       DeadInsts.push_back(MI);
02207       return;
02208     }
02209 
02210     // If the pointer is not the right type, insert a bitcast to the right
02211     // type.
02212     Type *NewTy =
02213       PointerType::get(AI->getType()->getElementType(), AddrSpace);
02214 
02215     if (OtherPtr->getType() != NewTy)
02216       OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
02217   }
02218 
02219   // Process each element of the aggregate.
02220   bool SROADest = MI->getRawDest() == Inst;
02221 
02222   Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
02223 
02224   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02225     // If this is a memcpy/memmove, emit a GEP of the other element address.
02226     Value *OtherElt = nullptr;
02227     unsigned OtherEltAlign = MemAlignment;
02228 
02229     if (OtherPtr) {
02230       Value *Idx[2] = { Zero,
02231                       ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
02232       OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
02233                                               OtherPtr->getName()+"."+Twine(i),
02234                                                    MI);
02235       uint64_t EltOffset;
02236       PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
02237       Type *OtherTy = OtherPtrTy->getElementType();
02238       if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
02239         EltOffset = DL->getStructLayout(ST)->getElementOffset(i);
02240       } else {
02241         Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
02242         EltOffset = DL->getTypeAllocSize(EltTy)*i;
02243       }
02244 
02245       // The alignment of the other pointer is the guaranteed alignment of the
02246       // element, which is affected by both the known alignment of the whole
02247       // mem intrinsic and the alignment of the element.  If the alignment of
02248       // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
02249       // known alignment is just 4 bytes.
02250       OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
02251     }
02252 
02253     Value *EltPtr = NewElts[i];
02254     Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
02255 
02256     // If we got down to a scalar, insert a load or store as appropriate.
02257     if (EltTy->isSingleValueType()) {
02258       if (isa<MemTransferInst>(MI)) {
02259         if (SROADest) {
02260           // From Other to Alloca.
02261           Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
02262           new StoreInst(Elt, EltPtr, MI);
02263         } else {
02264           // From Alloca to Other.
02265           Value *Elt = new LoadInst(EltPtr, "tmp", MI);
02266           new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
02267         }
02268         continue;
02269       }
02270       assert(isa<MemSetInst>(MI));
02271 
02272       // If the stored element is zero (common case), just store a null
02273       // constant.
02274       Constant *StoreVal;
02275       if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
02276         if (CI->isZero()) {
02277           StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
02278         } else {
02279           // If EltTy is a vector type, get the element type.
02280           Type *ValTy = EltTy->getScalarType();
02281 
02282           // Construct an integer with the right value.
02283           unsigned EltSize = DL->getTypeSizeInBits(ValTy);
02284           APInt OneVal(EltSize, CI->getZExtValue());
02285           APInt TotalVal(OneVal);
02286           // Set each byte.
02287           for (unsigned i = 0; 8*i < EltSize; ++i) {
02288             TotalVal = TotalVal.shl(8);
02289             TotalVal |= OneVal;
02290           }
02291 
02292           // Convert the integer value to the appropriate type.
02293           StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
02294           if (ValTy->isPointerTy())
02295             StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
02296           else if (ValTy->isFloatingPointTy())
02297             StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
02298           assert(StoreVal->getType() == ValTy && "Type mismatch!");
02299 
02300           // If the requested value was a vector constant, create it.
02301           if (EltTy->isVectorTy()) {
02302             unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
02303             StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
02304           }
02305         }
02306         new StoreInst(StoreVal, EltPtr, MI);
02307         continue;
02308       }
02309       // Otherwise, if we're storing a byte variable, use a memset call for
02310       // this element.
02311     }
02312 
02313     unsigned EltSize = DL->getTypeAllocSize(EltTy);
02314     if (!EltSize)
02315       continue;
02316 
02317     IRBuilder<> Builder(MI);
02318 
02319     // Finally, insert the meminst for this element.
02320     if (isa<MemSetInst>(MI)) {
02321       Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
02322                            MI->isVolatile());
02323     } else {
02324       assert(isa<MemTransferInst>(MI));
02325       Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
02326       Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
02327 
02328       if (isa<MemCpyInst>(MI))
02329         Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
02330       else
02331         Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
02332     }
02333   }
02334   DeadInsts.push_back(MI);
02335 }
02336 
02337 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
02338 /// overwrites the entire allocation.  Extract out the pieces of the stored
02339 /// integer and store them individually.
02340 void
02341 SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
02342                                     SmallVectorImpl<AllocaInst *> &NewElts) {
02343   // Extract each element out of the integer according to its structure offset
02344   // and store the element value to the individual alloca.
02345   Value *SrcVal = SI->getOperand(0);
02346   Type *AllocaEltTy = AI->getAllocatedType();
02347   uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
02348 
02349   IRBuilder<> Builder(SI);
02350 
02351   // Handle tail padding by extending the operand
02352   if (DL->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
02353     SrcVal = Builder.CreateZExt(SrcVal,
02354                             IntegerType::get(SI->getContext(), AllocaSizeBits));
02355 
02356   DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
02357                << '\n');
02358 
02359   // There are two forms here: AI could be an array or struct.  Both cases
02360   // have different ways to compute the element offset.
02361   if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
02362     const StructLayout *Layout = DL->getStructLayout(EltSTy);
02363 
02364     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02365       // Get the number of bits to shift SrcVal to get the value.
02366       Type *FieldTy = EltSTy->getElementType(i);
02367       uint64_t Shift = Layout->getElementOffsetInBits(i);
02368 
02369       if (DL->isBigEndian())
02370         Shift = AllocaSizeBits-Shift-DL->getTypeAllocSizeInBits(FieldTy);
02371 
02372       Value *EltVal = SrcVal;
02373       if (Shift) {
02374         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
02375         EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
02376       }
02377 
02378       // Truncate down to an integer of the right size.
02379       uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
02380 
02381       // Ignore zero sized fields like {}, they obviously contain no data.
02382       if (FieldSizeBits == 0) continue;
02383 
02384       if (FieldSizeBits != AllocaSizeBits)
02385         EltVal = Builder.CreateTrunc(EltVal,
02386                              IntegerType::get(SI->getContext(), FieldSizeBits));
02387       Value *DestField = NewElts[i];
02388       if (EltVal->getType() == FieldTy) {
02389         // Storing to an integer field of this size, just do it.
02390       } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
02391         // Bitcast to the right element type (for fp/vector values).
02392         EltVal = Builder.CreateBitCast(EltVal, FieldTy);
02393       } else {
02394         // Otherwise, bitcast the dest pointer (for aggregates).
02395         DestField = Builder.CreateBitCast(DestField,
02396                                      PointerType::getUnqual(EltVal->getType()));
02397       }
02398       new StoreInst(EltVal, DestField, SI);
02399     }
02400 
02401   } else {
02402     ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
02403     Type *ArrayEltTy = ATy->getElementType();
02404     uint64_t ElementOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
02405     uint64_t ElementSizeBits = DL->getTypeSizeInBits(ArrayEltTy);
02406 
02407     uint64_t Shift;
02408 
02409     if (DL->isBigEndian())
02410       Shift = AllocaSizeBits-ElementOffset;
02411     else
02412       Shift = 0;
02413 
02414     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02415       // Ignore zero sized fields like {}, they obviously contain no data.
02416       if (ElementSizeBits == 0) continue;
02417 
02418       Value *EltVal = SrcVal;
02419       if (Shift) {
02420         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
02421         EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
02422       }
02423 
02424       // Truncate down to an integer of the right size.
02425       if (ElementSizeBits != AllocaSizeBits)
02426         EltVal = Builder.CreateTrunc(EltVal,
02427                                      IntegerType::get(SI->getContext(),
02428                                                       ElementSizeBits));
02429       Value *DestField = NewElts[i];
02430       if (EltVal->getType() == ArrayEltTy) {
02431         // Storing to an integer field of this size, just do it.
02432       } else if (ArrayEltTy->isFloatingPointTy() ||
02433                  ArrayEltTy->isVectorTy()) {
02434         // Bitcast to the right element type (for fp/vector values).
02435         EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
02436       } else {
02437         // Otherwise, bitcast the dest pointer (for aggregates).
02438         DestField = Builder.CreateBitCast(DestField,
02439                                      PointerType::getUnqual(EltVal->getType()));
02440       }
02441       new StoreInst(EltVal, DestField, SI);
02442 
02443       if (DL->isBigEndian())
02444         Shift -= ElementOffset;
02445       else
02446         Shift += ElementOffset;
02447     }
02448   }
02449 
02450   DeadInsts.push_back(SI);
02451 }
02452 
02453 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
02454 /// an integer.  Load the individual pieces to form the aggregate value.
02455 void
02456 SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
02457                                    SmallVectorImpl<AllocaInst *> &NewElts) {
02458   // Extract each element out of the NewElts according to its structure offset
02459   // and form the result value.
02460   Type *AllocaEltTy = AI->getAllocatedType();
02461   uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
02462 
02463   DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
02464                << '\n');
02465 
02466   // There are two forms here: AI could be an array or struct.  Both cases
02467   // have different ways to compute the element offset.
02468   const StructLayout *Layout = nullptr;
02469   uint64_t ArrayEltBitOffset = 0;
02470   if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
02471     Layout = DL->getStructLayout(EltSTy);
02472   } else {
02473     Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
02474     ArrayEltBitOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
02475   }
02476 
02477   Value *ResultVal =
02478     Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
02479 
02480   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02481     // Load the value from the alloca.  If the NewElt is an aggregate, cast
02482     // the pointer to an integer of the same size before doing the load.
02483     Value *SrcField = NewElts[i];
02484     Type *FieldTy =
02485       cast<PointerType>(SrcField->getType())->getElementType();
02486     uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
02487 
02488     // Ignore zero sized fields like {}, they obviously contain no data.
02489     if (FieldSizeBits == 0) continue;
02490 
02491     IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
02492                                                      FieldSizeBits);
02493     if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
02494         !FieldTy->isVectorTy())
02495       SrcField = new BitCastInst(SrcField,
02496                                  PointerType::getUnqual(FieldIntTy),
02497                                  "", LI);
02498     SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
02499 
02500     // If SrcField is a fp or vector of the right size but that isn't an
02501     // integer type, bitcast to an integer so we can shift it.
02502     if (SrcField->getType() != FieldIntTy)
02503       SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
02504 
02505     // Zero extend the field to be the same size as the final alloca so that
02506     // we can shift and insert it.
02507     if (SrcField->getType() != ResultVal->getType())
02508       SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
02509 
02510     // Determine the number of bits to shift SrcField.
02511     uint64_t Shift;
02512     if (Layout) // Struct case.
02513       Shift = Layout->getElementOffsetInBits(i);
02514     else  // Array case.
02515       Shift = i*ArrayEltBitOffset;
02516 
02517     if (DL->isBigEndian())
02518       Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
02519 
02520     if (Shift) {
02521       Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
02522       SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
02523     }
02524 
02525     // Don't create an 'or x, 0' on the first iteration.
02526     if (!isa<Constant>(ResultVal) ||
02527         !cast<Constant>(ResultVal)->isNullValue())
02528       ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
02529     else
02530       ResultVal = SrcField;
02531   }
02532 
02533   // Handle tail padding by truncating the result
02534   if (DL->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
02535     ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
02536 
02537   LI->replaceAllUsesWith(ResultVal);
02538   DeadInsts.push_back(LI);
02539 }
02540 
02541 /// HasPadding - Return true if the specified type has any structure or
02542 /// alignment padding in between the elements that would be split apart
02543 /// by SROA; return false otherwise.
02544 static bool HasPadding(Type *Ty, const DataLayout &DL) {
02545   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
02546     Ty = ATy->getElementType();
02547     return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
02548   }
02549 
02550   // SROA currently handles only Arrays and Structs.
02551   StructType *STy = cast<StructType>(Ty);
02552   const StructLayout *SL = DL.getStructLayout(STy);
02553   unsigned PrevFieldBitOffset = 0;
02554   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
02555     unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
02556 
02557     // Check to see if there is any padding between this element and the
02558     // previous one.
02559     if (i) {
02560       unsigned PrevFieldEnd =
02561         PrevFieldBitOffset+DL.getTypeSizeInBits(STy->getElementType(i-1));
02562       if (PrevFieldEnd < FieldBitOffset)
02563         return true;
02564     }
02565     PrevFieldBitOffset = FieldBitOffset;
02566   }
02567   // Check for tail padding.
02568   if (unsigned EltCount = STy->getNumElements()) {
02569     unsigned PrevFieldEnd = PrevFieldBitOffset +
02570       DL.getTypeSizeInBits(STy->getElementType(EltCount-1));
02571     if (PrevFieldEnd < SL->getSizeInBits())
02572       return true;
02573   }
02574   return false;
02575 }
02576 
02577 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
02578 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
02579 /// or 1 if safe after canonicalization has been performed.
02580 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
02581   // Loop over the use list of the alloca.  We can only transform it if all of
02582   // the users are safe to transform.
02583   AllocaInfo Info(AI);
02584 
02585   isSafeForScalarRepl(AI, 0, Info);
02586   if (Info.isUnsafe) {
02587     DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
02588     return false;
02589   }
02590 
02591   // Okay, we know all the users are promotable.  If the aggregate is a memcpy
02592   // source and destination, we have to be careful.  In particular, the memcpy
02593   // could be moving around elements that live in structure padding of the LLVM
02594   // types, but may actually be used.  In these cases, we refuse to promote the
02595   // struct.
02596   if (Info.isMemCpySrc && Info.isMemCpyDst &&
02597       HasPadding(AI->getAllocatedType(), *DL))
02598     return false;
02599 
02600   // If the alloca never has an access to just *part* of it, but is accessed
02601   // via loads and stores, then we should use ConvertToScalarInfo to promote
02602   // the alloca instead of promoting each piece at a time and inserting fission
02603   // and fusion code.
02604   if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
02605     // If the struct/array just has one element, use basic SRoA.
02606     if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
02607       if (ST->getNumElements() > 1) return false;
02608     } else {
02609       if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
02610         return false;
02611     }
02612   }
02613 
02614   return true;
02615 }