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