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