OSDN Git Service

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