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