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