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