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