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