Reapply: Teach SROA how to update debug info for fragmented variables.
[oota-llvm.git] / lib / Transforms / Scalar / SROA.cpp
1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This transformation implements the well known scalar replacement of
11 /// aggregates transformation. It tries to identify promotable elements of an
12 /// aggregate alloca, and promote them to registers. It will also try to
13 /// convert uses of an element (or set of elements) of an alloca into a vector
14 /// or bitfield-style integer scalar if appropriate.
15 ///
16 /// It works to do this with minimal slicing of the alloca so that regions
17 /// which are merely transferred in and out of external memory remain unchanged
18 /// and are not decomposed to scalar code.
19 ///
20 /// Because this also performs alloca promotion, it can be thought of as also
21 /// serving the purpose of SSA formation. The algorithm iterates on the
22 /// function until all opportunities for promotion have been realized.
23 ///
24 //===----------------------------------------------------------------------===//
25
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/AssumptionCache.h"
32 #include "llvm/Analysis/Loads.h"
33 #include "llvm/Analysis/PtrUseVisitor.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DIBuilder.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DebugInfo.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Dominators.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/InstVisitor.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/IntrinsicInst.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Operator.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/TimeValue.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
58 #include "llvm/Transforms/Utils/SSAUpdater.h"
59
60 #if __cplusplus >= 201103L && !defined(NDEBUG)
61 // We only use this for a debug check in C++11
62 #include <random>
63 #endif
64
65 using namespace llvm;
66
67 #define DEBUG_TYPE "sroa"
68
69 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
70 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
71 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
72 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
73 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
74 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
75 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
76 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
77 STATISTIC(NumDeleted, "Number of instructions deleted");
78 STATISTIC(NumVectorized, "Number of vectorized aggregates");
79
80 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
81 /// forming SSA values through the SSAUpdater infrastructure.
82 static cl::opt<bool> ForceSSAUpdater("force-ssa-updater", cl::init(false),
83                                      cl::Hidden);
84
85 /// Hidden option to enable randomly shuffling the slices to help uncover
86 /// instability in their order.
87 static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
88                                              cl::init(false), cl::Hidden);
89
90 /// Hidden option to experiment with completely strict handling of inbounds
91 /// GEPs.
92 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
93                                         cl::Hidden);
94
95 namespace {
96 /// \brief A custom IRBuilder inserter which prefixes all names if they are
97 /// preserved.
98 template <bool preserveNames = true>
99 class IRBuilderPrefixedInserter
100     : public IRBuilderDefaultInserter<preserveNames> {
101   std::string Prefix;
102
103 public:
104   void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
105
106 protected:
107   void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
108                     BasicBlock::iterator InsertPt) const {
109     IRBuilderDefaultInserter<preserveNames>::InsertHelper(
110         I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
111   }
112 };
113
114 // Specialization for not preserving the name is trivial.
115 template <>
116 class IRBuilderPrefixedInserter<false>
117     : public IRBuilderDefaultInserter<false> {
118 public:
119   void SetNamePrefix(const Twine &P) {}
120 };
121
122 /// \brief Provide a typedef for IRBuilder that drops names in release builds.
123 #ifndef NDEBUG
124 typedef llvm::IRBuilder<true, ConstantFolder, IRBuilderPrefixedInserter<true>>
125     IRBuilderTy;
126 #else
127 typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
128     IRBuilderTy;
129 #endif
130 }
131
132 namespace {
133 /// \brief A used slice of an alloca.
134 ///
135 /// This structure represents a slice of an alloca used by some instruction. It
136 /// stores both the begin and end offsets of this use, a pointer to the use
137 /// itself, and a flag indicating whether we can classify the use as splittable
138 /// or not when forming partitions of the alloca.
139 class Slice {
140   /// \brief The beginning offset of the range.
141   uint64_t BeginOffset;
142
143   /// \brief The ending offset, not included in the range.
144   uint64_t EndOffset;
145
146   /// \brief Storage for both the use of this slice and whether it can be
147   /// split.
148   PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
149
150 public:
151   Slice() : BeginOffset(), EndOffset() {}
152   Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
153       : BeginOffset(BeginOffset), EndOffset(EndOffset),
154         UseAndIsSplittable(U, IsSplittable) {}
155
156   uint64_t beginOffset() const { return BeginOffset; }
157   uint64_t endOffset() const { return EndOffset; }
158
159   bool isSplittable() const { return UseAndIsSplittable.getInt(); }
160   void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
161
162   Use *getUse() const { return UseAndIsSplittable.getPointer(); }
163
164   bool isDead() const { return getUse() == nullptr; }
165   void kill() { UseAndIsSplittable.setPointer(nullptr); }
166
167   /// \brief Support for ordering ranges.
168   ///
169   /// This provides an ordering over ranges such that start offsets are
170   /// always increasing, and within equal start offsets, the end offsets are
171   /// decreasing. Thus the spanning range comes first in a cluster with the
172   /// same start position.
173   bool operator<(const Slice &RHS) const {
174     if (beginOffset() < RHS.beginOffset())
175       return true;
176     if (beginOffset() > RHS.beginOffset())
177       return false;
178     if (isSplittable() != RHS.isSplittable())
179       return !isSplittable();
180     if (endOffset() > RHS.endOffset())
181       return true;
182     return false;
183   }
184
185   /// \brief Support comparison with a single offset to allow binary searches.
186   friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
187                                               uint64_t RHSOffset) {
188     return LHS.beginOffset() < RHSOffset;
189   }
190   friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
191                                               const Slice &RHS) {
192     return LHSOffset < RHS.beginOffset();
193   }
194
195   bool operator==(const Slice &RHS) const {
196     return isSplittable() == RHS.isSplittable() &&
197            beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
198   }
199   bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
200 };
201 } // end anonymous namespace
202
203 namespace llvm {
204 template <typename T> struct isPodLike;
205 template <> struct isPodLike<Slice> { static const bool value = true; };
206 }
207
208 namespace {
209 /// \brief Representation of the alloca slices.
210 ///
211 /// This class represents the slices of an alloca which are formed by its
212 /// various uses. If a pointer escapes, we can't fully build a representation
213 /// for the slices used and we reflect that in this structure. The uses are
214 /// stored, sorted by increasing beginning offset and with unsplittable slices
215 /// starting at a particular offset before splittable slices.
216 class AllocaSlices {
217 public:
218   /// \brief Construct the slices of a particular alloca.
219   AllocaSlices(const DataLayout &DL, AllocaInst &AI);
220
221   /// \brief Test whether a pointer to the allocation escapes our analysis.
222   ///
223   /// If this is true, the slices are never fully built and should be
224   /// ignored.
225   bool isEscaped() const { return PointerEscapingInstr; }
226
227   /// \brief Support for iterating over the slices.
228   /// @{
229   typedef SmallVectorImpl<Slice>::iterator iterator;
230   typedef iterator_range<iterator> range;
231   iterator begin() { return Slices.begin(); }
232   iterator end() { return Slices.end(); }
233
234   typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
235   typedef iterator_range<const_iterator> const_range;
236   const_iterator begin() const { return Slices.begin(); }
237   const_iterator end() const { return Slices.end(); }
238   /// @}
239
240   /// \brief Erase a range of slices.
241   void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
242
243   /// \brief Insert new slices for this alloca.
244   ///
245   /// This moves the slices into the alloca's slices collection, and re-sorts
246   /// everything so that the usual ordering properties of the alloca's slices
247   /// hold.
248   void insert(ArrayRef<Slice> NewSlices) {
249     int OldSize = Slices.size();
250     std::move(NewSlices.begin(), NewSlices.end(), std::back_inserter(Slices));
251     auto SliceI = Slices.begin() + OldSize;
252     std::sort(SliceI, Slices.end());
253     std::inplace_merge(Slices.begin(), SliceI, Slices.end());
254   }
255
256   // Forward declare an iterator to befriend it.
257   class partition_iterator;
258
259   /// \brief A partition of the slices.
260   ///
261   /// An ephemeral representation for a range of slices which can be viewed as
262   /// a partition of the alloca. This range represents a span of the alloca's
263   /// memory which cannot be split, and provides access to all of the slices
264   /// overlapping some part of the partition.
265   ///
266   /// Objects of this type are produced by traversing the alloca's slices, but
267   /// are only ephemeral and not persistent.
268   class Partition {
269   private:
270     friend class AllocaSlices;
271     friend class AllocaSlices::partition_iterator;
272
273     /// \brief The begining and ending offsets of the alloca for this partition.
274     uint64_t BeginOffset, EndOffset;
275
276     /// \brief The start end end iterators of this partition.
277     iterator SI, SJ;
278
279     /// \brief A collection of split slice tails overlapping the partition.
280     SmallVector<Slice *, 4> SplitTails;
281
282     /// \brief Raw constructor builds an empty partition starting and ending at
283     /// the given iterator.
284     Partition(iterator SI) : SI(SI), SJ(SI) {}
285
286   public:
287     /// \brief The start offset of this partition.
288     ///
289     /// All of the contained slices start at or after this offset.
290     uint64_t beginOffset() const { return BeginOffset; }
291
292     /// \brief The end offset of this partition.
293     ///
294     /// All of the contained slices end at or before this offset.
295     uint64_t endOffset() const { return EndOffset; }
296
297     /// \brief The size of the partition.
298     ///
299     /// Note that this can never be zero.
300     uint64_t size() const {
301       assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
302       return EndOffset - BeginOffset;
303     }
304
305     /// \brief Test whether this partition contains no slices, and merely spans
306     /// a region occupied by split slices.
307     bool empty() const { return SI == SJ; }
308
309     /// \name Iterate slices that start within the partition.
310     /// These may be splittable or unsplittable. They have a begin offset >= the
311     /// partition begin offset.
312     /// @{
313     // FIXME: We should probably define a "concat_iterator" helper and use that
314     // to stitch together pointee_iterators over the split tails and the
315     // contiguous iterators of the partition. That would give a much nicer
316     // interface here. We could then additionally expose filtered iterators for
317     // split, unsplit, and unsplittable splices based on the usage patterns.
318     iterator begin() const { return SI; }
319     iterator end() const { return SJ; }
320     /// @}
321
322     /// \brief Get the sequence of split slice tails.
323     ///
324     /// These tails are of slices which start before this partition but are
325     /// split and overlap into the partition. We accumulate these while forming
326     /// partitions.
327     ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
328   };
329
330   /// \brief An iterator over partitions of the alloca's slices.
331   ///
332   /// This iterator implements the core algorithm for partitioning the alloca's
333   /// slices. It is a forward iterator as we don't support backtracking for
334   /// efficiency reasons, and re-use a single storage area to maintain the
335   /// current set of split slices.
336   ///
337   /// It is templated on the slice iterator type to use so that it can operate
338   /// with either const or non-const slice iterators.
339   class partition_iterator
340       : public iterator_facade_base<partition_iterator,
341                                     std::forward_iterator_tag, Partition> {
342     friend class AllocaSlices;
343
344     /// \brief Most of the state for walking the partitions is held in a class
345     /// with a nice interface for examining them.
346     Partition P;
347
348     /// \brief We need to keep the end of the slices to know when to stop.
349     AllocaSlices::iterator SE;
350
351     /// \brief We also need to keep track of the maximum split end offset seen.
352     /// FIXME: Do we really?
353     uint64_t MaxSplitSliceEndOffset;
354
355     /// \brief Sets the partition to be empty at given iterator, and sets the
356     /// end iterator.
357     partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
358         : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
359       // If not already at the end, advance our state to form the initial
360       // partition.
361       if (SI != SE)
362         advance();
363     }
364
365     /// \brief Advance the iterator to the next partition.
366     ///
367     /// Requires that the iterator not be at the end of the slices.
368     void advance() {
369       assert((P.SI != SE || !P.SplitTails.empty()) &&
370              "Cannot advance past the end of the slices!");
371
372       // Clear out any split uses which have ended.
373       if (!P.SplitTails.empty()) {
374         if (P.EndOffset >= MaxSplitSliceEndOffset) {
375           // If we've finished all splits, this is easy.
376           P.SplitTails.clear();
377           MaxSplitSliceEndOffset = 0;
378         } else {
379           // Remove the uses which have ended in the prior partition. This
380           // cannot change the max split slice end because we just checked that
381           // the prior partition ended prior to that max.
382           P.SplitTails.erase(
383               std::remove_if(
384                   P.SplitTails.begin(), P.SplitTails.end(),
385                   [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
386               P.SplitTails.end());
387           assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
388                              [&](Slice *S) {
389                                return S->endOffset() == MaxSplitSliceEndOffset;
390                              }) &&
391                  "Could not find the current max split slice offset!");
392           assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
393                              [&](Slice *S) {
394                                return S->endOffset() <= MaxSplitSliceEndOffset;
395                              }) &&
396                  "Max split slice end offset is not actually the max!");
397         }
398       }
399
400       // If P.SI is already at the end, then we've cleared the split tail and
401       // now have an end iterator.
402       if (P.SI == SE) {
403         assert(P.SplitTails.empty() && "Failed to clear the split slices!");
404         return;
405       }
406
407       // If we had a non-empty partition previously, set up the state for
408       // subsequent partitions.
409       if (P.SI != P.SJ) {
410         // Accumulate all the splittable slices which started in the old
411         // partition into the split list.
412         for (Slice &S : P)
413           if (S.isSplittable() && S.endOffset() > P.EndOffset) {
414             P.SplitTails.push_back(&S);
415             MaxSplitSliceEndOffset =
416                 std::max(S.endOffset(), MaxSplitSliceEndOffset);
417           }
418
419         // Start from the end of the previous partition.
420         P.SI = P.SJ;
421
422         // If P.SI is now at the end, we at most have a tail of split slices.
423         if (P.SI == SE) {
424           P.BeginOffset = P.EndOffset;
425           P.EndOffset = MaxSplitSliceEndOffset;
426           return;
427         }
428
429         // If the we have split slices and the next slice is after a gap and is
430         // not splittable immediately form an empty partition for the split
431         // slices up until the next slice begins.
432         if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
433             !P.SI->isSplittable()) {
434           P.BeginOffset = P.EndOffset;
435           P.EndOffset = P.SI->beginOffset();
436           return;
437         }
438       }
439
440       // OK, we need to consume new slices. Set the end offset based on the
441       // current slice, and step SJ past it. The beginning offset of the
442       // parttion is the beginning offset of the next slice unless we have
443       // pre-existing split slices that are continuing, in which case we begin
444       // at the prior end offset.
445       P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
446       P.EndOffset = P.SI->endOffset();
447       ++P.SJ;
448
449       // There are two strategies to form a partition based on whether the
450       // partition starts with an unsplittable slice or a splittable slice.
451       if (!P.SI->isSplittable()) {
452         // When we're forming an unsplittable region, it must always start at
453         // the first slice and will extend through its end.
454         assert(P.BeginOffset == P.SI->beginOffset());
455
456         // Form a partition including all of the overlapping slices with this
457         // unsplittable slice.
458         while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
459           if (!P.SJ->isSplittable())
460             P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
461           ++P.SJ;
462         }
463
464         // We have a partition across a set of overlapping unsplittable
465         // partitions.
466         return;
467       }
468
469       // If we're starting with a splittable slice, then we need to form
470       // a synthetic partition spanning it and any other overlapping splittable
471       // splices.
472       assert(P.SI->isSplittable() && "Forming a splittable partition!");
473
474       // Collect all of the overlapping splittable slices.
475       while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
476              P.SJ->isSplittable()) {
477         P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
478         ++P.SJ;
479       }
480
481       // Back upiP.EndOffset if we ended the span early when encountering an
482       // unsplittable slice. This synthesizes the early end offset of
483       // a partition spanning only splittable slices.
484       if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
485         assert(!P.SJ->isSplittable());
486         P.EndOffset = P.SJ->beginOffset();
487       }
488     }
489
490   public:
491     bool operator==(const partition_iterator &RHS) const {
492       assert(SE == RHS.SE &&
493              "End iterators don't match between compared partition iterators!");
494
495       // The observed positions of partitions is marked by the P.SI iterator and
496       // the emptyness of the split slices. The latter is only relevant when
497       // P.SI == SE, as the end iterator will additionally have an empty split
498       // slices list, but the prior may have the same P.SI and a tail of split
499       // slices.
500       if (P.SI == RHS.P.SI &&
501           P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
502         assert(P.SJ == RHS.P.SJ &&
503                "Same set of slices formed two different sized partitions!");
504         assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
505                "Same slice position with differently sized non-empty split "
506                "slice tails!");
507         return true;
508       }
509       return false;
510     }
511
512     partition_iterator &operator++() {
513       advance();
514       return *this;
515     }
516
517     Partition &operator*() { return P; }
518   };
519
520   /// \brief A forward range over the partitions of the alloca's slices.
521   ///
522   /// This accesses an iterator range over the partitions of the alloca's
523   /// slices. It computes these partitions on the fly based on the overlapping
524   /// offsets of the slices and the ability to split them. It will visit "empty"
525   /// partitions to cover regions of the alloca only accessed via split
526   /// slices.
527   iterator_range<partition_iterator> partitions() {
528     return make_range(partition_iterator(begin(), end()),
529                       partition_iterator(end(), end()));
530   }
531
532   /// \brief Access the dead users for this alloca.
533   ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
534
535   /// \brief Access the dead operands referring to this alloca.
536   ///
537   /// These are operands which have cannot actually be used to refer to the
538   /// alloca as they are outside its range and the user doesn't correct for
539   /// that. These mostly consist of PHI node inputs and the like which we just
540   /// need to replace with undef.
541   ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
542
543 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
544   void print(raw_ostream &OS, const_iterator I, StringRef Indent = "  ") const;
545   void printSlice(raw_ostream &OS, const_iterator I,
546                   StringRef Indent = "  ") const;
547   void printUse(raw_ostream &OS, const_iterator I,
548                 StringRef Indent = "  ") const;
549   void print(raw_ostream &OS) const;
550   void dump(const_iterator I) const;
551   void dump() const;
552 #endif
553
554 private:
555   template <typename DerivedT, typename RetT = void> class BuilderBase;
556   class SliceBuilder;
557   friend class AllocaSlices::SliceBuilder;
558
559 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
560   /// \brief Handle to alloca instruction to simplify method interfaces.
561   AllocaInst &AI;
562 #endif
563
564   /// \brief The instruction responsible for this alloca not having a known set
565   /// of slices.
566   ///
567   /// When an instruction (potentially) escapes the pointer to the alloca, we
568   /// store a pointer to that here and abort trying to form slices of the
569   /// alloca. This will be null if the alloca slices are analyzed successfully.
570   Instruction *PointerEscapingInstr;
571
572   /// \brief The slices of the alloca.
573   ///
574   /// We store a vector of the slices formed by uses of the alloca here. This
575   /// vector is sorted by increasing begin offset, and then the unsplittable
576   /// slices before the splittable ones. See the Slice inner class for more
577   /// details.
578   SmallVector<Slice, 8> Slices;
579
580   /// \brief Instructions which will become dead if we rewrite the alloca.
581   ///
582   /// Note that these are not separated by slice. This is because we expect an
583   /// alloca to be completely rewritten or not rewritten at all. If rewritten,
584   /// all these instructions can simply be removed and replaced with undef as
585   /// they come from outside of the allocated space.
586   SmallVector<Instruction *, 8> DeadUsers;
587
588   /// \brief Operands which will become dead if we rewrite the alloca.
589   ///
590   /// These are operands that in their particular use can be replaced with
591   /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
592   /// to PHI nodes and the like. They aren't entirely dead (there might be
593   /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
594   /// want to swap this particular input for undef to simplify the use lists of
595   /// the alloca.
596   SmallVector<Use *, 8> DeadOperands;
597 };
598 }
599
600 static Value *foldSelectInst(SelectInst &SI) {
601   // If the condition being selected on is a constant or the same value is
602   // being selected between, fold the select. Yes this does (rarely) happen
603   // early on.
604   if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
605     return SI.getOperand(1 + CI->isZero());
606   if (SI.getOperand(1) == SI.getOperand(2))
607     return SI.getOperand(1);
608
609   return nullptr;
610 }
611
612 /// \brief A helper that folds a PHI node or a select.
613 static Value *foldPHINodeOrSelectInst(Instruction &I) {
614   if (PHINode *PN = dyn_cast<PHINode>(&I)) {
615     // If PN merges together the same value, return that value.
616     return PN->hasConstantValue();
617   }
618   return foldSelectInst(cast<SelectInst>(I));
619 }
620
621 /// \brief Builder for the alloca slices.
622 ///
623 /// This class builds a set of alloca slices by recursively visiting the uses
624 /// of an alloca and making a slice for each load and store at each offset.
625 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
626   friend class PtrUseVisitor<SliceBuilder>;
627   friend class InstVisitor<SliceBuilder>;
628   typedef PtrUseVisitor<SliceBuilder> Base;
629
630   const uint64_t AllocSize;
631   AllocaSlices &AS;
632
633   SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
634   SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
635
636   /// \brief Set to de-duplicate dead instructions found in the use walk.
637   SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
638
639 public:
640   SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
641       : PtrUseVisitor<SliceBuilder>(DL),
642         AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
643
644 private:
645   void markAsDead(Instruction &I) {
646     if (VisitedDeadInsts.insert(&I).second)
647       AS.DeadUsers.push_back(&I);
648   }
649
650   void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
651                  bool IsSplittable = false) {
652     // Completely skip uses which have a zero size or start either before or
653     // past the end of the allocation.
654     if (Size == 0 || Offset.uge(AllocSize)) {
655       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
656                    << " which has zero size or starts outside of the "
657                    << AllocSize << " byte alloca:\n"
658                    << "    alloca: " << AS.AI << "\n"
659                    << "       use: " << I << "\n");
660       return markAsDead(I);
661     }
662
663     uint64_t BeginOffset = Offset.getZExtValue();
664     uint64_t EndOffset = BeginOffset + Size;
665
666     // Clamp the end offset to the end of the allocation. Note that this is
667     // formulated to handle even the case where "BeginOffset + Size" overflows.
668     // This may appear superficially to be something we could ignore entirely,
669     // but that is not so! There may be widened loads or PHI-node uses where
670     // some instructions are dead but not others. We can't completely ignore
671     // them, and so have to record at least the information here.
672     assert(AllocSize >= BeginOffset); // Established above.
673     if (Size > AllocSize - BeginOffset) {
674       DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
675                    << " to remain within the " << AllocSize << " byte alloca:\n"
676                    << "    alloca: " << AS.AI << "\n"
677                    << "       use: " << I << "\n");
678       EndOffset = AllocSize;
679     }
680
681     AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
682   }
683
684   void visitBitCastInst(BitCastInst &BC) {
685     if (BC.use_empty())
686       return markAsDead(BC);
687
688     return Base::visitBitCastInst(BC);
689   }
690
691   void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
692     if (GEPI.use_empty())
693       return markAsDead(GEPI);
694
695     if (SROAStrictInbounds && GEPI.isInBounds()) {
696       // FIXME: This is a manually un-factored variant of the basic code inside
697       // of GEPs with checking of the inbounds invariant specified in the
698       // langref in a very strict sense. If we ever want to enable
699       // SROAStrictInbounds, this code should be factored cleanly into
700       // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
701       // by writing out the code here where we have tho underlying allocation
702       // size readily available.
703       APInt GEPOffset = Offset;
704       for (gep_type_iterator GTI = gep_type_begin(GEPI),
705                              GTE = gep_type_end(GEPI);
706            GTI != GTE; ++GTI) {
707         ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
708         if (!OpC)
709           break;
710
711         // Handle a struct index, which adds its field offset to the pointer.
712         if (StructType *STy = dyn_cast<StructType>(*GTI)) {
713           unsigned ElementIdx = OpC->getZExtValue();
714           const StructLayout *SL = DL.getStructLayout(STy);
715           GEPOffset +=
716               APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
717         } else {
718           // For array or vector indices, scale the index by the size of the
719           // type.
720           APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
721           GEPOffset += Index * APInt(Offset.getBitWidth(),
722                                      DL.getTypeAllocSize(GTI.getIndexedType()));
723         }
724
725         // If this index has computed an intermediate pointer which is not
726         // inbounds, then the result of the GEP is a poison value and we can
727         // delete it and all uses.
728         if (GEPOffset.ugt(AllocSize))
729           return markAsDead(GEPI);
730       }
731     }
732
733     return Base::visitGetElementPtrInst(GEPI);
734   }
735
736   void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
737                          uint64_t Size, bool IsVolatile) {
738     // We allow splitting of non-volatile loads and stores where the type is an
739     // integer type. These may be used to implement 'memcpy' or other "transfer
740     // of bits" patterns.
741     bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
742
743     insertUse(I, Offset, Size, IsSplittable);
744   }
745
746   void visitLoadInst(LoadInst &LI) {
747     assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
748            "All simple FCA loads should have been pre-split");
749
750     if (!IsOffsetKnown)
751       return PI.setAborted(&LI);
752
753     uint64_t Size = DL.getTypeStoreSize(LI.getType());
754     return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
755   }
756
757   void visitStoreInst(StoreInst &SI) {
758     Value *ValOp = SI.getValueOperand();
759     if (ValOp == *U)
760       return PI.setEscapedAndAborted(&SI);
761     if (!IsOffsetKnown)
762       return PI.setAborted(&SI);
763
764     uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
765
766     // If this memory access can be shown to *statically* extend outside the
767     // bounds of of the allocation, it's behavior is undefined, so simply
768     // ignore it. Note that this is more strict than the generic clamping
769     // behavior of insertUse. We also try to handle cases which might run the
770     // risk of overflow.
771     // FIXME: We should instead consider the pointer to have escaped if this
772     // function is being instrumented for addressing bugs or race conditions.
773     if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
774       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
775                    << " which extends past the end of the " << AllocSize
776                    << " byte alloca:\n"
777                    << "    alloca: " << AS.AI << "\n"
778                    << "       use: " << SI << "\n");
779       return markAsDead(SI);
780     }
781
782     assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
783            "All simple FCA stores should have been pre-split");
784     handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
785   }
786
787   void visitMemSetInst(MemSetInst &II) {
788     assert(II.getRawDest() == *U && "Pointer use is not the destination?");
789     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
790     if ((Length && Length->getValue() == 0) ||
791         (IsOffsetKnown && Offset.uge(AllocSize)))
792       // Zero-length mem transfer intrinsics can be ignored entirely.
793       return markAsDead(II);
794
795     if (!IsOffsetKnown)
796       return PI.setAborted(&II);
797
798     insertUse(II, Offset, Length ? Length->getLimitedValue()
799                                  : AllocSize - Offset.getLimitedValue(),
800               (bool)Length);
801   }
802
803   void visitMemTransferInst(MemTransferInst &II) {
804     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
805     if (Length && Length->getValue() == 0)
806       // Zero-length mem transfer intrinsics can be ignored entirely.
807       return markAsDead(II);
808
809     // Because we can visit these intrinsics twice, also check to see if the
810     // first time marked this instruction as dead. If so, skip it.
811     if (VisitedDeadInsts.count(&II))
812       return;
813
814     if (!IsOffsetKnown)
815       return PI.setAborted(&II);
816
817     // This side of the transfer is completely out-of-bounds, and so we can
818     // nuke the entire transfer. However, we also need to nuke the other side
819     // if already added to our partitions.
820     // FIXME: Yet another place we really should bypass this when
821     // instrumenting for ASan.
822     if (Offset.uge(AllocSize)) {
823       SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
824           MemTransferSliceMap.find(&II);
825       if (MTPI != MemTransferSliceMap.end())
826         AS.Slices[MTPI->second].kill();
827       return markAsDead(II);
828     }
829
830     uint64_t RawOffset = Offset.getLimitedValue();
831     uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
832
833     // Check for the special case where the same exact value is used for both
834     // source and dest.
835     if (*U == II.getRawDest() && *U == II.getRawSource()) {
836       // For non-volatile transfers this is a no-op.
837       if (!II.isVolatile())
838         return markAsDead(II);
839
840       return insertUse(II, Offset, Size, /*IsSplittable=*/false);
841     }
842
843     // If we have seen both source and destination for a mem transfer, then
844     // they both point to the same alloca.
845     bool Inserted;
846     SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
847     std::tie(MTPI, Inserted) =
848         MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
849     unsigned PrevIdx = MTPI->second;
850     if (!Inserted) {
851       Slice &PrevP = AS.Slices[PrevIdx];
852
853       // Check if the begin offsets match and this is a non-volatile transfer.
854       // In that case, we can completely elide the transfer.
855       if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
856         PrevP.kill();
857         return markAsDead(II);
858       }
859
860       // Otherwise we have an offset transfer within the same alloca. We can't
861       // split those.
862       PrevP.makeUnsplittable();
863     }
864
865     // Insert the use now that we've fixed up the splittable nature.
866     insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
867
868     // Check that we ended up with a valid index in the map.
869     assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
870            "Map index doesn't point back to a slice with this user.");
871   }
872
873   // Disable SRoA for any intrinsics except for lifetime invariants.
874   // FIXME: What about debug intrinsics? This matches old behavior, but
875   // doesn't make sense.
876   void visitIntrinsicInst(IntrinsicInst &II) {
877     if (!IsOffsetKnown)
878       return PI.setAborted(&II);
879
880     if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
881         II.getIntrinsicID() == Intrinsic::lifetime_end) {
882       ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
883       uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
884                                Length->getLimitedValue());
885       insertUse(II, Offset, Size, true);
886       return;
887     }
888
889     Base::visitIntrinsicInst(II);
890   }
891
892   Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
893     // We consider any PHI or select that results in a direct load or store of
894     // the same offset to be a viable use for slicing purposes. These uses
895     // are considered unsplittable and the size is the maximum loaded or stored
896     // size.
897     SmallPtrSet<Instruction *, 4> Visited;
898     SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
899     Visited.insert(Root);
900     Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
901     // If there are no loads or stores, the access is dead. We mark that as
902     // a size zero access.
903     Size = 0;
904     do {
905       Instruction *I, *UsedI;
906       std::tie(UsedI, I) = Uses.pop_back_val();
907
908       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
909         Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
910         continue;
911       }
912       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
913         Value *Op = SI->getOperand(0);
914         if (Op == UsedI)
915           return SI;
916         Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
917         continue;
918       }
919
920       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
921         if (!GEP->hasAllZeroIndices())
922           return GEP;
923       } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
924                  !isa<SelectInst>(I)) {
925         return I;
926       }
927
928       for (User *U : I->users())
929         if (Visited.insert(cast<Instruction>(U)).second)
930           Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
931     } while (!Uses.empty());
932
933     return nullptr;
934   }
935
936   void visitPHINodeOrSelectInst(Instruction &I) {
937     assert(isa<PHINode>(I) || isa<SelectInst>(I));
938     if (I.use_empty())
939       return markAsDead(I);
940
941     // TODO: We could use SimplifyInstruction here to fold PHINodes and
942     // SelectInsts. However, doing so requires to change the current
943     // dead-operand-tracking mechanism. For instance, suppose neither loading
944     // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
945     // trap either.  However, if we simply replace %U with undef using the
946     // current dead-operand-tracking mechanism, "load (select undef, undef,
947     // %other)" may trap because the select may return the first operand
948     // "undef".
949     if (Value *Result = foldPHINodeOrSelectInst(I)) {
950       if (Result == *U)
951         // If the result of the constant fold will be the pointer, recurse
952         // through the PHI/select as if we had RAUW'ed it.
953         enqueueUsers(I);
954       else
955         // Otherwise the operand to the PHI/select is dead, and we can replace
956         // it with undef.
957         AS.DeadOperands.push_back(U);
958
959       return;
960     }
961
962     if (!IsOffsetKnown)
963       return PI.setAborted(&I);
964
965     // See if we already have computed info on this node.
966     uint64_t &Size = PHIOrSelectSizes[&I];
967     if (!Size) {
968       // This is a new PHI/Select, check for an unsafe use of it.
969       if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
970         return PI.setAborted(UnsafeI);
971     }
972
973     // For PHI and select operands outside the alloca, we can't nuke the entire
974     // phi or select -- the other side might still be relevant, so we special
975     // case them here and use a separate structure to track the operands
976     // themselves which should be replaced with undef.
977     // FIXME: This should instead be escaped in the event we're instrumenting
978     // for address sanitization.
979     if (Offset.uge(AllocSize)) {
980       AS.DeadOperands.push_back(U);
981       return;
982     }
983
984     insertUse(I, Offset, Size);
985   }
986
987   void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
988
989   void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
990
991   /// \brief Disable SROA entirely if there are unhandled users of the alloca.
992   void visitInstruction(Instruction &I) { PI.setAborted(&I); }
993 };
994
995 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
996     :
997 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
998       AI(AI),
999 #endif
1000       PointerEscapingInstr(nullptr) {
1001   SliceBuilder PB(DL, AI, *this);
1002   SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1003   if (PtrI.isEscaped() || PtrI.isAborted()) {
1004     // FIXME: We should sink the escape vs. abort info into the caller nicely,
1005     // possibly by just storing the PtrInfo in the AllocaSlices.
1006     PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1007                                                   : PtrI.getAbortingInst();
1008     assert(PointerEscapingInstr && "Did not track a bad instruction");
1009     return;
1010   }
1011
1012   Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
1013                               [](const Slice &S) {
1014                                 return S.isDead();
1015                               }),
1016                Slices.end());
1017
1018 #if __cplusplus >= 201103L && !defined(NDEBUG)
1019   if (SROARandomShuffleSlices) {
1020     std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
1021     std::shuffle(Slices.begin(), Slices.end(), MT);
1022   }
1023 #endif
1024
1025   // Sort the uses. This arranges for the offsets to be in ascending order,
1026   // and the sizes to be in descending order.
1027   std::sort(Slices.begin(), Slices.end());
1028 }
1029
1030 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1031
1032 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1033                          StringRef Indent) const {
1034   printSlice(OS, I, Indent);
1035   OS << "\n";
1036   printUse(OS, I, Indent);
1037 }
1038
1039 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1040                               StringRef Indent) const {
1041   OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
1042      << " slice #" << (I - begin())
1043      << (I->isSplittable() ? " (splittable)" : "");
1044 }
1045
1046 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1047                             StringRef Indent) const {
1048   OS << Indent << "  used by: " << *I->getUse()->getUser() << "\n";
1049 }
1050
1051 void AllocaSlices::print(raw_ostream &OS) const {
1052   if (PointerEscapingInstr) {
1053     OS << "Can't analyze slices for alloca: " << AI << "\n"
1054        << "  A pointer to this alloca escaped by:\n"
1055        << "  " << *PointerEscapingInstr << "\n";
1056     return;
1057   }
1058
1059   OS << "Slices of alloca: " << AI << "\n";
1060   for (const_iterator I = begin(), E = end(); I != E; ++I)
1061     print(OS, I);
1062 }
1063
1064 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1065   print(dbgs(), I);
1066 }
1067 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
1068
1069 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1070
1071 namespace {
1072 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1073 ///
1074 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1075 /// the loads and stores of an alloca instruction, as well as updating its
1076 /// debug information. This is used when a domtree is unavailable and thus
1077 /// mem2reg in its full form can't be used to handle promotion of allocas to
1078 /// scalar values.
1079 class AllocaPromoter : public LoadAndStorePromoter {
1080   AllocaInst &AI;
1081   DIBuilder &DIB;
1082
1083   SmallVector<DbgDeclareInst *, 4> DDIs;
1084   SmallVector<DbgValueInst *, 4> DVIs;
1085
1086 public:
1087   AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
1088                  AllocaInst &AI, DIBuilder &DIB)
1089       : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1090
1091   void run(const SmallVectorImpl<Instruction *> &Insts) {
1092     // Retain the debug information attached to the alloca for use when
1093     // rewriting loads and stores.
1094     if (auto *L = LocalAsMetadata::getIfExists(&AI)) {
1095       if (auto *DebugNode = MetadataAsValue::getIfExists(AI.getContext(), L)) {
1096         for (User *U : DebugNode->users())
1097           if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1098             DDIs.push_back(DDI);
1099           else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1100             DVIs.push_back(DVI);
1101       }
1102     }
1103
1104     LoadAndStorePromoter::run(Insts);
1105
1106     // While we have the debug information, clear it off of the alloca. The
1107     // caller takes care of deleting the alloca.
1108     while (!DDIs.empty())
1109       DDIs.pop_back_val()->eraseFromParent();
1110     while (!DVIs.empty())
1111       DVIs.pop_back_val()->eraseFromParent();
1112   }
1113
1114   bool
1115   isInstInList(Instruction *I,
1116                const SmallVectorImpl<Instruction *> &Insts) const override {
1117     Value *Ptr;
1118     if (LoadInst *LI = dyn_cast<LoadInst>(I))
1119       Ptr = LI->getOperand(0);
1120     else
1121       Ptr = cast<StoreInst>(I)->getPointerOperand();
1122
1123     // Only used to detect cycles, which will be rare and quickly found as
1124     // we're walking up a chain of defs rather than down through uses.
1125     SmallPtrSet<Value *, 4> Visited;
1126
1127     do {
1128       if (Ptr == &AI)
1129         return true;
1130
1131       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
1132         Ptr = BCI->getOperand(0);
1133       else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
1134         Ptr = GEPI->getPointerOperand();
1135       else
1136         return false;
1137
1138     } while (Visited.insert(Ptr).second);
1139
1140     return false;
1141   }
1142
1143   void updateDebugInfo(Instruction *Inst) const override {
1144     for (DbgDeclareInst *DDI : DDIs)
1145       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1146         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1147       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1148         ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1149     for (DbgValueInst *DVI : DVIs) {
1150       Value *Arg = nullptr;
1151       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1152         // If an argument is zero extended then use argument directly. The ZExt
1153         // may be zapped by an optimization pass in future.
1154         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1155           Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1156         else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1157           Arg = dyn_cast<Argument>(SExt->getOperand(0));
1158         if (!Arg)
1159           Arg = SI->getValueOperand();
1160       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1161         Arg = LI->getPointerOperand();
1162       } else {
1163         continue;
1164       }
1165       Instruction *DbgVal =
1166           DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1167                                       DIExpression(DVI->getExpression()), Inst);
1168       DbgVal->setDebugLoc(DVI->getDebugLoc());
1169     }
1170   }
1171 };
1172 } // end anon namespace
1173
1174 namespace {
1175 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1176 ///
1177 /// This pass takes allocations which can be completely analyzed (that is, they
1178 /// don't escape) and tries to turn them into scalar SSA values. There are
1179 /// a few steps to this process.
1180 ///
1181 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1182 ///    are used to try to split them into smaller allocations, ideally of
1183 ///    a single scalar data type. It will split up memcpy and memset accesses
1184 ///    as necessary and try to isolate individual scalar accesses.
1185 /// 2) It will transform accesses into forms which are suitable for SSA value
1186 ///    promotion. This can be replacing a memset with a scalar store of an
1187 ///    integer value, or it can involve speculating operations on a PHI or
1188 ///    select to be a PHI or select of the results.
1189 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1190 ///    onto insert and extract operations on a vector value, and convert them to
1191 ///    this form. By doing so, it will enable promotion of vector aggregates to
1192 ///    SSA vector values.
1193 class SROA : public FunctionPass {
1194   const bool RequiresDomTree;
1195
1196   LLVMContext *C;
1197   const DataLayout *DL;
1198   DominatorTree *DT;
1199   AssumptionCache *AC;
1200
1201   /// \brief Worklist of alloca instructions to simplify.
1202   ///
1203   /// Each alloca in the function is added to this. Each new alloca formed gets
1204   /// added to it as well to recursively simplify unless that alloca can be
1205   /// directly promoted. Finally, each time we rewrite a use of an alloca other
1206   /// the one being actively rewritten, we add it back onto the list if not
1207   /// already present to ensure it is re-visited.
1208   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> Worklist;
1209
1210   /// \brief A collection of instructions to delete.
1211   /// We try to batch deletions to simplify code and make things a bit more
1212   /// efficient.
1213   SetVector<Instruction *, SmallVector<Instruction *, 8>> DeadInsts;
1214
1215   /// \brief Post-promotion worklist.
1216   ///
1217   /// Sometimes we discover an alloca which has a high probability of becoming
1218   /// viable for SROA after a round of promotion takes place. In those cases,
1219   /// the alloca is enqueued here for re-processing.
1220   ///
1221   /// Note that we have to be very careful to clear allocas out of this list in
1222   /// the event they are deleted.
1223   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> PostPromotionWorklist;
1224
1225   /// \brief A collection of alloca instructions we can directly promote.
1226   std::vector<AllocaInst *> PromotableAllocas;
1227
1228   /// \brief A worklist of PHIs to speculate prior to promoting allocas.
1229   ///
1230   /// All of these PHIs have been checked for the safety of speculation and by
1231   /// being speculated will allow promoting allocas currently in the promotable
1232   /// queue.
1233   SetVector<PHINode *, SmallVector<PHINode *, 2>> SpeculatablePHIs;
1234
1235   /// \brief A worklist of select instructions to speculate prior to promoting
1236   /// allocas.
1237   ///
1238   /// All of these select instructions have been checked for the safety of
1239   /// speculation and by being speculated will allow promoting allocas
1240   /// currently in the promotable queue.
1241   SetVector<SelectInst *, SmallVector<SelectInst *, 2>> SpeculatableSelects;
1242
1243   /// Debug intrinsics do not show up as regular uses in the
1244   /// IR. This side-table holds the missing use edges.
1245   DenseMap<AllocaInst *, DbgDeclareInst *> DbgDeclares;
1246
1247 public:
1248   SROA(bool RequiresDomTree = true)
1249       : FunctionPass(ID), RequiresDomTree(RequiresDomTree), C(nullptr),
1250         DL(nullptr), DT(nullptr) {
1251     initializeSROAPass(*PassRegistry::getPassRegistry());
1252   }
1253   bool runOnFunction(Function &F) override;
1254   void getAnalysisUsage(AnalysisUsage &AU) const override;
1255
1256   const char *getPassName() const override { return "SROA"; }
1257   static char ID;
1258
1259 private:
1260   friend class PHIOrSelectSpeculator;
1261   friend class AllocaSliceRewriter;
1262
1263   bool presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS);
1264   AllocaInst *rewritePartition(AllocaInst &AI, AllocaSlices &AS,
1265                                AllocaSlices::Partition &P);
1266   bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
1267   bool runOnAlloca(AllocaInst &AI);
1268   void clobberUse(Use &U);
1269   void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
1270   bool promoteAllocas(Function &F);
1271 };
1272 }
1273
1274 char SROA::ID = 0;
1275
1276 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1277   return new SROA(RequiresDomTree);
1278 }
1279
1280 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1281                       false)
1282 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1283 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1284 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1285                     false)
1286
1287 /// Walk the range of a partitioning looking for a common type to cover this
1288 /// sequence of slices.
1289 static Type *findCommonType(AllocaSlices::const_iterator B,
1290                             AllocaSlices::const_iterator E,
1291                             uint64_t EndOffset) {
1292   Type *Ty = nullptr;
1293   bool TyIsCommon = true;
1294   IntegerType *ITy = nullptr;
1295
1296   // Note that we need to look at *every* alloca slice's Use to ensure we
1297   // always get consistent results regardless of the order of slices.
1298   for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1299     Use *U = I->getUse();
1300     if (isa<IntrinsicInst>(*U->getUser()))
1301       continue;
1302     if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1303       continue;
1304
1305     Type *UserTy = nullptr;
1306     if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1307       UserTy = LI->getType();
1308     } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1309       UserTy = SI->getValueOperand()->getType();
1310     }
1311
1312     if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1313       // If the type is larger than the partition, skip it. We only encounter
1314       // this for split integer operations where we want to use the type of the
1315       // entity causing the split. Also skip if the type is not a byte width
1316       // multiple.
1317       if (UserITy->getBitWidth() % 8 != 0 ||
1318           UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1319         continue;
1320
1321       // Track the largest bitwidth integer type used in this way in case there
1322       // is no common type.
1323       if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1324         ITy = UserITy;
1325     }
1326
1327     // To avoid depending on the order of slices, Ty and TyIsCommon must not
1328     // depend on types skipped above.
1329     if (!UserTy || (Ty && Ty != UserTy))
1330       TyIsCommon = false; // Give up on anything but an iN type.
1331     else
1332       Ty = UserTy;
1333   }
1334
1335   return TyIsCommon ? Ty : ITy;
1336 }
1337
1338 /// PHI instructions that use an alloca and are subsequently loaded can be
1339 /// rewritten to load both input pointers in the pred blocks and then PHI the
1340 /// results, allowing the load of the alloca to be promoted.
1341 /// From this:
1342 ///   %P2 = phi [i32* %Alloca, i32* %Other]
1343 ///   %V = load i32* %P2
1344 /// to:
1345 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1346 ///   ...
1347 ///   %V2 = load i32* %Other
1348 ///   ...
1349 ///   %V = phi [i32 %V1, i32 %V2]
1350 ///
1351 /// We can do this to a select if its only uses are loads and if the operands
1352 /// to the select can be loaded unconditionally.
1353 ///
1354 /// FIXME: This should be hoisted into a generic utility, likely in
1355 /// Transforms/Util/Local.h
1356 static bool isSafePHIToSpeculate(PHINode &PN, const DataLayout *DL = nullptr) {
1357   // For now, we can only do this promotion if the load is in the same block
1358   // as the PHI, and if there are no stores between the phi and load.
1359   // TODO: Allow recursive phi users.
1360   // TODO: Allow stores.
1361   BasicBlock *BB = PN.getParent();
1362   unsigned MaxAlign = 0;
1363   bool HaveLoad = false;
1364   for (User *U : PN.users()) {
1365     LoadInst *LI = dyn_cast<LoadInst>(U);
1366     if (!LI || !LI->isSimple())
1367       return false;
1368
1369     // For now we only allow loads in the same block as the PHI.  This is
1370     // a common case that happens when instcombine merges two loads through
1371     // a PHI.
1372     if (LI->getParent() != BB)
1373       return false;
1374
1375     // Ensure that there are no instructions between the PHI and the load that
1376     // could store.
1377     for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1378       if (BBI->mayWriteToMemory())
1379         return false;
1380
1381     MaxAlign = std::max(MaxAlign, LI->getAlignment());
1382     HaveLoad = true;
1383   }
1384
1385   if (!HaveLoad)
1386     return false;
1387
1388   // We can only transform this if it is safe to push the loads into the
1389   // predecessor blocks. The only thing to watch out for is that we can't put
1390   // a possibly trapping load in the predecessor if it is a critical edge.
1391   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1392     TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1393     Value *InVal = PN.getIncomingValue(Idx);
1394
1395     // If the value is produced by the terminator of the predecessor (an
1396     // invoke) or it has side-effects, there is no valid place to put a load
1397     // in the predecessor.
1398     if (TI == InVal || TI->mayHaveSideEffects())
1399       return false;
1400
1401     // If the predecessor has a single successor, then the edge isn't
1402     // critical.
1403     if (TI->getNumSuccessors() == 1)
1404       continue;
1405
1406     // If this pointer is always safe to load, or if we can prove that there
1407     // is already a load in the block, then we can move the load to the pred
1408     // block.
1409     if (InVal->isDereferenceablePointer(DL) ||
1410         isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
1411       continue;
1412
1413     return false;
1414   }
1415
1416   return true;
1417 }
1418
1419 static void speculatePHINodeLoads(PHINode &PN) {
1420   DEBUG(dbgs() << "    original: " << PN << "\n");
1421
1422   Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1423   IRBuilderTy PHIBuilder(&PN);
1424   PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1425                                         PN.getName() + ".sroa.speculated");
1426
1427   // Get the AA tags and alignment to use from one of the loads.  It doesn't
1428   // matter which one we get and if any differ.
1429   LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1430
1431   AAMDNodes AATags;
1432   SomeLoad->getAAMetadata(AATags);
1433   unsigned Align = SomeLoad->getAlignment();
1434
1435   // Rewrite all loads of the PN to use the new PHI.
1436   while (!PN.use_empty()) {
1437     LoadInst *LI = cast<LoadInst>(PN.user_back());
1438     LI->replaceAllUsesWith(NewPN);
1439     LI->eraseFromParent();
1440   }
1441
1442   // Inject loads into all of the pred blocks.
1443   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1444     BasicBlock *Pred = PN.getIncomingBlock(Idx);
1445     TerminatorInst *TI = Pred->getTerminator();
1446     Value *InVal = PN.getIncomingValue(Idx);
1447     IRBuilderTy PredBuilder(TI);
1448
1449     LoadInst *Load = PredBuilder.CreateLoad(
1450         InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1451     ++NumLoadsSpeculated;
1452     Load->setAlignment(Align);
1453     if (AATags)
1454       Load->setAAMetadata(AATags);
1455     NewPN->addIncoming(Load, Pred);
1456   }
1457
1458   DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
1459   PN.eraseFromParent();
1460 }
1461
1462 /// Select instructions that use an alloca and are subsequently loaded can be
1463 /// rewritten to load both input pointers and then select between the result,
1464 /// allowing the load of the alloca to be promoted.
1465 /// From this:
1466 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1467 ///   %V = load i32* %P2
1468 /// to:
1469 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1470 ///   %V2 = load i32* %Other
1471 ///   %V = select i1 %cond, i32 %V1, i32 %V2
1472 ///
1473 /// We can do this to a select if its only uses are loads and if the operand
1474 /// to the select can be loaded unconditionally.
1475 static bool isSafeSelectToSpeculate(SelectInst &SI,
1476                                     const DataLayout *DL = nullptr) {
1477   Value *TValue = SI.getTrueValue();
1478   Value *FValue = SI.getFalseValue();
1479   bool TDerefable = TValue->isDereferenceablePointer(DL);
1480   bool FDerefable = FValue->isDereferenceablePointer(DL);
1481
1482   for (User *U : SI.users()) {
1483     LoadInst *LI = dyn_cast<LoadInst>(U);
1484     if (!LI || !LI->isSimple())
1485       return false;
1486
1487     // Both operands to the select need to be dereferencable, either
1488     // absolutely (e.g. allocas) or at this point because we can see other
1489     // accesses to it.
1490     if (!TDerefable &&
1491         !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
1492       return false;
1493     if (!FDerefable &&
1494         !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
1495       return false;
1496   }
1497
1498   return true;
1499 }
1500
1501 static void speculateSelectInstLoads(SelectInst &SI) {
1502   DEBUG(dbgs() << "    original: " << SI << "\n");
1503
1504   IRBuilderTy IRB(&SI);
1505   Value *TV = SI.getTrueValue();
1506   Value *FV = SI.getFalseValue();
1507   // Replace the loads of the select with a select of two loads.
1508   while (!SI.use_empty()) {
1509     LoadInst *LI = cast<LoadInst>(SI.user_back());
1510     assert(LI->isSimple() && "We only speculate simple loads");
1511
1512     IRB.SetInsertPoint(LI);
1513     LoadInst *TL =
1514         IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1515     LoadInst *FL =
1516         IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1517     NumLoadsSpeculated += 2;
1518
1519     // Transfer alignment and AA info if present.
1520     TL->setAlignment(LI->getAlignment());
1521     FL->setAlignment(LI->getAlignment());
1522
1523     AAMDNodes Tags;
1524     LI->getAAMetadata(Tags);
1525     if (Tags) {
1526       TL->setAAMetadata(Tags);
1527       FL->setAAMetadata(Tags);
1528     }
1529
1530     Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1531                                 LI->getName() + ".sroa.speculated");
1532
1533     DEBUG(dbgs() << "          speculated to: " << *V << "\n");
1534     LI->replaceAllUsesWith(V);
1535     LI->eraseFromParent();
1536   }
1537   SI.eraseFromParent();
1538 }
1539
1540 /// \brief Build a GEP out of a base pointer and indices.
1541 ///
1542 /// This will return the BasePtr if that is valid, or build a new GEP
1543 /// instruction using the IRBuilder if GEP-ing is needed.
1544 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1545                        SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
1546   if (Indices.empty())
1547     return BasePtr;
1548
1549   // A single zero index is a no-op, so check for this and avoid building a GEP
1550   // in that case.
1551   if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1552     return BasePtr;
1553
1554   return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
1555 }
1556
1557 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1558 /// TargetTy without changing the offset of the pointer.
1559 ///
1560 /// This routine assumes we've already established a properly offset GEP with
1561 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1562 /// zero-indices down through type layers until we find one the same as
1563 /// TargetTy. If we can't find one with the same type, we at least try to use
1564 /// one with the same size. If none of that works, we just produce the GEP as
1565 /// indicated by Indices to have the correct offset.
1566 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1567                                     Value *BasePtr, Type *Ty, Type *TargetTy,
1568                                     SmallVectorImpl<Value *> &Indices,
1569                                     Twine NamePrefix) {
1570   if (Ty == TargetTy)
1571     return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1572
1573   // Pointer size to use for the indices.
1574   unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1575
1576   // See if we can descend into a struct and locate a field with the correct
1577   // type.
1578   unsigned NumLayers = 0;
1579   Type *ElementTy = Ty;
1580   do {
1581     if (ElementTy->isPointerTy())
1582       break;
1583
1584     if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1585       ElementTy = ArrayTy->getElementType();
1586       Indices.push_back(IRB.getIntN(PtrSize, 0));
1587     } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1588       ElementTy = VectorTy->getElementType();
1589       Indices.push_back(IRB.getInt32(0));
1590     } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1591       if (STy->element_begin() == STy->element_end())
1592         break; // Nothing left to descend into.
1593       ElementTy = *STy->element_begin();
1594       Indices.push_back(IRB.getInt32(0));
1595     } else {
1596       break;
1597     }
1598     ++NumLayers;
1599   } while (ElementTy != TargetTy);
1600   if (ElementTy != TargetTy)
1601     Indices.erase(Indices.end() - NumLayers, Indices.end());
1602
1603   return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1604 }
1605
1606 /// \brief Recursively compute indices for a natural GEP.
1607 ///
1608 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1609 /// element types adding appropriate indices for the GEP.
1610 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1611                                        Value *Ptr, Type *Ty, APInt &Offset,
1612                                        Type *TargetTy,
1613                                        SmallVectorImpl<Value *> &Indices,
1614                                        Twine NamePrefix) {
1615   if (Offset == 0)
1616     return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1617                                  NamePrefix);
1618
1619   // We can't recurse through pointer types.
1620   if (Ty->isPointerTy())
1621     return nullptr;
1622
1623   // We try to analyze GEPs over vectors here, but note that these GEPs are
1624   // extremely poorly defined currently. The long-term goal is to remove GEPing
1625   // over a vector from the IR completely.
1626   if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1627     unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1628     if (ElementSizeInBits % 8 != 0) {
1629       // GEPs over non-multiple of 8 size vector elements are invalid.
1630       return nullptr;
1631     }
1632     APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1633     APInt NumSkippedElements = Offset.sdiv(ElementSize);
1634     if (NumSkippedElements.ugt(VecTy->getNumElements()))
1635       return nullptr;
1636     Offset -= NumSkippedElements * ElementSize;
1637     Indices.push_back(IRB.getInt(NumSkippedElements));
1638     return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1639                                     Offset, TargetTy, Indices, NamePrefix);
1640   }
1641
1642   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1643     Type *ElementTy = ArrTy->getElementType();
1644     APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1645     APInt NumSkippedElements = Offset.sdiv(ElementSize);
1646     if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1647       return nullptr;
1648
1649     Offset -= NumSkippedElements * ElementSize;
1650     Indices.push_back(IRB.getInt(NumSkippedElements));
1651     return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1652                                     Indices, NamePrefix);
1653   }
1654
1655   StructType *STy = dyn_cast<StructType>(Ty);
1656   if (!STy)
1657     return nullptr;
1658
1659   const StructLayout *SL = DL.getStructLayout(STy);
1660   uint64_t StructOffset = Offset.getZExtValue();
1661   if (StructOffset >= SL->getSizeInBytes())
1662     return nullptr;
1663   unsigned Index = SL->getElementContainingOffset(StructOffset);
1664   Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1665   Type *ElementTy = STy->getElementType(Index);
1666   if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1667     return nullptr; // The offset points into alignment padding.
1668
1669   Indices.push_back(IRB.getInt32(Index));
1670   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1671                                   Indices, NamePrefix);
1672 }
1673
1674 /// \brief Get a natural GEP from a base pointer to a particular offset and
1675 /// resulting in a particular type.
1676 ///
1677 /// The goal is to produce a "natural" looking GEP that works with the existing
1678 /// composite types to arrive at the appropriate offset and element type for
1679 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1680 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1681 /// Indices, and setting Ty to the result subtype.
1682 ///
1683 /// If no natural GEP can be constructed, this function returns null.
1684 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1685                                       Value *Ptr, APInt Offset, Type *TargetTy,
1686                                       SmallVectorImpl<Value *> &Indices,
1687                                       Twine NamePrefix) {
1688   PointerType *Ty = cast<PointerType>(Ptr->getType());
1689
1690   // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1691   // an i8.
1692   if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
1693     return nullptr;
1694
1695   Type *ElementTy = Ty->getElementType();
1696   if (!ElementTy->isSized())
1697     return nullptr; // We can't GEP through an unsized element.
1698   APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1699   if (ElementSize == 0)
1700     return nullptr; // Zero-length arrays can't help us build a natural GEP.
1701   APInt NumSkippedElements = Offset.sdiv(ElementSize);
1702
1703   Offset -= NumSkippedElements * ElementSize;
1704   Indices.push_back(IRB.getInt(NumSkippedElements));
1705   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1706                                   Indices, NamePrefix);
1707 }
1708
1709 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1710 /// resulting pointer has PointerTy.
1711 ///
1712 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1713 /// and produces the pointer type desired. Where it cannot, it will try to use
1714 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1715 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1716 /// bitcast to the type.
1717 ///
1718 /// The strategy for finding the more natural GEPs is to peel off layers of the
1719 /// pointer, walking back through bit casts and GEPs, searching for a base
1720 /// pointer from which we can compute a natural GEP with the desired
1721 /// properties. The algorithm tries to fold as many constant indices into
1722 /// a single GEP as possible, thus making each GEP more independent of the
1723 /// surrounding code.
1724 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1725                              APInt Offset, Type *PointerTy, Twine NamePrefix) {
1726   // Even though we don't look through PHI nodes, we could be called on an
1727   // instruction in an unreachable block, which may be on a cycle.
1728   SmallPtrSet<Value *, 4> Visited;
1729   Visited.insert(Ptr);
1730   SmallVector<Value *, 4> Indices;
1731
1732   // We may end up computing an offset pointer that has the wrong type. If we
1733   // never are able to compute one directly that has the correct type, we'll
1734   // fall back to it, so keep it and the base it was computed from around here.
1735   Value *OffsetPtr = nullptr;
1736   Value *OffsetBasePtr;
1737
1738   // Remember any i8 pointer we come across to re-use if we need to do a raw
1739   // byte offset.
1740   Value *Int8Ptr = nullptr;
1741   APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1742
1743   Type *TargetTy = PointerTy->getPointerElementType();
1744
1745   do {
1746     // First fold any existing GEPs into the offset.
1747     while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1748       APInt GEPOffset(Offset.getBitWidth(), 0);
1749       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1750         break;
1751       Offset += GEPOffset;
1752       Ptr = GEP->getPointerOperand();
1753       if (!Visited.insert(Ptr).second)
1754         break;
1755     }
1756
1757     // See if we can perform a natural GEP here.
1758     Indices.clear();
1759     if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1760                                            Indices, NamePrefix)) {
1761       // If we have a new natural pointer at the offset, clear out any old
1762       // offset pointer we computed. Unless it is the base pointer or
1763       // a non-instruction, we built a GEP we don't need. Zap it.
1764       if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1765         if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1766           assert(I->use_empty() && "Built a GEP with uses some how!");
1767           I->eraseFromParent();
1768         }
1769       OffsetPtr = P;
1770       OffsetBasePtr = Ptr;
1771       // If we also found a pointer of the right type, we're done.
1772       if (P->getType() == PointerTy)
1773         return P;
1774     }
1775
1776     // Stash this pointer if we've found an i8*.
1777     if (Ptr->getType()->isIntegerTy(8)) {
1778       Int8Ptr = Ptr;
1779       Int8PtrOffset = Offset;
1780     }
1781
1782     // Peel off a layer of the pointer and update the offset appropriately.
1783     if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1784       Ptr = cast<Operator>(Ptr)->getOperand(0);
1785     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1786       if (GA->mayBeOverridden())
1787         break;
1788       Ptr = GA->getAliasee();
1789     } else {
1790       break;
1791     }
1792     assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1793   } while (Visited.insert(Ptr).second);
1794
1795   if (!OffsetPtr) {
1796     if (!Int8Ptr) {
1797       Int8Ptr = IRB.CreateBitCast(
1798           Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1799           NamePrefix + "sroa_raw_cast");
1800       Int8PtrOffset = Offset;
1801     }
1802
1803     OffsetPtr = Int8PtrOffset == 0
1804                     ? Int8Ptr
1805                     : IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1806                                             NamePrefix + "sroa_raw_idx");
1807   }
1808   Ptr = OffsetPtr;
1809
1810   // On the off chance we were targeting i8*, guard the bitcast here.
1811   if (Ptr->getType() != PointerTy)
1812     Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
1813
1814   return Ptr;
1815 }
1816
1817 /// \brief Compute the adjusted alignment for a load or store from an offset.
1818 static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1819                                      const DataLayout &DL) {
1820   unsigned Alignment;
1821   Type *Ty;
1822   if (auto *LI = dyn_cast<LoadInst>(I)) {
1823     Alignment = LI->getAlignment();
1824     Ty = LI->getType();
1825   } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1826     Alignment = SI->getAlignment();
1827     Ty = SI->getValueOperand()->getType();
1828   } else {
1829     llvm_unreachable("Only loads and stores are allowed!");
1830   }
1831
1832   if (!Alignment)
1833     Alignment = DL.getABITypeAlignment(Ty);
1834
1835   return MinAlign(Alignment, Offset);
1836 }
1837
1838 /// \brief Test whether we can convert a value from the old to the new type.
1839 ///
1840 /// This predicate should be used to guard calls to convertValue in order to
1841 /// ensure that we only try to convert viable values. The strategy is that we
1842 /// will peel off single element struct and array wrappings to get to an
1843 /// underlying value, and convert that value.
1844 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1845   if (OldTy == NewTy)
1846     return true;
1847   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1848     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1849       if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1850         return true;
1851   if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1852     return false;
1853   if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1854     return false;
1855
1856   // We can convert pointers to integers and vice-versa. Same for vectors
1857   // of pointers and integers.
1858   OldTy = OldTy->getScalarType();
1859   NewTy = NewTy->getScalarType();
1860   if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1861     if (NewTy->isPointerTy() && OldTy->isPointerTy())
1862       return true;
1863     if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1864       return true;
1865     return false;
1866   }
1867
1868   return true;
1869 }
1870
1871 /// \brief Generic routine to convert an SSA value to a value of a different
1872 /// type.
1873 ///
1874 /// This will try various different casting techniques, such as bitcasts,
1875 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1876 /// two types for viability with this routine.
1877 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1878                            Type *NewTy) {
1879   Type *OldTy = V->getType();
1880   assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1881
1882   if (OldTy == NewTy)
1883     return V;
1884
1885   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1886     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1887       if (NewITy->getBitWidth() > OldITy->getBitWidth())
1888         return IRB.CreateZExt(V, NewITy);
1889
1890   // See if we need inttoptr for this type pair. A cast involving both scalars
1891   // and vectors requires and additional bitcast.
1892   if (OldTy->getScalarType()->isIntegerTy() &&
1893       NewTy->getScalarType()->isPointerTy()) {
1894     // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1895     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1896       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1897                                 NewTy);
1898
1899     // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1900     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1901       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1902                                 NewTy);
1903
1904     return IRB.CreateIntToPtr(V, NewTy);
1905   }
1906
1907   // See if we need ptrtoint for this type pair. A cast involving both scalars
1908   // and vectors requires and additional bitcast.
1909   if (OldTy->getScalarType()->isPointerTy() &&
1910       NewTy->getScalarType()->isIntegerTy()) {
1911     // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1912     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1913       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1914                                NewTy);
1915
1916     // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1917     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1918       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1919                                NewTy);
1920
1921     return IRB.CreatePtrToInt(V, NewTy);
1922   }
1923
1924   return IRB.CreateBitCast(V, NewTy);
1925 }
1926
1927 /// \brief Test whether the given slice use can be promoted to a vector.
1928 ///
1929 /// This function is called to test each entry in a partioning which is slated
1930 /// for a single slice.
1931 static bool isVectorPromotionViableForSlice(AllocaSlices::Partition &P,
1932                                             const Slice &S, VectorType *Ty,
1933                                             uint64_t ElementSize,
1934                                             const DataLayout &DL) {
1935   // First validate the slice offsets.
1936   uint64_t BeginOffset =
1937       std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
1938   uint64_t BeginIndex = BeginOffset / ElementSize;
1939   if (BeginIndex * ElementSize != BeginOffset ||
1940       BeginIndex >= Ty->getNumElements())
1941     return false;
1942   uint64_t EndOffset =
1943       std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
1944   uint64_t EndIndex = EndOffset / ElementSize;
1945   if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1946     return false;
1947
1948   assert(EndIndex > BeginIndex && "Empty vector!");
1949   uint64_t NumElements = EndIndex - BeginIndex;
1950   Type *SliceTy = (NumElements == 1)
1951                       ? Ty->getElementType()
1952                       : VectorType::get(Ty->getElementType(), NumElements);
1953
1954   Type *SplitIntTy =
1955       Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1956
1957   Use *U = S.getUse();
1958
1959   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1960     if (MI->isVolatile())
1961       return false;
1962     if (!S.isSplittable())
1963       return false; // Skip any unsplittable intrinsics.
1964   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1965     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1966         II->getIntrinsicID() != Intrinsic::lifetime_end)
1967       return false;
1968   } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1969     // Disable vector promotion when there are loads or stores of an FCA.
1970     return false;
1971   } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1972     if (LI->isVolatile())
1973       return false;
1974     Type *LTy = LI->getType();
1975     if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1976       assert(LTy->isIntegerTy());
1977       LTy = SplitIntTy;
1978     }
1979     if (!canConvertValue(DL, SliceTy, LTy))
1980       return false;
1981   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1982     if (SI->isVolatile())
1983       return false;
1984     Type *STy = SI->getValueOperand()->getType();
1985     if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1986       assert(STy->isIntegerTy());
1987       STy = SplitIntTy;
1988     }
1989     if (!canConvertValue(DL, STy, SliceTy))
1990       return false;
1991   } else {
1992     return false;
1993   }
1994
1995   return true;
1996 }
1997
1998 /// \brief Test whether the given alloca partitioning and range of slices can be
1999 /// promoted to a vector.
2000 ///
2001 /// This is a quick test to check whether we can rewrite a particular alloca
2002 /// partition (and its newly formed alloca) into a vector alloca with only
2003 /// whole-vector loads and stores such that it could be promoted to a vector
2004 /// SSA value. We only can ensure this for a limited set of operations, and we
2005 /// don't want to do the rewrites unless we are confident that the result will
2006 /// be promotable, so we have an early test here.
2007 static VectorType *isVectorPromotionViable(AllocaSlices::Partition &P,
2008                                            const DataLayout &DL) {
2009   // Collect the candidate types for vector-based promotion. Also track whether
2010   // we have different element types.
2011   SmallVector<VectorType *, 4> CandidateTys;
2012   Type *CommonEltTy = nullptr;
2013   bool HaveCommonEltTy = true;
2014   auto CheckCandidateType = [&](Type *Ty) {
2015     if (auto *VTy = dyn_cast<VectorType>(Ty)) {
2016       CandidateTys.push_back(VTy);
2017       if (!CommonEltTy)
2018         CommonEltTy = VTy->getElementType();
2019       else if (CommonEltTy != VTy->getElementType())
2020         HaveCommonEltTy = false;
2021     }
2022   };
2023   // Consider any loads or stores that are the exact size of the slice.
2024   for (const Slice &S : P)
2025     if (S.beginOffset() == P.beginOffset() &&
2026         S.endOffset() == P.endOffset()) {
2027       if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
2028         CheckCandidateType(LI->getType());
2029       else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
2030         CheckCandidateType(SI->getValueOperand()->getType());
2031     }
2032
2033   // If we didn't find a vector type, nothing to do here.
2034   if (CandidateTys.empty())
2035     return nullptr;
2036
2037   // Remove non-integer vector types if we had multiple common element types.
2038   // FIXME: It'd be nice to replace them with integer vector types, but we can't
2039   // do that until all the backends are known to produce good code for all
2040   // integer vector types.
2041   if (!HaveCommonEltTy) {
2042     CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
2043                                       [](VectorType *VTy) {
2044                          return !VTy->getElementType()->isIntegerTy();
2045                        }),
2046                        CandidateTys.end());
2047
2048     // If there were no integer vector types, give up.
2049     if (CandidateTys.empty())
2050       return nullptr;
2051
2052     // Rank the remaining candidate vector types. This is easy because we know
2053     // they're all integer vectors. We sort by ascending number of elements.
2054     auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
2055       assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
2056              "Cannot have vector types of different sizes!");
2057       assert(RHSTy->getElementType()->isIntegerTy() &&
2058              "All non-integer types eliminated!");
2059       assert(LHSTy->getElementType()->isIntegerTy() &&
2060              "All non-integer types eliminated!");
2061       return RHSTy->getNumElements() < LHSTy->getNumElements();
2062     };
2063     std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
2064     CandidateTys.erase(
2065         std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
2066         CandidateTys.end());
2067   } else {
2068 // The only way to have the same element type in every vector type is to
2069 // have the same vector type. Check that and remove all but one.
2070 #ifndef NDEBUG
2071     for (VectorType *VTy : CandidateTys) {
2072       assert(VTy->getElementType() == CommonEltTy &&
2073              "Unaccounted for element type!");
2074       assert(VTy == CandidateTys[0] &&
2075              "Different vector types with the same element type!");
2076     }
2077 #endif
2078     CandidateTys.resize(1);
2079   }
2080
2081   // Try each vector type, and return the one which works.
2082   auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
2083     uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
2084
2085     // While the definition of LLVM vectors is bitpacked, we don't support sizes
2086     // that aren't byte sized.
2087     if (ElementSize % 8)
2088       return false;
2089     assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
2090            "vector size not a multiple of element size?");
2091     ElementSize /= 8;
2092
2093     for (const Slice &S : P)
2094       if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
2095         return false;
2096
2097     for (const Slice *S : P.splitSliceTails())
2098       if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
2099         return false;
2100
2101     return true;
2102   };
2103   for (VectorType *VTy : CandidateTys)
2104     if (CheckVectorTypeForPromotion(VTy))
2105       return VTy;
2106
2107   return nullptr;
2108 }
2109
2110 /// \brief Test whether a slice of an alloca is valid for integer widening.
2111 ///
2112 /// This implements the necessary checking for the \c isIntegerWideningViable
2113 /// test below on a single slice of the alloca.
2114 static bool isIntegerWideningViableForSlice(const Slice &S,
2115                                             uint64_t AllocBeginOffset,
2116                                             Type *AllocaTy,
2117                                             const DataLayout &DL,
2118                                             bool &WholeAllocaOp) {
2119   uint64_t Size = DL.getTypeStoreSize(AllocaTy);
2120
2121   uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2122   uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
2123
2124   // We can't reasonably handle cases where the load or store extends past
2125   // the end of the aloca's type and into its padding.
2126   if (RelEnd > Size)
2127     return false;
2128
2129   Use *U = S.getUse();
2130
2131   if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2132     if (LI->isVolatile())
2133       return false;
2134     // Note that we don't count vector loads or stores as whole-alloca
2135     // operations which enable integer widening because we would prefer to use
2136     // vector widening instead.
2137     if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
2138       WholeAllocaOp = true;
2139     if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2140       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
2141         return false;
2142     } else if (RelBegin != 0 || RelEnd != Size ||
2143                !canConvertValue(DL, AllocaTy, LI->getType())) {
2144       // Non-integer loads need to be convertible from the alloca type so that
2145       // they are promotable.
2146       return false;
2147     }
2148   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2149     Type *ValueTy = SI->getValueOperand()->getType();
2150     if (SI->isVolatile())
2151       return false;
2152     // Note that we don't count vector loads or stores as whole-alloca
2153     // operations which enable integer widening because we would prefer to use
2154     // vector widening instead.
2155     if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
2156       WholeAllocaOp = true;
2157     if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2158       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
2159         return false;
2160     } else if (RelBegin != 0 || RelEnd != Size ||
2161                !canConvertValue(DL, ValueTy, AllocaTy)) {
2162       // Non-integer stores need to be convertible to the alloca type so that
2163       // they are promotable.
2164       return false;
2165     }
2166   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2167     if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2168       return false;
2169     if (!S.isSplittable())
2170       return false; // Skip any unsplittable intrinsics.
2171   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2172     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2173         II->getIntrinsicID() != Intrinsic::lifetime_end)
2174       return false;
2175   } else {
2176     return false;
2177   }
2178
2179   return true;
2180 }
2181
2182 /// \brief Test whether the given alloca partition's integer operations can be
2183 /// widened to promotable ones.
2184 ///
2185 /// This is a quick test to check whether we can rewrite the integer loads and
2186 /// stores to a particular alloca into wider loads and stores and be able to
2187 /// promote the resulting alloca.
2188 static bool isIntegerWideningViable(AllocaSlices::Partition &P, Type *AllocaTy,
2189                                     const DataLayout &DL) {
2190   uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
2191   // Don't create integer types larger than the maximum bitwidth.
2192   if (SizeInBits > IntegerType::MAX_INT_BITS)
2193     return false;
2194
2195   // Don't try to handle allocas with bit-padding.
2196   if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
2197     return false;
2198
2199   // We need to ensure that an integer type with the appropriate bitwidth can
2200   // be converted to the alloca type, whatever that is. We don't want to force
2201   // the alloca itself to have an integer type if there is a more suitable one.
2202   Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2203   if (!canConvertValue(DL, AllocaTy, IntTy) ||
2204       !canConvertValue(DL, IntTy, AllocaTy))
2205     return false;
2206
2207   // While examining uses, we ensure that the alloca has a covering load or
2208   // store. We don't want to widen the integer operations only to fail to
2209   // promote due to some other unsplittable entry (which we may make splittable
2210   // later). However, if there are only splittable uses, go ahead and assume
2211   // that we cover the alloca.
2212   // FIXME: We shouldn't consider split slices that happen to start in the
2213   // partition here...
2214   bool WholeAllocaOp =
2215       P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
2216
2217   for (const Slice &S : P)
2218     if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2219                                          WholeAllocaOp))
2220       return false;
2221
2222   for (const Slice *S : P.splitSliceTails())
2223     if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2224                                          WholeAllocaOp))
2225       return false;
2226
2227   return WholeAllocaOp;
2228 }
2229
2230 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2231                              IntegerType *Ty, uint64_t Offset,
2232                              const Twine &Name) {
2233   DEBUG(dbgs() << "       start: " << *V << "\n");
2234   IntegerType *IntTy = cast<IntegerType>(V->getType());
2235   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2236          "Element extends past full value");
2237   uint64_t ShAmt = 8 * Offset;
2238   if (DL.isBigEndian())
2239     ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2240   if (ShAmt) {
2241     V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2242     DEBUG(dbgs() << "     shifted: " << *V << "\n");
2243   }
2244   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2245          "Cannot extract to a larger integer!");
2246   if (Ty != IntTy) {
2247     V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2248     DEBUG(dbgs() << "     trunced: " << *V << "\n");
2249   }
2250   return V;
2251 }
2252
2253 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2254                             Value *V, uint64_t Offset, const Twine &Name) {
2255   IntegerType *IntTy = cast<IntegerType>(Old->getType());
2256   IntegerType *Ty = cast<IntegerType>(V->getType());
2257   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2258          "Cannot insert a larger integer!");
2259   DEBUG(dbgs() << "       start: " << *V << "\n");
2260   if (Ty != IntTy) {
2261     V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2262     DEBUG(dbgs() << "    extended: " << *V << "\n");
2263   }
2264   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2265          "Element store outside of alloca store");
2266   uint64_t ShAmt = 8 * Offset;
2267   if (DL.isBigEndian())
2268     ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2269   if (ShAmt) {
2270     V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2271     DEBUG(dbgs() << "     shifted: " << *V << "\n");
2272   }
2273
2274   if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2275     APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2276     Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2277     DEBUG(dbgs() << "      masked: " << *Old << "\n");
2278     V = IRB.CreateOr(Old, V, Name + ".insert");
2279     DEBUG(dbgs() << "    inserted: " << *V << "\n");
2280   }
2281   return V;
2282 }
2283
2284 static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2285                             unsigned EndIndex, const Twine &Name) {
2286   VectorType *VecTy = cast<VectorType>(V->getType());
2287   unsigned NumElements = EndIndex - BeginIndex;
2288   assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2289
2290   if (NumElements == VecTy->getNumElements())
2291     return V;
2292
2293   if (NumElements == 1) {
2294     V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2295                                  Name + ".extract");
2296     DEBUG(dbgs() << "     extract: " << *V << "\n");
2297     return V;
2298   }
2299
2300   SmallVector<Constant *, 8> Mask;
2301   Mask.reserve(NumElements);
2302   for (unsigned i = BeginIndex; i != EndIndex; ++i)
2303     Mask.push_back(IRB.getInt32(i));
2304   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2305                               ConstantVector::get(Mask), Name + ".extract");
2306   DEBUG(dbgs() << "     shuffle: " << *V << "\n");
2307   return V;
2308 }
2309
2310 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2311                            unsigned BeginIndex, const Twine &Name) {
2312   VectorType *VecTy = cast<VectorType>(Old->getType());
2313   assert(VecTy && "Can only insert a vector into a vector");
2314
2315   VectorType *Ty = dyn_cast<VectorType>(V->getType());
2316   if (!Ty) {
2317     // Single element to insert.
2318     V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2319                                 Name + ".insert");
2320     DEBUG(dbgs() << "     insert: " << *V << "\n");
2321     return V;
2322   }
2323
2324   assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2325          "Too many elements!");
2326   if (Ty->getNumElements() == VecTy->getNumElements()) {
2327     assert(V->getType() == VecTy && "Vector type mismatch");
2328     return V;
2329   }
2330   unsigned EndIndex = BeginIndex + Ty->getNumElements();
2331
2332   // When inserting a smaller vector into the larger to store, we first
2333   // use a shuffle vector to widen it with undef elements, and then
2334   // a second shuffle vector to select between the loaded vector and the
2335   // incoming vector.
2336   SmallVector<Constant *, 8> Mask;
2337   Mask.reserve(VecTy->getNumElements());
2338   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2339     if (i >= BeginIndex && i < EndIndex)
2340       Mask.push_back(IRB.getInt32(i - BeginIndex));
2341     else
2342       Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2343   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2344                               ConstantVector::get(Mask), Name + ".expand");
2345   DEBUG(dbgs() << "    shuffle: " << *V << "\n");
2346
2347   Mask.clear();
2348   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2349     Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2350
2351   V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2352
2353   DEBUG(dbgs() << "    blend: " << *V << "\n");
2354   return V;
2355 }
2356
2357 namespace {
2358 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
2359 /// to use a new alloca.
2360 ///
2361 /// Also implements the rewriting to vector-based accesses when the partition
2362 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2363 /// lives here.
2364 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
2365   // Befriend the base class so it can delegate to private visit methods.
2366   friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2367   typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
2368
2369   const DataLayout &DL;
2370   AllocaSlices &AS;
2371   SROA &Pass;
2372   AllocaInst &OldAI, &NewAI;
2373   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2374   Type *NewAllocaTy;
2375
2376   // This is a convenience and flag variable that will be null unless the new
2377   // alloca's integer operations should be widened to this integer type due to
2378   // passing isIntegerWideningViable above. If it is non-null, the desired
2379   // integer type will be stored here for easy access during rewriting.
2380   IntegerType *IntTy;
2381
2382   // If we are rewriting an alloca partition which can be written as pure
2383   // vector operations, we stash extra information here. When VecTy is
2384   // non-null, we have some strict guarantees about the rewritten alloca:
2385   //   - The new alloca is exactly the size of the vector type here.
2386   //   - The accesses all either map to the entire vector or to a single
2387   //     element.
2388   //   - The set of accessing instructions is only one of those handled above
2389   //     in isVectorPromotionViable. Generally these are the same access kinds
2390   //     which are promotable via mem2reg.
2391   VectorType *VecTy;
2392   Type *ElementTy;
2393   uint64_t ElementSize;
2394
2395   // The original offset of the slice currently being rewritten relative to
2396   // the original alloca.
2397   uint64_t BeginOffset, EndOffset;
2398   // The new offsets of the slice currently being rewritten relative to the
2399   // original alloca.
2400   uint64_t NewBeginOffset, NewEndOffset;
2401
2402   uint64_t SliceSize;
2403   bool IsSplittable;
2404   bool IsSplit;
2405   Use *OldUse;
2406   Instruction *OldPtr;
2407
2408   // Track post-rewrite users which are PHI nodes and Selects.
2409   SmallPtrSetImpl<PHINode *> &PHIUsers;
2410   SmallPtrSetImpl<SelectInst *> &SelectUsers;
2411
2412   // Utility IR builder, whose name prefix is setup for each visited use, and
2413   // the insertion point is set to point to the user.
2414   IRBuilderTy IRB;
2415
2416 public:
2417   AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2418                       AllocaInst &OldAI, AllocaInst &NewAI,
2419                       uint64_t NewAllocaBeginOffset,
2420                       uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2421                       VectorType *PromotableVecTy,
2422                       SmallPtrSetImpl<PHINode *> &PHIUsers,
2423                       SmallPtrSetImpl<SelectInst *> &SelectUsers)
2424       : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2425         NewAllocaBeginOffset(NewAllocaBeginOffset),
2426         NewAllocaEndOffset(NewAllocaEndOffset),
2427         NewAllocaTy(NewAI.getAllocatedType()),
2428         IntTy(IsIntegerPromotable
2429                   ? Type::getIntNTy(
2430                         NewAI.getContext(),
2431                         DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2432                   : nullptr),
2433         VecTy(PromotableVecTy),
2434         ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2435         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2436         BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
2437         OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2438         IRB(NewAI.getContext(), ConstantFolder()) {
2439     if (VecTy) {
2440       assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
2441              "Only multiple-of-8 sized vector elements are viable");
2442       ++NumVectorized;
2443     }
2444     assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2445   }
2446
2447   bool visit(AllocaSlices::const_iterator I) {
2448     bool CanSROA = true;
2449     BeginOffset = I->beginOffset();
2450     EndOffset = I->endOffset();
2451     IsSplittable = I->isSplittable();
2452     IsSplit =
2453         BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2454     DEBUG(dbgs() << "  rewriting " << (IsSplit ? "split " : ""));
2455     DEBUG(AS.printSlice(dbgs(), I, ""));
2456     DEBUG(dbgs() << "\n");
2457
2458     // Compute the intersecting offset range.
2459     assert(BeginOffset < NewAllocaEndOffset);
2460     assert(EndOffset > NewAllocaBeginOffset);
2461     NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2462     NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2463
2464     SliceSize = NewEndOffset - NewBeginOffset;
2465
2466     OldUse = I->getUse();
2467     OldPtr = cast<Instruction>(OldUse->get());
2468
2469     Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2470     IRB.SetInsertPoint(OldUserI);
2471     IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2472     IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2473
2474     CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2475     if (VecTy || IntTy)
2476       assert(CanSROA);
2477     return CanSROA;
2478   }
2479
2480 private:
2481   // Make sure the other visit overloads are visible.
2482   using Base::visit;
2483
2484   // Every instruction which can end up as a user must have a rewrite rule.
2485   bool visitInstruction(Instruction &I) {
2486     DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
2487     llvm_unreachable("No rewrite rule for this instruction!");
2488   }
2489
2490   Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2491     // Note that the offset computation can use BeginOffset or NewBeginOffset
2492     // interchangeably for unsplit slices.
2493     assert(IsSplit || BeginOffset == NewBeginOffset);
2494     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2495
2496 #ifndef NDEBUG
2497     StringRef OldName = OldPtr->getName();
2498     // Skip through the last '.sroa.' component of the name.
2499     size_t LastSROAPrefix = OldName.rfind(".sroa.");
2500     if (LastSROAPrefix != StringRef::npos) {
2501       OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2502       // Look for an SROA slice index.
2503       size_t IndexEnd = OldName.find_first_not_of("0123456789");
2504       if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2505         // Strip the index and look for the offset.
2506         OldName = OldName.substr(IndexEnd + 1);
2507         size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2508         if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2509           // Strip the offset.
2510           OldName = OldName.substr(OffsetEnd + 1);
2511       }
2512     }
2513     // Strip any SROA suffixes as well.
2514     OldName = OldName.substr(0, OldName.find(".sroa_"));
2515 #endif
2516
2517     return getAdjustedPtr(IRB, DL, &NewAI,
2518                           APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
2519 #ifndef NDEBUG
2520                           Twine(OldName) + "."
2521 #else
2522                           Twine()
2523 #endif
2524                           );
2525   }
2526
2527   /// \brief Compute suitable alignment to access this slice of the *new*
2528   /// alloca.
2529   ///
2530   /// You can optionally pass a type to this routine and if that type's ABI
2531   /// alignment is itself suitable, this will return zero.
2532   unsigned getSliceAlign(Type *Ty = nullptr) {
2533     unsigned NewAIAlign = NewAI.getAlignment();
2534     if (!NewAIAlign)
2535       NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2536     unsigned Align =
2537         MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2538     return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
2539   }
2540
2541   unsigned getIndex(uint64_t Offset) {
2542     assert(VecTy && "Can only call getIndex when rewriting a vector");
2543     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2544     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2545     uint32_t Index = RelOffset / ElementSize;
2546     assert(Index * ElementSize == RelOffset);
2547     return Index;
2548   }
2549
2550   void deleteIfTriviallyDead(Value *V) {
2551     Instruction *I = cast<Instruction>(V);
2552     if (isInstructionTriviallyDead(I))
2553       Pass.DeadInsts.insert(I);
2554   }
2555
2556   Value *rewriteVectorizedLoadInst() {
2557     unsigned BeginIndex = getIndex(NewBeginOffset);
2558     unsigned EndIndex = getIndex(NewEndOffset);
2559     assert(EndIndex > BeginIndex && "Empty vector!");
2560
2561     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2562     return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2563   }
2564
2565   Value *rewriteIntegerLoad(LoadInst &LI) {
2566     assert(IntTy && "We cannot insert an integer to the alloca");
2567     assert(!LI.isVolatile());
2568     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2569     V = convertValue(DL, IRB, V, IntTy);
2570     assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2571     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2572     if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
2573       V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2574                          "extract");
2575     return V;
2576   }
2577
2578   bool visitLoadInst(LoadInst &LI) {
2579     DEBUG(dbgs() << "    original: " << LI << "\n");
2580     Value *OldOp = LI.getOperand(0);
2581     assert(OldOp == OldPtr);
2582
2583     Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2584                              : LI.getType();
2585     bool IsPtrAdjusted = false;
2586     Value *V;
2587     if (VecTy) {
2588       V = rewriteVectorizedLoadInst();
2589     } else if (IntTy && LI.getType()->isIntegerTy()) {
2590       V = rewriteIntegerLoad(LI);
2591     } else if (NewBeginOffset == NewAllocaBeginOffset &&
2592                canConvertValue(DL, NewAllocaTy, LI.getType())) {
2593       V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), LI.isVolatile(),
2594                                 LI.getName());
2595     } else {
2596       Type *LTy = TargetTy->getPointerTo();
2597       V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2598                                 getSliceAlign(TargetTy), LI.isVolatile(),
2599                                 LI.getName());
2600       IsPtrAdjusted = true;
2601     }
2602     V = convertValue(DL, IRB, V, TargetTy);
2603
2604     if (IsSplit) {
2605       assert(!LI.isVolatile());
2606       assert(LI.getType()->isIntegerTy() &&
2607              "Only integer type loads and stores are split");
2608       assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
2609              "Split load isn't smaller than original load");
2610       assert(LI.getType()->getIntegerBitWidth() ==
2611                  DL.getTypeStoreSizeInBits(LI.getType()) &&
2612              "Non-byte-multiple bit width");
2613       // Move the insertion point just past the load so that we can refer to it.
2614       IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
2615       // Create a placeholder value with the same type as LI to use as the
2616       // basis for the new value. This allows us to replace the uses of LI with
2617       // the computed value, and then replace the placeholder with LI, leaving
2618       // LI only used for this computation.
2619       Value *Placeholder =
2620           new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2621       V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2622                         "insert");
2623       LI.replaceAllUsesWith(V);
2624       Placeholder->replaceAllUsesWith(&LI);
2625       delete Placeholder;
2626     } else {
2627       LI.replaceAllUsesWith(V);
2628     }
2629
2630     Pass.DeadInsts.insert(&LI);
2631     deleteIfTriviallyDead(OldOp);
2632     DEBUG(dbgs() << "          to: " << *V << "\n");
2633     return !LI.isVolatile() && !IsPtrAdjusted;
2634   }
2635
2636   bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
2637     if (V->getType() != VecTy) {
2638       unsigned BeginIndex = getIndex(NewBeginOffset);
2639       unsigned EndIndex = getIndex(NewEndOffset);
2640       assert(EndIndex > BeginIndex && "Empty vector!");
2641       unsigned NumElements = EndIndex - BeginIndex;
2642       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2643       Type *SliceTy = (NumElements == 1)
2644                           ? ElementTy
2645                           : VectorType::get(ElementTy, NumElements);
2646       if (V->getType() != SliceTy)
2647         V = convertValue(DL, IRB, V, SliceTy);
2648
2649       // Mix in the existing elements.
2650       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2651       V = insertVector(IRB, Old, V, BeginIndex, "vec");
2652     }
2653     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2654     Pass.DeadInsts.insert(&SI);
2655
2656     (void)Store;
2657     DEBUG(dbgs() << "          to: " << *Store << "\n");
2658     return true;
2659   }
2660
2661   bool rewriteIntegerStore(Value *V, StoreInst &SI) {
2662     assert(IntTy && "We cannot extract an integer from the alloca");
2663     assert(!SI.isVolatile());
2664     if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2665       Value *Old =
2666           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2667       Old = convertValue(DL, IRB, Old, IntTy);
2668       assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2669       uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2670       V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
2671     }
2672     V = convertValue(DL, IRB, V, NewAllocaTy);
2673     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2674     Pass.DeadInsts.insert(&SI);
2675     (void)Store;
2676     DEBUG(dbgs() << "          to: " << *Store << "\n");
2677     return true;
2678   }
2679
2680   bool visitStoreInst(StoreInst &SI) {
2681     DEBUG(dbgs() << "    original: " << SI << "\n");
2682     Value *OldOp = SI.getOperand(1);
2683     assert(OldOp == OldPtr);
2684
2685     Value *V = SI.getValueOperand();
2686
2687     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2688     // alloca that should be re-examined after promoting this alloca.
2689     if (V->getType()->isPointerTy())
2690       if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2691         Pass.PostPromotionWorklist.insert(AI);
2692
2693     if (SliceSize < DL.getTypeStoreSize(V->getType())) {
2694       assert(!SI.isVolatile());
2695       assert(V->getType()->isIntegerTy() &&
2696              "Only integer type loads and stores are split");
2697       assert(V->getType()->getIntegerBitWidth() ==
2698                  DL.getTypeStoreSizeInBits(V->getType()) &&
2699              "Non-byte-multiple bit width");
2700       IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2701       V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2702                          "extract");
2703     }
2704
2705     if (VecTy)
2706       return rewriteVectorizedStoreInst(V, SI, OldOp);
2707     if (IntTy && V->getType()->isIntegerTy())
2708       return rewriteIntegerStore(V, SI);
2709
2710     StoreInst *NewSI;
2711     if (NewBeginOffset == NewAllocaBeginOffset &&
2712         NewEndOffset == NewAllocaEndOffset &&
2713         canConvertValue(DL, V->getType(), NewAllocaTy)) {
2714       V = convertValue(DL, IRB, V, NewAllocaTy);
2715       NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2716                                      SI.isVolatile());
2717     } else {
2718       Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
2719       NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2720                                      SI.isVolatile());
2721     }
2722     (void)NewSI;
2723     Pass.DeadInsts.insert(&SI);
2724     deleteIfTriviallyDead(OldOp);
2725
2726     DEBUG(dbgs() << "          to: " << *NewSI << "\n");
2727     return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2728   }
2729
2730   /// \brief Compute an integer value from splatting an i8 across the given
2731   /// number of bytes.
2732   ///
2733   /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2734   /// call this routine.
2735   /// FIXME: Heed the advice above.
2736   ///
2737   /// \param V The i8 value to splat.
2738   /// \param Size The number of bytes in the output (assuming i8 is one byte)
2739   Value *getIntegerSplat(Value *V, unsigned Size) {
2740     assert(Size > 0 && "Expected a positive number of bytes.");
2741     IntegerType *VTy = cast<IntegerType>(V->getType());
2742     assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2743     if (Size == 1)
2744       return V;
2745
2746     Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2747     V = IRB.CreateMul(
2748         IRB.CreateZExt(V, SplatIntTy, "zext"),
2749         ConstantExpr::getUDiv(
2750             Constant::getAllOnesValue(SplatIntTy),
2751             ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2752                                   SplatIntTy)),
2753         "isplat");
2754     return V;
2755   }
2756
2757   /// \brief Compute a vector splat for a given element value.
2758   Value *getVectorSplat(Value *V, unsigned NumElements) {
2759     V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2760     DEBUG(dbgs() << "       splat: " << *V << "\n");
2761     return V;
2762   }
2763
2764   bool visitMemSetInst(MemSetInst &II) {
2765     DEBUG(dbgs() << "    original: " << II << "\n");
2766     assert(II.getRawDest() == OldPtr);
2767
2768     // If the memset has a variable size, it cannot be split, just adjust the
2769     // pointer to the new alloca.
2770     if (!isa<Constant>(II.getLength())) {
2771       assert(!IsSplit);
2772       assert(NewBeginOffset == BeginOffset);
2773       II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2774       Type *CstTy = II.getAlignmentCst()->getType();
2775       II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
2776
2777       deleteIfTriviallyDead(OldPtr);
2778       return false;
2779     }
2780
2781     // Record this instruction for deletion.
2782     Pass.DeadInsts.insert(&II);
2783
2784     Type *AllocaTy = NewAI.getAllocatedType();
2785     Type *ScalarTy = AllocaTy->getScalarType();
2786
2787     // If this doesn't map cleanly onto the alloca type, and that type isn't
2788     // a single value type, just emit a memset.
2789     if (!VecTy && !IntTy &&
2790         (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2791          SliceSize != DL.getTypeStoreSize(AllocaTy) ||
2792          !AllocaTy->isSingleValueType() ||
2793          !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2794          DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
2795       Type *SizeTy = II.getLength()->getType();
2796       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2797       CallInst *New = IRB.CreateMemSet(
2798           getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2799           getSliceAlign(), II.isVolatile());
2800       (void)New;
2801       DEBUG(dbgs() << "          to: " << *New << "\n");
2802       return false;
2803     }
2804
2805     // If we can represent this as a simple value, we have to build the actual
2806     // value to store, which requires expanding the byte present in memset to
2807     // a sensible representation for the alloca type. This is essentially
2808     // splatting the byte to a sufficiently wide integer, splatting it across
2809     // any desired vector width, and bitcasting to the final type.
2810     Value *V;
2811
2812     if (VecTy) {
2813       // If this is a memset of a vectorized alloca, insert it.
2814       assert(ElementTy == ScalarTy);
2815
2816       unsigned BeginIndex = getIndex(NewBeginOffset);
2817       unsigned EndIndex = getIndex(NewEndOffset);
2818       assert(EndIndex > BeginIndex && "Empty vector!");
2819       unsigned NumElements = EndIndex - BeginIndex;
2820       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2821
2822       Value *Splat =
2823           getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2824       Splat = convertValue(DL, IRB, Splat, ElementTy);
2825       if (NumElements > 1)
2826         Splat = getVectorSplat(Splat, NumElements);
2827
2828       Value *Old =
2829           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2830       V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2831     } else if (IntTy) {
2832       // If this is a memset on an alloca where we can widen stores, insert the
2833       // set integer.
2834       assert(!II.isVolatile());
2835
2836       uint64_t Size = NewEndOffset - NewBeginOffset;
2837       V = getIntegerSplat(II.getValue(), Size);
2838
2839       if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2840                     EndOffset != NewAllocaBeginOffset)) {
2841         Value *Old =
2842             IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2843         Old = convertValue(DL, IRB, Old, IntTy);
2844         uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2845         V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2846       } else {
2847         assert(V->getType() == IntTy &&
2848                "Wrong type for an alloca wide integer!");
2849       }
2850       V = convertValue(DL, IRB, V, AllocaTy);
2851     } else {
2852       // Established these invariants above.
2853       assert(NewBeginOffset == NewAllocaBeginOffset);
2854       assert(NewEndOffset == NewAllocaEndOffset);
2855
2856       V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2857       if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2858         V = getVectorSplat(V, AllocaVecTy->getNumElements());
2859
2860       V = convertValue(DL, IRB, V, AllocaTy);
2861     }
2862
2863     Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2864                                         II.isVolatile());
2865     (void)New;
2866     DEBUG(dbgs() << "          to: " << *New << "\n");
2867     return !II.isVolatile();
2868   }
2869
2870   bool visitMemTransferInst(MemTransferInst &II) {
2871     // Rewriting of memory transfer instructions can be a bit tricky. We break
2872     // them into two categories: split intrinsics and unsplit intrinsics.
2873
2874     DEBUG(dbgs() << "    original: " << II << "\n");
2875
2876     bool IsDest = &II.getRawDestUse() == OldUse;
2877     assert((IsDest && II.getRawDest() == OldPtr) ||
2878            (!IsDest && II.getRawSource() == OldPtr));
2879
2880     unsigned SliceAlign = getSliceAlign();
2881
2882     // For unsplit intrinsics, we simply modify the source and destination
2883     // pointers in place. This isn't just an optimization, it is a matter of
2884     // correctness. With unsplit intrinsics we may be dealing with transfers
2885     // within a single alloca before SROA ran, or with transfers that have
2886     // a variable length. We may also be dealing with memmove instead of
2887     // memcpy, and so simply updating the pointers is the necessary for us to
2888     // update both source and dest of a single call.
2889     if (!IsSplittable) {
2890       Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2891       if (IsDest)
2892         II.setDest(AdjustedPtr);
2893       else
2894         II.setSource(AdjustedPtr);
2895
2896       if (II.getAlignment() > SliceAlign) {
2897         Type *CstTy = II.getAlignmentCst()->getType();
2898         II.setAlignment(
2899             ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
2900       }
2901
2902       DEBUG(dbgs() << "          to: " << II << "\n");
2903       deleteIfTriviallyDead(OldPtr);
2904       return false;
2905     }
2906     // For split transfer intrinsics we have an incredibly useful assurance:
2907     // the source and destination do not reside within the same alloca, and at
2908     // least one of them does not escape. This means that we can replace
2909     // memmove with memcpy, and we don't need to worry about all manner of
2910     // downsides to splitting and transforming the operations.
2911
2912     // If this doesn't map cleanly onto the alloca type, and that type isn't
2913     // a single value type, just emit a memcpy.
2914     bool EmitMemCpy =
2915         !VecTy && !IntTy &&
2916         (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2917          SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2918          !NewAI.getAllocatedType()->isSingleValueType());
2919
2920     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2921     // size hasn't been shrunk based on analysis of the viable range, this is
2922     // a no-op.
2923     if (EmitMemCpy && &OldAI == &NewAI) {
2924       // Ensure the start lines up.
2925       assert(NewBeginOffset == BeginOffset);
2926
2927       // Rewrite the size as needed.
2928       if (NewEndOffset != EndOffset)
2929         II.setLength(ConstantInt::get(II.getLength()->getType(),
2930                                       NewEndOffset - NewBeginOffset));
2931       return false;
2932     }
2933     // Record this instruction for deletion.
2934     Pass.DeadInsts.insert(&II);
2935
2936     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2937     // alloca that should be re-examined after rewriting this instruction.
2938     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2939     if (AllocaInst *AI =
2940             dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2941       assert(AI != &OldAI && AI != &NewAI &&
2942              "Splittable transfers cannot reach the same alloca on both ends.");
2943       Pass.Worklist.insert(AI);
2944     }
2945
2946     Type *OtherPtrTy = OtherPtr->getType();
2947     unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2948
2949     // Compute the relative offset for the other pointer within the transfer.
2950     unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
2951     APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2952     unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2953                                    OtherOffset.zextOrTrunc(64).getZExtValue());
2954
2955     if (EmitMemCpy) {
2956       // Compute the other pointer, folding as much as possible to produce
2957       // a single, simple GEP in most cases.
2958       OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2959                                 OtherPtr->getName() + ".");
2960
2961       Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2962       Type *SizeTy = II.getLength()->getType();
2963       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2964
2965       CallInst *New = IRB.CreateMemCpy(
2966           IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2967           MinAlign(SliceAlign, OtherAlign), II.isVolatile());
2968       (void)New;
2969       DEBUG(dbgs() << "          to: " << *New << "\n");
2970       return false;
2971     }
2972
2973     bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2974                          NewEndOffset == NewAllocaEndOffset;
2975     uint64_t Size = NewEndOffset - NewBeginOffset;
2976     unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2977     unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2978     unsigned NumElements = EndIndex - BeginIndex;
2979     IntegerType *SubIntTy =
2980         IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
2981
2982     // Reset the other pointer type to match the register type we're going to
2983     // use, but using the address space of the original other pointer.
2984     if (VecTy && !IsWholeAlloca) {
2985       if (NumElements == 1)
2986         OtherPtrTy = VecTy->getElementType();
2987       else
2988         OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2989
2990       OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
2991     } else if (IntTy && !IsWholeAlloca) {
2992       OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2993     } else {
2994       OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
2995     }
2996
2997     Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2998                                    OtherPtr->getName() + ".");
2999     unsigned SrcAlign = OtherAlign;
3000     Value *DstPtr = &NewAI;
3001     unsigned DstAlign = SliceAlign;
3002     if (!IsDest) {
3003       std::swap(SrcPtr, DstPtr);
3004       std::swap(SrcAlign, DstAlign);
3005     }
3006
3007     Value *Src;
3008     if (VecTy && !IsWholeAlloca && !IsDest) {
3009       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
3010       Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
3011     } else if (IntTy && !IsWholeAlloca && !IsDest) {
3012       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
3013       Src = convertValue(DL, IRB, Src, IntTy);
3014       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3015       Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
3016     } else {
3017       Src =
3018           IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
3019     }
3020
3021     if (VecTy && !IsWholeAlloca && IsDest) {
3022       Value *Old =
3023           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
3024       Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
3025     } else if (IntTy && !IsWholeAlloca && IsDest) {
3026       Value *Old =
3027           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
3028       Old = convertValue(DL, IRB, Old, IntTy);
3029       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3030       Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3031       Src = convertValue(DL, IRB, Src, NewAllocaTy);
3032     }
3033
3034     StoreInst *Store = cast<StoreInst>(
3035         IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
3036     (void)Store;
3037     DEBUG(dbgs() << "          to: " << *Store << "\n");
3038     return !II.isVolatile();
3039   }
3040
3041   bool visitIntrinsicInst(IntrinsicInst &II) {
3042     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
3043            II.getIntrinsicID() == Intrinsic::lifetime_end);
3044     DEBUG(dbgs() << "    original: " << II << "\n");
3045     assert(II.getArgOperand(1) == OldPtr);
3046
3047     // Record this instruction for deletion.
3048     Pass.DeadInsts.insert(&II);
3049
3050     ConstantInt *Size =
3051         ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
3052                          NewEndOffset - NewBeginOffset);
3053     Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3054     Value *New;
3055     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3056       New = IRB.CreateLifetimeStart(Ptr, Size);
3057     else
3058       New = IRB.CreateLifetimeEnd(Ptr, Size);
3059
3060     (void)New;
3061     DEBUG(dbgs() << "          to: " << *New << "\n");
3062     return true;
3063   }
3064
3065   bool visitPHINode(PHINode &PN) {
3066     DEBUG(dbgs() << "    original: " << PN << "\n");
3067     assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3068     assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
3069
3070     // We would like to compute a new pointer in only one place, but have it be
3071     // as local as possible to the PHI. To do that, we re-use the location of
3072     // the old pointer, which necessarily must be in the right position to
3073     // dominate the PHI.
3074     IRBuilderTy PtrBuilder(IRB);
3075     if (isa<PHINode>(OldPtr))
3076       PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
3077     else
3078       PtrBuilder.SetInsertPoint(OldPtr);
3079     PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
3080
3081     Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
3082     // Replace the operands which were using the old pointer.
3083     std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3084
3085     DEBUG(dbgs() << "          to: " << PN << "\n");
3086     deleteIfTriviallyDead(OldPtr);
3087
3088     // PHIs can't be promoted on their own, but often can be speculated. We
3089     // check the speculation outside of the rewriter so that we see the
3090     // fully-rewritten alloca.
3091     PHIUsers.insert(&PN);
3092     return true;
3093   }
3094
3095   bool visitSelectInst(SelectInst &SI) {
3096     DEBUG(dbgs() << "    original: " << SI << "\n");
3097     assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3098            "Pointer isn't an operand!");
3099     assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3100     assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
3101
3102     Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3103     // Replace the operands which were using the old pointer.
3104     if (SI.getOperand(1) == OldPtr)
3105       SI.setOperand(1, NewPtr);
3106     if (SI.getOperand(2) == OldPtr)
3107       SI.setOperand(2, NewPtr);
3108
3109     DEBUG(dbgs() << "          to: " << SI << "\n");
3110     deleteIfTriviallyDead(OldPtr);
3111
3112     // Selects can't be promoted on their own, but often can be speculated. We
3113     // check the speculation outside of the rewriter so that we see the
3114     // fully-rewritten alloca.
3115     SelectUsers.insert(&SI);
3116     return true;
3117   }
3118 };
3119 }
3120
3121 namespace {
3122 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
3123 ///
3124 /// This pass aggressively rewrites all aggregate loads and stores on
3125 /// a particular pointer (or any pointer derived from it which we can identify)
3126 /// with scalar loads and stores.
3127 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3128   // Befriend the base class so it can delegate to private visit methods.
3129   friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3130
3131   const DataLayout &DL;
3132
3133   /// Queue of pointer uses to analyze and potentially rewrite.
3134   SmallVector<Use *, 8> Queue;
3135
3136   /// Set to prevent us from cycling with phi nodes and loops.
3137   SmallPtrSet<User *, 8> Visited;
3138
3139   /// The current pointer use being rewritten. This is used to dig up the used
3140   /// value (as opposed to the user).
3141   Use *U;
3142
3143 public:
3144   AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
3145
3146   /// Rewrite loads and stores through a pointer and all pointers derived from
3147   /// it.
3148   bool rewrite(Instruction &I) {
3149     DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
3150     enqueueUsers(I);
3151     bool Changed = false;
3152     while (!Queue.empty()) {
3153       U = Queue.pop_back_val();
3154       Changed |= visit(cast<Instruction>(U->getUser()));
3155     }
3156     return Changed;
3157   }
3158
3159 private:
3160   /// Enqueue all the users of the given instruction for further processing.
3161   /// This uses a set to de-duplicate users.
3162   void enqueueUsers(Instruction &I) {
3163     for (Use &U : I.uses())
3164       if (Visited.insert(U.getUser()).second)
3165         Queue.push_back(&U);
3166   }
3167
3168   // Conservative default is to not rewrite anything.
3169   bool visitInstruction(Instruction &I) { return false; }
3170
3171   /// \brief Generic recursive split emission class.
3172   template <typename Derived> class OpSplitter {
3173   protected:
3174     /// The builder used to form new instructions.
3175     IRBuilderTy IRB;
3176     /// The indices which to be used with insert- or extractvalue to select the
3177     /// appropriate value within the aggregate.
3178     SmallVector<unsigned, 4> Indices;
3179     /// The indices to a GEP instruction which will move Ptr to the correct slot
3180     /// within the aggregate.
3181     SmallVector<Value *, 4> GEPIndices;
3182     /// The base pointer of the original op, used as a base for GEPing the
3183     /// split operations.
3184     Value *Ptr;
3185
3186     /// Initialize the splitter with an insertion point, Ptr and start with a
3187     /// single zero GEP index.
3188     OpSplitter(Instruction *InsertionPoint, Value *Ptr)
3189         : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3190
3191   public:
3192     /// \brief Generic recursive split emission routine.
3193     ///
3194     /// This method recursively splits an aggregate op (load or store) into
3195     /// scalar or vector ops. It splits recursively until it hits a single value
3196     /// and emits that single value operation via the template argument.
3197     ///
3198     /// The logic of this routine relies on GEPs and insertvalue and
3199     /// extractvalue all operating with the same fundamental index list, merely
3200     /// formatted differently (GEPs need actual values).
3201     ///
3202     /// \param Ty  The type being split recursively into smaller ops.
3203     /// \param Agg The aggregate value being built up or stored, depending on
3204     /// whether this is splitting a load or a store respectively.
3205     void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3206       if (Ty->isSingleValueType())
3207         return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
3208
3209       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3210         unsigned OldSize = Indices.size();
3211         (void)OldSize;
3212         for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3213              ++Idx) {
3214           assert(Indices.size() == OldSize && "Did not return to the old size");
3215           Indices.push_back(Idx);
3216           GEPIndices.push_back(IRB.getInt32(Idx));
3217           emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3218           GEPIndices.pop_back();
3219           Indices.pop_back();
3220         }
3221         return;
3222       }
3223
3224       if (StructType *STy = dyn_cast<StructType>(Ty)) {
3225         unsigned OldSize = Indices.size();
3226         (void)OldSize;
3227         for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3228              ++Idx) {
3229           assert(Indices.size() == OldSize && "Did not return to the old size");
3230           Indices.push_back(Idx);
3231           GEPIndices.push_back(IRB.getInt32(Idx));
3232           emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3233           GEPIndices.pop_back();
3234           Indices.pop_back();
3235         }
3236         return;
3237       }
3238
3239       llvm_unreachable("Only arrays and structs are aggregate loadable types");
3240     }
3241   };
3242
3243   struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3244     LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3245         : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
3246
3247     /// Emit a leaf load of a single value. This is called at the leaves of the
3248     /// recursive emission to actually load values.
3249     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3250       assert(Ty->isSingleValueType());
3251       // Load the single value and insert it using the indices.
3252       Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
3253       Value *Load = IRB.CreateLoad(GEP, Name + ".load");
3254       Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3255       DEBUG(dbgs() << "          to: " << *Load << "\n");
3256     }
3257   };
3258
3259   bool visitLoadInst(LoadInst &LI) {
3260     assert(LI.getPointerOperand() == *U);
3261     if (!LI.isSimple() || LI.getType()->isSingleValueType())
3262       return false;
3263
3264     // We have an aggregate being loaded, split it apart.
3265     DEBUG(dbgs() << "    original: " << LI << "\n");
3266     LoadOpSplitter Splitter(&LI, *U);
3267     Value *V = UndefValue::get(LI.getType());
3268     Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3269     LI.replaceAllUsesWith(V);
3270     LI.eraseFromParent();
3271     return true;
3272   }
3273
3274   struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
3275     StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3276         : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
3277
3278     /// Emit a leaf store of a single value. This is called at the leaves of the
3279     /// recursive emission to actually produce stores.
3280     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3281       assert(Ty->isSingleValueType());
3282       // Extract the single value and store it using the indices.
3283       Value *Store = IRB.CreateStore(
3284           IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3285           IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3286       (void)Store;
3287       DEBUG(dbgs() << "          to: " << *Store << "\n");
3288     }
3289   };
3290
3291   bool visitStoreInst(StoreInst &SI) {
3292     if (!SI.isSimple() || SI.getPointerOperand() != *U)
3293       return false;
3294     Value *V = SI.getValueOperand();
3295     if (V->getType()->isSingleValueType())
3296       return false;
3297
3298     // We have an aggregate being stored, split it apart.
3299     DEBUG(dbgs() << "    original: " << SI << "\n");
3300     StoreOpSplitter Splitter(&SI, *U);
3301     Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3302     SI.eraseFromParent();
3303     return true;
3304   }
3305
3306   bool visitBitCastInst(BitCastInst &BC) {
3307     enqueueUsers(BC);
3308     return false;
3309   }
3310
3311   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3312     enqueueUsers(GEPI);
3313     return false;
3314   }
3315
3316   bool visitPHINode(PHINode &PN) {
3317     enqueueUsers(PN);
3318     return false;
3319   }
3320
3321   bool visitSelectInst(SelectInst &SI) {
3322     enqueueUsers(SI);
3323     return false;
3324   }
3325 };
3326 }
3327
3328 /// \brief Strip aggregate type wrapping.
3329 ///
3330 /// This removes no-op aggregate types wrapping an underlying type. It will
3331 /// strip as many layers of types as it can without changing either the type
3332 /// size or the allocated size.
3333 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3334   if (Ty->isSingleValueType())
3335     return Ty;
3336
3337   uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3338   uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3339
3340   Type *InnerTy;
3341   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3342     InnerTy = ArrTy->getElementType();
3343   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3344     const StructLayout *SL = DL.getStructLayout(STy);
3345     unsigned Index = SL->getElementContainingOffset(0);
3346     InnerTy = STy->getElementType(Index);
3347   } else {
3348     return Ty;
3349   }
3350
3351   if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3352       TypeSize > DL.getTypeSizeInBits(InnerTy))
3353     return Ty;
3354
3355   return stripAggregateTypeWrapping(DL, InnerTy);
3356 }
3357
3358 /// \brief Try to find a partition of the aggregate type passed in for a given
3359 /// offset and size.
3360 ///
3361 /// This recurses through the aggregate type and tries to compute a subtype
3362 /// based on the offset and size. When the offset and size span a sub-section
3363 /// of an array, it will even compute a new array type for that sub-section,
3364 /// and the same for structs.
3365 ///
3366 /// Note that this routine is very strict and tries to find a partition of the
3367 /// type which produces the *exact* right offset and size. It is not forgiving
3368 /// when the size or offset cause either end of type-based partition to be off.
3369 /// Also, this is a best-effort routine. It is reasonable to give up and not
3370 /// return a type if necessary.
3371 static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3372                               uint64_t Size) {
3373   if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3374     return stripAggregateTypeWrapping(DL, Ty);
3375   if (Offset > DL.getTypeAllocSize(Ty) ||
3376       (DL.getTypeAllocSize(Ty) - Offset) < Size)
3377     return nullptr;
3378
3379   if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3380     // We can't partition pointers...
3381     if (SeqTy->isPointerTy())
3382       return nullptr;
3383
3384     Type *ElementTy = SeqTy->getElementType();
3385     uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3386     uint64_t NumSkippedElements = Offset / ElementSize;
3387     if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
3388       if (NumSkippedElements >= ArrTy->getNumElements())
3389         return nullptr;
3390     } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
3391       if (NumSkippedElements >= VecTy->getNumElements())
3392         return nullptr;
3393     }
3394     Offset -= NumSkippedElements * ElementSize;
3395
3396     // First check if we need to recurse.
3397     if (Offset > 0 || Size < ElementSize) {
3398       // Bail if the partition ends in a different array element.
3399       if ((Offset + Size) > ElementSize)
3400         return nullptr;
3401       // Recurse through the element type trying to peel off offset bytes.
3402       return getTypePartition(DL, ElementTy, Offset, Size);
3403     }
3404     assert(Offset == 0);
3405
3406     if (Size == ElementSize)
3407       return stripAggregateTypeWrapping(DL, ElementTy);
3408     assert(Size > ElementSize);
3409     uint64_t NumElements = Size / ElementSize;
3410     if (NumElements * ElementSize != Size)
3411       return nullptr;
3412     return ArrayType::get(ElementTy, NumElements);
3413   }
3414
3415   StructType *STy = dyn_cast<StructType>(Ty);
3416   if (!STy)
3417     return nullptr;
3418
3419   const StructLayout *SL = DL.getStructLayout(STy);
3420   if (Offset >= SL->getSizeInBytes())
3421     return nullptr;
3422   uint64_t EndOffset = Offset + Size;
3423   if (EndOffset > SL->getSizeInBytes())
3424     return nullptr;
3425
3426   unsigned Index = SL->getElementContainingOffset(Offset);
3427   Offset -= SL->getElementOffset(Index);
3428
3429   Type *ElementTy = STy->getElementType(Index);
3430   uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3431   if (Offset >= ElementSize)
3432     return nullptr; // The offset points into alignment padding.
3433
3434   // See if any partition must be contained by the element.
3435   if (Offset > 0 || Size < ElementSize) {
3436     if ((Offset + Size) > ElementSize)
3437       return nullptr;
3438     return getTypePartition(DL, ElementTy, Offset, Size);
3439   }
3440   assert(Offset == 0);
3441
3442   if (Size == ElementSize)
3443     return stripAggregateTypeWrapping(DL, ElementTy);
3444
3445   StructType::element_iterator EI = STy->element_begin() + Index,
3446                                EE = STy->element_end();
3447   if (EndOffset < SL->getSizeInBytes()) {
3448     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3449     if (Index == EndIndex)
3450       return nullptr; // Within a single element and its padding.
3451
3452     // Don't try to form "natural" types if the elements don't line up with the
3453     // expected size.
3454     // FIXME: We could potentially recurse down through the last element in the
3455     // sub-struct to find a natural end point.
3456     if (SL->getElementOffset(EndIndex) != EndOffset)
3457       return nullptr;
3458
3459     assert(Index < EndIndex);
3460     EE = STy->element_begin() + EndIndex;
3461   }
3462
3463   // Try to build up a sub-structure.
3464   StructType *SubTy =
3465       StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
3466   const StructLayout *SubSL = DL.getStructLayout(SubTy);
3467   if (Size != SubSL->getSizeInBytes())
3468     return nullptr; // The sub-struct doesn't have quite the size needed.
3469
3470   return SubTy;
3471 }
3472
3473 /// \brief Pre-split loads and stores to simplify rewriting.
3474 ///
3475 /// We want to break up the splittable load+store pairs as much as
3476 /// possible. This is important to do as a preprocessing step, as once we
3477 /// start rewriting the accesses to partitions of the alloca we lose the
3478 /// necessary information to correctly split apart paired loads and stores
3479 /// which both point into this alloca. The case to consider is something like
3480 /// the following:
3481 ///
3482 ///   %a = alloca [12 x i8]
3483 ///   %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3484 ///   %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3485 ///   %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3486 ///   %iptr1 = bitcast i8* %gep1 to i64*
3487 ///   %iptr2 = bitcast i8* %gep2 to i64*
3488 ///   %fptr1 = bitcast i8* %gep1 to float*
3489 ///   %fptr2 = bitcast i8* %gep2 to float*
3490 ///   %fptr3 = bitcast i8* %gep3 to float*
3491 ///   store float 0.0, float* %fptr1
3492 ///   store float 1.0, float* %fptr2
3493 ///   %v = load i64* %iptr1
3494 ///   store i64 %v, i64* %iptr2
3495 ///   %f1 = load float* %fptr2
3496 ///   %f2 = load float* %fptr3
3497 ///
3498 /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3499 /// promote everything so we recover the 2 SSA values that should have been
3500 /// there all along.
3501 ///
3502 /// \returns true if any changes are made.
3503 bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3504   DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3505
3506   // Track the loads and stores which are candidates for pre-splitting here, in
3507   // the order they first appear during the partition scan. These give stable
3508   // iteration order and a basis for tracking which loads and stores we
3509   // actually split.
3510   SmallVector<LoadInst *, 4> Loads;
3511   SmallVector<StoreInst *, 4> Stores;
3512
3513   // We need to accumulate the splits required of each load or store where we
3514   // can find them via a direct lookup. This is important to cross-check loads
3515   // and stores against each other. We also track the slice so that we can kill
3516   // all the slices that end up split.
3517   struct SplitOffsets {
3518     Slice *S;
3519     std::vector<uint64_t> Splits;
3520   };
3521   SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3522
3523   // Track loads out of this alloca which cannot, for any reason, be pre-split.
3524   // This is important as we also cannot pre-split stores of those loads!
3525   // FIXME: This is all pretty gross. It means that we can be more aggressive
3526   // in pre-splitting when the load feeding the store happens to come from
3527   // a separate alloca. Put another way, the effectiveness of SROA would be
3528   // decreased by a frontend which just concatenated all of its local allocas
3529   // into one big flat alloca. But defeating such patterns is exactly the job
3530   // SROA is tasked with! Sadly, to not have this discrepancy we would have
3531   // change store pre-splitting to actually force pre-splitting of the load
3532   // that feeds it *and all stores*. That makes pre-splitting much harder, but
3533   // maybe it would make it more principled?
3534   SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3535
3536   DEBUG(dbgs() << "  Searching for candidate loads and stores\n");
3537   for (auto &P : AS.partitions()) {
3538     for (Slice &S : P) {
3539       Instruction *I = cast<Instruction>(S.getUse()->getUser());
3540       if (!S.isSplittable() ||S.endOffset() <= P.endOffset()) {
3541         // If this was a load we have to track that it can't participate in any
3542         // pre-splitting!
3543         if (auto *LI = dyn_cast<LoadInst>(I))
3544           UnsplittableLoads.insert(LI);
3545         continue;
3546       }
3547       assert(P.endOffset() > S.beginOffset() &&
3548              "Empty or backwards partition!");
3549
3550       // Determine if this is a pre-splittable slice.
3551       if (auto *LI = dyn_cast<LoadInst>(I)) {
3552         assert(!LI->isVolatile() && "Cannot split volatile loads!");
3553
3554         // The load must be used exclusively to store into other pointers for
3555         // us to be able to arbitrarily pre-split it. The stores must also be
3556         // simple to avoid changing semantics.
3557         auto IsLoadSimplyStored = [](LoadInst *LI) {
3558           for (User *LU : LI->users()) {
3559             auto *SI = dyn_cast<StoreInst>(LU);
3560             if (!SI || !SI->isSimple())
3561               return false;
3562           }
3563           return true;
3564         };
3565         if (!IsLoadSimplyStored(LI)) {
3566           UnsplittableLoads.insert(LI);
3567           continue;
3568         }
3569
3570         Loads.push_back(LI);
3571       } else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) {
3572         if (!SI ||
3573             S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3574           continue;
3575         auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3576         if (!StoredLoad || !StoredLoad->isSimple())
3577           continue;
3578         assert(!SI->isVolatile() && "Cannot split volatile stores!");
3579
3580         Stores.push_back(SI);
3581       } else {
3582         // Other uses cannot be pre-split.
3583         continue;
3584       }
3585
3586       // Record the initial split.
3587       DEBUG(dbgs() << "    Candidate: " << *I << "\n");
3588       auto &Offsets = SplitOffsetsMap[I];
3589       assert(Offsets.Splits.empty() &&
3590              "Should not have splits the first time we see an instruction!");
3591       Offsets.S = &S;
3592       Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
3593     }
3594
3595     // Now scan the already split slices, and add a split for any of them which
3596     // we're going to pre-split.
3597     for (Slice *S : P.splitSliceTails()) {
3598       auto SplitOffsetsMapI =
3599           SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3600       if (SplitOffsetsMapI == SplitOffsetsMap.end())
3601         continue;
3602       auto &Offsets = SplitOffsetsMapI->second;
3603
3604       assert(Offsets.S == S && "Found a mismatched slice!");
3605       assert(!Offsets.Splits.empty() &&
3606              "Cannot have an empty set of splits on the second partition!");
3607       assert(Offsets.Splits.back() ==
3608                  P.beginOffset() - Offsets.S->beginOffset() &&
3609              "Previous split does not end where this one begins!");
3610
3611       // Record each split. The last partition's end isn't needed as the size
3612       // of the slice dictates that.
3613       if (S->endOffset() > P.endOffset())
3614         Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
3615     }
3616   }
3617
3618   // We may have split loads where some of their stores are split stores. For
3619   // such loads and stores, we can only pre-split them if their splits exactly
3620   // match relative to their starting offset. We have to verify this prior to
3621   // any rewriting.
3622   Stores.erase(
3623       std::remove_if(Stores.begin(), Stores.end(),
3624                      [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3625                        // Lookup the load we are storing in our map of split
3626                        // offsets.
3627                        auto *LI = cast<LoadInst>(SI->getValueOperand());
3628                        // If it was completely unsplittable, then we're done,
3629                        // and this store can't be pre-split.
3630                        if (UnsplittableLoads.count(LI))
3631                          return true;
3632
3633                        auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3634                        if (LoadOffsetsI == SplitOffsetsMap.end())
3635                          return false; // Unrelated loads are definitely safe.
3636                        auto &LoadOffsets = LoadOffsetsI->second;
3637
3638                        // Now lookup the store's offsets.
3639                        auto &StoreOffsets = SplitOffsetsMap[SI];
3640
3641                        // If the relative offsets of each split in the load and
3642                        // store match exactly, then we can split them and we
3643                        // don't need to remove them here.
3644                        if (LoadOffsets.Splits == StoreOffsets.Splits)
3645                          return false;
3646
3647                        DEBUG(dbgs()
3648                              << "    Mismatched splits for load and store:\n"
3649                              << "      " << *LI << "\n"
3650                              << "      " << *SI << "\n");
3651
3652                        // We've found a store and load that we need to split
3653                        // with mismatched relative splits. Just give up on them
3654                        // and remove both instructions from our list of
3655                        // candidates.
3656                        UnsplittableLoads.insert(LI);
3657                        return true;
3658                      }),
3659       Stores.end());
3660   // Now we have to go *back* through all te stores, because a later store may
3661   // have caused an earlier store's load to become unsplittable and if it is
3662   // unsplittable for the later store, then we can't rely on it being split in
3663   // the earlier store either.
3664   Stores.erase(std::remove_if(Stores.begin(), Stores.end(),
3665                               [&UnsplittableLoads](StoreInst *SI) {
3666                                 auto *LI =
3667                                     cast<LoadInst>(SI->getValueOperand());
3668                                 return UnsplittableLoads.count(LI);
3669                               }),
3670                Stores.end());
3671   // Once we've established all the loads that can't be split for some reason,
3672   // filter any that made it into our list out.
3673   Loads.erase(std::remove_if(Loads.begin(), Loads.end(),
3674                              [&UnsplittableLoads](LoadInst *LI) {
3675                                return UnsplittableLoads.count(LI);
3676                              }),
3677               Loads.end());
3678
3679
3680   // If no loads or stores are left, there is no pre-splitting to be done for
3681   // this alloca.
3682   if (Loads.empty() && Stores.empty())
3683     return false;
3684
3685   // From here on, we can't fail and will be building new accesses, so rig up
3686   // an IR builder.
3687   IRBuilderTy IRB(&AI);
3688
3689   // Collect the new slices which we will merge into the alloca slices.
3690   SmallVector<Slice, 4> NewSlices;
3691
3692   // Track any allocas we end up splitting loads and stores for so we iterate
3693   // on them.
3694   SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3695
3696   // At this point, we have collected all of the loads and stores we can
3697   // pre-split, and the specific splits needed for them. We actually do the
3698   // splitting in a specific order in order to handle when one of the loads in
3699   // the value operand to one of the stores.
3700   //
3701   // First, we rewrite all of the split loads, and just accumulate each split
3702   // load in a parallel structure. We also build the slices for them and append
3703   // them to the alloca slices.
3704   SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3705   std::vector<LoadInst *> SplitLoads;
3706   for (LoadInst *LI : Loads) {
3707     SplitLoads.clear();
3708
3709     IntegerType *Ty = cast<IntegerType>(LI->getType());
3710     uint64_t LoadSize = Ty->getBitWidth() / 8;
3711     assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3712
3713     auto &Offsets = SplitOffsetsMap[LI];
3714     assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3715            "Slice size should always match load size exactly!");
3716     uint64_t BaseOffset = Offsets.S->beginOffset();
3717     assert(BaseOffset + LoadSize > BaseOffset &&
3718            "Cannot represent alloca access size using 64-bit integers!");
3719
3720     Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
3721     IRB.SetInsertPoint(BasicBlock::iterator(LI));
3722
3723     DEBUG(dbgs() << "  Splitting load: " << *LI << "\n");
3724
3725     uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3726     int Idx = 0, Size = Offsets.Splits.size();
3727     for (;;) {
3728       auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3729       auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3730       LoadInst *PLoad = IRB.CreateAlignedLoad(
3731           getAdjustedPtr(IRB, *DL, BasePtr,
3732                          APInt(DL->getPointerSizeInBits(), PartOffset),
3733                          PartPtrTy, BasePtr->getName() + "."),
3734           getAdjustedAlignment(LI, PartOffset, *DL), /*IsVolatile*/ false,
3735           LI->getName());
3736
3737       // Append this load onto the list of split loads so we can find it later
3738       // to rewrite the stores.
3739       SplitLoads.push_back(PLoad);
3740
3741       // Now build a new slice for the alloca.
3742       NewSlices.push_back(
3743           Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3744                 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
3745                 /*IsSplittable*/ false));
3746       DEBUG(dbgs() << "    new slice [" << NewSlices.back().beginOffset()
3747                    << ", " << NewSlices.back().endOffset() << "): " << *PLoad
3748                    << "\n");
3749
3750       // See if we've handled all the splits.
3751       if (Idx >= Size)
3752         break;
3753
3754       // Setup the next partition.
3755       PartOffset = Offsets.Splits[Idx];
3756       ++Idx;
3757       PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3758     }
3759
3760     // Now that we have the split loads, do the slow walk over all uses of the
3761     // load and rewrite them as split stores, or save the split loads to use
3762     // below if the store is going to be split there anyways.
3763     bool DeferredStores = false;
3764     for (User *LU : LI->users()) {
3765       StoreInst *SI = cast<StoreInst>(LU);
3766       if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3767         DeferredStores = true;
3768         DEBUG(dbgs() << "    Deferred splitting of store: " << *SI << "\n");
3769         continue;
3770       }
3771
3772       Value *StoreBasePtr = SI->getPointerOperand();
3773       IRB.SetInsertPoint(BasicBlock::iterator(SI));
3774
3775       DEBUG(dbgs() << "    Splitting store of load: " << *SI << "\n");
3776
3777       for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3778         LoadInst *PLoad = SplitLoads[Idx];
3779         uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
3780         auto *PartPtrTy =
3781             PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
3782
3783         StoreInst *PStore = IRB.CreateAlignedStore(
3784             PLoad, getAdjustedPtr(IRB, *DL, StoreBasePtr,
3785                                   APInt(DL->getPointerSizeInBits(), PartOffset),
3786                                   PartPtrTy, StoreBasePtr->getName() + "."),
3787             getAdjustedAlignment(SI, PartOffset, *DL), /*IsVolatile*/ false);
3788         (void)PStore;
3789         DEBUG(dbgs() << "      +" << PartOffset << ":" << *PStore << "\n");
3790       }
3791
3792       // We want to immediately iterate on any allocas impacted by splitting
3793       // this store, and we have to track any promotable alloca (indicated by
3794       // a direct store) as needing to be resplit because it is no longer
3795       // promotable.
3796       if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3797         ResplitPromotableAllocas.insert(OtherAI);
3798         Worklist.insert(OtherAI);
3799       } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3800                      StoreBasePtr->stripInBoundsOffsets())) {
3801         Worklist.insert(OtherAI);
3802       }
3803
3804       // Mark the original store as dead.
3805       DeadInsts.insert(SI);
3806     }
3807
3808     // Save the split loads if there are deferred stores among the users.
3809     if (DeferredStores)
3810       SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3811
3812     // Mark the original load as dead and kill the original slice.
3813     DeadInsts.insert(LI);
3814     Offsets.S->kill();
3815   }
3816
3817   // Second, we rewrite all of the split stores. At this point, we know that
3818   // all loads from this alloca have been split already. For stores of such
3819   // loads, we can simply look up the pre-existing split loads. For stores of
3820   // other loads, we split those loads first and then write split stores of
3821   // them.
3822   for (StoreInst *SI : Stores) {
3823     auto *LI = cast<LoadInst>(SI->getValueOperand());
3824     IntegerType *Ty = cast<IntegerType>(LI->getType());
3825     uint64_t StoreSize = Ty->getBitWidth() / 8;
3826     assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3827
3828     auto &Offsets = SplitOffsetsMap[SI];
3829     assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3830            "Slice size should always match load size exactly!");
3831     uint64_t BaseOffset = Offsets.S->beginOffset();
3832     assert(BaseOffset + StoreSize > BaseOffset &&
3833            "Cannot represent alloca access size using 64-bit integers!");
3834
3835     Value *LoadBasePtr = LI->getPointerOperand();
3836     Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3837
3838     DEBUG(dbgs() << "  Splitting store: " << *SI << "\n");
3839
3840     // Check whether we have an already split load.
3841     auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3842     std::vector<LoadInst *> *SplitLoads = nullptr;
3843     if (SplitLoadsMapI != SplitLoadsMap.end()) {
3844       SplitLoads = &SplitLoadsMapI->second;
3845       assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3846              "Too few split loads for the number of splits in the store!");
3847     } else {
3848       DEBUG(dbgs() << "          of load: " << *LI << "\n");
3849     }
3850
3851     uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3852     int Idx = 0, Size = Offsets.Splits.size();
3853     for (;;) {
3854       auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3855       auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
3856
3857       // Either lookup a split load or create one.
3858       LoadInst *PLoad;
3859       if (SplitLoads) {
3860         PLoad = (*SplitLoads)[Idx];
3861       } else {
3862         IRB.SetInsertPoint(BasicBlock::iterator(LI));
3863         PLoad = IRB.CreateAlignedLoad(
3864             getAdjustedPtr(IRB, *DL, LoadBasePtr,
3865                            APInt(DL->getPointerSizeInBits(), PartOffset),
3866                            PartPtrTy, LoadBasePtr->getName() + "."),
3867             getAdjustedAlignment(LI, PartOffset, *DL), /*IsVolatile*/ false,
3868             LI->getName());
3869       }
3870
3871       // And store this partition.
3872       IRB.SetInsertPoint(BasicBlock::iterator(SI));
3873       StoreInst *PStore = IRB.CreateAlignedStore(
3874           PLoad, getAdjustedPtr(IRB, *DL, StoreBasePtr,
3875                                 APInt(DL->getPointerSizeInBits(), PartOffset),
3876                                 PartPtrTy, StoreBasePtr->getName() + "."),
3877           getAdjustedAlignment(SI, PartOffset, *DL), /*IsVolatile*/ false);
3878
3879       // Now build a new slice for the alloca.
3880       NewSlices.push_back(
3881           Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3882                 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
3883                 /*IsSplittable*/ false));
3884       DEBUG(dbgs() << "    new slice [" << NewSlices.back().beginOffset()
3885                    << ", " << NewSlices.back().endOffset() << "): " << *PStore
3886                    << "\n");
3887       if (!SplitLoads) {
3888         DEBUG(dbgs() << "      of split load: " << *PLoad << "\n");
3889       }
3890
3891       // See if we've finished all the splits.
3892       if (Idx >= Size)
3893         break;
3894
3895       // Setup the next partition.
3896       PartOffset = Offsets.Splits[Idx];
3897       ++Idx;
3898       PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3899     }
3900
3901     // We want to immediately iterate on any allocas impacted by splitting
3902     // this load, which is only relevant if it isn't a load of this alloca and
3903     // thus we didn't already split the loads above. We also have to keep track
3904     // of any promotable allocas we split loads on as they can no longer be
3905     // promoted.
3906     if (!SplitLoads) {
3907       if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3908         assert(OtherAI != &AI && "We can't re-split our own alloca!");
3909         ResplitPromotableAllocas.insert(OtherAI);
3910         Worklist.insert(OtherAI);
3911       } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3912                      LoadBasePtr->stripInBoundsOffsets())) {
3913         assert(OtherAI != &AI && "We can't re-split our own alloca!");
3914         Worklist.insert(OtherAI);
3915       }
3916     }
3917
3918     // Mark the original store as dead now that we've split it up and kill its
3919     // slice. Note that we leave the original load in place unless this store
3920     // was its ownly use. It may in turn be split up if it is an alloca load
3921     // for some other alloca, but it may be a normal load. This may introduce
3922     // redundant loads, but where those can be merged the rest of the optimizer
3923     // should handle the merging, and this uncovers SSA splits which is more
3924     // important. In practice, the original loads will almost always be fully
3925     // split and removed eventually, and the splits will be merged by any
3926     // trivial CSE, including instcombine.
3927     if (LI->hasOneUse()) {
3928       assert(*LI->user_begin() == SI && "Single use isn't this store!");
3929       DeadInsts.insert(LI);
3930     }
3931     DeadInsts.insert(SI);
3932     Offsets.S->kill();
3933   }
3934
3935   // Remove the killed slices that have ben pre-split.
3936   AS.erase(std::remove_if(AS.begin(), AS.end(), [](const Slice &S) {
3937     return S.isDead();
3938   }), AS.end());
3939
3940   // Insert our new slices. This will sort and merge them into the sorted
3941   // sequence.
3942   AS.insert(NewSlices);
3943
3944   DEBUG(dbgs() << "  Pre-split slices:\n");
3945 #ifndef NDEBUG
3946   for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3947     DEBUG(AS.print(dbgs(), I, "    "));
3948 #endif
3949
3950   // Finally, don't try to promote any allocas that new require re-splitting.
3951   // They have already been added to the worklist above.
3952   PromotableAllocas.erase(
3953       std::remove_if(
3954           PromotableAllocas.begin(), PromotableAllocas.end(),
3955           [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3956       PromotableAllocas.end());
3957
3958   return true;
3959 }
3960
3961 /// \brief Rewrite an alloca partition's users.
3962 ///
3963 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3964 /// to rewrite uses of an alloca partition to be conducive for SSA value
3965 /// promotion. If the partition needs a new, more refined alloca, this will
3966 /// build that new alloca, preserving as much type information as possible, and
3967 /// rewrite the uses of the old alloca to point at the new one and have the
3968 /// appropriate new offsets. It also evaluates how successful the rewrite was
3969 /// at enabling promotion and if it was successful queues the alloca to be
3970 /// promoted.
3971 AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
3972                                    AllocaSlices::Partition &P) {
3973   // Try to compute a friendly type for this partition of the alloca. This
3974   // won't always succeed, in which case we fall back to a legal integer type
3975   // or an i8 array of an appropriate size.
3976   Type *SliceTy = nullptr;
3977   if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
3978     if (DL->getTypeAllocSize(CommonUseTy) >= P.size())
3979       SliceTy = CommonUseTy;
3980   if (!SliceTy)
3981     if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
3982                                                  P.beginOffset(), P.size()))
3983       SliceTy = TypePartitionTy;
3984   if ((!SliceTy || (SliceTy->isArrayTy() &&
3985                     SliceTy->getArrayElementType()->isIntegerTy())) &&
3986       DL->isLegalInteger(P.size() * 8))
3987     SliceTy = Type::getIntNTy(*C, P.size() * 8);
3988   if (!SliceTy)
3989     SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
3990   assert(DL->getTypeAllocSize(SliceTy) >= P.size());
3991
3992   bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, *DL);
3993
3994   VectorType *VecTy =
3995       IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, *DL);
3996   if (VecTy)
3997     SliceTy = VecTy;
3998
3999   // Check for the case where we're going to rewrite to a new alloca of the
4000   // exact same type as the original, and with the same access offsets. In that
4001   // case, re-use the existing alloca, but still run through the rewriter to
4002   // perform phi and select speculation.
4003   AllocaInst *NewAI;
4004   if (SliceTy == AI.getAllocatedType()) {
4005     assert(P.beginOffset() == 0 &&
4006            "Non-zero begin offset but same alloca type");
4007     NewAI = &AI;
4008     // FIXME: We should be able to bail at this point with "nothing changed".
4009     // FIXME: We might want to defer PHI speculation until after here.
4010     // FIXME: return nullptr;
4011   } else {
4012     unsigned Alignment = AI.getAlignment();
4013     if (!Alignment) {
4014       // The minimum alignment which users can rely on when the explicit
4015       // alignment is omitted or zero is that required by the ABI for this
4016       // type.
4017       Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
4018     }
4019     Alignment = MinAlign(Alignment, P.beginOffset());
4020     // If we will get at least this much alignment from the type alone, leave
4021     // the alloca's alignment unconstrained.
4022     if (Alignment <= DL->getABITypeAlignment(SliceTy))
4023       Alignment = 0;
4024     NewAI = new AllocaInst(
4025         SliceTy, nullptr, Alignment,
4026         AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
4027     ++NumNewAllocas;
4028   }
4029
4030   DEBUG(dbgs() << "Rewriting alloca partition "
4031                << "[" << P.beginOffset() << "," << P.endOffset()
4032                << ") to: " << *NewAI << "\n");
4033
4034   // Track the high watermark on the worklist as it is only relevant for
4035   // promoted allocas. We will reset it to this point if the alloca is not in
4036   // fact scheduled for promotion.
4037   unsigned PPWOldSize = PostPromotionWorklist.size();
4038   unsigned NumUses = 0;
4039   SmallPtrSet<PHINode *, 8> PHIUsers;
4040   SmallPtrSet<SelectInst *, 8> SelectUsers;
4041
4042   AllocaSliceRewriter Rewriter(*DL, AS, *this, AI, *NewAI, P.beginOffset(),
4043                                P.endOffset(), IsIntegerPromotable, VecTy,
4044                                PHIUsers, SelectUsers);
4045   bool Promotable = true;
4046   for (Slice *S : P.splitSliceTails()) {
4047     Promotable &= Rewriter.visit(S);
4048     ++NumUses;
4049   }
4050   for (Slice &S : P) {
4051     Promotable &= Rewriter.visit(&S);
4052     ++NumUses;
4053   }
4054
4055   NumAllocaPartitionUses += NumUses;
4056   MaxUsesPerAllocaPartition =
4057       std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
4058
4059   // Now that we've processed all the slices in the new partition, check if any
4060   // PHIs or Selects would block promotion.
4061   for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
4062                                             E = PHIUsers.end();
4063        I != E; ++I)
4064     if (!isSafePHIToSpeculate(**I, DL)) {
4065       Promotable = false;
4066       PHIUsers.clear();
4067       SelectUsers.clear();
4068       break;
4069     }
4070   for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
4071                                                E = SelectUsers.end();
4072        I != E; ++I)
4073     if (!isSafeSelectToSpeculate(**I, DL)) {
4074       Promotable = false;
4075       PHIUsers.clear();
4076       SelectUsers.clear();
4077       break;
4078     }
4079
4080   if (Promotable) {
4081     if (PHIUsers.empty() && SelectUsers.empty()) {
4082       // Promote the alloca.
4083       PromotableAllocas.push_back(NewAI);
4084     } else {
4085       // If we have either PHIs or Selects to speculate, add them to those
4086       // worklists and re-queue the new alloca so that we promote in on the
4087       // next iteration.
4088       for (PHINode *PHIUser : PHIUsers)
4089         SpeculatablePHIs.insert(PHIUser);
4090       for (SelectInst *SelectUser : SelectUsers)
4091         SpeculatableSelects.insert(SelectUser);
4092       Worklist.insert(NewAI);
4093     }
4094   } else {
4095     // If we can't promote the alloca, iterate on it to check for new
4096     // refinements exposed by splitting the current alloca. Don't iterate on an
4097     // alloca which didn't actually change and didn't get promoted.
4098     if (NewAI != &AI)
4099       Worklist.insert(NewAI);
4100
4101     // Drop any post-promotion work items if promotion didn't happen.
4102     while (PostPromotionWorklist.size() > PPWOldSize)
4103       PostPromotionWorklist.pop_back();
4104   }
4105
4106   return NewAI;
4107 }
4108
4109 /// \brief Walks the slices of an alloca and form partitions based on them,
4110 /// rewriting each of their uses.
4111 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4112   if (AS.begin() == AS.end())
4113     return false;
4114
4115   unsigned NumPartitions = 0;
4116   bool Changed = false;
4117
4118   // First try to pre-split loads and stores.
4119   Changed |= presplitLoadsAndStores(AI, AS);
4120
4121   // Now that we have identified any pre-splitting opportunities, mark any
4122   // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
4123   // to split these during pre-splitting, we want to force them to be
4124   // rewritten into a partition.
4125   bool IsSorted = true;
4126   for (Slice &S : AS) {
4127     if (!S.isSplittable())
4128       continue;
4129     // FIXME: We currently leave whole-alloca splittable loads and stores. This
4130     // used to be the only splittable loads and stores and we need to be
4131     // confident that the above handling of splittable loads and stores is
4132     // completely sufficient before we forcibly disable the remaining handling.
4133     if (S.beginOffset() == 0 &&
4134         S.endOffset() >= DL->getTypeAllocSize(AI.getAllocatedType()))
4135       continue;
4136     if (isa<LoadInst>(S.getUse()->getUser()) ||
4137         isa<StoreInst>(S.getUse()->getUser())) {
4138       S.makeUnsplittable();
4139       IsSorted = false;
4140     }
4141   }
4142   if (!IsSorted)
4143     std::sort(AS.begin(), AS.end());
4144
4145   /// \brief Describes the allocas introduced by rewritePartition
4146   /// in order to migrate the debug info.
4147   struct Piece {
4148     AllocaInst *Alloca;
4149     uint64_t Offset;
4150     uint64_t Size;
4151     Piece(AllocaInst *AI, uint64_t O, uint64_t S)
4152       : Alloca(AI), Offset(O), Size(S) {}
4153   };
4154   SmallVector<Piece, 4> Pieces;
4155
4156   // Rewrite each partition.
4157   for (auto &P : AS.partitions()) {
4158     if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4159       Changed = true;
4160       if (NewAI != &AI)
4161         Pieces.push_back(Piece(NewAI, P.beginOffset(), P.size()));
4162     }
4163     ++NumPartitions;
4164   }
4165
4166   NumAllocaPartitions += NumPartitions;
4167   MaxPartitionsPerAlloca =
4168       std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
4169
4170   // Migrate debug information from the old alloca to the new alloca(s)
4171   // and the individial partitions.
4172   if (DbgDeclareInst *DbgDecl = DbgDeclares.lookup(&AI)) {
4173     DIVariable Var(DbgDecl->getVariable());
4174     DIExpression Expr(DbgDecl->getExpression());
4175     DIBuilder DIB(*AI.getParent()->getParent()->getParent(),
4176                   /*AllowUnresolved*/ false);
4177     bool IsSplit = Pieces.size() > 1;
4178     for (auto Piece : Pieces) {
4179       // Create a piece expression describing the new partition or reuse AI's
4180       // expression if there is only one partition.
4181       if (IsSplit)
4182         Expr = DIB.createPieceExpression(Piece.Offset, Piece.Size);
4183       Instruction *NewDDI = DIB.insertDeclare(Piece.Alloca, Var, Expr, &AI);
4184       NewDDI->setDebugLoc(DbgDecl->getDebugLoc());
4185       assert((!DbgDeclares.count(Piece.Alloca) ||
4186               DbgDeclares[Piece.Alloca] == cast<DbgDeclareInst>(NewDDI)
4187              ) && "alloca already described");
4188       DbgDeclares.insert(std::make_pair(Piece.Alloca,
4189                                         cast<DbgDeclareInst>(NewDDI)));
4190     }
4191   }
4192   return Changed;
4193 }
4194
4195 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
4196 void SROA::clobberUse(Use &U) {
4197   Value *OldV = U;
4198   // Replace the use with an undef value.
4199   U = UndefValue::get(OldV->getType());
4200
4201   // Check for this making an instruction dead. We have to garbage collect
4202   // all the dead instructions to ensure the uses of any alloca end up being
4203   // minimal.
4204   if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4205     if (isInstructionTriviallyDead(OldI)) {
4206       DeadInsts.insert(OldI);
4207     }
4208 }
4209
4210 /// \brief Analyze an alloca for SROA.
4211 ///
4212 /// This analyzes the alloca to ensure we can reason about it, builds
4213 /// the slices of the alloca, and then hands it off to be split and
4214 /// rewritten as needed.
4215 bool SROA::runOnAlloca(AllocaInst &AI) {
4216   DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4217   ++NumAllocasAnalyzed;
4218
4219   // Special case dead allocas, as they're trivial.
4220   if (AI.use_empty()) {
4221     AI.eraseFromParent();
4222     return true;
4223   }
4224
4225   // Skip alloca forms that this analysis can't handle.
4226   if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
4227       DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
4228     return false;
4229
4230   bool Changed = false;
4231
4232   // First, split any FCA loads and stores touching this alloca to promote
4233   // better splitting and promotion opportunities.
4234   AggLoadStoreRewriter AggRewriter(*DL);
4235   Changed |= AggRewriter.rewrite(AI);
4236
4237   // Build the slices using a recursive instruction-visiting builder.
4238   AllocaSlices AS(*DL, AI);
4239   DEBUG(AS.print(dbgs()));
4240   if (AS.isEscaped())
4241     return Changed;
4242
4243   // Delete all the dead users of this alloca before splitting and rewriting it.
4244   for (Instruction *DeadUser : AS.getDeadUsers()) {
4245     // Free up everything used by this instruction.
4246     for (Use &DeadOp : DeadUser->operands())
4247       clobberUse(DeadOp);
4248
4249     // Now replace the uses of this instruction.
4250     DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
4251
4252     // And mark it for deletion.
4253     DeadInsts.insert(DeadUser);
4254     Changed = true;
4255   }
4256   for (Use *DeadOp : AS.getDeadOperands()) {
4257     clobberUse(*DeadOp);
4258     Changed = true;
4259   }
4260
4261   // No slices to split. Leave the dead alloca for a later pass to clean up.
4262   if (AS.begin() == AS.end())
4263     return Changed;
4264
4265   Changed |= splitAlloca(AI, AS);
4266
4267   DEBUG(dbgs() << "  Speculating PHIs\n");
4268   while (!SpeculatablePHIs.empty())
4269     speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4270
4271   DEBUG(dbgs() << "  Speculating Selects\n");
4272   while (!SpeculatableSelects.empty())
4273     speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4274
4275   return Changed;
4276 }
4277
4278 /// \brief Delete the dead instructions accumulated in this run.
4279 ///
4280 /// Recursively deletes the dead instructions we've accumulated. This is done
4281 /// at the very end to maximize locality of the recursive delete and to
4282 /// minimize the problems of invalidated instruction pointers as such pointers
4283 /// are used heavily in the intermediate stages of the algorithm.
4284 ///
4285 /// We also record the alloca instructions deleted here so that they aren't
4286 /// subsequently handed to mem2reg to promote.
4287 void SROA::deleteDeadInstructions(
4288     SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
4289   while (!DeadInsts.empty()) {
4290     Instruction *I = DeadInsts.pop_back_val();
4291     DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4292
4293     I->replaceAllUsesWith(UndefValue::get(I->getType()));
4294
4295     for (Use &Operand : I->operands())
4296       if (Instruction *U = dyn_cast<Instruction>(Operand)) {
4297         // Zero out the operand and see if it becomes trivially dead.
4298         Operand = nullptr;
4299         if (isInstructionTriviallyDead(U))
4300           DeadInsts.insert(U);
4301       }
4302
4303     if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4304       DeletedAllocas.insert(AI);
4305       if (DbgDeclareInst *DbgDecl = DbgDeclares.lookup(AI)) {
4306         DbgDecl->eraseFromParent();
4307         DbgDeclares.erase(AI);
4308       }
4309     }
4310
4311     ++NumDeleted;
4312     I->eraseFromParent();
4313   }
4314 }
4315
4316 static void enqueueUsersInWorklist(Instruction &I,
4317                                    SmallVectorImpl<Instruction *> &Worklist,
4318                                    SmallPtrSetImpl<Instruction *> &Visited) {
4319   for (User *U : I.users())
4320     if (Visited.insert(cast<Instruction>(U)).second)
4321       Worklist.push_back(cast<Instruction>(U));
4322 }
4323
4324 /// \brief Promote the allocas, using the best available technique.
4325 ///
4326 /// This attempts to promote whatever allocas have been identified as viable in
4327 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
4328 /// If there is a domtree available, we attempt to promote using the full power
4329 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
4330 /// based on the SSAUpdater utilities. This function returns whether any
4331 /// promotion occurred.
4332 bool SROA::promoteAllocas(Function &F) {
4333   if (PromotableAllocas.empty())
4334     return false;
4335
4336   NumPromoted += PromotableAllocas.size();
4337
4338   if (DT && !ForceSSAUpdater) {
4339     DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
4340     PromoteMemToReg(PromotableAllocas, *DT, nullptr, AC);
4341     PromotableAllocas.clear();
4342     return true;
4343   }
4344
4345   DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
4346   SSAUpdater SSA;
4347   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
4348   SmallVector<Instruction *, 64> Insts;
4349
4350   // We need a worklist to walk the uses of each alloca.
4351   SmallVector<Instruction *, 8> Worklist;
4352   SmallPtrSet<Instruction *, 8> Visited;
4353   SmallVector<Instruction *, 32> DeadInsts;
4354
4355   for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
4356     AllocaInst *AI = PromotableAllocas[Idx];
4357     Insts.clear();
4358     Worklist.clear();
4359     Visited.clear();
4360
4361     enqueueUsersInWorklist(*AI, Worklist, Visited);
4362
4363     while (!Worklist.empty()) {
4364       Instruction *I = Worklist.pop_back_val();
4365
4366       // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
4367       // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
4368       // leading to them) here. Eventually it should use them to optimize the
4369       // scalar values produced.
4370       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
4371         assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
4372                II->getIntrinsicID() == Intrinsic::lifetime_end);
4373         II->eraseFromParent();
4374         continue;
4375       }
4376
4377       // Push the loads and stores we find onto the list. SROA will already
4378       // have validated that all loads and stores are viable candidates for
4379       // promotion.
4380       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4381         assert(LI->getType() == AI->getAllocatedType());
4382         Insts.push_back(LI);
4383         continue;
4384       }
4385       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
4386         assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
4387         Insts.push_back(SI);
4388         continue;
4389       }
4390
4391       // For everything else, we know that only no-op bitcasts and GEPs will
4392       // make it this far, just recurse through them and recall them for later
4393       // removal.
4394       DeadInsts.push_back(I);
4395       enqueueUsersInWorklist(*I, Worklist, Visited);
4396     }
4397     AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
4398     while (!DeadInsts.empty())
4399       DeadInsts.pop_back_val()->eraseFromParent();
4400     AI->eraseFromParent();
4401   }
4402
4403   PromotableAllocas.clear();
4404   return true;
4405 }
4406
4407 bool SROA::runOnFunction(Function &F) {
4408   if (skipOptnoneFunction(F))
4409     return false;
4410
4411   DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4412   C = &F.getContext();
4413   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
4414   if (!DLP) {
4415     DEBUG(dbgs() << "  Skipping SROA -- no target data!\n");
4416     return false;
4417   }
4418   DL = &DLP->getDataLayout();
4419   DominatorTreeWrapperPass *DTWP =
4420       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
4421   DT = DTWP ? &DTWP->getDomTree() : nullptr;
4422   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4423
4424   DbgDeclares.clear();
4425   BasicBlock &EntryBB = F.getEntryBlock();
4426   for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
4427        I != E; ++I) {
4428     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4429       Worklist.insert(AI);
4430     else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
4431       if (auto AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress()))
4432         DbgDeclares.insert(std::make_pair(AI, DDI));
4433   }
4434
4435   bool Changed = false;
4436   // A set of deleted alloca instruction pointers which should be removed from
4437   // the list of promotable allocas.
4438   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4439
4440   do {
4441     while (!Worklist.empty()) {
4442       Changed |= runOnAlloca(*Worklist.pop_back_val());
4443       deleteDeadInstructions(DeletedAllocas);
4444
4445       // Remove the deleted allocas from various lists so that we don't try to
4446       // continue processing them.
4447       if (!DeletedAllocas.empty()) {
4448         auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
4449         Worklist.remove_if(IsInSet);
4450         PostPromotionWorklist.remove_if(IsInSet);
4451         PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
4452                                                PromotableAllocas.end(),
4453                                                IsInSet),
4454                                 PromotableAllocas.end());
4455         DeletedAllocas.clear();
4456       }
4457     }
4458
4459     Changed |= promoteAllocas(F);
4460
4461     Worklist = PostPromotionWorklist;
4462     PostPromotionWorklist.clear();
4463   } while (!Worklist.empty());
4464
4465   return Changed;
4466 }
4467
4468 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
4469   AU.addRequired<AssumptionCacheTracker>();
4470   if (RequiresDomTree)
4471     AU.addRequired<DominatorTreeWrapperPass>();
4472   AU.setPreservesCFG();
4473 }