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