]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/Transforms/Scalar/SROA.cpp
[SROA] Change how SROA does vector-based promotion of allocas to handle
[opencl/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 //===----------------------------------------------------------------------===//
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"
60 #if __cplusplus >= 201103L && !defined(NDEBUG)
61 // We only use this for a debug check in C++11
62 #include <random>
63 #endif
65 using namespace llvm;
67 #define DEBUG_TYPE "sroa"
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");
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);
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);
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);
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;
103 public:
104   void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
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 };
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 };
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
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;
143   /// \brief The ending offset, not included in the range.
144   uint64_t EndOffset;
146   /// \brief Storage for both the use of this slice and whether it can be
147   /// split.
148   PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
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) {}
156   uint64_t beginOffset() const { return BeginOffset; }
157   uint64_t endOffset() const { return EndOffset; }
159   bool isSplittable() const { return UseAndIsSplittable.getInt(); }
160   void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
162   Use *getUse() const { return UseAndIsSplittable.getPointer(); }
164   bool isDead() const { return getUse() == nullptr; }
165   void kill() { UseAndIsSplittable.setPointer(nullptr); }
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   }
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   }
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
199 namespace llvm {
200 template <typename T> struct isPodLike;
201 template <> struct isPodLike<Slice> {
202    static const bool value = true;
203 };
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);
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; }
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(); }
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   /// @}
238   /// \brief Access the dead users for this alloca.
239   ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
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; }
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
260 private:
261   template <typename DerivedT, typename RetT = void> class BuilderBase;
262   class SliceBuilder;
263   friend class AllocaSlices::SliceBuilder;
265 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
266   /// \brief Handle to alloca instruction to simplify method interfaces.
267   AllocaInst &AI;
268 #endif
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;
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;
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;
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 };
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);
315   return nullptr;
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));
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;
336   const uint64_t AllocSize;
337   AllocaSlices &AS;
339   SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
340   SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
342   /// \brief Set to de-duplicate dead instructions found in the use walk.
343   SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
345 public:
346   SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
347       : PtrUseVisitor<SliceBuilder>(DL),
348         AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
350 private:
351   void markAsDead(Instruction &I) {
352     if (VisitedDeadInsts.insert(&I))
353       AS.DeadUsers.push_back(&I);
354   }
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: " << AS.AI << "\n"
365                    << "       use: " << I << "\n");
366       return markAsDead(I);
367     }
369     uint64_t BeginOffset = Offset.getZExtValue();
370     uint64_t EndOffset = BeginOffset + Size;
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: " << AS.AI << "\n"
383                    << "       use: " << I << "\n");
384       EndOffset = AllocSize;
385     }
387     AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
388   }
390   void visitBitCastInst(BitCastInst &BC) {
391     if (BC.use_empty())
392       return markAsDead(BC);
394     return Base::visitBitCastInst(BC);
395   }
397   void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
398     if (GEPI.use_empty())
399       return markAsDead(GEPI);
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;
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         }
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     }
438     return Base::visitGetElementPtrInst(GEPI);
439   }
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;
454     insertUse(I, Offset, Size, IsSplittable);
455   }
457   void visitLoadInst(LoadInst &LI) {
458     assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
459            "All simple FCA loads should have been pre-split");
461     if (!IsOffsetKnown)
462       return PI.setAborted(&LI);
464     uint64_t Size = DL.getTypeStoreSize(LI.getType());
465     return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
466   }
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);
475     uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
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: " << AS.AI << "\n"
489                    << "       use: " << SI << "\n");
490       return markAsDead(SI);
491     }
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   }
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);
507     if (!IsOffsetKnown)
508       return PI.setAborted(&II);
510     insertUse(II, Offset,
511               Length ? Length->getLimitedValue()
512                      : AllocSize - Offset.getLimitedValue(),
513               (bool)Length);
514   }
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);
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;
527     if (!IsOffsetKnown)
528       return PI.setAborted(&II);
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         AS.Slices[MTPI->second].kill();
539       return markAsDead(II);
540     }
542     uint64_t RawOffset = Offset.getLimitedValue();
543     uint64_t Size = Length ? Length->getLimitedValue()
544                            : AllocSize - RawOffset;
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);
553       return insertUse(II, Offset, Size, /*IsSplittable=*/false);
554     }
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, AS.Slices.size()));
562     unsigned PrevIdx = MTPI->second;
563     if (!Inserted) {
564       Slice &PrevP = AS.Slices[PrevIdx];
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       }
573       // Otherwise we have an offset transfer within the same alloca. We can't
574       // split those.
575       PrevP.makeUnsplittable();
576     }
578     // Insert the use now that we've fixed up the splittable nature.
579     insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
581     // Check that we ended up with a valid index in the map.
582     assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
583            "Map index doesn't point back to a slice with this user.");
584   }
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);
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     }
602     Base::visitIntrinsicInst(II);
603   }
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();
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       }
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       }
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());
646     return nullptr;
647   }
649   void visitPHINodeOrSelectInst(Instruction &I) {
650     assert(isa<PHINode>(I) || isa<SelectInst>(I));
651     if (I.use_empty())
652       return markAsDead(I);
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         AS.DeadOperands.push_back(U);
672       return;
673     }
675     if (!IsOffsetKnown)
676       return PI.setAborted(&I);
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     }
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       AS.DeadOperands.push_back(U);
694       return;
695     }
697     insertUse(I, Offset, Size);
698   }
700   void visitPHINode(PHINode &PN) {
701     visitPHINodeOrSelectInst(PN);
702   }
704   void visitSelectInst(SelectInst &SI) {
705     visitPHINodeOrSelectInst(SI);
706   }
708   /// \brief Disable SROA entirely if there are unhandled users of the alloca.
709   void visitInstruction(Instruction &I) {
710     PI.setAborted(&I);
711   }
712 };
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   }
731   Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
732                               std::mem_fun_ref(&Slice::isDead)),
733                Slices.end());
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
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());
747 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
749 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
750                          StringRef Indent) const {
751   printSlice(OS, I, Indent);
752   printUse(OS, I, Indent);
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";
762 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
763                             StringRef Indent) const {
764   OS << Indent << "  used by: " << *I->getUse()->getUser() << "\n";
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   }
775   OS << "Slices of alloca: " << AI << "\n";
776   for (const_iterator I = begin(), E = end(); I != E; ++I)
777     print(OS, I);
780 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
781   print(dbgs(), I);
783 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
785 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
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;
799   SmallVector<DbgDeclareInst *, 4> DDIs;
800   SmallVector<DbgValueInst *, 4> DVIs;
802 public:
803   AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
804                  AllocaInst &AI, DIBuilder &DIB)
805       : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
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     }
818     LoadAndStorePromoter::run(Insts);
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   }
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();
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;
840     do {
841       if (Ptr == &AI)
842         return true;
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;
851     } while (Visited.insert(Ptr));
853     return false;
854   }
856   void updateDebugInfo(Instruction *Inst) const override {
857     for (DbgDeclareInst *DDI : DDIs)
858       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
859         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
860       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
861         ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
862     for (DbgValueInst *DVI : DVIs) {
863       Value *Arg = nullptr;
864       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
865         // If an argument is zero extended then use argument directly. The ZExt
866         // may be zapped by an optimization pass in future.
867         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
868           Arg = dyn_cast<Argument>(ZExt->getOperand(0));
869         else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
870           Arg = dyn_cast<Argument>(SExt->getOperand(0));
871         if (!Arg)
872           Arg = SI->getValueOperand();
873       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
874         Arg = LI->getPointerOperand();
875       } else {
876         continue;
877       }
878       Instruction *DbgVal =
879           DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
880                                       DIExpression(DVI->getExpression()), Inst);
881       DbgVal->setDebugLoc(DVI->getDebugLoc());
882     }
883   }
884 };
885 } // end anon namespace
888 namespace {
889 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
890 ///
891 /// This pass takes allocations which can be completely analyzed (that is, they
892 /// don't escape) and tries to turn them into scalar SSA values. There are
893 /// a few steps to this process.
894 ///
895 /// 1) It takes allocations of aggregates and analyzes the ways in which they
896 ///    are used to try to split them into smaller allocations, ideally of
897 ///    a single scalar data type. It will split up memcpy and memset accesses
898 ///    as necessary and try to isolate individual scalar accesses.
899 /// 2) It will transform accesses into forms which are suitable for SSA value
900 ///    promotion. This can be replacing a memset with a scalar store of an
901 ///    integer value, or it can involve speculating operations on a PHI or
902 ///    select to be a PHI or select of the results.
903 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
904 ///    onto insert and extract operations on a vector value, and convert them to
905 ///    this form. By doing so, it will enable promotion of vector aggregates to
906 ///    SSA vector values.
907 class SROA : public FunctionPass {
908   const bool RequiresDomTree;
910   LLVMContext *C;
911   const DataLayout *DL;
912   DominatorTree *DT;
913   AssumptionTracker *AT;
915   /// \brief Worklist of alloca instructions to simplify.
916   ///
917   /// Each alloca in the function is added to this. Each new alloca formed gets
918   /// added to it as well to recursively simplify unless that alloca can be
919   /// directly promoted. Finally, each time we rewrite a use of an alloca other
920   /// the one being actively rewritten, we add it back onto the list if not
921   /// already present to ensure it is re-visited.
922   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
924   /// \brief A collection of instructions to delete.
925   /// We try to batch deletions to simplify code and make things a bit more
926   /// efficient.
927   SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
929   /// \brief Post-promotion worklist.
930   ///
931   /// Sometimes we discover an alloca which has a high probability of becoming
932   /// viable for SROA after a round of promotion takes place. In those cases,
933   /// the alloca is enqueued here for re-processing.
934   ///
935   /// Note that we have to be very careful to clear allocas out of this list in
936   /// the event they are deleted.
937   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
939   /// \brief A collection of alloca instructions we can directly promote.
940   std::vector<AllocaInst *> PromotableAllocas;
942   /// \brief A worklist of PHIs to speculate prior to promoting allocas.
943   ///
944   /// All of these PHIs have been checked for the safety of speculation and by
945   /// being speculated will allow promoting allocas currently in the promotable
946   /// queue.
947   SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
949   /// \brief A worklist of select instructions to speculate prior to promoting
950   /// allocas.
951   ///
952   /// All of these select instructions have been checked for the safety of
953   /// speculation and by being speculated will allow promoting allocas
954   /// currently in the promotable queue.
955   SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
957 public:
958   SROA(bool RequiresDomTree = true)
959       : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
960         C(nullptr), DL(nullptr), DT(nullptr) {
961     initializeSROAPass(*PassRegistry::getPassRegistry());
962   }
963   bool runOnFunction(Function &F) override;
964   void getAnalysisUsage(AnalysisUsage &AU) const override;
966   const char *getPassName() const override { return "SROA"; }
967   static char ID;
969 private:
970   friend class PHIOrSelectSpeculator;
971   friend class AllocaSliceRewriter;
973   bool rewritePartition(AllocaInst &AI, AllocaSlices &AS,
974                         AllocaSlices::iterator B, AllocaSlices::iterator E,
975                         int64_t BeginOffset, int64_t EndOffset,
976                         ArrayRef<AllocaSlices::iterator> SplitUses);
977   bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
978   bool runOnAlloca(AllocaInst &AI);
979   void clobberUse(Use &U);
980   void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
981   bool promoteAllocas(Function &F);
982 };
985 char SROA::ID = 0;
987 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
988   return new SROA(RequiresDomTree);
991 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
992                       false, false)
993 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
994 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
995 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
996                     false, false)
998 /// Walk the range of a partitioning looking for a common type to cover this
999 /// sequence of slices.
1000 static Type *findCommonType(AllocaSlices::const_iterator B,
1001                             AllocaSlices::const_iterator E,
1002                             uint64_t EndOffset) {
1003   Type *Ty = nullptr;
1004   bool TyIsCommon = true;
1005   IntegerType *ITy = nullptr;
1007   // Note that we need to look at *every* alloca slice's Use to ensure we
1008   // always get consistent results regardless of the order of slices.
1009   for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1010     Use *U = I->getUse();
1011     if (isa<IntrinsicInst>(*U->getUser()))
1012       continue;
1013     if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1014       continue;
1016     Type *UserTy = nullptr;
1017     if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1018       UserTy = LI->getType();
1019     } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1020       UserTy = SI->getValueOperand()->getType();
1021     }
1023     if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1024       // If the type is larger than the partition, skip it. We only encounter
1025       // this for split integer operations where we want to use the type of the
1026       // entity causing the split. Also skip if the type is not a byte width
1027       // multiple.
1028       if (UserITy->getBitWidth() % 8 != 0 ||
1029           UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1030         continue;
1032       // Track the largest bitwidth integer type used in this way in case there
1033       // is no common type.
1034       if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1035         ITy = UserITy;
1036     }
1038     // To avoid depending on the order of slices, Ty and TyIsCommon must not
1039     // depend on types skipped above.
1040     if (!UserTy || (Ty && Ty != UserTy))
1041       TyIsCommon = false; // Give up on anything but an iN type.
1042     else
1043       Ty = UserTy;
1044   }
1046   return TyIsCommon ? Ty : ITy;
1049 /// PHI instructions that use an alloca and are subsequently loaded can be
1050 /// rewritten to load both input pointers in the pred blocks and then PHI the
1051 /// results, allowing the load of the alloca to be promoted.
1052 /// From this:
1053 ///   %P2 = phi [i32* %Alloca, i32* %Other]
1054 ///   %V = load i32* %P2
1055 /// to:
1056 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1057 ///   ...
1058 ///   %V2 = load i32* %Other
1059 ///   ...
1060 ///   %V = phi [i32 %V1, i32 %V2]
1061 ///
1062 /// We can do this to a select if its only uses are loads and if the operands
1063 /// to the select can be loaded unconditionally.
1064 ///
1065 /// FIXME: This should be hoisted into a generic utility, likely in
1066 /// Transforms/Util/Local.h
1067 static bool isSafePHIToSpeculate(PHINode &PN,
1068                                  const DataLayout *DL = nullptr) {
1069   // For now, we can only do this promotion if the load is in the same block
1070   // as the PHI, and if there are no stores between the phi and load.
1071   // TODO: Allow recursive phi users.
1072   // TODO: Allow stores.
1073   BasicBlock *BB = PN.getParent();
1074   unsigned MaxAlign = 0;
1075   bool HaveLoad = false;
1076   for (User *U : PN.users()) {
1077     LoadInst *LI = dyn_cast<LoadInst>(U);
1078     if (!LI || !LI->isSimple())
1079       return false;
1081     // For now we only allow loads in the same block as the PHI.  This is
1082     // a common case that happens when instcombine merges two loads through
1083     // a PHI.
1084     if (LI->getParent() != BB)
1085       return false;
1087     // Ensure that there are no instructions between the PHI and the load that
1088     // could store.
1089     for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1090       if (BBI->mayWriteToMemory())
1091         return false;
1093     MaxAlign = std::max(MaxAlign, LI->getAlignment());
1094     HaveLoad = true;
1095   }
1097   if (!HaveLoad)
1098     return false;
1100   // We can only transform this if it is safe to push the loads into the
1101   // predecessor blocks. The only thing to watch out for is that we can't put
1102   // a possibly trapping load in the predecessor if it is a critical edge.
1103   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1104     TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1105     Value *InVal = PN.getIncomingValue(Idx);
1107     // If the value is produced by the terminator of the predecessor (an
1108     // invoke) or it has side-effects, there is no valid place to put a load
1109     // in the predecessor.
1110     if (TI == InVal || TI->mayHaveSideEffects())
1111       return false;
1113     // If the predecessor has a single successor, then the edge isn't
1114     // critical.
1115     if (TI->getNumSuccessors() == 1)
1116       continue;
1118     // If this pointer is always safe to load, or if we can prove that there
1119     // is already a load in the block, then we can move the load to the pred
1120     // block.
1121     if (InVal->isDereferenceablePointer(DL) ||
1122         isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
1123       continue;
1125     return false;
1126   }
1128   return true;
1131 static void speculatePHINodeLoads(PHINode &PN) {
1132   DEBUG(dbgs() << "    original: " << PN << "\n");
1134   Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1135   IRBuilderTy PHIBuilder(&PN);
1136   PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1137                                         PN.getName() + ".sroa.speculated");
1139   // Get the AA tags and alignment to use from one of the loads.  It doesn't
1140   // matter which one we get and if any differ.
1141   LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1143   AAMDNodes AATags;
1144   SomeLoad->getAAMetadata(AATags);
1145   unsigned Align = SomeLoad->getAlignment();
1147   // Rewrite all loads of the PN to use the new PHI.
1148   while (!PN.use_empty()) {
1149     LoadInst *LI = cast<LoadInst>(PN.user_back());
1150     LI->replaceAllUsesWith(NewPN);
1151     LI->eraseFromParent();
1152   }
1154   // Inject loads into all of the pred blocks.
1155   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1156     BasicBlock *Pred = PN.getIncomingBlock(Idx);
1157     TerminatorInst *TI = Pred->getTerminator();
1158     Value *InVal = PN.getIncomingValue(Idx);
1159     IRBuilderTy PredBuilder(TI);
1161     LoadInst *Load = PredBuilder.CreateLoad(
1162         InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1163     ++NumLoadsSpeculated;
1164     Load->setAlignment(Align);
1165     if (AATags)
1166       Load->setAAMetadata(AATags);
1167     NewPN->addIncoming(Load, Pred);
1168   }
1170   DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
1171   PN.eraseFromParent();
1174 /// Select instructions that use an alloca and are subsequently loaded can be
1175 /// rewritten to load both input pointers and then select between the result,
1176 /// allowing the load of the alloca to be promoted.
1177 /// From this:
1178 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1179 ///   %V = load i32* %P2
1180 /// to:
1181 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1182 ///   %V2 = load i32* %Other
1183 ///   %V = select i1 %cond, i32 %V1, i32 %V2
1184 ///
1185 /// We can do this to a select if its only uses are loads and if the operand
1186 /// to the select can be loaded unconditionally.
1187 static bool isSafeSelectToSpeculate(SelectInst &SI,
1188                                     const DataLayout *DL = nullptr) {
1189   Value *TValue = SI.getTrueValue();
1190   Value *FValue = SI.getFalseValue();
1191   bool TDerefable = TValue->isDereferenceablePointer(DL);
1192   bool FDerefable = FValue->isDereferenceablePointer(DL);
1194   for (User *U : SI.users()) {
1195     LoadInst *LI = dyn_cast<LoadInst>(U);
1196     if (!LI || !LI->isSimple())
1197       return false;
1199     // Both operands to the select need to be dereferencable, either
1200     // absolutely (e.g. allocas) or at this point because we can see other
1201     // accesses to it.
1202     if (!TDerefable &&
1203         !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
1204       return false;
1205     if (!FDerefable &&
1206         !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
1207       return false;
1208   }
1210   return true;
1213 static void speculateSelectInstLoads(SelectInst &SI) {
1214   DEBUG(dbgs() << "    original: " << SI << "\n");
1216   IRBuilderTy IRB(&SI);
1217   Value *TV = SI.getTrueValue();
1218   Value *FV = SI.getFalseValue();
1219   // Replace the loads of the select with a select of two loads.
1220   while (!SI.use_empty()) {
1221     LoadInst *LI = cast<LoadInst>(SI.user_back());
1222     assert(LI->isSimple() && "We only speculate simple loads");
1224     IRB.SetInsertPoint(LI);
1225     LoadInst *TL =
1226         IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1227     LoadInst *FL =
1228         IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1229     NumLoadsSpeculated += 2;
1231     // Transfer alignment and AA info if present.
1232     TL->setAlignment(LI->getAlignment());
1233     FL->setAlignment(LI->getAlignment());
1235     AAMDNodes Tags;
1236     LI->getAAMetadata(Tags);
1237     if (Tags) {
1238       TL->setAAMetadata(Tags);
1239       FL->setAAMetadata(Tags);
1240     }
1242     Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1243                                 LI->getName() + ".sroa.speculated");
1245     DEBUG(dbgs() << "          speculated to: " << *V << "\n");
1246     LI->replaceAllUsesWith(V);
1247     LI->eraseFromParent();
1248   }
1249   SI.eraseFromParent();
1252 /// \brief Build a GEP out of a base pointer and indices.
1253 ///
1254 /// This will return the BasePtr if that is valid, or build a new GEP
1255 /// instruction using the IRBuilder if GEP-ing is needed.
1256 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1257                        SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
1258   if (Indices.empty())
1259     return BasePtr;
1261   // A single zero index is a no-op, so check for this and avoid building a GEP
1262   // in that case.
1263   if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1264     return BasePtr;
1266   return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
1269 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1270 /// TargetTy without changing the offset of the pointer.
1271 ///
1272 /// This routine assumes we've already established a properly offset GEP with
1273 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1274 /// zero-indices down through type layers until we find one the same as
1275 /// TargetTy. If we can't find one with the same type, we at least try to use
1276 /// one with the same size. If none of that works, we just produce the GEP as
1277 /// indicated by Indices to have the correct offset.
1278 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1279                                     Value *BasePtr, Type *Ty, Type *TargetTy,
1280                                     SmallVectorImpl<Value *> &Indices,
1281                                     Twine NamePrefix) {
1282   if (Ty == TargetTy)
1283     return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1285   // Pointer size to use for the indices.
1286   unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1288   // See if we can descend into a struct and locate a field with the correct
1289   // type.
1290   unsigned NumLayers = 0;
1291   Type *ElementTy = Ty;
1292   do {
1293     if (ElementTy->isPointerTy())
1294       break;
1296     if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1297       ElementTy = ArrayTy->getElementType();
1298       Indices.push_back(IRB.getIntN(PtrSize, 0));
1299     } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1300       ElementTy = VectorTy->getElementType();
1301       Indices.push_back(IRB.getInt32(0));
1302     } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1303       if (STy->element_begin() == STy->element_end())
1304         break; // Nothing left to descend into.
1305       ElementTy = *STy->element_begin();
1306       Indices.push_back(IRB.getInt32(0));
1307     } else {
1308       break;
1309     }
1310     ++NumLayers;
1311   } while (ElementTy != TargetTy);
1312   if (ElementTy != TargetTy)
1313     Indices.erase(Indices.end() - NumLayers, Indices.end());
1315   return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1318 /// \brief Recursively compute indices for a natural GEP.
1319 ///
1320 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1321 /// element types adding appropriate indices for the GEP.
1322 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1323                                        Value *Ptr, Type *Ty, APInt &Offset,
1324                                        Type *TargetTy,
1325                                        SmallVectorImpl<Value *> &Indices,
1326                                        Twine NamePrefix) {
1327   if (Offset == 0)
1328     return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
1330   // We can't recurse through pointer types.
1331   if (Ty->isPointerTy())
1332     return nullptr;
1334   // We try to analyze GEPs over vectors here, but note that these GEPs are
1335   // extremely poorly defined currently. The long-term goal is to remove GEPing
1336   // over a vector from the IR completely.
1337   if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1338     unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1339     if (ElementSizeInBits % 8 != 0) {
1340       // GEPs over non-multiple of 8 size vector elements are invalid.
1341       return nullptr;
1342     }
1343     APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1344     APInt NumSkippedElements = Offset.sdiv(ElementSize);
1345     if (NumSkippedElements.ugt(VecTy->getNumElements()))
1346       return nullptr;
1347     Offset -= NumSkippedElements * ElementSize;
1348     Indices.push_back(IRB.getInt(NumSkippedElements));
1349     return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1350                                     Offset, TargetTy, Indices, NamePrefix);
1351   }
1353   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1354     Type *ElementTy = ArrTy->getElementType();
1355     APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1356     APInt NumSkippedElements = Offset.sdiv(ElementSize);
1357     if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1358       return nullptr;
1360     Offset -= NumSkippedElements * ElementSize;
1361     Indices.push_back(IRB.getInt(NumSkippedElements));
1362     return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1363                                     Indices, NamePrefix);
1364   }
1366   StructType *STy = dyn_cast<StructType>(Ty);
1367   if (!STy)
1368     return nullptr;
1370   const StructLayout *SL = DL.getStructLayout(STy);
1371   uint64_t StructOffset = Offset.getZExtValue();
1372   if (StructOffset >= SL->getSizeInBytes())
1373     return nullptr;
1374   unsigned Index = SL->getElementContainingOffset(StructOffset);
1375   Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1376   Type *ElementTy = STy->getElementType(Index);
1377   if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1378     return nullptr; // The offset points into alignment padding.
1380   Indices.push_back(IRB.getInt32(Index));
1381   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1382                                   Indices, NamePrefix);
1385 /// \brief Get a natural GEP from a base pointer to a particular offset and
1386 /// resulting in a particular type.
1387 ///
1388 /// The goal is to produce a "natural" looking GEP that works with the existing
1389 /// composite types to arrive at the appropriate offset and element type for
1390 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1391 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1392 /// Indices, and setting Ty to the result subtype.
1393 ///
1394 /// If no natural GEP can be constructed, this function returns null.
1395 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1396                                       Value *Ptr, APInt Offset, Type *TargetTy,
1397                                       SmallVectorImpl<Value *> &Indices,
1398                                       Twine NamePrefix) {
1399   PointerType *Ty = cast<PointerType>(Ptr->getType());
1401   // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1402   // an i8.
1403   if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
1404     return nullptr;
1406   Type *ElementTy = Ty->getElementType();
1407   if (!ElementTy->isSized())
1408     return nullptr; // We can't GEP through an unsized element.
1409   APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1410   if (ElementSize == 0)
1411     return nullptr; // Zero-length arrays can't help us build a natural GEP.
1412   APInt NumSkippedElements = Offset.sdiv(ElementSize);
1414   Offset -= NumSkippedElements * ElementSize;
1415   Indices.push_back(IRB.getInt(NumSkippedElements));
1416   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1417                                   Indices, NamePrefix);
1420 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1421 /// resulting pointer has PointerTy.
1422 ///
1423 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1424 /// and produces the pointer type desired. Where it cannot, it will try to use
1425 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1426 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1427 /// bitcast to the type.
1428 ///
1429 /// The strategy for finding the more natural GEPs is to peel off layers of the
1430 /// pointer, walking back through bit casts and GEPs, searching for a base
1431 /// pointer from which we can compute a natural GEP with the desired
1432 /// properties. The algorithm tries to fold as many constant indices into
1433 /// a single GEP as possible, thus making each GEP more independent of the
1434 /// surrounding code.
1435 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1436                              APInt Offset, Type *PointerTy,
1437                              Twine NamePrefix) {
1438   // Even though we don't look through PHI nodes, we could be called on an
1439   // instruction in an unreachable block, which may be on a cycle.
1440   SmallPtrSet<Value *, 4> Visited;
1441   Visited.insert(Ptr);
1442   SmallVector<Value *, 4> Indices;
1444   // We may end up computing an offset pointer that has the wrong type. If we
1445   // never are able to compute one directly that has the correct type, we'll
1446   // fall back to it, so keep it around here.
1447   Value *OffsetPtr = nullptr;
1449   // Remember any i8 pointer we come across to re-use if we need to do a raw
1450   // byte offset.
1451   Value *Int8Ptr = nullptr;
1452   APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1454   Type *TargetTy = PointerTy->getPointerElementType();
1456   do {
1457     // First fold any existing GEPs into the offset.
1458     while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1459       APInt GEPOffset(Offset.getBitWidth(), 0);
1460       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1461         break;
1462       Offset += GEPOffset;
1463       Ptr = GEP->getPointerOperand();
1464       if (!Visited.insert(Ptr))
1465         break;
1466     }
1468     // See if we can perform a natural GEP here.
1469     Indices.clear();
1470     if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1471                                            Indices, NamePrefix)) {
1472       if (P->getType() == PointerTy) {
1473         // Zap any offset pointer that we ended up computing in previous rounds.
1474         if (OffsetPtr && OffsetPtr->use_empty())
1475           if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1476             I->eraseFromParent();
1477         return P;
1478       }
1479       if (!OffsetPtr) {
1480         OffsetPtr = P;
1481       }
1482     }
1484     // Stash this pointer if we've found an i8*.
1485     if (Ptr->getType()->isIntegerTy(8)) {
1486       Int8Ptr = Ptr;
1487       Int8PtrOffset = Offset;
1488     }
1490     // Peel off a layer of the pointer and update the offset appropriately.
1491     if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1492       Ptr = cast<Operator>(Ptr)->getOperand(0);
1493     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1494       if (GA->mayBeOverridden())
1495         break;
1496       Ptr = GA->getAliasee();
1497     } else {
1498       break;
1499     }
1500     assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1501   } while (Visited.insert(Ptr));
1503   if (!OffsetPtr) {
1504     if (!Int8Ptr) {
1505       Int8Ptr = IRB.CreateBitCast(
1506           Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1507           NamePrefix + "sroa_raw_cast");
1508       Int8PtrOffset = Offset;
1509     }
1511     OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1512       IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1513                             NamePrefix + "sroa_raw_idx");
1514   }
1515   Ptr = OffsetPtr;
1517   // On the off chance we were targeting i8*, guard the bitcast here.
1518   if (Ptr->getType() != PointerTy)
1519     Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
1521   return Ptr;
1524 /// \brief Test whether we can convert a value from the old to the new type.
1525 ///
1526 /// This predicate should be used to guard calls to convertValue in order to
1527 /// ensure that we only try to convert viable values. The strategy is that we
1528 /// will peel off single element struct and array wrappings to get to an
1529 /// underlying value, and convert that value.
1530 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1531   if (OldTy == NewTy)
1532     return true;
1533   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1534     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1535       if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1536         return true;
1537   if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1538     return false;
1539   if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1540     return false;
1542   // We can convert pointers to integers and vice-versa. Same for vectors
1543   // of pointers and integers.
1544   OldTy = OldTy->getScalarType();
1545   NewTy = NewTy->getScalarType();
1546   if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1547     if (NewTy->isPointerTy() && OldTy->isPointerTy())
1548       return true;
1549     if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1550       return true;
1551     return false;
1552   }
1554   return true;
1557 /// \brief Generic routine to convert an SSA value to a value of a different
1558 /// type.
1559 ///
1560 /// This will try various different casting techniques, such as bitcasts,
1561 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1562 /// two types for viability with this routine.
1563 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1564                            Type *NewTy) {
1565   Type *OldTy = V->getType();
1566   assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1568   if (OldTy == NewTy)
1569     return V;
1571   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1572     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1573       if (NewITy->getBitWidth() > OldITy->getBitWidth())
1574         return IRB.CreateZExt(V, NewITy);
1576   // See if we need inttoptr for this type pair. A cast involving both scalars
1577   // and vectors requires and additional bitcast.
1578   if (OldTy->getScalarType()->isIntegerTy() &&
1579       NewTy->getScalarType()->isPointerTy()) {
1580     // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1581     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1582       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1583                                 NewTy);
1585     // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1586     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1587       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1588                                 NewTy);
1590     return IRB.CreateIntToPtr(V, NewTy);
1591   }
1593   // See if we need ptrtoint for this type pair. A cast involving both scalars
1594   // and vectors requires and additional bitcast.
1595   if (OldTy->getScalarType()->isPointerTy() &&
1596       NewTy->getScalarType()->isIntegerTy()) {
1597     // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1598     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1599       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1600                                NewTy);
1602     // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1603     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1604       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1605                                NewTy);
1607     return IRB.CreatePtrToInt(V, NewTy);
1608   }
1610   return IRB.CreateBitCast(V, NewTy);
1613 /// \brief Test whether the given slice use can be promoted to a vector.
1614 ///
1615 /// This function is called to test each entry in a partioning which is slated
1616 /// for a single slice.
1617 static bool
1618 isVectorPromotionViableForSlice(const DataLayout &DL, uint64_t SliceBeginOffset,
1619                                 uint64_t SliceEndOffset, VectorType *Ty,
1620                                 uint64_t ElementSize, const Slice &S) {
1621   // First validate the slice offsets.
1622   uint64_t BeginOffset =
1623       std::max(S.beginOffset(), SliceBeginOffset) - SliceBeginOffset;
1624   uint64_t BeginIndex = BeginOffset / ElementSize;
1625   if (BeginIndex * ElementSize != BeginOffset ||
1626       BeginIndex >= Ty->getNumElements())
1627     return false;
1628   uint64_t EndOffset =
1629       std::min(S.endOffset(), SliceEndOffset) - SliceBeginOffset;
1630   uint64_t EndIndex = EndOffset / ElementSize;
1631   if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1632     return false;
1634   assert(EndIndex > BeginIndex && "Empty vector!");
1635   uint64_t NumElements = EndIndex - BeginIndex;
1636   Type *SliceTy = (NumElements == 1)
1637                       ? Ty->getElementType()
1638                       : VectorType::get(Ty->getElementType(), NumElements);
1640   Type *SplitIntTy =
1641       Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1643   Use *U = S.getUse();
1645   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1646     if (MI->isVolatile())
1647       return false;
1648     if (!S.isSplittable())
1649       return false; // Skip any unsplittable intrinsics.
1650   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1651     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1652         II->getIntrinsicID() != Intrinsic::lifetime_end)
1653       return false;
1654   } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1655     // Disable vector promotion when there are loads or stores of an FCA.
1656     return false;
1657   } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1658     if (LI->isVolatile())
1659       return false;
1660     Type *LTy = LI->getType();
1661     if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) {
1662       assert(LTy->isIntegerTy());
1663       LTy = SplitIntTy;
1664     }
1665     if (!canConvertValue(DL, SliceTy, LTy))
1666       return false;
1667   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1668     if (SI->isVolatile())
1669       return false;
1670     Type *STy = SI->getValueOperand()->getType();
1671     if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) {
1672       assert(STy->isIntegerTy());
1673       STy = SplitIntTy;
1674     }
1675     if (!canConvertValue(DL, STy, SliceTy))
1676       return false;
1677   } else {
1678     return false;
1679   }
1681   return true;
1684 /// \brief Test whether the given alloca partitioning and range of slices can be
1685 /// promoted to a vector.
1686 ///
1687 /// This is a quick test to check whether we can rewrite a particular alloca
1688 /// partition (and its newly formed alloca) into a vector alloca with only
1689 /// whole-vector loads and stores such that it could be promoted to a vector
1690 /// SSA value. We only can ensure this for a limited set of operations, and we
1691 /// don't want to do the rewrites unless we are confident that the result will
1692 /// be promotable, so we have an early test here.
1693 static VectorType *
1694 isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy,
1695                         uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1696                         AllocaSlices::const_range Slices,
1697                         ArrayRef<AllocaSlices::iterator> SplitUses) {
1698   // Collect the candidate types for vector-based promotion. Also track whether
1699   // we have different element types.
1700   SmallVector<VectorType *, 4> CandidateTys;
1701   Type *CommonEltTy = nullptr;
1702   bool HaveCommonEltTy = true;
1703   auto CheckCandidateType = [&](Type *Ty) {
1704     if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1705       CandidateTys.push_back(VTy);
1706       if (!CommonEltTy)
1707         CommonEltTy = VTy->getElementType();
1708       else if (CommonEltTy != VTy->getElementType())
1709         HaveCommonEltTy = false;
1710     }
1711   };
1712   CheckCandidateType(AllocaTy);
1713   // Consider any loads or stores that are the exact size of the slice.
1714   for (const auto &S : Slices)
1715     if (S.beginOffset() == SliceBeginOffset &&
1716         S.endOffset() == SliceEndOffset) {
1717       if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1718         CheckCandidateType(LI->getType());
1719       else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1720         CheckCandidateType(SI->getValueOperand()->getType());
1721     }
1723   // If we didn't find a vector type, nothing to do here.
1724   if (CandidateTys.empty())
1725     return nullptr;
1727   // Remove non-integer vector types if we had multiple common element types.
1728   // FIXME: It'd be nice to replace them with integer vector types, but we can't
1729   // do that until all the backends are known to produce good code for all
1730   // integer vector types.
1731   if (!HaveCommonEltTy) {
1732     CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
1733                                       [](VectorType *VTy) {
1734                          return !VTy->getElementType()->isIntegerTy();
1735                        }),
1736                        CandidateTys.end());
1738     // If there were no integer vector types, give up.
1739     if (CandidateTys.empty())
1740       return nullptr;
1742     // Rank the remaining candidate vector types. This is easy because we know
1743     // they're all integer vectors. We sort by ascending number of elements.
1744     auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1745       assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1746              "Cannot have vector types of different sizes!");
1747       assert(RHSTy->getElementType()->isIntegerTy() &&
1748              "All non-integer types eliminated!");
1749       assert(LHSTy->getElementType()->isIntegerTy() &&
1750              "All non-integer types eliminated!");
1751       return RHSTy->getNumElements() < LHSTy->getNumElements();
1752     };
1753     std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1754     CandidateTys.erase(
1755         std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1756         CandidateTys.end());
1757   } else {
1758 // The only way to have the same element type in every vector type is to
1759 // have the same vector type. Check that and remove all but one.
1760 #ifndef NDEBUG
1761     for (VectorType *VTy : CandidateTys) {
1762       assert(VTy->getElementType() == CommonEltTy &&
1763              "Unaccounted for element type!");
1764       assert(VTy == CandidateTys[0] &&
1765              "Different vector types with the same element type!");
1766     }
1767 #endif
1768     CandidateTys.resize(1);
1769   }
1771   // Try each vector type, and return the one which works.
1772   auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1773     uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1775     // While the definition of LLVM vectors is bitpacked, we don't support sizes
1776     // that aren't byte sized.
1777     if (ElementSize % 8)
1778       return false;
1779     assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1780            "vector size not a multiple of element size?");
1781     ElementSize /= 8;
1783     for (const auto &S : Slices)
1784       if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
1785                                            VTy, ElementSize, S))
1786         return false;
1788     for (const auto &SI : SplitUses)
1789       if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
1790                                            VTy, ElementSize, *SI))
1791         return false;
1793     return true;
1794   };
1795   for (VectorType *VTy : CandidateTys)
1796     if (CheckVectorTypeForPromotion(VTy))
1797       return VTy;
1799   return nullptr;
1802 /// \brief Test whether a slice of an alloca is valid for integer widening.
1803 ///
1804 /// This implements the necessary checking for the \c isIntegerWideningViable
1805 /// test below on a single slice of the alloca.
1806 static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1807                                             Type *AllocaTy,
1808                                             uint64_t AllocBeginOffset,
1809                                             uint64_t Size,
1810                                             const Slice &S,
1811                                             bool &WholeAllocaOp) {
1812   uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1813   uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
1815   // We can't reasonably handle cases where the load or store extends past
1816   // the end of the aloca's type and into its padding.
1817   if (RelEnd > Size)
1818     return false;
1820   Use *U = S.getUse();
1822   if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1823     if (LI->isVolatile())
1824       return false;
1825     // Note that we don't count vector loads or stores as whole-alloca
1826     // operations which enable integer widening because we would prefer to use
1827     // vector widening instead.
1828     if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
1829       WholeAllocaOp = true;
1830     if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1831       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1832         return false;
1833     } else if (RelBegin != 0 || RelEnd != Size ||
1834                !canConvertValue(DL, AllocaTy, LI->getType())) {
1835       // Non-integer loads need to be convertible from the alloca type so that
1836       // they are promotable.
1837       return false;
1838     }
1839   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1840     Type *ValueTy = SI->getValueOperand()->getType();
1841     if (SI->isVolatile())
1842       return false;
1843     // Note that we don't count vector loads or stores as whole-alloca
1844     // operations which enable integer widening because we would prefer to use
1845     // vector widening instead.
1846     if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
1847       WholeAllocaOp = true;
1848     if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
1849       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1850         return false;
1851     } else if (RelBegin != 0 || RelEnd != Size ||
1852                !canConvertValue(DL, ValueTy, AllocaTy)) {
1853       // Non-integer stores need to be convertible to the alloca type so that
1854       // they are promotable.
1855       return false;
1856     }
1857   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1858     if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1859       return false;
1860     if (!S.isSplittable())
1861       return false; // Skip any unsplittable intrinsics.
1862   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1863     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1864         II->getIntrinsicID() != Intrinsic::lifetime_end)
1865       return false;
1866   } else {
1867     return false;
1868   }
1870   return true;
1873 /// \brief Test whether the given alloca partition's integer operations can be
1874 /// widened to promotable ones.
1875 ///
1876 /// This is a quick test to check whether we can rewrite the integer loads and
1877 /// stores to a particular alloca into wider loads and stores and be able to
1878 /// promote the resulting alloca.
1879 static bool
1880 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
1881                         uint64_t AllocBeginOffset,
1882                         AllocaSlices::const_range Slices,
1883                         ArrayRef<AllocaSlices::iterator> SplitUses) {
1884   uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
1885   // Don't create integer types larger than the maximum bitwidth.
1886   if (SizeInBits > IntegerType::MAX_INT_BITS)
1887     return false;
1889   // Don't try to handle allocas with bit-padding.
1890   if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
1891     return false;
1893   // We need to ensure that an integer type with the appropriate bitwidth can
1894   // be converted to the alloca type, whatever that is. We don't want to force
1895   // the alloca itself to have an integer type if there is a more suitable one.
1896   Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
1897   if (!canConvertValue(DL, AllocaTy, IntTy) ||
1898       !canConvertValue(DL, IntTy, AllocaTy))
1899     return false;
1901   uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1903   // While examining uses, we ensure that the alloca has a covering load or
1904   // store. We don't want to widen the integer operations only to fail to
1905   // promote due to some other unsplittable entry (which we may make splittable
1906   // later). However, if there are only splittable uses, go ahead and assume
1907   // that we cover the alloca.
1908   bool WholeAllocaOp =
1909       Slices.begin() != Slices.end() ? false : DL.isLegalInteger(SizeInBits);
1911   for (const auto &S : Slices)
1912     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1913                                          S, WholeAllocaOp))
1914       return false;
1916   for (const auto &SI : SplitUses)
1917     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1918                                          *SI, WholeAllocaOp))
1919       return false;
1921   return WholeAllocaOp;
1924 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1925                              IntegerType *Ty, uint64_t Offset,
1926                              const Twine &Name) {
1927   DEBUG(dbgs() << "       start: " << *V << "\n");
1928   IntegerType *IntTy = cast<IntegerType>(V->getType());
1929   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1930          "Element extends past full value");
1931   uint64_t ShAmt = 8*Offset;
1932   if (DL.isBigEndian())
1933     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1934   if (ShAmt) {
1935     V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
1936     DEBUG(dbgs() << "     shifted: " << *V << "\n");
1937   }
1938   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1939          "Cannot extract to a larger integer!");
1940   if (Ty != IntTy) {
1941     V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
1942     DEBUG(dbgs() << "     trunced: " << *V << "\n");
1943   }
1944   return V;
1947 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
1948                             Value *V, uint64_t Offset, const Twine &Name) {
1949   IntegerType *IntTy = cast<IntegerType>(Old->getType());
1950   IntegerType *Ty = cast<IntegerType>(V->getType());
1951   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1952          "Cannot insert a larger integer!");
1953   DEBUG(dbgs() << "       start: " << *V << "\n");
1954   if (Ty != IntTy) {
1955     V = IRB.CreateZExt(V, IntTy, Name + ".ext");
1956     DEBUG(dbgs() << "    extended: " << *V << "\n");
1957   }
1958   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1959          "Element store outside of alloca store");
1960   uint64_t ShAmt = 8*Offset;
1961   if (DL.isBigEndian())
1962     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1963   if (ShAmt) {
1964     V = IRB.CreateShl(V, ShAmt, Name + ".shift");
1965     DEBUG(dbgs() << "     shifted: " << *V << "\n");
1966   }
1968   if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1969     APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1970     Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
1971     DEBUG(dbgs() << "      masked: " << *Old << "\n");
1972     V = IRB.CreateOr(Old, V, Name + ".insert");
1973     DEBUG(dbgs() << "    inserted: " << *V << "\n");
1974   }
1975   return V;
1978 static Value *extractVector(IRBuilderTy &IRB, Value *V,
1979                             unsigned BeginIndex, unsigned EndIndex,
1980                             const Twine &Name) {
1981   VectorType *VecTy = cast<VectorType>(V->getType());
1982   unsigned NumElements = EndIndex - BeginIndex;
1983   assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1985   if (NumElements == VecTy->getNumElements())
1986     return V;
1988   if (NumElements == 1) {
1989     V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1990                                  Name + ".extract");
1991     DEBUG(dbgs() << "     extract: " << *V << "\n");
1992     return V;
1993   }
1995   SmallVector<Constant*, 8> Mask;
1996   Mask.reserve(NumElements);
1997   for (unsigned i = BeginIndex; i != EndIndex; ++i)
1998     Mask.push_back(IRB.getInt32(i));
1999   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2000                               ConstantVector::get(Mask),
2001                               Name + ".extract");
2002   DEBUG(dbgs() << "     shuffle: " << *V << "\n");
2003   return V;
2006 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2007                            unsigned BeginIndex, const Twine &Name) {
2008   VectorType *VecTy = cast<VectorType>(Old->getType());
2009   assert(VecTy && "Can only insert a vector into a vector");
2011   VectorType *Ty = dyn_cast<VectorType>(V->getType());
2012   if (!Ty) {
2013     // Single element to insert.
2014     V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2015                                 Name + ".insert");
2016     DEBUG(dbgs() <<  "     insert: " << *V << "\n");
2017     return V;
2018   }
2020   assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2021          "Too many elements!");
2022   if (Ty->getNumElements() == VecTy->getNumElements()) {
2023     assert(V->getType() == VecTy && "Vector type mismatch");
2024     return V;
2025   }
2026   unsigned EndIndex = BeginIndex + Ty->getNumElements();
2028   // When inserting a smaller vector into the larger to store, we first
2029   // use a shuffle vector to widen it with undef elements, and then
2030   // a second shuffle vector to select between the loaded vector and the
2031   // incoming vector.
2032   SmallVector<Constant*, 8> Mask;
2033   Mask.reserve(VecTy->getNumElements());
2034   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2035     if (i >= BeginIndex && i < EndIndex)
2036       Mask.push_back(IRB.getInt32(i - BeginIndex));
2037     else
2038       Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2039   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2040                               ConstantVector::get(Mask),
2041                               Name + ".expand");
2042   DEBUG(dbgs() << "    shuffle: " << *V << "\n");
2044   Mask.clear();
2045   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2046     Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2048   V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2050   DEBUG(dbgs() << "    blend: " << *V << "\n");
2051   return V;
2054 namespace {
2055 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
2056 /// to use a new alloca.
2057 ///
2058 /// Also implements the rewriting to vector-based accesses when the partition
2059 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2060 /// lives here.
2061 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
2062   // Befriend the base class so it can delegate to private visit methods.
2063   friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2064   typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
2066   const DataLayout &DL;
2067   AllocaSlices &AS;
2068   SROA &Pass;
2069   AllocaInst &OldAI, &NewAI;
2070   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2071   Type *NewAllocaTy;
2073   // This is a convenience and flag variable that will be null unless the new
2074   // alloca's integer operations should be widened to this integer type due to
2075   // passing isIntegerWideningViable above. If it is non-null, the desired
2076   // integer type will be stored here for easy access during rewriting.
2077   IntegerType *IntTy;
2079   // If we are rewriting an alloca partition which can be written as pure
2080   // vector operations, we stash extra information here. When VecTy is
2081   // non-null, we have some strict guarantees about the rewritten alloca:
2082   //   - The new alloca is exactly the size of the vector type here.
2083   //   - The accesses all either map to the entire vector or to a single
2084   //     element.
2085   //   - The set of accessing instructions is only one of those handled above
2086   //     in isVectorPromotionViable. Generally these are the same access kinds
2087   //     which are promotable via mem2reg.
2088   VectorType *VecTy;
2089   Type *ElementTy;
2090   uint64_t ElementSize;
2092   // The original offset of the slice currently being rewritten relative to
2093   // the original alloca.
2094   uint64_t BeginOffset, EndOffset;
2095   // The new offsets of the slice currently being rewritten relative to the
2096   // original alloca.
2097   uint64_t NewBeginOffset, NewEndOffset;
2099   uint64_t SliceSize;
2100   bool IsSplittable;
2101   bool IsSplit;
2102   Use *OldUse;
2103   Instruction *OldPtr;
2105   // Track post-rewrite users which are PHI nodes and Selects.
2106   SmallPtrSetImpl<PHINode *> &PHIUsers;
2107   SmallPtrSetImpl<SelectInst *> &SelectUsers;
2109   // Utility IR builder, whose name prefix is setup for each visited use, and
2110   // the insertion point is set to point to the user.
2111   IRBuilderTy IRB;
2113 public:
2114   AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2115                       AllocaInst &OldAI, AllocaInst &NewAI,
2116                       uint64_t NewAllocaBeginOffset,
2117                       uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2118                       VectorType *PromotableVecTy,
2119                       SmallPtrSetImpl<PHINode *> &PHIUsers,
2120                       SmallPtrSetImpl<SelectInst *> &SelectUsers)
2121       : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2122         NewAllocaBeginOffset(NewAllocaBeginOffset),
2123         NewAllocaEndOffset(NewAllocaEndOffset),
2124         NewAllocaTy(NewAI.getAllocatedType()),
2125         IntTy(IsIntegerPromotable
2126                   ? Type::getIntNTy(
2127                         NewAI.getContext(),
2128                         DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2129                   : nullptr),
2130         VecTy(PromotableVecTy),
2131         ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2132         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2133         BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
2134         OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2135         IRB(NewAI.getContext(), ConstantFolder()) {
2136     if (VecTy) {
2137       assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
2138              "Only multiple-of-8 sized vector elements are viable");
2139       ++NumVectorized;
2140     }
2141     assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2142   }
2144   bool visit(AllocaSlices::const_iterator I) {
2145     bool CanSROA = true;
2146     BeginOffset = I->beginOffset();
2147     EndOffset = I->endOffset();
2148     IsSplittable = I->isSplittable();
2149     IsSplit =
2150         BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2152     // Compute the intersecting offset range.
2153     assert(BeginOffset < NewAllocaEndOffset);
2154     assert(EndOffset > NewAllocaBeginOffset);
2155     NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2156     NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2158     SliceSize = NewEndOffset - NewBeginOffset;
2160     OldUse = I->getUse();
2161     OldPtr = cast<Instruction>(OldUse->get());
2163     Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2164     IRB.SetInsertPoint(OldUserI);
2165     IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2166     IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2168     CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2169     if (VecTy || IntTy)
2170       assert(CanSROA);
2171     return CanSROA;
2172   }
2174 private:
2175   // Make sure the other visit overloads are visible.
2176   using Base::visit;
2178   // Every instruction which can end up as a user must have a rewrite rule.
2179   bool visitInstruction(Instruction &I) {
2180     DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
2181     llvm_unreachable("No rewrite rule for this instruction!");
2182   }
2184   Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2185     // Note that the offset computation can use BeginOffset or NewBeginOffset
2186     // interchangeably for unsplit slices.
2187     assert(IsSplit || BeginOffset == NewBeginOffset);
2188     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2190 #ifndef NDEBUG
2191     StringRef OldName = OldPtr->getName();
2192     // Skip through the last '.sroa.' component of the name.
2193     size_t LastSROAPrefix = OldName.rfind(".sroa.");
2194     if (LastSROAPrefix != StringRef::npos) {
2195       OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2196       // Look for an SROA slice index.
2197       size_t IndexEnd = OldName.find_first_not_of("0123456789");
2198       if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2199         // Strip the index and look for the offset.
2200         OldName = OldName.substr(IndexEnd + 1);
2201         size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2202         if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2203           // Strip the offset.
2204           OldName = OldName.substr(OffsetEnd + 1);
2205       }
2206     }
2207     // Strip any SROA suffixes as well.
2208     OldName = OldName.substr(0, OldName.find(".sroa_"));
2209 #endif
2211     return getAdjustedPtr(IRB, DL, &NewAI,
2212                           APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
2213 #ifndef NDEBUG
2214                           Twine(OldName) + "."
2215 #else
2216                           Twine()
2217 #endif
2218                           );
2219   }
2221   /// \brief Compute suitable alignment to access this slice of the *new* alloca.
2222   ///
2223   /// You can optionally pass a type to this routine and if that type's ABI
2224   /// alignment is itself suitable, this will return zero.
2225   unsigned getSliceAlign(Type *Ty = nullptr) {
2226     unsigned NewAIAlign = NewAI.getAlignment();
2227     if (!NewAIAlign)
2228       NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2229     unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2230     return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
2231   }
2233   unsigned getIndex(uint64_t Offset) {
2234     assert(VecTy && "Can only call getIndex when rewriting a vector");
2235     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2236     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2237     uint32_t Index = RelOffset / ElementSize;
2238     assert(Index * ElementSize == RelOffset);
2239     return Index;
2240   }
2242   void deleteIfTriviallyDead(Value *V) {
2243     Instruction *I = cast<Instruction>(V);
2244     if (isInstructionTriviallyDead(I))
2245       Pass.DeadInsts.insert(I);
2246   }
2248   Value *rewriteVectorizedLoadInst() {
2249     unsigned BeginIndex = getIndex(NewBeginOffset);
2250     unsigned EndIndex = getIndex(NewEndOffset);
2251     assert(EndIndex > BeginIndex && "Empty vector!");
2253     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2254                                      "load");
2255     return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2256   }
2258   Value *rewriteIntegerLoad(LoadInst &LI) {
2259     assert(IntTy && "We cannot insert an integer to the alloca");
2260     assert(!LI.isVolatile());
2261     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2262                                      "load");
2263     V = convertValue(DL, IRB, V, IntTy);
2264     assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2265     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2266     if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
2267       V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2268                          "extract");
2269     return V;
2270   }
2272   bool visitLoadInst(LoadInst &LI) {
2273     DEBUG(dbgs() << "    original: " << LI << "\n");
2274     Value *OldOp = LI.getOperand(0);
2275     assert(OldOp == OldPtr);
2277     Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2278                              : LI.getType();
2279     bool IsPtrAdjusted = false;
2280     Value *V;
2281     if (VecTy) {
2282       V = rewriteVectorizedLoadInst();
2283     } else if (IntTy && LI.getType()->isIntegerTy()) {
2284       V = rewriteIntegerLoad(LI);
2285     } else if (NewBeginOffset == NewAllocaBeginOffset &&
2286                canConvertValue(DL, NewAllocaTy, LI.getType())) {
2287       V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2288                                 LI.isVolatile(), LI.getName());
2289     } else {
2290       Type *LTy = TargetTy->getPointerTo();
2291       V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2292                                 getSliceAlign(TargetTy), LI.isVolatile(),
2293                                 LI.getName());
2294       IsPtrAdjusted = true;
2295     }
2296     V = convertValue(DL, IRB, V, TargetTy);
2298     if (IsSplit) {
2299       assert(!LI.isVolatile());
2300       assert(LI.getType()->isIntegerTy() &&
2301              "Only integer type loads and stores are split");
2302       assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
2303              "Split load isn't smaller than original load");
2304       assert(LI.getType()->getIntegerBitWidth() ==
2305              DL.getTypeStoreSizeInBits(LI.getType()) &&
2306              "Non-byte-multiple bit width");
2307       // Move the insertion point just past the load so that we can refer to it.
2308       IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
2309       // Create a placeholder value with the same type as LI to use as the
2310       // basis for the new value. This allows us to replace the uses of LI with
2311       // the computed value, and then replace the placeholder with LI, leaving
2312       // LI only used for this computation.
2313       Value *Placeholder
2314         = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2315       V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
2316                         "insert");
2317       LI.replaceAllUsesWith(V);
2318       Placeholder->replaceAllUsesWith(&LI);
2319       delete Placeholder;
2320     } else {
2321       LI.replaceAllUsesWith(V);
2322     }
2324     Pass.DeadInsts.insert(&LI);
2325     deleteIfTriviallyDead(OldOp);
2326     DEBUG(dbgs() << "          to: " << *V << "\n");
2327     return !LI.isVolatile() && !IsPtrAdjusted;
2328   }
2330   bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
2331     if (V->getType() != VecTy) {
2332       unsigned BeginIndex = getIndex(NewBeginOffset);
2333       unsigned EndIndex = getIndex(NewEndOffset);
2334       assert(EndIndex > BeginIndex && "Empty vector!");
2335       unsigned NumElements = EndIndex - BeginIndex;
2336       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2337       Type *SliceTy =
2338           (NumElements == 1) ? ElementTy
2339                              : VectorType::get(ElementTy, NumElements);
2340       if (V->getType() != SliceTy)
2341         V = convertValue(DL, IRB, V, SliceTy);
2343       // Mix in the existing elements.
2344       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2345                                          "load");
2346       V = insertVector(IRB, Old, V, BeginIndex, "vec");
2347     }
2348     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2349     Pass.DeadInsts.insert(&SI);
2351     (void)Store;
2352     DEBUG(dbgs() << "          to: " << *Store << "\n");
2353     return true;
2354   }
2356   bool rewriteIntegerStore(Value *V, StoreInst &SI) {
2357     assert(IntTy && "We cannot extract an integer from the alloca");
2358     assert(!SI.isVolatile());
2359     if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2360       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2361                                          "oldload");
2362       Old = convertValue(DL, IRB, Old, IntTy);
2363       assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2364       uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2365       V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
2366                         "insert");
2367     }
2368     V = convertValue(DL, IRB, V, NewAllocaTy);
2369     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2370     Pass.DeadInsts.insert(&SI);
2371     (void)Store;
2372     DEBUG(dbgs() << "          to: " << *Store << "\n");
2373     return true;
2374   }
2376   bool visitStoreInst(StoreInst &SI) {
2377     DEBUG(dbgs() << "    original: " << SI << "\n");
2378     Value *OldOp = SI.getOperand(1);
2379     assert(OldOp == OldPtr);
2381     Value *V = SI.getValueOperand();
2383     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2384     // alloca that should be re-examined after promoting this alloca.
2385     if (V->getType()->isPointerTy())
2386       if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2387         Pass.PostPromotionWorklist.insert(AI);
2389     if (SliceSize < DL.getTypeStoreSize(V->getType())) {
2390       assert(!SI.isVolatile());
2391       assert(V->getType()->isIntegerTy() &&
2392              "Only integer type loads and stores are split");
2393       assert(V->getType()->getIntegerBitWidth() ==
2394              DL.getTypeStoreSizeInBits(V->getType()) &&
2395              "Non-byte-multiple bit width");
2396       IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2397       V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
2398                          "extract");
2399     }
2401     if (VecTy)
2402       return rewriteVectorizedStoreInst(V, SI, OldOp);
2403     if (IntTy && V->getType()->isIntegerTy())
2404       return rewriteIntegerStore(V, SI);
2406     StoreInst *NewSI;
2407     if (NewBeginOffset == NewAllocaBeginOffset &&
2408         NewEndOffset == NewAllocaEndOffset &&
2409         canConvertValue(DL, V->getType(), NewAllocaTy)) {
2410       V = convertValue(DL, IRB, V, NewAllocaTy);
2411       NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2412                                      SI.isVolatile());
2413     } else {
2414       Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
2415       NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2416                                      SI.isVolatile());
2417     }
2418     (void)NewSI;
2419     Pass.DeadInsts.insert(&SI);
2420     deleteIfTriviallyDead(OldOp);
2422     DEBUG(dbgs() << "          to: " << *NewSI << "\n");
2423     return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2424   }
2426   /// \brief Compute an integer value from splatting an i8 across the given
2427   /// number of bytes.
2428   ///
2429   /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2430   /// call this routine.
2431   /// FIXME: Heed the advice above.
2432   ///
2433   /// \param V The i8 value to splat.
2434   /// \param Size The number of bytes in the output (assuming i8 is one byte)
2435   Value *getIntegerSplat(Value *V, unsigned Size) {
2436     assert(Size > 0 && "Expected a positive number of bytes.");
2437     IntegerType *VTy = cast<IntegerType>(V->getType());
2438     assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2439     if (Size == 1)
2440       return V;
2442     Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2443     V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
2444                       ConstantExpr::getUDiv(
2445                         Constant::getAllOnesValue(SplatIntTy),
2446                         ConstantExpr::getZExt(
2447                           Constant::getAllOnesValue(V->getType()),
2448                           SplatIntTy)),
2449                       "isplat");
2450     return V;
2451   }
2453   /// \brief Compute a vector splat for a given element value.
2454   Value *getVectorSplat(Value *V, unsigned NumElements) {
2455     V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2456     DEBUG(dbgs() << "       splat: " << *V << "\n");
2457     return V;
2458   }
2460   bool visitMemSetInst(MemSetInst &II) {
2461     DEBUG(dbgs() << "    original: " << II << "\n");
2462     assert(II.getRawDest() == OldPtr);
2464     // If the memset has a variable size, it cannot be split, just adjust the
2465     // pointer to the new alloca.
2466     if (!isa<Constant>(II.getLength())) {
2467       assert(!IsSplit);
2468       assert(NewBeginOffset == BeginOffset);
2469       II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2470       Type *CstTy = II.getAlignmentCst()->getType();
2471       II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
2473       deleteIfTriviallyDead(OldPtr);
2474       return false;
2475     }
2477     // Record this instruction for deletion.
2478     Pass.DeadInsts.insert(&II);
2480     Type *AllocaTy = NewAI.getAllocatedType();
2481     Type *ScalarTy = AllocaTy->getScalarType();
2483     // If this doesn't map cleanly onto the alloca type, and that type isn't
2484     // a single value type, just emit a memset.
2485     if (!VecTy && !IntTy &&
2486         (BeginOffset > NewAllocaBeginOffset ||
2487          EndOffset < NewAllocaEndOffset ||
2488          SliceSize != DL.getTypeStoreSize(AllocaTy) ||
2489          !AllocaTy->isSingleValueType() ||
2490          !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2491          DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
2492       Type *SizeTy = II.getLength()->getType();
2493       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2494       CallInst *New = IRB.CreateMemSet(
2495           getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2496           getSliceAlign(), II.isVolatile());
2497       (void)New;
2498       DEBUG(dbgs() << "          to: " << *New << "\n");
2499       return false;
2500     }
2502     // If we can represent this as a simple value, we have to build the actual
2503     // value to store, which requires expanding the byte present in memset to
2504     // a sensible representation for the alloca type. This is essentially
2505     // splatting the byte to a sufficiently wide integer, splatting it across
2506     // any desired vector width, and bitcasting to the final type.
2507     Value *V;
2509     if (VecTy) {
2510       // If this is a memset of a vectorized alloca, insert it.
2511       assert(ElementTy == ScalarTy);
2513       unsigned BeginIndex = getIndex(NewBeginOffset);
2514       unsigned EndIndex = getIndex(NewEndOffset);
2515       assert(EndIndex > BeginIndex && "Empty vector!");
2516       unsigned NumElements = EndIndex - BeginIndex;
2517       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2519       Value *Splat =
2520           getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2521       Splat = convertValue(DL, IRB, Splat, ElementTy);
2522       if (NumElements > 1)
2523         Splat = getVectorSplat(Splat, NumElements);
2525       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2526                                          "oldload");
2527       V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2528     } else if (IntTy) {
2529       // If this is a memset on an alloca where we can widen stores, insert the
2530       // set integer.
2531       assert(!II.isVolatile());
2533       uint64_t Size = NewEndOffset - NewBeginOffset;
2534       V = getIntegerSplat(II.getValue(), Size);
2536       if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2537                     EndOffset != NewAllocaBeginOffset)) {
2538         Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2539                                            "oldload");
2540         Old = convertValue(DL, IRB, Old, IntTy);
2541         uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2542         V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2543       } else {
2544         assert(V->getType() == IntTy &&
2545                "Wrong type for an alloca wide integer!");
2546       }
2547       V = convertValue(DL, IRB, V, AllocaTy);
2548     } else {
2549       // Established these invariants above.
2550       assert(NewBeginOffset == NewAllocaBeginOffset);
2551       assert(NewEndOffset == NewAllocaEndOffset);
2553       V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2554       if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2555         V = getVectorSplat(V, AllocaVecTy->getNumElements());
2557       V = convertValue(DL, IRB, V, AllocaTy);
2558     }
2560     Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2561                                         II.isVolatile());
2562     (void)New;
2563     DEBUG(dbgs() << "          to: " << *New << "\n");
2564     return !II.isVolatile();
2565   }
2567   bool visitMemTransferInst(MemTransferInst &II) {
2568     // Rewriting of memory transfer instructions can be a bit tricky. We break
2569     // them into two categories: split intrinsics and unsplit intrinsics.
2571     DEBUG(dbgs() << "    original: " << II << "\n");
2573     bool IsDest = &II.getRawDestUse() == OldUse;
2574     assert((IsDest && II.getRawDest() == OldPtr) ||
2575            (!IsDest && II.getRawSource() == OldPtr));
2577     unsigned SliceAlign = getSliceAlign();
2579     // For unsplit intrinsics, we simply modify the source and destination
2580     // pointers in place. This isn't just an optimization, it is a matter of
2581     // correctness. With unsplit intrinsics we may be dealing with transfers
2582     // within a single alloca before SROA ran, or with transfers that have
2583     // a variable length. We may also be dealing with memmove instead of
2584     // memcpy, and so simply updating the pointers is the necessary for us to
2585     // update both source and dest of a single call.
2586     if (!IsSplittable) {
2587       Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2588       if (IsDest)
2589         II.setDest(AdjustedPtr);
2590       else
2591         II.setSource(AdjustedPtr);
2593       if (II.getAlignment() > SliceAlign) {
2594         Type *CstTy = II.getAlignmentCst()->getType();
2595         II.setAlignment(
2596             ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
2597       }
2599       DEBUG(dbgs() << "          to: " << II << "\n");
2600       deleteIfTriviallyDead(OldPtr);
2601       return false;
2602     }
2603     // For split transfer intrinsics we have an incredibly useful assurance:
2604     // the source and destination do not reside within the same alloca, and at
2605     // least one of them does not escape. This means that we can replace
2606     // memmove with memcpy, and we don't need to worry about all manner of
2607     // downsides to splitting and transforming the operations.
2609     // If this doesn't map cleanly onto the alloca type, and that type isn't
2610     // a single value type, just emit a memcpy.
2611     bool EmitMemCpy =
2612         !VecTy && !IntTy &&
2613         (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2614          SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2615          !NewAI.getAllocatedType()->isSingleValueType());
2617     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2618     // size hasn't been shrunk based on analysis of the viable range, this is
2619     // a no-op.
2620     if (EmitMemCpy && &OldAI == &NewAI) {
2621       // Ensure the start lines up.
2622       assert(NewBeginOffset == BeginOffset);
2624       // Rewrite the size as needed.
2625       if (NewEndOffset != EndOffset)
2626         II.setLength(ConstantInt::get(II.getLength()->getType(),
2627                                       NewEndOffset - NewBeginOffset));
2628       return false;
2629     }
2630     // Record this instruction for deletion.
2631     Pass.DeadInsts.insert(&II);
2633     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2634     // alloca that should be re-examined after rewriting this instruction.
2635     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2636     if (AllocaInst *AI
2637           = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2638       assert(AI != &OldAI && AI != &NewAI &&
2639              "Splittable transfers cannot reach the same alloca on both ends.");
2640       Pass.Worklist.insert(AI);
2641     }
2643     Type *OtherPtrTy = OtherPtr->getType();
2644     unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2646     // Compute the relative offset for the other pointer within the transfer.
2647     unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
2648     APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2649     unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2650                                    OtherOffset.zextOrTrunc(64).getZExtValue());
2652     if (EmitMemCpy) {
2653       // Compute the other pointer, folding as much as possible to produce
2654       // a single, simple GEP in most cases.
2655       OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2656                                 OtherPtr->getName() + ".");
2658       Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2659       Type *SizeTy = II.getLength()->getType();
2660       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2662       CallInst *New = IRB.CreateMemCpy(
2663           IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2664           MinAlign(SliceAlign, OtherAlign), II.isVolatile());
2665       (void)New;
2666       DEBUG(dbgs() << "          to: " << *New << "\n");
2667       return false;
2668     }
2670     bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2671                          NewEndOffset == NewAllocaEndOffset;
2672     uint64_t Size = NewEndOffset - NewBeginOffset;
2673     unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2674     unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2675     unsigned NumElements = EndIndex - BeginIndex;
2676     IntegerType *SubIntTy
2677       = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : nullptr;
2679     // Reset the other pointer type to match the register type we're going to
2680     // use, but using the address space of the original other pointer.
2681     if (VecTy && !IsWholeAlloca) {
2682       if (NumElements == 1)
2683         OtherPtrTy = VecTy->getElementType();
2684       else
2685         OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2687       OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
2688     } else if (IntTy && !IsWholeAlloca) {
2689       OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2690     } else {
2691       OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
2692     }
2694     Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2695                                    OtherPtr->getName() + ".");
2696     unsigned SrcAlign = OtherAlign;
2697     Value *DstPtr = &NewAI;
2698     unsigned DstAlign = SliceAlign;
2699     if (!IsDest) {
2700       std::swap(SrcPtr, DstPtr);
2701       std::swap(SrcAlign, DstAlign);
2702     }
2704     Value *Src;
2705     if (VecTy && !IsWholeAlloca && !IsDest) {
2706       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2707                                   "load");
2708       Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
2709     } else if (IntTy && !IsWholeAlloca && !IsDest) {
2710       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2711                                   "load");
2712       Src = convertValue(DL, IRB, Src, IntTy);
2713       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2714       Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
2715     } else {
2716       Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
2717                                   "copyload");
2718     }
2720     if (VecTy && !IsWholeAlloca && IsDest) {
2721       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2722                                          "oldload");
2723       Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
2724     } else if (IntTy && !IsWholeAlloca && IsDest) {
2725       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2726                                          "oldload");
2727       Old = convertValue(DL, IRB, Old, IntTy);
2728       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2729       Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2730       Src = convertValue(DL, IRB, Src, NewAllocaTy);
2731     }
2733     StoreInst *Store = cast<StoreInst>(
2734         IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
2735     (void)Store;
2736     DEBUG(dbgs() << "          to: " << *Store << "\n");
2737     return !II.isVolatile();
2738   }
2740   bool visitIntrinsicInst(IntrinsicInst &II) {
2741     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2742            II.getIntrinsicID() == Intrinsic::lifetime_end);
2743     DEBUG(dbgs() << "    original: " << II << "\n");
2744     assert(II.getArgOperand(1) == OldPtr);
2746     // Record this instruction for deletion.
2747     Pass.DeadInsts.insert(&II);
2749     ConstantInt *Size
2750       = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2751                          NewEndOffset - NewBeginOffset);
2752     Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2753     Value *New;
2754     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2755       New = IRB.CreateLifetimeStart(Ptr, Size);
2756     else
2757       New = IRB.CreateLifetimeEnd(Ptr, Size);
2759     (void)New;
2760     DEBUG(dbgs() << "          to: " << *New << "\n");
2761     return true;
2762   }
2764   bool visitPHINode(PHINode &PN) {
2765     DEBUG(dbgs() << "    original: " << PN << "\n");
2766     assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2767     assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
2769     // We would like to compute a new pointer in only one place, but have it be
2770     // as local as possible to the PHI. To do that, we re-use the location of
2771     // the old pointer, which necessarily must be in the right position to
2772     // dominate the PHI.
2773     IRBuilderTy PtrBuilder(IRB);
2774     if (isa<PHINode>(OldPtr))
2775       PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
2776     else
2777       PtrBuilder.SetInsertPoint(OldPtr);
2778     PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
2780     Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
2781     // Replace the operands which were using the old pointer.
2782     std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
2784     DEBUG(dbgs() << "          to: " << PN << "\n");
2785     deleteIfTriviallyDead(OldPtr);
2787     // PHIs can't be promoted on their own, but often can be speculated. We
2788     // check the speculation outside of the rewriter so that we see the
2789     // fully-rewritten alloca.
2790     PHIUsers.insert(&PN);
2791     return true;
2792   }
2794   bool visitSelectInst(SelectInst &SI) {
2795     DEBUG(dbgs() << "    original: " << SI << "\n");
2796     assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2797            "Pointer isn't an operand!");
2798     assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2799     assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
2801     Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2802     // Replace the operands which were using the old pointer.
2803     if (SI.getOperand(1) == OldPtr)
2804       SI.setOperand(1, NewPtr);
2805     if (SI.getOperand(2) == OldPtr)
2806       SI.setOperand(2, NewPtr);
2808     DEBUG(dbgs() << "          to: " << SI << "\n");
2809     deleteIfTriviallyDead(OldPtr);
2811     // Selects can't be promoted on their own, but often can be speculated. We
2812     // check the speculation outside of the rewriter so that we see the
2813     // fully-rewritten alloca.
2814     SelectUsers.insert(&SI);
2815     return true;
2816   }
2818 };
2821 namespace {
2822 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2823 ///
2824 /// This pass aggressively rewrites all aggregate loads and stores on
2825 /// a particular pointer (or any pointer derived from it which we can identify)
2826 /// with scalar loads and stores.
2827 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2828   // Befriend the base class so it can delegate to private visit methods.
2829   friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2831   const DataLayout &DL;
2833   /// Queue of pointer uses to analyze and potentially rewrite.
2834   SmallVector<Use *, 8> Queue;
2836   /// Set to prevent us from cycling with phi nodes and loops.
2837   SmallPtrSet<User *, 8> Visited;
2839   /// The current pointer use being rewritten. This is used to dig up the used
2840   /// value (as opposed to the user).
2841   Use *U;
2843 public:
2844   AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
2846   /// Rewrite loads and stores through a pointer and all pointers derived from
2847   /// it.
2848   bool rewrite(Instruction &I) {
2849     DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
2850     enqueueUsers(I);
2851     bool Changed = false;
2852     while (!Queue.empty()) {
2853       U = Queue.pop_back_val();
2854       Changed |= visit(cast<Instruction>(U->getUser()));
2855     }
2856     return Changed;
2857   }
2859 private:
2860   /// Enqueue all the users of the given instruction for further processing.
2861   /// This uses a set to de-duplicate users.
2862   void enqueueUsers(Instruction &I) {
2863     for (Use &U : I.uses())
2864       if (Visited.insert(U.getUser()))
2865         Queue.push_back(&U);
2866   }
2868   // Conservative default is to not rewrite anything.
2869   bool visitInstruction(Instruction &I) { return false; }
2871   /// \brief Generic recursive split emission class.
2872   template <typename Derived>
2873   class OpSplitter {
2874   protected:
2875     /// The builder used to form new instructions.
2876     IRBuilderTy IRB;
2877     /// The indices which to be used with insert- or extractvalue to select the
2878     /// appropriate value within the aggregate.
2879     SmallVector<unsigned, 4> Indices;
2880     /// The indices to a GEP instruction which will move Ptr to the correct slot
2881     /// within the aggregate.
2882     SmallVector<Value *, 4> GEPIndices;
2883     /// The base pointer of the original op, used as a base for GEPing the
2884     /// split operations.
2885     Value *Ptr;
2887     /// Initialize the splitter with an insertion point, Ptr and start with a
2888     /// single zero GEP index.
2889     OpSplitter(Instruction *InsertionPoint, Value *Ptr)
2890       : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
2892   public:
2893     /// \brief Generic recursive split emission routine.
2894     ///
2895     /// This method recursively splits an aggregate op (load or store) into
2896     /// scalar or vector ops. It splits recursively until it hits a single value
2897     /// and emits that single value operation via the template argument.
2898     ///
2899     /// The logic of this routine relies on GEPs and insertvalue and
2900     /// extractvalue all operating with the same fundamental index list, merely
2901     /// formatted differently (GEPs need actual values).
2902     ///
2903     /// \param Ty  The type being split recursively into smaller ops.
2904     /// \param Agg The aggregate value being built up or stored, depending on
2905     /// whether this is splitting a load or a store respectively.
2906     void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2907       if (Ty->isSingleValueType())
2908         return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
2910       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2911         unsigned OldSize = Indices.size();
2912         (void)OldSize;
2913         for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2914              ++Idx) {
2915           assert(Indices.size() == OldSize && "Did not return to the old size");
2916           Indices.push_back(Idx);
2917           GEPIndices.push_back(IRB.getInt32(Idx));
2918           emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2919           GEPIndices.pop_back();
2920           Indices.pop_back();
2921         }
2922         return;
2923       }
2925       if (StructType *STy = dyn_cast<StructType>(Ty)) {
2926         unsigned OldSize = Indices.size();
2927         (void)OldSize;
2928         for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2929              ++Idx) {
2930           assert(Indices.size() == OldSize && "Did not return to the old size");
2931           Indices.push_back(Idx);
2932           GEPIndices.push_back(IRB.getInt32(Idx));
2933           emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2934           GEPIndices.pop_back();
2935           Indices.pop_back();
2936         }
2937         return;
2938       }
2940       llvm_unreachable("Only arrays and structs are aggregate loadable types");
2941     }
2942   };
2944   struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
2945     LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2946       : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
2948     /// Emit a leaf load of a single value. This is called at the leaves of the
2949     /// recursive emission to actually load values.
2950     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2951       assert(Ty->isSingleValueType());
2952       // Load the single value and insert it using the indices.
2953       Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2954       Value *Load = IRB.CreateLoad(GEP, Name + ".load");
2955       Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2956       DEBUG(dbgs() << "          to: " << *Load << "\n");
2957     }
2958   };
2960   bool visitLoadInst(LoadInst &LI) {
2961     assert(LI.getPointerOperand() == *U);
2962     if (!LI.isSimple() || LI.getType()->isSingleValueType())
2963       return false;
2965     // We have an aggregate being loaded, split it apart.
2966     DEBUG(dbgs() << "    original: " << LI << "\n");
2967     LoadOpSplitter Splitter(&LI, *U);
2968     Value *V = UndefValue::get(LI.getType());
2969     Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
2970     LI.replaceAllUsesWith(V);
2971     LI.eraseFromParent();
2972     return true;
2973   }
2975   struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
2976     StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2977       : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
2979     /// Emit a leaf store of a single value. This is called at the leaves of the
2980     /// recursive emission to actually produce stores.
2981     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2982       assert(Ty->isSingleValueType());
2983       // Extract the single value and store it using the indices.
2984       Value *Store = IRB.CreateStore(
2985         IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2986         IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2987       (void)Store;
2988       DEBUG(dbgs() << "          to: " << *Store << "\n");
2989     }
2990   };
2992   bool visitStoreInst(StoreInst &SI) {
2993     if (!SI.isSimple() || SI.getPointerOperand() != *U)
2994       return false;
2995     Value *V = SI.getValueOperand();
2996     if (V->getType()->isSingleValueType())
2997       return false;
2999     // We have an aggregate being stored, split it apart.
3000     DEBUG(dbgs() << "    original: " << SI << "\n");
3001     StoreOpSplitter Splitter(&SI, *U);
3002     Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3003     SI.eraseFromParent();
3004     return true;
3005   }
3007   bool visitBitCastInst(BitCastInst &BC) {
3008     enqueueUsers(BC);
3009     return false;
3010   }
3012   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3013     enqueueUsers(GEPI);
3014     return false;
3015   }
3017   bool visitPHINode(PHINode &PN) {
3018     enqueueUsers(PN);
3019     return false;
3020   }
3022   bool visitSelectInst(SelectInst &SI) {
3023     enqueueUsers(SI);
3024     return false;
3025   }
3026 };
3029 /// \brief Strip aggregate type wrapping.
3030 ///
3031 /// This removes no-op aggregate types wrapping an underlying type. It will
3032 /// strip as many layers of types as it can without changing either the type
3033 /// size or the allocated size.
3034 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3035   if (Ty->isSingleValueType())
3036     return Ty;
3038   uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3039   uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3041   Type *InnerTy;
3042   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3043     InnerTy = ArrTy->getElementType();
3044   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3045     const StructLayout *SL = DL.getStructLayout(STy);
3046     unsigned Index = SL->getElementContainingOffset(0);
3047     InnerTy = STy->getElementType(Index);
3048   } else {
3049     return Ty;
3050   }
3052   if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3053       TypeSize > DL.getTypeSizeInBits(InnerTy))
3054     return Ty;
3056   return stripAggregateTypeWrapping(DL, InnerTy);
3059 /// \brief Try to find a partition of the aggregate type passed in for a given
3060 /// offset and size.
3061 ///
3062 /// This recurses through the aggregate type and tries to compute a subtype
3063 /// based on the offset and size. When the offset and size span a sub-section
3064 /// of an array, it will even compute a new array type for that sub-section,
3065 /// and the same for structs.
3066 ///
3067 /// Note that this routine is very strict and tries to find a partition of the
3068 /// type which produces the *exact* right offset and size. It is not forgiving
3069 /// when the size or offset cause either end of type-based partition to be off.
3070 /// Also, this is a best-effort routine. It is reasonable to give up and not
3071 /// return a type if necessary.
3072 static Type *getTypePartition(const DataLayout &DL, Type *Ty,
3073                               uint64_t Offset, uint64_t Size) {
3074   if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3075     return stripAggregateTypeWrapping(DL, Ty);
3076   if (Offset > DL.getTypeAllocSize(Ty) ||
3077       (DL.getTypeAllocSize(Ty) - Offset) < Size)
3078     return nullptr;
3080   if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3081     // We can't partition pointers...
3082     if (SeqTy->isPointerTy())
3083       return nullptr;
3085     Type *ElementTy = SeqTy->getElementType();
3086     uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3087     uint64_t NumSkippedElements = Offset / ElementSize;
3088     if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
3089       if (NumSkippedElements >= ArrTy->getNumElements())
3090         return nullptr;
3091     } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
3092       if (NumSkippedElements >= VecTy->getNumElements())
3093         return nullptr;
3094     }
3095     Offset -= NumSkippedElements * ElementSize;
3097     // First check if we need to recurse.
3098     if (Offset > 0 || Size < ElementSize) {
3099       // Bail if the partition ends in a different array element.
3100       if ((Offset + Size) > ElementSize)
3101         return nullptr;
3102       // Recurse through the element type trying to peel off offset bytes.
3103       return getTypePartition(DL, ElementTy, Offset, Size);
3104     }
3105     assert(Offset == 0);
3107     if (Size == ElementSize)
3108       return stripAggregateTypeWrapping(DL, ElementTy);
3109     assert(Size > ElementSize);
3110     uint64_t NumElements = Size / ElementSize;
3111     if (NumElements * ElementSize != Size)
3112       return nullptr;
3113     return ArrayType::get(ElementTy, NumElements);
3114   }
3116   StructType *STy = dyn_cast<StructType>(Ty);
3117   if (!STy)
3118     return nullptr;
3120   const StructLayout *SL = DL.getStructLayout(STy);
3121   if (Offset >= SL->getSizeInBytes())
3122     return nullptr;
3123   uint64_t EndOffset = Offset + Size;
3124   if (EndOffset > SL->getSizeInBytes())
3125     return nullptr;
3127   unsigned Index = SL->getElementContainingOffset(Offset);
3128   Offset -= SL->getElementOffset(Index);
3130   Type *ElementTy = STy->getElementType(Index);
3131   uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3132   if (Offset >= ElementSize)
3133     return nullptr; // The offset points into alignment padding.
3135   // See if any partition must be contained by the element.
3136   if (Offset > 0 || Size < ElementSize) {
3137     if ((Offset + Size) > ElementSize)
3138       return nullptr;
3139     return getTypePartition(DL, ElementTy, Offset, Size);
3140   }
3141   assert(Offset == 0);
3143   if (Size == ElementSize)
3144     return stripAggregateTypeWrapping(DL, ElementTy);
3146   StructType::element_iterator EI = STy->element_begin() + Index,
3147                                EE = STy->element_end();
3148   if (EndOffset < SL->getSizeInBytes()) {
3149     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3150     if (Index == EndIndex)
3151       return nullptr; // Within a single element and its padding.
3153     // Don't try to form "natural" types if the elements don't line up with the
3154     // expected size.
3155     // FIXME: We could potentially recurse down through the last element in the
3156     // sub-struct to find a natural end point.
3157     if (SL->getElementOffset(EndIndex) != EndOffset)
3158       return nullptr;
3160     assert(Index < EndIndex);
3161     EE = STy->element_begin() + EndIndex;
3162   }
3164   // Try to build up a sub-structure.
3165   StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
3166                                       STy->isPacked());
3167   const StructLayout *SubSL = DL.getStructLayout(SubTy);
3168   if (Size != SubSL->getSizeInBytes())
3169     return nullptr; // The sub-struct doesn't have quite the size needed.
3171   return SubTy;
3174 /// \brief Rewrite an alloca partition's users.
3175 ///
3176 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3177 /// to rewrite uses of an alloca partition to be conducive for SSA value
3178 /// promotion. If the partition needs a new, more refined alloca, this will
3179 /// build that new alloca, preserving as much type information as possible, and
3180 /// rewrite the uses of the old alloca to point at the new one and have the
3181 /// appropriate new offsets. It also evaluates how successful the rewrite was
3182 /// at enabling promotion and if it was successful queues the alloca to be
3183 /// promoted.
3184 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
3185                             AllocaSlices::iterator B, AllocaSlices::iterator E,
3186                             int64_t BeginOffset, int64_t EndOffset,
3187                             ArrayRef<AllocaSlices::iterator> SplitUses) {
3188   assert(BeginOffset < EndOffset);
3189   uint64_t SliceSize = EndOffset - BeginOffset;
3191   // Try to compute a friendly type for this partition of the alloca. This
3192   // won't always succeed, in which case we fall back to a legal integer type
3193   // or an i8 array of an appropriate size.
3194   Type *SliceTy = nullptr;
3195   if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
3196     if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3197       SliceTy = CommonUseTy;
3198   if (!SliceTy)
3199     if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
3200                                                  BeginOffset, SliceSize))
3201       SliceTy = TypePartitionTy;
3202   if ((!SliceTy || (SliceTy->isArrayTy() &&
3203                     SliceTy->getArrayElementType()->isIntegerTy())) &&
3204       DL->isLegalInteger(SliceSize * 8))
3205     SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3206   if (!SliceTy)
3207     SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3208   assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
3210   bool IsIntegerPromotable = isIntegerWideningViable(
3211       *DL, SliceTy, BeginOffset, AllocaSlices::const_range(B, E), SplitUses);
3213   VectorType *VecTy =
3214       IsIntegerPromotable
3215           ? nullptr
3216           : isVectorPromotionViable(*DL, SliceTy, BeginOffset, EndOffset,
3217                                     AllocaSlices::const_range(B, E), SplitUses);
3218   if (VecTy)
3219     SliceTy = VecTy;
3221   // Check for the case where we're going to rewrite to a new alloca of the
3222   // exact same type as the original, and with the same access offsets. In that
3223   // case, re-use the existing alloca, but still run through the rewriter to
3224   // perform phi and select speculation.
3225   AllocaInst *NewAI;
3226   if (SliceTy == AI.getAllocatedType()) {
3227     assert(BeginOffset == 0 &&
3228            "Non-zero begin offset but same alloca type");
3229     NewAI = &AI;
3230     // FIXME: We should be able to bail at this point with "nothing changed".
3231     // FIXME: We might want to defer PHI speculation until after here.
3232   } else {
3233     unsigned Alignment = AI.getAlignment();
3234     if (!Alignment) {
3235       // The minimum alignment which users can rely on when the explicit
3236       // alignment is omitted or zero is that required by the ABI for this
3237       // type.
3238       Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
3239     }
3240     Alignment = MinAlign(Alignment, BeginOffset);
3241     // If we will get at least this much alignment from the type alone, leave
3242     // the alloca's alignment unconstrained.
3243     if (Alignment <= DL->getABITypeAlignment(SliceTy))
3244       Alignment = 0;
3245     NewAI =
3246         new AllocaInst(SliceTy, nullptr, Alignment,
3247                        AI.getName() + ".sroa." + Twine(B - AS.begin()), &AI);
3248     ++NumNewAllocas;
3249   }
3251   DEBUG(dbgs() << "Rewriting alloca partition "
3252                << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3253                << "\n");
3255   // Track the high watermark on the worklist as it is only relevant for
3256   // promoted allocas. We will reset it to this point if the alloca is not in
3257   // fact scheduled for promotion.
3258   unsigned PPWOldSize = PostPromotionWorklist.size();
3259   unsigned NumUses = 0;
3260   SmallPtrSet<PHINode *, 8> PHIUsers;
3261   SmallPtrSet<SelectInst *, 8> SelectUsers;
3263   AllocaSliceRewriter Rewriter(*DL, AS, *this, AI, *NewAI, BeginOffset,
3264                                EndOffset, IsIntegerPromotable, VecTy, PHIUsers,
3265                                SelectUsers);
3266   bool Promotable = true;
3267   for (auto & SplitUse : SplitUses) {
3268     DEBUG(dbgs() << "  rewriting split ");
3269     DEBUG(AS.printSlice(dbgs(), SplitUse, ""));
3270     Promotable &= Rewriter.visit(SplitUse);
3271     ++NumUses;
3272   }
3273   for (AllocaSlices::iterator I = B; I != E; ++I) {
3274     DEBUG(dbgs() << "  rewriting ");
3275     DEBUG(AS.printSlice(dbgs(), I, ""));
3276     Promotable &= Rewriter.visit(I);
3277     ++NumUses;
3278   }
3280   NumAllocaPartitionUses += NumUses;
3281   MaxUsesPerAllocaPartition =
3282       std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
3284   // Now that we've processed all the slices in the new partition, check if any
3285   // PHIs or Selects would block promotion.
3286   for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3287                                             E = PHIUsers.end();
3288        I != E; ++I)
3289     if (!isSafePHIToSpeculate(**I, DL)) {
3290       Promotable = false;
3291       PHIUsers.clear();
3292       SelectUsers.clear();
3293       break;
3294     }
3295   for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3296                                                E = SelectUsers.end();
3297        I != E; ++I)
3298     if (!isSafeSelectToSpeculate(**I, DL)) {
3299       Promotable = false;
3300       PHIUsers.clear();
3301       SelectUsers.clear();
3302       break;
3303     }
3305   if (Promotable) {
3306     if (PHIUsers.empty() && SelectUsers.empty()) {
3307       // Promote the alloca.
3308       PromotableAllocas.push_back(NewAI);
3309     } else {
3310       // If we have either PHIs or Selects to speculate, add them to those
3311       // worklists and re-queue the new alloca so that we promote in on the
3312       // next iteration.
3313       for (PHINode *PHIUser : PHIUsers)
3314         SpeculatablePHIs.insert(PHIUser);
3315       for (SelectInst *SelectUser : SelectUsers)
3316         SpeculatableSelects.insert(SelectUser);
3317       Worklist.insert(NewAI);
3318     }
3319   } else {
3320     // If we can't promote the alloca, iterate on it to check for new
3321     // refinements exposed by splitting the current alloca. Don't iterate on an
3322     // alloca which didn't actually change and didn't get promoted.
3323     if (NewAI != &AI)
3324       Worklist.insert(NewAI);
3326     // Drop any post-promotion work items if promotion didn't happen.
3327     while (PostPromotionWorklist.size() > PPWOldSize)
3328       PostPromotionWorklist.pop_back();
3329   }
3331   return true;
3334 static void
3335 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3336                         uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
3337   if (Offset >= MaxSplitUseEndOffset) {
3338     SplitUses.clear();
3339     MaxSplitUseEndOffset = 0;
3340     return;
3341   }
3343   size_t SplitUsesOldSize = SplitUses.size();
3344   SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
3345                                  [Offset](const AllocaSlices::iterator &I) {
3346                     return I->endOffset() <= Offset;
3347                   }),
3348                   SplitUses.end());
3349   if (SplitUsesOldSize == SplitUses.size())
3350     return;
3352   // Recompute the max. While this is linear, so is remove_if.
3353   MaxSplitUseEndOffset = 0;
3354   for (AllocaSlices::iterator SplitUse : SplitUses)
3355     MaxSplitUseEndOffset =
3356         std::max(SplitUse->endOffset(), MaxSplitUseEndOffset);
3359 /// \brief Walks the slices of an alloca and form partitions based on them,
3360 /// rewriting each of their uses.
3361 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
3362   if (AS.begin() == AS.end())
3363     return false;
3365   unsigned NumPartitions = 0;
3366   bool Changed = false;
3367   SmallVector<AllocaSlices::iterator, 4> SplitUses;
3368   uint64_t MaxSplitUseEndOffset = 0;
3370   uint64_t BeginOffset = AS.begin()->beginOffset();
3372   for (AllocaSlices::iterator SI = AS.begin(), SJ = std::next(SI),
3373                               SE = AS.end();
3374        SI != SE; SI = SJ) {
3375     uint64_t MaxEndOffset = SI->endOffset();
3377     if (!SI->isSplittable()) {
3378       // When we're forming an unsplittable region, it must always start at the
3379       // first slice and will extend through its end.
3380       assert(BeginOffset == SI->beginOffset());
3382       // Form a partition including all of the overlapping slices with this
3383       // unsplittable slice.
3384       while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3385         if (!SJ->isSplittable())
3386           MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3387         ++SJ;
3388       }
3389     } else {
3390       assert(SI->isSplittable()); // Established above.
3392       // Collect all of the overlapping splittable slices.
3393       while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3394              SJ->isSplittable()) {
3395         MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3396         ++SJ;
3397       }
3399       // Back up MaxEndOffset and SJ if we ended the span early when
3400       // encountering an unsplittable slice.
3401       if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3402         assert(!SJ->isSplittable());
3403         MaxEndOffset = SJ->beginOffset();
3404       }
3405     }
3407     // Check if we have managed to move the end offset forward yet. If so,
3408     // we'll have to rewrite uses and erase old split uses.
3409     if (BeginOffset < MaxEndOffset) {
3410       // Rewrite a sequence of overlapping slices.
3411       Changed |= rewritePartition(AI, AS, SI, SJ, BeginOffset, MaxEndOffset,
3412                                   SplitUses);
3413       ++NumPartitions;
3415       removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3416     }
3418     // Accumulate all the splittable slices from the [SI,SJ) region which
3419     // overlap going forward.
3420     for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3421       if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3422         SplitUses.push_back(SK);
3423         MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
3424       }
3426     // If we're already at the end and we have no split uses, we're done.
3427     if (SJ == SE && SplitUses.empty())
3428       break;
3430     // If we have no split uses or no gap in offsets, we're ready to move to
3431     // the next slice.
3432     if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3433       BeginOffset = SJ->beginOffset();
3434       continue;
3435     }
3437     // Even if we have split slices, if the next slice is splittable and the
3438     // split slices reach it, we can simply set up the beginning offset of the
3439     // next iteration to bridge between them.
3440     if (SJ != SE && SJ->isSplittable() &&
3441         MaxSplitUseEndOffset > SJ->beginOffset()) {
3442       BeginOffset = MaxEndOffset;
3443       continue;
3444     }
3446     // Otherwise, we have a tail of split slices. Rewrite them with an empty
3447     // range of slices.
3448     uint64_t PostSplitEndOffset =
3449         SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
3451     Changed |= rewritePartition(AI, AS, SJ, SJ, MaxEndOffset,
3452                                 PostSplitEndOffset, SplitUses);
3453     ++NumPartitions;
3455     if (SJ == SE)
3456       break; // Skip the rest, we don't need to do any cleanup.
3458     removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3459                             PostSplitEndOffset);
3461     // Now just reset the begin offset for the next iteration.
3462     BeginOffset = SJ->beginOffset();
3463   }
3465   NumAllocaPartitions += NumPartitions;
3466   MaxPartitionsPerAlloca =
3467       std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
3469   return Changed;
3472 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3473 void SROA::clobberUse(Use &U) {
3474   Value *OldV = U;
3475   // Replace the use with an undef value.
3476   U = UndefValue::get(OldV->getType());
3478   // Check for this making an instruction dead. We have to garbage collect
3479   // all the dead instructions to ensure the uses of any alloca end up being
3480   // minimal.
3481   if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3482     if (isInstructionTriviallyDead(OldI)) {
3483       DeadInsts.insert(OldI);
3484     }
3487 /// \brief Analyze an alloca for SROA.
3488 ///
3489 /// This analyzes the alloca to ensure we can reason about it, builds
3490 /// the slices of the alloca, and then hands it off to be split and
3491 /// rewritten as needed.
3492 bool SROA::runOnAlloca(AllocaInst &AI) {
3493   DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3494   ++NumAllocasAnalyzed;
3496   // Special case dead allocas, as they're trivial.
3497   if (AI.use_empty()) {
3498     AI.eraseFromParent();
3499     return true;
3500   }
3502   // Skip alloca forms that this analysis can't handle.
3503   if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3504       DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
3505     return false;
3507   bool Changed = false;
3509   // First, split any FCA loads and stores touching this alloca to promote
3510   // better splitting and promotion opportunities.
3511   AggLoadStoreRewriter AggRewriter(*DL);
3512   Changed |= AggRewriter.rewrite(AI);
3514   // Build the slices using a recursive instruction-visiting builder.
3515   AllocaSlices AS(*DL, AI);
3516   DEBUG(AS.print(dbgs()));
3517   if (AS.isEscaped())
3518     return Changed;
3520   // Delete all the dead users of this alloca before splitting and rewriting it.
3521   for (Instruction *DeadUser : AS.getDeadUsers()) {
3522     // Free up everything used by this instruction.
3523     for (Use &DeadOp : DeadUser->operands())
3524       clobberUse(DeadOp);
3526     // Now replace the uses of this instruction.
3527     DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
3529     // And mark it for deletion.
3530     DeadInsts.insert(DeadUser);
3531     Changed = true;
3532   }
3533   for (Use *DeadOp : AS.getDeadOperands()) {
3534     clobberUse(*DeadOp);
3535     Changed = true;
3536   }
3538   // No slices to split. Leave the dead alloca for a later pass to clean up.
3539   if (AS.begin() == AS.end())
3540     return Changed;
3542   Changed |= splitAlloca(AI, AS);
3544   DEBUG(dbgs() << "  Speculating PHIs\n");
3545   while (!SpeculatablePHIs.empty())
3546     speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3548   DEBUG(dbgs() << "  Speculating Selects\n");
3549   while (!SpeculatableSelects.empty())
3550     speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3552   return Changed;
3555 /// \brief Delete the dead instructions accumulated in this run.
3556 ///
3557 /// Recursively deletes the dead instructions we've accumulated. This is done
3558 /// at the very end to maximize locality of the recursive delete and to
3559 /// minimize the problems of invalidated instruction pointers as such pointers
3560 /// are used heavily in the intermediate stages of the algorithm.
3561 ///
3562 /// We also record the alloca instructions deleted here so that they aren't
3563 /// subsequently handed to mem2reg to promote.
3564 void SROA::deleteDeadInstructions(SmallPtrSetImpl<AllocaInst*> &DeletedAllocas) {
3565   while (!DeadInsts.empty()) {
3566     Instruction *I = DeadInsts.pop_back_val();
3567     DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3569     I->replaceAllUsesWith(UndefValue::get(I->getType()));
3571     for (Use &Operand : I->operands())
3572       if (Instruction *U = dyn_cast<Instruction>(Operand)) {
3573         // Zero out the operand and see if it becomes trivially dead.
3574         Operand = nullptr;
3575         if (isInstructionTriviallyDead(U))
3576           DeadInsts.insert(U);
3577       }
3579     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3580       DeletedAllocas.insert(AI);
3582     ++NumDeleted;
3583     I->eraseFromParent();
3584   }
3587 static void enqueueUsersInWorklist(Instruction &I,
3588                                    SmallVectorImpl<Instruction *> &Worklist,
3589                                    SmallPtrSetImpl<Instruction *> &Visited) {
3590   for (User *U : I.users())
3591     if (Visited.insert(cast<Instruction>(U)))
3592       Worklist.push_back(cast<Instruction>(U));
3595 /// \brief Promote the allocas, using the best available technique.
3596 ///
3597 /// This attempts to promote whatever allocas have been identified as viable in
3598 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3599 /// If there is a domtree available, we attempt to promote using the full power
3600 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3601 /// based on the SSAUpdater utilities. This function returns whether any
3602 /// promotion occurred.
3603 bool SROA::promoteAllocas(Function &F) {
3604   if (PromotableAllocas.empty())
3605     return false;
3607   NumPromoted += PromotableAllocas.size();
3609   if (DT && !ForceSSAUpdater) {
3610     DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3611     PromoteMemToReg(PromotableAllocas, *DT, nullptr, AT);
3612     PromotableAllocas.clear();
3613     return true;
3614   }
3616   DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3617   SSAUpdater SSA;
3618   DIBuilder DIB(*F.getParent());
3619   SmallVector<Instruction *, 64> Insts;
3621   // We need a worklist to walk the uses of each alloca.
3622   SmallVector<Instruction *, 8> Worklist;
3623   SmallPtrSet<Instruction *, 8> Visited;
3624   SmallVector<Instruction *, 32> DeadInsts;
3626   for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3627     AllocaInst *AI = PromotableAllocas[Idx];
3628     Insts.clear();
3629     Worklist.clear();
3630     Visited.clear();
3632     enqueueUsersInWorklist(*AI, Worklist, Visited);
3634     while (!Worklist.empty()) {
3635       Instruction *I = Worklist.pop_back_val();
3637       // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3638       // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3639       // leading to them) here. Eventually it should use them to optimize the
3640       // scalar values produced.
3641       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3642         assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3643                II->getIntrinsicID() == Intrinsic::lifetime_end);
3644         II->eraseFromParent();
3645         continue;
3646       }
3648       // Push the loads and stores we find onto the list. SROA will already
3649       // have validated that all loads and stores are viable candidates for
3650       // promotion.
3651       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3652         assert(LI->getType() == AI->getAllocatedType());
3653         Insts.push_back(LI);
3654         continue;
3655       }
3656       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3657         assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3658         Insts.push_back(SI);
3659         continue;
3660       }
3662       // For everything else, we know that only no-op bitcasts and GEPs will
3663       // make it this far, just recurse through them and recall them for later
3664       // removal.
3665       DeadInsts.push_back(I);
3666       enqueueUsersInWorklist(*I, Worklist, Visited);
3667     }
3668     AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3669     while (!DeadInsts.empty())
3670       DeadInsts.pop_back_val()->eraseFromParent();
3671     AI->eraseFromParent();
3672   }
3674   PromotableAllocas.clear();
3675   return true;
3678 bool SROA::runOnFunction(Function &F) {
3679   if (skipOptnoneFunction(F))
3680     return false;
3682   DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3683   C = &F.getContext();
3684   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3685   if (!DLP) {
3686     DEBUG(dbgs() << "  Skipping SROA -- no target data!\n");
3687     return false;
3688   }
3689   DL = &DLP->getDataLayout();
3690   DominatorTreeWrapperPass *DTWP =
3691       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
3692   DT = DTWP ? &DTWP->getDomTree() : nullptr;
3693   AT = &getAnalysis<AssumptionTracker>();
3695   BasicBlock &EntryBB = F.getEntryBlock();
3696   for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
3697        I != E; ++I)
3698     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3699       Worklist.insert(AI);
3701   bool Changed = false;
3702   // A set of deleted alloca instruction pointers which should be removed from
3703   // the list of promotable allocas.
3704   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3706   do {
3707     while (!Worklist.empty()) {
3708       Changed |= runOnAlloca(*Worklist.pop_back_val());
3709       deleteDeadInstructions(DeletedAllocas);
3711       // Remove the deleted allocas from various lists so that we don't try to
3712       // continue processing them.
3713       if (!DeletedAllocas.empty()) {
3714         auto IsInSet = [&](AllocaInst *AI) {
3715           return DeletedAllocas.count(AI);
3716         };
3717         Worklist.remove_if(IsInSet);
3718         PostPromotionWorklist.remove_if(IsInSet);
3719         PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3720                                                PromotableAllocas.end(),
3721                                                IsInSet),
3722                                 PromotableAllocas.end());
3723         DeletedAllocas.clear();
3724       }
3725     }
3727     Changed |= promoteAllocas(F);
3729     Worklist = PostPromotionWorklist;
3730     PostPromotionWorklist.clear();
3731   } while (!Worklist.empty());
3733   return Changed;
3736 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3737   AU.addRequired<AssumptionTracker>();
3738   if (RequiresDomTree)
3739     AU.addRequired<DominatorTreeWrapperPass>();
3740   AU.setPreservesCFG();