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