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