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