LLVM API Documentation

SROA.cpp
Go to the documentation of this file.
00001 //===- SROA.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 /// \file
00010 /// This transformation implements the well known scalar replacement of
00011 /// aggregates transformation. It tries to identify promotable elements of an
00012 /// aggregate alloca, and promote them to registers. It will also try to
00013 /// convert uses of an element (or set of elements) of an alloca into a vector
00014 /// or bitfield-style integer scalar if appropriate.
00015 ///
00016 /// It works to do this with minimal slicing of the alloca so that regions
00017 /// which are merely transferred in and out of external memory remain unchanged
00018 /// and are not decomposed to scalar code.
00019 ///
00020 /// Because this also performs alloca promotion, it can be thought of as also
00021 /// serving the purpose of SSA formation. The algorithm iterates on the
00022 /// function until all opportunities for promotion have been realized.
00023 ///
00024 //===----------------------------------------------------------------------===//
00025 
00026 #include "llvm/Transforms/Scalar.h"
00027 #include "llvm/ADT/STLExtras.h"
00028 #include "llvm/ADT/SetVector.h"
00029 #include "llvm/ADT/SmallVector.h"
00030 #include "llvm/ADT/Statistic.h"
00031 #include "llvm/Analysis/Loads.h"
00032 #include "llvm/Analysis/PtrUseVisitor.h"
00033 #include "llvm/Analysis/ValueTracking.h"
00034 #include "llvm/IR/Constants.h"
00035 #include "llvm/IR/DIBuilder.h"
00036 #include "llvm/IR/DataLayout.h"
00037 #include "llvm/IR/DebugInfo.h"
00038 #include "llvm/IR/DerivedTypes.h"
00039 #include "llvm/IR/Dominators.h"
00040 #include "llvm/IR/Function.h"
00041 #include "llvm/IR/IRBuilder.h"
00042 #include "llvm/IR/InstVisitor.h"
00043 #include "llvm/IR/Instructions.h"
00044 #include "llvm/IR/IntrinsicInst.h"
00045 #include "llvm/IR/LLVMContext.h"
00046 #include "llvm/IR/Operator.h"
00047 #include "llvm/Pass.h"
00048 #include "llvm/Support/CommandLine.h"
00049 #include "llvm/Support/Compiler.h"
00050 #include "llvm/Support/Debug.h"
00051 #include "llvm/Support/ErrorHandling.h"
00052 #include "llvm/Support/MathExtras.h"
00053 #include "llvm/Support/TimeValue.h"
00054 #include "llvm/Support/raw_ostream.h"
00055 #include "llvm/Transforms/Utils/Local.h"
00056 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
00057 #include "llvm/Transforms/Utils/SSAUpdater.h"
00058 
00059 #if __cplusplus >= 201103L && !defined(NDEBUG)
00060 // We only use this for a debug check in C++11
00061 #include <random>
00062 #endif
00063 
00064 using namespace llvm;
00065 
00066 #define DEBUG_TYPE "sroa"
00067 
00068 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
00069 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
00070 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
00071 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
00072 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
00073 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
00074 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
00075 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
00076 STATISTIC(NumDeleted, "Number of instructions deleted");
00077 STATISTIC(NumVectorized, "Number of vectorized aggregates");
00078 
00079 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
00080 /// forming SSA values through the SSAUpdater infrastructure.
00081 static cl::opt<bool>
00082 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
00083 
00084 /// Hidden option to enable randomly shuffling the slices to help uncover
00085 /// instability in their order.
00086 static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
00087                                              cl::init(false), cl::Hidden);
00088 
00089 /// Hidden option to experiment with completely strict handling of inbounds
00090 /// GEPs.
00091 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds",
00092                                         cl::init(false), cl::Hidden);
00093 
00094 namespace {
00095 /// \brief A custom IRBuilder inserter which prefixes all names if they are
00096 /// preserved.
00097 template <bool preserveNames = true>
00098 class IRBuilderPrefixedInserter :
00099     public IRBuilderDefaultInserter<preserveNames> {
00100   std::string Prefix;
00101 
00102 public:
00103   void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
00104 
00105 protected:
00106   void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
00107                     BasicBlock::iterator InsertPt) const {
00108     IRBuilderDefaultInserter<preserveNames>::InsertHelper(
00109         I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
00110   }
00111 };
00112 
00113 // Specialization for not preserving the name is trivial.
00114 template <>
00115 class IRBuilderPrefixedInserter<false> :
00116     public IRBuilderDefaultInserter<false> {
00117 public:
00118   void SetNamePrefix(const Twine &P) {}
00119 };
00120 
00121 /// \brief Provide a typedef for IRBuilder that drops names in release builds.
00122 #ifndef NDEBUG
00123 typedef llvm::IRBuilder<true, ConstantFolder,
00124                         IRBuilderPrefixedInserter<true> > IRBuilderTy;
00125 #else
00126 typedef llvm::IRBuilder<false, ConstantFolder,
00127                         IRBuilderPrefixedInserter<false> > IRBuilderTy;
00128 #endif
00129 }
00130 
00131 namespace {
00132 /// \brief A used slice of an alloca.
00133 ///
00134 /// This structure represents a slice of an alloca used by some instruction. It
00135 /// stores both the begin and end offsets of this use, a pointer to the use
00136 /// itself, and a flag indicating whether we can classify the use as splittable
00137 /// or not when forming partitions of the alloca.
00138 class Slice {
00139   /// \brief The beginning offset of the range.
00140   uint64_t BeginOffset;
00141 
00142   /// \brief The ending offset, not included in the range.
00143   uint64_t EndOffset;
00144 
00145   /// \brief Storage for both the use of this slice and whether it can be
00146   /// split.
00147   PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
00148 
00149 public:
00150   Slice() : BeginOffset(), EndOffset() {}
00151   Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
00152       : BeginOffset(BeginOffset), EndOffset(EndOffset),
00153         UseAndIsSplittable(U, IsSplittable) {}
00154 
00155   uint64_t beginOffset() const { return BeginOffset; }
00156   uint64_t endOffset() const { return EndOffset; }
00157 
00158   bool isSplittable() const { return UseAndIsSplittable.getInt(); }
00159   void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
00160 
00161   Use *getUse() const { return UseAndIsSplittable.getPointer(); }
00162 
00163   bool isDead() const { return getUse() == nullptr; }
00164   void kill() { UseAndIsSplittable.setPointer(nullptr); }
00165 
00166   /// \brief Support for ordering ranges.
00167   ///
00168   /// This provides an ordering over ranges such that start offsets are
00169   /// always increasing, and within equal start offsets, the end offsets are
00170   /// decreasing. Thus the spanning range comes first in a cluster with the
00171   /// same start position.
00172   bool operator<(const Slice &RHS) const {
00173     if (beginOffset() < RHS.beginOffset()) return true;
00174     if (beginOffset() > RHS.beginOffset()) return false;
00175     if (isSplittable() != RHS.isSplittable()) return !isSplittable();
00176     if (endOffset() > RHS.endOffset()) return true;
00177     return false;
00178   }
00179 
00180   /// \brief Support comparison with a single offset to allow binary searches.
00181   friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
00182                                               uint64_t RHSOffset) {
00183     return LHS.beginOffset() < RHSOffset;
00184   }
00185   friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
00186                                               const Slice &RHS) {
00187     return LHSOffset < RHS.beginOffset();
00188   }
00189 
00190   bool operator==(const Slice &RHS) const {
00191     return isSplittable() == RHS.isSplittable() &&
00192            beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
00193   }
00194   bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
00195 };
00196 } // end anonymous namespace
00197 
00198 namespace llvm {
00199 template <typename T> struct isPodLike;
00200 template <> struct isPodLike<Slice> {
00201    static const bool value = true;
00202 };
00203 }
00204 
00205 namespace {
00206 /// \brief Representation of the alloca slices.
00207 ///
00208 /// This class represents the slices of an alloca which are formed by its
00209 /// various uses. If a pointer escapes, we can't fully build a representation
00210 /// for the slices used and we reflect that in this structure. The uses are
00211 /// stored, sorted by increasing beginning offset and with unsplittable slices
00212 /// starting at a particular offset before splittable slices.
00213 class AllocaSlices {
00214 public:
00215   /// \brief Construct the slices of a particular alloca.
00216   AllocaSlices(const DataLayout &DL, AllocaInst &AI);
00217 
00218   /// \brief Test whether a pointer to the allocation escapes our analysis.
00219   ///
00220   /// If this is true, the slices are never fully built and should be
00221   /// ignored.
00222   bool isEscaped() const { return PointerEscapingInstr; }
00223 
00224   /// \brief Support for iterating over the slices.
00225   /// @{
00226   typedef SmallVectorImpl<Slice>::iterator iterator;
00227   iterator begin() { return Slices.begin(); }
00228   iterator end() { return Slices.end(); }
00229 
00230   typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
00231   const_iterator begin() const { return Slices.begin(); }
00232   const_iterator end() const { return Slices.end(); }
00233   /// @}
00234 
00235   /// \brief Allow iterating the dead users for this alloca.
00236   ///
00237   /// These are instructions which will never actually use the alloca as they
00238   /// are outside the allocated range. They are safe to replace with undef and
00239   /// delete.
00240   /// @{
00241   typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
00242   dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
00243   dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
00244   /// @}
00245 
00246   /// \brief Allow iterating the dead expressions referring to this alloca.
00247   ///
00248   /// These are operands which have cannot actually be used to refer to the
00249   /// alloca as they are outside its range and the user doesn't correct for
00250   /// that. These mostly consist of PHI node inputs and the like which we just
00251   /// need to replace with undef.
00252   /// @{
00253   typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
00254   dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
00255   dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
00256   /// @}
00257 
00258 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00259   void print(raw_ostream &OS, const_iterator I, StringRef Indent = "  ") const;
00260   void printSlice(raw_ostream &OS, const_iterator I,
00261                   StringRef Indent = "  ") const;
00262   void printUse(raw_ostream &OS, const_iterator I,
00263                 StringRef Indent = "  ") const;
00264   void print(raw_ostream &OS) const;
00265   void dump(const_iterator I) const;
00266   void dump() const;
00267 #endif
00268 
00269 private:
00270   template <typename DerivedT, typename RetT = void> class BuilderBase;
00271   class SliceBuilder;
00272   friend class AllocaSlices::SliceBuilder;
00273 
00274 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00275   /// \brief Handle to alloca instruction to simplify method interfaces.
00276   AllocaInst &AI;
00277 #endif
00278 
00279   /// \brief The instruction responsible for this alloca not having a known set
00280   /// of slices.
00281   ///
00282   /// When an instruction (potentially) escapes the pointer to the alloca, we
00283   /// store a pointer to that here and abort trying to form slices of the
00284   /// alloca. This will be null if the alloca slices are analyzed successfully.
00285   Instruction *PointerEscapingInstr;
00286 
00287   /// \brief The slices of the alloca.
00288   ///
00289   /// We store a vector of the slices formed by uses of the alloca here. This
00290   /// vector is sorted by increasing begin offset, and then the unsplittable
00291   /// slices before the splittable ones. See the Slice inner class for more
00292   /// details.
00293   SmallVector<Slice, 8> Slices;
00294 
00295   /// \brief Instructions which will become dead if we rewrite the alloca.
00296   ///
00297   /// Note that these are not separated by slice. This is because we expect an
00298   /// alloca to be completely rewritten or not rewritten at all. If rewritten,
00299   /// all these instructions can simply be removed and replaced with undef as
00300   /// they come from outside of the allocated space.
00301   SmallVector<Instruction *, 8> DeadUsers;
00302 
00303   /// \brief Operands which will become dead if we rewrite the alloca.
00304   ///
00305   /// These are operands that in their particular use can be replaced with
00306   /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
00307   /// to PHI nodes and the like. They aren't entirely dead (there might be
00308   /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
00309   /// want to swap this particular input for undef to simplify the use lists of
00310   /// the alloca.
00311   SmallVector<Use *, 8> DeadOperands;
00312 };
00313 }
00314 
00315 static Value *foldSelectInst(SelectInst &SI) {
00316   // If the condition being selected on is a constant or the same value is
00317   // being selected between, fold the select. Yes this does (rarely) happen
00318   // early on.
00319   if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
00320     return SI.getOperand(1+CI->isZero());
00321   if (SI.getOperand(1) == SI.getOperand(2))
00322     return SI.getOperand(1);
00323 
00324   return nullptr;
00325 }
00326 
00327 /// \brief Builder for the alloca slices.
00328 ///
00329 /// This class builds a set of alloca slices by recursively visiting the uses
00330 /// of an alloca and making a slice for each load and store at each offset.
00331 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
00332   friend class PtrUseVisitor<SliceBuilder>;
00333   friend class InstVisitor<SliceBuilder>;
00334   typedef PtrUseVisitor<SliceBuilder> Base;
00335 
00336   const uint64_t AllocSize;
00337   AllocaSlices &S;
00338 
00339   SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
00340   SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
00341 
00342   /// \brief Set to de-duplicate dead instructions found in the use walk.
00343   SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
00344 
00345 public:
00346   SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
00347       : PtrUseVisitor<SliceBuilder>(DL),
00348         AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
00349 
00350 private:
00351   void markAsDead(Instruction &I) {
00352     if (VisitedDeadInsts.insert(&I))
00353       S.DeadUsers.push_back(&I);
00354   }
00355 
00356   void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
00357                  bool IsSplittable = false) {
00358     // Completely skip uses which have a zero size or start either before or
00359     // past the end of the allocation.
00360     if (Size == 0 || Offset.uge(AllocSize)) {
00361       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
00362                    << " which has zero size or starts outside of the "
00363                    << AllocSize << " byte alloca:\n"
00364                    << "    alloca: " << S.AI << "\n"
00365                    << "       use: " << I << "\n");
00366       return markAsDead(I);
00367     }
00368 
00369     uint64_t BeginOffset = Offset.getZExtValue();
00370     uint64_t EndOffset = BeginOffset + Size;
00371 
00372     // Clamp the end offset to the end of the allocation. Note that this is
00373     // formulated to handle even the case where "BeginOffset + Size" overflows.
00374     // This may appear superficially to be something we could ignore entirely,
00375     // but that is not so! There may be widened loads or PHI-node uses where
00376     // some instructions are dead but not others. We can't completely ignore
00377     // them, and so have to record at least the information here.
00378     assert(AllocSize >= BeginOffset); // Established above.
00379     if (Size > AllocSize - BeginOffset) {
00380       DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
00381                    << " to remain within the " << AllocSize << " byte alloca:\n"
00382                    << "    alloca: " << S.AI << "\n"
00383                    << "       use: " << I << "\n");
00384       EndOffset = AllocSize;
00385     }
00386 
00387     S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
00388   }
00389 
00390   void visitBitCastInst(BitCastInst &BC) {
00391     if (BC.use_empty())
00392       return markAsDead(BC);
00393 
00394     return Base::visitBitCastInst(BC);
00395   }
00396 
00397   void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
00398     if (GEPI.use_empty())
00399       return markAsDead(GEPI);
00400 
00401     if (SROAStrictInbounds && GEPI.isInBounds()) {
00402       // FIXME: This is a manually un-factored variant of the basic code inside
00403       // of GEPs with checking of the inbounds invariant specified in the
00404       // langref in a very strict sense. If we ever want to enable
00405       // SROAStrictInbounds, this code should be factored cleanly into
00406       // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
00407       // by writing out the code here where we have tho underlying allocation
00408       // size readily available.
00409       APInt GEPOffset = Offset;
00410       for (gep_type_iterator GTI = gep_type_begin(GEPI),
00411                              GTE = gep_type_end(GEPI);
00412            GTI != GTE; ++GTI) {
00413         ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
00414         if (!OpC)
00415           break;
00416 
00417         // Handle a struct index, which adds its field offset to the pointer.
00418         if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00419           unsigned ElementIdx = OpC->getZExtValue();
00420           const StructLayout *SL = DL.getStructLayout(STy);
00421           GEPOffset +=
00422               APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
00423         } else {
00424           // For array or vector indices, scale the index by the size of the type.
00425           APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
00426           GEPOffset += Index * APInt(Offset.getBitWidth(),
00427                                      DL.getTypeAllocSize(GTI.getIndexedType()));
00428         }
00429 
00430         // If this index has computed an intermediate pointer which is not
00431         // inbounds, then the result of the GEP is a poison value and we can
00432         // delete it and all uses.
00433         if (GEPOffset.ugt(AllocSize))
00434           return markAsDead(GEPI);
00435       }
00436     }
00437 
00438     return Base::visitGetElementPtrInst(GEPI);
00439   }
00440 
00441   void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
00442                          uint64_t Size, bool IsVolatile) {
00443     // We allow splitting of loads and stores where the type is an integer type
00444     // and cover the entire alloca. This prevents us from splitting over
00445     // eagerly.
00446     // FIXME: In the great blue eventually, we should eagerly split all integer
00447     // loads and stores, and then have a separate step that merges adjacent
00448     // alloca partitions into a single partition suitable for integer widening.
00449     // Or we should skip the merge step and rely on GVN and other passes to
00450     // merge adjacent loads and stores that survive mem2reg.
00451     bool IsSplittable =
00452         Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
00453 
00454     insertUse(I, Offset, Size, IsSplittable);
00455   }
00456 
00457   void visitLoadInst(LoadInst &LI) {
00458     assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
00459            "All simple FCA loads should have been pre-split");
00460 
00461     if (!IsOffsetKnown)
00462       return PI.setAborted(&LI);
00463 
00464     uint64_t Size = DL.getTypeStoreSize(LI.getType());
00465     return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
00466   }
00467 
00468   void visitStoreInst(StoreInst &SI) {
00469     Value *ValOp = SI.getValueOperand();
00470     if (ValOp == *U)
00471       return PI.setEscapedAndAborted(&SI);
00472     if (!IsOffsetKnown)
00473       return PI.setAborted(&SI);
00474 
00475     uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
00476 
00477     // If this memory access can be shown to *statically* extend outside the
00478     // bounds of of the allocation, it's behavior is undefined, so simply
00479     // ignore it. Note that this is more strict than the generic clamping
00480     // behavior of insertUse. We also try to handle cases which might run the
00481     // risk of overflow.
00482     // FIXME: We should instead consider the pointer to have escaped if this
00483     // function is being instrumented for addressing bugs or race conditions.
00484     if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
00485       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
00486                    << " which extends past the end of the " << AllocSize
00487                    << " byte alloca:\n"
00488                    << "    alloca: " << S.AI << "\n"
00489                    << "       use: " << SI << "\n");
00490       return markAsDead(SI);
00491     }
00492 
00493     assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
00494            "All simple FCA stores should have been pre-split");
00495     handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
00496   }
00497 
00498 
00499   void visitMemSetInst(MemSetInst &II) {
00500     assert(II.getRawDest() == *U && "Pointer use is not the destination?");
00501     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
00502     if ((Length && Length->getValue() == 0) ||
00503         (IsOffsetKnown && Offset.uge(AllocSize)))
00504       // Zero-length mem transfer intrinsics can be ignored entirely.
00505       return markAsDead(II);
00506 
00507     if (!IsOffsetKnown)
00508       return PI.setAborted(&II);
00509 
00510     insertUse(II, Offset,
00511               Length ? Length->getLimitedValue()
00512                      : AllocSize - Offset.getLimitedValue(),
00513               (bool)Length);
00514   }
00515 
00516   void visitMemTransferInst(MemTransferInst &II) {
00517     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
00518     if (Length && Length->getValue() == 0)
00519       // Zero-length mem transfer intrinsics can be ignored entirely.
00520       return markAsDead(II);
00521 
00522     // Because we can visit these intrinsics twice, also check to see if the
00523     // first time marked this instruction as dead. If so, skip it.
00524     if (VisitedDeadInsts.count(&II))
00525       return;
00526 
00527     if (!IsOffsetKnown)
00528       return PI.setAborted(&II);
00529 
00530     // This side of the transfer is completely out-of-bounds, and so we can
00531     // nuke the entire transfer. However, we also need to nuke the other side
00532     // if already added to our partitions.
00533     // FIXME: Yet another place we really should bypass this when
00534     // instrumenting for ASan.
00535     if (Offset.uge(AllocSize)) {
00536       SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II);
00537       if (MTPI != MemTransferSliceMap.end())
00538         S.Slices[MTPI->second].kill();
00539       return markAsDead(II);
00540     }
00541 
00542     uint64_t RawOffset = Offset.getLimitedValue();
00543     uint64_t Size = Length ? Length->getLimitedValue()
00544                            : AllocSize - RawOffset;
00545 
00546     // Check for the special case where the same exact value is used for both
00547     // source and dest.
00548     if (*U == II.getRawDest() && *U == II.getRawSource()) {
00549       // For non-volatile transfers this is a no-op.
00550       if (!II.isVolatile())
00551         return markAsDead(II);
00552 
00553       return insertUse(II, Offset, Size, /*IsSplittable=*/false);
00554     }
00555 
00556     // If we have seen both source and destination for a mem transfer, then
00557     // they both point to the same alloca.
00558     bool Inserted;
00559     SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
00560     std::tie(MTPI, Inserted) =
00561         MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
00562     unsigned PrevIdx = MTPI->second;
00563     if (!Inserted) {
00564       Slice &PrevP = S.Slices[PrevIdx];
00565 
00566       // Check if the begin offsets match and this is a non-volatile transfer.
00567       // In that case, we can completely elide the transfer.
00568       if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
00569         PrevP.kill();
00570         return markAsDead(II);
00571       }
00572 
00573       // Otherwise we have an offset transfer within the same alloca. We can't
00574       // split those.
00575       PrevP.makeUnsplittable();
00576     }
00577 
00578     // Insert the use now that we've fixed up the splittable nature.
00579     insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
00580 
00581     // Check that we ended up with a valid index in the map.
00582     assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
00583            "Map index doesn't point back to a slice with this user.");
00584   }
00585 
00586   // Disable SRoA for any intrinsics except for lifetime invariants.
00587   // FIXME: What about debug intrinsics? This matches old behavior, but
00588   // doesn't make sense.
00589   void visitIntrinsicInst(IntrinsicInst &II) {
00590     if (!IsOffsetKnown)
00591       return PI.setAborted(&II);
00592 
00593     if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
00594         II.getIntrinsicID() == Intrinsic::lifetime_end) {
00595       ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
00596       uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
00597                                Length->getLimitedValue());
00598       insertUse(II, Offset, Size, true);
00599       return;
00600     }
00601 
00602     Base::visitIntrinsicInst(II);
00603   }
00604 
00605   Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
00606     // We consider any PHI or select that results in a direct load or store of
00607     // the same offset to be a viable use for slicing purposes. These uses
00608     // are considered unsplittable and the size is the maximum loaded or stored
00609     // size.
00610     SmallPtrSet<Instruction *, 4> Visited;
00611     SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
00612     Visited.insert(Root);
00613     Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
00614     // If there are no loads or stores, the access is dead. We mark that as
00615     // a size zero access.
00616     Size = 0;
00617     do {
00618       Instruction *I, *UsedI;
00619       std::tie(UsedI, I) = Uses.pop_back_val();
00620 
00621       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00622         Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
00623         continue;
00624       }
00625       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00626         Value *Op = SI->getOperand(0);
00627         if (Op == UsedI)
00628           return SI;
00629         Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
00630         continue;
00631       }
00632 
00633       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
00634         if (!GEP->hasAllZeroIndices())
00635           return GEP;
00636       } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
00637                  !isa<SelectInst>(I)) {
00638         return I;
00639       }
00640 
00641       for (User *U : I->users())
00642         if (Visited.insert(cast<Instruction>(U)))
00643           Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
00644     } while (!Uses.empty());
00645 
00646     return nullptr;
00647   }
00648 
00649   void visitPHINode(PHINode &PN) {
00650     if (PN.use_empty())
00651       return markAsDead(PN);
00652     if (!IsOffsetKnown)
00653       return PI.setAborted(&PN);
00654 
00655     // See if we already have computed info on this node.
00656     uint64_t &PHISize = PHIOrSelectSizes[&PN];
00657     if (!PHISize) {
00658       // This is a new PHI node, check for an unsafe use of the PHI node.
00659       if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
00660         return PI.setAborted(UnsafeI);
00661     }
00662 
00663     // For PHI and select operands outside the alloca, we can't nuke the entire
00664     // phi or select -- the other side might still be relevant, so we special
00665     // case them here and use a separate structure to track the operands
00666     // themselves which should be replaced with undef.
00667     // FIXME: This should instead be escaped in the event we're instrumenting
00668     // for address sanitization.
00669     if (Offset.uge(AllocSize)) {
00670       S.DeadOperands.push_back(U);
00671       return;
00672     }
00673 
00674     insertUse(PN, Offset, PHISize);
00675   }
00676 
00677   void visitSelectInst(SelectInst &SI) {
00678     if (SI.use_empty())
00679       return markAsDead(SI);
00680     if (Value *Result = foldSelectInst(SI)) {
00681       if (Result == *U)
00682         // If the result of the constant fold will be the pointer, recurse
00683         // through the select as if we had RAUW'ed it.
00684         enqueueUsers(SI);
00685       else
00686         // Otherwise the operand to the select is dead, and we can replace it
00687         // with undef.
00688         S.DeadOperands.push_back(U);
00689 
00690       return;
00691     }
00692     if (!IsOffsetKnown)
00693       return PI.setAborted(&SI);
00694 
00695     // See if we already have computed info on this node.
00696     uint64_t &SelectSize = PHIOrSelectSizes[&SI];
00697     if (!SelectSize) {
00698       // This is a new Select, check for an unsafe use of it.
00699       if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
00700         return PI.setAborted(UnsafeI);
00701     }
00702 
00703     // For PHI and select operands outside the alloca, we can't nuke the entire
00704     // phi or select -- the other side might still be relevant, so we special
00705     // case them here and use a separate structure to track the operands
00706     // themselves which should be replaced with undef.
00707     // FIXME: This should instead be escaped in the event we're instrumenting
00708     // for address sanitization.
00709     if (Offset.uge(AllocSize)) {
00710       S.DeadOperands.push_back(U);
00711       return;
00712     }
00713 
00714     insertUse(SI, Offset, SelectSize);
00715   }
00716 
00717   /// \brief Disable SROA entirely if there are unhandled users of the alloca.
00718   void visitInstruction(Instruction &I) {
00719     PI.setAborted(&I);
00720   }
00721 };
00722 
00723 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
00724     :
00725 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00726       AI(AI),
00727 #endif
00728       PointerEscapingInstr(nullptr) {
00729   SliceBuilder PB(DL, AI, *this);
00730   SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
00731   if (PtrI.isEscaped() || PtrI.isAborted()) {
00732     // FIXME: We should sink the escape vs. abort info into the caller nicely,
00733     // possibly by just storing the PtrInfo in the AllocaSlices.
00734     PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
00735                                                   : PtrI.getAbortingInst();
00736     assert(PointerEscapingInstr && "Did not track a bad instruction");
00737     return;
00738   }
00739 
00740   Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
00741                               std::mem_fun_ref(&Slice::isDead)),
00742                Slices.end());
00743 
00744 #if __cplusplus >= 201103L && !defined(NDEBUG)
00745   if (SROARandomShuffleSlices) {
00746     std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
00747     std::shuffle(Slices.begin(), Slices.end(), MT);
00748   }
00749 #endif
00750 
00751   // Sort the uses. This arranges for the offsets to be in ascending order,
00752   // and the sizes to be in descending order.
00753   std::sort(Slices.begin(), Slices.end());
00754 }
00755 
00756 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00757 
00758 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
00759                          StringRef Indent) const {
00760   printSlice(OS, I, Indent);
00761   printUse(OS, I, Indent);
00762 }
00763 
00764 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
00765                               StringRef Indent) const {
00766   OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
00767      << " slice #" << (I - begin())
00768      << (I->isSplittable() ? " (splittable)" : "") << "\n";
00769 }
00770 
00771 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
00772                             StringRef Indent) const {
00773   OS << Indent << "  used by: " << *I->getUse()->getUser() << "\n";
00774 }
00775 
00776 void AllocaSlices::print(raw_ostream &OS) const {
00777   if (PointerEscapingInstr) {
00778     OS << "Can't analyze slices for alloca: " << AI << "\n"
00779        << "  A pointer to this alloca escaped by:\n"
00780        << "  " << *PointerEscapingInstr << "\n";
00781     return;
00782   }
00783 
00784   OS << "Slices of alloca: " << AI << "\n";
00785   for (const_iterator I = begin(), E = end(); I != E; ++I)
00786     print(OS, I);
00787 }
00788 
00789 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
00790   print(dbgs(), I);
00791 }
00792 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
00793 
00794 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00795 
00796 namespace {
00797 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
00798 ///
00799 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
00800 /// the loads and stores of an alloca instruction, as well as updating its
00801 /// debug information. This is used when a domtree is unavailable and thus
00802 /// mem2reg in its full form can't be used to handle promotion of allocas to
00803 /// scalar values.
00804 class AllocaPromoter : public LoadAndStorePromoter {
00805   AllocaInst &AI;
00806   DIBuilder &DIB;
00807 
00808   SmallVector<DbgDeclareInst *, 4> DDIs;
00809   SmallVector<DbgValueInst *, 4> DVIs;
00810 
00811 public:
00812   AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
00813                  AllocaInst &AI, DIBuilder &DIB)
00814       : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
00815 
00816   void run(const SmallVectorImpl<Instruction*> &Insts) {
00817     // Retain the debug information attached to the alloca for use when
00818     // rewriting loads and stores.
00819     if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
00820       for (User *U : DebugNode->users())
00821         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
00822           DDIs.push_back(DDI);
00823         else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
00824           DVIs.push_back(DVI);
00825     }
00826 
00827     LoadAndStorePromoter::run(Insts);
00828 
00829     // While we have the debug information, clear it off of the alloca. The
00830     // caller takes care of deleting the alloca.
00831     while (!DDIs.empty())
00832       DDIs.pop_back_val()->eraseFromParent();
00833     while (!DVIs.empty())
00834       DVIs.pop_back_val()->eraseFromParent();
00835   }
00836 
00837   bool isInstInList(Instruction *I,
00838                     const SmallVectorImpl<Instruction*> &Insts) const override {
00839     Value *Ptr;
00840     if (LoadInst *LI = dyn_cast<LoadInst>(I))
00841       Ptr = LI->getOperand(0);
00842     else
00843       Ptr = cast<StoreInst>(I)->getPointerOperand();
00844 
00845     // Only used to detect cycles, which will be rare and quickly found as
00846     // we're walking up a chain of defs rather than down through uses.
00847     SmallPtrSet<Value *, 4> Visited;
00848 
00849     do {
00850       if (Ptr == &AI)
00851         return true;
00852 
00853       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
00854         Ptr = BCI->getOperand(0);
00855       else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
00856         Ptr = GEPI->getPointerOperand();
00857       else
00858         return false;
00859 
00860     } while (Visited.insert(Ptr));
00861 
00862     return false;
00863   }
00864 
00865   void updateDebugInfo(Instruction *Inst) const override {
00866     for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
00867            E = DDIs.end(); I != E; ++I) {
00868       DbgDeclareInst *DDI = *I;
00869       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
00870         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
00871       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
00872         ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
00873     }
00874     for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
00875            E = DVIs.end(); I != E; ++I) {
00876       DbgValueInst *DVI = *I;
00877       Value *Arg = nullptr;
00878       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00879         // If an argument is zero extended then use argument directly. The ZExt
00880         // may be zapped by an optimization pass in future.
00881         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
00882           Arg = dyn_cast<Argument>(ZExt->getOperand(0));
00883         else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
00884           Arg = dyn_cast<Argument>(SExt->getOperand(0));
00885         if (!Arg)
00886           Arg = SI->getValueOperand();
00887       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
00888         Arg = LI->getPointerOperand();
00889       } else {
00890         continue;
00891       }
00892       Instruction *DbgVal =
00893         DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
00894                                      Inst);
00895       DbgVal->setDebugLoc(DVI->getDebugLoc());
00896     }
00897   }
00898 };
00899 } // end anon namespace
00900 
00901 
00902 namespace {
00903 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
00904 ///
00905 /// This pass takes allocations which can be completely analyzed (that is, they
00906 /// don't escape) and tries to turn them into scalar SSA values. There are
00907 /// a few steps to this process.
00908 ///
00909 /// 1) It takes allocations of aggregates and analyzes the ways in which they
00910 ///    are used to try to split them into smaller allocations, ideally of
00911 ///    a single scalar data type. It will split up memcpy and memset accesses
00912 ///    as necessary and try to isolate individual scalar accesses.
00913 /// 2) It will transform accesses into forms which are suitable for SSA value
00914 ///    promotion. This can be replacing a memset with a scalar store of an
00915 ///    integer value, or it can involve speculating operations on a PHI or
00916 ///    select to be a PHI or select of the results.
00917 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
00918 ///    onto insert and extract operations on a vector value, and convert them to
00919 ///    this form. By doing so, it will enable promotion of vector aggregates to
00920 ///    SSA vector values.
00921 class SROA : public FunctionPass {
00922   const bool RequiresDomTree;
00923 
00924   LLVMContext *C;
00925   const DataLayout *DL;
00926   DominatorTree *DT;
00927 
00928   /// \brief Worklist of alloca instructions to simplify.
00929   ///
00930   /// Each alloca in the function is added to this. Each new alloca formed gets
00931   /// added to it as well to recursively simplify unless that alloca can be
00932   /// directly promoted. Finally, each time we rewrite a use of an alloca other
00933   /// the one being actively rewritten, we add it back onto the list if not
00934   /// already present to ensure it is re-visited.
00935   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
00936 
00937   /// \brief A collection of instructions to delete.
00938   /// We try to batch deletions to simplify code and make things a bit more
00939   /// efficient.
00940   SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
00941 
00942   /// \brief Post-promotion worklist.
00943   ///
00944   /// Sometimes we discover an alloca which has a high probability of becoming
00945   /// viable for SROA after a round of promotion takes place. In those cases,
00946   /// the alloca is enqueued here for re-processing.
00947   ///
00948   /// Note that we have to be very careful to clear allocas out of this list in
00949   /// the event they are deleted.
00950   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
00951 
00952   /// \brief A collection of alloca instructions we can directly promote.
00953   std::vector<AllocaInst *> PromotableAllocas;
00954 
00955   /// \brief A worklist of PHIs to speculate prior to promoting allocas.
00956   ///
00957   /// All of these PHIs have been checked for the safety of speculation and by
00958   /// being speculated will allow promoting allocas currently in the promotable
00959   /// queue.
00960   SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
00961 
00962   /// \brief A worklist of select instructions to speculate prior to promoting
00963   /// allocas.
00964   ///
00965   /// All of these select instructions have been checked for the safety of
00966   /// speculation and by being speculated will allow promoting allocas
00967   /// currently in the promotable queue.
00968   SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
00969 
00970 public:
00971   SROA(bool RequiresDomTree = true)
00972       : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
00973         C(nullptr), DL(nullptr), DT(nullptr) {
00974     initializeSROAPass(*PassRegistry::getPassRegistry());
00975   }
00976   bool runOnFunction(Function &F) override;
00977   void getAnalysisUsage(AnalysisUsage &AU) const override;
00978 
00979   const char *getPassName() const override { return "SROA"; }
00980   static char ID;
00981 
00982 private:
00983   friend class PHIOrSelectSpeculator;
00984   friend class AllocaSliceRewriter;
00985 
00986   bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
00987                         AllocaSlices::iterator B, AllocaSlices::iterator E,
00988                         int64_t BeginOffset, int64_t EndOffset,
00989                         ArrayRef<AllocaSlices::iterator> SplitUses);
00990   bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
00991   bool runOnAlloca(AllocaInst &AI);
00992   void clobberUse(Use &U);
00993   void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
00994   bool promoteAllocas(Function &F);
00995 };
00996 }
00997 
00998 char SROA::ID = 0;
00999 
01000 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
01001   return new SROA(RequiresDomTree);
01002 }
01003 
01004 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
01005                       false, false)
01006 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
01007 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
01008                     false, false)
01009 
01010 /// Walk the range of a partitioning looking for a common type to cover this
01011 /// sequence of slices.
01012 static Type *findCommonType(AllocaSlices::const_iterator B,
01013                             AllocaSlices::const_iterator E,
01014                             uint64_t EndOffset) {
01015   Type *Ty = nullptr;
01016   bool TyIsCommon = true;
01017   IntegerType *ITy = nullptr;
01018 
01019   // Note that we need to look at *every* alloca slice's Use to ensure we
01020   // always get consistent results regardless of the order of slices.
01021   for (AllocaSlices::const_iterator I = B; I != E; ++I) {
01022     Use *U = I->getUse();
01023     if (isa<IntrinsicInst>(*U->getUser()))
01024       continue;
01025     if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
01026       continue;
01027 
01028     Type *UserTy = nullptr;
01029     if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01030       UserTy = LI->getType();
01031     } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01032       UserTy = SI->getValueOperand()->getType();
01033     }
01034 
01035     if (!UserTy || (Ty && Ty != UserTy))
01036       TyIsCommon = false; // Give up on anything but an iN type.
01037     else
01038       Ty = UserTy;
01039 
01040     if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
01041       // If the type is larger than the partition, skip it. We only encounter
01042       // this for split integer operations where we want to use the type of the
01043       // entity causing the split. Also skip if the type is not a byte width
01044       // multiple.
01045       if (UserITy->getBitWidth() % 8 != 0 ||
01046           UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
01047         continue;
01048 
01049       // Track the largest bitwidth integer type used in this way in case there
01050       // is no common type.
01051       if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
01052         ITy = UserITy;
01053     }
01054   }
01055 
01056   return TyIsCommon ? Ty : ITy;
01057 }
01058 
01059 /// PHI instructions that use an alloca and are subsequently loaded can be
01060 /// rewritten to load both input pointers in the pred blocks and then PHI the
01061 /// results, allowing the load of the alloca to be promoted.
01062 /// From this:
01063 ///   %P2 = phi [i32* %Alloca, i32* %Other]
01064 ///   %V = load i32* %P2
01065 /// to:
01066 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01067 ///   ...
01068 ///   %V2 = load i32* %Other
01069 ///   ...
01070 ///   %V = phi [i32 %V1, i32 %V2]
01071 ///
01072 /// We can do this to a select if its only uses are loads and if the operands
01073 /// to the select can be loaded unconditionally.
01074 ///
01075 /// FIXME: This should be hoisted into a generic utility, likely in
01076 /// Transforms/Util/Local.h
01077 static bool isSafePHIToSpeculate(PHINode &PN,
01078                                  const DataLayout *DL = nullptr) {
01079   // For now, we can only do this promotion if the load is in the same block
01080   // as the PHI, and if there are no stores between the phi and load.
01081   // TODO: Allow recursive phi users.
01082   // TODO: Allow stores.
01083   BasicBlock *BB = PN.getParent();
01084   unsigned MaxAlign = 0;
01085   bool HaveLoad = false;
01086   for (User *U : PN.users()) {
01087     LoadInst *LI = dyn_cast<LoadInst>(U);
01088     if (!LI || !LI->isSimple())
01089       return false;
01090 
01091     // For now we only allow loads in the same block as the PHI.  This is
01092     // a common case that happens when instcombine merges two loads through
01093     // a PHI.
01094     if (LI->getParent() != BB)
01095       return false;
01096 
01097     // Ensure that there are no instructions between the PHI and the load that
01098     // could store.
01099     for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
01100       if (BBI->mayWriteToMemory())
01101         return false;
01102 
01103     MaxAlign = std::max(MaxAlign, LI->getAlignment());
01104     HaveLoad = true;
01105   }
01106 
01107   if (!HaveLoad)
01108     return false;
01109 
01110   // We can only transform this if it is safe to push the loads into the
01111   // predecessor blocks. The only thing to watch out for is that we can't put
01112   // a possibly trapping load in the predecessor if it is a critical edge.
01113   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
01114     TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
01115     Value *InVal = PN.getIncomingValue(Idx);
01116 
01117     // If the value is produced by the terminator of the predecessor (an
01118     // invoke) or it has side-effects, there is no valid place to put a load
01119     // in the predecessor.
01120     if (TI == InVal || TI->mayHaveSideEffects())
01121       return false;
01122 
01123     // If the predecessor has a single successor, then the edge isn't
01124     // critical.
01125     if (TI->getNumSuccessors() == 1)
01126       continue;
01127 
01128     // If this pointer is always safe to load, or if we can prove that there
01129     // is already a load in the block, then we can move the load to the pred
01130     // block.
01131     if (InVal->isDereferenceablePointer() ||
01132         isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
01133       continue;
01134 
01135     return false;
01136   }
01137 
01138   return true;
01139 }
01140 
01141 static void speculatePHINodeLoads(PHINode &PN) {
01142   DEBUG(dbgs() << "    original: " << PN << "\n");
01143 
01144   Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
01145   IRBuilderTy PHIBuilder(&PN);
01146   PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
01147                                         PN.getName() + ".sroa.speculated");
01148 
01149   // Get the TBAA tag and alignment to use from one of the loads.  It doesn't
01150   // matter which one we get and if any differ.
01151   LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
01152   MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
01153   unsigned Align = SomeLoad->getAlignment();
01154 
01155   // Rewrite all loads of the PN to use the new PHI.
01156   while (!PN.use_empty()) {
01157     LoadInst *LI = cast<LoadInst>(PN.user_back());
01158     LI->replaceAllUsesWith(NewPN);
01159     LI->eraseFromParent();
01160   }
01161 
01162   // Inject loads into all of the pred blocks.
01163   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
01164     BasicBlock *Pred = PN.getIncomingBlock(Idx);
01165     TerminatorInst *TI = Pred->getTerminator();
01166     Value *InVal = PN.getIncomingValue(Idx);
01167     IRBuilderTy PredBuilder(TI);
01168 
01169     LoadInst *Load = PredBuilder.CreateLoad(
01170         InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
01171     ++NumLoadsSpeculated;
01172     Load->setAlignment(Align);
01173     if (TBAATag)
01174       Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
01175     NewPN->addIncoming(Load, Pred);
01176   }
01177 
01178   DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
01179   PN.eraseFromParent();
01180 }
01181 
01182 /// Select instructions that use an alloca and are subsequently loaded can be
01183 /// rewritten to load both input pointers and then select between the result,
01184 /// allowing the load of the alloca to be promoted.
01185 /// From this:
01186 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
01187 ///   %V = load i32* %P2
01188 /// to:
01189 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01190 ///   %V2 = load i32* %Other
01191 ///   %V = select i1 %cond, i32 %V1, i32 %V2
01192 ///
01193 /// We can do this to a select if its only uses are loads and if the operand
01194 /// to the select can be loaded unconditionally.
01195 static bool isSafeSelectToSpeculate(SelectInst &SI,
01196                                     const DataLayout *DL = nullptr) {
01197   Value *TValue = SI.getTrueValue();
01198   Value *FValue = SI.getFalseValue();
01199   bool TDerefable = TValue->isDereferenceablePointer();
01200   bool FDerefable = FValue->isDereferenceablePointer();
01201 
01202   for (User *U : SI.users()) {
01203     LoadInst *LI = dyn_cast<LoadInst>(U);
01204     if (!LI || !LI->isSimple())
01205       return false;
01206 
01207     // Both operands to the select need to be dereferencable, either
01208     // absolutely (e.g. allocas) or at this point because we can see other
01209     // accesses to it.
01210     if (!TDerefable &&
01211         !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
01212       return false;
01213     if (!FDerefable &&
01214         !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
01215       return false;
01216   }
01217 
01218   return true;
01219 }
01220 
01221 static void speculateSelectInstLoads(SelectInst &SI) {
01222   DEBUG(dbgs() << "    original: " << SI << "\n");
01223 
01224   IRBuilderTy IRB(&SI);
01225   Value *TV = SI.getTrueValue();
01226   Value *FV = SI.getFalseValue();
01227   // Replace the loads of the select with a select of two loads.
01228   while (!SI.use_empty()) {
01229     LoadInst *LI = cast<LoadInst>(SI.user_back());
01230     assert(LI->isSimple() && "We only speculate simple loads");
01231 
01232     IRB.SetInsertPoint(LI);
01233     LoadInst *TL =
01234         IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
01235     LoadInst *FL =
01236         IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
01237     NumLoadsSpeculated += 2;
01238 
01239     // Transfer alignment and TBAA info if present.
01240     TL->setAlignment(LI->getAlignment());
01241     FL->setAlignment(LI->getAlignment());
01242     if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
01243       TL->setMetadata(LLVMContext::MD_tbaa, Tag);
01244       FL->setMetadata(LLVMContext::MD_tbaa, Tag);
01245     }
01246 
01247     Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
01248                                 LI->getName() + ".sroa.speculated");
01249 
01250     DEBUG(dbgs() << "          speculated to: " << *V << "\n");
01251     LI->replaceAllUsesWith(V);
01252     LI->eraseFromParent();
01253   }
01254   SI.eraseFromParent();
01255 }
01256 
01257 /// \brief Build a GEP out of a base pointer and indices.
01258 ///
01259 /// This will return the BasePtr if that is valid, or build a new GEP
01260 /// instruction using the IRBuilder if GEP-ing is needed.
01261 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
01262                        SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
01263   if (Indices.empty())
01264     return BasePtr;
01265 
01266   // A single zero index is a no-op, so check for this and avoid building a GEP
01267   // in that case.
01268   if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
01269     return BasePtr;
01270 
01271   return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
01272 }
01273 
01274 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
01275 /// TargetTy without changing the offset of the pointer.
01276 ///
01277 /// This routine assumes we've already established a properly offset GEP with
01278 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
01279 /// zero-indices down through type layers until we find one the same as
01280 /// TargetTy. If we can't find one with the same type, we at least try to use
01281 /// one with the same size. If none of that works, we just produce the GEP as
01282 /// indicated by Indices to have the correct offset.
01283 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
01284                                     Value *BasePtr, Type *Ty, Type *TargetTy,
01285                                     SmallVectorImpl<Value *> &Indices,
01286                                     Twine NamePrefix) {
01287   if (Ty == TargetTy)
01288     return buildGEP(IRB, BasePtr, Indices, NamePrefix);
01289 
01290   // Pointer size to use for the indices.
01291   unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
01292 
01293   // See if we can descend into a struct and locate a field with the correct
01294   // type.
01295   unsigned NumLayers = 0;
01296   Type *ElementTy = Ty;
01297   do {
01298     if (ElementTy->isPointerTy())
01299       break;
01300 
01301     if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
01302       ElementTy = ArrayTy->getElementType();
01303       Indices.push_back(IRB.getIntN(PtrSize, 0));
01304     } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
01305       ElementTy = VectorTy->getElementType();
01306       Indices.push_back(IRB.getInt32(0));
01307     } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
01308       if (STy->element_begin() == STy->element_end())
01309         break; // Nothing left to descend into.
01310       ElementTy = *STy->element_begin();
01311       Indices.push_back(IRB.getInt32(0));
01312     } else {
01313       break;
01314     }
01315     ++NumLayers;
01316   } while (ElementTy != TargetTy);
01317   if (ElementTy != TargetTy)
01318     Indices.erase(Indices.end() - NumLayers, Indices.end());
01319 
01320   return buildGEP(IRB, BasePtr, Indices, NamePrefix);
01321 }
01322 
01323 /// \brief Recursively compute indices for a natural GEP.
01324 ///
01325 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
01326 /// element types adding appropriate indices for the GEP.
01327 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
01328                                        Value *Ptr, Type *Ty, APInt &Offset,
01329                                        Type *TargetTy,
01330                                        SmallVectorImpl<Value *> &Indices,
01331                                        Twine NamePrefix) {
01332   if (Offset == 0)
01333     return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
01334 
01335   // We can't recurse through pointer types.
01336   if (Ty->isPointerTy())
01337     return nullptr;
01338 
01339   // We try to analyze GEPs over vectors here, but note that these GEPs are
01340   // extremely poorly defined currently. The long-term goal is to remove GEPing
01341   // over a vector from the IR completely.
01342   if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
01343     unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
01344     if (ElementSizeInBits % 8 != 0) {
01345       // GEPs over non-multiple of 8 size vector elements are invalid.
01346       return nullptr;
01347     }
01348     APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
01349     APInt NumSkippedElements = Offset.sdiv(ElementSize);
01350     if (NumSkippedElements.ugt(VecTy->getNumElements()))
01351       return nullptr;
01352     Offset -= NumSkippedElements * ElementSize;
01353     Indices.push_back(IRB.getInt(NumSkippedElements));
01354     return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
01355                                     Offset, TargetTy, Indices, NamePrefix);
01356   }
01357 
01358   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
01359     Type *ElementTy = ArrTy->getElementType();
01360     APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
01361     APInt NumSkippedElements = Offset.sdiv(ElementSize);
01362     if (NumSkippedElements.ugt(ArrTy->getNumElements()))
01363       return nullptr;
01364 
01365     Offset -= NumSkippedElements * ElementSize;
01366     Indices.push_back(IRB.getInt(NumSkippedElements));
01367     return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01368                                     Indices, NamePrefix);
01369   }
01370 
01371   StructType *STy = dyn_cast<StructType>(Ty);
01372   if (!STy)
01373     return nullptr;
01374 
01375   const StructLayout *SL = DL.getStructLayout(STy);
01376   uint64_t StructOffset = Offset.getZExtValue();
01377   if (StructOffset >= SL->getSizeInBytes())
01378     return nullptr;
01379   unsigned Index = SL->getElementContainingOffset(StructOffset);
01380   Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
01381   Type *ElementTy = STy->getElementType(Index);
01382   if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
01383     return nullptr; // The offset points into alignment padding.
01384 
01385   Indices.push_back(IRB.getInt32(Index));
01386   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01387                                   Indices, NamePrefix);
01388 }
01389 
01390 /// \brief Get a natural GEP from a base pointer to a particular offset and
01391 /// resulting in a particular type.
01392 ///
01393 /// The goal is to produce a "natural" looking GEP that works with the existing
01394 /// composite types to arrive at the appropriate offset and element type for
01395 /// a pointer. TargetTy is the element type the returned GEP should point-to if
01396 /// possible. We recurse by decreasing Offset, adding the appropriate index to
01397 /// Indices, and setting Ty to the result subtype.
01398 ///
01399 /// If no natural GEP can be constructed, this function returns null.
01400 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
01401                                       Value *Ptr, APInt Offset, Type *TargetTy,
01402                                       SmallVectorImpl<Value *> &Indices,
01403                                       Twine NamePrefix) {
01404   PointerType *Ty = cast<PointerType>(Ptr->getType());
01405 
01406   // Don't consider any GEPs through an i8* as natural unless the TargetTy is
01407   // an i8.
01408   if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
01409     return nullptr;
01410 
01411   Type *ElementTy = Ty->getElementType();
01412   if (!ElementTy->isSized())
01413     return nullptr; // We can't GEP through an unsized element.
01414   APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
01415   if (ElementSize == 0)
01416     return nullptr; // Zero-length arrays can't help us build a natural GEP.
01417   APInt NumSkippedElements = Offset.sdiv(ElementSize);
01418 
01419   Offset -= NumSkippedElements * ElementSize;
01420   Indices.push_back(IRB.getInt(NumSkippedElements));
01421   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01422                                   Indices, NamePrefix);
01423 }
01424 
01425 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
01426 /// resulting pointer has PointerTy.
01427 ///
01428 /// This tries very hard to compute a "natural" GEP which arrives at the offset
01429 /// and produces the pointer type desired. Where it cannot, it will try to use
01430 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
01431 /// fails, it will try to use an existing i8* and GEP to the byte offset and
01432 /// bitcast to the type.
01433 ///
01434 /// The strategy for finding the more natural GEPs is to peel off layers of the
01435 /// pointer, walking back through bit casts and GEPs, searching for a base
01436 /// pointer from which we can compute a natural GEP with the desired
01437 /// properties. The algorithm tries to fold as many constant indices into
01438 /// a single GEP as possible, thus making each GEP more independent of the
01439 /// surrounding code.
01440 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
01441                              APInt Offset, Type *PointerTy,
01442                              Twine NamePrefix) {
01443   // Even though we don't look through PHI nodes, we could be called on an
01444   // instruction in an unreachable block, which may be on a cycle.
01445   SmallPtrSet<Value *, 4> Visited;
01446   Visited.insert(Ptr);
01447   SmallVector<Value *, 4> Indices;
01448 
01449   // We may end up computing an offset pointer that has the wrong type. If we
01450   // never are able to compute one directly that has the correct type, we'll
01451   // fall back to it, so keep it around here.
01452   Value *OffsetPtr = nullptr;
01453 
01454   // Remember any i8 pointer we come across to re-use if we need to do a raw
01455   // byte offset.
01456   Value *Int8Ptr = nullptr;
01457   APInt Int8PtrOffset(Offset.getBitWidth(), 0);
01458 
01459   Type *TargetTy = PointerTy->getPointerElementType();
01460 
01461   do {
01462     // First fold any existing GEPs into the offset.
01463     while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
01464       APInt GEPOffset(Offset.getBitWidth(), 0);
01465       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
01466         break;
01467       Offset += GEPOffset;
01468       Ptr = GEP->getPointerOperand();
01469       if (!Visited.insert(Ptr))
01470         break;
01471     }
01472 
01473     // See if we can perform a natural GEP here.
01474     Indices.clear();
01475     if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
01476                                            Indices, NamePrefix)) {
01477       if (P->getType() == PointerTy) {
01478         // Zap any offset pointer that we ended up computing in previous rounds.
01479         if (OffsetPtr && OffsetPtr->use_empty())
01480           if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
01481             I->eraseFromParent();
01482         return P;
01483       }
01484       if (!OffsetPtr) {
01485         OffsetPtr = P;
01486       }
01487     }
01488 
01489     // Stash this pointer if we've found an i8*.
01490     if (Ptr->getType()->isIntegerTy(8)) {
01491       Int8Ptr = Ptr;
01492       Int8PtrOffset = Offset;
01493     }
01494 
01495     // Peel off a layer of the pointer and update the offset appropriately.
01496     if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
01497       Ptr = cast<Operator>(Ptr)->getOperand(0);
01498     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
01499       if (GA->mayBeOverridden())
01500         break;
01501       Ptr = GA->getAliasee();
01502     } else {
01503       break;
01504     }
01505     assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
01506   } while (Visited.insert(Ptr));
01507 
01508   if (!OffsetPtr) {
01509     if (!Int8Ptr) {
01510       Int8Ptr = IRB.CreateBitCast(
01511           Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
01512           NamePrefix + "sroa_raw_cast");
01513       Int8PtrOffset = Offset;
01514     }
01515 
01516     OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
01517       IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
01518                             NamePrefix + "sroa_raw_idx");
01519   }
01520   Ptr = OffsetPtr;
01521 
01522   // On the off chance we were targeting i8*, guard the bitcast here.
01523   if (Ptr->getType() != PointerTy)
01524     Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
01525 
01526   return Ptr;
01527 }
01528 
01529 /// \brief Test whether we can convert a value from the old to the new type.
01530 ///
01531 /// This predicate should be used to guard calls to convertValue in order to
01532 /// ensure that we only try to convert viable values. The strategy is that we
01533 /// will peel off single element struct and array wrappings to get to an
01534 /// underlying value, and convert that value.
01535 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
01536   if (OldTy == NewTy)
01537     return true;
01538   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
01539     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
01540       if (NewITy->getBitWidth() >= OldITy->getBitWidth())
01541         return true;
01542   if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
01543     return false;
01544   if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
01545     return false;
01546 
01547   // We can convert pointers to integers and vice-versa. Same for vectors
01548   // of pointers and integers.
01549   OldTy = OldTy->getScalarType();
01550   NewTy = NewTy->getScalarType();
01551   if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
01552     if (NewTy->isPointerTy() && OldTy->isPointerTy())
01553       return true;
01554     if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
01555       return true;
01556     return false;
01557   }
01558 
01559   return true;
01560 }
01561 
01562 /// \brief Generic routine to convert an SSA value to a value of a different
01563 /// type.
01564 ///
01565 /// This will try various different casting techniques, such as bitcasts,
01566 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
01567 /// two types for viability with this routine.
01568 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
01569                            Type *NewTy) {
01570   Type *OldTy = V->getType();
01571   assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
01572 
01573   if (OldTy == NewTy)
01574     return V;
01575 
01576   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
01577     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
01578       if (NewITy->getBitWidth() > OldITy->getBitWidth())
01579         return IRB.CreateZExt(V, NewITy);
01580 
01581   // See if we need inttoptr for this type pair. A cast involving both scalars
01582   // and vectors requires and additional bitcast.
01583   if (OldTy->getScalarType()->isIntegerTy() &&
01584       NewTy->getScalarType()->isPointerTy()) {
01585     // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
01586     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
01587       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
01588                                 NewTy);
01589 
01590     // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
01591     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
01592       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
01593                                 NewTy);
01594 
01595     return IRB.CreateIntToPtr(V, NewTy);
01596   }
01597 
01598   // See if we need ptrtoint for this type pair. A cast involving both scalars
01599   // and vectors requires and additional bitcast.
01600   if (OldTy->getScalarType()->isPointerTy() &&
01601       NewTy->getScalarType()->isIntegerTy()) {
01602     // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
01603     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
01604       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
01605                                NewTy);
01606 
01607     // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
01608     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
01609       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
01610                                NewTy);
01611 
01612     return IRB.CreatePtrToInt(V, NewTy);
01613   }
01614 
01615   return IRB.CreateBitCast(V, NewTy);
01616 }
01617 
01618 /// \brief Test whether the given slice use can be promoted to a vector.
01619 ///
01620 /// This function is called to test each entry in a partioning which is slated
01621 /// for a single slice.
01622 static bool isVectorPromotionViableForSlice(
01623     const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
01624     uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
01625     AllocaSlices::const_iterator I) {
01626   // First validate the slice offsets.
01627   uint64_t BeginOffset =
01628       std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
01629   uint64_t BeginIndex = BeginOffset / ElementSize;
01630   if (BeginIndex * ElementSize != BeginOffset ||
01631       BeginIndex >= Ty->getNumElements())
01632     return false;
01633   uint64_t EndOffset =
01634       std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
01635   uint64_t EndIndex = EndOffset / ElementSize;
01636   if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
01637     return false;
01638 
01639   assert(EndIndex > BeginIndex && "Empty vector!");
01640   uint64_t NumElements = EndIndex - BeginIndex;
01641   Type *SliceTy =
01642       (NumElements == 1) ? Ty->getElementType()
01643                          : VectorType::get(Ty->getElementType(), NumElements);
01644 
01645   Type *SplitIntTy =
01646       Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
01647 
01648   Use *U = I->getUse();
01649 
01650   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
01651     if (MI->isVolatile())
01652       return false;
01653     if (!I->isSplittable())
01654       return false; // Skip any unsplittable intrinsics.
01655   } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
01656     // Disable vector promotion when there are loads or stores of an FCA.
01657     return false;
01658   } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01659     if (LI->isVolatile())
01660       return false;
01661     Type *LTy = LI->getType();
01662     if (SliceBeginOffset > I->beginOffset() ||
01663         SliceEndOffset < I->endOffset()) {
01664       assert(LTy->isIntegerTy());
01665       LTy = SplitIntTy;
01666     }
01667     if (!canConvertValue(DL, SliceTy, LTy))
01668       return false;
01669   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01670     if (SI->isVolatile())
01671       return false;
01672     Type *STy = SI->getValueOperand()->getType();
01673     if (SliceBeginOffset > I->beginOffset() ||
01674         SliceEndOffset < I->endOffset()) {
01675       assert(STy->isIntegerTy());
01676       STy = SplitIntTy;
01677     }
01678     if (!canConvertValue(DL, STy, SliceTy))
01679       return false;
01680   } else {
01681     return false;
01682   }
01683 
01684   return true;
01685 }
01686 
01687 /// \brief Test whether the given alloca partitioning and range of slices can be
01688 /// promoted to a vector.
01689 ///
01690 /// This is a quick test to check whether we can rewrite a particular alloca
01691 /// partition (and its newly formed alloca) into a vector alloca with only
01692 /// whole-vector loads and stores such that it could be promoted to a vector
01693 /// SSA value. We only can ensure this for a limited set of operations, and we
01694 /// don't want to do the rewrites unless we are confident that the result will
01695 /// be promotable, so we have an early test here.
01696 static bool
01697 isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
01698                         uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
01699                         AllocaSlices::const_iterator I,
01700                         AllocaSlices::const_iterator E,
01701                         ArrayRef<AllocaSlices::iterator> SplitUses) {
01702   VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
01703   if (!Ty)
01704     return false;
01705 
01706   uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
01707 
01708   // While the definition of LLVM vectors is bitpacked, we don't support sizes
01709   // that aren't byte sized.
01710   if (ElementSize % 8)
01711     return false;
01712   assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
01713          "vector size not a multiple of element size?");
01714   ElementSize /= 8;
01715 
01716   for (; I != E; ++I)
01717     if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
01718                                          SliceEndOffset, Ty, ElementSize, I))
01719       return false;
01720 
01721   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
01722                                                         SUE = SplitUses.end();
01723        SUI != SUE; ++SUI)
01724     if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
01725                                          SliceEndOffset, Ty, ElementSize, *SUI))
01726       return false;
01727 
01728   return true;
01729 }
01730 
01731 /// \brief Test whether a slice of an alloca is valid for integer widening.
01732 ///
01733 /// This implements the necessary checking for the \c isIntegerWideningViable
01734 /// test below on a single slice of the alloca.
01735 static bool isIntegerWideningViableForSlice(const DataLayout &DL,
01736                                             Type *AllocaTy,
01737                                             uint64_t AllocBeginOffset,
01738                                             uint64_t Size, AllocaSlices &S,
01739                                             AllocaSlices::const_iterator I,
01740                                             bool &WholeAllocaOp) {
01741   uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
01742   uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
01743 
01744   // We can't reasonably handle cases where the load or store extends past
01745   // the end of the aloca's type and into its padding.
01746   if (RelEnd > Size)
01747     return false;
01748 
01749   Use *U = I->getUse();
01750 
01751   if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01752     if (LI->isVolatile())
01753       return false;
01754     if (RelBegin == 0 && RelEnd == Size)
01755       WholeAllocaOp = true;
01756     if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
01757       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
01758         return false;
01759     } else if (RelBegin != 0 || RelEnd != Size ||
01760                !canConvertValue(DL, AllocaTy, LI->getType())) {
01761       // Non-integer loads need to be convertible from the alloca type so that
01762       // they are promotable.
01763       return false;
01764     }
01765   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01766     Type *ValueTy = SI->getValueOperand()->getType();
01767     if (SI->isVolatile())
01768       return false;
01769     if (RelBegin == 0 && RelEnd == Size)
01770       WholeAllocaOp = true;
01771     if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
01772       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
01773         return false;
01774     } else if (RelBegin != 0 || RelEnd != Size ||
01775                !canConvertValue(DL, ValueTy, AllocaTy)) {
01776       // Non-integer stores need to be convertible to the alloca type so that
01777       // they are promotable.
01778       return false;
01779     }
01780   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
01781     if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
01782       return false;
01783     if (!I->isSplittable())
01784       return false; // Skip any unsplittable intrinsics.
01785   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
01786     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
01787         II->getIntrinsicID() != Intrinsic::lifetime_end)
01788       return false;
01789   } else {
01790     return false;
01791   }
01792 
01793   return true;
01794 }
01795 
01796 /// \brief Test whether the given alloca partition's integer operations can be
01797 /// widened to promotable ones.
01798 ///
01799 /// This is a quick test to check whether we can rewrite the integer loads and
01800 /// stores to a particular alloca into wider loads and stores and be able to
01801 /// promote the resulting alloca.
01802 static bool
01803 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
01804                         uint64_t AllocBeginOffset, AllocaSlices &S,
01805                         AllocaSlices::const_iterator I,
01806                         AllocaSlices::const_iterator E,
01807                         ArrayRef<AllocaSlices::iterator> SplitUses) {
01808   uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
01809   // Don't create integer types larger than the maximum bitwidth.
01810   if (SizeInBits > IntegerType::MAX_INT_BITS)
01811     return false;
01812 
01813   // Don't try to handle allocas with bit-padding.
01814   if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
01815     return false;
01816 
01817   // We need to ensure that an integer type with the appropriate bitwidth can
01818   // be converted to the alloca type, whatever that is. We don't want to force
01819   // the alloca itself to have an integer type if there is a more suitable one.
01820   Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
01821   if (!canConvertValue(DL, AllocaTy, IntTy) ||
01822       !canConvertValue(DL, IntTy, AllocaTy))
01823     return false;
01824 
01825   uint64_t Size = DL.getTypeStoreSize(AllocaTy);
01826 
01827   // While examining uses, we ensure that the alloca has a covering load or
01828   // store. We don't want to widen the integer operations only to fail to
01829   // promote due to some other unsplittable entry (which we may make splittable
01830   // later). However, if there are only splittable uses, go ahead and assume
01831   // that we cover the alloca.
01832   bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
01833 
01834   for (; I != E; ++I)
01835     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
01836                                          S, I, WholeAllocaOp))
01837       return false;
01838 
01839   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
01840                                                         SUE = SplitUses.end();
01841        SUI != SUE; ++SUI)
01842     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
01843                                          S, *SUI, WholeAllocaOp))
01844       return false;
01845 
01846   return WholeAllocaOp;
01847 }
01848 
01849 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
01850                              IntegerType *Ty, uint64_t Offset,
01851                              const Twine &Name) {
01852   DEBUG(dbgs() << "       start: " << *V << "\n");
01853   IntegerType *IntTy = cast<IntegerType>(V->getType());
01854   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
01855          "Element extends past full value");
01856   uint64_t ShAmt = 8*Offset;
01857   if (DL.isBigEndian())
01858     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
01859   if (ShAmt) {
01860     V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
01861     DEBUG(dbgs() << "     shifted: " << *V << "\n");
01862   }
01863   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
01864          "Cannot extract to a larger integer!");
01865   if (Ty != IntTy) {
01866     V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
01867     DEBUG(dbgs() << "     trunced: " << *V << "\n");
01868   }
01869   return V;
01870 }
01871 
01872 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
01873                             Value *V, uint64_t Offset, const Twine &Name) {
01874   IntegerType *IntTy = cast<IntegerType>(Old->getType());
01875   IntegerType *Ty = cast<IntegerType>(V->getType());
01876   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
01877          "Cannot insert a larger integer!");
01878   DEBUG(dbgs() << "       start: " << *V << "\n");
01879   if (Ty != IntTy) {
01880     V = IRB.CreateZExt(V, IntTy, Name + ".ext");
01881     DEBUG(dbgs() << "    extended: " << *V << "\n");
01882   }
01883   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
01884          "Element store outside of alloca store");
01885   uint64_t ShAmt = 8*Offset;
01886   if (DL.isBigEndian())
01887     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
01888   if (ShAmt) {
01889     V = IRB.CreateShl(V, ShAmt, Name + ".shift");
01890     DEBUG(dbgs() << "     shifted: " << *V << "\n");
01891   }
01892 
01893   if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
01894     APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
01895     Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
01896     DEBUG(dbgs() << "      masked: " << *Old << "\n");
01897     V = IRB.CreateOr(Old, V, Name + ".insert");
01898     DEBUG(dbgs() << "    inserted: " << *V << "\n");
01899   }
01900   return V;
01901 }
01902 
01903 static Value *extractVector(IRBuilderTy &IRB, Value *V,
01904                             unsigned BeginIndex, unsigned EndIndex,
01905                             const Twine &Name) {
01906   VectorType *VecTy = cast<VectorType>(V->getType());
01907   unsigned NumElements = EndIndex - BeginIndex;
01908   assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
01909 
01910   if (NumElements == VecTy->getNumElements())
01911     return V;
01912 
01913   if (NumElements == 1) {
01914     V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
01915                                  Name + ".extract");
01916     DEBUG(dbgs() << "     extract: " << *V << "\n");
01917     return V;
01918   }
01919 
01920   SmallVector<Constant*, 8> Mask;
01921   Mask.reserve(NumElements);
01922   for (unsigned i = BeginIndex; i != EndIndex; ++i)
01923     Mask.push_back(IRB.getInt32(i));
01924   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
01925                               ConstantVector::get(Mask),
01926                               Name + ".extract");
01927   DEBUG(dbgs() << "     shuffle: " << *V << "\n");
01928   return V;
01929 }
01930 
01931 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
01932                            unsigned BeginIndex, const Twine &Name) {
01933   VectorType *VecTy = cast<VectorType>(Old->getType());
01934   assert(VecTy && "Can only insert a vector into a vector");
01935 
01936   VectorType *Ty = dyn_cast<VectorType>(V->getType());
01937   if (!Ty) {
01938     // Single element to insert.
01939     V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
01940                                 Name + ".insert");
01941     DEBUG(dbgs() <<  "     insert: " << *V << "\n");
01942     return V;
01943   }
01944 
01945   assert(Ty->getNumElements() <= VecTy->getNumElements() &&
01946          "Too many elements!");
01947   if (Ty->getNumElements() == VecTy->getNumElements()) {
01948     assert(V->getType() == VecTy && "Vector type mismatch");
01949     return V;
01950   }
01951   unsigned EndIndex = BeginIndex + Ty->getNumElements();
01952 
01953   // When inserting a smaller vector into the larger to store, we first
01954   // use a shuffle vector to widen it with undef elements, and then
01955   // a second shuffle vector to select between the loaded vector and the
01956   // incoming vector.
01957   SmallVector<Constant*, 8> Mask;
01958   Mask.reserve(VecTy->getNumElements());
01959   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
01960     if (i >= BeginIndex && i < EndIndex)
01961       Mask.push_back(IRB.getInt32(i - BeginIndex));
01962     else
01963       Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
01964   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
01965                               ConstantVector::get(Mask),
01966                               Name + ".expand");
01967   DEBUG(dbgs() << "    shuffle: " << *V << "\n");
01968 
01969   Mask.clear();
01970   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
01971     Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
01972 
01973   V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
01974 
01975   DEBUG(dbgs() << "    blend: " << *V << "\n");
01976   return V;
01977 }
01978 
01979 namespace {
01980 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
01981 /// to use a new alloca.
01982 ///
01983 /// Also implements the rewriting to vector-based accesses when the partition
01984 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
01985 /// lives here.
01986 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
01987   // Befriend the base class so it can delegate to private visit methods.
01988   friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
01989   typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
01990 
01991   const DataLayout &DL;
01992   AllocaSlices &S;
01993   SROA &Pass;
01994   AllocaInst &OldAI, &NewAI;
01995   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
01996   Type *NewAllocaTy;
01997 
01998   // If we are rewriting an alloca partition which can be written as pure
01999   // vector operations, we stash extra information here. When VecTy is
02000   // non-null, we have some strict guarantees about the rewritten alloca:
02001   //   - The new alloca is exactly the size of the vector type here.
02002   //   - The accesses all either map to the entire vector or to a single
02003   //     element.
02004   //   - The set of accessing instructions is only one of those handled above
02005   //     in isVectorPromotionViable. Generally these are the same access kinds
02006   //     which are promotable via mem2reg.
02007   VectorType *VecTy;
02008   Type *ElementTy;
02009   uint64_t ElementSize;
02010 
02011   // This is a convenience and flag variable that will be null unless the new
02012   // alloca's integer operations should be widened to this integer type due to
02013   // passing isIntegerWideningViable above. If it is non-null, the desired
02014   // integer type will be stored here for easy access during rewriting.
02015   IntegerType *IntTy;
02016 
02017   // The original offset of the slice currently being rewritten relative to
02018   // the original alloca.
02019   uint64_t BeginOffset, EndOffset;
02020   // The new offsets of the slice currently being rewritten relative to the
02021   // original alloca.
02022   uint64_t NewBeginOffset, NewEndOffset;
02023 
02024   uint64_t SliceSize;
02025   bool IsSplittable;
02026   bool IsSplit;
02027   Use *OldUse;
02028   Instruction *OldPtr;
02029 
02030   // Track post-rewrite users which are PHI nodes and Selects.
02031   SmallPtrSetImpl<PHINode *> &PHIUsers;
02032   SmallPtrSetImpl<SelectInst *> &SelectUsers;
02033 
02034   // Utility IR builder, whose name prefix is setup for each visited use, and
02035   // the insertion point is set to point to the user.
02036   IRBuilderTy IRB;
02037 
02038 public:
02039   AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
02040                       AllocaInst &OldAI, AllocaInst &NewAI,
02041                       uint64_t NewAllocaBeginOffset,
02042                       uint64_t NewAllocaEndOffset, bool IsVectorPromotable,
02043                       bool IsIntegerPromotable,
02044                       SmallPtrSetImpl<PHINode *> &PHIUsers,
02045                       SmallPtrSetImpl<SelectInst *> &SelectUsers)
02046       : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
02047         NewAllocaBeginOffset(NewAllocaBeginOffset),
02048         NewAllocaEndOffset(NewAllocaEndOffset),
02049         NewAllocaTy(NewAI.getAllocatedType()),
02050         VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : nullptr),
02051         ElementTy(VecTy ? VecTy->getElementType() : nullptr),
02052         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
02053         IntTy(IsIntegerPromotable
02054                   ? Type::getIntNTy(
02055                         NewAI.getContext(),
02056                         DL.getTypeSizeInBits(NewAI.getAllocatedType()))
02057                   : nullptr),
02058         BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
02059         OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
02060         IRB(NewAI.getContext(), ConstantFolder()) {
02061     if (VecTy) {
02062       assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
02063              "Only multiple-of-8 sized vector elements are viable");
02064       ++NumVectorized;
02065     }
02066     assert((!IsVectorPromotable && !IsIntegerPromotable) ||
02067            IsVectorPromotable != IsIntegerPromotable);
02068   }
02069 
02070   bool visit(AllocaSlices::const_iterator I) {
02071     bool CanSROA = true;
02072     BeginOffset = I->beginOffset();
02073     EndOffset = I->endOffset();
02074     IsSplittable = I->isSplittable();
02075     IsSplit =
02076         BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
02077 
02078     // Compute the intersecting offset range.
02079     assert(BeginOffset < NewAllocaEndOffset);
02080     assert(EndOffset > NewAllocaBeginOffset);
02081     NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
02082     NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
02083 
02084     SliceSize = NewEndOffset - NewBeginOffset;
02085 
02086     OldUse = I->getUse();
02087     OldPtr = cast<Instruction>(OldUse->get());
02088 
02089     Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
02090     IRB.SetInsertPoint(OldUserI);
02091     IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
02092     IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
02093 
02094     CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
02095     if (VecTy || IntTy)
02096       assert(CanSROA);
02097     return CanSROA;
02098   }
02099 
02100 private:
02101   // Make sure the other visit overloads are visible.
02102   using Base::visit;
02103 
02104   // Every instruction which can end up as a user must have a rewrite rule.
02105   bool visitInstruction(Instruction &I) {
02106     DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
02107     llvm_unreachable("No rewrite rule for this instruction!");
02108   }
02109 
02110   Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
02111     // Note that the offset computation can use BeginOffset or NewBeginOffset
02112     // interchangeably for unsplit slices.
02113     assert(IsSplit || BeginOffset == NewBeginOffset);
02114     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02115 
02116 #ifndef NDEBUG
02117     StringRef OldName = OldPtr->getName();
02118     // Skip through the last '.sroa.' component of the name.
02119     size_t LastSROAPrefix = OldName.rfind(".sroa.");
02120     if (LastSROAPrefix != StringRef::npos) {
02121       OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
02122       // Look for an SROA slice index.
02123       size_t IndexEnd = OldName.find_first_not_of("0123456789");
02124       if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
02125         // Strip the index and look for the offset.
02126         OldName = OldName.substr(IndexEnd + 1);
02127         size_t OffsetEnd = OldName.find_first_not_of("0123456789");
02128         if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
02129           // Strip the offset.
02130           OldName = OldName.substr(OffsetEnd + 1);
02131       }
02132     }
02133     // Strip any SROA suffixes as well.
02134     OldName = OldName.substr(0, OldName.find(".sroa_"));
02135 #endif
02136 
02137     return getAdjustedPtr(IRB, DL, &NewAI,
02138                           APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
02139 #ifndef NDEBUG
02140                           Twine(OldName) + "."
02141 #else
02142                           Twine()
02143 #endif
02144                           );
02145   }
02146 
02147   /// \brief Compute suitable alignment to access this slice of the *new* alloca.
02148   ///
02149   /// You can optionally pass a type to this routine and if that type's ABI
02150   /// alignment is itself suitable, this will return zero.
02151   unsigned getSliceAlign(Type *Ty = nullptr) {
02152     unsigned NewAIAlign = NewAI.getAlignment();
02153     if (!NewAIAlign)
02154       NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
02155     unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
02156     return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
02157   }
02158 
02159   unsigned getIndex(uint64_t Offset) {
02160     assert(VecTy && "Can only call getIndex when rewriting a vector");
02161     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
02162     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
02163     uint32_t Index = RelOffset / ElementSize;
02164     assert(Index * ElementSize == RelOffset);
02165     return Index;
02166   }
02167 
02168   void deleteIfTriviallyDead(Value *V) {
02169     Instruction *I = cast<Instruction>(V);
02170     if (isInstructionTriviallyDead(I))
02171       Pass.DeadInsts.insert(I);
02172   }
02173 
02174   Value *rewriteVectorizedLoadInst() {
02175     unsigned BeginIndex = getIndex(NewBeginOffset);
02176     unsigned EndIndex = getIndex(NewEndOffset);
02177     assert(EndIndex > BeginIndex && "Empty vector!");
02178 
02179     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02180                                      "load");
02181     return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
02182   }
02183 
02184   Value *rewriteIntegerLoad(LoadInst &LI) {
02185     assert(IntTy && "We cannot insert an integer to the alloca");
02186     assert(!LI.isVolatile());
02187     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02188                                      "load");
02189     V = convertValue(DL, IRB, V, IntTy);
02190     assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
02191     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02192     if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
02193       V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
02194                          "extract");
02195     return V;
02196   }
02197 
02198   bool visitLoadInst(LoadInst &LI) {
02199     DEBUG(dbgs() << "    original: " << LI << "\n");
02200     Value *OldOp = LI.getOperand(0);
02201     assert(OldOp == OldPtr);
02202 
02203     Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
02204                              : LI.getType();
02205     bool IsPtrAdjusted = false;
02206     Value *V;
02207     if (VecTy) {
02208       V = rewriteVectorizedLoadInst();
02209     } else if (IntTy && LI.getType()->isIntegerTy()) {
02210       V = rewriteIntegerLoad(LI);
02211     } else if (NewBeginOffset == NewAllocaBeginOffset &&
02212                canConvertValue(DL, NewAllocaTy, LI.getType())) {
02213       V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02214                                 LI.isVolatile(), LI.getName());
02215     } else {
02216       Type *LTy = TargetTy->getPointerTo();
02217       V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
02218                                 getSliceAlign(TargetTy), LI.isVolatile(),
02219                                 LI.getName());
02220       IsPtrAdjusted = true;
02221     }
02222     V = convertValue(DL, IRB, V, TargetTy);
02223 
02224     if (IsSplit) {
02225       assert(!LI.isVolatile());
02226       assert(LI.getType()->isIntegerTy() &&
02227              "Only integer type loads and stores are split");
02228       assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
02229              "Split load isn't smaller than original load");
02230       assert(LI.getType()->getIntegerBitWidth() ==
02231              DL.getTypeStoreSizeInBits(LI.getType()) &&
02232              "Non-byte-multiple bit width");
02233       // Move the insertion point just past the load so that we can refer to it.
02234       IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
02235       // Create a placeholder value with the same type as LI to use as the
02236       // basis for the new value. This allows us to replace the uses of LI with
02237       // the computed value, and then replace the placeholder with LI, leaving
02238       // LI only used for this computation.
02239       Value *Placeholder
02240         = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
02241       V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
02242                         "insert");
02243       LI.replaceAllUsesWith(V);
02244       Placeholder->replaceAllUsesWith(&LI);
02245       delete Placeholder;
02246     } else {
02247       LI.replaceAllUsesWith(V);
02248     }
02249 
02250     Pass.DeadInsts.insert(&LI);
02251     deleteIfTriviallyDead(OldOp);
02252     DEBUG(dbgs() << "          to: " << *V << "\n");
02253     return !LI.isVolatile() && !IsPtrAdjusted;
02254   }
02255 
02256   bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
02257     if (V->getType() != VecTy) {
02258       unsigned BeginIndex = getIndex(NewBeginOffset);
02259       unsigned EndIndex = getIndex(NewEndOffset);
02260       assert(EndIndex > BeginIndex && "Empty vector!");
02261       unsigned NumElements = EndIndex - BeginIndex;
02262       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
02263       Type *SliceTy =
02264           (NumElements == 1) ? ElementTy
02265                              : VectorType::get(ElementTy, NumElements);
02266       if (V->getType() != SliceTy)
02267         V = convertValue(DL, IRB, V, SliceTy);
02268 
02269       // Mix in the existing elements.
02270       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02271                                          "load");
02272       V = insertVector(IRB, Old, V, BeginIndex, "vec");
02273     }
02274     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
02275     Pass.DeadInsts.insert(&SI);
02276 
02277     (void)Store;
02278     DEBUG(dbgs() << "          to: " << *Store << "\n");
02279     return true;
02280   }
02281 
02282   bool rewriteIntegerStore(Value *V, StoreInst &SI) {
02283     assert(IntTy && "We cannot extract an integer from the alloca");
02284     assert(!SI.isVolatile());
02285     if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
02286       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02287                                          "oldload");
02288       Old = convertValue(DL, IRB, Old, IntTy);
02289       assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
02290       uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
02291       V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
02292                         "insert");
02293     }
02294     V = convertValue(DL, IRB, V, NewAllocaTy);
02295     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
02296     Pass.DeadInsts.insert(&SI);
02297     (void)Store;
02298     DEBUG(dbgs() << "          to: " << *Store << "\n");
02299     return true;
02300   }
02301 
02302   bool visitStoreInst(StoreInst &SI) {
02303     DEBUG(dbgs() << "    original: " << SI << "\n");
02304     Value *OldOp = SI.getOperand(1);
02305     assert(OldOp == OldPtr);
02306 
02307     Value *V = SI.getValueOperand();
02308 
02309     // Strip all inbounds GEPs and pointer casts to try to dig out any root
02310     // alloca that should be re-examined after promoting this alloca.
02311     if (V->getType()->isPointerTy())
02312       if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
02313         Pass.PostPromotionWorklist.insert(AI);
02314 
02315     if (SliceSize < DL.getTypeStoreSize(V->getType())) {
02316       assert(!SI.isVolatile());
02317       assert(V->getType()->isIntegerTy() &&
02318              "Only integer type loads and stores are split");
02319       assert(V->getType()->getIntegerBitWidth() ==
02320              DL.getTypeStoreSizeInBits(V->getType()) &&
02321              "Non-byte-multiple bit width");
02322       IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
02323       V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
02324                          "extract");
02325     }
02326 
02327     if (VecTy)
02328       return rewriteVectorizedStoreInst(V, SI, OldOp);
02329     if (IntTy && V->getType()->isIntegerTy())
02330       return rewriteIntegerStore(V, SI);
02331 
02332     StoreInst *NewSI;
02333     if (NewBeginOffset == NewAllocaBeginOffset &&
02334         NewEndOffset == NewAllocaEndOffset &&
02335         canConvertValue(DL, V->getType(), NewAllocaTy)) {
02336       V = convertValue(DL, IRB, V, NewAllocaTy);
02337       NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
02338                                      SI.isVolatile());
02339     } else {
02340       Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
02341       NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
02342                                      SI.isVolatile());
02343     }
02344     (void)NewSI;
02345     Pass.DeadInsts.insert(&SI);
02346     deleteIfTriviallyDead(OldOp);
02347 
02348     DEBUG(dbgs() << "          to: " << *NewSI << "\n");
02349     return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
02350   }
02351 
02352   /// \brief Compute an integer value from splatting an i8 across the given
02353   /// number of bytes.
02354   ///
02355   /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
02356   /// call this routine.
02357   /// FIXME: Heed the advice above.
02358   ///
02359   /// \param V The i8 value to splat.
02360   /// \param Size The number of bytes in the output (assuming i8 is one byte)
02361   Value *getIntegerSplat(Value *V, unsigned Size) {
02362     assert(Size > 0 && "Expected a positive number of bytes.");
02363     IntegerType *VTy = cast<IntegerType>(V->getType());
02364     assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
02365     if (Size == 1)
02366       return V;
02367 
02368     Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
02369     V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
02370                       ConstantExpr::getUDiv(
02371                         Constant::getAllOnesValue(SplatIntTy),
02372                         ConstantExpr::getZExt(
02373                           Constant::getAllOnesValue(V->getType()),
02374                           SplatIntTy)),
02375                       "isplat");
02376     return V;
02377   }
02378 
02379   /// \brief Compute a vector splat for a given element value.
02380   Value *getVectorSplat(Value *V, unsigned NumElements) {
02381     V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
02382     DEBUG(dbgs() << "       splat: " << *V << "\n");
02383     return V;
02384   }
02385 
02386   bool visitMemSetInst(MemSetInst &II) {
02387     DEBUG(dbgs() << "    original: " << II << "\n");
02388     assert(II.getRawDest() == OldPtr);
02389 
02390     // If the memset has a variable size, it cannot be split, just adjust the
02391     // pointer to the new alloca.
02392     if (!isa<Constant>(II.getLength())) {
02393       assert(!IsSplit);
02394       assert(NewBeginOffset == BeginOffset);
02395       II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
02396       Type *CstTy = II.getAlignmentCst()->getType();
02397       II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
02398 
02399       deleteIfTriviallyDead(OldPtr);
02400       return false;
02401     }
02402 
02403     // Record this instruction for deletion.
02404     Pass.DeadInsts.insert(&II);
02405 
02406     Type *AllocaTy = NewAI.getAllocatedType();
02407     Type *ScalarTy = AllocaTy->getScalarType();
02408 
02409     // If this doesn't map cleanly onto the alloca type, and that type isn't
02410     // a single value type, just emit a memset.
02411     if (!VecTy && !IntTy &&
02412         (BeginOffset > NewAllocaBeginOffset ||
02413          EndOffset < NewAllocaEndOffset ||
02414          !AllocaTy->isSingleValueType() ||
02415          !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
02416          DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
02417       Type *SizeTy = II.getLength()->getType();
02418       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
02419       CallInst *New = IRB.CreateMemSet(
02420           getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
02421           getSliceAlign(), II.isVolatile());
02422       (void)New;
02423       DEBUG(dbgs() << "          to: " << *New << "\n");
02424       return false;
02425     }
02426 
02427     // If we can represent this as a simple value, we have to build the actual
02428     // value to store, which requires expanding the byte present in memset to
02429     // a sensible representation for the alloca type. This is essentially
02430     // splatting the byte to a sufficiently wide integer, splatting it across
02431     // any desired vector width, and bitcasting to the final type.
02432     Value *V;
02433 
02434     if (VecTy) {
02435       // If this is a memset of a vectorized alloca, insert it.
02436       assert(ElementTy == ScalarTy);
02437 
02438       unsigned BeginIndex = getIndex(NewBeginOffset);
02439       unsigned EndIndex = getIndex(NewEndOffset);
02440       assert(EndIndex > BeginIndex && "Empty vector!");
02441       unsigned NumElements = EndIndex - BeginIndex;
02442       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
02443 
02444       Value *Splat =
02445           getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
02446       Splat = convertValue(DL, IRB, Splat, ElementTy);
02447       if (NumElements > 1)
02448         Splat = getVectorSplat(Splat, NumElements);
02449 
02450       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02451                                          "oldload");
02452       V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
02453     } else if (IntTy) {
02454       // If this is a memset on an alloca where we can widen stores, insert the
02455       // set integer.
02456       assert(!II.isVolatile());
02457 
02458       uint64_t Size = NewEndOffset - NewBeginOffset;
02459       V = getIntegerSplat(II.getValue(), Size);
02460 
02461       if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
02462                     EndOffset != NewAllocaBeginOffset)) {
02463         Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02464                                            "oldload");
02465         Old = convertValue(DL, IRB, Old, IntTy);
02466         uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02467         V = insertInteger(DL, IRB, Old, V, Offset, "insert");
02468       } else {
02469         assert(V->getType() == IntTy &&
02470                "Wrong type for an alloca wide integer!");
02471       }
02472       V = convertValue(DL, IRB, V, AllocaTy);
02473     } else {
02474       // Established these invariants above.
02475       assert(NewBeginOffset == NewAllocaBeginOffset);
02476       assert(NewEndOffset == NewAllocaEndOffset);
02477 
02478       V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
02479       if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
02480         V = getVectorSplat(V, AllocaVecTy->getNumElements());
02481 
02482       V = convertValue(DL, IRB, V, AllocaTy);
02483     }
02484 
02485     Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
02486                                         II.isVolatile());
02487     (void)New;
02488     DEBUG(dbgs() << "          to: " << *New << "\n");
02489     return !II.isVolatile();
02490   }
02491 
02492   bool visitMemTransferInst(MemTransferInst &II) {
02493     // Rewriting of memory transfer instructions can be a bit tricky. We break
02494     // them into two categories: split intrinsics and unsplit intrinsics.
02495 
02496     DEBUG(dbgs() << "    original: " << II << "\n");
02497 
02498     bool IsDest = &II.getRawDestUse() == OldUse;
02499     assert((IsDest && II.getRawDest() == OldPtr) ||
02500            (!IsDest && II.getRawSource() == OldPtr));
02501 
02502     unsigned SliceAlign = getSliceAlign();
02503 
02504     // For unsplit intrinsics, we simply modify the source and destination
02505     // pointers in place. This isn't just an optimization, it is a matter of
02506     // correctness. With unsplit intrinsics we may be dealing with transfers
02507     // within a single alloca before SROA ran, or with transfers that have
02508     // a variable length. We may also be dealing with memmove instead of
02509     // memcpy, and so simply updating the pointers is the necessary for us to
02510     // update both source and dest of a single call.
02511     if (!IsSplittable) {
02512       Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02513       if (IsDest)
02514         II.setDest(AdjustedPtr);
02515       else
02516         II.setSource(AdjustedPtr);
02517 
02518       if (II.getAlignment() > SliceAlign) {
02519         Type *CstTy = II.getAlignmentCst()->getType();
02520         II.setAlignment(
02521             ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
02522       }
02523 
02524       DEBUG(dbgs() << "          to: " << II << "\n");
02525       deleteIfTriviallyDead(OldPtr);
02526       return false;
02527     }
02528     // For split transfer intrinsics we have an incredibly useful assurance:
02529     // the source and destination do not reside within the same alloca, and at
02530     // least one of them does not escape. This means that we can replace
02531     // memmove with memcpy, and we don't need to worry about all manner of
02532     // downsides to splitting and transforming the operations.
02533 
02534     // If this doesn't map cleanly onto the alloca type, and that type isn't
02535     // a single value type, just emit a memcpy.
02536     bool EmitMemCpy
02537       = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
02538                              EndOffset < NewAllocaEndOffset ||
02539                              !NewAI.getAllocatedType()->isSingleValueType());
02540 
02541     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
02542     // size hasn't been shrunk based on analysis of the viable range, this is
02543     // a no-op.
02544     if (EmitMemCpy && &OldAI == &NewAI) {
02545       // Ensure the start lines up.
02546       assert(NewBeginOffset == BeginOffset);
02547 
02548       // Rewrite the size as needed.
02549       if (NewEndOffset != EndOffset)
02550         II.setLength(ConstantInt::get(II.getLength()->getType(),
02551                                       NewEndOffset - NewBeginOffset));
02552       return false;
02553     }
02554     // Record this instruction for deletion.
02555     Pass.DeadInsts.insert(&II);
02556 
02557     // Strip all inbounds GEPs and pointer casts to try to dig out any root
02558     // alloca that should be re-examined after rewriting this instruction.
02559     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
02560     if (AllocaInst *AI
02561           = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
02562       assert(AI != &OldAI && AI != &NewAI &&
02563              "Splittable transfers cannot reach the same alloca on both ends.");
02564       Pass.Worklist.insert(AI);
02565     }
02566 
02567     Type *OtherPtrTy = OtherPtr->getType();
02568     unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
02569 
02570     // Compute the relative offset for the other pointer within the transfer.
02571     unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
02572     APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
02573     unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
02574                                    OtherOffset.zextOrTrunc(64).getZExtValue());
02575 
02576     if (EmitMemCpy) {
02577       // Compute the other pointer, folding as much as possible to produce
02578       // a single, simple GEP in most cases.
02579       OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
02580                                 OtherPtr->getName() + ".");
02581 
02582       Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02583       Type *SizeTy = II.getLength()->getType();
02584       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
02585 
02586       CallInst *New = IRB.CreateMemCpy(
02587           IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
02588           MinAlign(SliceAlign, OtherAlign), II.isVolatile());
02589       (void)New;
02590       DEBUG(dbgs() << "          to: " << *New << "\n");
02591       return false;
02592     }
02593 
02594     bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
02595                          NewEndOffset == NewAllocaEndOffset;
02596     uint64_t Size = NewEndOffset - NewBeginOffset;
02597     unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
02598     unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
02599     unsigned NumElements = EndIndex - BeginIndex;
02600     IntegerType *SubIntTy
02601       = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : nullptr;
02602 
02603     // Reset the other pointer type to match the register type we're going to
02604     // use, but using the address space of the original other pointer.
02605     if (VecTy && !IsWholeAlloca) {
02606       if (NumElements == 1)
02607         OtherPtrTy = VecTy->getElementType();
02608       else
02609         OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
02610 
02611       OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
02612     } else if (IntTy && !IsWholeAlloca) {
02613       OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
02614     } else {
02615       OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
02616     }
02617 
02618     Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
02619                                    OtherPtr->getName() + ".");
02620     unsigned SrcAlign = OtherAlign;
02621     Value *DstPtr = &NewAI;
02622     unsigned DstAlign = SliceAlign;
02623     if (!IsDest) {
02624       std::swap(SrcPtr, DstPtr);
02625       std::swap(SrcAlign, DstAlign);
02626     }
02627 
02628     Value *Src;
02629     if (VecTy && !IsWholeAlloca && !IsDest) {
02630       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02631                                   "load");
02632       Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
02633     } else if (IntTy && !IsWholeAlloca && !IsDest) {
02634       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02635                                   "load");
02636       Src = convertValue(DL, IRB, Src, IntTy);
02637       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02638       Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
02639     } else {
02640       Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
02641                                   "copyload");
02642     }
02643 
02644     if (VecTy && !IsWholeAlloca && IsDest) {
02645       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02646                                          "oldload");
02647       Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
02648     } else if (IntTy && !IsWholeAlloca && IsDest) {
02649       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02650                                          "oldload");
02651       Old = convertValue(DL, IRB, Old, IntTy);
02652       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02653       Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
02654       Src = convertValue(DL, IRB, Src, NewAllocaTy);
02655     }
02656 
02657     StoreInst *Store = cast<StoreInst>(
02658         IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
02659     (void)Store;
02660     DEBUG(dbgs() << "          to: " << *Store << "\n");
02661     return !II.isVolatile();
02662   }
02663 
02664   bool visitIntrinsicInst(IntrinsicInst &II) {
02665     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
02666            II.getIntrinsicID() == Intrinsic::lifetime_end);
02667     DEBUG(dbgs() << "    original: " << II << "\n");
02668     assert(II.getArgOperand(1) == OldPtr);
02669 
02670     // Record this instruction for deletion.
02671     Pass.DeadInsts.insert(&II);
02672 
02673     ConstantInt *Size
02674       = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
02675                          NewEndOffset - NewBeginOffset);
02676     Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02677     Value *New;
02678     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
02679       New = IRB.CreateLifetimeStart(Ptr, Size);
02680     else
02681       New = IRB.CreateLifetimeEnd(Ptr, Size);
02682 
02683     (void)New;
02684     DEBUG(dbgs() << "          to: " << *New << "\n");
02685     return true;
02686   }
02687 
02688   bool visitPHINode(PHINode &PN) {
02689     DEBUG(dbgs() << "    original: " << PN << "\n");
02690     assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
02691     assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
02692 
02693     // We would like to compute a new pointer in only one place, but have it be
02694     // as local as possible to the PHI. To do that, we re-use the location of
02695     // the old pointer, which necessarily must be in the right position to
02696     // dominate the PHI.
02697     IRBuilderTy PtrBuilder(IRB);
02698     PtrBuilder.SetInsertPoint(OldPtr);
02699     PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
02700 
02701     Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
02702     // Replace the operands which were using the old pointer.
02703     std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
02704 
02705     DEBUG(dbgs() << "          to: " << PN << "\n");
02706     deleteIfTriviallyDead(OldPtr);
02707 
02708     // PHIs can't be promoted on their own, but often can be speculated. We
02709     // check the speculation outside of the rewriter so that we see the
02710     // fully-rewritten alloca.
02711     PHIUsers.insert(&PN);
02712     return true;
02713   }
02714 
02715   bool visitSelectInst(SelectInst &SI) {
02716     DEBUG(dbgs() << "    original: " << SI << "\n");
02717     assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
02718            "Pointer isn't an operand!");
02719     assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
02720     assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
02721 
02722     Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02723     // Replace the operands which were using the old pointer.
02724     if (SI.getOperand(1) == OldPtr)
02725       SI.setOperand(1, NewPtr);
02726     if (SI.getOperand(2) == OldPtr)
02727       SI.setOperand(2, NewPtr);
02728 
02729     DEBUG(dbgs() << "          to: " << SI << "\n");
02730     deleteIfTriviallyDead(OldPtr);
02731 
02732     // Selects can't be promoted on their own, but often can be speculated. We
02733     // check the speculation outside of the rewriter so that we see the
02734     // fully-rewritten alloca.
02735     SelectUsers.insert(&SI);
02736     return true;
02737   }
02738 
02739 };
02740 }
02741 
02742 namespace {
02743 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
02744 ///
02745 /// This pass aggressively rewrites all aggregate loads and stores on
02746 /// a particular pointer (or any pointer derived from it which we can identify)
02747 /// with scalar loads and stores.
02748 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
02749   // Befriend the base class so it can delegate to private visit methods.
02750   friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
02751 
02752   const DataLayout &DL;
02753 
02754   /// Queue of pointer uses to analyze and potentially rewrite.
02755   SmallVector<Use *, 8> Queue;
02756 
02757   /// Set to prevent us from cycling with phi nodes and loops.
02758   SmallPtrSet<User *, 8> Visited;
02759 
02760   /// The current pointer use being rewritten. This is used to dig up the used
02761   /// value (as opposed to the user).
02762   Use *U;
02763 
02764 public:
02765   AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
02766 
02767   /// Rewrite loads and stores through a pointer and all pointers derived from
02768   /// it.
02769   bool rewrite(Instruction &I) {
02770     DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
02771     enqueueUsers(I);
02772     bool Changed = false;
02773     while (!Queue.empty()) {
02774       U = Queue.pop_back_val();
02775       Changed |= visit(cast<Instruction>(U->getUser()));
02776     }
02777     return Changed;
02778   }
02779 
02780 private:
02781   /// Enqueue all the users of the given instruction for further processing.
02782   /// This uses a set to de-duplicate users.
02783   void enqueueUsers(Instruction &I) {
02784     for (Use &U : I.uses())
02785       if (Visited.insert(U.getUser()))
02786         Queue.push_back(&U);
02787   }
02788 
02789   // Conservative default is to not rewrite anything.
02790   bool visitInstruction(Instruction &I) { return false; }
02791 
02792   /// \brief Generic recursive split emission class.
02793   template <typename Derived>
02794   class OpSplitter {
02795   protected:
02796     /// The builder used to form new instructions.
02797     IRBuilderTy IRB;
02798     /// The indices which to be used with insert- or extractvalue to select the
02799     /// appropriate value within the aggregate.
02800     SmallVector<unsigned, 4> Indices;
02801     /// The indices to a GEP instruction which will move Ptr to the correct slot
02802     /// within the aggregate.
02803     SmallVector<Value *, 4> GEPIndices;
02804     /// The base pointer of the original op, used as a base for GEPing the
02805     /// split operations.
02806     Value *Ptr;
02807 
02808     /// Initialize the splitter with an insertion point, Ptr and start with a
02809     /// single zero GEP index.
02810     OpSplitter(Instruction *InsertionPoint, Value *Ptr)
02811       : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
02812 
02813   public:
02814     /// \brief Generic recursive split emission routine.
02815     ///
02816     /// This method recursively splits an aggregate op (load or store) into
02817     /// scalar or vector ops. It splits recursively until it hits a single value
02818     /// and emits that single value operation via the template argument.
02819     ///
02820     /// The logic of this routine relies on GEPs and insertvalue and
02821     /// extractvalue all operating with the same fundamental index list, merely
02822     /// formatted differently (GEPs need actual values).
02823     ///
02824     /// \param Ty  The type being split recursively into smaller ops.
02825     /// \param Agg The aggregate value being built up or stored, depending on
02826     /// whether this is splitting a load or a store respectively.
02827     void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
02828       if (Ty->isSingleValueType())
02829         return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
02830 
02831       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
02832         unsigned OldSize = Indices.size();
02833         (void)OldSize;
02834         for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
02835              ++Idx) {
02836           assert(Indices.size() == OldSize && "Did not return to the old size");
02837           Indices.push_back(Idx);
02838           GEPIndices.push_back(IRB.getInt32(Idx));
02839           emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
02840           GEPIndices.pop_back();
02841           Indices.pop_back();
02842         }
02843         return;
02844       }
02845 
02846       if (StructType *STy = dyn_cast<StructType>(Ty)) {
02847         unsigned OldSize = Indices.size();
02848         (void)OldSize;
02849         for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
02850              ++Idx) {
02851           assert(Indices.size() == OldSize && "Did not return to the old size");
02852           Indices.push_back(Idx);
02853           GEPIndices.push_back(IRB.getInt32(Idx));
02854           emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
02855           GEPIndices.pop_back();
02856           Indices.pop_back();
02857         }
02858         return;
02859       }
02860 
02861       llvm_unreachable("Only arrays and structs are aggregate loadable types");
02862     }
02863   };
02864 
02865   struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
02866     LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
02867       : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
02868 
02869     /// Emit a leaf load of a single value. This is called at the leaves of the
02870     /// recursive emission to actually load values.
02871     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
02872       assert(Ty->isSingleValueType());
02873       // Load the single value and insert it using the indices.
02874       Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
02875       Value *Load = IRB.CreateLoad(GEP, Name + ".load");
02876       Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
02877       DEBUG(dbgs() << "          to: " << *Load << "\n");
02878     }
02879   };
02880 
02881   bool visitLoadInst(LoadInst &LI) {
02882     assert(LI.getPointerOperand() == *U);
02883     if (!LI.isSimple() || LI.getType()->isSingleValueType())
02884       return false;
02885 
02886     // We have an aggregate being loaded, split it apart.
02887     DEBUG(dbgs() << "    original: " << LI << "\n");
02888     LoadOpSplitter Splitter(&LI, *U);
02889     Value *V = UndefValue::get(LI.getType());
02890     Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
02891     LI.replaceAllUsesWith(V);
02892     LI.eraseFromParent();
02893     return true;
02894   }
02895 
02896   struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
02897     StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
02898       : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
02899 
02900     /// Emit a leaf store of a single value. This is called at the leaves of the
02901     /// recursive emission to actually produce stores.
02902     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
02903       assert(Ty->isSingleValueType());
02904       // Extract the single value and store it using the indices.
02905       Value *Store = IRB.CreateStore(
02906         IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
02907         IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
02908       (void)Store;
02909       DEBUG(dbgs() << "          to: " << *Store << "\n");
02910     }
02911   };
02912 
02913   bool visitStoreInst(StoreInst &SI) {
02914     if (!SI.isSimple() || SI.getPointerOperand() != *U)
02915       return false;
02916     Value *V = SI.getValueOperand();
02917     if (V->getType()->isSingleValueType())
02918       return false;
02919 
02920     // We have an aggregate being stored, split it apart.
02921     DEBUG(dbgs() << "    original: " << SI << "\n");
02922     StoreOpSplitter Splitter(&SI, *U);
02923     Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
02924     SI.eraseFromParent();
02925     return true;
02926   }
02927 
02928   bool visitBitCastInst(BitCastInst &BC) {
02929     enqueueUsers(BC);
02930     return false;
02931   }
02932 
02933   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
02934     enqueueUsers(GEPI);
02935     return false;
02936   }
02937 
02938   bool visitPHINode(PHINode &PN) {
02939     enqueueUsers(PN);
02940     return false;
02941   }
02942 
02943   bool visitSelectInst(SelectInst &SI) {
02944     enqueueUsers(SI);
02945     return false;
02946   }
02947 };
02948 }
02949 
02950 /// \brief Strip aggregate type wrapping.
02951 ///
02952 /// This removes no-op aggregate types wrapping an underlying type. It will
02953 /// strip as many layers of types as it can without changing either the type
02954 /// size or the allocated size.
02955 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
02956   if (Ty->isSingleValueType())
02957     return Ty;
02958 
02959   uint64_t AllocSize = DL.getTypeAllocSize(Ty);
02960   uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
02961 
02962   Type *InnerTy;
02963   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
02964     InnerTy = ArrTy->getElementType();
02965   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
02966     const StructLayout *SL = DL.getStructLayout(STy);
02967     unsigned Index = SL->getElementContainingOffset(0);
02968     InnerTy = STy->getElementType(Index);
02969   } else {
02970     return Ty;
02971   }
02972 
02973   if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
02974       TypeSize > DL.getTypeSizeInBits(InnerTy))
02975     return Ty;
02976 
02977   return stripAggregateTypeWrapping(DL, InnerTy);
02978 }
02979 
02980 /// \brief Try to find a partition of the aggregate type passed in for a given
02981 /// offset and size.
02982 ///
02983 /// This recurses through the aggregate type and tries to compute a subtype
02984 /// based on the offset and size. When the offset and size span a sub-section
02985 /// of an array, it will even compute a new array type for that sub-section,
02986 /// and the same for structs.
02987 ///
02988 /// Note that this routine is very strict and tries to find a partition of the
02989 /// type which produces the *exact* right offset and size. It is not forgiving
02990 /// when the size or offset cause either end of type-based partition to be off.
02991 /// Also, this is a best-effort routine. It is reasonable to give up and not
02992 /// return a type if necessary.
02993 static Type *getTypePartition(const DataLayout &DL, Type *Ty,
02994                               uint64_t Offset, uint64_t Size) {
02995   if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
02996     return stripAggregateTypeWrapping(DL, Ty);
02997   if (Offset > DL.getTypeAllocSize(Ty) ||
02998       (DL.getTypeAllocSize(Ty) - Offset) < Size)
02999     return nullptr;
03000 
03001   if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
03002     // We can't partition pointers...
03003     if (SeqTy->isPointerTy())
03004       return nullptr;
03005 
03006     Type *ElementTy = SeqTy->getElementType();
03007     uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
03008     uint64_t NumSkippedElements = Offset / ElementSize;
03009     if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
03010       if (NumSkippedElements >= ArrTy->getNumElements())
03011         return nullptr;
03012     } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
03013       if (NumSkippedElements >= VecTy->getNumElements())
03014         return nullptr;
03015     }
03016     Offset -= NumSkippedElements * ElementSize;
03017 
03018     // First check if we need to recurse.
03019     if (Offset > 0 || Size < ElementSize) {
03020       // Bail if the partition ends in a different array element.
03021       if ((Offset + Size) > ElementSize)
03022         return nullptr;
03023       // Recurse through the element type trying to peel off offset bytes.
03024       return getTypePartition(DL, ElementTy, Offset, Size);
03025     }
03026     assert(Offset == 0);
03027 
03028     if (Size == ElementSize)
03029       return stripAggregateTypeWrapping(DL, ElementTy);
03030     assert(Size > ElementSize);
03031     uint64_t NumElements = Size / ElementSize;
03032     if (NumElements * ElementSize != Size)
03033       return nullptr;
03034     return ArrayType::get(ElementTy, NumElements);
03035   }
03036 
03037   StructType *STy = dyn_cast<StructType>(Ty);
03038   if (!STy)
03039     return nullptr;
03040 
03041   const StructLayout *SL = DL.getStructLayout(STy);
03042   if (Offset >= SL->getSizeInBytes())
03043     return nullptr;
03044   uint64_t EndOffset = Offset + Size;
03045   if (EndOffset > SL->getSizeInBytes())
03046     return nullptr;
03047 
03048   unsigned Index = SL->getElementContainingOffset(Offset);
03049   Offset -= SL->getElementOffset(Index);
03050 
03051   Type *ElementTy = STy->getElementType(Index);
03052   uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
03053   if (Offset >= ElementSize)
03054     return nullptr; // The offset points into alignment padding.
03055 
03056   // See if any partition must be contained by the element.
03057   if (Offset > 0 || Size < ElementSize) {
03058     if ((Offset + Size) > ElementSize)
03059       return nullptr;
03060     return getTypePartition(DL, ElementTy, Offset, Size);
03061   }
03062   assert(Offset == 0);
03063 
03064   if (Size == ElementSize)
03065     return stripAggregateTypeWrapping(DL, ElementTy);
03066 
03067   StructType::element_iterator EI = STy->element_begin() + Index,
03068                                EE = STy->element_end();
03069   if (EndOffset < SL->getSizeInBytes()) {
03070     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
03071     if (Index == EndIndex)
03072       return nullptr; // Within a single element and its padding.
03073 
03074     // Don't try to form "natural" types if the elements don't line up with the
03075     // expected size.
03076     // FIXME: We could potentially recurse down through the last element in the
03077     // sub-struct to find a natural end point.
03078     if (SL->getElementOffset(EndIndex) != EndOffset)
03079       return nullptr;
03080 
03081     assert(Index < EndIndex);
03082     EE = STy->element_begin() + EndIndex;
03083   }
03084 
03085   // Try to build up a sub-structure.
03086   StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
03087                                       STy->isPacked());
03088   const StructLayout *SubSL = DL.getStructLayout(SubTy);
03089   if (Size != SubSL->getSizeInBytes())
03090     return nullptr; // The sub-struct doesn't have quite the size needed.
03091 
03092   return SubTy;
03093 }
03094 
03095 /// \brief Rewrite an alloca partition's users.
03096 ///
03097 /// This routine drives both of the rewriting goals of the SROA pass. It tries
03098 /// to rewrite uses of an alloca partition to be conducive for SSA value
03099 /// promotion. If the partition needs a new, more refined alloca, this will
03100 /// build that new alloca, preserving as much type information as possible, and
03101 /// rewrite the uses of the old alloca to point at the new one and have the
03102 /// appropriate new offsets. It also evaluates how successful the rewrite was
03103 /// at enabling promotion and if it was successful queues the alloca to be
03104 /// promoted.
03105 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
03106                             AllocaSlices::iterator B, AllocaSlices::iterator E,
03107                             int64_t BeginOffset, int64_t EndOffset,
03108                             ArrayRef<AllocaSlices::iterator> SplitUses) {
03109   assert(BeginOffset < EndOffset);
03110   uint64_t SliceSize = EndOffset - BeginOffset;
03111 
03112   // Try to compute a friendly type for this partition of the alloca. This
03113   // won't always succeed, in which case we fall back to a legal integer type
03114   // or an i8 array of an appropriate size.
03115   Type *SliceTy = nullptr;
03116   if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
03117     if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
03118       SliceTy = CommonUseTy;
03119   if (!SliceTy)
03120     if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
03121                                                  BeginOffset, SliceSize))
03122       SliceTy = TypePartitionTy;
03123   if ((!SliceTy || (SliceTy->isArrayTy() &&
03124                     SliceTy->getArrayElementType()->isIntegerTy())) &&
03125       DL->isLegalInteger(SliceSize * 8))
03126     SliceTy = Type::getIntNTy(*C, SliceSize * 8);
03127   if (!SliceTy)
03128     SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
03129   assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
03130 
03131   bool IsVectorPromotable = isVectorPromotionViable(
03132       *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
03133 
03134   bool IsIntegerPromotable =
03135       !IsVectorPromotable &&
03136       isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
03137 
03138   // Check for the case where we're going to rewrite to a new alloca of the
03139   // exact same type as the original, and with the same access offsets. In that
03140   // case, re-use the existing alloca, but still run through the rewriter to
03141   // perform phi and select speculation.
03142   AllocaInst *NewAI;
03143   if (SliceTy == AI.getAllocatedType()) {
03144     assert(BeginOffset == 0 &&
03145            "Non-zero begin offset but same alloca type");
03146     NewAI = &AI;
03147     // FIXME: We should be able to bail at this point with "nothing changed".
03148     // FIXME: We might want to defer PHI speculation until after here.
03149   } else {
03150     unsigned Alignment = AI.getAlignment();
03151     if (!Alignment) {
03152       // The minimum alignment which users can rely on when the explicit
03153       // alignment is omitted or zero is that required by the ABI for this
03154       // type.
03155       Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
03156     }
03157     Alignment = MinAlign(Alignment, BeginOffset);
03158     // If we will get at least this much alignment from the type alone, leave
03159     // the alloca's alignment unconstrained.
03160     if (Alignment <= DL->getABITypeAlignment(SliceTy))
03161       Alignment = 0;
03162     NewAI = new AllocaInst(SliceTy, nullptr, Alignment,
03163                            AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
03164     ++NumNewAllocas;
03165   }
03166 
03167   DEBUG(dbgs() << "Rewriting alloca partition "
03168                << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
03169                << "\n");
03170 
03171   // Track the high watermark on the worklist as it is only relevant for
03172   // promoted allocas. We will reset it to this point if the alloca is not in
03173   // fact scheduled for promotion.
03174   unsigned PPWOldSize = PostPromotionWorklist.size();
03175   unsigned NumUses = 0;
03176   SmallPtrSet<PHINode *, 8> PHIUsers;
03177   SmallPtrSet<SelectInst *, 8> SelectUsers;
03178 
03179   AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
03180                                EndOffset, IsVectorPromotable,
03181                                IsIntegerPromotable, PHIUsers, SelectUsers);
03182   bool Promotable = true;
03183   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
03184                                                         SUE = SplitUses.end();
03185        SUI != SUE; ++SUI) {
03186     DEBUG(dbgs() << "  rewriting split ");
03187     DEBUG(S.printSlice(dbgs(), *SUI, ""));
03188     Promotable &= Rewriter.visit(*SUI);
03189     ++NumUses;
03190   }
03191   for (AllocaSlices::iterator I = B; I != E; ++I) {
03192     DEBUG(dbgs() << "  rewriting ");
03193     DEBUG(S.printSlice(dbgs(), I, ""));
03194     Promotable &= Rewriter.visit(I);
03195     ++NumUses;
03196   }
03197 
03198   NumAllocaPartitionUses += NumUses;
03199   MaxUsesPerAllocaPartition =
03200       std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
03201 
03202   // Now that we've processed all the slices in the new partition, check if any
03203   // PHIs or Selects would block promotion.
03204   for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
03205                                             E = PHIUsers.end();
03206        I != E; ++I)
03207     if (!isSafePHIToSpeculate(**I, DL)) {
03208       Promotable = false;
03209       PHIUsers.clear();
03210       SelectUsers.clear();
03211       break;
03212     }
03213   for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
03214                                                E = SelectUsers.end();
03215        I != E; ++I)
03216     if (!isSafeSelectToSpeculate(**I, DL)) {
03217       Promotable = false;
03218       PHIUsers.clear();
03219       SelectUsers.clear();
03220       break;
03221     }
03222 
03223   if (Promotable) {
03224     if (PHIUsers.empty() && SelectUsers.empty()) {
03225       // Promote the alloca.
03226       PromotableAllocas.push_back(NewAI);
03227     } else {
03228       // If we have either PHIs or Selects to speculate, add them to those
03229       // worklists and re-queue the new alloca so that we promote in on the
03230       // next iteration.
03231       for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
03232                                                 E = PHIUsers.end();
03233            I != E; ++I)
03234         SpeculatablePHIs.insert(*I);
03235       for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
03236                                                    E = SelectUsers.end();
03237            I != E; ++I)
03238         SpeculatableSelects.insert(*I);
03239       Worklist.insert(NewAI);
03240     }
03241   } else {
03242     // If we can't promote the alloca, iterate on it to check for new
03243     // refinements exposed by splitting the current alloca. Don't iterate on an
03244     // alloca which didn't actually change and didn't get promoted.
03245     if (NewAI != &AI)
03246       Worklist.insert(NewAI);
03247 
03248     // Drop any post-promotion work items if promotion didn't happen.
03249     while (PostPromotionWorklist.size() > PPWOldSize)
03250       PostPromotionWorklist.pop_back();
03251   }
03252 
03253   return true;
03254 }
03255 
03256 static void
03257 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
03258                         uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
03259   if (Offset >= MaxSplitUseEndOffset) {
03260     SplitUses.clear();
03261     MaxSplitUseEndOffset = 0;
03262     return;
03263   }
03264 
03265   size_t SplitUsesOldSize = SplitUses.size();
03266   SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
03267                                  [Offset](const AllocaSlices::iterator &I) {
03268                     return I->endOffset() <= Offset;
03269                   }),
03270                   SplitUses.end());
03271   if (SplitUsesOldSize == SplitUses.size())
03272     return;
03273 
03274   // Recompute the max. While this is linear, so is remove_if.
03275   MaxSplitUseEndOffset = 0;
03276   for (SmallVectorImpl<AllocaSlices::iterator>::iterator
03277            SUI = SplitUses.begin(),
03278            SUE = SplitUses.end();
03279        SUI != SUE; ++SUI)
03280     MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
03281 }
03282 
03283 /// \brief Walks the slices of an alloca and form partitions based on them,
03284 /// rewriting each of their uses.
03285 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
03286   if (S.begin() == S.end())
03287     return false;
03288 
03289   unsigned NumPartitions = 0;
03290   bool Changed = false;
03291   SmallVector<AllocaSlices::iterator, 4> SplitUses;
03292   uint64_t MaxSplitUseEndOffset = 0;
03293 
03294   uint64_t BeginOffset = S.begin()->beginOffset();
03295 
03296   for (AllocaSlices::iterator SI = S.begin(), SJ = std::next(SI), SE = S.end();
03297        SI != SE; SI = SJ) {
03298     uint64_t MaxEndOffset = SI->endOffset();
03299 
03300     if (!SI->isSplittable()) {
03301       // When we're forming an unsplittable region, it must always start at the
03302       // first slice and will extend through its end.
03303       assert(BeginOffset == SI->beginOffset());
03304 
03305       // Form a partition including all of the overlapping slices with this
03306       // unsplittable slice.
03307       while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
03308         if (!SJ->isSplittable())
03309           MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
03310         ++SJ;
03311       }
03312     } else {
03313       assert(SI->isSplittable()); // Established above.
03314 
03315       // Collect all of the overlapping splittable slices.
03316       while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
03317              SJ->isSplittable()) {
03318         MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
03319         ++SJ;
03320       }
03321 
03322       // Back up MaxEndOffset and SJ if we ended the span early when
03323       // encountering an unsplittable slice.
03324       if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
03325         assert(!SJ->isSplittable());
03326         MaxEndOffset = SJ->beginOffset();
03327       }
03328     }
03329 
03330     // Check if we have managed to move the end offset forward yet. If so,
03331     // we'll have to rewrite uses and erase old split uses.
03332     if (BeginOffset < MaxEndOffset) {
03333       // Rewrite a sequence of overlapping slices.
03334       Changed |=
03335           rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
03336       ++NumPartitions;
03337 
03338       removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
03339     }
03340 
03341     // Accumulate all the splittable slices from the [SI,SJ) region which
03342     // overlap going forward.
03343     for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
03344       if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
03345         SplitUses.push_back(SK);
03346         MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
03347       }
03348 
03349     // If we're already at the end and we have no split uses, we're done.
03350     if (SJ == SE && SplitUses.empty())
03351       break;
03352 
03353     // If we have no split uses or no gap in offsets, we're ready to move to
03354     // the next slice.
03355     if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
03356       BeginOffset = SJ->beginOffset();
03357       continue;
03358     }
03359 
03360     // Even if we have split slices, if the next slice is splittable and the
03361     // split slices reach it, we can simply set up the beginning offset of the
03362     // next iteration to bridge between them.
03363     if (SJ != SE && SJ->isSplittable() &&
03364         MaxSplitUseEndOffset > SJ->beginOffset()) {
03365       BeginOffset = MaxEndOffset;
03366       continue;
03367     }
03368 
03369     // Otherwise, we have a tail of split slices. Rewrite them with an empty
03370     // range of slices.
03371     uint64_t PostSplitEndOffset =
03372         SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
03373 
03374     Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
03375                                 SplitUses);
03376     ++NumPartitions;
03377 
03378     if (SJ == SE)
03379       break; // Skip the rest, we don't need to do any cleanup.
03380 
03381     removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
03382                             PostSplitEndOffset);
03383 
03384     // Now just reset the begin offset for the next iteration.
03385     BeginOffset = SJ->beginOffset();
03386   }
03387 
03388   NumAllocaPartitions += NumPartitions;
03389   MaxPartitionsPerAlloca =
03390       std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
03391 
03392   return Changed;
03393 }
03394 
03395 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
03396 void SROA::clobberUse(Use &U) {
03397   Value *OldV = U;
03398   // Replace the use with an undef value.
03399   U = UndefValue::get(OldV->getType());
03400 
03401   // Check for this making an instruction dead. We have to garbage collect
03402   // all the dead instructions to ensure the uses of any alloca end up being
03403   // minimal.
03404   if (Instruction *OldI = dyn_cast<Instruction>(OldV))
03405     if (isInstructionTriviallyDead(OldI)) {
03406       DeadInsts.insert(OldI);
03407     }
03408 }
03409 
03410 /// \brief Analyze an alloca for SROA.
03411 ///
03412 /// This analyzes the alloca to ensure we can reason about it, builds
03413 /// the slices of the alloca, and then hands it off to be split and
03414 /// rewritten as needed.
03415 bool SROA::runOnAlloca(AllocaInst &AI) {
03416   DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
03417   ++NumAllocasAnalyzed;
03418 
03419   // Special case dead allocas, as they're trivial.
03420   if (AI.use_empty()) {
03421     AI.eraseFromParent();
03422     return true;
03423   }
03424 
03425   // Skip alloca forms that this analysis can't handle.
03426   if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
03427       DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
03428     return false;
03429 
03430   bool Changed = false;
03431 
03432   // First, split any FCA loads and stores touching this alloca to promote
03433   // better splitting and promotion opportunities.
03434   AggLoadStoreRewriter AggRewriter(*DL);
03435   Changed |= AggRewriter.rewrite(AI);
03436 
03437   // Build the slices using a recursive instruction-visiting builder.
03438   AllocaSlices S(*DL, AI);
03439   DEBUG(S.print(dbgs()));
03440   if (S.isEscaped())
03441     return Changed;
03442 
03443   // Delete all the dead users of this alloca before splitting and rewriting it.
03444   for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
03445                                         DE = S.dead_user_end();
03446        DI != DE; ++DI) {
03447     // Free up everything used by this instruction.
03448     for (Use &DeadOp : (*DI)->operands())
03449       clobberUse(DeadOp);
03450 
03451     // Now replace the uses of this instruction.
03452     (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
03453 
03454     // And mark it for deletion.
03455     DeadInsts.insert(*DI);
03456     Changed = true;
03457   }
03458   for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
03459                                       DE = S.dead_op_end();
03460        DO != DE; ++DO) {
03461     clobberUse(**DO);
03462     Changed = true;
03463   }
03464 
03465   // No slices to split. Leave the dead alloca for a later pass to clean up.
03466   if (S.begin() == S.end())
03467     return Changed;
03468 
03469   Changed |= splitAlloca(AI, S);
03470 
03471   DEBUG(dbgs() << "  Speculating PHIs\n");
03472   while (!SpeculatablePHIs.empty())
03473     speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
03474 
03475   DEBUG(dbgs() << "  Speculating Selects\n");
03476   while (!SpeculatableSelects.empty())
03477     speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
03478 
03479   return Changed;
03480 }
03481 
03482 /// \brief Delete the dead instructions accumulated in this run.
03483 ///
03484 /// Recursively deletes the dead instructions we've accumulated. This is done
03485 /// at the very end to maximize locality of the recursive delete and to
03486 /// minimize the problems of invalidated instruction pointers as such pointers
03487 /// are used heavily in the intermediate stages of the algorithm.
03488 ///
03489 /// We also record the alloca instructions deleted here so that they aren't
03490 /// subsequently handed to mem2reg to promote.
03491 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
03492   while (!DeadInsts.empty()) {
03493     Instruction *I = DeadInsts.pop_back_val();
03494     DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
03495 
03496     I->replaceAllUsesWith(UndefValue::get(I->getType()));
03497 
03498     for (Use &Operand : I->operands())
03499       if (Instruction *U = dyn_cast<Instruction>(Operand)) {
03500         // Zero out the operand and see if it becomes trivially dead.
03501         Operand = nullptr;
03502         if (isInstructionTriviallyDead(U))
03503           DeadInsts.insert(U);
03504       }
03505 
03506     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
03507       DeletedAllocas.insert(AI);
03508 
03509     ++NumDeleted;
03510     I->eraseFromParent();
03511   }
03512 }
03513 
03514 static void enqueueUsersInWorklist(Instruction &I,
03515                                    SmallVectorImpl<Instruction *> &Worklist,
03516                                    SmallPtrSet<Instruction *, 8> &Visited) {
03517   for (User *U : I.users())
03518     if (Visited.insert(cast<Instruction>(U)))
03519       Worklist.push_back(cast<Instruction>(U));
03520 }
03521 
03522 /// \brief Promote the allocas, using the best available technique.
03523 ///
03524 /// This attempts to promote whatever allocas have been identified as viable in
03525 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
03526 /// If there is a domtree available, we attempt to promote using the full power
03527 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
03528 /// based on the SSAUpdater utilities. This function returns whether any
03529 /// promotion occurred.
03530 bool SROA::promoteAllocas(Function &F) {
03531   if (PromotableAllocas.empty())
03532     return false;
03533 
03534   NumPromoted += PromotableAllocas.size();
03535 
03536   if (DT && !ForceSSAUpdater) {
03537     DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
03538     PromoteMemToReg(PromotableAllocas, *DT);
03539     PromotableAllocas.clear();
03540     return true;
03541   }
03542 
03543   DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
03544   SSAUpdater SSA;
03545   DIBuilder DIB(*F.getParent());
03546   SmallVector<Instruction *, 64> Insts;
03547 
03548   // We need a worklist to walk the uses of each alloca.
03549   SmallVector<Instruction *, 8> Worklist;
03550   SmallPtrSet<Instruction *, 8> Visited;
03551   SmallVector<Instruction *, 32> DeadInsts;
03552 
03553   for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
03554     AllocaInst *AI = PromotableAllocas[Idx];
03555     Insts.clear();
03556     Worklist.clear();
03557     Visited.clear();
03558 
03559     enqueueUsersInWorklist(*AI, Worklist, Visited);
03560 
03561     while (!Worklist.empty()) {
03562       Instruction *I = Worklist.pop_back_val();
03563 
03564       // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
03565       // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
03566       // leading to them) here. Eventually it should use them to optimize the
03567       // scalar values produced.
03568       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
03569         assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
03570                II->getIntrinsicID() == Intrinsic::lifetime_end);
03571         II->eraseFromParent();
03572         continue;
03573       }
03574 
03575       // Push the loads and stores we find onto the list. SROA will already
03576       // have validated that all loads and stores are viable candidates for
03577       // promotion.
03578       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
03579         assert(LI->getType() == AI->getAllocatedType());
03580         Insts.push_back(LI);
03581         continue;
03582       }
03583       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
03584         assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
03585         Insts.push_back(SI);
03586         continue;
03587       }
03588 
03589       // For everything else, we know that only no-op bitcasts and GEPs will
03590       // make it this far, just recurse through them and recall them for later
03591       // removal.
03592       DeadInsts.push_back(I);
03593       enqueueUsersInWorklist(*I, Worklist, Visited);
03594     }
03595     AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
03596     while (!DeadInsts.empty())
03597       DeadInsts.pop_back_val()->eraseFromParent();
03598     AI->eraseFromParent();
03599   }
03600 
03601   PromotableAllocas.clear();
03602   return true;
03603 }
03604 
03605 bool SROA::runOnFunction(Function &F) {
03606   if (skipOptnoneFunction(F))
03607     return false;
03608 
03609   DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
03610   C = &F.getContext();
03611   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
03612   if (!DLP) {
03613     DEBUG(dbgs() << "  Skipping SROA -- no target data!\n");
03614     return false;
03615   }
03616   DL = &DLP->getDataLayout();
03617   DominatorTreeWrapperPass *DTWP =
03618       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
03619   DT = DTWP ? &DTWP->getDomTree() : nullptr;
03620 
03621   BasicBlock &EntryBB = F.getEntryBlock();
03622   for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
03623        I != E; ++I)
03624     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
03625       Worklist.insert(AI);
03626 
03627   bool Changed = false;
03628   // A set of deleted alloca instruction pointers which should be removed from
03629   // the list of promotable allocas.
03630   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
03631 
03632   do {
03633     while (!Worklist.empty()) {
03634       Changed |= runOnAlloca(*Worklist.pop_back_val());
03635       deleteDeadInstructions(DeletedAllocas);
03636 
03637       // Remove the deleted allocas from various lists so that we don't try to
03638       // continue processing them.
03639       if (!DeletedAllocas.empty()) {
03640         auto IsInSet = [&](AllocaInst *AI) {
03641           return DeletedAllocas.count(AI);
03642         };
03643         Worklist.remove_if(IsInSet);
03644         PostPromotionWorklist.remove_if(IsInSet);
03645         PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
03646                                                PromotableAllocas.end(),
03647                                                IsInSet),
03648                                 PromotableAllocas.end());
03649         DeletedAllocas.clear();
03650       }
03651     }
03652 
03653     Changed |= promoteAllocas(F);
03654 
03655     Worklist = PostPromotionWorklist;
03656     PostPromotionWorklist.clear();
03657   } while (!Worklist.empty());
03658 
03659   return Changed;
03660 }
03661 
03662 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
03663   if (RequiresDomTree)
03664     AU.addRequired<DominatorTreeWrapperPass>();
03665   AU.setPreservesCFG();
03666 }