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