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