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