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