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/AssumptionCache.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> ForceSSAUpdater("force-ssa-updater", cl::init(false),
00083                                      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", cl::init(false),
00093                                         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, IRBuilderPrefixedInserter<true>>
00125     IRBuilderTy;
00126 #else
00127 typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
00128     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())
00175       return true;
00176     if (beginOffset() > RHS.beginOffset())
00177       return false;
00178     if (isSplittable() != RHS.isSplittable())
00179       return !isSplittable();
00180     if (endOffset() > RHS.endOffset())
00181       return true;
00182     return false;
00183   }
00184 
00185   /// \brief Support comparison with a single offset to allow binary searches.
00186   friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
00187                                               uint64_t RHSOffset) {
00188     return LHS.beginOffset() < RHSOffset;
00189   }
00190   friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
00191                                               const Slice &RHS) {
00192     return LHSOffset < RHS.beginOffset();
00193   }
00194 
00195   bool operator==(const Slice &RHS) const {
00196     return isSplittable() == RHS.isSplittable() &&
00197            beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
00198   }
00199   bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
00200 };
00201 } // end anonymous namespace
00202 
00203 namespace llvm {
00204 template <typename T> struct isPodLike;
00205 template <> struct isPodLike<Slice> { static const bool value = true; };
00206 }
00207 
00208 namespace {
00209 /// \brief Representation of the alloca slices.
00210 ///
00211 /// This class represents the slices of an alloca which are formed by its
00212 /// various uses. If a pointer escapes, we can't fully build a representation
00213 /// for the slices used and we reflect that in this structure. The uses are
00214 /// stored, sorted by increasing beginning offset and with unsplittable slices
00215 /// starting at a particular offset before splittable slices.
00216 class AllocaSlices {
00217 public:
00218   /// \brief Construct the slices of a particular alloca.
00219   AllocaSlices(const DataLayout &DL, AllocaInst &AI);
00220 
00221   /// \brief Test whether a pointer to the allocation escapes our analysis.
00222   ///
00223   /// If this is true, the slices are never fully built and should be
00224   /// ignored.
00225   bool isEscaped() const { return PointerEscapingInstr; }
00226 
00227   /// \brief Support for iterating over the slices.
00228   /// @{
00229   typedef SmallVectorImpl<Slice>::iterator iterator;
00230   typedef iterator_range<iterator> range;
00231   iterator begin() { return Slices.begin(); }
00232   iterator end() { return Slices.end(); }
00233 
00234   typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
00235   typedef iterator_range<const_iterator> const_range;
00236   const_iterator begin() const { return Slices.begin(); }
00237   const_iterator end() const { return Slices.end(); }
00238   /// @}
00239 
00240   /// \brief Erase a range of slices.
00241   void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
00242 
00243   /// \brief Insert new slices for this alloca.
00244   ///
00245   /// This moves the slices into the alloca's slices collection, and re-sorts
00246   /// everything so that the usual ordering properties of the alloca's slices
00247   /// hold.
00248   void insert(ArrayRef<Slice> NewSlices) {
00249     int OldSize = Slices.size();
00250     std::move(NewSlices.begin(), NewSlices.end(), std::back_inserter(Slices));
00251     auto SliceI = Slices.begin() + OldSize;
00252     std::sort(SliceI, Slices.end());
00253     std::inplace_merge(Slices.begin(), SliceI, Slices.end());
00254   }
00255 
00256   // Forward declare an iterator to befriend it.
00257   class partition_iterator;
00258 
00259   /// \brief A partition of the slices.
00260   ///
00261   /// An ephemeral representation for a range of slices which can be viewed as
00262   /// a partition of the alloca. This range represents a span of the alloca's
00263   /// memory which cannot be split, and provides access to all of the slices
00264   /// overlapping some part of the partition.
00265   ///
00266   /// Objects of this type are produced by traversing the alloca's slices, but
00267   /// are only ephemeral and not persistent.
00268   class Partition {
00269   private:
00270     friend class AllocaSlices;
00271     friend class AllocaSlices::partition_iterator;
00272 
00273     /// \brief The begining and ending offsets of the alloca for this partition.
00274     uint64_t BeginOffset, EndOffset;
00275 
00276     /// \brief The start end end iterators of this partition.
00277     iterator SI, SJ;
00278 
00279     /// \brief A collection of split slice tails overlapping the partition.
00280     SmallVector<Slice *, 4> SplitTails;
00281 
00282     /// \brief Raw constructor builds an empty partition starting and ending at
00283     /// the given iterator.
00284     Partition(iterator SI) : SI(SI), SJ(SI) {}
00285 
00286   public:
00287     /// \brief The start offset of this partition.
00288     ///
00289     /// All of the contained slices start at or after this offset.
00290     uint64_t beginOffset() const { return BeginOffset; }
00291 
00292     /// \brief The end offset of this partition.
00293     ///
00294     /// All of the contained slices end at or before this offset.
00295     uint64_t endOffset() const { return EndOffset; }
00296 
00297     /// \brief The size of the partition.
00298     ///
00299     /// Note that this can never be zero.
00300     uint64_t size() const {
00301       assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
00302       return EndOffset - BeginOffset;
00303     }
00304 
00305     /// \brief Test whether this partition contains no slices, and merely spans
00306     /// a region occupied by split slices.
00307     bool empty() const { return SI == SJ; }
00308 
00309     /// \name Iterate slices that start within the partition.
00310     /// These may be splittable or unsplittable. They have a begin offset >= the
00311     /// partition begin offset.
00312     /// @{
00313     // FIXME: We should probably define a "concat_iterator" helper and use that
00314     // to stitch together pointee_iterators over the split tails and the
00315     // contiguous iterators of the partition. That would give a much nicer
00316     // interface here. We could then additionally expose filtered iterators for
00317     // split, unsplit, and unsplittable splices based on the usage patterns.
00318     iterator begin() const { return SI; }
00319     iterator end() const { return SJ; }
00320     /// @}
00321 
00322     /// \brief Get the sequence of split slice tails.
00323     ///
00324     /// These tails are of slices which start before this partition but are
00325     /// split and overlap into the partition. We accumulate these while forming
00326     /// partitions.
00327     ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
00328   };
00329 
00330   /// \brief An iterator over partitions of the alloca's slices.
00331   ///
00332   /// This iterator implements the core algorithm for partitioning the alloca's
00333   /// slices. It is a forward iterator as we don't support backtracking for
00334   /// efficiency reasons, and re-use a single storage area to maintain the
00335   /// current set of split slices.
00336   ///
00337   /// It is templated on the slice iterator type to use so that it can operate
00338   /// with either const or non-const slice iterators.
00339   class partition_iterator
00340       : public iterator_facade_base<partition_iterator,
00341                                     std::forward_iterator_tag, Partition> {
00342     friend class AllocaSlices;
00343 
00344     /// \brief Most of the state for walking the partitions is held in a class
00345     /// with a nice interface for examining them.
00346     Partition P;
00347 
00348     /// \brief We need to keep the end of the slices to know when to stop.
00349     AllocaSlices::iterator SE;
00350 
00351     /// \brief We also need to keep track of the maximum split end offset seen.
00352     /// FIXME: Do we really?
00353     uint64_t MaxSplitSliceEndOffset;
00354 
00355     /// \brief Sets the partition to be empty at given iterator, and sets the
00356     /// end iterator.
00357     partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
00358         : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
00359       // If not already at the end, advance our state to form the initial
00360       // partition.
00361       if (SI != SE)
00362         advance();
00363     }
00364 
00365     /// \brief Advance the iterator to the next partition.
00366     ///
00367     /// Requires that the iterator not be at the end of the slices.
00368     void advance() {
00369       assert((P.SI != SE || !P.SplitTails.empty()) &&
00370              "Cannot advance past the end of the slices!");
00371 
00372       // Clear out any split uses which have ended.
00373       if (!P.SplitTails.empty()) {
00374         if (P.EndOffset >= MaxSplitSliceEndOffset) {
00375           // If we've finished all splits, this is easy.
00376           P.SplitTails.clear();
00377           MaxSplitSliceEndOffset = 0;
00378         } else {
00379           // Remove the uses which have ended in the prior partition. This
00380           // cannot change the max split slice end because we just checked that
00381           // the prior partition ended prior to that max.
00382           P.SplitTails.erase(
00383               std::remove_if(
00384                   P.SplitTails.begin(), P.SplitTails.end(),
00385                   [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
00386               P.SplitTails.end());
00387           assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
00388                              [&](Slice *S) {
00389                                return S->endOffset() == MaxSplitSliceEndOffset;
00390                              }) &&
00391                  "Could not find the current max split slice offset!");
00392           assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
00393                              [&](Slice *S) {
00394                                return S->endOffset() <= MaxSplitSliceEndOffset;
00395                              }) &&
00396                  "Max split slice end offset is not actually the max!");
00397         }
00398       }
00399 
00400       // If P.SI is already at the end, then we've cleared the split tail and
00401       // now have an end iterator.
00402       if (P.SI == SE) {
00403         assert(P.SplitTails.empty() && "Failed to clear the split slices!");
00404         return;
00405       }
00406 
00407       // If we had a non-empty partition previously, set up the state for
00408       // subsequent partitions.
00409       if (P.SI != P.SJ) {
00410         // Accumulate all the splittable slices which started in the old
00411         // partition into the split list.
00412         for (Slice &S : P)
00413           if (S.isSplittable() && S.endOffset() > P.EndOffset) {
00414             P.SplitTails.push_back(&S);
00415             MaxSplitSliceEndOffset =
00416                 std::max(S.endOffset(), MaxSplitSliceEndOffset);
00417           }
00418 
00419         // Start from the end of the previous partition.
00420         P.SI = P.SJ;
00421 
00422         // If P.SI is now at the end, we at most have a tail of split slices.
00423         if (P.SI == SE) {
00424           P.BeginOffset = P.EndOffset;
00425           P.EndOffset = MaxSplitSliceEndOffset;
00426           return;
00427         }
00428 
00429         // If the we have split slices and the next slice is after a gap and is
00430         // not splittable immediately form an empty partition for the split
00431         // slices up until the next slice begins.
00432         if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
00433             !P.SI->isSplittable()) {
00434           P.BeginOffset = P.EndOffset;
00435           P.EndOffset = P.SI->beginOffset();
00436           return;
00437         }
00438       }
00439 
00440       // OK, we need to consume new slices. Set the end offset based on the
00441       // current slice, and step SJ past it. The beginning offset of the
00442       // parttion is the beginning offset of the next slice unless we have
00443       // pre-existing split slices that are continuing, in which case we begin
00444       // at the prior end offset.
00445       P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
00446       P.EndOffset = P.SI->endOffset();
00447       ++P.SJ;
00448 
00449       // There are two strategies to form a partition based on whether the
00450       // partition starts with an unsplittable slice or a splittable slice.
00451       if (!P.SI->isSplittable()) {
00452         // When we're forming an unsplittable region, it must always start at
00453         // the first slice and will extend through its end.
00454         assert(P.BeginOffset == P.SI->beginOffset());
00455 
00456         // Form a partition including all of the overlapping slices with this
00457         // unsplittable slice.
00458         while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
00459           if (!P.SJ->isSplittable())
00460             P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
00461           ++P.SJ;
00462         }
00463 
00464         // We have a partition across a set of overlapping unsplittable
00465         // partitions.
00466         return;
00467       }
00468 
00469       // If we're starting with a splittable slice, then we need to form
00470       // a synthetic partition spanning it and any other overlapping splittable
00471       // splices.
00472       assert(P.SI->isSplittable() && "Forming a splittable partition!");
00473 
00474       // Collect all of the overlapping splittable slices.
00475       while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
00476              P.SJ->isSplittable()) {
00477         P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
00478         ++P.SJ;
00479       }
00480 
00481       // Back upiP.EndOffset if we ended the span early when encountering an
00482       // unsplittable slice. This synthesizes the early end offset of
00483       // a partition spanning only splittable slices.
00484       if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
00485         assert(!P.SJ->isSplittable());
00486         P.EndOffset = P.SJ->beginOffset();
00487       }
00488     }
00489 
00490   public:
00491     bool operator==(const partition_iterator &RHS) const {
00492       assert(SE == RHS.SE &&
00493              "End iterators don't match between compared partition iterators!");
00494 
00495       // The observed positions of partitions is marked by the P.SI iterator and
00496       // the emptyness of the split slices. The latter is only relevant when
00497       // P.SI == SE, as the end iterator will additionally have an empty split
00498       // slices list, but the prior may have the same P.SI and a tail of split
00499       // slices.
00500       if (P.SI == RHS.P.SI &&
00501           P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
00502         assert(P.SJ == RHS.P.SJ &&
00503                "Same set of slices formed two different sized partitions!");
00504         assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
00505                "Same slice position with differently sized non-empty split "
00506                "slice tails!");
00507         return true;
00508       }
00509       return false;
00510     }
00511 
00512     partition_iterator &operator++() {
00513       advance();
00514       return *this;
00515     }
00516 
00517     Partition &operator*() { return P; }
00518   };
00519 
00520   /// \brief A forward range over the partitions of the alloca's slices.
00521   ///
00522   /// This accesses an iterator range over the partitions of the alloca's
00523   /// slices. It computes these partitions on the fly based on the overlapping
00524   /// offsets of the slices and the ability to split them. It will visit "empty"
00525   /// partitions to cover regions of the alloca only accessed via split
00526   /// slices.
00527   iterator_range<partition_iterator> partitions() {
00528     return make_range(partition_iterator(begin(), end()),
00529                       partition_iterator(end(), end()));
00530   }
00531 
00532   /// \brief Access the dead users for this alloca.
00533   ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
00534 
00535   /// \brief Access the dead operands referring to this alloca.
00536   ///
00537   /// These are operands which have cannot actually be used to refer to the
00538   /// alloca as they are outside its range and the user doesn't correct for
00539   /// that. These mostly consist of PHI node inputs and the like which we just
00540   /// need to replace with undef.
00541   ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
00542 
00543 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00544   void print(raw_ostream &OS, const_iterator I, StringRef Indent = "  ") const;
00545   void printSlice(raw_ostream &OS, const_iterator I,
00546                   StringRef Indent = "  ") const;
00547   void printUse(raw_ostream &OS, const_iterator I,
00548                 StringRef Indent = "  ") const;
00549   void print(raw_ostream &OS) const;
00550   void dump(const_iterator I) const;
00551   void dump() const;
00552 #endif
00553 
00554 private:
00555   template <typename DerivedT, typename RetT = void> class BuilderBase;
00556   class SliceBuilder;
00557   friend class AllocaSlices::SliceBuilder;
00558 
00559 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00560   /// \brief Handle to alloca instruction to simplify method interfaces.
00561   AllocaInst &AI;
00562 #endif
00563 
00564   /// \brief The instruction responsible for this alloca not having a known set
00565   /// of slices.
00566   ///
00567   /// When an instruction (potentially) escapes the pointer to the alloca, we
00568   /// store a pointer to that here and abort trying to form slices of the
00569   /// alloca. This will be null if the alloca slices are analyzed successfully.
00570   Instruction *PointerEscapingInstr;
00571 
00572   /// \brief The slices of the alloca.
00573   ///
00574   /// We store a vector of the slices formed by uses of the alloca here. This
00575   /// vector is sorted by increasing begin offset, and then the unsplittable
00576   /// slices before the splittable ones. See the Slice inner class for more
00577   /// details.
00578   SmallVector<Slice, 8> Slices;
00579 
00580   /// \brief Instructions which will become dead if we rewrite the alloca.
00581   ///
00582   /// Note that these are not separated by slice. This is because we expect an
00583   /// alloca to be completely rewritten or not rewritten at all. If rewritten,
00584   /// all these instructions can simply be removed and replaced with undef as
00585   /// they come from outside of the allocated space.
00586   SmallVector<Instruction *, 8> DeadUsers;
00587 
00588   /// \brief Operands which will become dead if we rewrite the alloca.
00589   ///
00590   /// These are operands that in their particular use can be replaced with
00591   /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
00592   /// to PHI nodes and the like. They aren't entirely dead (there might be
00593   /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
00594   /// want to swap this particular input for undef to simplify the use lists of
00595   /// the alloca.
00596   SmallVector<Use *, 8> DeadOperands;
00597 };
00598 }
00599 
00600 static Value *foldSelectInst(SelectInst &SI) {
00601   // If the condition being selected on is a constant or the same value is
00602   // being selected between, fold the select. Yes this does (rarely) happen
00603   // early on.
00604   if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
00605     return SI.getOperand(1 + CI->isZero());
00606   if (SI.getOperand(1) == SI.getOperand(2))
00607     return SI.getOperand(1);
00608 
00609   return nullptr;
00610 }
00611 
00612 /// \brief A helper that folds a PHI node or a select.
00613 static Value *foldPHINodeOrSelectInst(Instruction &I) {
00614   if (PHINode *PN = dyn_cast<PHINode>(&I)) {
00615     // If PN merges together the same value, return that value.
00616     return PN->hasConstantValue();
00617   }
00618   return foldSelectInst(cast<SelectInst>(I));
00619 }
00620 
00621 /// \brief Builder for the alloca slices.
00622 ///
00623 /// This class builds a set of alloca slices by recursively visiting the uses
00624 /// of an alloca and making a slice for each load and store at each offset.
00625 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
00626   friend class PtrUseVisitor<SliceBuilder>;
00627   friend class InstVisitor<SliceBuilder>;
00628   typedef PtrUseVisitor<SliceBuilder> Base;
00629 
00630   const uint64_t AllocSize;
00631   AllocaSlices &AS;
00632 
00633   SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
00634   SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
00635 
00636   /// \brief Set to de-duplicate dead instructions found in the use walk.
00637   SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
00638 
00639 public:
00640   SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
00641       : PtrUseVisitor<SliceBuilder>(DL),
00642         AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
00643 
00644 private:
00645   void markAsDead(Instruction &I) {
00646     if (VisitedDeadInsts.insert(&I).second)
00647       AS.DeadUsers.push_back(&I);
00648   }
00649 
00650   void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
00651                  bool IsSplittable = false) {
00652     // Completely skip uses which have a zero size or start either before or
00653     // past the end of the allocation.
00654     if (Size == 0 || Offset.uge(AllocSize)) {
00655       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
00656                    << " which has zero size or starts outside of the "
00657                    << AllocSize << " byte alloca:\n"
00658                    << "    alloca: " << AS.AI << "\n"
00659                    << "       use: " << I << "\n");
00660       return markAsDead(I);
00661     }
00662 
00663     uint64_t BeginOffset = Offset.getZExtValue();
00664     uint64_t EndOffset = BeginOffset + Size;
00665 
00666     // Clamp the end offset to the end of the allocation. Note that this is
00667     // formulated to handle even the case where "BeginOffset + Size" overflows.
00668     // This may appear superficially to be something we could ignore entirely,
00669     // but that is not so! There may be widened loads or PHI-node uses where
00670     // some instructions are dead but not others. We can't completely ignore
00671     // them, and so have to record at least the information here.
00672     assert(AllocSize >= BeginOffset); // Established above.
00673     if (Size > AllocSize - BeginOffset) {
00674       DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
00675                    << " to remain within the " << AllocSize << " byte alloca:\n"
00676                    << "    alloca: " << AS.AI << "\n"
00677                    << "       use: " << I << "\n");
00678       EndOffset = AllocSize;
00679     }
00680 
00681     AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
00682   }
00683 
00684   void visitBitCastInst(BitCastInst &BC) {
00685     if (BC.use_empty())
00686       return markAsDead(BC);
00687 
00688     return Base::visitBitCastInst(BC);
00689   }
00690 
00691   void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
00692     if (GEPI.use_empty())
00693       return markAsDead(GEPI);
00694 
00695     if (SROAStrictInbounds && GEPI.isInBounds()) {
00696       // FIXME: This is a manually un-factored variant of the basic code inside
00697       // of GEPs with checking of the inbounds invariant specified in the
00698       // langref in a very strict sense. If we ever want to enable
00699       // SROAStrictInbounds, this code should be factored cleanly into
00700       // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
00701       // by writing out the code here where we have tho underlying allocation
00702       // size readily available.
00703       APInt GEPOffset = Offset;
00704       for (gep_type_iterator GTI = gep_type_begin(GEPI),
00705                              GTE = gep_type_end(GEPI);
00706            GTI != GTE; ++GTI) {
00707         ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
00708         if (!OpC)
00709           break;
00710 
00711         // Handle a struct index, which adds its field offset to the pointer.
00712         if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00713           unsigned ElementIdx = OpC->getZExtValue();
00714           const StructLayout *SL = DL.getStructLayout(STy);
00715           GEPOffset +=
00716               APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
00717         } else {
00718           // For array or vector indices, scale the index by the size of the
00719           // type.
00720           APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
00721           GEPOffset += Index * APInt(Offset.getBitWidth(),
00722                                      DL.getTypeAllocSize(GTI.getIndexedType()));
00723         }
00724 
00725         // If this index has computed an intermediate pointer which is not
00726         // inbounds, then the result of the GEP is a poison value and we can
00727         // delete it and all uses.
00728         if (GEPOffset.ugt(AllocSize))
00729           return markAsDead(GEPI);
00730       }
00731     }
00732 
00733     return Base::visitGetElementPtrInst(GEPI);
00734   }
00735 
00736   void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
00737                          uint64_t Size, bool IsVolatile) {
00738     // We allow splitting of non-volatile loads and stores where the type is an
00739     // integer type. These may be used to implement 'memcpy' or other "transfer
00740     // of bits" patterns.
00741     bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
00742 
00743     insertUse(I, Offset, Size, IsSplittable);
00744   }
00745 
00746   void visitLoadInst(LoadInst &LI) {
00747     assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
00748            "All simple FCA loads should have been pre-split");
00749 
00750     if (!IsOffsetKnown)
00751       return PI.setAborted(&LI);
00752 
00753     uint64_t Size = DL.getTypeStoreSize(LI.getType());
00754     return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
00755   }
00756 
00757   void visitStoreInst(StoreInst &SI) {
00758     Value *ValOp = SI.getValueOperand();
00759     if (ValOp == *U)
00760       return PI.setEscapedAndAborted(&SI);
00761     if (!IsOffsetKnown)
00762       return PI.setAborted(&SI);
00763 
00764     uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
00765 
00766     // If this memory access can be shown to *statically* extend outside the
00767     // bounds of of the allocation, it's behavior is undefined, so simply
00768     // ignore it. Note that this is more strict than the generic clamping
00769     // behavior of insertUse. We also try to handle cases which might run the
00770     // risk of overflow.
00771     // FIXME: We should instead consider the pointer to have escaped if this
00772     // function is being instrumented for addressing bugs or race conditions.
00773     if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
00774       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
00775                    << " which extends past the end of the " << AllocSize
00776                    << " byte alloca:\n"
00777                    << "    alloca: " << AS.AI << "\n"
00778                    << "       use: " << SI << "\n");
00779       return markAsDead(SI);
00780     }
00781 
00782     assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
00783            "All simple FCA stores should have been pre-split");
00784     handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
00785   }
00786 
00787   void visitMemSetInst(MemSetInst &II) {
00788     assert(II.getRawDest() == *U && "Pointer use is not the destination?");
00789     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
00790     if ((Length && Length->getValue() == 0) ||
00791         (IsOffsetKnown && Offset.uge(AllocSize)))
00792       // Zero-length mem transfer intrinsics can be ignored entirely.
00793       return markAsDead(II);
00794 
00795     if (!IsOffsetKnown)
00796       return PI.setAborted(&II);
00797 
00798     insertUse(II, Offset, Length ? Length->getLimitedValue()
00799                                  : AllocSize - Offset.getLimitedValue(),
00800               (bool)Length);
00801   }
00802 
00803   void visitMemTransferInst(MemTransferInst &II) {
00804     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
00805     if (Length && Length->getValue() == 0)
00806       // Zero-length mem transfer intrinsics can be ignored entirely.
00807       return markAsDead(II);
00808 
00809     // Because we can visit these intrinsics twice, also check to see if the
00810     // first time marked this instruction as dead. If so, skip it.
00811     if (VisitedDeadInsts.count(&II))
00812       return;
00813 
00814     if (!IsOffsetKnown)
00815       return PI.setAborted(&II);
00816 
00817     // This side of the transfer is completely out-of-bounds, and so we can
00818     // nuke the entire transfer. However, we also need to nuke the other side
00819     // if already added to our partitions.
00820     // FIXME: Yet another place we really should bypass this when
00821     // instrumenting for ASan.
00822     if (Offset.uge(AllocSize)) {
00823       SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
00824           MemTransferSliceMap.find(&II);
00825       if (MTPI != MemTransferSliceMap.end())
00826         AS.Slices[MTPI->second].kill();
00827       return markAsDead(II);
00828     }
00829 
00830     uint64_t RawOffset = Offset.getLimitedValue();
00831     uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
00832 
00833     // Check for the special case where the same exact value is used for both
00834     // source and dest.
00835     if (*U == II.getRawDest() && *U == II.getRawSource()) {
00836       // For non-volatile transfers this is a no-op.
00837       if (!II.isVolatile())
00838         return markAsDead(II);
00839 
00840       return insertUse(II, Offset, Size, /*IsSplittable=*/false);
00841     }
00842 
00843     // If we have seen both source and destination for a mem transfer, then
00844     // they both point to the same alloca.
00845     bool Inserted;
00846     SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
00847     std::tie(MTPI, Inserted) =
00848         MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
00849     unsigned PrevIdx = MTPI->second;
00850     if (!Inserted) {
00851       Slice &PrevP = AS.Slices[PrevIdx];
00852 
00853       // Check if the begin offsets match and this is a non-volatile transfer.
00854       // In that case, we can completely elide the transfer.
00855       if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
00856         PrevP.kill();
00857         return markAsDead(II);
00858       }
00859 
00860       // Otherwise we have an offset transfer within the same alloca. We can't
00861       // split those.
00862       PrevP.makeUnsplittable();
00863     }
00864 
00865     // Insert the use now that we've fixed up the splittable nature.
00866     insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
00867 
00868     // Check that we ended up with a valid index in the map.
00869     assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
00870            "Map index doesn't point back to a slice with this user.");
00871   }
00872 
00873   // Disable SRoA for any intrinsics except for lifetime invariants.
00874   // FIXME: What about debug intrinsics? This matches old behavior, but
00875   // doesn't make sense.
00876   void visitIntrinsicInst(IntrinsicInst &II) {
00877     if (!IsOffsetKnown)
00878       return PI.setAborted(&II);
00879 
00880     if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
00881         II.getIntrinsicID() == Intrinsic::lifetime_end) {
00882       ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
00883       uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
00884                                Length->getLimitedValue());
00885       insertUse(II, Offset, Size, true);
00886       return;
00887     }
00888 
00889     Base::visitIntrinsicInst(II);
00890   }
00891 
00892   Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
00893     // We consider any PHI or select that results in a direct load or store of
00894     // the same offset to be a viable use for slicing purposes. These uses
00895     // are considered unsplittable and the size is the maximum loaded or stored
00896     // size.
00897     SmallPtrSet<Instruction *, 4> Visited;
00898     SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
00899     Visited.insert(Root);
00900     Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
00901     // If there are no loads or stores, the access is dead. We mark that as
00902     // a size zero access.
00903     Size = 0;
00904     do {
00905       Instruction *I, *UsedI;
00906       std::tie(UsedI, I) = Uses.pop_back_val();
00907 
00908       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00909         Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
00910         continue;
00911       }
00912       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00913         Value *Op = SI->getOperand(0);
00914         if (Op == UsedI)
00915           return SI;
00916         Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
00917         continue;
00918       }
00919 
00920       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
00921         if (!GEP->hasAllZeroIndices())
00922           return GEP;
00923       } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
00924                  !isa<SelectInst>(I)) {
00925         return I;
00926       }
00927 
00928       for (User *U : I->users())
00929         if (Visited.insert(cast<Instruction>(U)).second)
00930           Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
00931     } while (!Uses.empty());
00932 
00933     return nullptr;
00934   }
00935 
00936   void visitPHINodeOrSelectInst(Instruction &I) {
00937     assert(isa<PHINode>(I) || isa<SelectInst>(I));
00938     if (I.use_empty())
00939       return markAsDead(I);
00940 
00941     // TODO: We could use SimplifyInstruction here to fold PHINodes and
00942     // SelectInsts. However, doing so requires to change the current
00943     // dead-operand-tracking mechanism. For instance, suppose neither loading
00944     // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
00945     // trap either.  However, if we simply replace %U with undef using the
00946     // current dead-operand-tracking mechanism, "load (select undef, undef,
00947     // %other)" may trap because the select may return the first operand
00948     // "undef".
00949     if (Value *Result = foldPHINodeOrSelectInst(I)) {
00950       if (Result == *U)
00951         // If the result of the constant fold will be the pointer, recurse
00952         // through the PHI/select as if we had RAUW'ed it.
00953         enqueueUsers(I);
00954       else
00955         // Otherwise the operand to the PHI/select is dead, and we can replace
00956         // it with undef.
00957         AS.DeadOperands.push_back(U);
00958 
00959       return;
00960     }
00961 
00962     if (!IsOffsetKnown)
00963       return PI.setAborted(&I);
00964 
00965     // See if we already have computed info on this node.
00966     uint64_t &Size = PHIOrSelectSizes[&I];
00967     if (!Size) {
00968       // This is a new PHI/Select, check for an unsafe use of it.
00969       if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
00970         return PI.setAborted(UnsafeI);
00971     }
00972 
00973     // For PHI and select operands outside the alloca, we can't nuke the entire
00974     // phi or select -- the other side might still be relevant, so we special
00975     // case them here and use a separate structure to track the operands
00976     // themselves which should be replaced with undef.
00977     // FIXME: This should instead be escaped in the event we're instrumenting
00978     // for address sanitization.
00979     if (Offset.uge(AllocSize)) {
00980       AS.DeadOperands.push_back(U);
00981       return;
00982     }
00983 
00984     insertUse(I, Offset, Size);
00985   }
00986 
00987   void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
00988 
00989   void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
00990 
00991   /// \brief Disable SROA entirely if there are unhandled users of the alloca.
00992   void visitInstruction(Instruction &I) { PI.setAborted(&I); }
00993 };
00994 
00995 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
00996     :
00997 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00998       AI(AI),
00999 #endif
01000       PointerEscapingInstr(nullptr) {
01001   SliceBuilder PB(DL, AI, *this);
01002   SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
01003   if (PtrI.isEscaped() || PtrI.isAborted()) {
01004     // FIXME: We should sink the escape vs. abort info into the caller nicely,
01005     // possibly by just storing the PtrInfo in the AllocaSlices.
01006     PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
01007                                                   : PtrI.getAbortingInst();
01008     assert(PointerEscapingInstr && "Did not track a bad instruction");
01009     return;
01010   }
01011 
01012   Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
01013                               [](const Slice &S) {
01014                                 return S.isDead();
01015                               }),
01016                Slices.end());
01017 
01018 #if __cplusplus >= 201103L && !defined(NDEBUG)
01019   if (SROARandomShuffleSlices) {
01020     std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
01021     std::shuffle(Slices.begin(), Slices.end(), MT);
01022   }
01023 #endif
01024 
01025   // Sort the uses. This arranges for the offsets to be in ascending order,
01026   // and the sizes to be in descending order.
01027   std::sort(Slices.begin(), Slices.end());
01028 }
01029 
01030 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01031 
01032 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
01033                          StringRef Indent) const {
01034   printSlice(OS, I, Indent);
01035   OS << "\n";
01036   printUse(OS, I, Indent);
01037 }
01038 
01039 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
01040                               StringRef Indent) const {
01041   OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
01042      << " slice #" << (I - begin())
01043      << (I->isSplittable() ? " (splittable)" : "");
01044 }
01045 
01046 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
01047                             StringRef Indent) const {
01048   OS << Indent << "  used by: " << *I->getUse()->getUser() << "\n";
01049 }
01050 
01051 void AllocaSlices::print(raw_ostream &OS) const {
01052   if (PointerEscapingInstr) {
01053     OS << "Can't analyze slices for alloca: " << AI << "\n"
01054        << "  A pointer to this alloca escaped by:\n"
01055        << "  " << *PointerEscapingInstr << "\n";
01056     return;
01057   }
01058 
01059   OS << "Slices of alloca: " << AI << "\n";
01060   for (const_iterator I = begin(), E = end(); I != E; ++I)
01061     print(OS, I);
01062 }
01063 
01064 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
01065   print(dbgs(), I);
01066 }
01067 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
01068 
01069 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01070 
01071 namespace {
01072 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
01073 ///
01074 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
01075 /// the loads and stores of an alloca instruction, as well as updating its
01076 /// debug information. This is used when a domtree is unavailable and thus
01077 /// mem2reg in its full form can't be used to handle promotion of allocas to
01078 /// scalar values.
01079 class AllocaPromoter : public LoadAndStorePromoter {
01080   AllocaInst &AI;
01081   DIBuilder &DIB;
01082 
01083   SmallVector<DbgDeclareInst *, 4> DDIs;
01084   SmallVector<DbgValueInst *, 4> DVIs;
01085 
01086 public:
01087   AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
01088                  AllocaInst &AI, DIBuilder &DIB)
01089       : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
01090 
01091   void run(const SmallVectorImpl<Instruction *> &Insts) {
01092     // Retain the debug information attached to the alloca for use when
01093     // rewriting loads and stores.
01094     if (auto *L = LocalAsMetadata::getIfExists(&AI)) {
01095       if (auto *DebugNode = MetadataAsValue::getIfExists(AI.getContext(), L)) {
01096         for (User *U : DebugNode->users())
01097           if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
01098             DDIs.push_back(DDI);
01099           else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
01100             DVIs.push_back(DVI);
01101       }
01102     }
01103 
01104     LoadAndStorePromoter::run(Insts);
01105 
01106     // While we have the debug information, clear it off of the alloca. The
01107     // caller takes care of deleting the alloca.
01108     while (!DDIs.empty())
01109       DDIs.pop_back_val()->eraseFromParent();
01110     while (!DVIs.empty())
01111       DVIs.pop_back_val()->eraseFromParent();
01112   }
01113 
01114   bool
01115   isInstInList(Instruction *I,
01116                const SmallVectorImpl<Instruction *> &Insts) const override {
01117     Value *Ptr;
01118     if (LoadInst *LI = dyn_cast<LoadInst>(I))
01119       Ptr = LI->getOperand(0);
01120     else
01121       Ptr = cast<StoreInst>(I)->getPointerOperand();
01122 
01123     // Only used to detect cycles, which will be rare and quickly found as
01124     // we're walking up a chain of defs rather than down through uses.
01125     SmallPtrSet<Value *, 4> Visited;
01126 
01127     do {
01128       if (Ptr == &AI)
01129         return true;
01130 
01131       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
01132         Ptr = BCI->getOperand(0);
01133       else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
01134         Ptr = GEPI->getPointerOperand();
01135       else
01136         return false;
01137 
01138     } while (Visited.insert(Ptr).second);
01139 
01140     return false;
01141   }
01142 
01143   void updateDebugInfo(Instruction *Inst) const override {
01144     for (DbgDeclareInst *DDI : DDIs)
01145       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
01146         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
01147       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
01148         ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
01149     for (DbgValueInst *DVI : DVIs) {
01150       Value *Arg = nullptr;
01151       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
01152         // If an argument is zero extended then use argument directly. The ZExt
01153         // may be zapped by an optimization pass in future.
01154         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
01155           Arg = dyn_cast<Argument>(ZExt->getOperand(0));
01156         else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
01157           Arg = dyn_cast<Argument>(SExt->getOperand(0));
01158         if (!Arg)
01159           Arg = SI->getValueOperand();
01160       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
01161         Arg = LI->getPointerOperand();
01162       } else {
01163         continue;
01164       }
01165       Instruction *DbgVal =
01166           DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
01167                                       DIExpression(DVI->getExpression()), Inst);
01168       DbgVal->setDebugLoc(DVI->getDebugLoc());
01169     }
01170   }
01171 };
01172 } // end anon namespace
01173 
01174 namespace {
01175 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
01176 ///
01177 /// This pass takes allocations which can be completely analyzed (that is, they
01178 /// don't escape) and tries to turn them into scalar SSA values. There are
01179 /// a few steps to this process.
01180 ///
01181 /// 1) It takes allocations of aggregates and analyzes the ways in which they
01182 ///    are used to try to split them into smaller allocations, ideally of
01183 ///    a single scalar data type. It will split up memcpy and memset accesses
01184 ///    as necessary and try to isolate individual scalar accesses.
01185 /// 2) It will transform accesses into forms which are suitable for SSA value
01186 ///    promotion. This can be replacing a memset with a scalar store of an
01187 ///    integer value, or it can involve speculating operations on a PHI or
01188 ///    select to be a PHI or select of the results.
01189 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
01190 ///    onto insert and extract operations on a vector value, and convert them to
01191 ///    this form. By doing so, it will enable promotion of vector aggregates to
01192 ///    SSA vector values.
01193 class SROA : public FunctionPass {
01194   const bool RequiresDomTree;
01195 
01196   LLVMContext *C;
01197   const DataLayout *DL;
01198   DominatorTree *DT;
01199   AssumptionCache *AC;
01200 
01201   /// \brief Worklist of alloca instructions to simplify.
01202   ///
01203   /// Each alloca in the function is added to this. Each new alloca formed gets
01204   /// added to it as well to recursively simplify unless that alloca can be
01205   /// directly promoted. Finally, each time we rewrite a use of an alloca other
01206   /// the one being actively rewritten, we add it back onto the list if not
01207   /// already present to ensure it is re-visited.
01208   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> Worklist;
01209 
01210   /// \brief A collection of instructions to delete.
01211   /// We try to batch deletions to simplify code and make things a bit more
01212   /// efficient.
01213   SetVector<Instruction *, SmallVector<Instruction *, 8>> DeadInsts;
01214 
01215   /// \brief Post-promotion worklist.
01216   ///
01217   /// Sometimes we discover an alloca which has a high probability of becoming
01218   /// viable for SROA after a round of promotion takes place. In those cases,
01219   /// the alloca is enqueued here for re-processing.
01220   ///
01221   /// Note that we have to be very careful to clear allocas out of this list in
01222   /// the event they are deleted.
01223   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> PostPromotionWorklist;
01224 
01225   /// \brief A collection of alloca instructions we can directly promote.
01226   std::vector<AllocaInst *> PromotableAllocas;
01227 
01228   /// \brief A worklist of PHIs to speculate prior to promoting allocas.
01229   ///
01230   /// All of these PHIs have been checked for the safety of speculation and by
01231   /// being speculated will allow promoting allocas currently in the promotable
01232   /// queue.
01233   SetVector<PHINode *, SmallVector<PHINode *, 2>> SpeculatablePHIs;
01234 
01235   /// \brief A worklist of select instructions to speculate prior to promoting
01236   /// allocas.
01237   ///
01238   /// All of these select instructions have been checked for the safety of
01239   /// speculation and by being speculated will allow promoting allocas
01240   /// currently in the promotable queue.
01241   SetVector<SelectInst *, SmallVector<SelectInst *, 2>> SpeculatableSelects;
01242 
01243 public:
01244   SROA(bool RequiresDomTree = true)
01245       : FunctionPass(ID), RequiresDomTree(RequiresDomTree), C(nullptr),
01246         DL(nullptr), DT(nullptr) {
01247     initializeSROAPass(*PassRegistry::getPassRegistry());
01248   }
01249   bool runOnFunction(Function &F) override;
01250   void getAnalysisUsage(AnalysisUsage &AU) const override;
01251 
01252   const char *getPassName() const override { return "SROA"; }
01253   static char ID;
01254 
01255 private:
01256   friend class PHIOrSelectSpeculator;
01257   friend class AllocaSliceRewriter;
01258 
01259   bool presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS);
01260   AllocaInst *rewritePartition(AllocaInst &AI, AllocaSlices &AS,
01261                                AllocaSlices::Partition &P);
01262   bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
01263   bool runOnAlloca(AllocaInst &AI);
01264   void clobberUse(Use &U);
01265   void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
01266   bool promoteAllocas(Function &F);
01267 };
01268 }
01269 
01270 char SROA::ID = 0;
01271 
01272 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
01273   return new SROA(RequiresDomTree);
01274 }
01275 
01276 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
01277                       false)
01278 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
01279 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
01280 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
01281                     false)
01282 
01283 /// Walk the range of a partitioning looking for a common type to cover this
01284 /// sequence of slices.
01285 static Type *findCommonType(AllocaSlices::const_iterator B,
01286                             AllocaSlices::const_iterator E,
01287                             uint64_t EndOffset) {
01288   Type *Ty = nullptr;
01289   bool TyIsCommon = true;
01290   IntegerType *ITy = nullptr;
01291 
01292   // Note that we need to look at *every* alloca slice's Use to ensure we
01293   // always get consistent results regardless of the order of slices.
01294   for (AllocaSlices::const_iterator I = B; I != E; ++I) {
01295     Use *U = I->getUse();
01296     if (isa<IntrinsicInst>(*U->getUser()))
01297       continue;
01298     if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
01299       continue;
01300 
01301     Type *UserTy = nullptr;
01302     if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01303       UserTy = LI->getType();
01304     } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01305       UserTy = SI->getValueOperand()->getType();
01306     }
01307 
01308     if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
01309       // If the type is larger than the partition, skip it. We only encounter
01310       // this for split integer operations where we want to use the type of the
01311       // entity causing the split. Also skip if the type is not a byte width
01312       // multiple.
01313       if (UserITy->getBitWidth() % 8 != 0 ||
01314           UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
01315         continue;
01316 
01317       // Track the largest bitwidth integer type used in this way in case there
01318       // is no common type.
01319       if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
01320         ITy = UserITy;
01321     }
01322 
01323     // To avoid depending on the order of slices, Ty and TyIsCommon must not
01324     // depend on types skipped above.
01325     if (!UserTy || (Ty && Ty != UserTy))
01326       TyIsCommon = false; // Give up on anything but an iN type.
01327     else
01328       Ty = UserTy;
01329   }
01330 
01331   return TyIsCommon ? Ty : ITy;
01332 }
01333 
01334 /// PHI instructions that use an alloca and are subsequently loaded can be
01335 /// rewritten to load both input pointers in the pred blocks and then PHI the
01336 /// results, allowing the load of the alloca to be promoted.
01337 /// From this:
01338 ///   %P2 = phi [i32* %Alloca, i32* %Other]
01339 ///   %V = load i32* %P2
01340 /// to:
01341 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01342 ///   ...
01343 ///   %V2 = load i32* %Other
01344 ///   ...
01345 ///   %V = phi [i32 %V1, i32 %V2]
01346 ///
01347 /// We can do this to a select if its only uses are loads and if the operands
01348 /// to the select can be loaded unconditionally.
01349 ///
01350 /// FIXME: This should be hoisted into a generic utility, likely in
01351 /// Transforms/Util/Local.h
01352 static bool isSafePHIToSpeculate(PHINode &PN, const DataLayout *DL = nullptr) {
01353   // For now, we can only do this promotion if the load is in the same block
01354   // as the PHI, and if there are no stores between the phi and load.
01355   // TODO: Allow recursive phi users.
01356   // TODO: Allow stores.
01357   BasicBlock *BB = PN.getParent();
01358   unsigned MaxAlign = 0;
01359   bool HaveLoad = false;
01360   for (User *U : PN.users()) {
01361     LoadInst *LI = dyn_cast<LoadInst>(U);
01362     if (!LI || !LI->isSimple())
01363       return false;
01364 
01365     // For now we only allow loads in the same block as the PHI.  This is
01366     // a common case that happens when instcombine merges two loads through
01367     // a PHI.
01368     if (LI->getParent() != BB)
01369       return false;
01370 
01371     // Ensure that there are no instructions between the PHI and the load that
01372     // could store.
01373     for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
01374       if (BBI->mayWriteToMemory())
01375         return false;
01376 
01377     MaxAlign = std::max(MaxAlign, LI->getAlignment());
01378     HaveLoad = true;
01379   }
01380 
01381   if (!HaveLoad)
01382     return false;
01383 
01384   // We can only transform this if it is safe to push the loads into the
01385   // predecessor blocks. The only thing to watch out for is that we can't put
01386   // a possibly trapping load in the predecessor if it is a critical edge.
01387   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
01388     TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
01389     Value *InVal = PN.getIncomingValue(Idx);
01390 
01391     // If the value is produced by the terminator of the predecessor (an
01392     // invoke) or it has side-effects, there is no valid place to put a load
01393     // in the predecessor.
01394     if (TI == InVal || TI->mayHaveSideEffects())
01395       return false;
01396 
01397     // If the predecessor has a single successor, then the edge isn't
01398     // critical.
01399     if (TI->getNumSuccessors() == 1)
01400       continue;
01401 
01402     // If this pointer is always safe to load, or if we can prove that there
01403     // is already a load in the block, then we can move the load to the pred
01404     // block.
01405     if (InVal->isDereferenceablePointer(DL) ||
01406         isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
01407       continue;
01408 
01409     return false;
01410   }
01411 
01412   return true;
01413 }
01414 
01415 static void speculatePHINodeLoads(PHINode &PN) {
01416   DEBUG(dbgs() << "    original: " << PN << "\n");
01417 
01418   Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
01419   IRBuilderTy PHIBuilder(&PN);
01420   PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
01421                                         PN.getName() + ".sroa.speculated");
01422 
01423   // Get the AA tags and alignment to use from one of the loads.  It doesn't
01424   // matter which one we get and if any differ.
01425   LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
01426 
01427   AAMDNodes AATags;
01428   SomeLoad->getAAMetadata(AATags);
01429   unsigned Align = SomeLoad->getAlignment();
01430 
01431   // Rewrite all loads of the PN to use the new PHI.
01432   while (!PN.use_empty()) {
01433     LoadInst *LI = cast<LoadInst>(PN.user_back());
01434     LI->replaceAllUsesWith(NewPN);
01435     LI->eraseFromParent();
01436   }
01437 
01438   // Inject loads into all of the pred blocks.
01439   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
01440     BasicBlock *Pred = PN.getIncomingBlock(Idx);
01441     TerminatorInst *TI = Pred->getTerminator();
01442     Value *InVal = PN.getIncomingValue(Idx);
01443     IRBuilderTy PredBuilder(TI);
01444 
01445     LoadInst *Load = PredBuilder.CreateLoad(
01446         InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
01447     ++NumLoadsSpeculated;
01448     Load->setAlignment(Align);
01449     if (AATags)
01450       Load->setAAMetadata(AATags);
01451     NewPN->addIncoming(Load, Pred);
01452   }
01453 
01454   DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
01455   PN.eraseFromParent();
01456 }
01457 
01458 /// Select instructions that use an alloca and are subsequently loaded can be
01459 /// rewritten to load both input pointers and then select between the result,
01460 /// allowing the load of the alloca to be promoted.
01461 /// From this:
01462 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
01463 ///   %V = load i32* %P2
01464 /// to:
01465 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01466 ///   %V2 = load i32* %Other
01467 ///   %V = select i1 %cond, i32 %V1, i32 %V2
01468 ///
01469 /// We can do this to a select if its only uses are loads and if the operand
01470 /// to the select can be loaded unconditionally.
01471 static bool isSafeSelectToSpeculate(SelectInst &SI,
01472                                     const DataLayout *DL = nullptr) {
01473   Value *TValue = SI.getTrueValue();
01474   Value *FValue = SI.getFalseValue();
01475   bool TDerefable = TValue->isDereferenceablePointer(DL);
01476   bool FDerefable = FValue->isDereferenceablePointer(DL);
01477 
01478   for (User *U : SI.users()) {
01479     LoadInst *LI = dyn_cast<LoadInst>(U);
01480     if (!LI || !LI->isSimple())
01481       return false;
01482 
01483     // Both operands to the select need to be dereferencable, either
01484     // absolutely (e.g. allocas) or at this point because we can see other
01485     // accesses to it.
01486     if (!TDerefable &&
01487         !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
01488       return false;
01489     if (!FDerefable &&
01490         !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
01491       return false;
01492   }
01493 
01494   return true;
01495 }
01496 
01497 static void speculateSelectInstLoads(SelectInst &SI) {
01498   DEBUG(dbgs() << "    original: " << SI << "\n");
01499 
01500   IRBuilderTy IRB(&SI);
01501   Value *TV = SI.getTrueValue();
01502   Value *FV = SI.getFalseValue();
01503   // Replace the loads of the select with a select of two loads.
01504   while (!SI.use_empty()) {
01505     LoadInst *LI = cast<LoadInst>(SI.user_back());
01506     assert(LI->isSimple() && "We only speculate simple loads");
01507 
01508     IRB.SetInsertPoint(LI);
01509     LoadInst *TL =
01510         IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
01511     LoadInst *FL =
01512         IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
01513     NumLoadsSpeculated += 2;
01514 
01515     // Transfer alignment and AA info if present.
01516     TL->setAlignment(LI->getAlignment());
01517     FL->setAlignment(LI->getAlignment());
01518 
01519     AAMDNodes Tags;
01520     LI->getAAMetadata(Tags);
01521     if (Tags) {
01522       TL->setAAMetadata(Tags);
01523       FL->setAAMetadata(Tags);
01524     }
01525 
01526     Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
01527                                 LI->getName() + ".sroa.speculated");
01528 
01529     DEBUG(dbgs() << "          speculated to: " << *V << "\n");
01530     LI->replaceAllUsesWith(V);
01531     LI->eraseFromParent();
01532   }
01533   SI.eraseFromParent();
01534 }
01535 
01536 /// \brief Build a GEP out of a base pointer and indices.
01537 ///
01538 /// This will return the BasePtr if that is valid, or build a new GEP
01539 /// instruction using the IRBuilder if GEP-ing is needed.
01540 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
01541                        SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
01542   if (Indices.empty())
01543     return BasePtr;
01544 
01545   // A single zero index is a no-op, so check for this and avoid building a GEP
01546   // in that case.
01547   if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
01548     return BasePtr;
01549 
01550   return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
01551 }
01552 
01553 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
01554 /// TargetTy without changing the offset of the pointer.
01555 ///
01556 /// This routine assumes we've already established a properly offset GEP with
01557 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
01558 /// zero-indices down through type layers until we find one the same as
01559 /// TargetTy. If we can't find one with the same type, we at least try to use
01560 /// one with the same size. If none of that works, we just produce the GEP as
01561 /// indicated by Indices to have the correct offset.
01562 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
01563                                     Value *BasePtr, Type *Ty, Type *TargetTy,
01564                                     SmallVectorImpl<Value *> &Indices,
01565                                     Twine NamePrefix) {
01566   if (Ty == TargetTy)
01567     return buildGEP(IRB, BasePtr, Indices, NamePrefix);
01568 
01569   // Pointer size to use for the indices.
01570   unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
01571 
01572   // See if we can descend into a struct and locate a field with the correct
01573   // type.
01574   unsigned NumLayers = 0;
01575   Type *ElementTy = Ty;
01576   do {
01577     if (ElementTy->isPointerTy())
01578       break;
01579 
01580     if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
01581       ElementTy = ArrayTy->getElementType();
01582       Indices.push_back(IRB.getIntN(PtrSize, 0));
01583     } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
01584       ElementTy = VectorTy->getElementType();
01585       Indices.push_back(IRB.getInt32(0));
01586     } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
01587       if (STy->element_begin() == STy->element_end())
01588         break; // Nothing left to descend into.
01589       ElementTy = *STy->element_begin();
01590       Indices.push_back(IRB.getInt32(0));
01591     } else {
01592       break;
01593     }
01594     ++NumLayers;
01595   } while (ElementTy != TargetTy);
01596   if (ElementTy != TargetTy)
01597     Indices.erase(Indices.end() - NumLayers, Indices.end());
01598 
01599   return buildGEP(IRB, BasePtr, Indices, NamePrefix);
01600 }
01601 
01602 /// \brief Recursively compute indices for a natural GEP.
01603 ///
01604 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
01605 /// element types adding appropriate indices for the GEP.
01606 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
01607                                        Value *Ptr, Type *Ty, APInt &Offset,
01608                                        Type *TargetTy,
01609                                        SmallVectorImpl<Value *> &Indices,
01610                                        Twine NamePrefix) {
01611   if (Offset == 0)
01612     return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
01613                                  NamePrefix);
01614 
01615   // We can't recurse through pointer types.
01616   if (Ty->isPointerTy())
01617     return nullptr;
01618 
01619   // We try to analyze GEPs over vectors here, but note that these GEPs are
01620   // extremely poorly defined currently. The long-term goal is to remove GEPing
01621   // over a vector from the IR completely.
01622   if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
01623     unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
01624     if (ElementSizeInBits % 8 != 0) {
01625       // GEPs over non-multiple of 8 size vector elements are invalid.
01626       return nullptr;
01627     }
01628     APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
01629     APInt NumSkippedElements = Offset.sdiv(ElementSize);
01630     if (NumSkippedElements.ugt(VecTy->getNumElements()))
01631       return nullptr;
01632     Offset -= NumSkippedElements * ElementSize;
01633     Indices.push_back(IRB.getInt(NumSkippedElements));
01634     return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
01635                                     Offset, TargetTy, Indices, NamePrefix);
01636   }
01637 
01638   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
01639     Type *ElementTy = ArrTy->getElementType();
01640     APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
01641     APInt NumSkippedElements = Offset.sdiv(ElementSize);
01642     if (NumSkippedElements.ugt(ArrTy->getNumElements()))
01643       return nullptr;
01644 
01645     Offset -= NumSkippedElements * ElementSize;
01646     Indices.push_back(IRB.getInt(NumSkippedElements));
01647     return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01648                                     Indices, NamePrefix);
01649   }
01650 
01651   StructType *STy = dyn_cast<StructType>(Ty);
01652   if (!STy)
01653     return nullptr;
01654 
01655   const StructLayout *SL = DL.getStructLayout(STy);
01656   uint64_t StructOffset = Offset.getZExtValue();
01657   if (StructOffset >= SL->getSizeInBytes())
01658     return nullptr;
01659   unsigned Index = SL->getElementContainingOffset(StructOffset);
01660   Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
01661   Type *ElementTy = STy->getElementType(Index);
01662   if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
01663     return nullptr; // The offset points into alignment padding.
01664 
01665   Indices.push_back(IRB.getInt32(Index));
01666   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01667                                   Indices, NamePrefix);
01668 }
01669 
01670 /// \brief Get a natural GEP from a base pointer to a particular offset and
01671 /// resulting in a particular type.
01672 ///
01673 /// The goal is to produce a "natural" looking GEP that works with the existing
01674 /// composite types to arrive at the appropriate offset and element type for
01675 /// a pointer. TargetTy is the element type the returned GEP should point-to if
01676 /// possible. We recurse by decreasing Offset, adding the appropriate index to
01677 /// Indices, and setting Ty to the result subtype.
01678 ///
01679 /// If no natural GEP can be constructed, this function returns null.
01680 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
01681                                       Value *Ptr, APInt Offset, Type *TargetTy,
01682                                       SmallVectorImpl<Value *> &Indices,
01683                                       Twine NamePrefix) {
01684   PointerType *Ty = cast<PointerType>(Ptr->getType());
01685 
01686   // Don't consider any GEPs through an i8* as natural unless the TargetTy is
01687   // an i8.
01688   if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
01689     return nullptr;
01690 
01691   Type *ElementTy = Ty->getElementType();
01692   if (!ElementTy->isSized())
01693     return nullptr; // We can't GEP through an unsized element.
01694   APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
01695   if (ElementSize == 0)
01696     return nullptr; // Zero-length arrays can't help us build a natural GEP.
01697   APInt NumSkippedElements = Offset.sdiv(ElementSize);
01698 
01699   Offset -= NumSkippedElements * ElementSize;
01700   Indices.push_back(IRB.getInt(NumSkippedElements));
01701   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01702                                   Indices, NamePrefix);
01703 }
01704 
01705 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
01706 /// resulting pointer has PointerTy.
01707 ///
01708 /// This tries very hard to compute a "natural" GEP which arrives at the offset
01709 /// and produces the pointer type desired. Where it cannot, it will try to use
01710 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
01711 /// fails, it will try to use an existing i8* and GEP to the byte offset and
01712 /// bitcast to the type.
01713 ///
01714 /// The strategy for finding the more natural GEPs is to peel off layers of the
01715 /// pointer, walking back through bit casts and GEPs, searching for a base
01716 /// pointer from which we can compute a natural GEP with the desired
01717 /// properties. The algorithm tries to fold as many constant indices into
01718 /// a single GEP as possible, thus making each GEP more independent of the
01719 /// surrounding code.
01720 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
01721                              APInt Offset, Type *PointerTy, Twine NamePrefix) {
01722   // Even though we don't look through PHI nodes, we could be called on an
01723   // instruction in an unreachable block, which may be on a cycle.
01724   SmallPtrSet<Value *, 4> Visited;
01725   Visited.insert(Ptr);
01726   SmallVector<Value *, 4> Indices;
01727 
01728   // We may end up computing an offset pointer that has the wrong type. If we
01729   // never are able to compute one directly that has the correct type, we'll
01730   // fall back to it, so keep it and the base it was computed from around here.
01731   Value *OffsetPtr = nullptr;
01732   Value *OffsetBasePtr;
01733 
01734   // Remember any i8 pointer we come across to re-use if we need to do a raw
01735   // byte offset.
01736   Value *Int8Ptr = nullptr;
01737   APInt Int8PtrOffset(Offset.getBitWidth(), 0);
01738 
01739   Type *TargetTy = PointerTy->getPointerElementType();
01740 
01741   do {
01742     // First fold any existing GEPs into the offset.
01743     while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
01744       APInt GEPOffset(Offset.getBitWidth(), 0);
01745       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
01746         break;
01747       Offset += GEPOffset;
01748       Ptr = GEP->getPointerOperand();
01749       if (!Visited.insert(Ptr).second)
01750         break;
01751     }
01752 
01753     // See if we can perform a natural GEP here.
01754     Indices.clear();
01755     if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
01756                                            Indices, NamePrefix)) {
01757       // If we have a new natural pointer at the offset, clear out any old
01758       // offset pointer we computed. Unless it is the base pointer or
01759       // a non-instruction, we built a GEP we don't need. Zap it.
01760       if (OffsetPtr && OffsetPtr != OffsetBasePtr)
01761         if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
01762           assert(I->use_empty() && "Built a GEP with uses some how!");
01763           I->eraseFromParent();
01764         }
01765       OffsetPtr = P;
01766       OffsetBasePtr = Ptr;
01767       // If we also found a pointer of the right type, we're done.
01768       if (P->getType() == PointerTy)
01769         return P;
01770     }
01771 
01772     // Stash this pointer if we've found an i8*.
01773     if (Ptr->getType()->isIntegerTy(8)) {
01774       Int8Ptr = Ptr;
01775       Int8PtrOffset = Offset;
01776     }
01777 
01778     // Peel off a layer of the pointer and update the offset appropriately.
01779     if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
01780       Ptr = cast<Operator>(Ptr)->getOperand(0);
01781     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
01782       if (GA->mayBeOverridden())
01783         break;
01784       Ptr = GA->getAliasee();
01785     } else {
01786       break;
01787     }
01788     assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
01789   } while (Visited.insert(Ptr).second);
01790 
01791   if (!OffsetPtr) {
01792     if (!Int8Ptr) {
01793       Int8Ptr = IRB.CreateBitCast(
01794           Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
01795           NamePrefix + "sroa_raw_cast");
01796       Int8PtrOffset = Offset;
01797     }
01798 
01799     OffsetPtr = Int8PtrOffset == 0
01800                     ? Int8Ptr
01801                     : IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
01802                                             NamePrefix + "sroa_raw_idx");
01803   }
01804   Ptr = OffsetPtr;
01805 
01806   // On the off chance we were targeting i8*, guard the bitcast here.
01807   if (Ptr->getType() != PointerTy)
01808     Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
01809 
01810   return Ptr;
01811 }
01812 
01813 /// \brief Compute the adjusted alignment for a load or store from an offset.
01814 static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
01815                                      const DataLayout &DL) {
01816   unsigned Alignment;
01817   Type *Ty;
01818   if (auto *LI = dyn_cast<LoadInst>(I)) {
01819     Alignment = LI->getAlignment();
01820     Ty = LI->getType();
01821   } else if (auto *SI = dyn_cast<StoreInst>(I)) {
01822     Alignment = SI->getAlignment();
01823     Ty = SI->getValueOperand()->getType();
01824   } else {
01825     llvm_unreachable("Only loads and stores are allowed!");
01826   }
01827 
01828   if (!Alignment)
01829     Alignment = DL.getABITypeAlignment(Ty);
01830 
01831   return MinAlign(Alignment, Offset);
01832 }
01833 
01834 /// \brief Test whether we can convert a value from the old to the new type.
01835 ///
01836 /// This predicate should be used to guard calls to convertValue in order to
01837 /// ensure that we only try to convert viable values. The strategy is that we
01838 /// will peel off single element struct and array wrappings to get to an
01839 /// underlying value, and convert that value.
01840 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
01841   if (OldTy == NewTy)
01842     return true;
01843   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
01844     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
01845       if (NewITy->getBitWidth() >= OldITy->getBitWidth())
01846         return true;
01847   if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
01848     return false;
01849   if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
01850     return false;
01851 
01852   // We can convert pointers to integers and vice-versa. Same for vectors
01853   // of pointers and integers.
01854   OldTy = OldTy->getScalarType();
01855   NewTy = NewTy->getScalarType();
01856   if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
01857     if (NewTy->isPointerTy() && OldTy->isPointerTy())
01858       return true;
01859     if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
01860       return true;
01861     return false;
01862   }
01863 
01864   return true;
01865 }
01866 
01867 /// \brief Generic routine to convert an SSA value to a value of a different
01868 /// type.
01869 ///
01870 /// This will try various different casting techniques, such as bitcasts,
01871 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
01872 /// two types for viability with this routine.
01873 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
01874                            Type *NewTy) {
01875   Type *OldTy = V->getType();
01876   assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
01877 
01878   if (OldTy == NewTy)
01879     return V;
01880 
01881   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
01882     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
01883       if (NewITy->getBitWidth() > OldITy->getBitWidth())
01884         return IRB.CreateZExt(V, NewITy);
01885 
01886   // See if we need inttoptr for this type pair. A cast involving both scalars
01887   // and vectors requires and additional bitcast.
01888   if (OldTy->getScalarType()->isIntegerTy() &&
01889       NewTy->getScalarType()->isPointerTy()) {
01890     // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
01891     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
01892       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
01893                                 NewTy);
01894 
01895     // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
01896     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
01897       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
01898                                 NewTy);
01899 
01900     return IRB.CreateIntToPtr(V, NewTy);
01901   }
01902 
01903   // See if we need ptrtoint for this type pair. A cast involving both scalars
01904   // and vectors requires and additional bitcast.
01905   if (OldTy->getScalarType()->isPointerTy() &&
01906       NewTy->getScalarType()->isIntegerTy()) {
01907     // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
01908     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
01909       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
01910                                NewTy);
01911 
01912     // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
01913     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
01914       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
01915                                NewTy);
01916 
01917     return IRB.CreatePtrToInt(V, NewTy);
01918   }
01919 
01920   return IRB.CreateBitCast(V, NewTy);
01921 }
01922 
01923 /// \brief Test whether the given slice use can be promoted to a vector.
01924 ///
01925 /// This function is called to test each entry in a partioning which is slated
01926 /// for a single slice.
01927 static bool isVectorPromotionViableForSlice(AllocaSlices::Partition &P,
01928                                             const Slice &S, VectorType *Ty,
01929                                             uint64_t ElementSize,
01930                                             const DataLayout &DL) {
01931   // First validate the slice offsets.
01932   uint64_t BeginOffset =
01933       std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
01934   uint64_t BeginIndex = BeginOffset / ElementSize;
01935   if (BeginIndex * ElementSize != BeginOffset ||
01936       BeginIndex >= Ty->getNumElements())
01937     return false;
01938   uint64_t EndOffset =
01939       std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
01940   uint64_t EndIndex = EndOffset / ElementSize;
01941   if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
01942     return false;
01943 
01944   assert(EndIndex > BeginIndex && "Empty vector!");
01945   uint64_t NumElements = EndIndex - BeginIndex;
01946   Type *SliceTy = (NumElements == 1)
01947                       ? Ty->getElementType()
01948                       : VectorType::get(Ty->getElementType(), NumElements);
01949 
01950   Type *SplitIntTy =
01951       Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
01952 
01953   Use *U = S.getUse();
01954 
01955   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
01956     if (MI->isVolatile())
01957       return false;
01958     if (!S.isSplittable())
01959       return false; // Skip any unsplittable intrinsics.
01960   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
01961     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
01962         II->getIntrinsicID() != Intrinsic::lifetime_end)
01963       return false;
01964   } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
01965     // Disable vector promotion when there are loads or stores of an FCA.
01966     return false;
01967   } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01968     if (LI->isVolatile())
01969       return false;
01970     Type *LTy = LI->getType();
01971     if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
01972       assert(LTy->isIntegerTy());
01973       LTy = SplitIntTy;
01974     }
01975     if (!canConvertValue(DL, SliceTy, LTy))
01976       return false;
01977   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01978     if (SI->isVolatile())
01979       return false;
01980     Type *STy = SI->getValueOperand()->getType();
01981     if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
01982       assert(STy->isIntegerTy());
01983       STy = SplitIntTy;
01984     }
01985     if (!canConvertValue(DL, STy, SliceTy))
01986       return false;
01987   } else {
01988     return false;
01989   }
01990 
01991   return true;
01992 }
01993 
01994 /// \brief Test whether the given alloca partitioning and range of slices can be
01995 /// promoted to a vector.
01996 ///
01997 /// This is a quick test to check whether we can rewrite a particular alloca
01998 /// partition (and its newly formed alloca) into a vector alloca with only
01999 /// whole-vector loads and stores such that it could be promoted to a vector
02000 /// SSA value. We only can ensure this for a limited set of operations, and we
02001 /// don't want to do the rewrites unless we are confident that the result will
02002 /// be promotable, so we have an early test here.
02003 static VectorType *isVectorPromotionViable(AllocaSlices::Partition &P,
02004                                            const DataLayout &DL) {
02005   // Collect the candidate types for vector-based promotion. Also track whether
02006   // we have different element types.
02007   SmallVector<VectorType *, 4> CandidateTys;
02008   Type *CommonEltTy = nullptr;
02009   bool HaveCommonEltTy = true;
02010   auto CheckCandidateType = [&](Type *Ty) {
02011     if (auto *VTy = dyn_cast<VectorType>(Ty)) {
02012       CandidateTys.push_back(VTy);
02013       if (!CommonEltTy)
02014         CommonEltTy = VTy->getElementType();
02015       else if (CommonEltTy != VTy->getElementType())
02016         HaveCommonEltTy = false;
02017     }
02018   };
02019   // Consider any loads or stores that are the exact size of the slice.
02020   for (const Slice &S : P)
02021     if (S.beginOffset() == P.beginOffset() &&
02022         S.endOffset() == P.endOffset()) {
02023       if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
02024         CheckCandidateType(LI->getType());
02025       else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
02026         CheckCandidateType(SI->getValueOperand()->getType());
02027     }
02028 
02029   // If we didn't find a vector type, nothing to do here.
02030   if (CandidateTys.empty())
02031     return nullptr;
02032 
02033   // Remove non-integer vector types if we had multiple common element types.
02034   // FIXME: It'd be nice to replace them with integer vector types, but we can't
02035   // do that until all the backends are known to produce good code for all
02036   // integer vector types.
02037   if (!HaveCommonEltTy) {
02038     CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
02039                                       [](VectorType *VTy) {
02040                          return !VTy->getElementType()->isIntegerTy();
02041                        }),
02042                        CandidateTys.end());
02043 
02044     // If there were no integer vector types, give up.
02045     if (CandidateTys.empty())
02046       return nullptr;
02047 
02048     // Rank the remaining candidate vector types. This is easy because we know
02049     // they're all integer vectors. We sort by ascending number of elements.
02050     auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
02051       assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
02052              "Cannot have vector types of different sizes!");
02053       assert(RHSTy->getElementType()->isIntegerTy() &&
02054              "All non-integer types eliminated!");
02055       assert(LHSTy->getElementType()->isIntegerTy() &&
02056              "All non-integer types eliminated!");
02057       return RHSTy->getNumElements() < LHSTy->getNumElements();
02058     };
02059     std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
02060     CandidateTys.erase(
02061         std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
02062         CandidateTys.end());
02063   } else {
02064 // The only way to have the same element type in every vector type is to
02065 // have the same vector type. Check that and remove all but one.
02066 #ifndef NDEBUG
02067     for (VectorType *VTy : CandidateTys) {
02068       assert(VTy->getElementType() == CommonEltTy &&
02069              "Unaccounted for element type!");
02070       assert(VTy == CandidateTys[0] &&
02071              "Different vector types with the same element type!");
02072     }
02073 #endif
02074     CandidateTys.resize(1);
02075   }
02076 
02077   // Try each vector type, and return the one which works.
02078   auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
02079     uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
02080 
02081     // While the definition of LLVM vectors is bitpacked, we don't support sizes
02082     // that aren't byte sized.
02083     if (ElementSize % 8)
02084       return false;
02085     assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
02086            "vector size not a multiple of element size?");
02087     ElementSize /= 8;
02088 
02089     for (const Slice &S : P)
02090       if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
02091         return false;
02092 
02093     for (const Slice *S : P.splitSliceTails())
02094       if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
02095         return false;
02096 
02097     return true;
02098   };
02099   for (VectorType *VTy : CandidateTys)
02100     if (CheckVectorTypeForPromotion(VTy))
02101       return VTy;
02102 
02103   return nullptr;
02104 }
02105 
02106 /// \brief Test whether a slice of an alloca is valid for integer widening.
02107 ///
02108 /// This implements the necessary checking for the \c isIntegerWideningViable
02109 /// test below on a single slice of the alloca.
02110 static bool isIntegerWideningViableForSlice(const Slice &S,
02111                                             uint64_t AllocBeginOffset,
02112                                             Type *AllocaTy,
02113                                             const DataLayout &DL,
02114                                             bool &WholeAllocaOp) {
02115   uint64_t Size = DL.getTypeStoreSize(AllocaTy);
02116 
02117   uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
02118   uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
02119 
02120   // We can't reasonably handle cases where the load or store extends past
02121   // the end of the aloca's type and into its padding.
02122   if (RelEnd > Size)
02123     return false;
02124 
02125   Use *U = S.getUse();
02126 
02127   if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
02128     if (LI->isVolatile())
02129       return false;
02130     // Note that we don't count vector loads or stores as whole-alloca
02131     // operations which enable integer widening because we would prefer to use
02132     // vector widening instead.
02133     if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
02134       WholeAllocaOp = true;
02135     if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
02136       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
02137         return false;
02138     } else if (RelBegin != 0 || RelEnd != Size ||
02139                !canConvertValue(DL, AllocaTy, LI->getType())) {
02140       // Non-integer loads need to be convertible from the alloca type so that
02141       // they are promotable.
02142       return false;
02143     }
02144   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
02145     Type *ValueTy = SI->getValueOperand()->getType();
02146     if (SI->isVolatile())
02147       return false;
02148     // Note that we don't count vector loads or stores as whole-alloca
02149     // operations which enable integer widening because we would prefer to use
02150     // vector widening instead.
02151     if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
02152       WholeAllocaOp = true;
02153     if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
02154       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
02155         return false;
02156     } else if (RelBegin != 0 || RelEnd != Size ||
02157                !canConvertValue(DL, ValueTy, AllocaTy)) {
02158       // Non-integer stores need to be convertible to the alloca type so that
02159       // they are promotable.
02160       return false;
02161     }
02162   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
02163     if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
02164       return false;
02165     if (!S.isSplittable())
02166       return false; // Skip any unsplittable intrinsics.
02167   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
02168     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
02169         II->getIntrinsicID() != Intrinsic::lifetime_end)
02170       return false;
02171   } else {
02172     return false;
02173   }
02174 
02175   return true;
02176 }
02177 
02178 /// \brief Test whether the given alloca partition's integer operations can be
02179 /// widened to promotable ones.
02180 ///
02181 /// This is a quick test to check whether we can rewrite the integer loads and
02182 /// stores to a particular alloca into wider loads and stores and be able to
02183 /// promote the resulting alloca.
02184 static bool isIntegerWideningViable(AllocaSlices::Partition &P, Type *AllocaTy,
02185                                     const DataLayout &DL) {
02186   uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
02187   // Don't create integer types larger than the maximum bitwidth.
02188   if (SizeInBits > IntegerType::MAX_INT_BITS)
02189     return false;
02190 
02191   // Don't try to handle allocas with bit-padding.
02192   if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
02193     return false;
02194 
02195   // We need to ensure that an integer type with the appropriate bitwidth can
02196   // be converted to the alloca type, whatever that is. We don't want to force
02197   // the alloca itself to have an integer type if there is a more suitable one.
02198   Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
02199   if (!canConvertValue(DL, AllocaTy, IntTy) ||
02200       !canConvertValue(DL, IntTy, AllocaTy))
02201     return false;
02202 
02203   // While examining uses, we ensure that the alloca has a covering load or
02204   // store. We don't want to widen the integer operations only to fail to
02205   // promote due to some other unsplittable entry (which we may make splittable
02206   // later). However, if there are only splittable uses, go ahead and assume
02207   // that we cover the alloca.
02208   // FIXME: We shouldn't consider split slices that happen to start in the
02209   // partition here...
02210   bool WholeAllocaOp =
02211       P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
02212 
02213   for (const Slice &S : P)
02214     if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
02215                                          WholeAllocaOp))
02216       return false;
02217 
02218   for (const Slice *S : P.splitSliceTails())
02219     if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
02220                                          WholeAllocaOp))
02221       return false;
02222 
02223   return WholeAllocaOp;
02224 }
02225 
02226 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
02227                              IntegerType *Ty, uint64_t Offset,
02228                              const Twine &Name) {
02229   DEBUG(dbgs() << "       start: " << *V << "\n");
02230   IntegerType *IntTy = cast<IntegerType>(V->getType());
02231   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
02232          "Element extends past full value");
02233   uint64_t ShAmt = 8 * Offset;
02234   if (DL.isBigEndian())
02235     ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
02236   if (ShAmt) {
02237     V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
02238     DEBUG(dbgs() << "     shifted: " << *V << "\n");
02239   }
02240   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
02241          "Cannot extract to a larger integer!");
02242   if (Ty != IntTy) {
02243     V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
02244     DEBUG(dbgs() << "     trunced: " << *V << "\n");
02245   }
02246   return V;
02247 }
02248 
02249 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
02250                             Value *V, uint64_t Offset, const Twine &Name) {
02251   IntegerType *IntTy = cast<IntegerType>(Old->getType());
02252   IntegerType *Ty = cast<IntegerType>(V->getType());
02253   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
02254          "Cannot insert a larger integer!");
02255   DEBUG(dbgs() << "       start: " << *V << "\n");
02256   if (Ty != IntTy) {
02257     V = IRB.CreateZExt(V, IntTy, Name + ".ext");
02258     DEBUG(dbgs() << "    extended: " << *V << "\n");
02259   }
02260   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
02261          "Element store outside of alloca store");
02262   uint64_t ShAmt = 8 * Offset;
02263   if (DL.isBigEndian())
02264     ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
02265   if (ShAmt) {
02266     V = IRB.CreateShl(V, ShAmt, Name + ".shift");
02267     DEBUG(dbgs() << "     shifted: " << *V << "\n");
02268   }
02269 
02270   if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
02271     APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
02272     Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
02273     DEBUG(dbgs() << "      masked: " << *Old << "\n");
02274     V = IRB.CreateOr(Old, V, Name + ".insert");
02275     DEBUG(dbgs() << "    inserted: " << *V << "\n");
02276   }
02277   return V;
02278 }
02279 
02280 static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
02281                             unsigned EndIndex, const Twine &Name) {
02282   VectorType *VecTy = cast<VectorType>(V->getType());
02283   unsigned NumElements = EndIndex - BeginIndex;
02284   assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
02285 
02286   if (NumElements == VecTy->getNumElements())
02287     return V;
02288 
02289   if (NumElements == 1) {
02290     V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
02291                                  Name + ".extract");
02292     DEBUG(dbgs() << "     extract: " << *V << "\n");
02293     return V;
02294   }
02295 
02296   SmallVector<Constant *, 8> Mask;
02297   Mask.reserve(NumElements);
02298   for (unsigned i = BeginIndex; i != EndIndex; ++i)
02299     Mask.push_back(IRB.getInt32(i));
02300   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
02301                               ConstantVector::get(Mask), Name + ".extract");
02302   DEBUG(dbgs() << "     shuffle: " << *V << "\n");
02303   return V;
02304 }
02305 
02306 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
02307                            unsigned BeginIndex, const Twine &Name) {
02308   VectorType *VecTy = cast<VectorType>(Old->getType());
02309   assert(VecTy && "Can only insert a vector into a vector");
02310 
02311   VectorType *Ty = dyn_cast<VectorType>(V->getType());
02312   if (!Ty) {
02313     // Single element to insert.
02314     V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
02315                                 Name + ".insert");
02316     DEBUG(dbgs() << "     insert: " << *V << "\n");
02317     return V;
02318   }
02319 
02320   assert(Ty->getNumElements() <= VecTy->getNumElements() &&
02321          "Too many elements!");
02322   if (Ty->getNumElements() == VecTy->getNumElements()) {
02323     assert(V->getType() == VecTy && "Vector type mismatch");
02324     return V;
02325   }
02326   unsigned EndIndex = BeginIndex + Ty->getNumElements();
02327 
02328   // When inserting a smaller vector into the larger to store, we first
02329   // use a shuffle vector to widen it with undef elements, and then
02330   // a second shuffle vector to select between the loaded vector and the
02331   // incoming vector.
02332   SmallVector<Constant *, 8> Mask;
02333   Mask.reserve(VecTy->getNumElements());
02334   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
02335     if (i >= BeginIndex && i < EndIndex)
02336       Mask.push_back(IRB.getInt32(i - BeginIndex));
02337     else
02338       Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
02339   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
02340                               ConstantVector::get(Mask), Name + ".expand");
02341   DEBUG(dbgs() << "    shuffle: " << *V << "\n");
02342 
02343   Mask.clear();
02344   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
02345     Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
02346 
02347   V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
02348 
02349   DEBUG(dbgs() << "    blend: " << *V << "\n");
02350   return V;
02351 }
02352 
02353 namespace {
02354 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
02355 /// to use a new alloca.
02356 ///
02357 /// Also implements the rewriting to vector-based accesses when the partition
02358 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
02359 /// lives here.
02360 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
02361   // Befriend the base class so it can delegate to private visit methods.
02362   friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
02363   typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
02364 
02365   const DataLayout &DL;
02366   AllocaSlices &AS;
02367   SROA &Pass;
02368   AllocaInst &OldAI, &NewAI;
02369   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
02370   Type *NewAllocaTy;
02371 
02372   // This is a convenience and flag variable that will be null unless the new
02373   // alloca's integer operations should be widened to this integer type due to
02374   // passing isIntegerWideningViable above. If it is non-null, the desired
02375   // integer type will be stored here for easy access during rewriting.
02376   IntegerType *IntTy;
02377 
02378   // If we are rewriting an alloca partition which can be written as pure
02379   // vector operations, we stash extra information here. When VecTy is
02380   // non-null, we have some strict guarantees about the rewritten alloca:
02381   //   - The new alloca is exactly the size of the vector type here.
02382   //   - The accesses all either map to the entire vector or to a single
02383   //     element.
02384   //   - The set of accessing instructions is only one of those handled above
02385   //     in isVectorPromotionViable. Generally these are the same access kinds
02386   //     which are promotable via mem2reg.
02387   VectorType *VecTy;
02388   Type *ElementTy;
02389   uint64_t ElementSize;
02390 
02391   // The original offset of the slice currently being rewritten relative to
02392   // the original alloca.
02393   uint64_t BeginOffset, EndOffset;
02394   // The new offsets of the slice currently being rewritten relative to the
02395   // original alloca.
02396   uint64_t NewBeginOffset, NewEndOffset;
02397 
02398   uint64_t SliceSize;
02399   bool IsSplittable;
02400   bool IsSplit;
02401   Use *OldUse;
02402   Instruction *OldPtr;
02403 
02404   // Track post-rewrite users which are PHI nodes and Selects.
02405   SmallPtrSetImpl<PHINode *> &PHIUsers;
02406   SmallPtrSetImpl<SelectInst *> &SelectUsers;
02407 
02408   // Utility IR builder, whose name prefix is setup for each visited use, and
02409   // the insertion point is set to point to the user.
02410   IRBuilderTy IRB;
02411 
02412 public:
02413   AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
02414                       AllocaInst &OldAI, AllocaInst &NewAI,
02415                       uint64_t NewAllocaBeginOffset,
02416                       uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
02417                       VectorType *PromotableVecTy,
02418                       SmallPtrSetImpl<PHINode *> &PHIUsers,
02419                       SmallPtrSetImpl<SelectInst *> &SelectUsers)
02420       : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
02421         NewAllocaBeginOffset(NewAllocaBeginOffset),
02422         NewAllocaEndOffset(NewAllocaEndOffset),
02423         NewAllocaTy(NewAI.getAllocatedType()),
02424         IntTy(IsIntegerPromotable
02425                   ? Type::getIntNTy(
02426                         NewAI.getContext(),
02427                         DL.getTypeSizeInBits(NewAI.getAllocatedType()))
02428                   : nullptr),
02429         VecTy(PromotableVecTy),
02430         ElementTy(VecTy ? VecTy->getElementType() : nullptr),
02431         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
02432         BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
02433         OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
02434         IRB(NewAI.getContext(), ConstantFolder()) {
02435     if (VecTy) {
02436       assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
02437              "Only multiple-of-8 sized vector elements are viable");
02438       ++NumVectorized;
02439     }
02440     assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
02441   }
02442 
02443   bool visit(AllocaSlices::const_iterator I) {
02444     bool CanSROA = true;
02445     BeginOffset = I->beginOffset();
02446     EndOffset = I->endOffset();
02447     IsSplittable = I->isSplittable();
02448     IsSplit =
02449         BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
02450     DEBUG(dbgs() << "  rewriting " << (IsSplit ? "split " : ""));
02451     DEBUG(AS.printSlice(dbgs(), I, ""));
02452     DEBUG(dbgs() << "\n");
02453 
02454     // Compute the intersecting offset range.
02455     assert(BeginOffset < NewAllocaEndOffset);
02456     assert(EndOffset > NewAllocaBeginOffset);
02457     NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
02458     NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
02459 
02460     SliceSize = NewEndOffset - NewBeginOffset;
02461 
02462     OldUse = I->getUse();
02463     OldPtr = cast<Instruction>(OldUse->get());
02464 
02465     Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
02466     IRB.SetInsertPoint(OldUserI);
02467     IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
02468     IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
02469 
02470     CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
02471     if (VecTy || IntTy)
02472       assert(CanSROA);
02473     return CanSROA;
02474   }
02475 
02476 private:
02477   // Make sure the other visit overloads are visible.
02478   using Base::visit;
02479 
02480   // Every instruction which can end up as a user must have a rewrite rule.
02481   bool visitInstruction(Instruction &I) {
02482     DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
02483     llvm_unreachable("No rewrite rule for this instruction!");
02484   }
02485 
02486   Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
02487     // Note that the offset computation can use BeginOffset or NewBeginOffset
02488     // interchangeably for unsplit slices.
02489     assert(IsSplit || BeginOffset == NewBeginOffset);
02490     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02491 
02492 #ifndef NDEBUG
02493     StringRef OldName = OldPtr->getName();
02494     // Skip through the last '.sroa.' component of the name.
02495     size_t LastSROAPrefix = OldName.rfind(".sroa.");
02496     if (LastSROAPrefix != StringRef::npos) {
02497       OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
02498       // Look for an SROA slice index.
02499       size_t IndexEnd = OldName.find_first_not_of("0123456789");
02500       if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
02501         // Strip the index and look for the offset.
02502         OldName = OldName.substr(IndexEnd + 1);
02503         size_t OffsetEnd = OldName.find_first_not_of("0123456789");
02504         if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
02505           // Strip the offset.
02506           OldName = OldName.substr(OffsetEnd + 1);
02507       }
02508     }
02509     // Strip any SROA suffixes as well.
02510     OldName = OldName.substr(0, OldName.find(".sroa_"));
02511 #endif
02512 
02513     return getAdjustedPtr(IRB, DL, &NewAI,
02514                           APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
02515 #ifndef NDEBUG
02516                           Twine(OldName) + "."
02517 #else
02518                           Twine()
02519 #endif
02520                           );
02521   }
02522 
02523   /// \brief Compute suitable alignment to access this slice of the *new*
02524   /// alloca.
02525   ///
02526   /// You can optionally pass a type to this routine and if that type's ABI
02527   /// alignment is itself suitable, this will return zero.
02528   unsigned getSliceAlign(Type *Ty = nullptr) {
02529     unsigned NewAIAlign = NewAI.getAlignment();
02530     if (!NewAIAlign)
02531       NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
02532     unsigned Align =
02533         MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
02534     return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
02535   }
02536 
02537   unsigned getIndex(uint64_t Offset) {
02538     assert(VecTy && "Can only call getIndex when rewriting a vector");
02539     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
02540     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
02541     uint32_t Index = RelOffset / ElementSize;
02542     assert(Index * ElementSize == RelOffset);
02543     return Index;
02544   }
02545 
02546   void deleteIfTriviallyDead(Value *V) {
02547     Instruction *I = cast<Instruction>(V);
02548     if (isInstructionTriviallyDead(I))
02549       Pass.DeadInsts.insert(I);
02550   }
02551 
02552   Value *rewriteVectorizedLoadInst() {
02553     unsigned BeginIndex = getIndex(NewBeginOffset);
02554     unsigned EndIndex = getIndex(NewEndOffset);
02555     assert(EndIndex > BeginIndex && "Empty vector!");
02556 
02557     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
02558     return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
02559   }
02560 
02561   Value *rewriteIntegerLoad(LoadInst &LI) {
02562     assert(IntTy && "We cannot insert an integer to the alloca");
02563     assert(!LI.isVolatile());
02564     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
02565     V = convertValue(DL, IRB, V, IntTy);
02566     assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
02567     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02568     if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
02569       V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
02570                          "extract");
02571     return V;
02572   }
02573 
02574   bool visitLoadInst(LoadInst &LI) {
02575     DEBUG(dbgs() << "    original: " << LI << "\n");
02576     Value *OldOp = LI.getOperand(0);
02577     assert(OldOp == OldPtr);
02578 
02579     Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
02580                              : LI.getType();
02581     bool IsPtrAdjusted = false;
02582     Value *V;
02583     if (VecTy) {
02584       V = rewriteVectorizedLoadInst();
02585     } else if (IntTy && LI.getType()->isIntegerTy()) {
02586       V = rewriteIntegerLoad(LI);
02587     } else if (NewBeginOffset == NewAllocaBeginOffset &&
02588                canConvertValue(DL, NewAllocaTy, LI.getType())) {
02589       V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), LI.isVolatile(),
02590                                 LI.getName());
02591     } else {
02592       Type *LTy = TargetTy->getPointerTo();
02593       V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
02594                                 getSliceAlign(TargetTy), LI.isVolatile(),
02595                                 LI.getName());
02596       IsPtrAdjusted = true;
02597     }
02598     V = convertValue(DL, IRB, V, TargetTy);
02599 
02600     if (IsSplit) {
02601       assert(!LI.isVolatile());
02602       assert(LI.getType()->isIntegerTy() &&
02603              "Only integer type loads and stores are split");
02604       assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
02605              "Split load isn't smaller than original load");
02606       assert(LI.getType()->getIntegerBitWidth() ==
02607                  DL.getTypeStoreSizeInBits(LI.getType()) &&
02608              "Non-byte-multiple bit width");
02609       // Move the insertion point just past the load so that we can refer to it.
02610       IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
02611       // Create a placeholder value with the same type as LI to use as the
02612       // basis for the new value. This allows us to replace the uses of LI with
02613       // the computed value, and then replace the placeholder with LI, leaving
02614       // LI only used for this computation.
02615       Value *Placeholder =
02616           new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
02617       V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
02618                         "insert");
02619       LI.replaceAllUsesWith(V);
02620       Placeholder->replaceAllUsesWith(&LI);
02621       delete Placeholder;
02622     } else {
02623       LI.replaceAllUsesWith(V);
02624     }
02625 
02626     Pass.DeadInsts.insert(&LI);
02627     deleteIfTriviallyDead(OldOp);
02628     DEBUG(dbgs() << "          to: " << *V << "\n");
02629     return !LI.isVolatile() && !IsPtrAdjusted;
02630   }
02631 
02632   bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
02633     if (V->getType() != VecTy) {
02634       unsigned BeginIndex = getIndex(NewBeginOffset);
02635       unsigned EndIndex = getIndex(NewEndOffset);
02636       assert(EndIndex > BeginIndex && "Empty vector!");
02637       unsigned NumElements = EndIndex - BeginIndex;
02638       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
02639       Type *SliceTy = (NumElements == 1)
02640                           ? ElementTy
02641                           : VectorType::get(ElementTy, NumElements);
02642       if (V->getType() != SliceTy)
02643         V = convertValue(DL, IRB, V, SliceTy);
02644 
02645       // Mix in the existing elements.
02646       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
02647       V = insertVector(IRB, Old, V, BeginIndex, "vec");
02648     }
02649     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
02650     Pass.DeadInsts.insert(&SI);
02651 
02652     (void)Store;
02653     DEBUG(dbgs() << "          to: " << *Store << "\n");
02654     return true;
02655   }
02656 
02657   bool rewriteIntegerStore(Value *V, StoreInst &SI) {
02658     assert(IntTy && "We cannot extract an integer from the alloca");
02659     assert(!SI.isVolatile());
02660     if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
02661       Value *Old =
02662           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
02663       Old = convertValue(DL, IRB, Old, IntTy);
02664       assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
02665       uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
02666       V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
02667     }
02668     V = convertValue(DL, IRB, V, NewAllocaTy);
02669     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
02670     Pass.DeadInsts.insert(&SI);
02671     (void)Store;
02672     DEBUG(dbgs() << "          to: " << *Store << "\n");
02673     return true;
02674   }
02675 
02676   bool visitStoreInst(StoreInst &SI) {
02677     DEBUG(dbgs() << "    original: " << SI << "\n");
02678     Value *OldOp = SI.getOperand(1);
02679     assert(OldOp == OldPtr);
02680 
02681     Value *V = SI.getValueOperand();
02682 
02683     // Strip all inbounds GEPs and pointer casts to try to dig out any root
02684     // alloca that should be re-examined after promoting this alloca.
02685     if (V->getType()->isPointerTy())
02686       if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
02687         Pass.PostPromotionWorklist.insert(AI);
02688 
02689     if (SliceSize < DL.getTypeStoreSize(V->getType())) {
02690       assert(!SI.isVolatile());
02691       assert(V->getType()->isIntegerTy() &&
02692              "Only integer type loads and stores are split");
02693       assert(V->getType()->getIntegerBitWidth() ==
02694                  DL.getTypeStoreSizeInBits(V->getType()) &&
02695              "Non-byte-multiple bit width");
02696       IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
02697       V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
02698                          "extract");
02699     }
02700 
02701     if (VecTy)
02702       return rewriteVectorizedStoreInst(V, SI, OldOp);
02703     if (IntTy && V->getType()->isIntegerTy())
02704       return rewriteIntegerStore(V, SI);
02705 
02706     StoreInst *NewSI;
02707     if (NewBeginOffset == NewAllocaBeginOffset &&
02708         NewEndOffset == NewAllocaEndOffset &&
02709         canConvertValue(DL, V->getType(), NewAllocaTy)) {
02710       V = convertValue(DL, IRB, V, NewAllocaTy);
02711       NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
02712                                      SI.isVolatile());
02713     } else {
02714       Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
02715       NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
02716                                      SI.isVolatile());
02717     }
02718     (void)NewSI;
02719     Pass.DeadInsts.insert(&SI);
02720     deleteIfTriviallyDead(OldOp);
02721 
02722     DEBUG(dbgs() << "          to: " << *NewSI << "\n");
02723     return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
02724   }
02725 
02726   /// \brief Compute an integer value from splatting an i8 across the given
02727   /// number of bytes.
02728   ///
02729   /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
02730   /// call this routine.
02731   /// FIXME: Heed the advice above.
02732   ///
02733   /// \param V The i8 value to splat.
02734   /// \param Size The number of bytes in the output (assuming i8 is one byte)
02735   Value *getIntegerSplat(Value *V, unsigned Size) {
02736     assert(Size > 0 && "Expected a positive number of bytes.");
02737     IntegerType *VTy = cast<IntegerType>(V->getType());
02738     assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
02739     if (Size == 1)
02740       return V;
02741 
02742     Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
02743     V = IRB.CreateMul(
02744         IRB.CreateZExt(V, SplatIntTy, "zext"),
02745         ConstantExpr::getUDiv(
02746             Constant::getAllOnesValue(SplatIntTy),
02747             ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
02748                                   SplatIntTy)),
02749         "isplat");
02750     return V;
02751   }
02752 
02753   /// \brief Compute a vector splat for a given element value.
02754   Value *getVectorSplat(Value *V, unsigned NumElements) {
02755     V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
02756     DEBUG(dbgs() << "       splat: " << *V << "\n");
02757     return V;
02758   }
02759 
02760   bool visitMemSetInst(MemSetInst &II) {
02761     DEBUG(dbgs() << "    original: " << II << "\n");
02762     assert(II.getRawDest() == OldPtr);
02763 
02764     // If the memset has a variable size, it cannot be split, just adjust the
02765     // pointer to the new alloca.
02766     if (!isa<Constant>(II.getLength())) {
02767       assert(!IsSplit);
02768       assert(NewBeginOffset == BeginOffset);
02769       II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
02770       Type *CstTy = II.getAlignmentCst()->getType();
02771       II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
02772 
02773       deleteIfTriviallyDead(OldPtr);
02774       return false;
02775     }
02776 
02777     // Record this instruction for deletion.
02778     Pass.DeadInsts.insert(&II);
02779 
02780     Type *AllocaTy = NewAI.getAllocatedType();
02781     Type *ScalarTy = AllocaTy->getScalarType();
02782 
02783     // If this doesn't map cleanly onto the alloca type, and that type isn't
02784     // a single value type, just emit a memset.
02785     if (!VecTy && !IntTy &&
02786         (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
02787          SliceSize != DL.getTypeStoreSize(AllocaTy) ||
02788          !AllocaTy->isSingleValueType() ||
02789          !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
02790          DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
02791       Type *SizeTy = II.getLength()->getType();
02792       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
02793       CallInst *New = IRB.CreateMemSet(
02794           getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
02795           getSliceAlign(), II.isVolatile());
02796       (void)New;
02797       DEBUG(dbgs() << "          to: " << *New << "\n");
02798       return false;
02799     }
02800 
02801     // If we can represent this as a simple value, we have to build the actual
02802     // value to store, which requires expanding the byte present in memset to
02803     // a sensible representation for the alloca type. This is essentially
02804     // splatting the byte to a sufficiently wide integer, splatting it across
02805     // any desired vector width, and bitcasting to the final type.
02806     Value *V;
02807 
02808     if (VecTy) {
02809       // If this is a memset of a vectorized alloca, insert it.
02810       assert(ElementTy == ScalarTy);
02811 
02812       unsigned BeginIndex = getIndex(NewBeginOffset);
02813       unsigned EndIndex = getIndex(NewEndOffset);
02814       assert(EndIndex > BeginIndex && "Empty vector!");
02815       unsigned NumElements = EndIndex - BeginIndex;
02816       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
02817 
02818       Value *Splat =
02819           getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
02820       Splat = convertValue(DL, IRB, Splat, ElementTy);
02821       if (NumElements > 1)
02822         Splat = getVectorSplat(Splat, NumElements);
02823 
02824       Value *Old =
02825           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
02826       V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
02827     } else if (IntTy) {
02828       // If this is a memset on an alloca where we can widen stores, insert the
02829       // set integer.
02830       assert(!II.isVolatile());
02831 
02832       uint64_t Size = NewEndOffset - NewBeginOffset;
02833       V = getIntegerSplat(II.getValue(), Size);
02834 
02835       if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
02836                     EndOffset != NewAllocaBeginOffset)) {
02837         Value *Old =
02838             IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
02839         Old = convertValue(DL, IRB, Old, IntTy);
02840         uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02841         V = insertInteger(DL, IRB, Old, V, Offset, "insert");
02842       } else {
02843         assert(V->getType() == IntTy &&
02844                "Wrong type for an alloca wide integer!");
02845       }
02846       V = convertValue(DL, IRB, V, AllocaTy);
02847     } else {
02848       // Established these invariants above.
02849       assert(NewBeginOffset == NewAllocaBeginOffset);
02850       assert(NewEndOffset == NewAllocaEndOffset);
02851 
02852       V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
02853       if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
02854         V = getVectorSplat(V, AllocaVecTy->getNumElements());
02855 
02856       V = convertValue(DL, IRB, V, AllocaTy);
02857     }
02858 
02859     Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
02860                                         II.isVolatile());
02861     (void)New;
02862     DEBUG(dbgs() << "          to: " << *New << "\n");
02863     return !II.isVolatile();
02864   }
02865 
02866   bool visitMemTransferInst(MemTransferInst &II) {
02867     // Rewriting of memory transfer instructions can be a bit tricky. We break
02868     // them into two categories: split intrinsics and unsplit intrinsics.
02869 
02870     DEBUG(dbgs() << "    original: " << II << "\n");
02871 
02872     bool IsDest = &II.getRawDestUse() == OldUse;
02873     assert((IsDest && II.getRawDest() == OldPtr) ||
02874            (!IsDest && II.getRawSource() == OldPtr));
02875 
02876     unsigned SliceAlign = getSliceAlign();
02877 
02878     // For unsplit intrinsics, we simply modify the source and destination
02879     // pointers in place. This isn't just an optimization, it is a matter of
02880     // correctness. With unsplit intrinsics we may be dealing with transfers
02881     // within a single alloca before SROA ran, or with transfers that have
02882     // a variable length. We may also be dealing with memmove instead of
02883     // memcpy, and so simply updating the pointers is the necessary for us to
02884     // update both source and dest of a single call.
02885     if (!IsSplittable) {
02886       Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02887       if (IsDest)
02888         II.setDest(AdjustedPtr);
02889       else
02890         II.setSource(AdjustedPtr);
02891 
02892       if (II.getAlignment() > SliceAlign) {
02893         Type *CstTy = II.getAlignmentCst()->getType();
02894         II.setAlignment(
02895             ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
02896       }
02897 
02898       DEBUG(dbgs() << "          to: " << II << "\n");
02899       deleteIfTriviallyDead(OldPtr);
02900       return false;
02901     }
02902     // For split transfer intrinsics we have an incredibly useful assurance:
02903     // the source and destination do not reside within the same alloca, and at
02904     // least one of them does not escape. This means that we can replace
02905     // memmove with memcpy, and we don't need to worry about all manner of
02906     // downsides to splitting and transforming the operations.
02907 
02908     // If this doesn't map cleanly onto the alloca type, and that type isn't
02909     // a single value type, just emit a memcpy.
02910     bool EmitMemCpy =
02911         !VecTy && !IntTy &&
02912         (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
02913          SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
02914          !NewAI.getAllocatedType()->isSingleValueType());
02915 
02916     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
02917     // size hasn't been shrunk based on analysis of the viable range, this is
02918     // a no-op.
02919     if (EmitMemCpy && &OldAI == &NewAI) {
02920       // Ensure the start lines up.
02921       assert(NewBeginOffset == BeginOffset);
02922 
02923       // Rewrite the size as needed.
02924       if (NewEndOffset != EndOffset)
02925         II.setLength(ConstantInt::get(II.getLength()->getType(),
02926                                       NewEndOffset - NewBeginOffset));
02927       return false;
02928     }
02929     // Record this instruction for deletion.
02930     Pass.DeadInsts.insert(&II);
02931 
02932     // Strip all inbounds GEPs and pointer casts to try to dig out any root
02933     // alloca that should be re-examined after rewriting this instruction.
02934     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
02935     if (AllocaInst *AI =
02936             dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
02937       assert(AI != &OldAI && AI != &NewAI &&
02938              "Splittable transfers cannot reach the same alloca on both ends.");
02939       Pass.Worklist.insert(AI);
02940     }
02941 
02942     Type *OtherPtrTy = OtherPtr->getType();
02943     unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
02944 
02945     // Compute the relative offset for the other pointer within the transfer.
02946     unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
02947     APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
02948     unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
02949                                    OtherOffset.zextOrTrunc(64).getZExtValue());
02950 
02951     if (EmitMemCpy) {
02952       // Compute the other pointer, folding as much as possible to produce
02953       // a single, simple GEP in most cases.
02954       OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
02955                                 OtherPtr->getName() + ".");
02956 
02957       Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02958       Type *SizeTy = II.getLength()->getType();
02959       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
02960 
02961       CallInst *New = IRB.CreateMemCpy(
02962           IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
02963           MinAlign(SliceAlign, OtherAlign), II.isVolatile());
02964       (void)New;
02965       DEBUG(dbgs() << "          to: " << *New << "\n");
02966       return false;
02967     }
02968 
02969     bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
02970                          NewEndOffset == NewAllocaEndOffset;
02971     uint64_t Size = NewEndOffset - NewBeginOffset;
02972     unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
02973     unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
02974     unsigned NumElements = EndIndex - BeginIndex;
02975     IntegerType *SubIntTy =
02976         IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
02977 
02978     // Reset the other pointer type to match the register type we're going to
02979     // use, but using the address space of the original other pointer.
02980     if (VecTy && !IsWholeAlloca) {
02981       if (NumElements == 1)
02982         OtherPtrTy = VecTy->getElementType();
02983       else
02984         OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
02985 
02986       OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
02987     } else if (IntTy && !IsWholeAlloca) {
02988       OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
02989     } else {
02990       OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
02991     }
02992 
02993     Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
02994                                    OtherPtr->getName() + ".");
02995     unsigned SrcAlign = OtherAlign;
02996     Value *DstPtr = &NewAI;
02997     unsigned DstAlign = SliceAlign;
02998     if (!IsDest) {
02999       std::swap(SrcPtr, DstPtr);
03000       std::swap(SrcAlign, DstAlign);
03001     }
03002 
03003     Value *Src;
03004     if (VecTy && !IsWholeAlloca && !IsDest) {
03005       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
03006       Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
03007     } else if (IntTy && !IsWholeAlloca && !IsDest) {
03008       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
03009       Src = convertValue(DL, IRB, Src, IntTy);
03010       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
03011       Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
03012     } else {
03013       Src =
03014           IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
03015     }
03016 
03017     if (VecTy && !IsWholeAlloca && IsDest) {
03018       Value *Old =
03019           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
03020       Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
03021     } else if (IntTy && !IsWholeAlloca && IsDest) {
03022       Value *Old =
03023           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
03024       Old = convertValue(DL, IRB, Old, IntTy);
03025       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
03026       Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
03027       Src = convertValue(DL, IRB, Src, NewAllocaTy);
03028     }
03029 
03030     StoreInst *Store = cast<StoreInst>(
03031         IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
03032     (void)Store;
03033     DEBUG(dbgs() << "          to: " << *Store << "\n");
03034     return !II.isVolatile();
03035   }
03036 
03037   bool visitIntrinsicInst(IntrinsicInst &II) {
03038     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
03039            II.getIntrinsicID() == Intrinsic::lifetime_end);
03040     DEBUG(dbgs() << "    original: " << II << "\n");
03041     assert(II.getArgOperand(1) == OldPtr);
03042 
03043     // Record this instruction for deletion.
03044     Pass.DeadInsts.insert(&II);
03045 
03046     ConstantInt *Size =
03047         ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
03048                          NewEndOffset - NewBeginOffset);
03049     Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
03050     Value *New;
03051     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
03052       New = IRB.CreateLifetimeStart(Ptr, Size);
03053     else
03054       New = IRB.CreateLifetimeEnd(Ptr, Size);
03055 
03056     (void)New;
03057     DEBUG(dbgs() << "          to: " << *New << "\n");
03058     return true;
03059   }
03060 
03061   bool visitPHINode(PHINode &PN) {
03062     DEBUG(dbgs() << "    original: " << PN << "\n");
03063     assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
03064     assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
03065 
03066     // We would like to compute a new pointer in only one place, but have it be
03067     // as local as possible to the PHI. To do that, we re-use the location of
03068     // the old pointer, which necessarily must be in the right position to
03069     // dominate the PHI.
03070     IRBuilderTy PtrBuilder(IRB);
03071     if (isa<PHINode>(OldPtr))
03072       PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
03073     else
03074       PtrBuilder.SetInsertPoint(OldPtr);
03075     PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
03076 
03077     Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
03078     // Replace the operands which were using the old pointer.
03079     std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
03080 
03081     DEBUG(dbgs() << "          to: " << PN << "\n");
03082     deleteIfTriviallyDead(OldPtr);
03083 
03084     // PHIs can't be promoted on their own, but often can be speculated. We
03085     // check the speculation outside of the rewriter so that we see the
03086     // fully-rewritten alloca.
03087     PHIUsers.insert(&PN);
03088     return true;
03089   }
03090 
03091   bool visitSelectInst(SelectInst &SI) {
03092     DEBUG(dbgs() << "    original: " << SI << "\n");
03093     assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
03094            "Pointer isn't an operand!");
03095     assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
03096     assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
03097 
03098     Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
03099     // Replace the operands which were using the old pointer.
03100     if (SI.getOperand(1) == OldPtr)
03101       SI.setOperand(1, NewPtr);
03102     if (SI.getOperand(2) == OldPtr)
03103       SI.setOperand(2, NewPtr);
03104 
03105     DEBUG(dbgs() << "          to: " << SI << "\n");
03106     deleteIfTriviallyDead(OldPtr);
03107 
03108     // Selects can't be promoted on their own, but often can be speculated. We
03109     // check the speculation outside of the rewriter so that we see the
03110     // fully-rewritten alloca.
03111     SelectUsers.insert(&SI);
03112     return true;
03113   }
03114 };
03115 }
03116 
03117 namespace {
03118 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
03119 ///
03120 /// This pass aggressively rewrites all aggregate loads and stores on
03121 /// a particular pointer (or any pointer derived from it which we can identify)
03122 /// with scalar loads and stores.
03123 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
03124   // Befriend the base class so it can delegate to private visit methods.
03125   friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
03126 
03127   const DataLayout &DL;
03128 
03129   /// Queue of pointer uses to analyze and potentially rewrite.
03130   SmallVector<Use *, 8> Queue;
03131 
03132   /// Set to prevent us from cycling with phi nodes and loops.
03133   SmallPtrSet<User *, 8> Visited;
03134 
03135   /// The current pointer use being rewritten. This is used to dig up the used
03136   /// value (as opposed to the user).
03137   Use *U;
03138 
03139 public:
03140   AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
03141 
03142   /// Rewrite loads and stores through a pointer and all pointers derived from
03143   /// it.
03144   bool rewrite(Instruction &I) {
03145     DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
03146     enqueueUsers(I);
03147     bool Changed = false;
03148     while (!Queue.empty()) {
03149       U = Queue.pop_back_val();
03150       Changed |= visit(cast<Instruction>(U->getUser()));
03151     }
03152     return Changed;
03153   }
03154 
03155 private:
03156   /// Enqueue all the users of the given instruction for further processing.
03157   /// This uses a set to de-duplicate users.
03158   void enqueueUsers(Instruction &I) {
03159     for (Use &U : I.uses())
03160       if (Visited.insert(U.getUser()).second)
03161         Queue.push_back(&U);
03162   }
03163 
03164   // Conservative default is to not rewrite anything.
03165   bool visitInstruction(Instruction &I) { return false; }
03166 
03167   /// \brief Generic recursive split emission class.
03168   template <typename Derived> class OpSplitter {
03169   protected:
03170     /// The builder used to form new instructions.
03171     IRBuilderTy IRB;
03172     /// The indices which to be used with insert- or extractvalue to select the
03173     /// appropriate value within the aggregate.
03174     SmallVector<unsigned, 4> Indices;
03175     /// The indices to a GEP instruction which will move Ptr to the correct slot
03176     /// within the aggregate.
03177     SmallVector<Value *, 4> GEPIndices;
03178     /// The base pointer of the original op, used as a base for GEPing the
03179     /// split operations.
03180     Value *Ptr;
03181 
03182     /// Initialize the splitter with an insertion point, Ptr and start with a
03183     /// single zero GEP index.
03184     OpSplitter(Instruction *InsertionPoint, Value *Ptr)
03185         : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
03186 
03187   public:
03188     /// \brief Generic recursive split emission routine.
03189     ///
03190     /// This method recursively splits an aggregate op (load or store) into
03191     /// scalar or vector ops. It splits recursively until it hits a single value
03192     /// and emits that single value operation via the template argument.
03193     ///
03194     /// The logic of this routine relies on GEPs and insertvalue and
03195     /// extractvalue all operating with the same fundamental index list, merely
03196     /// formatted differently (GEPs need actual values).
03197     ///
03198     /// \param Ty  The type being split recursively into smaller ops.
03199     /// \param Agg The aggregate value being built up or stored, depending on
03200     /// whether this is splitting a load or a store respectively.
03201     void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
03202       if (Ty->isSingleValueType())
03203         return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
03204 
03205       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
03206         unsigned OldSize = Indices.size();
03207         (void)OldSize;
03208         for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
03209              ++Idx) {
03210           assert(Indices.size() == OldSize && "Did not return to the old size");
03211           Indices.push_back(Idx);
03212           GEPIndices.push_back(IRB.getInt32(Idx));
03213           emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
03214           GEPIndices.pop_back();
03215           Indices.pop_back();
03216         }
03217         return;
03218       }
03219 
03220       if (StructType *STy = dyn_cast<StructType>(Ty)) {
03221         unsigned OldSize = Indices.size();
03222         (void)OldSize;
03223         for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
03224              ++Idx) {
03225           assert(Indices.size() == OldSize && "Did not return to the old size");
03226           Indices.push_back(Idx);
03227           GEPIndices.push_back(IRB.getInt32(Idx));
03228           emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
03229           GEPIndices.pop_back();
03230           Indices.pop_back();
03231         }
03232         return;
03233       }
03234 
03235       llvm_unreachable("Only arrays and structs are aggregate loadable types");
03236     }
03237   };
03238 
03239   struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
03240     LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
03241         : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
03242 
03243     /// Emit a leaf load of a single value. This is called at the leaves of the
03244     /// recursive emission to actually load values.
03245     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
03246       assert(Ty->isSingleValueType());
03247       // Load the single value and insert it using the indices.
03248       Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
03249       Value *Load = IRB.CreateLoad(GEP, Name + ".load");
03250       Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
03251       DEBUG(dbgs() << "          to: " << *Load << "\n");
03252     }
03253   };
03254 
03255   bool visitLoadInst(LoadInst &LI) {
03256     assert(LI.getPointerOperand() == *U);
03257     if (!LI.isSimple() || LI.getType()->isSingleValueType())
03258       return false;
03259 
03260     // We have an aggregate being loaded, split it apart.
03261     DEBUG(dbgs() << "    original: " << LI << "\n");
03262     LoadOpSplitter Splitter(&LI, *U);
03263     Value *V = UndefValue::get(LI.getType());
03264     Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
03265     LI.replaceAllUsesWith(V);
03266     LI.eraseFromParent();
03267     return true;
03268   }
03269 
03270   struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
03271     StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
03272         : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
03273 
03274     /// Emit a leaf store of a single value. This is called at the leaves of the
03275     /// recursive emission to actually produce stores.
03276     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
03277       assert(Ty->isSingleValueType());
03278       // Extract the single value and store it using the indices.
03279       Value *Store = IRB.CreateStore(
03280           IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
03281           IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
03282       (void)Store;
03283       DEBUG(dbgs() << "          to: " << *Store << "\n");
03284     }
03285   };
03286 
03287   bool visitStoreInst(StoreInst &SI) {
03288     if (!SI.isSimple() || SI.getPointerOperand() != *U)
03289       return false;
03290     Value *V = SI.getValueOperand();
03291     if (V->getType()->isSingleValueType())
03292       return false;
03293 
03294     // We have an aggregate being stored, split it apart.
03295     DEBUG(dbgs() << "    original: " << SI << "\n");
03296     StoreOpSplitter Splitter(&SI, *U);
03297     Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
03298     SI.eraseFromParent();
03299     return true;
03300   }
03301 
03302   bool visitBitCastInst(BitCastInst &BC) {
03303     enqueueUsers(BC);
03304     return false;
03305   }
03306 
03307   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
03308     enqueueUsers(GEPI);
03309     return false;
03310   }
03311 
03312   bool visitPHINode(PHINode &PN) {
03313     enqueueUsers(PN);
03314     return false;
03315   }
03316 
03317   bool visitSelectInst(SelectInst &SI) {
03318     enqueueUsers(SI);
03319     return false;
03320   }
03321 };
03322 }
03323 
03324 /// \brief Strip aggregate type wrapping.
03325 ///
03326 /// This removes no-op aggregate types wrapping an underlying type. It will
03327 /// strip as many layers of types as it can without changing either the type
03328 /// size or the allocated size.
03329 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
03330   if (Ty->isSingleValueType())
03331     return Ty;
03332 
03333   uint64_t AllocSize = DL.getTypeAllocSize(Ty);
03334   uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
03335 
03336   Type *InnerTy;
03337   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
03338     InnerTy = ArrTy->getElementType();
03339   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
03340     const StructLayout *SL = DL.getStructLayout(STy);
03341     unsigned Index = SL->getElementContainingOffset(0);
03342     InnerTy = STy->getElementType(Index);
03343   } else {
03344     return Ty;
03345   }
03346 
03347   if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
03348       TypeSize > DL.getTypeSizeInBits(InnerTy))
03349     return Ty;
03350 
03351   return stripAggregateTypeWrapping(DL, InnerTy);
03352 }
03353 
03354 /// \brief Try to find a partition of the aggregate type passed in for a given
03355 /// offset and size.
03356 ///
03357 /// This recurses through the aggregate type and tries to compute a subtype
03358 /// based on the offset and size. When the offset and size span a sub-section
03359 /// of an array, it will even compute a new array type for that sub-section,
03360 /// and the same for structs.
03361 ///
03362 /// Note that this routine is very strict and tries to find a partition of the
03363 /// type which produces the *exact* right offset and size. It is not forgiving
03364 /// when the size or offset cause either end of type-based partition to be off.
03365 /// Also, this is a best-effort routine. It is reasonable to give up and not
03366 /// return a type if necessary.
03367 static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
03368                               uint64_t Size) {
03369   if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
03370     return stripAggregateTypeWrapping(DL, Ty);
03371   if (Offset > DL.getTypeAllocSize(Ty) ||
03372       (DL.getTypeAllocSize(Ty) - Offset) < Size)
03373     return nullptr;
03374 
03375   if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
03376     // We can't partition pointers...
03377     if (SeqTy->isPointerTy())
03378       return nullptr;
03379 
03380     Type *ElementTy = SeqTy->getElementType();
03381     uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
03382     uint64_t NumSkippedElements = Offset / ElementSize;
03383     if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
03384       if (NumSkippedElements >= ArrTy->getNumElements())
03385         return nullptr;
03386     } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
03387       if (NumSkippedElements >= VecTy->getNumElements())
03388         return nullptr;
03389     }
03390     Offset -= NumSkippedElements * ElementSize;
03391 
03392     // First check if we need to recurse.
03393     if (Offset > 0 || Size < ElementSize) {
03394       // Bail if the partition ends in a different array element.
03395       if ((Offset + Size) > ElementSize)
03396         return nullptr;
03397       // Recurse through the element type trying to peel off offset bytes.
03398       return getTypePartition(DL, ElementTy, Offset, Size);
03399     }
03400     assert(Offset == 0);
03401 
03402     if (Size == ElementSize)
03403       return stripAggregateTypeWrapping(DL, ElementTy);
03404     assert(Size > ElementSize);
03405     uint64_t NumElements = Size / ElementSize;
03406     if (NumElements * ElementSize != Size)
03407       return nullptr;
03408     return ArrayType::get(ElementTy, NumElements);
03409   }
03410 
03411   StructType *STy = dyn_cast<StructType>(Ty);
03412   if (!STy)
03413     return nullptr;
03414 
03415   const StructLayout *SL = DL.getStructLayout(STy);
03416   if (Offset >= SL->getSizeInBytes())
03417     return nullptr;
03418   uint64_t EndOffset = Offset + Size;
03419   if (EndOffset > SL->getSizeInBytes())
03420     return nullptr;
03421 
03422   unsigned Index = SL->getElementContainingOffset(Offset);
03423   Offset -= SL->getElementOffset(Index);
03424 
03425   Type *ElementTy = STy->getElementType(Index);
03426   uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
03427   if (Offset >= ElementSize)
03428     return nullptr; // The offset points into alignment padding.
03429 
03430   // See if any partition must be contained by the element.
03431   if (Offset > 0 || Size < ElementSize) {
03432     if ((Offset + Size) > ElementSize)
03433       return nullptr;
03434     return getTypePartition(DL, ElementTy, Offset, Size);
03435   }
03436   assert(Offset == 0);
03437 
03438   if (Size == ElementSize)
03439     return stripAggregateTypeWrapping(DL, ElementTy);
03440 
03441   StructType::element_iterator EI = STy->element_begin() + Index,
03442                                EE = STy->element_end();
03443   if (EndOffset < SL->getSizeInBytes()) {
03444     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
03445     if (Index == EndIndex)
03446       return nullptr; // Within a single element and its padding.
03447 
03448     // Don't try to form "natural" types if the elements don't line up with the
03449     // expected size.
03450     // FIXME: We could potentially recurse down through the last element in the
03451     // sub-struct to find a natural end point.
03452     if (SL->getElementOffset(EndIndex) != EndOffset)
03453       return nullptr;
03454 
03455     assert(Index < EndIndex);
03456     EE = STy->element_begin() + EndIndex;
03457   }
03458 
03459   // Try to build up a sub-structure.
03460   StructType *SubTy =
03461       StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
03462   const StructLayout *SubSL = DL.getStructLayout(SubTy);
03463   if (Size != SubSL->getSizeInBytes())
03464     return nullptr; // The sub-struct doesn't have quite the size needed.
03465 
03466   return SubTy;
03467 }
03468 
03469 /// \brief Pre-split loads and stores to simplify rewriting.
03470 ///
03471 /// We want to break up the splittable load+store pairs as much as
03472 /// possible. This is important to do as a preprocessing step, as once we
03473 /// start rewriting the accesses to partitions of the alloca we lose the
03474 /// necessary information to correctly split apart paired loads and stores
03475 /// which both point into this alloca. The case to consider is something like
03476 /// the following:
03477 ///
03478 ///   %a = alloca [12 x i8]
03479 ///   %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
03480 ///   %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
03481 ///   %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
03482 ///   %iptr1 = bitcast i8* %gep1 to i64*
03483 ///   %iptr2 = bitcast i8* %gep2 to i64*
03484 ///   %fptr1 = bitcast i8* %gep1 to float*
03485 ///   %fptr2 = bitcast i8* %gep2 to float*
03486 ///   %fptr3 = bitcast i8* %gep3 to float*
03487 ///   store float 0.0, float* %fptr1
03488 ///   store float 1.0, float* %fptr2
03489 ///   %v = load i64* %iptr1
03490 ///   store i64 %v, i64* %iptr2
03491 ///   %f1 = load float* %fptr2
03492 ///   %f2 = load float* %fptr3
03493 ///
03494 /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
03495 /// promote everything so we recover the 2 SSA values that should have been
03496 /// there all along.
03497 ///
03498 /// \returns true if any changes are made.
03499 bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
03500   DEBUG(dbgs() << "Pre-splitting loads and stores\n");
03501 
03502   // Track the loads and stores which are candidates for pre-splitting here, in
03503   // the order they first appear during the partition scan. These give stable
03504   // iteration order and a basis for tracking which loads and stores we
03505   // actually split.
03506   SmallVector<LoadInst *, 4> Loads;
03507   SmallVector<StoreInst *, 4> Stores;
03508 
03509   // We need to accumulate the splits required of each load or store where we
03510   // can find them via a direct lookup. This is important to cross-check loads
03511   // and stores against each other. We also track the slice so that we can kill
03512   // all the slices that end up split.
03513   struct SplitOffsets {
03514     Slice *S;
03515     std::vector<uint64_t> Splits;
03516   };
03517   SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
03518 
03519   // Track loads out of this alloca which cannot, for any reason, be pre-split.
03520   // This is important as we also cannot pre-split stores of those loads!
03521   // FIXME: This is all pretty gross. It means that we can be more aggressive
03522   // in pre-splitting when the load feeding the store happens to come from
03523   // a separate alloca. Put another way, the effectiveness of SROA would be
03524   // decreased by a frontend which just concatenated all of its local allocas
03525   // into one big flat alloca. But defeating such patterns is exactly the job
03526   // SROA is tasked with! Sadly, to not have this discrepancy we would have
03527   // change store pre-splitting to actually force pre-splitting of the load
03528   // that feeds it *and all stores*. That makes pre-splitting much harder, but
03529   // maybe it would make it more principled?
03530   SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
03531 
03532   DEBUG(dbgs() << "  Searching for candidate loads and stores\n");
03533   for (auto &P : AS.partitions()) {
03534     for (Slice &S : P) {
03535       Instruction *I = cast<Instruction>(S.getUse()->getUser());
03536       if (!S.isSplittable() ||S.endOffset() <= P.endOffset()) {
03537         // If this was a load we have to track that it can't participate in any
03538         // pre-splitting!
03539         if (auto *LI = dyn_cast<LoadInst>(I))
03540           UnsplittableLoads.insert(LI);
03541         continue;
03542       }
03543       assert(P.endOffset() > S.beginOffset() &&
03544              "Empty or backwards partition!");
03545 
03546       // Determine if this is a pre-splittable slice.
03547       if (auto *LI = dyn_cast<LoadInst>(I)) {
03548         assert(!LI->isVolatile() && "Cannot split volatile loads!");
03549 
03550         // The load must be used exclusively to store into other pointers for
03551         // us to be able to arbitrarily pre-split it. The stores must also be
03552         // simple to avoid changing semantics.
03553         auto IsLoadSimplyStored = [](LoadInst *LI) {
03554           for (User *LU : LI->users()) {
03555             auto *SI = dyn_cast<StoreInst>(LU);
03556             if (!SI || !SI->isSimple())
03557               return false;
03558           }
03559           return true;
03560         };
03561         if (!IsLoadSimplyStored(LI)) {
03562           UnsplittableLoads.insert(LI);
03563           continue;
03564         }
03565 
03566         Loads.push_back(LI);
03567       } else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) {
03568         if (!SI ||
03569             S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
03570           continue;
03571         auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
03572         if (!StoredLoad || !StoredLoad->isSimple())
03573           continue;
03574         assert(!SI->isVolatile() && "Cannot split volatile stores!");
03575 
03576         Stores.push_back(SI);
03577       } else {
03578         // Other uses cannot be pre-split.
03579         continue;
03580       }
03581 
03582       // Record the initial split.
03583       DEBUG(dbgs() << "    Candidate: " << *I << "\n");
03584       auto &Offsets = SplitOffsetsMap[I];
03585       assert(Offsets.Splits.empty() &&
03586              "Should not have splits the first time we see an instruction!");
03587       Offsets.S = &S;
03588       Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
03589     }
03590 
03591     // Now scan the already split slices, and add a split for any of them which
03592     // we're going to pre-split.
03593     for (Slice *S : P.splitSliceTails()) {
03594       auto SplitOffsetsMapI =
03595           SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
03596       if (SplitOffsetsMapI == SplitOffsetsMap.end())
03597         continue;
03598       auto &Offsets = SplitOffsetsMapI->second;
03599 
03600       assert(Offsets.S == S && "Found a mismatched slice!");
03601       assert(!Offsets.Splits.empty() &&
03602              "Cannot have an empty set of splits on the second partition!");
03603       assert(Offsets.Splits.back() ==
03604                  P.beginOffset() - Offsets.S->beginOffset() &&
03605              "Previous split does not end where this one begins!");
03606 
03607       // Record each split. The last partition's end isn't needed as the size
03608       // of the slice dictates that.
03609       if (S->endOffset() > P.endOffset())
03610         Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
03611     }
03612   }
03613 
03614   // We may have split loads where some of their stores are split stores. For
03615   // such loads and stores, we can only pre-split them if their splits exactly
03616   // match relative to their starting offset. We have to verify this prior to
03617   // any rewriting.
03618   Stores.erase(
03619       std::remove_if(Stores.begin(), Stores.end(),
03620                      [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
03621                        // Lookup the load we are storing in our map of split
03622                        // offsets.
03623                        auto *LI = cast<LoadInst>(SI->getValueOperand());
03624                        // If it was completely unsplittable, then we're done,
03625                        // and this store can't be pre-split.
03626                        if (UnsplittableLoads.count(LI))
03627                          return true;
03628 
03629                        auto LoadOffsetsI = SplitOffsetsMap.find(LI);
03630                        if (LoadOffsetsI == SplitOffsetsMap.end())
03631                          return false; // Unrelated loads are definitely safe.
03632                        auto &LoadOffsets = LoadOffsetsI->second;
03633 
03634                        // Now lookup the store's offsets.
03635                        auto &StoreOffsets = SplitOffsetsMap[SI];
03636 
03637                        // If the relative offsets of each split in the load and
03638                        // store match exactly, then we can split them and we
03639                        // don't need to remove them here.
03640                        if (LoadOffsets.Splits == StoreOffsets.Splits)
03641                          return false;
03642 
03643                        DEBUG(dbgs()
03644                              << "    Mismatched splits for load and store:\n"
03645                              << "      " << *LI << "\n"
03646                              << "      " << *SI << "\n");
03647 
03648                        // We've found a store and load that we need to split
03649                        // with mismatched relative splits. Just give up on them
03650                        // and remove both instructions from our list of
03651                        // candidates.
03652                        UnsplittableLoads.insert(LI);
03653                        return true;
03654                      }),
03655       Stores.end());
03656   // Now we have to go *back* through all te stores, because a later store may
03657   // have caused an earlier store's load to become unsplittable and if it is
03658   // unsplittable for the later store, then we can't rely on it being split in
03659   // the earlier store either.
03660   Stores.erase(std::remove_if(Stores.begin(), Stores.end(),
03661                               [&UnsplittableLoads](StoreInst *SI) {
03662                                 auto *LI =
03663                                     cast<LoadInst>(SI->getValueOperand());
03664                                 return UnsplittableLoads.count(LI);
03665                               }),
03666                Stores.end());
03667   // Once we've established all the loads that can't be split for some reason,
03668   // filter any that made it into our list out.
03669   Loads.erase(std::remove_if(Loads.begin(), Loads.end(),
03670                              [&UnsplittableLoads](LoadInst *LI) {
03671                                return UnsplittableLoads.count(LI);
03672                              }),
03673               Loads.end());
03674 
03675 
03676   // If no loads or stores are left, there is no pre-splitting to be done for
03677   // this alloca.
03678   if (Loads.empty() && Stores.empty())
03679     return false;
03680 
03681   // From here on, we can't fail and will be building new accesses, so rig up
03682   // an IR builder.
03683   IRBuilderTy IRB(&AI);
03684 
03685   // Collect the new slices which we will merge into the alloca slices.
03686   SmallVector<Slice, 4> NewSlices;
03687 
03688   // Track any allocas we end up splitting loads and stores for so we iterate
03689   // on them.
03690   SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
03691 
03692   // At this point, we have collected all of the loads and stores we can
03693   // pre-split, and the specific splits needed for them. We actually do the
03694   // splitting in a specific order in order to handle when one of the loads in
03695   // the value operand to one of the stores.
03696   //
03697   // First, we rewrite all of the split loads, and just accumulate each split
03698   // load in a parallel structure. We also build the slices for them and append
03699   // them to the alloca slices.
03700   SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
03701   std::vector<LoadInst *> SplitLoads;
03702   for (LoadInst *LI : Loads) {
03703     SplitLoads.clear();
03704 
03705     IntegerType *Ty = cast<IntegerType>(LI->getType());
03706     uint64_t LoadSize = Ty->getBitWidth() / 8;
03707     assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
03708 
03709     auto &Offsets = SplitOffsetsMap[LI];
03710     assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
03711            "Slice size should always match load size exactly!");
03712     uint64_t BaseOffset = Offsets.S->beginOffset();
03713     assert(BaseOffset + LoadSize > BaseOffset &&
03714            "Cannot represent alloca access size using 64-bit integers!");
03715 
03716     Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
03717     IRB.SetInsertPoint(BasicBlock::iterator(LI));
03718 
03719     DEBUG(dbgs() << "  Splitting load: " << *LI << "\n");
03720 
03721     uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
03722     int Idx = 0, Size = Offsets.Splits.size();
03723     for (;;) {
03724       auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
03725       auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
03726       LoadInst *PLoad = IRB.CreateAlignedLoad(
03727           getAdjustedPtr(IRB, *DL, BasePtr,
03728                          APInt(DL->getPointerSizeInBits(), PartOffset),
03729                          PartPtrTy, BasePtr->getName() + "."),
03730           getAdjustedAlignment(LI, PartOffset, *DL), /*IsVolatile*/ false,
03731           LI->getName());
03732 
03733       // Append this load onto the list of split loads so we can find it later
03734       // to rewrite the stores.
03735       SplitLoads.push_back(PLoad);
03736 
03737       // Now build a new slice for the alloca.
03738       NewSlices.push_back(
03739           Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
03740                 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
03741                 /*IsSplittable*/ false));
03742       DEBUG(dbgs() << "    new slice [" << NewSlices.back().beginOffset()
03743                    << ", " << NewSlices.back().endOffset() << "): " << *PLoad
03744                    << "\n");
03745 
03746       // See if we've handled all the splits.
03747       if (Idx >= Size)
03748         break;
03749 
03750       // Setup the next partition.
03751       PartOffset = Offsets.Splits[Idx];
03752       ++Idx;
03753       PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
03754     }
03755 
03756     // Now that we have the split loads, do the slow walk over all uses of the
03757     // load and rewrite them as split stores, or save the split loads to use
03758     // below if the store is going to be split there anyways.
03759     bool DeferredStores = false;
03760     for (User *LU : LI->users()) {
03761       StoreInst *SI = cast<StoreInst>(LU);
03762       if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
03763         DeferredStores = true;
03764         DEBUG(dbgs() << "    Deferred splitting of store: " << *SI << "\n");
03765         continue;
03766       }
03767 
03768       Value *StoreBasePtr = SI->getPointerOperand();
03769       IRB.SetInsertPoint(BasicBlock::iterator(SI));
03770 
03771       DEBUG(dbgs() << "    Splitting store of load: " << *SI << "\n");
03772 
03773       for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
03774         LoadInst *PLoad = SplitLoads[Idx];
03775         uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
03776         auto *PartPtrTy =
03777             PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
03778 
03779         StoreInst *PStore = IRB.CreateAlignedStore(
03780             PLoad, getAdjustedPtr(IRB, *DL, StoreBasePtr,
03781                                   APInt(DL->getPointerSizeInBits(), PartOffset),
03782                                   PartPtrTy, StoreBasePtr->getName() + "."),
03783             getAdjustedAlignment(SI, PartOffset, *DL), /*IsVolatile*/ false);
03784         (void)PStore;
03785         DEBUG(dbgs() << "      +" << PartOffset << ":" << *PStore << "\n");
03786       }
03787 
03788       // We want to immediately iterate on any allocas impacted by splitting
03789       // this store, and we have to track any promotable alloca (indicated by
03790       // a direct store) as needing to be resplit because it is no longer
03791       // promotable.
03792       if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
03793         ResplitPromotableAllocas.insert(OtherAI);
03794         Worklist.insert(OtherAI);
03795       } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
03796                      StoreBasePtr->stripInBoundsOffsets())) {
03797         Worklist.insert(OtherAI);
03798       }
03799 
03800       // Mark the original store as dead.
03801       DeadInsts.insert(SI);
03802     }
03803 
03804     // Save the split loads if there are deferred stores among the users.
03805     if (DeferredStores)
03806       SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
03807 
03808     // Mark the original load as dead and kill the original slice.
03809     DeadInsts.insert(LI);
03810     Offsets.S->kill();
03811   }
03812 
03813   // Second, we rewrite all of the split stores. At this point, we know that
03814   // all loads from this alloca have been split already. For stores of such
03815   // loads, we can simply look up the pre-existing split loads. For stores of
03816   // other loads, we split those loads first and then write split stores of
03817   // them.
03818   for (StoreInst *SI : Stores) {
03819     auto *LI = cast<LoadInst>(SI->getValueOperand());
03820     IntegerType *Ty = cast<IntegerType>(LI->getType());
03821     uint64_t StoreSize = Ty->getBitWidth() / 8;
03822     assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
03823 
03824     auto &Offsets = SplitOffsetsMap[SI];
03825     assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
03826            "Slice size should always match load size exactly!");
03827     uint64_t BaseOffset = Offsets.S->beginOffset();
03828     assert(BaseOffset + StoreSize > BaseOffset &&
03829            "Cannot represent alloca access size using 64-bit integers!");
03830 
03831     Value *LoadBasePtr = LI->getPointerOperand();
03832     Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
03833 
03834     DEBUG(dbgs() << "  Splitting store: " << *SI << "\n");
03835 
03836     // Check whether we have an already split load.
03837     auto SplitLoadsMapI = SplitLoadsMap.find(LI);
03838     std::vector<LoadInst *> *SplitLoads = nullptr;
03839     if (SplitLoadsMapI != SplitLoadsMap.end()) {
03840       SplitLoads = &SplitLoadsMapI->second;
03841       assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
03842              "Too few split loads for the number of splits in the store!");
03843     } else {
03844       DEBUG(dbgs() << "          of load: " << *LI << "\n");
03845     }
03846 
03847     uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
03848     int Idx = 0, Size = Offsets.Splits.size();
03849     for (;;) {
03850       auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
03851       auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
03852 
03853       // Either lookup a split load or create one.
03854       LoadInst *PLoad;
03855       if (SplitLoads) {
03856         PLoad = (*SplitLoads)[Idx];
03857       } else {
03858         IRB.SetInsertPoint(BasicBlock::iterator(LI));
03859         PLoad = IRB.CreateAlignedLoad(
03860             getAdjustedPtr(IRB, *DL, LoadBasePtr,
03861                            APInt(DL->getPointerSizeInBits(), PartOffset),
03862                            PartPtrTy, LoadBasePtr->getName() + "."),
03863             getAdjustedAlignment(LI, PartOffset, *DL), /*IsVolatile*/ false,
03864             LI->getName());
03865       }
03866 
03867       // And store this partition.
03868       IRB.SetInsertPoint(BasicBlock::iterator(SI));
03869       StoreInst *PStore = IRB.CreateAlignedStore(
03870           PLoad, getAdjustedPtr(IRB, *DL, StoreBasePtr,
03871                                 APInt(DL->getPointerSizeInBits(), PartOffset),
03872                                 PartPtrTy, StoreBasePtr->getName() + "."),
03873           getAdjustedAlignment(SI, PartOffset, *DL), /*IsVolatile*/ false);
03874 
03875       // Now build a new slice for the alloca.
03876       NewSlices.push_back(
03877           Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
03878                 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
03879                 /*IsSplittable*/ false));
03880       DEBUG(dbgs() << "    new slice [" << NewSlices.back().beginOffset()
03881                    << ", " << NewSlices.back().endOffset() << "): " << *PStore
03882                    << "\n");
03883       if (!SplitLoads) {
03884         DEBUG(dbgs() << "      of split load: " << *PLoad << "\n");
03885       }
03886 
03887       // See if we've finished all the splits.
03888       if (Idx >= Size)
03889         break;
03890 
03891       // Setup the next partition.
03892       PartOffset = Offsets.Splits[Idx];
03893       ++Idx;
03894       PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
03895     }
03896 
03897     // We want to immediately iterate on any allocas impacted by splitting
03898     // this load, which is only relevant if it isn't a load of this alloca and
03899     // thus we didn't already split the loads above. We also have to keep track
03900     // of any promotable allocas we split loads on as they can no longer be
03901     // promoted.
03902     if (!SplitLoads) {
03903       if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
03904         assert(OtherAI != &AI && "We can't re-split our own alloca!");
03905         ResplitPromotableAllocas.insert(OtherAI);
03906         Worklist.insert(OtherAI);
03907       } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
03908                      LoadBasePtr->stripInBoundsOffsets())) {
03909         assert(OtherAI != &AI && "We can't re-split our own alloca!");
03910         Worklist.insert(OtherAI);
03911       }
03912     }
03913 
03914     // Mark the original store as dead now that we've split it up and kill its
03915     // slice. Note that we leave the original load in place unless this store
03916     // was its ownly use. It may in turn be split up if it is an alloca load
03917     // for some other alloca, but it may be a normal load. This may introduce
03918     // redundant loads, but where those can be merged the rest of the optimizer
03919     // should handle the merging, and this uncovers SSA splits which is more
03920     // important. In practice, the original loads will almost always be fully
03921     // split and removed eventually, and the splits will be merged by any
03922     // trivial CSE, including instcombine.
03923     if (LI->hasOneUse()) {
03924       assert(*LI->user_begin() == SI && "Single use isn't this store!");
03925       DeadInsts.insert(LI);
03926     }
03927     DeadInsts.insert(SI);
03928     Offsets.S->kill();
03929   }
03930 
03931   // Remove the killed slices that have ben pre-split.
03932   AS.erase(std::remove_if(AS.begin(), AS.end(), [](const Slice &S) {
03933     return S.isDead();
03934   }), AS.end());
03935 
03936   // Insert our new slices. This will sort and merge them into the sorted
03937   // sequence.
03938   AS.insert(NewSlices);
03939 
03940   DEBUG(dbgs() << "  Pre-split slices:\n");
03941 #ifndef NDEBUG
03942   for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
03943     DEBUG(AS.print(dbgs(), I, "    "));
03944 #endif
03945 
03946   // Finally, don't try to promote any allocas that new require re-splitting.
03947   // They have already been added to the worklist above.
03948   PromotableAllocas.erase(
03949       std::remove_if(
03950           PromotableAllocas.begin(), PromotableAllocas.end(),
03951           [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
03952       PromotableAllocas.end());
03953 
03954   return true;
03955 }
03956 
03957 /// \brief Rewrite an alloca partition's users.
03958 ///
03959 /// This routine drives both of the rewriting goals of the SROA pass. It tries
03960 /// to rewrite uses of an alloca partition to be conducive for SSA value
03961 /// promotion. If the partition needs a new, more refined alloca, this will
03962 /// build that new alloca, preserving as much type information as possible, and
03963 /// rewrite the uses of the old alloca to point at the new one and have the
03964 /// appropriate new offsets. It also evaluates how successful the rewrite was
03965 /// at enabling promotion and if it was successful queues the alloca to be
03966 /// promoted.
03967 AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
03968                                    AllocaSlices::Partition &P) {
03969   // Try to compute a friendly type for this partition of the alloca. This
03970   // won't always succeed, in which case we fall back to a legal integer type
03971   // or an i8 array of an appropriate size.
03972   Type *SliceTy = nullptr;
03973   if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
03974     if (DL->getTypeAllocSize(CommonUseTy) >= P.size())
03975       SliceTy = CommonUseTy;
03976   if (!SliceTy)
03977     if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
03978                                                  P.beginOffset(), P.size()))
03979       SliceTy = TypePartitionTy;
03980   if ((!SliceTy || (SliceTy->isArrayTy() &&
03981                     SliceTy->getArrayElementType()->isIntegerTy())) &&
03982       DL->isLegalInteger(P.size() * 8))
03983     SliceTy = Type::getIntNTy(*C, P.size() * 8);
03984   if (!SliceTy)
03985     SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
03986   assert(DL->getTypeAllocSize(SliceTy) >= P.size());
03987 
03988   bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, *DL);
03989 
03990   VectorType *VecTy =
03991       IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, *DL);
03992   if (VecTy)
03993     SliceTy = VecTy;
03994 
03995   // Check for the case where we're going to rewrite to a new alloca of the
03996   // exact same type as the original, and with the same access offsets. In that
03997   // case, re-use the existing alloca, but still run through the rewriter to
03998   // perform phi and select speculation.
03999   AllocaInst *NewAI;
04000   if (SliceTy == AI.getAllocatedType()) {
04001     assert(P.beginOffset() == 0 &&
04002            "Non-zero begin offset but same alloca type");
04003     NewAI = &AI;
04004     // FIXME: We should be able to bail at this point with "nothing changed".
04005     // FIXME: We might want to defer PHI speculation until after here.
04006     // FIXME: return nullptr;
04007   } else {
04008     unsigned Alignment = AI.getAlignment();
04009     if (!Alignment) {
04010       // The minimum alignment which users can rely on when the explicit
04011       // alignment is omitted or zero is that required by the ABI for this
04012       // type.
04013       Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
04014     }
04015     Alignment = MinAlign(Alignment, P.beginOffset());
04016     // If we will get at least this much alignment from the type alone, leave
04017     // the alloca's alignment unconstrained.
04018     if (Alignment <= DL->getABITypeAlignment(SliceTy))
04019       Alignment = 0;
04020     NewAI = new AllocaInst(
04021         SliceTy, nullptr, Alignment,
04022         AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
04023     ++NumNewAllocas;
04024   }
04025 
04026   DEBUG(dbgs() << "Rewriting alloca partition "
04027                << "[" << P.beginOffset() << "," << P.endOffset()
04028                << ") to: " << *NewAI << "\n");
04029 
04030   // Track the high watermark on the worklist as it is only relevant for
04031   // promoted allocas. We will reset it to this point if the alloca is not in
04032   // fact scheduled for promotion.
04033   unsigned PPWOldSize = PostPromotionWorklist.size();
04034   unsigned NumUses = 0;
04035   SmallPtrSet<PHINode *, 8> PHIUsers;
04036   SmallPtrSet<SelectInst *, 8> SelectUsers;
04037 
04038   AllocaSliceRewriter Rewriter(*DL, AS, *this, AI, *NewAI, P.beginOffset(),
04039                                P.endOffset(), IsIntegerPromotable, VecTy,
04040                                PHIUsers, SelectUsers);
04041   bool Promotable = true;
04042   for (Slice *S : P.splitSliceTails()) {
04043     Promotable &= Rewriter.visit(S);
04044     ++NumUses;
04045   }
04046   for (Slice &S : P) {
04047     Promotable &= Rewriter.visit(&S);
04048     ++NumUses;
04049   }
04050 
04051   NumAllocaPartitionUses += NumUses;
04052   MaxUsesPerAllocaPartition =
04053       std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
04054 
04055   // Now that we've processed all the slices in the new partition, check if any
04056   // PHIs or Selects would block promotion.
04057   for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
04058                                             E = PHIUsers.end();
04059        I != E; ++I)
04060     if (!isSafePHIToSpeculate(**I, DL)) {
04061       Promotable = false;
04062       PHIUsers.clear();
04063       SelectUsers.clear();
04064       break;
04065     }
04066   for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
04067                                                E = SelectUsers.end();
04068        I != E; ++I)
04069     if (!isSafeSelectToSpeculate(**I, DL)) {
04070       Promotable = false;
04071       PHIUsers.clear();
04072       SelectUsers.clear();
04073       break;
04074     }
04075 
04076   if (Promotable) {
04077     if (PHIUsers.empty() && SelectUsers.empty()) {
04078       // Promote the alloca.
04079       PromotableAllocas.push_back(NewAI);
04080     } else {
04081       // If we have either PHIs or Selects to speculate, add them to those
04082       // worklists and re-queue the new alloca so that we promote in on the
04083       // next iteration.
04084       for (PHINode *PHIUser : PHIUsers)
04085         SpeculatablePHIs.insert(PHIUser);
04086       for (SelectInst *SelectUser : SelectUsers)
04087         SpeculatableSelects.insert(SelectUser);
04088       Worklist.insert(NewAI);
04089     }
04090   } else {
04091     // If we can't promote the alloca, iterate on it to check for new
04092     // refinements exposed by splitting the current alloca. Don't iterate on an
04093     // alloca which didn't actually change and didn't get promoted.
04094     if (NewAI != &AI)
04095       Worklist.insert(NewAI);
04096 
04097     // Drop any post-promotion work items if promotion didn't happen.
04098     while (PostPromotionWorklist.size() > PPWOldSize)
04099       PostPromotionWorklist.pop_back();
04100   }
04101 
04102   return NewAI;
04103 }
04104 
04105 /// \brief Walks the slices of an alloca and form partitions based on them,
04106 /// rewriting each of their uses.
04107 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
04108   if (AS.begin() == AS.end())
04109     return false;
04110 
04111   unsigned NumPartitions = 0;
04112   bool Changed = false;
04113 
04114   // First try to pre-split loads and stores.
04115   Changed |= presplitLoadsAndStores(AI, AS);
04116 
04117   // Now that we have identified any pre-splitting opportunities, mark any
04118   // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
04119   // to split these during pre-splitting, we want to force them to be
04120   // rewritten into a partition.
04121   bool IsSorted = true;
04122   for (Slice &S : AS) {
04123     if (!S.isSplittable())
04124       continue;
04125     // FIXME: We currently leave whole-alloca splittable loads and stores. This
04126     // used to be the only splittable loads and stores and we need to be
04127     // confident that the above handling of splittable loads and stores is
04128     // completely sufficient before we forcibly disable the remaining handling.
04129     if (S.beginOffset() == 0 &&
04130         S.endOffset() >= DL->getTypeAllocSize(AI.getAllocatedType()))
04131       continue;
04132     if (isa<LoadInst>(S.getUse()->getUser()) ||
04133         isa<StoreInst>(S.getUse()->getUser())) {
04134       S.makeUnsplittable();
04135       IsSorted = false;
04136     }
04137   }
04138   if (!IsSorted)
04139     std::sort(AS.begin(), AS.end());
04140 
04141   /// \brief Describes the allocas introduced by rewritePartition
04142   /// in order to migrate the debug info.
04143   struct Piece {
04144     AllocaInst *Alloca;
04145     uint64_t Offset;
04146     uint64_t Size;
04147     Piece(AllocaInst *AI, uint64_t O, uint64_t S)
04148       : Alloca(AI), Offset(O), Size(S) {}
04149   };
04150   SmallVector<Piece, 4> Pieces;
04151 
04152   // Rewrite each partition.
04153   for (auto &P : AS.partitions()) {
04154     if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
04155       Changed = true;
04156       if (NewAI != &AI) {
04157         uint64_t SizeOfByte = 8;
04158         uint64_t AllocaSize = DL->getTypeSizeInBits(NewAI->getAllocatedType());
04159         // Don't include any padding.
04160         uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
04161         Pieces.push_back(Piece(NewAI, P.beginOffset() * SizeOfByte, Size));
04162       }
04163     }
04164     ++NumPartitions;
04165   }
04166 
04167   NumAllocaPartitions += NumPartitions;
04168   MaxPartitionsPerAlloca =
04169       std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
04170 
04171   // Migrate debug information from the old alloca to the new alloca(s)
04172   // and the individial partitions.
04173   if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(&AI)) {
04174     DIVariable Var(DbgDecl->getVariable());
04175     DIExpression Expr(DbgDecl->getExpression());
04176     DIBuilder DIB(*AI.getParent()->getParent()->getParent(),
04177                   /*AllowUnresolved*/ false);
04178     bool IsSplit = Pieces.size() > 1;
04179     for (auto Piece : Pieces) {
04180       // Create a piece expression describing the new partition or reuse AI's
04181       // expression if there is only one partition.
04182       DIExpression PieceExpr = Expr;
04183       if (IsSplit || Expr.isBitPiece()) {
04184         // If this alloca is already a scalar replacement of a larger aggregate,
04185         // Piece.Offset describes the offset inside the scalar.
04186         uint64_t Offset = Expr.isBitPiece() ? Expr.getBitPieceOffset() : 0;
04187         uint64_t Start = Offset + Piece.Offset;
04188         uint64_t Size = Piece.Size;
04189         if (Expr.isBitPiece()) {
04190           uint64_t AbsEnd = Expr.getBitPieceOffset() + Expr.getBitPieceSize();
04191           if (Start >= AbsEnd)
04192             // No need to describe a SROAed padding.
04193             continue;
04194           Size = std::min(Size, AbsEnd - Start);
04195         }
04196         PieceExpr = DIB.createBitPieceExpression(Start, Size);
04197       }
04198 
04199       // Remove any existing dbg.declare intrinsic describing the same alloca.
04200       if (DbgDeclareInst *OldDDI = FindAllocaDbgDeclare(Piece.Alloca))
04201         OldDDI->eraseFromParent();
04202 
04203       auto *NewDDI = DIB.insertDeclare(Piece.Alloca, Var, PieceExpr, &AI);
04204       NewDDI->setDebugLoc(DbgDecl->getDebugLoc());
04205     }
04206   }
04207   return Changed;
04208 }
04209 
04210 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
04211 void SROA::clobberUse(Use &U) {
04212   Value *OldV = U;
04213   // Replace the use with an undef value.
04214   U = UndefValue::get(OldV->getType());
04215 
04216   // Check for this making an instruction dead. We have to garbage collect
04217   // all the dead instructions to ensure the uses of any alloca end up being
04218   // minimal.
04219   if (Instruction *OldI = dyn_cast<Instruction>(OldV))
04220     if (isInstructionTriviallyDead(OldI)) {
04221       DeadInsts.insert(OldI);
04222     }
04223 }
04224 
04225 /// \brief Analyze an alloca for SROA.
04226 ///
04227 /// This analyzes the alloca to ensure we can reason about it, builds
04228 /// the slices of the alloca, and then hands it off to be split and
04229 /// rewritten as needed.
04230 bool SROA::runOnAlloca(AllocaInst &AI) {
04231   DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
04232   ++NumAllocasAnalyzed;
04233 
04234   // Special case dead allocas, as they're trivial.
04235   if (AI.use_empty()) {
04236     AI.eraseFromParent();
04237     return true;
04238   }
04239 
04240   // Skip alloca forms that this analysis can't handle.
04241   if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
04242       DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
04243     return false;
04244 
04245   bool Changed = false;
04246 
04247   // First, split any FCA loads and stores touching this alloca to promote
04248   // better splitting and promotion opportunities.
04249   AggLoadStoreRewriter AggRewriter(*DL);
04250   Changed |= AggRewriter.rewrite(AI);
04251 
04252   // Build the slices using a recursive instruction-visiting builder.
04253   AllocaSlices AS(*DL, AI);
04254   DEBUG(AS.print(dbgs()));
04255   if (AS.isEscaped())
04256     return Changed;
04257 
04258   // Delete all the dead users of this alloca before splitting and rewriting it.
04259   for (Instruction *DeadUser : AS.getDeadUsers()) {
04260     // Free up everything used by this instruction.
04261     for (Use &DeadOp : DeadUser->operands())
04262       clobberUse(DeadOp);
04263 
04264     // Now replace the uses of this instruction.
04265     DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
04266 
04267     // And mark it for deletion.
04268     DeadInsts.insert(DeadUser);
04269     Changed = true;
04270   }
04271   for (Use *DeadOp : AS.getDeadOperands()) {
04272     clobberUse(*DeadOp);
04273     Changed = true;
04274   }
04275 
04276   // No slices to split. Leave the dead alloca for a later pass to clean up.
04277   if (AS.begin() == AS.end())
04278     return Changed;
04279 
04280   Changed |= splitAlloca(AI, AS);
04281 
04282   DEBUG(dbgs() << "  Speculating PHIs\n");
04283   while (!SpeculatablePHIs.empty())
04284     speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
04285 
04286   DEBUG(dbgs() << "  Speculating Selects\n");
04287   while (!SpeculatableSelects.empty())
04288     speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
04289 
04290   return Changed;
04291 }
04292 
04293 /// \brief Delete the dead instructions accumulated in this run.
04294 ///
04295 /// Recursively deletes the dead instructions we've accumulated. This is done
04296 /// at the very end to maximize locality of the recursive delete and to
04297 /// minimize the problems of invalidated instruction pointers as such pointers
04298 /// are used heavily in the intermediate stages of the algorithm.
04299 ///
04300 /// We also record the alloca instructions deleted here so that they aren't
04301 /// subsequently handed to mem2reg to promote.
04302 void SROA::deleteDeadInstructions(
04303     SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
04304   while (!DeadInsts.empty()) {
04305     Instruction *I = DeadInsts.pop_back_val();
04306     DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
04307 
04308     I->replaceAllUsesWith(UndefValue::get(I->getType()));
04309 
04310     for (Use &Operand : I->operands())
04311       if (Instruction *U = dyn_cast<Instruction>(Operand)) {
04312         // Zero out the operand and see if it becomes trivially dead.
04313         Operand = nullptr;
04314         if (isInstructionTriviallyDead(U))
04315           DeadInsts.insert(U);
04316       }
04317 
04318     if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
04319       DeletedAllocas.insert(AI);
04320       if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
04321         DbgDecl->eraseFromParent();
04322     }
04323 
04324     ++NumDeleted;
04325     I->eraseFromParent();
04326   }
04327 }
04328 
04329 static void enqueueUsersInWorklist(Instruction &I,
04330                                    SmallVectorImpl<Instruction *> &Worklist,
04331                                    SmallPtrSetImpl<Instruction *> &Visited) {
04332   for (User *U : I.users())
04333     if (Visited.insert(cast<Instruction>(U)).second)
04334       Worklist.push_back(cast<Instruction>(U));
04335 }
04336 
04337 /// \brief Promote the allocas, using the best available technique.
04338 ///
04339 /// This attempts to promote whatever allocas have been identified as viable in
04340 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
04341 /// If there is a domtree available, we attempt to promote using the full power
04342 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
04343 /// based on the SSAUpdater utilities. This function returns whether any
04344 /// promotion occurred.
04345 bool SROA::promoteAllocas(Function &F) {
04346   if (PromotableAllocas.empty())
04347     return false;
04348 
04349   NumPromoted += PromotableAllocas.size();
04350 
04351   if (DT && !ForceSSAUpdater) {
04352     DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
04353     PromoteMemToReg(PromotableAllocas, *DT, nullptr, AC);
04354     PromotableAllocas.clear();
04355     return true;
04356   }
04357 
04358   DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
04359   SSAUpdater SSA;
04360   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
04361   SmallVector<Instruction *, 64> Insts;
04362 
04363   // We need a worklist to walk the uses of each alloca.
04364   SmallVector<Instruction *, 8> Worklist;
04365   SmallPtrSet<Instruction *, 8> Visited;
04366   SmallVector<Instruction *, 32> DeadInsts;
04367 
04368   for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
04369     AllocaInst *AI = PromotableAllocas[Idx];
04370     Insts.clear();
04371     Worklist.clear();
04372     Visited.clear();
04373 
04374     enqueueUsersInWorklist(*AI, Worklist, Visited);
04375 
04376     while (!Worklist.empty()) {
04377       Instruction *I = Worklist.pop_back_val();
04378 
04379       // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
04380       // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
04381       // leading to them) here. Eventually it should use them to optimize the
04382       // scalar values produced.
04383       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
04384         assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
04385                II->getIntrinsicID() == Intrinsic::lifetime_end);
04386         II->eraseFromParent();
04387         continue;
04388       }
04389 
04390       // Push the loads and stores we find onto the list. SROA will already
04391       // have validated that all loads and stores are viable candidates for
04392       // promotion.
04393       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
04394         assert(LI->getType() == AI->getAllocatedType());
04395         Insts.push_back(LI);
04396         continue;
04397       }
04398       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
04399         assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
04400         Insts.push_back(SI);
04401         continue;
04402       }
04403 
04404       // For everything else, we know that only no-op bitcasts and GEPs will
04405       // make it this far, just recurse through them and recall them for later
04406       // removal.
04407       DeadInsts.push_back(I);
04408       enqueueUsersInWorklist(*I, Worklist, Visited);
04409     }
04410     AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
04411     while (!DeadInsts.empty())
04412       DeadInsts.pop_back_val()->eraseFromParent();
04413     AI->eraseFromParent();
04414   }
04415 
04416   PromotableAllocas.clear();
04417   return true;
04418 }
04419 
04420 bool SROA::runOnFunction(Function &F) {
04421   if (skipOptnoneFunction(F))
04422     return false;
04423 
04424   DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
04425   C = &F.getContext();
04426   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
04427   if (!DLP) {
04428     DEBUG(dbgs() << "  Skipping SROA -- no target data!\n");
04429     return false;
04430   }
04431   DL = &DLP->getDataLayout();
04432   DominatorTreeWrapperPass *DTWP =
04433       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
04434   DT = DTWP ? &DTWP->getDomTree() : nullptr;
04435   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
04436 
04437   BasicBlock &EntryBB = F.getEntryBlock();
04438   for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
04439        I != E; ++I) {
04440     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
04441       Worklist.insert(AI);
04442   }
04443 
04444   bool Changed = false;
04445   // A set of deleted alloca instruction pointers which should be removed from
04446   // the list of promotable allocas.
04447   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
04448 
04449   do {
04450     while (!Worklist.empty()) {
04451       Changed |= runOnAlloca(*Worklist.pop_back_val());
04452       deleteDeadInstructions(DeletedAllocas);
04453 
04454       // Remove the deleted allocas from various lists so that we don't try to
04455       // continue processing them.
04456       if (!DeletedAllocas.empty()) {
04457         auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
04458         Worklist.remove_if(IsInSet);
04459         PostPromotionWorklist.remove_if(IsInSet);
04460         PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
04461                                                PromotableAllocas.end(),
04462                                                IsInSet),
04463                                 PromotableAllocas.end());
04464         DeletedAllocas.clear();
04465       }
04466     }
04467 
04468     Changed |= promoteAllocas(F);
04469 
04470     Worklist = PostPromotionWorklist;
04471     PostPromotionWorklist.clear();
04472   } while (!Worklist.empty());
04473 
04474   return Changed;
04475 }
04476 
04477 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
04478   AU.addRequired<AssumptionCacheTracker>();
04479   if (RequiresDomTree)
04480     AU.addRequired<DominatorTreeWrapperPass>();
04481   AU.setPreservesCFG();
04482 }