OSDN Git Service

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