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 
getNameWithPrefix(const Twine & Name) const125   const Twine getNameWithPrefix(const Twine &Name) const {
126     return Name.isTriviallyEmpty() ? Name : Prefix + Name;
127   }
128 
129 public:
SetNamePrefix(const Twine & P)130   void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
131 
InsertHelper(Instruction * I,const Twine & Name,BasicBlock * BB,BasicBlock::iterator InsertPt) const132   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 
Slice(uint64_t BeginOffset,uint64_t EndOffset,Use * U,bool IsSplittable)162   Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
163       : BeginOffset(BeginOffset), EndOffset(EndOffset),
164         UseAndIsSplittable(U, IsSplittable) {}
165 
beginOffset() const166   uint64_t beginOffset() const { return BeginOffset; }
endOffset() const167   uint64_t endOffset() const { return EndOffset; }
168 
isSplittable() const169   bool isSplittable() const { return UseAndIsSplittable.getInt(); }
makeUnsplittable()170   void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
171 
getUse() const172   Use *getUse() const { return UseAndIsSplittable.getPointer(); }
173 
isDead() const174   bool isDead() const { return getUse() == nullptr; }
kill()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.
operator <(const Slice & RHS) const183   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.
operator <(const Slice & LHS,uint64_t RHSOffset)196   friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
197                                               uint64_t RHSOffset) {
198     return LHS.beginOffset() < RHSOffset;
199   }
operator <(uint64_t LHSOffset,const Slice & RHS)200   friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
201                                               const Slice &RHS) {
202     return LHSOffset < RHS.beginOffset();
203   }
204 
operator ==(const Slice & RHS) const205   bool operator==(const Slice &RHS) const {
206     return isSplittable() == RHS.isSplittable() &&
207            beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
208   }
operator !=(const Slice & RHS) const209   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.
isEscaped() const230   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 
begin()237   iterator begin() { return Slices.begin(); }
end()238   iterator end() { return Slices.end(); }
239 
240   using const_iterator = SmallVectorImpl<Slice>::const_iterator;
241   using const_range = iterator_range<const_iterator>;
242 
begin() const243   const_iterator begin() const { return Slices.begin(); }
end() const244   const_iterator end() const { return Slices.end(); }
245   /// @}
246 
247   /// Erase a range of slices.
erase(iterator Start,iterator Stop)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.
insert(ArrayRef<Slice> NewSlices)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.
getDeadUsers() const269   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.
getDeadOperands() const277   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.
Partition(iterator SI)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.
beginOffset() const370   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.
endOffset() const375   uint64_t endOffset() const { return EndOffset; }
376 
377   /// The size of the partition.
378   ///
379   /// Note that this can never be zero.
size() const380   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.
empty() const387   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.
begin() const398   iterator begin() const { return SI; }
end() const399   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.
splitSliceTails() const407   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.
partition_iterator(AllocaSlices::iterator SI,AllocaSlices::iterator SE)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.
advance()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:
operator ==(const partition_iterator & RHS) const572   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 
operator ++()592   partition_iterator &operator++() {
593     advance();
594     return *this;
595   }
596 
operator *()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.
partitions()607 iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
608   return make_range(partition_iterator(begin(), end()),
609                     partition_iterator(end(), end()));
610 }
611 
foldSelectInst(SelectInst & SI)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.
foldPHINodeOrSelectInst(Instruction & I)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:
SliceBuilder(const DataLayout & DL,AllocaInst & AI,AllocaSlices & AS)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:
markAsDead(Instruction & I)659   void markAsDead(Instruction &I) {
660     if (VisitedDeadInsts.insert(&I).second)
661       AS.DeadUsers.push_back(&I);
662   }
663 
insertUse(Instruction & I,const APInt & Offset,uint64_t Size,bool IsSplittable=false)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 
visitBitCastInst(BitCastInst & BC)700   void visitBitCastInst(BitCastInst &BC) {
701     if (BC.use_empty())
702       return markAsDead(BC);
703 
704     return Base::visitBitCastInst(BC);
705   }
706 
visitAddrSpaceCastInst(AddrSpaceCastInst & ASC)707   void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
708     if (ASC.use_empty())
709       return markAsDead(ASC);
710 
711     return Base::visitAddrSpaceCastInst(ASC);
712   }
713 
visitGetElementPtrInst(GetElementPtrInst & GEPI)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 
handleLoadOrStore(Type * Ty,Instruction & I,const APInt & Offset,uint64_t Size,bool IsVolatile)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 
visitLoadInst(LoadInst & LI)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 
visitStoreInst(StoreInst & SI)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 
visitMemSetInst(MemSetInst & II)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 
visitMemTransferInst(MemTransferInst & II)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.
visitIntrinsicInst(IntrinsicInst & II)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 
hasUnsafePHIOrSelectUse(Instruction * Root,uint64_t & Size)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 
visitPHINodeOrSelectInst(Instruction & I)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 
visitPHINode(PHINode & PN)1035   void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
1036 
visitSelectInst(SelectInst & SI)1037   void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
1038 
1039   /// Disable SROA entirely if there are unhandled users of the alloca.
visitInstruction(Instruction & I)1040   void visitInstruction(Instruction &I) { PI.setAborted(&I); }
1041 };
1042 
AllocaSlices(const DataLayout & DL,AllocaInst & AI)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 
print(raw_ostream & OS,const_iterator I,StringRef Indent) const1071 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 
printSlice(raw_ostream & OS,const_iterator I,StringRef Indent) const1078 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 
printUse(raw_ostream & OS,const_iterator I,StringRef Indent) const1085 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1086                             StringRef Indent) const {
1087   OS << Indent << "  used by: " << *I->getUse()->getUser() << "\n";
1088 }
1089 
print(raw_ostream & OS) const1090 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 
dump(const_iterator I) const1103 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1104   print(dbgs(), I);
1105 }
dump() const1106 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.
findCommonType(AllocaSlices::const_iterator B,AllocaSlices::const_iterator E,uint64_t EndOffset)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
isSafePHIToSpeculate(PHINode & PN)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 
speculatePHINodeLoads(PHINode & PN)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.
isSafeSelectToSpeculate(SelectInst & SI)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 
speculateSelectInstLoads(SelectInst & SI)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.
buildGEP(IRBuilderTy & IRB,Value * BasePtr,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)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.
getNaturalGEPWithType(IRBuilderTy & IRB,const DataLayout & DL,Value * BasePtr,Type * Ty,Type * TargetTy,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)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.
getNaturalGEPRecursively(IRBuilderTy & IRB,const DataLayout & DL,Value * Ptr,Type * Ty,APInt & Offset,Type * TargetTy,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)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(cast<FixedVectorType>(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.
getNaturalGEPWithOffset(IRBuilderTy & IRB,const DataLayout & DL,Value * Ptr,APInt Offset,Type * TargetTy,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)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.
getAdjustedPtr(IRBuilderTy & IRB,const DataLayout & DL,Value * Ptr,APInt Offset,Type * PointerTy,Twine NamePrefix)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.
getAdjustedAlignment(Instruction * I,uint64_t 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.
canConvertValue(const DataLayout & DL,Type * OldTy,Type * NewTy)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.
convertValue(const DataLayout & DL,IRBuilderTy & IRB,Value * V,Type * NewTy)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.
isVectorPromotionViableForSlice(Partition & P,const Slice & S,VectorType * Ty,uint64_t ElementSize,const DataLayout & DL)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 >= cast<FixedVectorType>(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 ||
1808       EndIndex > cast<FixedVectorType>(Ty)->getNumElements())
1809     return false;
1810 
1811   assert(EndIndex > BeginIndex && "Empty vector!");
1812   uint64_t NumElements = EndIndex - BeginIndex;
1813   Type *SliceTy = (NumElements == 1)
1814                       ? Ty->getElementType()
1815                       : FixedVectorType::get(Ty->getElementType(), NumElements);
1816 
1817   Type *SplitIntTy =
1818       Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1819 
1820   Use *U = S.getUse();
1821 
1822   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1823     if (MI->isVolatile())
1824       return false;
1825     if (!S.isSplittable())
1826       return false; // Skip any unsplittable intrinsics.
1827   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1828     if (!II->isLifetimeStartOrEnd())
1829       return false;
1830   } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1831     // Disable vector promotion when there are loads or stores of an FCA.
1832     return false;
1833   } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1834     if (LI->isVolatile())
1835       return false;
1836     Type *LTy = LI->getType();
1837     if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1838       assert(LTy->isIntegerTy());
1839       LTy = SplitIntTy;
1840     }
1841     if (!canConvertValue(DL, SliceTy, LTy))
1842       return false;
1843   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1844     if (SI->isVolatile())
1845       return false;
1846     Type *STy = SI->getValueOperand()->getType();
1847     if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1848       assert(STy->isIntegerTy());
1849       STy = SplitIntTy;
1850     }
1851     if (!canConvertValue(DL, STy, SliceTy))
1852       return false;
1853   } else {
1854     return false;
1855   }
1856 
1857   return true;
1858 }
1859 
1860 /// Test whether the given alloca partitioning and range of slices can be
1861 /// promoted to a vector.
1862 ///
1863 /// This is a quick test to check whether we can rewrite a particular alloca
1864 /// partition (and its newly formed alloca) into a vector alloca with only
1865 /// whole-vector loads and stores such that it could be promoted to a vector
1866 /// SSA value. We only can ensure this for a limited set of operations, and we
1867 /// don't want to do the rewrites unless we are confident that the result will
1868 /// be promotable, so we have an early test here.
isVectorPromotionViable(Partition & P,const DataLayout & DL)1869 static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
1870   // Collect the candidate types for vector-based promotion. Also track whether
1871   // we have different element types.
1872   SmallVector<VectorType *, 4> CandidateTys;
1873   Type *CommonEltTy = nullptr;
1874   bool HaveCommonEltTy = true;
1875   auto CheckCandidateType = [&](Type *Ty) {
1876     if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1877       // Return if bitcast to vectors is different for total size in bits.
1878       if (!CandidateTys.empty()) {
1879         VectorType *V = CandidateTys[0];
1880         if (DL.getTypeSizeInBits(VTy).getFixedSize() !=
1881             DL.getTypeSizeInBits(V).getFixedSize()) {
1882           CandidateTys.clear();
1883           return;
1884         }
1885       }
1886       CandidateTys.push_back(VTy);
1887       if (!CommonEltTy)
1888         CommonEltTy = VTy->getElementType();
1889       else if (CommonEltTy != VTy->getElementType())
1890         HaveCommonEltTy = false;
1891     }
1892   };
1893   // Consider any loads or stores that are the exact size of the slice.
1894   for (const Slice &S : P)
1895     if (S.beginOffset() == P.beginOffset() &&
1896         S.endOffset() == P.endOffset()) {
1897       if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1898         CheckCandidateType(LI->getType());
1899       else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1900         CheckCandidateType(SI->getValueOperand()->getType());
1901     }
1902 
1903   // If we didn't find a vector type, nothing to do here.
1904   if (CandidateTys.empty())
1905     return nullptr;
1906 
1907   // Remove non-integer vector types if we had multiple common element types.
1908   // FIXME: It'd be nice to replace them with integer vector types, but we can't
1909   // do that until all the backends are known to produce good code for all
1910   // integer vector types.
1911   if (!HaveCommonEltTy) {
1912     CandidateTys.erase(
1913         llvm::remove_if(CandidateTys,
1914                         [](VectorType *VTy) {
1915                           return !VTy->getElementType()->isIntegerTy();
1916                         }),
1917         CandidateTys.end());
1918 
1919     // If there were no integer vector types, give up.
1920     if (CandidateTys.empty())
1921       return nullptr;
1922 
1923     // Rank the remaining candidate vector types. This is easy because we know
1924     // they're all integer vectors. We sort by ascending number of elements.
1925     auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1926       (void)DL;
1927       assert(DL.getTypeSizeInBits(RHSTy).getFixedSize() ==
1928                  DL.getTypeSizeInBits(LHSTy).getFixedSize() &&
1929              "Cannot have vector types of different sizes!");
1930       assert(RHSTy->getElementType()->isIntegerTy() &&
1931              "All non-integer types eliminated!");
1932       assert(LHSTy->getElementType()->isIntegerTy() &&
1933              "All non-integer types eliminated!");
1934       return cast<FixedVectorType>(RHSTy)->getNumElements() <
1935              cast<FixedVectorType>(LHSTy)->getNumElements();
1936     };
1937     llvm::sort(CandidateTys, RankVectorTypes);
1938     CandidateTys.erase(
1939         std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1940         CandidateTys.end());
1941   } else {
1942 // The only way to have the same element type in every vector type is to
1943 // have the same vector type. Check that and remove all but one.
1944 #ifndef NDEBUG
1945     for (VectorType *VTy : CandidateTys) {
1946       assert(VTy->getElementType() == CommonEltTy &&
1947              "Unaccounted for element type!");
1948       assert(VTy == CandidateTys[0] &&
1949              "Different vector types with the same element type!");
1950     }
1951 #endif
1952     CandidateTys.resize(1);
1953   }
1954 
1955   // Try each vector type, and return the one which works.
1956   auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1957     uint64_t ElementSize =
1958         DL.getTypeSizeInBits(VTy->getElementType()).getFixedSize();
1959 
1960     // While the definition of LLVM vectors is bitpacked, we don't support sizes
1961     // that aren't byte sized.
1962     if (ElementSize % 8)
1963       return false;
1964     assert((DL.getTypeSizeInBits(VTy).getFixedSize() % 8) == 0 &&
1965            "vector size not a multiple of element size?");
1966     ElementSize /= 8;
1967 
1968     for (const Slice &S : P)
1969       if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
1970         return false;
1971 
1972     for (const Slice *S : P.splitSliceTails())
1973       if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
1974         return false;
1975 
1976     return true;
1977   };
1978   for (VectorType *VTy : CandidateTys)
1979     if (CheckVectorTypeForPromotion(VTy))
1980       return VTy;
1981 
1982   return nullptr;
1983 }
1984 
1985 /// Test whether a slice of an alloca is valid for integer widening.
1986 ///
1987 /// This implements the necessary checking for the \c isIntegerWideningViable
1988 /// test below on a single slice of the alloca.
isIntegerWideningViableForSlice(const Slice & S,uint64_t AllocBeginOffset,Type * AllocaTy,const DataLayout & DL,bool & WholeAllocaOp)1989 static bool isIntegerWideningViableForSlice(const Slice &S,
1990                                             uint64_t AllocBeginOffset,
1991                                             Type *AllocaTy,
1992                                             const DataLayout &DL,
1993                                             bool &WholeAllocaOp) {
1994   uint64_t Size = DL.getTypeStoreSize(AllocaTy).getFixedSize();
1995 
1996   uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1997   uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
1998 
1999   // We can't reasonably handle cases where the load or store extends past
2000   // the end of the alloca's type and into its padding.
2001   if (RelEnd > Size)
2002     return false;
2003 
2004   Use *U = S.getUse();
2005 
2006   if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2007     if (LI->isVolatile())
2008       return false;
2009     // We can't handle loads that extend past the allocated memory.
2010     if (DL.getTypeStoreSize(LI->getType()).getFixedSize() > Size)
2011       return false;
2012     // So far, AllocaSliceRewriter does not support widening split slice tails
2013     // in rewriteIntegerLoad.
2014     if (S.beginOffset() < AllocBeginOffset)
2015       return false;
2016     // Note that we don't count vector loads or stores as whole-alloca
2017     // operations which enable integer widening because we would prefer to use
2018     // vector widening instead.
2019     if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
2020       WholeAllocaOp = true;
2021     if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2022       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedSize())
2023         return false;
2024     } else if (RelBegin != 0 || RelEnd != Size ||
2025                !canConvertValue(DL, AllocaTy, LI->getType())) {
2026       // Non-integer loads need to be convertible from the alloca type so that
2027       // they are promotable.
2028       return false;
2029     }
2030   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2031     Type *ValueTy = SI->getValueOperand()->getType();
2032     if (SI->isVolatile())
2033       return false;
2034     // We can't handle stores that extend past the allocated memory.
2035     if (DL.getTypeStoreSize(ValueTy).getFixedSize() > Size)
2036       return false;
2037     // So far, AllocaSliceRewriter does not support widening split slice tails
2038     // in rewriteIntegerStore.
2039     if (S.beginOffset() < AllocBeginOffset)
2040       return false;
2041     // Note that we don't count vector loads or stores as whole-alloca
2042     // operations which enable integer widening because we would prefer to use
2043     // vector widening instead.
2044     if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
2045       WholeAllocaOp = true;
2046     if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2047       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedSize())
2048         return false;
2049     } else if (RelBegin != 0 || RelEnd != Size ||
2050                !canConvertValue(DL, ValueTy, AllocaTy)) {
2051       // Non-integer stores need to be convertible to the alloca type so that
2052       // they are promotable.
2053       return false;
2054     }
2055   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2056     if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2057       return false;
2058     if (!S.isSplittable())
2059       return false; // Skip any unsplittable intrinsics.
2060   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2061     if (!II->isLifetimeStartOrEnd())
2062       return false;
2063   } else {
2064     return false;
2065   }
2066 
2067   return true;
2068 }
2069 
2070 /// Test whether the given alloca partition's integer operations can be
2071 /// widened to promotable ones.
2072 ///
2073 /// This is a quick test to check whether we can rewrite the integer loads and
2074 /// stores to a particular alloca into wider loads and stores and be able to
2075 /// promote the resulting alloca.
isIntegerWideningViable(Partition & P,Type * AllocaTy,const DataLayout & DL)2076 static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
2077                                     const DataLayout &DL) {
2078   uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy).getFixedSize();
2079   // Don't create integer types larger than the maximum bitwidth.
2080   if (SizeInBits > IntegerType::MAX_INT_BITS)
2081     return false;
2082 
2083   // Don't try to handle allocas with bit-padding.
2084   if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy).getFixedSize())
2085     return false;
2086 
2087   // We need to ensure that an integer type with the appropriate bitwidth can
2088   // be converted to the alloca type, whatever that is. We don't want to force
2089   // the alloca itself to have an integer type if there is a more suitable one.
2090   Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2091   if (!canConvertValue(DL, AllocaTy, IntTy) ||
2092       !canConvertValue(DL, IntTy, AllocaTy))
2093     return false;
2094 
2095   // While examining uses, we ensure that the alloca has a covering load or
2096   // store. We don't want to widen the integer operations only to fail to
2097   // promote due to some other unsplittable entry (which we may make splittable
2098   // later). However, if there are only splittable uses, go ahead and assume
2099   // that we cover the alloca.
2100   // FIXME: We shouldn't consider split slices that happen to start in the
2101   // partition here...
2102   bool WholeAllocaOp =
2103       P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
2104 
2105   for (const Slice &S : P)
2106     if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2107                                          WholeAllocaOp))
2108       return false;
2109 
2110   for (const Slice *S : P.splitSliceTails())
2111     if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2112                                          WholeAllocaOp))
2113       return false;
2114 
2115   return WholeAllocaOp;
2116 }
2117 
extractInteger(const DataLayout & DL,IRBuilderTy & IRB,Value * V,IntegerType * Ty,uint64_t Offset,const Twine & Name)2118 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2119                              IntegerType *Ty, uint64_t Offset,
2120                              const Twine &Name) {
2121   LLVM_DEBUG(dbgs() << "       start: " << *V << "\n");
2122   IntegerType *IntTy = cast<IntegerType>(V->getType());
2123   assert(DL.getTypeStoreSize(Ty).getFixedSize() + Offset <=
2124              DL.getTypeStoreSize(IntTy).getFixedSize() &&
2125          "Element extends past full value");
2126   uint64_t ShAmt = 8 * Offset;
2127   if (DL.isBigEndian())
2128     ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedSize() -
2129                  DL.getTypeStoreSize(Ty).getFixedSize() - Offset);
2130   if (ShAmt) {
2131     V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2132     LLVM_DEBUG(dbgs() << "     shifted: " << *V << "\n");
2133   }
2134   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2135          "Cannot extract to a larger integer!");
2136   if (Ty != IntTy) {
2137     V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2138     LLVM_DEBUG(dbgs() << "     trunced: " << *V << "\n");
2139   }
2140   return V;
2141 }
2142 
insertInteger(const DataLayout & DL,IRBuilderTy & IRB,Value * Old,Value * V,uint64_t Offset,const Twine & Name)2143 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2144                             Value *V, uint64_t Offset, const Twine &Name) {
2145   IntegerType *IntTy = cast<IntegerType>(Old->getType());
2146   IntegerType *Ty = cast<IntegerType>(V->getType());
2147   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2148          "Cannot insert a larger integer!");
2149   LLVM_DEBUG(dbgs() << "       start: " << *V << "\n");
2150   if (Ty != IntTy) {
2151     V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2152     LLVM_DEBUG(dbgs() << "    extended: " << *V << "\n");
2153   }
2154   assert(DL.getTypeStoreSize(Ty).getFixedSize() + Offset <=
2155              DL.getTypeStoreSize(IntTy).getFixedSize() &&
2156          "Element store outside of alloca store");
2157   uint64_t ShAmt = 8 * Offset;
2158   if (DL.isBigEndian())
2159     ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedSize() -
2160                  DL.getTypeStoreSize(Ty).getFixedSize() - Offset);
2161   if (ShAmt) {
2162     V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2163     LLVM_DEBUG(dbgs() << "     shifted: " << *V << "\n");
2164   }
2165 
2166   if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2167     APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2168     Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2169     LLVM_DEBUG(dbgs() << "      masked: " << *Old << "\n");
2170     V = IRB.CreateOr(Old, V, Name + ".insert");
2171     LLVM_DEBUG(dbgs() << "    inserted: " << *V << "\n");
2172   }
2173   return V;
2174 }
2175 
extractVector(IRBuilderTy & IRB,Value * V,unsigned BeginIndex,unsigned EndIndex,const Twine & Name)2176 static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2177                             unsigned EndIndex, const Twine &Name) {
2178   auto *VecTy = cast<FixedVectorType>(V->getType());
2179   unsigned NumElements = EndIndex - BeginIndex;
2180   assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2181 
2182   if (NumElements == VecTy->getNumElements())
2183     return V;
2184 
2185   if (NumElements == 1) {
2186     V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2187                                  Name + ".extract");
2188     LLVM_DEBUG(dbgs() << "     extract: " << *V << "\n");
2189     return V;
2190   }
2191 
2192   SmallVector<int, 8> Mask;
2193   Mask.reserve(NumElements);
2194   for (unsigned i = BeginIndex; i != EndIndex; ++i)
2195     Mask.push_back(i);
2196   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()), Mask,
2197                               Name + ".extract");
2198   LLVM_DEBUG(dbgs() << "     shuffle: " << *V << "\n");
2199   return V;
2200 }
2201 
insertVector(IRBuilderTy & IRB,Value * Old,Value * V,unsigned BeginIndex,const Twine & Name)2202 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2203                            unsigned BeginIndex, const Twine &Name) {
2204   VectorType *VecTy = cast<VectorType>(Old->getType());
2205   assert(VecTy && "Can only insert a vector into a vector");
2206 
2207   VectorType *Ty = dyn_cast<VectorType>(V->getType());
2208   if (!Ty) {
2209     // Single element to insert.
2210     V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2211                                 Name + ".insert");
2212     LLVM_DEBUG(dbgs() << "     insert: " << *V << "\n");
2213     return V;
2214   }
2215 
2216   assert(cast<FixedVectorType>(Ty)->getNumElements() <=
2217              cast<FixedVectorType>(VecTy)->getNumElements() &&
2218          "Too many elements!");
2219   if (cast<FixedVectorType>(Ty)->getNumElements() ==
2220       cast<FixedVectorType>(VecTy)->getNumElements()) {
2221     assert(V->getType() == VecTy && "Vector type mismatch");
2222     return V;
2223   }
2224   unsigned EndIndex = BeginIndex + cast<FixedVectorType>(Ty)->getNumElements();
2225 
2226   // When inserting a smaller vector into the larger to store, we first
2227   // use a shuffle vector to widen it with undef elements, and then
2228   // a second shuffle vector to select between the loaded vector and the
2229   // incoming vector.
2230   SmallVector<Constant *, 8> Mask;
2231   Mask.reserve(cast<FixedVectorType>(VecTy)->getNumElements());
2232   for (unsigned i = 0; i != cast<FixedVectorType>(VecTy)->getNumElements(); ++i)
2233     if (i >= BeginIndex && i < EndIndex)
2234       Mask.push_back(IRB.getInt32(i - BeginIndex));
2235     else
2236       Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2237   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2238                               ConstantVector::get(Mask), Name + ".expand");
2239   LLVM_DEBUG(dbgs() << "    shuffle: " << *V << "\n");
2240 
2241   Mask.clear();
2242   for (unsigned i = 0; i != cast<FixedVectorType>(VecTy)->getNumElements(); ++i)
2243     Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2244 
2245   V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2246 
2247   LLVM_DEBUG(dbgs() << "    blend: " << *V << "\n");
2248   return V;
2249 }
2250 
2251 /// Visitor to rewrite instructions using p particular slice of an alloca
2252 /// to use a new alloca.
2253 ///
2254 /// Also implements the rewriting to vector-based accesses when the partition
2255 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2256 /// lives here.
2257 class llvm::sroa::AllocaSliceRewriter
2258     : public InstVisitor<AllocaSliceRewriter, bool> {
2259   // Befriend the base class so it can delegate to private visit methods.
2260   friend class InstVisitor<AllocaSliceRewriter, bool>;
2261 
2262   using Base = InstVisitor<AllocaSliceRewriter, bool>;
2263 
2264   const DataLayout &DL;
2265   AllocaSlices &AS;
2266   SROA &Pass;
2267   AllocaInst &OldAI, &NewAI;
2268   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2269   Type *NewAllocaTy;
2270 
2271   // This is a convenience and flag variable that will be null unless the new
2272   // alloca's integer operations should be widened to this integer type due to
2273   // passing isIntegerWideningViable above. If it is non-null, the desired
2274   // integer type will be stored here for easy access during rewriting.
2275   IntegerType *IntTy;
2276 
2277   // If we are rewriting an alloca partition which can be written as pure
2278   // vector operations, we stash extra information here. When VecTy is
2279   // non-null, we have some strict guarantees about the rewritten alloca:
2280   //   - The new alloca is exactly the size of the vector type here.
2281   //   - The accesses all either map to the entire vector or to a single
2282   //     element.
2283   //   - The set of accessing instructions is only one of those handled above
2284   //     in isVectorPromotionViable. Generally these are the same access kinds
2285   //     which are promotable via mem2reg.
2286   VectorType *VecTy;
2287   Type *ElementTy;
2288   uint64_t ElementSize;
2289 
2290   // The original offset of the slice currently being rewritten relative to
2291   // the original alloca.
2292   uint64_t BeginOffset = 0;
2293   uint64_t EndOffset = 0;
2294 
2295   // The new offsets of the slice currently being rewritten relative to the
2296   // original alloca.
2297   uint64_t NewBeginOffset = 0, NewEndOffset = 0;
2298 
2299   uint64_t SliceSize = 0;
2300   bool IsSplittable = false;
2301   bool IsSplit = false;
2302   Use *OldUse = nullptr;
2303   Instruction *OldPtr = nullptr;
2304 
2305   // Track post-rewrite users which are PHI nodes and Selects.
2306   SmallSetVector<PHINode *, 8> &PHIUsers;
2307   SmallSetVector<SelectInst *, 8> &SelectUsers;
2308 
2309   // Utility IR builder, whose name prefix is setup for each visited use, and
2310   // the insertion point is set to point to the user.
2311   IRBuilderTy IRB;
2312 
2313 public:
AllocaSliceRewriter(const DataLayout & DL,AllocaSlices & AS,SROA & Pass,AllocaInst & OldAI,AllocaInst & NewAI,uint64_t NewAllocaBeginOffset,uint64_t NewAllocaEndOffset,bool IsIntegerPromotable,VectorType * PromotableVecTy,SmallSetVector<PHINode *,8> & PHIUsers,SmallSetVector<SelectInst *,8> & SelectUsers)2314   AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2315                       AllocaInst &OldAI, AllocaInst &NewAI,
2316                       uint64_t NewAllocaBeginOffset,
2317                       uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2318                       VectorType *PromotableVecTy,
2319                       SmallSetVector<PHINode *, 8> &PHIUsers,
2320                       SmallSetVector<SelectInst *, 8> &SelectUsers)
2321       : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2322         NewAllocaBeginOffset(NewAllocaBeginOffset),
2323         NewAllocaEndOffset(NewAllocaEndOffset),
2324         NewAllocaTy(NewAI.getAllocatedType()),
2325         IntTy(
2326             IsIntegerPromotable
2327                 ? Type::getIntNTy(NewAI.getContext(),
2328                                   DL.getTypeSizeInBits(NewAI.getAllocatedType())
2329                                       .getFixedSize())
2330                 : nullptr),
2331         VecTy(PromotableVecTy),
2332         ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2333         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy).getFixedSize() / 8
2334                           : 0),
2335         PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2336         IRB(NewAI.getContext(), ConstantFolder()) {
2337     if (VecTy) {
2338       assert((DL.getTypeSizeInBits(ElementTy).getFixedSize() % 8) == 0 &&
2339              "Only multiple-of-8 sized vector elements are viable");
2340       ++NumVectorized;
2341     }
2342     assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2343   }
2344 
visit(AllocaSlices::const_iterator I)2345   bool visit(AllocaSlices::const_iterator I) {
2346     bool CanSROA = true;
2347     BeginOffset = I->beginOffset();
2348     EndOffset = I->endOffset();
2349     IsSplittable = I->isSplittable();
2350     IsSplit =
2351         BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2352     LLVM_DEBUG(dbgs() << "  rewriting " << (IsSplit ? "split " : ""));
2353     LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
2354     LLVM_DEBUG(dbgs() << "\n");
2355 
2356     // Compute the intersecting offset range.
2357     assert(BeginOffset < NewAllocaEndOffset);
2358     assert(EndOffset > NewAllocaBeginOffset);
2359     NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2360     NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2361 
2362     SliceSize = NewEndOffset - NewBeginOffset;
2363 
2364     OldUse = I->getUse();
2365     OldPtr = cast<Instruction>(OldUse->get());
2366 
2367     Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2368     IRB.SetInsertPoint(OldUserI);
2369     IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2370     IRB.getInserter().SetNamePrefix(
2371         Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2372 
2373     CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2374     if (VecTy || IntTy)
2375       assert(CanSROA);
2376     return CanSROA;
2377   }
2378 
2379 private:
2380   // Make sure the other visit overloads are visible.
2381   using Base::visit;
2382 
2383   // Every instruction which can end up as a user must have a rewrite rule.
visitInstruction(Instruction & I)2384   bool visitInstruction(Instruction &I) {
2385     LLVM_DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
2386     llvm_unreachable("No rewrite rule for this instruction!");
2387   }
2388 
getNewAllocaSlicePtr(IRBuilderTy & IRB,Type * PointerTy)2389   Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2390     // Note that the offset computation can use BeginOffset or NewBeginOffset
2391     // interchangeably for unsplit slices.
2392     assert(IsSplit || BeginOffset == NewBeginOffset);
2393     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2394 
2395 #ifndef NDEBUG
2396     StringRef OldName = OldPtr->getName();
2397     // Skip through the last '.sroa.' component of the name.
2398     size_t LastSROAPrefix = OldName.rfind(".sroa.");
2399     if (LastSROAPrefix != StringRef::npos) {
2400       OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2401       // Look for an SROA slice index.
2402       size_t IndexEnd = OldName.find_first_not_of("0123456789");
2403       if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2404         // Strip the index and look for the offset.
2405         OldName = OldName.substr(IndexEnd + 1);
2406         size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2407         if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2408           // Strip the offset.
2409           OldName = OldName.substr(OffsetEnd + 1);
2410       }
2411     }
2412     // Strip any SROA suffixes as well.
2413     OldName = OldName.substr(0, OldName.find(".sroa_"));
2414 #endif
2415 
2416     return getAdjustedPtr(IRB, DL, &NewAI,
2417                           APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
2418                           PointerTy,
2419 #ifndef NDEBUG
2420                           Twine(OldName) + "."
2421 #else
2422                           Twine()
2423 #endif
2424                           );
2425   }
2426 
2427   /// Compute suitable alignment to access this slice of the *new*
2428   /// alloca.
2429   ///
2430   /// You can optionally pass a type to this routine and if that type's ABI
2431   /// alignment is itself suitable, this will return zero.
getSliceAlign()2432   Align getSliceAlign() {
2433     return commonAlignment(NewAI.getAlign(),
2434                            NewBeginOffset - NewAllocaBeginOffset);
2435   }
2436 
getIndex(uint64_t Offset)2437   unsigned getIndex(uint64_t Offset) {
2438     assert(VecTy && "Can only call getIndex when rewriting a vector");
2439     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2440     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2441     uint32_t Index = RelOffset / ElementSize;
2442     assert(Index * ElementSize == RelOffset);
2443     return Index;
2444   }
2445 
deleteIfTriviallyDead(Value * V)2446   void deleteIfTriviallyDead(Value *V) {
2447     Instruction *I = cast<Instruction>(V);
2448     if (isInstructionTriviallyDead(I))
2449       Pass.DeadInsts.insert(I);
2450   }
2451 
rewriteVectorizedLoadInst()2452   Value *rewriteVectorizedLoadInst() {
2453     unsigned BeginIndex = getIndex(NewBeginOffset);
2454     unsigned EndIndex = getIndex(NewEndOffset);
2455     assert(EndIndex > BeginIndex && "Empty vector!");
2456 
2457     Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2458                                      NewAI.getAlign(), "load");
2459     return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2460   }
2461 
rewriteIntegerLoad(LoadInst & LI)2462   Value *rewriteIntegerLoad(LoadInst &LI) {
2463     assert(IntTy && "We cannot insert an integer to the alloca");
2464     assert(!LI.isVolatile());
2465     Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2466                                      NewAI.getAlign(), "load");
2467     V = convertValue(DL, IRB, V, IntTy);
2468     assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2469     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2470     if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2471       IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2472       V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2473     }
2474     // It is possible that the extracted type is not the load type. This
2475     // happens if there is a load past the end of the alloca, and as
2476     // a consequence the slice is narrower but still a candidate for integer
2477     // lowering. To handle this case, we just zero extend the extracted
2478     // integer.
2479     assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2480            "Can only handle an extract for an overly wide load");
2481     if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2482       V = IRB.CreateZExt(V, LI.getType());
2483     return V;
2484   }
2485 
visitLoadInst(LoadInst & LI)2486   bool visitLoadInst(LoadInst &LI) {
2487     LLVM_DEBUG(dbgs() << "    original: " << LI << "\n");
2488     Value *OldOp = LI.getOperand(0);
2489     assert(OldOp == OldPtr);
2490 
2491     AAMDNodes AATags;
2492     LI.getAAMetadata(AATags);
2493 
2494     unsigned AS = LI.getPointerAddressSpace();
2495 
2496     Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2497                              : LI.getType();
2498     const bool IsLoadPastEnd =
2499         DL.getTypeStoreSize(TargetTy).getFixedSize() > SliceSize;
2500     bool IsPtrAdjusted = false;
2501     Value *V;
2502     if (VecTy) {
2503       V = rewriteVectorizedLoadInst();
2504     } else if (IntTy && LI.getType()->isIntegerTy()) {
2505       V = rewriteIntegerLoad(LI);
2506     } else if (NewBeginOffset == NewAllocaBeginOffset &&
2507                NewEndOffset == NewAllocaEndOffset &&
2508                (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2509                 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2510                  TargetTy->isIntegerTy()))) {
2511       LoadInst *NewLI = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2512                                               NewAI.getAlign(), LI.isVolatile(),
2513                                               LI.getName());
2514       if (AATags)
2515         NewLI->setAAMetadata(AATags);
2516       if (LI.isVolatile())
2517         NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
2518       if (NewLI->isAtomic())
2519         NewLI->setAlignment(LI.getAlign());
2520 
2521       // Any !nonnull metadata or !range metadata on the old load is also valid
2522       // on the new load. This is even true in some cases even when the loads
2523       // are different types, for example by mapping !nonnull metadata to
2524       // !range metadata by modeling the null pointer constant converted to the
2525       // integer type.
2526       // FIXME: Add support for range metadata here. Currently the utilities
2527       // for this don't propagate range metadata in trivial cases from one
2528       // integer load to another, don't handle non-addrspace-0 null pointers
2529       // correctly, and don't have any support for mapping ranges as the
2530       // integer type becomes winder or narrower.
2531       if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2532         copyNonnullMetadata(LI, N, *NewLI);
2533 
2534       // Try to preserve nonnull metadata
2535       V = NewLI;
2536 
2537       // If this is an integer load past the end of the slice (which means the
2538       // bytes outside the slice are undef or this load is dead) just forcibly
2539       // fix the integer size with correct handling of endianness.
2540       if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2541         if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2542           if (AITy->getBitWidth() < TITy->getBitWidth()) {
2543             V = IRB.CreateZExt(V, TITy, "load.ext");
2544             if (DL.isBigEndian())
2545               V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2546                                 "endian_shift");
2547           }
2548     } else {
2549       Type *LTy = TargetTy->getPointerTo(AS);
2550       LoadInst *NewLI =
2551           IRB.CreateAlignedLoad(TargetTy, getNewAllocaSlicePtr(IRB, LTy),
2552                                 getSliceAlign(), LI.isVolatile(), LI.getName());
2553       if (AATags)
2554         NewLI->setAAMetadata(AATags);
2555       if (LI.isVolatile())
2556         NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
2557 
2558       V = NewLI;
2559       IsPtrAdjusted = true;
2560     }
2561     V = convertValue(DL, IRB, V, TargetTy);
2562 
2563     if (IsSplit) {
2564       assert(!LI.isVolatile());
2565       assert(LI.getType()->isIntegerTy() &&
2566              "Only integer type loads and stores are split");
2567       assert(SliceSize < DL.getTypeStoreSize(LI.getType()).getFixedSize() &&
2568              "Split load isn't smaller than original load");
2569       assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&
2570              "Non-byte-multiple bit width");
2571       // Move the insertion point just past the load so that we can refer to it.
2572       IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
2573       // Create a placeholder value with the same type as LI to use as the
2574       // basis for the new value. This allows us to replace the uses of LI with
2575       // the computed value, and then replace the placeholder with LI, leaving
2576       // LI only used for this computation.
2577       Value *Placeholder = new LoadInst(
2578           LI.getType(), UndefValue::get(LI.getType()->getPointerTo(AS)), "",
2579           false, Align(1));
2580       V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2581                         "insert");
2582       LI.replaceAllUsesWith(V);
2583       Placeholder->replaceAllUsesWith(&LI);
2584       Placeholder->deleteValue();
2585     } else {
2586       LI.replaceAllUsesWith(V);
2587     }
2588 
2589     Pass.DeadInsts.insert(&LI);
2590     deleteIfTriviallyDead(OldOp);
2591     LLVM_DEBUG(dbgs() << "          to: " << *V << "\n");
2592     return !LI.isVolatile() && !IsPtrAdjusted;
2593   }
2594 
rewriteVectorizedStoreInst(Value * V,StoreInst & SI,Value * OldOp,AAMDNodes AATags)2595   bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2596                                   AAMDNodes AATags) {
2597     if (V->getType() != VecTy) {
2598       unsigned BeginIndex = getIndex(NewBeginOffset);
2599       unsigned EndIndex = getIndex(NewEndOffset);
2600       assert(EndIndex > BeginIndex && "Empty vector!");
2601       unsigned NumElements = EndIndex - BeginIndex;
2602       assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
2603              "Too many elements!");
2604       Type *SliceTy = (NumElements == 1)
2605                           ? ElementTy
2606                           : FixedVectorType::get(ElementTy, NumElements);
2607       if (V->getType() != SliceTy)
2608         V = convertValue(DL, IRB, V, SliceTy);
2609 
2610       // Mix in the existing elements.
2611       Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2612                                          NewAI.getAlign(), "load");
2613       V = insertVector(IRB, Old, V, BeginIndex, "vec");
2614     }
2615     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
2616     if (AATags)
2617       Store->setAAMetadata(AATags);
2618     Pass.DeadInsts.insert(&SI);
2619 
2620     LLVM_DEBUG(dbgs() << "          to: " << *Store << "\n");
2621     return true;
2622   }
2623 
rewriteIntegerStore(Value * V,StoreInst & SI,AAMDNodes AATags)2624   bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
2625     assert(IntTy && "We cannot extract an integer from the alloca");
2626     assert(!SI.isVolatile());
2627     if (DL.getTypeSizeInBits(V->getType()).getFixedSize() !=
2628         IntTy->getBitWidth()) {
2629       Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2630                                          NewAI.getAlign(), "oldload");
2631       Old = convertValue(DL, IRB, Old, IntTy);
2632       assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2633       uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2634       V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
2635     }
2636     V = convertValue(DL, IRB, V, NewAllocaTy);
2637     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
2638     Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2639                              LLVMContext::MD_access_group});
2640     if (AATags)
2641       Store->setAAMetadata(AATags);
2642     Pass.DeadInsts.insert(&SI);
2643     LLVM_DEBUG(dbgs() << "          to: " << *Store << "\n");
2644     return true;
2645   }
2646 
visitStoreInst(StoreInst & SI)2647   bool visitStoreInst(StoreInst &SI) {
2648     LLVM_DEBUG(dbgs() << "    original: " << SI << "\n");
2649     Value *OldOp = SI.getOperand(1);
2650     assert(OldOp == OldPtr);
2651 
2652     AAMDNodes AATags;
2653     SI.getAAMetadata(AATags);
2654 
2655     Value *V = SI.getValueOperand();
2656 
2657     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2658     // alloca that should be re-examined after promoting this alloca.
2659     if (V->getType()->isPointerTy())
2660       if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2661         Pass.PostPromotionWorklist.insert(AI);
2662 
2663     if (SliceSize < DL.getTypeStoreSize(V->getType()).getFixedSize()) {
2664       assert(!SI.isVolatile());
2665       assert(V->getType()->isIntegerTy() &&
2666              "Only integer type loads and stores are split");
2667       assert(DL.typeSizeEqualsStoreSize(V->getType()) &&
2668              "Non-byte-multiple bit width");
2669       IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2670       V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2671                          "extract");
2672     }
2673 
2674     if (VecTy)
2675       return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
2676     if (IntTy && V->getType()->isIntegerTy())
2677       return rewriteIntegerStore(V, SI, AATags);
2678 
2679     const bool IsStorePastEnd =
2680         DL.getTypeStoreSize(V->getType()).getFixedSize() > SliceSize;
2681     StoreInst *NewSI;
2682     if (NewBeginOffset == NewAllocaBeginOffset &&
2683         NewEndOffset == NewAllocaEndOffset &&
2684         (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2685          (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2686           V->getType()->isIntegerTy()))) {
2687       // If this is an integer store past the end of slice (and thus the bytes
2688       // past that point are irrelevant or this is unreachable), truncate the
2689       // value prior to storing.
2690       if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2691         if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2692           if (VITy->getBitWidth() > AITy->getBitWidth()) {
2693             if (DL.isBigEndian())
2694               V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2695                                  "endian_shift");
2696             V = IRB.CreateTrunc(V, AITy, "load.trunc");
2697           }
2698 
2699       V = convertValue(DL, IRB, V, NewAllocaTy);
2700       NewSI =
2701           IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign(), SI.isVolatile());
2702     } else {
2703       unsigned AS = SI.getPointerAddressSpace();
2704       Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
2705       NewSI =
2706           IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(), SI.isVolatile());
2707     }
2708     NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2709                              LLVMContext::MD_access_group});
2710     if (AATags)
2711       NewSI->setAAMetadata(AATags);
2712     if (SI.isVolatile())
2713       NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
2714     if (NewSI->isAtomic())
2715       NewSI->setAlignment(SI.getAlign());
2716     Pass.DeadInsts.insert(&SI);
2717     deleteIfTriviallyDead(OldOp);
2718 
2719     LLVM_DEBUG(dbgs() << "          to: " << *NewSI << "\n");
2720     return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2721   }
2722 
2723   /// Compute an integer value from splatting an i8 across the given
2724   /// number of bytes.
2725   ///
2726   /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2727   /// call this routine.
2728   /// FIXME: Heed the advice above.
2729   ///
2730   /// \param V The i8 value to splat.
2731   /// \param Size The number of bytes in the output (assuming i8 is one byte)
getIntegerSplat(Value * V,unsigned Size)2732   Value *getIntegerSplat(Value *V, unsigned Size) {
2733     assert(Size > 0 && "Expected a positive number of bytes.");
2734     IntegerType *VTy = cast<IntegerType>(V->getType());
2735     assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2736     if (Size == 1)
2737       return V;
2738 
2739     Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2740     V = IRB.CreateMul(
2741         IRB.CreateZExt(V, SplatIntTy, "zext"),
2742         ConstantExpr::getUDiv(
2743             Constant::getAllOnesValue(SplatIntTy),
2744             ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2745                                   SplatIntTy)),
2746         "isplat");
2747     return V;
2748   }
2749 
2750   /// Compute a vector splat for a given element value.
getVectorSplat(Value * V,unsigned NumElements)2751   Value *getVectorSplat(Value *V, unsigned NumElements) {
2752     V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2753     LLVM_DEBUG(dbgs() << "       splat: " << *V << "\n");
2754     return V;
2755   }
2756 
visitMemSetInst(MemSetInst & II)2757   bool visitMemSetInst(MemSetInst &II) {
2758     LLVM_DEBUG(dbgs() << "    original: " << II << "\n");
2759     assert(II.getRawDest() == OldPtr);
2760 
2761     AAMDNodes AATags;
2762     II.getAAMetadata(AATags);
2763 
2764     // If the memset has a variable size, it cannot be split, just adjust the
2765     // pointer to the new alloca.
2766     if (!isa<Constant>(II.getLength())) {
2767       assert(!IsSplit);
2768       assert(NewBeginOffset == BeginOffset);
2769       II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2770       II.setDestAlignment(getSliceAlign());
2771 
2772       deleteIfTriviallyDead(OldPtr);
2773       return false;
2774     }
2775 
2776     // Record this instruction for deletion.
2777     Pass.DeadInsts.insert(&II);
2778 
2779     Type *AllocaTy = NewAI.getAllocatedType();
2780     Type *ScalarTy = AllocaTy->getScalarType();
2781 
2782     const bool CanContinue = [&]() {
2783       if (VecTy || IntTy)
2784         return true;
2785       if (BeginOffset > NewAllocaBeginOffset ||
2786           EndOffset < NewAllocaEndOffset)
2787         return false;
2788       auto *C = cast<ConstantInt>(II.getLength());
2789       if (C->getBitWidth() > 64)
2790         return false;
2791       const auto Len = C->getZExtValue();
2792       auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
2793       auto *SrcTy = FixedVectorType::get(Int8Ty, Len);
2794       return canConvertValue(DL, SrcTy, AllocaTy) &&
2795              DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy).getFixedSize());
2796     }();
2797 
2798     // If this doesn't map cleanly onto the alloca type, and that type isn't
2799     // a single value type, just emit a memset.
2800     if (!CanContinue) {
2801       Type *SizeTy = II.getLength()->getType();
2802       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2803       CallInst *New = IRB.CreateMemSet(
2804           getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2805           MaybeAlign(getSliceAlign()), II.isVolatile());
2806       if (AATags)
2807         New->setAAMetadata(AATags);
2808       LLVM_DEBUG(dbgs() << "          to: " << *New << "\n");
2809       return false;
2810     }
2811 
2812     // If we can represent this as a simple value, we have to build the actual
2813     // value to store, which requires expanding the byte present in memset to
2814     // a sensible representation for the alloca type. This is essentially
2815     // splatting the byte to a sufficiently wide integer, splatting it across
2816     // any desired vector width, and bitcasting to the final type.
2817     Value *V;
2818 
2819     if (VecTy) {
2820       // If this is a memset of a vectorized alloca, insert it.
2821       assert(ElementTy == ScalarTy);
2822 
2823       unsigned BeginIndex = getIndex(NewBeginOffset);
2824       unsigned EndIndex = getIndex(NewEndOffset);
2825       assert(EndIndex > BeginIndex && "Empty vector!");
2826       unsigned NumElements = EndIndex - BeginIndex;
2827       assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
2828              "Too many elements!");
2829 
2830       Value *Splat = getIntegerSplat(
2831           II.getValue(), DL.getTypeSizeInBits(ElementTy).getFixedSize() / 8);
2832       Splat = convertValue(DL, IRB, Splat, ElementTy);
2833       if (NumElements > 1)
2834         Splat = getVectorSplat(Splat, NumElements);
2835 
2836       Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2837                                          NewAI.getAlign(), "oldload");
2838       V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2839     } else if (IntTy) {
2840       // If this is a memset on an alloca where we can widen stores, insert the
2841       // set integer.
2842       assert(!II.isVolatile());
2843 
2844       uint64_t Size = NewEndOffset - NewBeginOffset;
2845       V = getIntegerSplat(II.getValue(), Size);
2846 
2847       if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2848                     EndOffset != NewAllocaBeginOffset)) {
2849         Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2850                                            NewAI.getAlign(), "oldload");
2851         Old = convertValue(DL, IRB, Old, IntTy);
2852         uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2853         V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2854       } else {
2855         assert(V->getType() == IntTy &&
2856                "Wrong type for an alloca wide integer!");
2857       }
2858       V = convertValue(DL, IRB, V, AllocaTy);
2859     } else {
2860       // Established these invariants above.
2861       assert(NewBeginOffset == NewAllocaBeginOffset);
2862       assert(NewEndOffset == NewAllocaEndOffset);
2863 
2864       V = getIntegerSplat(II.getValue(),
2865                           DL.getTypeSizeInBits(ScalarTy).getFixedSize() / 8);
2866       if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2867         V = getVectorSplat(
2868             V, cast<FixedVectorType>(AllocaVecTy)->getNumElements());
2869 
2870       V = convertValue(DL, IRB, V, AllocaTy);
2871     }
2872 
2873     StoreInst *New =
2874         IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign(), II.isVolatile());
2875     if (AATags)
2876       New->setAAMetadata(AATags);
2877     LLVM_DEBUG(dbgs() << "          to: " << *New << "\n");
2878     return !II.isVolatile();
2879   }
2880 
visitMemTransferInst(MemTransferInst & II)2881   bool visitMemTransferInst(MemTransferInst &II) {
2882     // Rewriting of memory transfer instructions can be a bit tricky. We break
2883     // them into two categories: split intrinsics and unsplit intrinsics.
2884 
2885     LLVM_DEBUG(dbgs() << "    original: " << II << "\n");
2886 
2887     AAMDNodes AATags;
2888     II.getAAMetadata(AATags);
2889 
2890     bool IsDest = &II.getRawDestUse() == OldUse;
2891     assert((IsDest && II.getRawDest() == OldPtr) ||
2892            (!IsDest && II.getRawSource() == OldPtr));
2893 
2894     MaybeAlign SliceAlign = getSliceAlign();
2895 
2896     // For unsplit intrinsics, we simply modify the source and destination
2897     // pointers in place. This isn't just an optimization, it is a matter of
2898     // correctness. With unsplit intrinsics we may be dealing with transfers
2899     // within a single alloca before SROA ran, or with transfers that have
2900     // a variable length. We may also be dealing with memmove instead of
2901     // memcpy, and so simply updating the pointers is the necessary for us to
2902     // update both source and dest of a single call.
2903     if (!IsSplittable) {
2904       Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2905       if (IsDest) {
2906         II.setDest(AdjustedPtr);
2907         II.setDestAlignment(SliceAlign);
2908       }
2909       else {
2910         II.setSource(AdjustedPtr);
2911         II.setSourceAlignment(SliceAlign);
2912       }
2913 
2914       LLVM_DEBUG(dbgs() << "          to: " << II << "\n");
2915       deleteIfTriviallyDead(OldPtr);
2916       return false;
2917     }
2918     // For split transfer intrinsics we have an incredibly useful assurance:
2919     // the source and destination do not reside within the same alloca, and at
2920     // least one of them does not escape. This means that we can replace
2921     // memmove with memcpy, and we don't need to worry about all manner of
2922     // downsides to splitting and transforming the operations.
2923 
2924     // If this doesn't map cleanly onto the alloca type, and that type isn't
2925     // a single value type, just emit a memcpy.
2926     bool EmitMemCpy =
2927         !VecTy && !IntTy &&
2928         (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2929          SliceSize !=
2930              DL.getTypeStoreSize(NewAI.getAllocatedType()).getFixedSize() ||
2931          !NewAI.getAllocatedType()->isSingleValueType());
2932 
2933     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2934     // size hasn't been shrunk based on analysis of the viable range, this is
2935     // a no-op.
2936     if (EmitMemCpy && &OldAI == &NewAI) {
2937       // Ensure the start lines up.
2938       assert(NewBeginOffset == BeginOffset);
2939 
2940       // Rewrite the size as needed.
2941       if (NewEndOffset != EndOffset)
2942         II.setLength(ConstantInt::get(II.getLength()->getType(),
2943                                       NewEndOffset - NewBeginOffset));
2944       return false;
2945     }
2946     // Record this instruction for deletion.
2947     Pass.DeadInsts.insert(&II);
2948 
2949     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2950     // alloca that should be re-examined after rewriting this instruction.
2951     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2952     if (AllocaInst *AI =
2953             dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2954       assert(AI != &OldAI && AI != &NewAI &&
2955              "Splittable transfers cannot reach the same alloca on both ends.");
2956       Pass.Worklist.insert(AI);
2957     }
2958 
2959     Type *OtherPtrTy = OtherPtr->getType();
2960     unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2961 
2962     // Compute the relative offset for the other pointer within the transfer.
2963     unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
2964     APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
2965     Align OtherAlign =
2966         (IsDest ? II.getSourceAlign() : II.getDestAlign()).valueOrOne();
2967     OtherAlign =
2968         commonAlignment(OtherAlign, OtherOffset.zextOrTrunc(64).getZExtValue());
2969 
2970     if (EmitMemCpy) {
2971       // Compute the other pointer, folding as much as possible to produce
2972       // a single, simple GEP in most cases.
2973       OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2974                                 OtherPtr->getName() + ".");
2975 
2976       Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2977       Type *SizeTy = II.getLength()->getType();
2978       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2979 
2980       Value *DestPtr, *SrcPtr;
2981       MaybeAlign DestAlign, SrcAlign;
2982       // Note: IsDest is true iff we're copying into the new alloca slice
2983       if (IsDest) {
2984         DestPtr = OurPtr;
2985         DestAlign = SliceAlign;
2986         SrcPtr = OtherPtr;
2987         SrcAlign = OtherAlign;
2988       } else {
2989         DestPtr = OtherPtr;
2990         DestAlign = OtherAlign;
2991         SrcPtr = OurPtr;
2992         SrcAlign = SliceAlign;
2993       }
2994       CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
2995                                        Size, II.isVolatile());
2996       if (AATags)
2997         New->setAAMetadata(AATags);
2998       LLVM_DEBUG(dbgs() << "          to: " << *New << "\n");
2999       return false;
3000     }
3001 
3002     bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
3003                          NewEndOffset == NewAllocaEndOffset;
3004     uint64_t Size = NewEndOffset - NewBeginOffset;
3005     unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
3006     unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
3007     unsigned NumElements = EndIndex - BeginIndex;
3008     IntegerType *SubIntTy =
3009         IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
3010 
3011     // Reset the other pointer type to match the register type we're going to
3012     // use, but using the address space of the original other pointer.
3013     Type *OtherTy;
3014     if (VecTy && !IsWholeAlloca) {
3015       if (NumElements == 1)
3016         OtherTy = VecTy->getElementType();
3017       else
3018         OtherTy = FixedVectorType::get(VecTy->getElementType(), NumElements);
3019     } else if (IntTy && !IsWholeAlloca) {
3020       OtherTy = SubIntTy;
3021     } else {
3022       OtherTy = NewAllocaTy;
3023     }
3024     OtherPtrTy = OtherTy->getPointerTo(OtherAS);
3025 
3026     Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
3027                                    OtherPtr->getName() + ".");
3028     MaybeAlign SrcAlign = OtherAlign;
3029     Value *DstPtr = &NewAI;
3030     MaybeAlign DstAlign = SliceAlign;
3031     if (!IsDest) {
3032       std::swap(SrcPtr, DstPtr);
3033       std::swap(SrcAlign, DstAlign);
3034     }
3035 
3036     Value *Src;
3037     if (VecTy && !IsWholeAlloca && !IsDest) {
3038       Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3039                                   NewAI.getAlign(), "load");
3040       Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
3041     } else if (IntTy && !IsWholeAlloca && !IsDest) {
3042       Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3043                                   NewAI.getAlign(), "load");
3044       Src = convertValue(DL, IRB, Src, IntTy);
3045       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3046       Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
3047     } else {
3048       LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
3049                                              II.isVolatile(), "copyload");
3050       if (AATags)
3051         Load->setAAMetadata(AATags);
3052       Src = Load;
3053     }
3054 
3055     if (VecTy && !IsWholeAlloca && IsDest) {
3056       Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3057                                          NewAI.getAlign(), "oldload");
3058       Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
3059     } else if (IntTy && !IsWholeAlloca && IsDest) {
3060       Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3061                                          NewAI.getAlign(), "oldload");
3062       Old = convertValue(DL, IRB, Old, IntTy);
3063       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3064       Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3065       Src = convertValue(DL, IRB, Src, NewAllocaTy);
3066     }
3067 
3068     StoreInst *Store = cast<StoreInst>(
3069         IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
3070     if (AATags)
3071       Store->setAAMetadata(AATags);
3072     LLVM_DEBUG(dbgs() << "          to: " << *Store << "\n");
3073     return !II.isVolatile();
3074   }
3075 
visitIntrinsicInst(IntrinsicInst & II)3076   bool visitIntrinsicInst(IntrinsicInst &II) {
3077     assert(II.isLifetimeStartOrEnd());
3078     LLVM_DEBUG(dbgs() << "    original: " << II << "\n");
3079     assert(II.getArgOperand(1) == OldPtr);
3080 
3081     // Record this instruction for deletion.
3082     Pass.DeadInsts.insert(&II);
3083 
3084     // Lifetime intrinsics are only promotable if they cover the whole alloca.
3085     // Therefore, we drop lifetime intrinsics which don't cover the whole
3086     // alloca.
3087     // (In theory, intrinsics which partially cover an alloca could be
3088     // promoted, but PromoteMemToReg doesn't handle that case.)
3089     // FIXME: Check whether the alloca is promotable before dropping the
3090     // lifetime intrinsics?
3091     if (NewBeginOffset != NewAllocaBeginOffset ||
3092         NewEndOffset != NewAllocaEndOffset)
3093       return true;
3094 
3095     ConstantInt *Size =
3096         ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
3097                          NewEndOffset - NewBeginOffset);
3098     // Lifetime intrinsics always expect an i8* so directly get such a pointer
3099     // for the new alloca slice.
3100     Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace());
3101     Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
3102     Value *New;
3103     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3104       New = IRB.CreateLifetimeStart(Ptr, Size);
3105     else
3106       New = IRB.CreateLifetimeEnd(Ptr, Size);
3107 
3108     (void)New;
3109     LLVM_DEBUG(dbgs() << "          to: " << *New << "\n");
3110 
3111     return true;
3112   }
3113 
fixLoadStoreAlign(Instruction & Root)3114   void fixLoadStoreAlign(Instruction &Root) {
3115     // This algorithm implements the same visitor loop as
3116     // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
3117     // or store found.
3118     SmallPtrSet<Instruction *, 4> Visited;
3119     SmallVector<Instruction *, 4> Uses;
3120     Visited.insert(&Root);
3121     Uses.push_back(&Root);
3122     do {
3123       Instruction *I = Uses.pop_back_val();
3124 
3125       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3126         LI->setAlignment(std::min(LI->getAlign(), getSliceAlign()));
3127         continue;
3128       }
3129       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3130         SI->setAlignment(std::min(SI->getAlign(), getSliceAlign()));
3131         continue;
3132       }
3133 
3134       assert(isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) ||
3135              isa<PHINode>(I) || isa<SelectInst>(I) ||
3136              isa<GetElementPtrInst>(I));
3137       for (User *U : I->users())
3138         if (Visited.insert(cast<Instruction>(U)).second)
3139           Uses.push_back(cast<Instruction>(U));
3140     } while (!Uses.empty());
3141   }
3142 
visitPHINode(PHINode & PN)3143   bool visitPHINode(PHINode &PN) {
3144     LLVM_DEBUG(dbgs() << "    original: " << PN << "\n");
3145     assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3146     assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
3147 
3148     // We would like to compute a new pointer in only one place, but have it be
3149     // as local as possible to the PHI. To do that, we re-use the location of
3150     // the old pointer, which necessarily must be in the right position to
3151     // dominate the PHI.
3152     IRBuilderBase::InsertPointGuard Guard(IRB);
3153     if (isa<PHINode>(OldPtr))
3154       IRB.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
3155     else
3156       IRB.SetInsertPoint(OldPtr);
3157     IRB.SetCurrentDebugLocation(OldPtr->getDebugLoc());
3158 
3159     Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3160     // Replace the operands which were using the old pointer.
3161     std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3162 
3163     LLVM_DEBUG(dbgs() << "          to: " << PN << "\n");
3164     deleteIfTriviallyDead(OldPtr);
3165 
3166     // Fix the alignment of any loads or stores using this PHI node.
3167     fixLoadStoreAlign(PN);
3168 
3169     // PHIs can't be promoted on their own, but often can be speculated. We
3170     // check the speculation outside of the rewriter so that we see the
3171     // fully-rewritten alloca.
3172     PHIUsers.insert(&PN);
3173     return true;
3174   }
3175 
visitSelectInst(SelectInst & SI)3176   bool visitSelectInst(SelectInst &SI) {
3177     LLVM_DEBUG(dbgs() << "    original: " << SI << "\n");
3178     assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3179            "Pointer isn't an operand!");
3180     assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3181     assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
3182 
3183     Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3184     // Replace the operands which were using the old pointer.
3185     if (SI.getOperand(1) == OldPtr)
3186       SI.setOperand(1, NewPtr);
3187     if (SI.getOperand(2) == OldPtr)
3188       SI.setOperand(2, NewPtr);
3189 
3190     LLVM_DEBUG(dbgs() << "          to: " << SI << "\n");
3191     deleteIfTriviallyDead(OldPtr);
3192 
3193     // Fix the alignment of any loads or stores using this select.
3194     fixLoadStoreAlign(SI);
3195 
3196     // Selects can't be promoted on their own, but often can be speculated. We
3197     // check the speculation outside of the rewriter so that we see the
3198     // fully-rewritten alloca.
3199     SelectUsers.insert(&SI);
3200     return true;
3201   }
3202 };
3203 
3204 namespace {
3205 
3206 /// Visitor to rewrite aggregate loads and stores as scalar.
3207 ///
3208 /// This pass aggressively rewrites all aggregate loads and stores on
3209 /// a particular pointer (or any pointer derived from it which we can identify)
3210 /// with scalar loads and stores.
3211 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3212   // Befriend the base class so it can delegate to private visit methods.
3213   friend class InstVisitor<AggLoadStoreRewriter, bool>;
3214 
3215   /// Queue of pointer uses to analyze and potentially rewrite.
3216   SmallVector<Use *, 8> Queue;
3217 
3218   /// Set to prevent us from cycling with phi nodes and loops.
3219   SmallPtrSet<User *, 8> Visited;
3220 
3221   /// The current pointer use being rewritten. This is used to dig up the used
3222   /// value (as opposed to the user).
3223   Use *U = nullptr;
3224 
3225   /// Used to calculate offsets, and hence alignment, of subobjects.
3226   const DataLayout &DL;
3227 
3228 public:
AggLoadStoreRewriter(const DataLayout & DL)3229   AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
3230 
3231   /// Rewrite loads and stores through a pointer and all pointers derived from
3232   /// it.
rewrite(Instruction & I)3233   bool rewrite(Instruction &I) {
3234     LLVM_DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
3235     enqueueUsers(I);
3236     bool Changed = false;
3237     while (!Queue.empty()) {
3238       U = Queue.pop_back_val();
3239       Changed |= visit(cast<Instruction>(U->getUser()));
3240     }
3241     return Changed;
3242   }
3243 
3244 private:
3245   /// Enqueue all the users of the given instruction for further processing.
3246   /// This uses a set to de-duplicate users.
enqueueUsers(Instruction & I)3247   void enqueueUsers(Instruction &I) {
3248     for (Use &U : I.uses())
3249       if (Visited.insert(U.getUser()).second)
3250         Queue.push_back(&U);
3251   }
3252 
3253   // Conservative default is to not rewrite anything.
visitInstruction(Instruction & I)3254   bool visitInstruction(Instruction &I) { return false; }
3255 
3256   /// Generic recursive split emission class.
3257   template <typename Derived> class OpSplitter {
3258   protected:
3259     /// The builder used to form new instructions.
3260     IRBuilderTy IRB;
3261 
3262     /// The indices which to be used with insert- or extractvalue to select the
3263     /// appropriate value within the aggregate.
3264     SmallVector<unsigned, 4> Indices;
3265 
3266     /// The indices to a GEP instruction which will move Ptr to the correct slot
3267     /// within the aggregate.
3268     SmallVector<Value *, 4> GEPIndices;
3269 
3270     /// The base pointer of the original op, used as a base for GEPing the
3271     /// split operations.
3272     Value *Ptr;
3273 
3274     /// The base pointee type being GEPed into.
3275     Type *BaseTy;
3276 
3277     /// Known alignment of the base pointer.
3278     Align BaseAlign;
3279 
3280     /// To calculate offset of each component so we can correctly deduce
3281     /// alignments.
3282     const DataLayout &DL;
3283 
3284     /// Initialize the splitter with an insertion point, Ptr and start with a
3285     /// single zero GEP index.
OpSplitter(Instruction * InsertionPoint,Value * Ptr,Type * BaseTy,Align BaseAlign,const DataLayout & DL)3286     OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3287                Align BaseAlign, const DataLayout &DL)
3288         : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr),
3289           BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {}
3290 
3291   public:
3292     /// Generic recursive split emission routine.
3293     ///
3294     /// This method recursively splits an aggregate op (load or store) into
3295     /// scalar or vector ops. It splits recursively until it hits a single value
3296     /// and emits that single value operation via the template argument.
3297     ///
3298     /// The logic of this routine relies on GEPs and insertvalue and
3299     /// extractvalue all operating with the same fundamental index list, merely
3300     /// formatted differently (GEPs need actual values).
3301     ///
3302     /// \param Ty  The type being split recursively into smaller ops.
3303     /// \param Agg The aggregate value being built up or stored, depending on
3304     /// whether this is splitting a load or a store respectively.
emitSplitOps(Type * Ty,Value * & Agg,const Twine & Name)3305     void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3306       if (Ty->isSingleValueType()) {
3307         unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
3308         return static_cast<Derived *>(this)->emitFunc(
3309             Ty, Agg, commonAlignment(BaseAlign, Offset), Name);
3310       }
3311 
3312       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3313         unsigned OldSize = Indices.size();
3314         (void)OldSize;
3315         for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3316              ++Idx) {
3317           assert(Indices.size() == OldSize && "Did not return to the old size");
3318           Indices.push_back(Idx);
3319           GEPIndices.push_back(IRB.getInt32(Idx));
3320           emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3321           GEPIndices.pop_back();
3322           Indices.pop_back();
3323         }
3324         return;
3325       }
3326 
3327       if (StructType *STy = dyn_cast<StructType>(Ty)) {
3328         unsigned OldSize = Indices.size();
3329         (void)OldSize;
3330         for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3331              ++Idx) {
3332           assert(Indices.size() == OldSize && "Did not return to the old size");
3333           Indices.push_back(Idx);
3334           GEPIndices.push_back(IRB.getInt32(Idx));
3335           emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3336           GEPIndices.pop_back();
3337           Indices.pop_back();
3338         }
3339         return;
3340       }
3341 
3342       llvm_unreachable("Only arrays and structs are aggregate loadable types");
3343     }
3344   };
3345 
3346   struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3347     AAMDNodes AATags;
3348 
LoadOpSplitter__anon423183b00b11::AggLoadStoreRewriter::LoadOpSplitter3349     LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3350                    AAMDNodes AATags, Align BaseAlign, const DataLayout &DL)
3351         : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3352                                      DL),
3353           AATags(AATags) {}
3354 
3355     /// Emit a leaf load of a single value. This is called at the leaves of the
3356     /// recursive emission to actually load values.
emitFunc__anon423183b00b11::AggLoadStoreRewriter::LoadOpSplitter3357     void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
3358       assert(Ty->isSingleValueType());
3359       // Load the single value and insert it using the indices.
3360       Value *GEP =
3361           IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
3362       LoadInst *Load =
3363           IRB.CreateAlignedLoad(Ty, GEP, Alignment, Name + ".load");
3364       if (AATags)
3365         Load->setAAMetadata(AATags);
3366       Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3367       LLVM_DEBUG(dbgs() << "          to: " << *Load << "\n");
3368     }
3369   };
3370 
visitLoadInst(LoadInst & LI)3371   bool visitLoadInst(LoadInst &LI) {
3372     assert(LI.getPointerOperand() == *U);
3373     if (!LI.isSimple() || LI.getType()->isSingleValueType())
3374       return false;
3375 
3376     // We have an aggregate being loaded, split it apart.
3377     LLVM_DEBUG(dbgs() << "    original: " << LI << "\n");
3378     AAMDNodes AATags;
3379     LI.getAAMetadata(AATags);
3380     LoadOpSplitter Splitter(&LI, *U, LI.getType(), AATags,
3381                             getAdjustedAlignment(&LI, 0), DL);
3382     Value *V = UndefValue::get(LI.getType());
3383     Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3384     Visited.erase(&LI);
3385     LI.replaceAllUsesWith(V);
3386     LI.eraseFromParent();
3387     return true;
3388   }
3389 
3390   struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
StoreOpSplitter__anon423183b00b11::AggLoadStoreRewriter::StoreOpSplitter3391     StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3392                     AAMDNodes AATags, Align BaseAlign, const DataLayout &DL)
3393         : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3394                                       DL),
3395           AATags(AATags) {}
3396     AAMDNodes AATags;
3397     /// Emit a leaf store of a single value. This is called at the leaves of the
3398     /// recursive emission to actually produce stores.
emitFunc__anon423183b00b11::AggLoadStoreRewriter::StoreOpSplitter3399     void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
3400       assert(Ty->isSingleValueType());
3401       // Extract the single value and store it using the indices.
3402       //
3403       // The gep and extractvalue values are factored out of the CreateStore
3404       // call to make the output independent of the argument evaluation order.
3405       Value *ExtractValue =
3406           IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3407       Value *InBoundsGEP =
3408           IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
3409       StoreInst *Store =
3410           IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Alignment);
3411       if (AATags)
3412         Store->setAAMetadata(AATags);
3413       LLVM_DEBUG(dbgs() << "          to: " << *Store << "\n");
3414     }
3415   };
3416 
visitStoreInst(StoreInst & SI)3417   bool visitStoreInst(StoreInst &SI) {
3418     if (!SI.isSimple() || SI.getPointerOperand() != *U)
3419       return false;
3420     Value *V = SI.getValueOperand();
3421     if (V->getType()->isSingleValueType())
3422       return false;
3423 
3424     // We have an aggregate being stored, split it apart.
3425     LLVM_DEBUG(dbgs() << "    original: " << SI << "\n");
3426     AAMDNodes AATags;
3427     SI.getAAMetadata(AATags);
3428     StoreOpSplitter Splitter(&SI, *U, V->getType(), AATags,
3429                              getAdjustedAlignment(&SI, 0), DL);
3430     Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3431     Visited.erase(&SI);
3432     SI.eraseFromParent();
3433     return true;
3434   }
3435 
visitBitCastInst(BitCastInst & BC)3436   bool visitBitCastInst(BitCastInst &BC) {
3437     enqueueUsers(BC);
3438     return false;
3439   }
3440 
visitAddrSpaceCastInst(AddrSpaceCastInst & ASC)3441   bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
3442     enqueueUsers(ASC);
3443     return false;
3444   }
3445 
3446   // Fold gep (select cond, ptr1, ptr2) => select cond, gep(ptr1), gep(ptr2)
foldGEPSelect(GetElementPtrInst & GEPI)3447   bool foldGEPSelect(GetElementPtrInst &GEPI) {
3448     if (!GEPI.hasAllConstantIndices())
3449       return false;
3450 
3451     SelectInst *Sel = cast<SelectInst>(GEPI.getPointerOperand());
3452 
3453     LLVM_DEBUG(dbgs() << "  Rewriting gep(select) -> select(gep):"
3454                       << "\n    original: " << *Sel
3455                       << "\n              " << GEPI);
3456 
3457     IRBuilderTy Builder(&GEPI);
3458     SmallVector<Value *, 4> Index(GEPI.idx_begin(), GEPI.idx_end());
3459     bool IsInBounds = GEPI.isInBounds();
3460 
3461     Value *True = Sel->getTrueValue();
3462     Value *NTrue =
3463         IsInBounds
3464             ? Builder.CreateInBoundsGEP(True, Index,
3465                                         True->getName() + ".sroa.gep")
3466             : Builder.CreateGEP(True, Index, True->getName() + ".sroa.gep");
3467 
3468     Value *False = Sel->getFalseValue();
3469 
3470     Value *NFalse =
3471         IsInBounds
3472             ? Builder.CreateInBoundsGEP(False, Index,
3473                                         False->getName() + ".sroa.gep")
3474             : Builder.CreateGEP(False, Index, False->getName() + ".sroa.gep");
3475 
3476     Value *NSel = Builder.CreateSelect(Sel->getCondition(), NTrue, NFalse,
3477                                        Sel->getName() + ".sroa.sel");
3478     Visited.erase(&GEPI);
3479     GEPI.replaceAllUsesWith(NSel);
3480     GEPI.eraseFromParent();
3481     Instruction *NSelI = cast<Instruction>(NSel);
3482     Visited.insert(NSelI);
3483     enqueueUsers(*NSelI);
3484 
3485     LLVM_DEBUG(dbgs() << "\n          to: " << *NTrue
3486                       << "\n              " << *NFalse
3487                       << "\n              " << *NSel << '\n');
3488 
3489     return true;
3490   }
3491 
3492   // Fold gep (phi ptr1, ptr2) => phi gep(ptr1), gep(ptr2)
foldGEPPhi(GetElementPtrInst & GEPI)3493   bool foldGEPPhi(GetElementPtrInst &GEPI) {
3494     if (!GEPI.hasAllConstantIndices())
3495       return false;
3496 
3497     PHINode *PHI = cast<PHINode>(GEPI.getPointerOperand());
3498     if (GEPI.getParent() != PHI->getParent() ||
3499         llvm::any_of(PHI->incoming_values(), [](Value *In)
3500           { Instruction *I = dyn_cast<Instruction>(In);
3501             return !I || isa<GetElementPtrInst>(I) || isa<PHINode>(I) ||
3502                    succ_empty(I->getParent()) ||
3503                    !I->getParent()->isLegalToHoistInto();
3504           }))
3505       return false;
3506 
3507     LLVM_DEBUG(dbgs() << "  Rewriting gep(phi) -> phi(gep):"
3508                       << "\n    original: " << *PHI
3509                       << "\n              " << GEPI
3510                       << "\n          to: ");
3511 
3512     SmallVector<Value *, 4> Index(GEPI.idx_begin(), GEPI.idx_end());
3513     bool IsInBounds = GEPI.isInBounds();
3514     IRBuilderTy PHIBuilder(GEPI.getParent()->getFirstNonPHI());
3515     PHINode *NewPN = PHIBuilder.CreatePHI(GEPI.getType(),
3516                                           PHI->getNumIncomingValues(),
3517                                           PHI->getName() + ".sroa.phi");
3518     for (unsigned I = 0, E = PHI->getNumIncomingValues(); I != E; ++I) {
3519       Instruction *In = cast<Instruction>(PHI->getIncomingValue(I));
3520 
3521       IRBuilderTy B(In->getParent(), std::next(In->getIterator()));
3522       Value *NewVal = IsInBounds
3523           ? B.CreateInBoundsGEP(In, Index, In->getName() + ".sroa.gep")
3524           : B.CreateGEP(In, Index, In->getName() + ".sroa.gep");
3525       NewPN->addIncoming(NewVal, PHI->getIncomingBlock(I));
3526     }
3527 
3528     Visited.erase(&GEPI);
3529     GEPI.replaceAllUsesWith(NewPN);
3530     GEPI.eraseFromParent();
3531     Visited.insert(NewPN);
3532     enqueueUsers(*NewPN);
3533 
3534     LLVM_DEBUG(for (Value *In : NewPN->incoming_values())
3535                  dbgs() << "\n              " << *In;
3536                dbgs() << "\n              " << *NewPN << '\n');
3537 
3538     return true;
3539   }
3540 
visitGetElementPtrInst(GetElementPtrInst & GEPI)3541   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3542     if (isa<SelectInst>(GEPI.getPointerOperand()) &&
3543         foldGEPSelect(GEPI))
3544       return true;
3545 
3546     if (isa<PHINode>(GEPI.getPointerOperand()) &&
3547         foldGEPPhi(GEPI))
3548       return true;
3549 
3550     enqueueUsers(GEPI);
3551     return false;
3552   }
3553 
visitPHINode(PHINode & PN)3554   bool visitPHINode(PHINode &PN) {
3555     enqueueUsers(PN);
3556     return false;
3557   }
3558 
visitSelectInst(SelectInst & SI)3559   bool visitSelectInst(SelectInst &SI) {
3560     enqueueUsers(SI);
3561     return false;
3562   }
3563 };
3564 
3565 } // end anonymous namespace
3566 
3567 /// Strip aggregate type wrapping.
3568 ///
3569 /// This removes no-op aggregate types wrapping an underlying type. It will
3570 /// strip as many layers of types as it can without changing either the type
3571 /// size or the allocated size.
stripAggregateTypeWrapping(const DataLayout & DL,Type * Ty)3572 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3573   if (Ty->isSingleValueType())
3574     return Ty;
3575 
3576   uint64_t AllocSize = DL.getTypeAllocSize(Ty).getFixedSize();
3577   uint64_t TypeSize = DL.getTypeSizeInBits(Ty).getFixedSize();
3578 
3579   Type *InnerTy;
3580   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3581     InnerTy = ArrTy->getElementType();
3582   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3583     const StructLayout *SL = DL.getStructLayout(STy);
3584     unsigned Index = SL->getElementContainingOffset(0);
3585     InnerTy = STy->getElementType(Index);
3586   } else {
3587     return Ty;
3588   }
3589 
3590   if (AllocSize > DL.getTypeAllocSize(InnerTy).getFixedSize() ||
3591       TypeSize > DL.getTypeSizeInBits(InnerTy).getFixedSize())
3592     return Ty;
3593 
3594   return stripAggregateTypeWrapping(DL, InnerTy);
3595 }
3596 
3597 /// Try to find a partition of the aggregate type passed in for a given
3598 /// offset and size.
3599 ///
3600 /// This recurses through the aggregate type and tries to compute a subtype
3601 /// based on the offset and size. When the offset and size span a sub-section
3602 /// of an array, it will even compute a new array type for that sub-section,
3603 /// and the same for structs.
3604 ///
3605 /// Note that this routine is very strict and tries to find a partition of the
3606 /// type which produces the *exact* right offset and size. It is not forgiving
3607 /// when the size or offset cause either end of type-based partition to be off.
3608 /// Also, this is a best-effort routine. It is reasonable to give up and not
3609 /// return a type if necessary.
getTypePartition(const DataLayout & DL,Type * Ty,uint64_t Offset,uint64_t Size)3610 static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3611                               uint64_t Size) {
3612   if (Offset == 0 && DL.getTypeAllocSize(Ty).getFixedSize() == Size)
3613     return stripAggregateTypeWrapping(DL, Ty);
3614   if (Offset > DL.getTypeAllocSize(Ty).getFixedSize() ||
3615       (DL.getTypeAllocSize(Ty).getFixedSize() - Offset) < Size)
3616     return nullptr;
3617 
3618   if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
3619      Type *ElementTy;
3620      uint64_t TyNumElements;
3621      if (auto *AT = dyn_cast<ArrayType>(Ty)) {
3622        ElementTy = AT->getElementType();
3623        TyNumElements = AT->getNumElements();
3624      } else {
3625        // FIXME: This isn't right for vectors with non-byte-sized or
3626        // non-power-of-two sized elements.
3627        auto *VT = cast<FixedVectorType>(Ty);
3628        ElementTy = VT->getElementType();
3629        TyNumElements = VT->getNumElements();
3630     }
3631     uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedSize();
3632     uint64_t NumSkippedElements = Offset / ElementSize;
3633     if (NumSkippedElements >= TyNumElements)
3634       return nullptr;
3635     Offset -= NumSkippedElements * ElementSize;
3636 
3637     // First check if we need to recurse.
3638     if (Offset > 0 || Size < ElementSize) {
3639       // Bail if the partition ends in a different array element.
3640       if ((Offset + Size) > ElementSize)
3641         return nullptr;
3642       // Recurse through the element type trying to peel off offset bytes.
3643       return getTypePartition(DL, ElementTy, Offset, Size);
3644     }
3645     assert(Offset == 0);
3646 
3647     if (Size == ElementSize)
3648       return stripAggregateTypeWrapping(DL, ElementTy);
3649     assert(Size > ElementSize);
3650     uint64_t NumElements = Size / ElementSize;
3651     if (NumElements * ElementSize != Size)
3652       return nullptr;
3653     return ArrayType::get(ElementTy, NumElements);
3654   }
3655 
3656   StructType *STy = dyn_cast<StructType>(Ty);
3657   if (!STy)
3658     return nullptr;
3659 
3660   const StructLayout *SL = DL.getStructLayout(STy);
3661   if (Offset >= SL->getSizeInBytes())
3662     return nullptr;
3663   uint64_t EndOffset = Offset + Size;
3664   if (EndOffset > SL->getSizeInBytes())
3665     return nullptr;
3666 
3667   unsigned Index = SL->getElementContainingOffset(Offset);
3668   Offset -= SL->getElementOffset(Index);
3669 
3670   Type *ElementTy = STy->getElementType(Index);
3671   uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedSize();
3672   if (Offset >= ElementSize)
3673     return nullptr; // The offset points into alignment padding.
3674 
3675   // See if any partition must be contained by the element.
3676   if (Offset > 0 || Size < ElementSize) {
3677     if ((Offset + Size) > ElementSize)
3678       return nullptr;
3679     return getTypePartition(DL, ElementTy, Offset, Size);
3680   }
3681   assert(Offset == 0);
3682 
3683   if (Size == ElementSize)
3684     return stripAggregateTypeWrapping(DL, ElementTy);
3685 
3686   StructType::element_iterator EI = STy->element_begin() + Index,
3687                                EE = STy->element_end();
3688   if (EndOffset < SL->getSizeInBytes()) {
3689     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3690     if (Index == EndIndex)
3691       return nullptr; // Within a single element and its padding.
3692 
3693     // Don't try to form "natural" types if the elements don't line up with the
3694     // expected size.
3695     // FIXME: We could potentially recurse down through the last element in the
3696     // sub-struct to find a natural end point.
3697     if (SL->getElementOffset(EndIndex) != EndOffset)
3698       return nullptr;
3699 
3700     assert(Index < EndIndex);
3701     EE = STy->element_begin() + EndIndex;
3702   }
3703 
3704   // Try to build up a sub-structure.
3705   StructType *SubTy =
3706       StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
3707   const StructLayout *SubSL = DL.getStructLayout(SubTy);
3708   if (Size != SubSL->getSizeInBytes())
3709     return nullptr; // The sub-struct doesn't have quite the size needed.
3710 
3711   return SubTy;
3712 }
3713 
3714 /// Pre-split loads and stores to simplify rewriting.
3715 ///
3716 /// We want to break up the splittable load+store pairs as much as
3717 /// possible. This is important to do as a preprocessing step, as once we
3718 /// start rewriting the accesses to partitions of the alloca we lose the
3719 /// necessary information to correctly split apart paired loads and stores
3720 /// which both point into this alloca. The case to consider is something like
3721 /// the following:
3722 ///
3723 ///   %a = alloca [12 x i8]
3724 ///   %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3725 ///   %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3726 ///   %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3727 ///   %iptr1 = bitcast i8* %gep1 to i64*
3728 ///   %iptr2 = bitcast i8* %gep2 to i64*
3729 ///   %fptr1 = bitcast i8* %gep1 to float*
3730 ///   %fptr2 = bitcast i8* %gep2 to float*
3731 ///   %fptr3 = bitcast i8* %gep3 to float*
3732 ///   store float 0.0, float* %fptr1
3733 ///   store float 1.0, float* %fptr2
3734 ///   %v = load i64* %iptr1
3735 ///   store i64 %v, i64* %iptr2
3736 ///   %f1 = load float* %fptr2
3737 ///   %f2 = load float* %fptr3
3738 ///
3739 /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3740 /// promote everything so we recover the 2 SSA values that should have been
3741 /// there all along.
3742 ///
3743 /// \returns true if any changes are made.
presplitLoadsAndStores(AllocaInst & AI,AllocaSlices & AS)3744 bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3745   LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3746 
3747   // Track the loads and stores which are candidates for pre-splitting here, in
3748   // the order they first appear during the partition scan. These give stable
3749   // iteration order and a basis for tracking which loads and stores we
3750   // actually split.
3751   SmallVector<LoadInst *, 4> Loads;
3752   SmallVector<StoreInst *, 4> Stores;
3753 
3754   // We need to accumulate the splits required of each load or store where we
3755   // can find them via a direct lookup. This is important to cross-check loads
3756   // and stores against each other. We also track the slice so that we can kill
3757   // all the slices that end up split.
3758   struct SplitOffsets {
3759     Slice *S;
3760     std::vector<uint64_t> Splits;
3761   };
3762   SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3763 
3764   // Track loads out of this alloca which cannot, for any reason, be pre-split.
3765   // This is important as we also cannot pre-split stores of those loads!
3766   // FIXME: This is all pretty gross. It means that we can be more aggressive
3767   // in pre-splitting when the load feeding the store happens to come from
3768   // a separate alloca. Put another way, the effectiveness of SROA would be
3769   // decreased by a frontend which just concatenated all of its local allocas
3770   // into one big flat alloca. But defeating such patterns is exactly the job
3771   // SROA is tasked with! Sadly, to not have this discrepancy we would have
3772   // change store pre-splitting to actually force pre-splitting of the load
3773   // that feeds it *and all stores*. That makes pre-splitting much harder, but
3774   // maybe it would make it more principled?
3775   SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3776 
3777   LLVM_DEBUG(dbgs() << "  Searching for candidate loads and stores\n");
3778   for (auto &P : AS.partitions()) {
3779     for (Slice &S : P) {
3780       Instruction *I = cast<Instruction>(S.getUse()->getUser());
3781       if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3782         // If this is a load we have to track that it can't participate in any
3783         // pre-splitting. If this is a store of a load we have to track that
3784         // that load also can't participate in any pre-splitting.
3785         if (auto *LI = dyn_cast<LoadInst>(I))
3786           UnsplittableLoads.insert(LI);
3787         else if (auto *SI = dyn_cast<StoreInst>(I))
3788           if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3789             UnsplittableLoads.insert(LI);
3790         continue;
3791       }
3792       assert(P.endOffset() > S.beginOffset() &&
3793              "Empty or backwards partition!");
3794 
3795       // Determine if this is a pre-splittable slice.
3796       if (auto *LI = dyn_cast<LoadInst>(I)) {
3797         assert(!LI->isVolatile() && "Cannot split volatile loads!");
3798 
3799         // The load must be used exclusively to store into other pointers for
3800         // us to be able to arbitrarily pre-split it. The stores must also be
3801         // simple to avoid changing semantics.
3802         auto IsLoadSimplyStored = [](LoadInst *LI) {
3803           for (User *LU : LI->users()) {
3804             auto *SI = dyn_cast<StoreInst>(LU);
3805             if (!SI || !SI->isSimple())
3806               return false;
3807           }
3808           return true;
3809         };
3810         if (!IsLoadSimplyStored(LI)) {
3811           UnsplittableLoads.insert(LI);
3812           continue;
3813         }
3814 
3815         Loads.push_back(LI);
3816       } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3817         if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3818           // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
3819           continue;
3820         auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3821         if (!StoredLoad || !StoredLoad->isSimple())
3822           continue;
3823         assert(!SI->isVolatile() && "Cannot split volatile stores!");
3824 
3825         Stores.push_back(SI);
3826       } else {
3827         // Other uses cannot be pre-split.
3828         continue;
3829       }
3830 
3831       // Record the initial split.
3832       LLVM_DEBUG(dbgs() << "    Candidate: " << *I << "\n");
3833       auto &Offsets = SplitOffsetsMap[I];
3834       assert(Offsets.Splits.empty() &&
3835              "Should not have splits the first time we see an instruction!");
3836       Offsets.S = &S;
3837       Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
3838     }
3839 
3840     // Now scan the already split slices, and add a split for any of them which
3841     // we're going to pre-split.
3842     for (Slice *S : P.splitSliceTails()) {
3843       auto SplitOffsetsMapI =
3844           SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3845       if (SplitOffsetsMapI == SplitOffsetsMap.end())
3846         continue;
3847       auto &Offsets = SplitOffsetsMapI->second;
3848 
3849       assert(Offsets.S == S && "Found a mismatched slice!");
3850       assert(!Offsets.Splits.empty() &&
3851              "Cannot have an empty set of splits on the second partition!");
3852       assert(Offsets.Splits.back() ==
3853                  P.beginOffset() - Offsets.S->beginOffset() &&
3854              "Previous split does not end where this one begins!");
3855 
3856       // Record each split. The last partition's end isn't needed as the size
3857       // of the slice dictates that.
3858       if (S->endOffset() > P.endOffset())
3859         Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
3860     }
3861   }
3862 
3863   // We may have split loads where some of their stores are split stores. For
3864   // such loads and stores, we can only pre-split them if their splits exactly
3865   // match relative to their starting offset. We have to verify this prior to
3866   // any rewriting.
3867   Stores.erase(
3868       llvm::remove_if(Stores,
3869                       [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3870                         // Lookup the load we are storing in our map of split
3871                         // offsets.
3872                         auto *LI = cast<LoadInst>(SI->getValueOperand());
3873                         // If it was completely unsplittable, then we're done,
3874                         // and this store can't be pre-split.
3875                         if (UnsplittableLoads.count(LI))
3876                           return true;
3877 
3878                         auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3879                         if (LoadOffsetsI == SplitOffsetsMap.end())
3880                           return false; // Unrelated loads are definitely safe.
3881                         auto &LoadOffsets = LoadOffsetsI->second;
3882 
3883                         // Now lookup the store's offsets.
3884                         auto &StoreOffsets = SplitOffsetsMap[SI];
3885 
3886                         // If the relative offsets of each split in the load and
3887                         // store match exactly, then we can split them and we
3888                         // don't need to remove them here.
3889                         if (LoadOffsets.Splits == StoreOffsets.Splits)
3890                           return false;
3891 
3892                         LLVM_DEBUG(
3893                             dbgs()
3894                             << "    Mismatched splits for load and store:\n"
3895                             << "      " << *LI << "\n"
3896                             << "      " << *SI << "\n");
3897 
3898                         // We've found a store and load that we need to split
3899                         // with mismatched relative splits. Just give up on them
3900                         // and remove both instructions from our list of
3901                         // candidates.
3902                         UnsplittableLoads.insert(LI);
3903                         return true;
3904                       }),
3905       Stores.end());
3906   // Now we have to go *back* through all the stores, because a later store may
3907   // have caused an earlier store's load to become unsplittable and if it is
3908   // unsplittable for the later store, then we can't rely on it being split in
3909   // the earlier store either.
3910   Stores.erase(llvm::remove_if(Stores,
3911                                [&UnsplittableLoads](StoreInst *SI) {
3912                                  auto *LI =
3913                                      cast<LoadInst>(SI->getValueOperand());
3914                                  return UnsplittableLoads.count(LI);
3915                                }),
3916                Stores.end());
3917   // Once we've established all the loads that can't be split for some reason,
3918   // filter any that made it into our list out.
3919   Loads.erase(llvm::remove_if(Loads,
3920                               [&UnsplittableLoads](LoadInst *LI) {
3921                                 return UnsplittableLoads.count(LI);
3922                               }),
3923               Loads.end());
3924 
3925   // If no loads or stores are left, there is no pre-splitting to be done for
3926   // this alloca.
3927   if (Loads.empty() && Stores.empty())
3928     return false;
3929 
3930   // From here on, we can't fail and will be building new accesses, so rig up
3931   // an IR builder.
3932   IRBuilderTy IRB(&AI);
3933 
3934   // Collect the new slices which we will merge into the alloca slices.
3935   SmallVector<Slice, 4> NewSlices;
3936 
3937   // Track any allocas we end up splitting loads and stores for so we iterate
3938   // on them.
3939   SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3940 
3941   // At this point, we have collected all of the loads and stores we can
3942   // pre-split, and the specific splits needed for them. We actually do the
3943   // splitting in a specific order in order to handle when one of the loads in
3944   // the value operand to one of the stores.
3945   //
3946   // First, we rewrite all of the split loads, and just accumulate each split
3947   // load in a parallel structure. We also build the slices for them and append
3948   // them to the alloca slices.
3949   SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3950   std::vector<LoadInst *> SplitLoads;
3951   const DataLayout &DL = AI.getModule()->getDataLayout();
3952   for (LoadInst *LI : Loads) {
3953     SplitLoads.clear();
3954 
3955     IntegerType *Ty = cast<IntegerType>(LI->getType());
3956     uint64_t LoadSize = Ty->getBitWidth() / 8;
3957     assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3958 
3959     auto &Offsets = SplitOffsetsMap[LI];
3960     assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3961            "Slice size should always match load size exactly!");
3962     uint64_t BaseOffset = Offsets.S->beginOffset();
3963     assert(BaseOffset + LoadSize > BaseOffset &&
3964            "Cannot represent alloca access size using 64-bit integers!");
3965 
3966     Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
3967     IRB.SetInsertPoint(LI);
3968 
3969     LLVM_DEBUG(dbgs() << "  Splitting load: " << *LI << "\n");
3970 
3971     uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3972     int Idx = 0, Size = Offsets.Splits.size();
3973     for (;;) {
3974       auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3975       auto AS = LI->getPointerAddressSpace();
3976       auto *PartPtrTy = PartTy->getPointerTo(AS);
3977       LoadInst *PLoad = IRB.CreateAlignedLoad(
3978           PartTy,
3979           getAdjustedPtr(IRB, DL, BasePtr,
3980                          APInt(DL.getIndexSizeInBits(AS), PartOffset),
3981                          PartPtrTy, BasePtr->getName() + "."),
3982           getAdjustedAlignment(LI, PartOffset),
3983           /*IsVolatile*/ false, LI->getName());
3984       PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3985                                 LLVMContext::MD_access_group});
3986 
3987       // Append this load onto the list of split loads so we can find it later
3988       // to rewrite the stores.
3989       SplitLoads.push_back(PLoad);
3990 
3991       // Now build a new slice for the alloca.
3992       NewSlices.push_back(
3993           Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3994                 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
3995                 /*IsSplittable*/ false));
3996       LLVM_DEBUG(dbgs() << "    new slice [" << NewSlices.back().beginOffset()
3997                         << ", " << NewSlices.back().endOffset()
3998                         << "): " << *PLoad << "\n");
3999 
4000       // See if we've handled all the splits.
4001       if (Idx >= Size)
4002         break;
4003 
4004       // Setup the next partition.
4005       PartOffset = Offsets.Splits[Idx];
4006       ++Idx;
4007       PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
4008     }
4009 
4010     // Now that we have the split loads, do the slow walk over all uses of the
4011     // load and rewrite them as split stores, or save the split loads to use
4012     // below if the store is going to be split there anyways.
4013     bool DeferredStores = false;
4014     for (User *LU : LI->users()) {
4015       StoreInst *SI = cast<StoreInst>(LU);
4016       if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
4017         DeferredStores = true;
4018         LLVM_DEBUG(dbgs() << "    Deferred splitting of store: " << *SI
4019                           << "\n");
4020         continue;
4021       }
4022 
4023       Value *StoreBasePtr = SI->getPointerOperand();
4024       IRB.SetInsertPoint(SI);
4025 
4026       LLVM_DEBUG(dbgs() << "    Splitting store of load: " << *SI << "\n");
4027 
4028       for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
4029         LoadInst *PLoad = SplitLoads[Idx];
4030         uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
4031         auto *PartPtrTy =
4032             PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
4033 
4034         auto AS = SI->getPointerAddressSpace();
4035         StoreInst *PStore = IRB.CreateAlignedStore(
4036             PLoad,
4037             getAdjustedPtr(IRB, DL, StoreBasePtr,
4038                            APInt(DL.getIndexSizeInBits(AS), PartOffset),
4039                            PartPtrTy, StoreBasePtr->getName() + "."),
4040             getAdjustedAlignment(SI, PartOffset),
4041             /*IsVolatile*/ false);
4042         PStore->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
4043                                    LLVMContext::MD_access_group});
4044         LLVM_DEBUG(dbgs() << "      +" << PartOffset << ":" << *PStore << "\n");
4045       }
4046 
4047       // We want to immediately iterate on any allocas impacted by splitting
4048       // this store, and we have to track any promotable alloca (indicated by
4049       // a direct store) as needing to be resplit because it is no longer
4050       // promotable.
4051       if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
4052         ResplitPromotableAllocas.insert(OtherAI);
4053         Worklist.insert(OtherAI);
4054       } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
4055                      StoreBasePtr->stripInBoundsOffsets())) {
4056         Worklist.insert(OtherAI);
4057       }
4058 
4059       // Mark the original store as dead.
4060       DeadInsts.insert(SI);
4061     }
4062 
4063     // Save the split loads if there are deferred stores among the users.
4064     if (DeferredStores)
4065       SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
4066 
4067     // Mark the original load as dead and kill the original slice.
4068     DeadInsts.insert(LI);
4069     Offsets.S->kill();
4070   }
4071 
4072   // Second, we rewrite all of the split stores. At this point, we know that
4073   // all loads from this alloca have been split already. For stores of such
4074   // loads, we can simply look up the pre-existing split loads. For stores of
4075   // other loads, we split those loads first and then write split stores of
4076   // them.
4077   for (StoreInst *SI : Stores) {
4078     auto *LI = cast<LoadInst>(SI->getValueOperand());
4079     IntegerType *Ty = cast<IntegerType>(LI->getType());
4080     uint64_t StoreSize = Ty->getBitWidth() / 8;
4081     assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
4082 
4083     auto &Offsets = SplitOffsetsMap[SI];
4084     assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
4085            "Slice size should always match load size exactly!");
4086     uint64_t BaseOffset = Offsets.S->beginOffset();
4087     assert(BaseOffset + StoreSize > BaseOffset &&
4088            "Cannot represent alloca access size using 64-bit integers!");
4089 
4090     Value *LoadBasePtr = LI->getPointerOperand();
4091     Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
4092 
4093     LLVM_DEBUG(dbgs() << "  Splitting store: " << *SI << "\n");
4094 
4095     // Check whether we have an already split load.
4096     auto SplitLoadsMapI = SplitLoadsMap.find(LI);
4097     std::vector<LoadInst *> *SplitLoads = nullptr;
4098     if (SplitLoadsMapI != SplitLoadsMap.end()) {
4099       SplitLoads = &SplitLoadsMapI->second;
4100       assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
4101              "Too few split loads for the number of splits in the store!");
4102     } else {
4103       LLVM_DEBUG(dbgs() << "          of load: " << *LI << "\n");
4104     }
4105 
4106     uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
4107     int Idx = 0, Size = Offsets.Splits.size();
4108     for (;;) {
4109       auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
4110       auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
4111       auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
4112 
4113       // Either lookup a split load or create one.
4114       LoadInst *PLoad;
4115       if (SplitLoads) {
4116         PLoad = (*SplitLoads)[Idx];
4117       } else {
4118         IRB.SetInsertPoint(LI);
4119         auto AS = LI->getPointerAddressSpace();
4120         PLoad = IRB.CreateAlignedLoad(
4121             PartTy,
4122             getAdjustedPtr(IRB, DL, LoadBasePtr,
4123                            APInt(DL.getIndexSizeInBits(AS), PartOffset),
4124                            LoadPartPtrTy, LoadBasePtr->getName() + "."),
4125             getAdjustedAlignment(LI, PartOffset),
4126             /*IsVolatile*/ false, LI->getName());
4127       }
4128 
4129       // And store this partition.
4130       IRB.SetInsertPoint(SI);
4131       auto AS = SI->getPointerAddressSpace();
4132       StoreInst *PStore = IRB.CreateAlignedStore(
4133           PLoad,
4134           getAdjustedPtr(IRB, DL, StoreBasePtr,
4135                          APInt(DL.getIndexSizeInBits(AS), PartOffset),
4136                          StorePartPtrTy, StoreBasePtr->getName() + "."),
4137           getAdjustedAlignment(SI, PartOffset),
4138           /*IsVolatile*/ false);
4139 
4140       // Now build a new slice for the alloca.
4141       NewSlices.push_back(
4142           Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
4143                 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
4144                 /*IsSplittable*/ false));
4145       LLVM_DEBUG(dbgs() << "    new slice [" << NewSlices.back().beginOffset()
4146                         << ", " << NewSlices.back().endOffset()
4147                         << "): " << *PStore << "\n");
4148       if (!SplitLoads) {
4149         LLVM_DEBUG(dbgs() << "      of split load: " << *PLoad << "\n");
4150       }
4151 
4152       // See if we've finished all the splits.
4153       if (Idx >= Size)
4154         break;
4155 
4156       // Setup the next partition.
4157       PartOffset = Offsets.Splits[Idx];
4158       ++Idx;
4159       PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
4160     }
4161 
4162     // We want to immediately iterate on any allocas impacted by splitting
4163     // this load, which is only relevant if it isn't a load of this alloca and
4164     // thus we didn't already split the loads above. We also have to keep track
4165     // of any promotable allocas we split loads on as they can no longer be
4166     // promoted.
4167     if (!SplitLoads) {
4168       if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
4169         assert(OtherAI != &AI && "We can't re-split our own alloca!");
4170         ResplitPromotableAllocas.insert(OtherAI);
4171         Worklist.insert(OtherAI);
4172       } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
4173                      LoadBasePtr->stripInBoundsOffsets())) {
4174         assert(OtherAI != &AI && "We can't re-split our own alloca!");
4175         Worklist.insert(OtherAI);
4176       }
4177     }
4178 
4179     // Mark the original store as dead now that we've split it up and kill its
4180     // slice. Note that we leave the original load in place unless this store
4181     // was its only use. It may in turn be split up if it is an alloca load
4182     // for some other alloca, but it may be a normal load. This may introduce
4183     // redundant loads, but where those can be merged the rest of the optimizer
4184     // should handle the merging, and this uncovers SSA splits which is more
4185     // important. In practice, the original loads will almost always be fully
4186     // split and removed eventually, and the splits will be merged by any
4187     // trivial CSE, including instcombine.
4188     if (LI->hasOneUse()) {
4189       assert(*LI->user_begin() == SI && "Single use isn't this store!");
4190       DeadInsts.insert(LI);
4191     }
4192     DeadInsts.insert(SI);
4193     Offsets.S->kill();
4194   }
4195 
4196   // Remove the killed slices that have ben pre-split.
4197   AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }),
4198            AS.end());
4199 
4200   // Insert our new slices. This will sort and merge them into the sorted
4201   // sequence.
4202   AS.insert(NewSlices);
4203 
4204   LLVM_DEBUG(dbgs() << "  Pre-split slices:\n");
4205 #ifndef NDEBUG
4206   for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
4207     LLVM_DEBUG(AS.print(dbgs(), I, "    "));
4208 #endif
4209 
4210   // Finally, don't try to promote any allocas that new require re-splitting.
4211   // They have already been added to the worklist above.
4212   PromotableAllocas.erase(
4213       llvm::remove_if(
4214           PromotableAllocas,
4215           [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
4216       PromotableAllocas.end());
4217 
4218   return true;
4219 }
4220 
4221 /// Rewrite an alloca partition's users.
4222 ///
4223 /// This routine drives both of the rewriting goals of the SROA pass. It tries
4224 /// to rewrite uses of an alloca partition to be conducive for SSA value
4225 /// promotion. If the partition needs a new, more refined alloca, this will
4226 /// build that new alloca, preserving as much type information as possible, and
4227 /// rewrite the uses of the old alloca to point at the new one and have the
4228 /// appropriate new offsets. It also evaluates how successful the rewrite was
4229 /// at enabling promotion and if it was successful queues the alloca to be
4230 /// promoted.
rewritePartition(AllocaInst & AI,AllocaSlices & AS,Partition & P)4231 AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
4232                                    Partition &P) {
4233   // Try to compute a friendly type for this partition of the alloca. This
4234   // won't always succeed, in which case we fall back to a legal integer type
4235   // or an i8 array of an appropriate size.
4236   Type *SliceTy = nullptr;
4237   const DataLayout &DL = AI.getModule()->getDataLayout();
4238   if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
4239     if (DL.getTypeAllocSize(CommonUseTy).getFixedSize() >= P.size())
4240       SliceTy = CommonUseTy;
4241   if (!SliceTy)
4242     if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
4243                                                  P.beginOffset(), P.size()))
4244       SliceTy = TypePartitionTy;
4245   if ((!SliceTy || (SliceTy->isArrayTy() &&
4246                     SliceTy->getArrayElementType()->isIntegerTy())) &&
4247       DL.isLegalInteger(P.size() * 8))
4248     SliceTy = Type::getIntNTy(*C, P.size() * 8);
4249   if (!SliceTy)
4250     SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
4251   assert(DL.getTypeAllocSize(SliceTy).getFixedSize() >= P.size());
4252 
4253   bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
4254 
4255   VectorType *VecTy =
4256       IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
4257   if (VecTy)
4258     SliceTy = VecTy;
4259 
4260   // Check for the case where we're going to rewrite to a new alloca of the
4261   // exact same type as the original, and with the same access offsets. In that
4262   // case, re-use the existing alloca, but still run through the rewriter to
4263   // perform phi and select speculation.
4264   // P.beginOffset() can be non-zero even with the same type in a case with
4265   // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
4266   AllocaInst *NewAI;
4267   if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) {
4268     NewAI = &AI;
4269     // FIXME: We should be able to bail at this point with "nothing changed".
4270     // FIXME: We might want to defer PHI speculation until after here.
4271     // FIXME: return nullptr;
4272   } else {
4273     // Make sure the alignment is compatible with P.beginOffset().
4274     const Align Alignment = commonAlignment(AI.getAlign(), P.beginOffset());
4275     // If we will get at least this much alignment from the type alone, leave
4276     // the alloca's alignment unconstrained.
4277     const bool IsUnconstrained = Alignment <= DL.getABITypeAlign(SliceTy);
4278     NewAI = new AllocaInst(
4279         SliceTy, AI.getType()->getAddressSpace(), nullptr,
4280         IsUnconstrained ? DL.getPrefTypeAlign(SliceTy) : Alignment,
4281         AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
4282     // Copy the old AI debug location over to the new one.
4283     NewAI->setDebugLoc(AI.getDebugLoc());
4284     ++NumNewAllocas;
4285   }
4286 
4287   LLVM_DEBUG(dbgs() << "Rewriting alloca partition "
4288                     << "[" << P.beginOffset() << "," << P.endOffset()
4289                     << ") to: " << *NewAI << "\n");
4290 
4291   // Track the high watermark on the worklist as it is only relevant for
4292   // promoted allocas. We will reset it to this point if the alloca is not in
4293   // fact scheduled for promotion.
4294   unsigned PPWOldSize = PostPromotionWorklist.size();
4295   unsigned NumUses = 0;
4296   SmallSetVector<PHINode *, 8> PHIUsers;
4297   SmallSetVector<SelectInst *, 8> SelectUsers;
4298 
4299   AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
4300                                P.endOffset(), IsIntegerPromotable, VecTy,
4301                                PHIUsers, SelectUsers);
4302   bool Promotable = true;
4303   for (Slice *S : P.splitSliceTails()) {
4304     Promotable &= Rewriter.visit(S);
4305     ++NumUses;
4306   }
4307   for (Slice &S : P) {
4308     Promotable &= Rewriter.visit(&S);
4309     ++NumUses;
4310   }
4311 
4312   NumAllocaPartitionUses += NumUses;
4313   MaxUsesPerAllocaPartition.updateMax(NumUses);
4314 
4315   // Now that we've processed all the slices in the new partition, check if any
4316   // PHIs or Selects would block promotion.
4317   for (PHINode *PHI : PHIUsers)
4318     if (!isSafePHIToSpeculate(*PHI)) {
4319       Promotable = false;
4320       PHIUsers.clear();
4321       SelectUsers.clear();
4322       break;
4323     }
4324 
4325   for (SelectInst *Sel : SelectUsers)
4326     if (!isSafeSelectToSpeculate(*Sel)) {
4327       Promotable = false;
4328       PHIUsers.clear();
4329       SelectUsers.clear();
4330       break;
4331     }
4332 
4333   if (Promotable) {
4334     if (PHIUsers.empty() && SelectUsers.empty()) {
4335       // Promote the alloca.
4336       PromotableAllocas.push_back(NewAI);
4337     } else {
4338       // If we have either PHIs or Selects to speculate, add them to those
4339       // worklists and re-queue the new alloca so that we promote in on the
4340       // next iteration.
4341       for (PHINode *PHIUser : PHIUsers)
4342         SpeculatablePHIs.insert(PHIUser);
4343       for (SelectInst *SelectUser : SelectUsers)
4344         SpeculatableSelects.insert(SelectUser);
4345       Worklist.insert(NewAI);
4346     }
4347   } else {
4348     // Drop any post-promotion work items if promotion didn't happen.
4349     while (PostPromotionWorklist.size() > PPWOldSize)
4350       PostPromotionWorklist.pop_back();
4351 
4352     // We couldn't promote and we didn't create a new partition, nothing
4353     // happened.
4354     if (NewAI == &AI)
4355       return nullptr;
4356 
4357     // If we can't promote the alloca, iterate on it to check for new
4358     // refinements exposed by splitting the current alloca. Don't iterate on an
4359     // alloca which didn't actually change and didn't get promoted.
4360     Worklist.insert(NewAI);
4361   }
4362 
4363   return NewAI;
4364 }
4365 
4366 /// Walks the slices of an alloca and form partitions based on them,
4367 /// rewriting each of their uses.
splitAlloca(AllocaInst & AI,AllocaSlices & AS)4368 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4369   if (AS.begin() == AS.end())
4370     return false;
4371 
4372   unsigned NumPartitions = 0;
4373   bool Changed = false;
4374   const DataLayout &DL = AI.getModule()->getDataLayout();
4375 
4376   // First try to pre-split loads and stores.
4377   Changed |= presplitLoadsAndStores(AI, AS);
4378 
4379   // Now that we have identified any pre-splitting opportunities,
4380   // mark loads and stores unsplittable except for the following case.
4381   // We leave a slice splittable if all other slices are disjoint or fully
4382   // included in the slice, such as whole-alloca loads and stores.
4383   // If we fail to split these during pre-splitting, we want to force them
4384   // to be rewritten into a partition.
4385   bool IsSorted = true;
4386 
4387   uint64_t AllocaSize =
4388       DL.getTypeAllocSize(AI.getAllocatedType()).getFixedSize();
4389   const uint64_t MaxBitVectorSize = 1024;
4390   if (AllocaSize <= MaxBitVectorSize) {
4391     // If a byte boundary is included in any load or store, a slice starting or
4392     // ending at the boundary is not splittable.
4393     SmallBitVector SplittableOffset(AllocaSize + 1, true);
4394     for (Slice &S : AS)
4395       for (unsigned O = S.beginOffset() + 1;
4396            O < S.endOffset() && O < AllocaSize; O++)
4397         SplittableOffset.reset(O);
4398 
4399     for (Slice &S : AS) {
4400       if (!S.isSplittable())
4401         continue;
4402 
4403       if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4404           (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4405         continue;
4406 
4407       if (isa<LoadInst>(S.getUse()->getUser()) ||
4408           isa<StoreInst>(S.getUse()->getUser())) {
4409         S.makeUnsplittable();
4410         IsSorted = false;
4411       }
4412     }
4413   }
4414   else {
4415     // We only allow whole-alloca splittable loads and stores
4416     // for a large alloca to avoid creating too large BitVector.
4417     for (Slice &S : AS) {
4418       if (!S.isSplittable())
4419         continue;
4420 
4421       if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4422         continue;
4423 
4424       if (isa<LoadInst>(S.getUse()->getUser()) ||
4425           isa<StoreInst>(S.getUse()->getUser())) {
4426         S.makeUnsplittable();
4427         IsSorted = false;
4428       }
4429     }
4430   }
4431 
4432   if (!IsSorted)
4433     llvm::sort(AS);
4434 
4435   /// Describes the allocas introduced by rewritePartition in order to migrate
4436   /// the debug info.
4437   struct Fragment {
4438     AllocaInst *Alloca;
4439     uint64_t Offset;
4440     uint64_t Size;
4441     Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
4442       : Alloca(AI), Offset(O), Size(S) {}
4443   };
4444   SmallVector<Fragment, 4> Fragments;
4445 
4446   // Rewrite each partition.
4447   for (auto &P : AS.partitions()) {
4448     if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4449       Changed = true;
4450       if (NewAI != &AI) {
4451         uint64_t SizeOfByte = 8;
4452         uint64_t AllocaSize =
4453             DL.getTypeSizeInBits(NewAI->getAllocatedType()).getFixedSize();
4454         // Don't include any padding.
4455         uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
4456         Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
4457       }
4458     }
4459     ++NumPartitions;
4460   }
4461 
4462   NumAllocaPartitions += NumPartitions;
4463   MaxPartitionsPerAlloca.updateMax(NumPartitions);
4464 
4465   // Migrate debug information from the old alloca to the new alloca(s)
4466   // and the individual partitions.
4467   TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
4468   if (!DbgDeclares.empty()) {
4469     auto *Var = DbgDeclares.front()->getVariable();
4470     auto *Expr = DbgDeclares.front()->getExpression();
4471     auto VarSize = Var->getSizeInBits();
4472     DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
4473     uint64_t AllocaSize =
4474         DL.getTypeSizeInBits(AI.getAllocatedType()).getFixedSize();
4475     for (auto Fragment : Fragments) {
4476       // Create a fragment expression describing the new partition or reuse AI's
4477       // expression if there is only one partition.
4478       auto *FragmentExpr = Expr;
4479       if (Fragment.Size < AllocaSize || Expr->isFragment()) {
4480         // If this alloca is already a scalar replacement of a larger aggregate,
4481         // Fragment.Offset describes the offset inside the scalar.
4482         auto ExprFragment = Expr->getFragmentInfo();
4483         uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
4484         uint64_t Start = Offset + Fragment.Offset;
4485         uint64_t Size = Fragment.Size;
4486         if (ExprFragment) {
4487           uint64_t AbsEnd =
4488               ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
4489           if (Start >= AbsEnd)
4490             // No need to describe a SROAed padding.
4491             continue;
4492           Size = std::min(Size, AbsEnd - Start);
4493         }
4494         // The new, smaller fragment is stenciled out from the old fragment.
4495         if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4496           assert(Start >= OrigFragment->OffsetInBits &&
4497                  "new fragment is outside of original fragment");
4498           Start -= OrigFragment->OffsetInBits;
4499         }
4500 
4501         // The alloca may be larger than the variable.
4502         if (VarSize) {
4503           if (Size > *VarSize)
4504             Size = *VarSize;
4505           if (Size == 0 || Start + Size > *VarSize)
4506             continue;
4507         }
4508 
4509         // Avoid creating a fragment expression that covers the entire variable.
4510         if (!VarSize || *VarSize != Size) {
4511           if (auto E =
4512                   DIExpression::createFragmentExpression(Expr, Start, Size))
4513             FragmentExpr = *E;
4514           else
4515             continue;
4516         }
4517       }
4518 
4519       // Remove any existing intrinsics describing the same alloca.
4520       for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca))
4521         OldDII->eraseFromParent();
4522 
4523       DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
4524                         DbgDeclares.front()->getDebugLoc(), &AI);
4525     }
4526   }
4527   return Changed;
4528 }
4529 
4530 /// Clobber a use with undef, deleting the used value if it becomes dead.
clobberUse(Use & U)4531 void SROA::clobberUse(Use &U) {
4532   Value *OldV = U;
4533   // Replace the use with an undef value.
4534   U = UndefValue::get(OldV->getType());
4535 
4536   // Check for this making an instruction dead. We have to garbage collect
4537   // all the dead instructions to ensure the uses of any alloca end up being
4538   // minimal.
4539   if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4540     if (isInstructionTriviallyDead(OldI)) {
4541       DeadInsts.insert(OldI);
4542     }
4543 }
4544 
4545 /// Analyze an alloca for SROA.
4546 ///
4547 /// This analyzes the alloca to ensure we can reason about it, builds
4548 /// the slices of the alloca, and then hands it off to be split and
4549 /// rewritten as needed.
runOnAlloca(AllocaInst & AI)4550 bool SROA::runOnAlloca(AllocaInst &AI) {
4551   LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4552   ++NumAllocasAnalyzed;
4553 
4554   // Special case dead allocas, as they're trivial.
4555   if (AI.use_empty()) {
4556     AI.eraseFromParent();
4557     return true;
4558   }
4559   const DataLayout &DL = AI.getModule()->getDataLayout();
4560 
4561   // Skip alloca forms that this analysis can't handle.
4562   auto *AT = AI.getAllocatedType();
4563   if (AI.isArrayAllocation() || !AT->isSized() || isa<ScalableVectorType>(AT) ||
4564       DL.getTypeAllocSize(AT).getFixedSize() == 0)
4565     return false;
4566 
4567   bool Changed = false;
4568 
4569   // First, split any FCA loads and stores touching this alloca to promote
4570   // better splitting and promotion opportunities.
4571   AggLoadStoreRewriter AggRewriter(DL);
4572   Changed |= AggRewriter.rewrite(AI);
4573 
4574   // Build the slices using a recursive instruction-visiting builder.
4575   AllocaSlices AS(DL, AI);
4576   LLVM_DEBUG(AS.print(dbgs()));
4577   if (AS.isEscaped())
4578     return Changed;
4579 
4580   // Delete all the dead users of this alloca before splitting and rewriting it.
4581   for (Instruction *DeadUser : AS.getDeadUsers()) {
4582     // Free up everything used by this instruction.
4583     for (Use &DeadOp : DeadUser->operands())
4584       clobberUse(DeadOp);
4585 
4586     // Now replace the uses of this instruction.
4587     DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
4588 
4589     // And mark it for deletion.
4590     DeadInsts.insert(DeadUser);
4591     Changed = true;
4592   }
4593   for (Use *DeadOp : AS.getDeadOperands()) {
4594     clobberUse(*DeadOp);
4595     Changed = true;
4596   }
4597 
4598   // No slices to split. Leave the dead alloca for a later pass to clean up.
4599   if (AS.begin() == AS.end())
4600     return Changed;
4601 
4602   Changed |= splitAlloca(AI, AS);
4603 
4604   LLVM_DEBUG(dbgs() << "  Speculating PHIs\n");
4605   while (!SpeculatablePHIs.empty())
4606     speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4607 
4608   LLVM_DEBUG(dbgs() << "  Speculating Selects\n");
4609   while (!SpeculatableSelects.empty())
4610     speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4611 
4612   return Changed;
4613 }
4614 
4615 /// Delete the dead instructions accumulated in this run.
4616 ///
4617 /// Recursively deletes the dead instructions we've accumulated. This is done
4618 /// at the very end to maximize locality of the recursive delete and to
4619 /// minimize the problems of invalidated instruction pointers as such pointers
4620 /// are used heavily in the intermediate stages of the algorithm.
4621 ///
4622 /// We also record the alloca instructions deleted here so that they aren't
4623 /// subsequently handed to mem2reg to promote.
deleteDeadInstructions(SmallPtrSetImpl<AllocaInst * > & DeletedAllocas)4624 bool SROA::deleteDeadInstructions(
4625     SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
4626   bool Changed = false;
4627   while (!DeadInsts.empty()) {
4628     Instruction *I = DeadInsts.pop_back_val();
4629     LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4630 
4631     // If the instruction is an alloca, find the possible dbg.declare connected
4632     // to it, and remove it too. We must do this before calling RAUW or we will
4633     // not be able to find it.
4634     if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4635       DeletedAllocas.insert(AI);
4636       for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI))
4637         OldDII->eraseFromParent();
4638     }
4639 
4640     I->replaceAllUsesWith(UndefValue::get(I->getType()));
4641 
4642     for (Use &Operand : I->operands())
4643       if (Instruction *U = dyn_cast<Instruction>(Operand)) {
4644         // Zero out the operand and see if it becomes trivially dead.
4645         Operand = nullptr;
4646         if (isInstructionTriviallyDead(U))
4647           DeadInsts.insert(U);
4648       }
4649 
4650     ++NumDeleted;
4651     I->eraseFromParent();
4652     Changed = true;
4653   }
4654   return Changed;
4655 }
4656 
4657 /// Promote the allocas, using the best available technique.
4658 ///
4659 /// This attempts to promote whatever allocas have been identified as viable in
4660 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
4661 /// This function returns whether any promotion occurred.
promoteAllocas(Function & F)4662 bool SROA::promoteAllocas(Function &F) {
4663   if (PromotableAllocas.empty())
4664     return false;
4665 
4666   NumPromoted += PromotableAllocas.size();
4667 
4668   LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
4669   PromoteMemToReg(PromotableAllocas, *DT, AC);
4670   PromotableAllocas.clear();
4671   return true;
4672 }
4673 
runImpl(Function & F,DominatorTree & RunDT,AssumptionCache & RunAC)4674 PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4675                                 AssumptionCache &RunAC) {
4676   LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4677   C = &F.getContext();
4678   DT = &RunDT;
4679   AC = &RunAC;
4680 
4681   BasicBlock &EntryBB = F.getEntryBlock();
4682   for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
4683        I != E; ++I) {
4684     if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4685       if (isa<ScalableVectorType>(AI->getAllocatedType())) {
4686         if (isAllocaPromotable(AI))
4687           PromotableAllocas.push_back(AI);
4688       } else {
4689         Worklist.insert(AI);
4690       }
4691     }
4692   }
4693 
4694   bool Changed = false;
4695   // A set of deleted alloca instruction pointers which should be removed from
4696   // the list of promotable allocas.
4697   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4698 
4699   do {
4700     while (!Worklist.empty()) {
4701       Changed |= runOnAlloca(*Worklist.pop_back_val());
4702       Changed |= deleteDeadInstructions(DeletedAllocas);
4703 
4704       // Remove the deleted allocas from various lists so that we don't try to
4705       // continue processing them.
4706       if (!DeletedAllocas.empty()) {
4707         auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
4708         Worklist.remove_if(IsInSet);
4709         PostPromotionWorklist.remove_if(IsInSet);
4710         PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet),
4711                                 PromotableAllocas.end());
4712         DeletedAllocas.clear();
4713       }
4714     }
4715 
4716     Changed |= promoteAllocas(F);
4717 
4718     Worklist = PostPromotionWorklist;
4719     PostPromotionWorklist.clear();
4720   } while (!Worklist.empty());
4721 
4722   if (!Changed)
4723     return PreservedAnalyses::all();
4724 
4725   PreservedAnalyses PA;
4726   PA.preserveSet<CFGAnalyses>();
4727   PA.preserve<GlobalsAA>();
4728   return PA;
4729 }
4730 
run(Function & F,FunctionAnalysisManager & AM)4731 PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
4732   return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4733                  AM.getResult<AssumptionAnalysis>(F));
4734 }
4735 
4736 /// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4737 ///
4738 /// This is in the llvm namespace purely to allow it to be a friend of the \c
4739 /// SROA pass.
4740 class llvm::sroa::SROALegacyPass : public FunctionPass {
4741   /// The SROA implementation.
4742   SROA Impl;
4743 
4744 public:
4745   static char ID;
4746 
SROALegacyPass()4747   SROALegacyPass() : FunctionPass(ID) {
4748     initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4749   }
4750 
runOnFunction(Function & F)4751   bool runOnFunction(Function &F) override {
4752     if (skipFunction(F))
4753       return false;
4754 
4755     auto PA = Impl.runImpl(
4756         F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4757         getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
4758     return !PA.areAllPreserved();
4759   }
4760 
getAnalysisUsage(AnalysisUsage & AU) const4761   void getAnalysisUsage(AnalysisUsage &AU) const override {
4762     AU.addRequired<AssumptionCacheTracker>();
4763     AU.addRequired<DominatorTreeWrapperPass>();
4764     AU.addPreserved<GlobalsAAWrapperPass>();
4765     AU.setPreservesCFG();
4766   }
4767 
getPassName() const4768   StringRef getPassName() const override { return "SROA"; }
4769 };
4770 
4771 char SROALegacyPass::ID = 0;
4772 
createSROAPass()4773 FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4774 
4775 INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4776                       "Scalar Replacement Of Aggregates", false, false)
4777 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4778 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4779 INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4780                     false, false)
4781