a0be2c6947ed0af6769bd762b8b5eea41b15de65
[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     // Retain the debug information attached to the alloca for use when
742     // rewriting loads and stores.
743     if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
744       for (Value::use_iterator UI = DebugNode->use_begin(),
745                                UE = DebugNode->use_end();
746            UI != UE; ++UI)
747         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
748           DDIs.push_back(DDI);
749         else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
750           DVIs.push_back(DVI);
751     }
752
753     LoadAndStorePromoter::run(Insts);
754
755     // While we have the debug information, clear it off of the alloca. The
756     // caller takes care of deleting the alloca.
757     while (!DDIs.empty())
758       DDIs.pop_back_val()->eraseFromParent();
759     while (!DVIs.empty())
760       DVIs.pop_back_val()->eraseFromParent();
761   }
762
763   virtual bool isInstInList(Instruction *I,
764                             const SmallVectorImpl<Instruction*> &Insts) const {
765     Value *Ptr;
766     if (LoadInst *LI = dyn_cast<LoadInst>(I))
767       Ptr = LI->getOperand(0);
768     else
769       Ptr = cast<StoreInst>(I)->getPointerOperand();
770
771     // Only used to detect cycles, which will be rare and quickly found as
772     // we're walking up a chain of defs rather than down through uses.
773     SmallPtrSet<Value *, 4> Visited;
774
775     do {
776       if (Ptr == &AI)
777         return true;
778
779       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
780         Ptr = BCI->getOperand(0);
781       else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
782         Ptr = GEPI->getPointerOperand();
783       else
784         return false;
785
786     } while (Visited.insert(Ptr));
787
788     return false;
789   }
790
791   virtual void updateDebugInfo(Instruction *Inst) const {
792     for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
793            E = DDIs.end(); I != E; ++I) {
794       DbgDeclareInst *DDI = *I;
795       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
796         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
797       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
798         ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
799     }
800     for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
801            E = DVIs.end(); I != E; ++I) {
802       DbgValueInst *DVI = *I;
803       Value *Arg = 0;
804       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
805         // If an argument is zero extended then use argument directly. The ZExt
806         // may be zapped by an optimization pass in future.
807         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
808           Arg = dyn_cast<Argument>(ZExt->getOperand(0));
809         else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
810           Arg = dyn_cast<Argument>(SExt->getOperand(0));
811         if (!Arg)
812           Arg = SI->getValueOperand();
813       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
814         Arg = LI->getPointerOperand();
815       } else {
816         continue;
817       }
818       Instruction *DbgVal =
819         DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
820                                      Inst);
821       DbgVal->setDebugLoc(DVI->getDebugLoc());
822     }
823   }
824 };
825 } // end anon namespace
826
827
828 namespace {
829 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
830 ///
831 /// This pass takes allocations which can be completely analyzed (that is, they
832 /// don't escape) and tries to turn them into scalar SSA values. There are
833 /// a few steps to this process.
834 ///
835 /// 1) It takes allocations of aggregates and analyzes the ways in which they
836 ///    are used to try to split them into smaller allocations, ideally of
837 ///    a single scalar data type. It will split up memcpy and memset accesses
838 ///    as necessary and try to isolate individual scalar accesses.
839 /// 2) It will transform accesses into forms which are suitable for SSA value
840 ///    promotion. This can be replacing a memset with a scalar store of an
841 ///    integer value, or it can involve speculating operations on a PHI or
842 ///    select to be a PHI or select of the results.
843 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
844 ///    onto insert and extract operations on a vector value, and convert them to
845 ///    this form. By doing so, it will enable promotion of vector aggregates to
846 ///    SSA vector values.
847 class SROA : public FunctionPass {
848   const bool RequiresDomTree;
849
850   LLVMContext *C;
851   const DataLayout *DL;
852   DominatorTree *DT;
853
854   /// \brief Worklist of alloca instructions to simplify.
855   ///
856   /// Each alloca in the function is added to this. Each new alloca formed gets
857   /// added to it as well to recursively simplify unless that alloca can be
858   /// directly promoted. Finally, each time we rewrite a use of an alloca other
859   /// the one being actively rewritten, we add it back onto the list if not
860   /// already present to ensure it is re-visited.
861   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
862
863   /// \brief A collection of instructions to delete.
864   /// We try to batch deletions to simplify code and make things a bit more
865   /// efficient.
866   SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
867
868   /// \brief Post-promotion worklist.
869   ///
870   /// Sometimes we discover an alloca which has a high probability of becoming
871   /// viable for SROA after a round of promotion takes place. In those cases,
872   /// the alloca is enqueued here for re-processing.
873   ///
874   /// Note that we have to be very careful to clear allocas out of this list in
875   /// the event they are deleted.
876   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
877
878   /// \brief A collection of alloca instructions we can directly promote.
879   std::vector<AllocaInst *> PromotableAllocas;
880
881   /// \brief A worklist of PHIs to speculate prior to promoting allocas.
882   ///
883   /// All of these PHIs have been checked for the safety of speculation and by
884   /// being speculated will allow promoting allocas currently in the promotable
885   /// queue.
886   SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
887
888   /// \brief A worklist of select instructions to speculate prior to promoting
889   /// allocas.
890   ///
891   /// All of these select instructions have been checked for the safety of
892   /// speculation and by being speculated will allow promoting allocas
893   /// currently in the promotable queue.
894   SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
895
896 public:
897   SROA(bool RequiresDomTree = true)
898       : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
899         C(0), DL(0), DT(0) {
900     initializeSROAPass(*PassRegistry::getPassRegistry());
901   }
902   bool runOnFunction(Function &F);
903   void getAnalysisUsage(AnalysisUsage &AU) const;
904
905   const char *getPassName() const { return "SROA"; }
906   static char ID;
907
908 private:
909   friend class PHIOrSelectSpeculator;
910   friend class AllocaSliceRewriter;
911
912   bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
913                         AllocaSlices::iterator B, AllocaSlices::iterator E,
914                         int64_t BeginOffset, int64_t EndOffset,
915                         ArrayRef<AllocaSlices::iterator> SplitUses);
916   bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
917   bool runOnAlloca(AllocaInst &AI);
918   void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
919   bool promoteAllocas(Function &F);
920 };
921 }
922
923 char SROA::ID = 0;
924
925 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
926   return new SROA(RequiresDomTree);
927 }
928
929 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
930                       false, false)
931 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
932 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
933                     false, false)
934
935 /// Walk the range of a partitioning looking for a common type to cover this
936 /// sequence of slices.
937 static Type *findCommonType(AllocaSlices::const_iterator B,
938                             AllocaSlices::const_iterator E,
939                             uint64_t EndOffset) {
940   Type *Ty = 0;
941   for (AllocaSlices::const_iterator I = B; I != E; ++I) {
942     Use *U = I->getUse();
943     if (isa<IntrinsicInst>(*U->getUser()))
944       continue;
945     if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
946       continue;
947
948     Type *UserTy = 0;
949     if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
950       UserTy = LI->getType();
951     else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
952       UserTy = SI->getValueOperand()->getType();
953     else
954       return 0; // Bail if we have weird uses.
955
956     if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
957       // If the type is larger than the partition, skip it. We only encounter
958       // this for split integer operations where we want to use the type of the
959       // entity causing the split.
960       if (ITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
961         continue;
962
963       // If we have found an integer type use covering the alloca, use that
964       // regardless of the other types, as integers are often used for a
965       // "bucket
966       // of bits" type.
967       return ITy;
968     }
969
970     if (Ty && Ty != UserTy)
971       return 0;
972
973     Ty = UserTy;
974   }
975   return Ty;
976 }
977
978 /// PHI instructions that use an alloca and are subsequently loaded can be
979 /// rewritten to load both input pointers in the pred blocks and then PHI the
980 /// results, allowing the load of the alloca to be promoted.
981 /// From this:
982 ///   %P2 = phi [i32* %Alloca, i32* %Other]
983 ///   %V = load i32* %P2
984 /// to:
985 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
986 ///   ...
987 ///   %V2 = load i32* %Other
988 ///   ...
989 ///   %V = phi [i32 %V1, i32 %V2]
990 ///
991 /// We can do this to a select if its only uses are loads and if the operands
992 /// to the select can be loaded unconditionally.
993 ///
994 /// FIXME: This should be hoisted into a generic utility, likely in
995 /// Transforms/Util/Local.h
996 static bool isSafePHIToSpeculate(PHINode &PN,
997                                  const DataLayout *DL = 0) {
998   // For now, we can only do this promotion if the load is in the same block
999   // as the PHI, and if there are no stores between the phi and load.
1000   // TODO: Allow recursive phi users.
1001   // TODO: Allow stores.
1002   BasicBlock *BB = PN.getParent();
1003   unsigned MaxAlign = 0;
1004   bool HaveLoad = false;
1005   for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
1006        ++UI) {
1007     LoadInst *LI = dyn_cast<LoadInst>(*UI);
1008     if (LI == 0 || !LI->isSimple())
1009       return false;
1010
1011     // For now we only allow loads in the same block as the PHI.  This is
1012     // a common case that happens when instcombine merges two loads through
1013     // a PHI.
1014     if (LI->getParent() != BB)
1015       return false;
1016
1017     // Ensure that there are no instructions between the PHI and the load that
1018     // could store.
1019     for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1020       if (BBI->mayWriteToMemory())
1021         return false;
1022
1023     MaxAlign = std::max(MaxAlign, LI->getAlignment());
1024     HaveLoad = true;
1025   }
1026
1027   if (!HaveLoad)
1028     return false;
1029
1030   // We can only transform this if it is safe to push the loads into the
1031   // predecessor blocks. The only thing to watch out for is that we can't put
1032   // a possibly trapping load in the predecessor if it is a critical edge.
1033   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1034     TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1035     Value *InVal = PN.getIncomingValue(Idx);
1036
1037     // If the value is produced by the terminator of the predecessor (an
1038     // invoke) or it has side-effects, there is no valid place to put a load
1039     // in the predecessor.
1040     if (TI == InVal || TI->mayHaveSideEffects())
1041       return false;
1042
1043     // If the predecessor has a single successor, then the edge isn't
1044     // critical.
1045     if (TI->getNumSuccessors() == 1)
1046       continue;
1047
1048     // If this pointer is always safe to load, or if we can prove that there
1049     // is already a load in the block, then we can move the load to the pred
1050     // block.
1051     if (InVal->isDereferenceablePointer() ||
1052         isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
1053       continue;
1054
1055     return false;
1056   }
1057
1058   return true;
1059 }
1060
1061 static void speculatePHINodeLoads(PHINode &PN) {
1062   DEBUG(dbgs() << "    original: " << PN << "\n");
1063
1064   Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1065   IRBuilderTy PHIBuilder(&PN);
1066   PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1067                                         PN.getName() + ".sroa.speculated");
1068
1069   // Get the TBAA tag and alignment to use from one of the loads.  It doesn't
1070   // matter which one we get and if any differ.
1071   LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1072   MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1073   unsigned Align = SomeLoad->getAlignment();
1074
1075   // Rewrite all loads of the PN to use the new PHI.
1076   while (!PN.use_empty()) {
1077     LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1078     LI->replaceAllUsesWith(NewPN);
1079     LI->eraseFromParent();
1080   }
1081
1082   // Inject loads into all of the pred blocks.
1083   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1084     BasicBlock *Pred = PN.getIncomingBlock(Idx);
1085     TerminatorInst *TI = Pred->getTerminator();
1086     Value *InVal = PN.getIncomingValue(Idx);
1087     IRBuilderTy PredBuilder(TI);
1088
1089     LoadInst *Load = PredBuilder.CreateLoad(
1090         InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1091     ++NumLoadsSpeculated;
1092     Load->setAlignment(Align);
1093     if (TBAATag)
1094       Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1095     NewPN->addIncoming(Load, Pred);
1096   }
1097
1098   DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
1099   PN.eraseFromParent();
1100 }
1101
1102 /// Select instructions that use an alloca and are subsequently loaded can be
1103 /// rewritten to load both input pointers and then select between the result,
1104 /// allowing the load of the alloca to be promoted.
1105 /// From this:
1106 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1107 ///   %V = load i32* %P2
1108 /// to:
1109 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1110 ///   %V2 = load i32* %Other
1111 ///   %V = select i1 %cond, i32 %V1, i32 %V2
1112 ///
1113 /// We can do this to a select if its only uses are loads and if the operand
1114 /// to the select can be loaded unconditionally.
1115 static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
1116   Value *TValue = SI.getTrueValue();
1117   Value *FValue = SI.getFalseValue();
1118   bool TDerefable = TValue->isDereferenceablePointer();
1119   bool FDerefable = FValue->isDereferenceablePointer();
1120
1121   for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1122        ++UI) {
1123     LoadInst *LI = dyn_cast<LoadInst>(*UI);
1124     if (LI == 0 || !LI->isSimple())
1125       return false;
1126
1127     // Both operands to the select need to be dereferencable, either
1128     // absolutely (e.g. allocas) or at this point because we can see other
1129     // accesses to it.
1130     if (!TDerefable &&
1131         !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
1132       return false;
1133     if (!FDerefable &&
1134         !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
1135       return false;
1136   }
1137
1138   return true;
1139 }
1140
1141 static void speculateSelectInstLoads(SelectInst &SI) {
1142   DEBUG(dbgs() << "    original: " << SI << "\n");
1143
1144   IRBuilderTy IRB(&SI);
1145   Value *TV = SI.getTrueValue();
1146   Value *FV = SI.getFalseValue();
1147   // Replace the loads of the select with a select of two loads.
1148   while (!SI.use_empty()) {
1149     LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1150     assert(LI->isSimple() && "We only speculate simple loads");
1151
1152     IRB.SetInsertPoint(LI);
1153     LoadInst *TL =
1154         IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1155     LoadInst *FL =
1156         IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1157     NumLoadsSpeculated += 2;
1158
1159     // Transfer alignment and TBAA info if present.
1160     TL->setAlignment(LI->getAlignment());
1161     FL->setAlignment(LI->getAlignment());
1162     if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1163       TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1164       FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1165     }
1166
1167     Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1168                                 LI->getName() + ".sroa.speculated");
1169
1170     DEBUG(dbgs() << "          speculated to: " << *V << "\n");
1171     LI->replaceAllUsesWith(V);
1172     LI->eraseFromParent();
1173   }
1174   SI.eraseFromParent();
1175 }
1176
1177 /// \brief Build a GEP out of a base pointer and indices.
1178 ///
1179 /// This will return the BasePtr if that is valid, or build a new GEP
1180 /// instruction using the IRBuilder if GEP-ing is needed.
1181 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1182                        SmallVectorImpl<Value *> &Indices) {
1183   if (Indices.empty())
1184     return BasePtr;
1185
1186   // A single zero index is a no-op, so check for this and avoid building a GEP
1187   // in that case.
1188   if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1189     return BasePtr;
1190
1191   return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
1192 }
1193
1194 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1195 /// TargetTy without changing the offset of the pointer.
1196 ///
1197 /// This routine assumes we've already established a properly offset GEP with
1198 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1199 /// zero-indices down through type layers until we find one the same as
1200 /// TargetTy. If we can't find one with the same type, we at least try to use
1201 /// one with the same size. If none of that works, we just produce the GEP as
1202 /// indicated by Indices to have the correct offset.
1203 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1204                                     Value *BasePtr, Type *Ty, Type *TargetTy,
1205                                     SmallVectorImpl<Value *> &Indices) {
1206   if (Ty == TargetTy)
1207     return buildGEP(IRB, BasePtr, Indices);
1208
1209   // See if we can descend into a struct and locate a field with the correct
1210   // type.
1211   unsigned NumLayers = 0;
1212   Type *ElementTy = Ty;
1213   do {
1214     if (ElementTy->isPointerTy())
1215       break;
1216     if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1217       ElementTy = SeqTy->getElementType();
1218       // Note that we use the default address space as this index is over an
1219       // array or a vector, not a pointer.
1220       Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
1221     } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1222       if (STy->element_begin() == STy->element_end())
1223         break; // Nothing left to descend into.
1224       ElementTy = *STy->element_begin();
1225       Indices.push_back(IRB.getInt32(0));
1226     } else {
1227       break;
1228     }
1229     ++NumLayers;
1230   } while (ElementTy != TargetTy);
1231   if (ElementTy != TargetTy)
1232     Indices.erase(Indices.end() - NumLayers, Indices.end());
1233
1234   return buildGEP(IRB, BasePtr, Indices);
1235 }
1236
1237 /// \brief Recursively compute indices for a natural GEP.
1238 ///
1239 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1240 /// element types adding appropriate indices for the GEP.
1241 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1242                                        Value *Ptr, Type *Ty, APInt &Offset,
1243                                        Type *TargetTy,
1244                                        SmallVectorImpl<Value *> &Indices) {
1245   if (Offset == 0)
1246     return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices);
1247
1248   // We can't recurse through pointer types.
1249   if (Ty->isPointerTy())
1250     return 0;
1251
1252   // We try to analyze GEPs over vectors here, but note that these GEPs are
1253   // extremely poorly defined currently. The long-term goal is to remove GEPing
1254   // over a vector from the IR completely.
1255   if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1256     unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1257     if (ElementSizeInBits % 8)
1258       return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1259     APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1260     APInt NumSkippedElements = Offset.sdiv(ElementSize);
1261     if (NumSkippedElements.ugt(VecTy->getNumElements()))
1262       return 0;
1263     Offset -= NumSkippedElements * ElementSize;
1264     Indices.push_back(IRB.getInt(NumSkippedElements));
1265     return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1266                                     Offset, TargetTy, Indices);
1267   }
1268
1269   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1270     Type *ElementTy = ArrTy->getElementType();
1271     APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1272     APInt NumSkippedElements = Offset.sdiv(ElementSize);
1273     if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1274       return 0;
1275
1276     Offset -= NumSkippedElements * ElementSize;
1277     Indices.push_back(IRB.getInt(NumSkippedElements));
1278     return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1279                                     Indices);
1280   }
1281
1282   StructType *STy = dyn_cast<StructType>(Ty);
1283   if (!STy)
1284     return 0;
1285
1286   const StructLayout *SL = DL.getStructLayout(STy);
1287   uint64_t StructOffset = Offset.getZExtValue();
1288   if (StructOffset >= SL->getSizeInBytes())
1289     return 0;
1290   unsigned Index = SL->getElementContainingOffset(StructOffset);
1291   Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1292   Type *ElementTy = STy->getElementType(Index);
1293   if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1294     return 0; // The offset points into alignment padding.
1295
1296   Indices.push_back(IRB.getInt32(Index));
1297   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1298                                   Indices);
1299 }
1300
1301 /// \brief Get a natural GEP from a base pointer to a particular offset and
1302 /// resulting in a particular type.
1303 ///
1304 /// The goal is to produce a "natural" looking GEP that works with the existing
1305 /// composite types to arrive at the appropriate offset and element type for
1306 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1307 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1308 /// Indices, and setting Ty to the result subtype.
1309 ///
1310 /// If no natural GEP can be constructed, this function returns null.
1311 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1312                                       Value *Ptr, APInt Offset, Type *TargetTy,
1313                                       SmallVectorImpl<Value *> &Indices) {
1314   PointerType *Ty = cast<PointerType>(Ptr->getType());
1315
1316   // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1317   // an i8.
1318   if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1319     return 0;
1320
1321   Type *ElementTy = Ty->getElementType();
1322   if (!ElementTy->isSized())
1323     return 0; // We can't GEP through an unsized element.
1324   APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1325   if (ElementSize == 0)
1326     return 0; // Zero-length arrays can't help us build a natural GEP.
1327   APInt NumSkippedElements = Offset.sdiv(ElementSize);
1328
1329   Offset -= NumSkippedElements * ElementSize;
1330   Indices.push_back(IRB.getInt(NumSkippedElements));
1331   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1332                                   Indices);
1333 }
1334
1335 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1336 /// resulting pointer has PointerTy.
1337 ///
1338 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1339 /// and produces the pointer type desired. Where it cannot, it will try to use
1340 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1341 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1342 /// bitcast to the type.
1343 ///
1344 /// The strategy for finding the more natural GEPs is to peel off layers of the
1345 /// pointer, walking back through bit casts and GEPs, searching for a base
1346 /// pointer from which we can compute a natural GEP with the desired
1347 /// properties. The algorithm tries to fold as many constant indices into
1348 /// a single GEP as possible, thus making each GEP more independent of the
1349 /// surrounding code.
1350 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL,
1351                              Value *Ptr, APInt Offset, Type *PointerTy) {
1352   // Even though we don't look through PHI nodes, we could be called on an
1353   // instruction in an unreachable block, which may be on a cycle.
1354   SmallPtrSet<Value *, 4> Visited;
1355   Visited.insert(Ptr);
1356   SmallVector<Value *, 4> Indices;
1357
1358   // We may end up computing an offset pointer that has the wrong type. If we
1359   // never are able to compute one directly that has the correct type, we'll
1360   // fall back to it, so keep it around here.
1361   Value *OffsetPtr = 0;
1362
1363   // Remember any i8 pointer we come across to re-use if we need to do a raw
1364   // byte offset.
1365   Value *Int8Ptr = 0;
1366   APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1367
1368   Type *TargetTy = PointerTy->getPointerElementType();
1369
1370   do {
1371     // First fold any existing GEPs into the offset.
1372     while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1373       APInt GEPOffset(Offset.getBitWidth(), 0);
1374       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1375         break;
1376       Offset += GEPOffset;
1377       Ptr = GEP->getPointerOperand();
1378       if (!Visited.insert(Ptr))
1379         break;
1380     }
1381
1382     // See if we can perform a natural GEP here.
1383     Indices.clear();
1384     if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1385                                            Indices)) {
1386       if (P->getType() == PointerTy) {
1387         // Zap any offset pointer that we ended up computing in previous rounds.
1388         if (OffsetPtr && OffsetPtr->use_empty())
1389           if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1390             I->eraseFromParent();
1391         return P;
1392       }
1393       if (!OffsetPtr) {
1394         OffsetPtr = P;
1395       }
1396     }
1397
1398     // Stash this pointer if we've found an i8*.
1399     if (Ptr->getType()->isIntegerTy(8)) {
1400       Int8Ptr = Ptr;
1401       Int8PtrOffset = Offset;
1402     }
1403
1404     // Peel off a layer of the pointer and update the offset appropriately.
1405     if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1406       Ptr = cast<Operator>(Ptr)->getOperand(0);
1407     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1408       if (GA->mayBeOverridden())
1409         break;
1410       Ptr = GA->getAliasee();
1411     } else {
1412       break;
1413     }
1414     assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1415   } while (Visited.insert(Ptr));
1416
1417   if (!OffsetPtr) {
1418     if (!Int8Ptr) {
1419       Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1420                                   "raw_cast");
1421       Int8PtrOffset = Offset;
1422     }
1423
1424     OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1425       IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1426                             "raw_idx");
1427   }
1428   Ptr = OffsetPtr;
1429
1430   // On the off chance we were targeting i8*, guard the bitcast here.
1431   if (Ptr->getType() != PointerTy)
1432     Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
1433
1434   return Ptr;
1435 }
1436
1437 /// \brief Test whether we can convert a value from the old to the new type.
1438 ///
1439 /// This predicate should be used to guard calls to convertValue in order to
1440 /// ensure that we only try to convert viable values. The strategy is that we
1441 /// will peel off single element struct and array wrappings to get to an
1442 /// underlying value, and convert that value.
1443 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1444   if (OldTy == NewTy)
1445     return true;
1446   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1447     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1448       if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1449         return true;
1450   if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1451     return false;
1452   if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1453     return false;
1454
1455   // We can convert pointers to integers and vice-versa. Same for vectors
1456   // of pointers and integers.
1457   OldTy = OldTy->getScalarType();
1458   NewTy = NewTy->getScalarType();
1459   if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1460     if (NewTy->isPointerTy() && OldTy->isPointerTy())
1461       return true;
1462     if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1463       return true;
1464     return false;
1465   }
1466
1467   return true;
1468 }
1469
1470 /// \brief Generic routine to convert an SSA value to a value of a different
1471 /// type.
1472 ///
1473 /// This will try various different casting techniques, such as bitcasts,
1474 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1475 /// two types for viability with this routine.
1476 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1477                            Type *NewTy) {
1478   Type *OldTy = V->getType();
1479   assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1480
1481   if (OldTy == NewTy)
1482     return V;
1483
1484   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1485     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1486       if (NewITy->getBitWidth() > OldITy->getBitWidth())
1487         return IRB.CreateZExt(V, NewITy);
1488
1489   // See if we need inttoptr for this type pair. A cast involving both scalars
1490   // and vectors requires and additional bitcast.
1491   if (OldTy->getScalarType()->isIntegerTy() &&
1492       NewTy->getScalarType()->isPointerTy()) {
1493     // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1494     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1495       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1496                                 NewTy);
1497
1498     // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1499     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1500       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1501                                 NewTy);
1502
1503     return IRB.CreateIntToPtr(V, NewTy);
1504   }
1505
1506   // See if we need ptrtoint for this type pair. A cast involving both scalars
1507   // and vectors requires and additional bitcast.
1508   if (OldTy->getScalarType()->isPointerTy() &&
1509       NewTy->getScalarType()->isIntegerTy()) {
1510     // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1511     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1512       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1513                                NewTy);
1514
1515     // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1516     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1517       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1518                                NewTy);
1519
1520     return IRB.CreatePtrToInt(V, NewTy);
1521   }
1522
1523   return IRB.CreateBitCast(V, NewTy);
1524 }
1525
1526 /// \brief Test whether the given slice use can be promoted to a vector.
1527 ///
1528 /// This function is called to test each entry in a partioning which is slated
1529 /// for a single slice.
1530 static bool isVectorPromotionViableForSlice(
1531     const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1532     uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1533     AllocaSlices::const_iterator I) {
1534   // First validate the slice offsets.
1535   uint64_t BeginOffset =
1536       std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
1537   uint64_t BeginIndex = BeginOffset / ElementSize;
1538   if (BeginIndex * ElementSize != BeginOffset ||
1539       BeginIndex >= Ty->getNumElements())
1540     return false;
1541   uint64_t EndOffset =
1542       std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
1543   uint64_t EndIndex = EndOffset / ElementSize;
1544   if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1545     return false;
1546
1547   assert(EndIndex > BeginIndex && "Empty vector!");
1548   uint64_t NumElements = EndIndex - BeginIndex;
1549   Type *SliceTy =
1550       (NumElements == 1) ? Ty->getElementType()
1551                          : VectorType::get(Ty->getElementType(), NumElements);
1552
1553   Type *SplitIntTy =
1554       Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1555
1556   Use *U = I->getUse();
1557
1558   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1559     if (MI->isVolatile())
1560       return false;
1561     if (!I->isSplittable())
1562       return false; // Skip any unsplittable intrinsics.
1563   } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1564     // Disable vector promotion when there are loads or stores of an FCA.
1565     return false;
1566   } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1567     if (LI->isVolatile())
1568       return false;
1569     Type *LTy = LI->getType();
1570     if (SliceBeginOffset > I->beginOffset() ||
1571         SliceEndOffset < I->endOffset()) {
1572       assert(LTy->isIntegerTy());
1573       LTy = SplitIntTy;
1574     }
1575     if (!canConvertValue(DL, SliceTy, LTy))
1576       return false;
1577   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1578     if (SI->isVolatile())
1579       return false;
1580     Type *STy = SI->getValueOperand()->getType();
1581     if (SliceBeginOffset > I->beginOffset() ||
1582         SliceEndOffset < I->endOffset()) {
1583       assert(STy->isIntegerTy());
1584       STy = SplitIntTy;
1585     }
1586     if (!canConvertValue(DL, STy, SliceTy))
1587       return false;
1588   } else {
1589     return false;
1590   }
1591
1592   return true;
1593 }
1594
1595 /// \brief Test whether the given alloca partitioning and range of slices can be
1596 /// promoted to a vector.
1597 ///
1598 /// This is a quick test to check whether we can rewrite a particular alloca
1599 /// partition (and its newly formed alloca) into a vector alloca with only
1600 /// whole-vector loads and stores such that it could be promoted to a vector
1601 /// SSA value. We only can ensure this for a limited set of operations, and we
1602 /// don't want to do the rewrites unless we are confident that the result will
1603 /// be promotable, so we have an early test here.
1604 static bool
1605 isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1606                         uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1607                         AllocaSlices::const_iterator I,
1608                         AllocaSlices::const_iterator E,
1609                         ArrayRef<AllocaSlices::iterator> SplitUses) {
1610   VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1611   if (!Ty)
1612     return false;
1613
1614   uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
1615
1616   // While the definition of LLVM vectors is bitpacked, we don't support sizes
1617   // that aren't byte sized.
1618   if (ElementSize % 8)
1619     return false;
1620   assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
1621          "vector size not a multiple of element size?");
1622   ElementSize /= 8;
1623
1624   for (; I != E; ++I)
1625     if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1626                                          SliceEndOffset, Ty, ElementSize, I))
1627       return false;
1628
1629   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1630                                                         SUE = SplitUses.end();
1631        SUI != SUE; ++SUI)
1632     if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1633                                          SliceEndOffset, Ty, ElementSize, *SUI))
1634       return false;
1635
1636   return true;
1637 }
1638
1639 /// \brief Test whether a slice of an alloca is valid for integer widening.
1640 ///
1641 /// This implements the necessary checking for the \c isIntegerWideningViable
1642 /// test below on a single slice of the alloca.
1643 static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1644                                             Type *AllocaTy,
1645                                             uint64_t AllocBeginOffset,
1646                                             uint64_t Size, AllocaSlices &S,
1647                                             AllocaSlices::const_iterator I,
1648                                             bool &WholeAllocaOp) {
1649   uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1650   uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1651
1652   // We can't reasonably handle cases where the load or store extends past
1653   // the end of the aloca's type and into its padding.
1654   if (RelEnd > Size)
1655     return false;
1656
1657   Use *U = I->getUse();
1658
1659   if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1660     if (LI->isVolatile())
1661       return false;
1662     if (RelBegin == 0 && RelEnd == Size)
1663       WholeAllocaOp = true;
1664     if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1665       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1666         return false;
1667     } else if (RelBegin != 0 || RelEnd != Size ||
1668                !canConvertValue(DL, AllocaTy, LI->getType())) {
1669       // Non-integer loads need to be convertible from the alloca type so that
1670       // they are promotable.
1671       return false;
1672     }
1673   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1674     Type *ValueTy = SI->getValueOperand()->getType();
1675     if (SI->isVolatile())
1676       return false;
1677     if (RelBegin == 0 && RelEnd == Size)
1678       WholeAllocaOp = true;
1679     if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
1680       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1681         return false;
1682     } else if (RelBegin != 0 || RelEnd != Size ||
1683                !canConvertValue(DL, ValueTy, AllocaTy)) {
1684       // Non-integer stores need to be convertible to the alloca type so that
1685       // they are promotable.
1686       return false;
1687     }
1688   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1689     if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1690       return false;
1691     if (!I->isSplittable())
1692       return false; // Skip any unsplittable intrinsics.
1693   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1694     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1695         II->getIntrinsicID() != Intrinsic::lifetime_end)
1696       return false;
1697   } else {
1698     return false;
1699   }
1700
1701   return true;
1702 }
1703
1704 /// \brief Test whether the given alloca partition's integer operations can be
1705 /// widened to promotable ones.
1706 ///
1707 /// This is a quick test to check whether we can rewrite the integer loads and
1708 /// stores to a particular alloca into wider loads and stores and be able to
1709 /// promote the resulting alloca.
1710 static bool
1711 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
1712                         uint64_t AllocBeginOffset, AllocaSlices &S,
1713                         AllocaSlices::const_iterator I,
1714                         AllocaSlices::const_iterator E,
1715                         ArrayRef<AllocaSlices::iterator> SplitUses) {
1716   uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
1717   // Don't create integer types larger than the maximum bitwidth.
1718   if (SizeInBits > IntegerType::MAX_INT_BITS)
1719     return false;
1720
1721   // Don't try to handle allocas with bit-padding.
1722   if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
1723     return false;
1724
1725   // We need to ensure that an integer type with the appropriate bitwidth can
1726   // be converted to the alloca type, whatever that is. We don't want to force
1727   // the alloca itself to have an integer type if there is a more suitable one.
1728   Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
1729   if (!canConvertValue(DL, AllocaTy, IntTy) ||
1730       !canConvertValue(DL, IntTy, AllocaTy))
1731     return false;
1732
1733   uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1734
1735   // While examining uses, we ensure that the alloca has a covering load or
1736   // store. We don't want to widen the integer operations only to fail to
1737   // promote due to some other unsplittable entry (which we may make splittable
1738   // later). However, if there are only splittable uses, go ahead and assume
1739   // that we cover the alloca.
1740   bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
1741
1742   for (; I != E; ++I)
1743     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1744                                          S, I, WholeAllocaOp))
1745       return false;
1746
1747   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1748                                                         SUE = SplitUses.end();
1749        SUI != SUE; ++SUI)
1750     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1751                                          S, *SUI, WholeAllocaOp))
1752       return false;
1753
1754   return WholeAllocaOp;
1755 }
1756
1757 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1758                              IntegerType *Ty, uint64_t Offset,
1759                              const Twine &Name) {
1760   DEBUG(dbgs() << "       start: " << *V << "\n");
1761   IntegerType *IntTy = cast<IntegerType>(V->getType());
1762   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1763          "Element extends past full value");
1764   uint64_t ShAmt = 8*Offset;
1765   if (DL.isBigEndian())
1766     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1767   if (ShAmt) {
1768     V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
1769     DEBUG(dbgs() << "     shifted: " << *V << "\n");
1770   }
1771   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1772          "Cannot extract to a larger integer!");
1773   if (Ty != IntTy) {
1774     V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
1775     DEBUG(dbgs() << "     trunced: " << *V << "\n");
1776   }
1777   return V;
1778 }
1779
1780 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
1781                             Value *V, uint64_t Offset, const Twine &Name) {
1782   IntegerType *IntTy = cast<IntegerType>(Old->getType());
1783   IntegerType *Ty = cast<IntegerType>(V->getType());
1784   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1785          "Cannot insert a larger integer!");
1786   DEBUG(dbgs() << "       start: " << *V << "\n");
1787   if (Ty != IntTy) {
1788     V = IRB.CreateZExt(V, IntTy, Name + ".ext");
1789     DEBUG(dbgs() << "    extended: " << *V << "\n");
1790   }
1791   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1792          "Element store outside of alloca store");
1793   uint64_t ShAmt = 8*Offset;
1794   if (DL.isBigEndian())
1795     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1796   if (ShAmt) {
1797     V = IRB.CreateShl(V, ShAmt, Name + ".shift");
1798     DEBUG(dbgs() << "     shifted: " << *V << "\n");
1799   }
1800
1801   if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1802     APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1803     Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
1804     DEBUG(dbgs() << "      masked: " << *Old << "\n");
1805     V = IRB.CreateOr(Old, V, Name + ".insert");
1806     DEBUG(dbgs() << "    inserted: " << *V << "\n");
1807   }
1808   return V;
1809 }
1810
1811 static Value *extractVector(IRBuilderTy &IRB, Value *V,
1812                             unsigned BeginIndex, unsigned EndIndex,
1813                             const Twine &Name) {
1814   VectorType *VecTy = cast<VectorType>(V->getType());
1815   unsigned NumElements = EndIndex - BeginIndex;
1816   assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1817
1818   if (NumElements == VecTy->getNumElements())
1819     return V;
1820
1821   if (NumElements == 1) {
1822     V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1823                                  Name + ".extract");
1824     DEBUG(dbgs() << "     extract: " << *V << "\n");
1825     return V;
1826   }
1827
1828   SmallVector<Constant*, 8> Mask;
1829   Mask.reserve(NumElements);
1830   for (unsigned i = BeginIndex; i != EndIndex; ++i)
1831     Mask.push_back(IRB.getInt32(i));
1832   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1833                               ConstantVector::get(Mask),
1834                               Name + ".extract");
1835   DEBUG(dbgs() << "     shuffle: " << *V << "\n");
1836   return V;
1837 }
1838
1839 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
1840                            unsigned BeginIndex, const Twine &Name) {
1841   VectorType *VecTy = cast<VectorType>(Old->getType());
1842   assert(VecTy && "Can only insert a vector into a vector");
1843
1844   VectorType *Ty = dyn_cast<VectorType>(V->getType());
1845   if (!Ty) {
1846     // Single element to insert.
1847     V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1848                                 Name + ".insert");
1849     DEBUG(dbgs() <<  "     insert: " << *V << "\n");
1850     return V;
1851   }
1852
1853   assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1854          "Too many elements!");
1855   if (Ty->getNumElements() == VecTy->getNumElements()) {
1856     assert(V->getType() == VecTy && "Vector type mismatch");
1857     return V;
1858   }
1859   unsigned EndIndex = BeginIndex + Ty->getNumElements();
1860
1861   // When inserting a smaller vector into the larger to store, we first
1862   // use a shuffle vector to widen it with undef elements, and then
1863   // a second shuffle vector to select between the loaded vector and the
1864   // incoming vector.
1865   SmallVector<Constant*, 8> Mask;
1866   Mask.reserve(VecTy->getNumElements());
1867   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1868     if (i >= BeginIndex && i < EndIndex)
1869       Mask.push_back(IRB.getInt32(i - BeginIndex));
1870     else
1871       Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1872   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1873                               ConstantVector::get(Mask),
1874                               Name + ".expand");
1875   DEBUG(dbgs() << "    shuffle: " << *V << "\n");
1876
1877   Mask.clear();
1878   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1879     Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1880
1881   V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1882
1883   DEBUG(dbgs() << "    blend: " << *V << "\n");
1884   return V;
1885 }
1886
1887 namespace {
1888 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
1889 /// to use a new alloca.
1890 ///
1891 /// Also implements the rewriting to vector-based accesses when the partition
1892 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1893 /// lives here.
1894 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
1895   // Befriend the base class so it can delegate to private visit methods.
1896   friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1897   typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
1898
1899   const DataLayout &DL;
1900   AllocaSlices &S;
1901   SROA &Pass;
1902   AllocaInst &OldAI, &NewAI;
1903   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1904   Type *NewAllocaTy;
1905
1906   // If we are rewriting an alloca partition which can be written as pure
1907   // vector operations, we stash extra information here. When VecTy is
1908   // non-null, we have some strict guarantees about the rewritten alloca:
1909   //   - The new alloca is exactly the size of the vector type here.
1910   //   - The accesses all either map to the entire vector or to a single
1911   //     element.
1912   //   - The set of accessing instructions is only one of those handled above
1913   //     in isVectorPromotionViable. Generally these are the same access kinds
1914   //     which are promotable via mem2reg.
1915   VectorType *VecTy;
1916   Type *ElementTy;
1917   uint64_t ElementSize;
1918
1919   // This is a convenience and flag variable that will be null unless the new
1920   // alloca's integer operations should be widened to this integer type due to
1921   // passing isIntegerWideningViable above. If it is non-null, the desired
1922   // integer type will be stored here for easy access during rewriting.
1923   IntegerType *IntTy;
1924
1925   // The offset of the slice currently being rewritten.
1926   uint64_t BeginOffset, EndOffset;
1927   bool IsSplittable;
1928   bool IsSplit;
1929   Use *OldUse;
1930   Instruction *OldPtr;
1931
1932   // Output members carrying state about the result of visiting and rewriting
1933   // the slice of the alloca.
1934   bool IsUsedByRewrittenSpeculatableInstructions;
1935
1936   // Utility IR builder, whose name prefix is setup for each visited use, and
1937   // the insertion point is set to point to the user.
1938   IRBuilderTy IRB;
1939
1940 public:
1941   AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
1942                       AllocaInst &OldAI, AllocaInst &NewAI,
1943                       uint64_t NewBeginOffset, uint64_t NewEndOffset,
1944                       bool IsVectorPromotable = false,
1945                       bool IsIntegerPromotable = false)
1946       : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
1947         NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1948         NewAllocaTy(NewAI.getAllocatedType()),
1949         VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1950         ElementTy(VecTy ? VecTy->getElementType() : 0),
1951         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
1952         IntTy(IsIntegerPromotable
1953                   ? Type::getIntNTy(
1954                         NewAI.getContext(),
1955                         DL.getTypeSizeInBits(NewAI.getAllocatedType()))
1956                   : 0),
1957         BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
1958         OldPtr(), IsUsedByRewrittenSpeculatableInstructions(false),
1959         IRB(NewAI.getContext(), ConstantFolder()) {
1960     if (VecTy) {
1961       assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
1962              "Only multiple-of-8 sized vector elements are viable");
1963       ++NumVectorized;
1964     }
1965     assert((!IsVectorPromotable && !IsIntegerPromotable) ||
1966            IsVectorPromotable != IsIntegerPromotable);
1967   }
1968
1969   bool visit(AllocaSlices::const_iterator I) {
1970     bool CanSROA = true;
1971     BeginOffset = I->beginOffset();
1972     EndOffset = I->endOffset();
1973     IsSplittable = I->isSplittable();
1974     IsSplit =
1975         BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
1976
1977     OldUse = I->getUse();
1978     OldPtr = cast<Instruction>(OldUse->get());
1979
1980     Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
1981     IRB.SetInsertPoint(OldUserI);
1982     IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
1983     IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
1984
1985     CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
1986     if (VecTy || IntTy)
1987       assert(CanSROA);
1988     return CanSROA;
1989   }
1990
1991   /// \brief Query whether this slice is used by speculatable instructions after
1992   /// rewriting.
1993   ///
1994   /// These instructions (PHIs and Selects currently) require the alloca slice
1995   /// to run back through the rewriter. Thus, they are promotable, but not on
1996   /// this iteration. This is distinct from a slice which is unpromotable for
1997   /// some other reason, in which case we don't even want to perform the
1998   /// speculation. This can be querried at any time and reflects whether (at
1999   /// that point) a visit call has rewritten a speculatable instruction on the
2000   /// current slice.
2001   bool isUsedByRewrittenSpeculatableInstructions() const {
2002     return IsUsedByRewrittenSpeculatableInstructions;
2003   }
2004
2005 private:
2006   // Make sure the other visit overloads are visible.
2007   using Base::visit;
2008
2009   // Every instruction which can end up as a user must have a rewrite rule.
2010   bool visitInstruction(Instruction &I) {
2011     DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
2012     llvm_unreachable("No rewrite rule for this instruction!");
2013   }
2014
2015   Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
2016                               Type *PointerTy) {
2017     assert(Offset >= NewAllocaBeginOffset);
2018     return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
2019                                                  Offset - NewAllocaBeginOffset),
2020                           PointerTy);
2021   }
2022
2023   /// \brief Compute suitable alignment to access an offset into the new alloca.
2024   unsigned getOffsetAlign(uint64_t Offset) {
2025     unsigned NewAIAlign = NewAI.getAlignment();
2026     if (!NewAIAlign)
2027       NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2028     return MinAlign(NewAIAlign, Offset);
2029   }
2030
2031   /// \brief Compute suitable alignment to access a type at an offset of the
2032   /// new alloca.
2033   ///
2034   /// \returns zero if the type's ABI alignment is a suitable alignment,
2035   /// otherwise returns the maximal suitable alignment.
2036   unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2037     unsigned Align = getOffsetAlign(Offset);
2038     return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
2039   }
2040
2041   unsigned getIndex(uint64_t Offset) {
2042     assert(VecTy && "Can only call getIndex when rewriting a vector");
2043     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2044     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2045     uint32_t Index = RelOffset / ElementSize;
2046     assert(Index * ElementSize == RelOffset);
2047     return Index;
2048   }
2049
2050   void deleteIfTriviallyDead(Value *V) {
2051     Instruction *I = cast<Instruction>(V);
2052     if (isInstructionTriviallyDead(I))
2053       Pass.DeadInsts.insert(I);
2054   }
2055
2056   Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
2057                                    uint64_t NewEndOffset) {
2058     unsigned BeginIndex = getIndex(NewBeginOffset);
2059     unsigned EndIndex = getIndex(NewEndOffset);
2060     assert(EndIndex > BeginIndex && "Empty vector!");
2061
2062     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2063                                      "load");
2064     return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2065   }
2066
2067   Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2068                             uint64_t NewEndOffset) {
2069     assert(IntTy && "We cannot insert an integer to the alloca");
2070     assert(!LI.isVolatile());
2071     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2072                                      "load");
2073     V = convertValue(DL, IRB, V, IntTy);
2074     assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2075     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2076     if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
2077       V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2078                          "extract");
2079     return V;
2080   }
2081
2082   bool visitLoadInst(LoadInst &LI) {
2083     DEBUG(dbgs() << "    original: " << LI << "\n");
2084     Value *OldOp = LI.getOperand(0);
2085     assert(OldOp == OldPtr);
2086
2087     // Compute the intersecting offset range.
2088     assert(BeginOffset < NewAllocaEndOffset);
2089     assert(EndOffset > NewAllocaBeginOffset);
2090     uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2091     uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2092
2093     uint64_t Size = NewEndOffset - NewBeginOffset;
2094
2095     Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2096                              : LI.getType();
2097     bool IsPtrAdjusted = false;
2098     Value *V;
2099     if (VecTy) {
2100       V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
2101     } else if (IntTy && LI.getType()->isIntegerTy()) {
2102       V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2103     } else if (NewBeginOffset == NewAllocaBeginOffset &&
2104                canConvertValue(DL, NewAllocaTy, LI.getType())) {
2105       V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2106                                 LI.isVolatile(), "load");
2107     } else {
2108       Type *LTy = TargetTy->getPointerTo();
2109       V = IRB.CreateAlignedLoad(
2110           getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2111           getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2112           LI.isVolatile(), "load");
2113       IsPtrAdjusted = true;
2114     }
2115     V = convertValue(DL, IRB, V, TargetTy);
2116
2117     if (IsSplit) {
2118       assert(!LI.isVolatile());
2119       assert(LI.getType()->isIntegerTy() &&
2120              "Only integer type loads and stores are split");
2121       assert(Size < DL.getTypeStoreSize(LI.getType()) &&
2122              "Split load isn't smaller than original load");
2123       assert(LI.getType()->getIntegerBitWidth() ==
2124              DL.getTypeStoreSizeInBits(LI.getType()) &&
2125              "Non-byte-multiple bit width");
2126       // Move the insertion point just past the load so that we can refer to it.
2127       IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
2128       // Create a placeholder value with the same type as LI to use as the
2129       // basis for the new value. This allows us to replace the uses of LI with
2130       // the computed value, and then replace the placeholder with LI, leaving
2131       // LI only used for this computation.
2132       Value *Placeholder
2133         = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2134       V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
2135                         "insert");
2136       LI.replaceAllUsesWith(V);
2137       Placeholder->replaceAllUsesWith(&LI);
2138       delete Placeholder;
2139     } else {
2140       LI.replaceAllUsesWith(V);
2141     }
2142
2143     Pass.DeadInsts.insert(&LI);
2144     deleteIfTriviallyDead(OldOp);
2145     DEBUG(dbgs() << "          to: " << *V << "\n");
2146     return !LI.isVolatile() && !IsPtrAdjusted;
2147   }
2148
2149   bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2150                                   uint64_t NewBeginOffset,
2151                                   uint64_t NewEndOffset) {
2152     if (V->getType() != VecTy) {
2153       unsigned BeginIndex = getIndex(NewBeginOffset);
2154       unsigned EndIndex = getIndex(NewEndOffset);
2155       assert(EndIndex > BeginIndex && "Empty vector!");
2156       unsigned NumElements = EndIndex - BeginIndex;
2157       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2158       Type *SliceTy =
2159           (NumElements == 1) ? ElementTy
2160                              : VectorType::get(ElementTy, NumElements);
2161       if (V->getType() != SliceTy)
2162         V = convertValue(DL, IRB, V, SliceTy);
2163
2164       // Mix in the existing elements.
2165       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2166                                          "load");
2167       V = insertVector(IRB, Old, V, BeginIndex, "vec");
2168     }
2169     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2170     Pass.DeadInsts.insert(&SI);
2171
2172     (void)Store;
2173     DEBUG(dbgs() << "          to: " << *Store << "\n");
2174     return true;
2175   }
2176
2177   bool rewriteIntegerStore(Value *V, StoreInst &SI,
2178                            uint64_t NewBeginOffset, uint64_t NewEndOffset) {
2179     assert(IntTy && "We cannot extract an integer from the alloca");
2180     assert(!SI.isVolatile());
2181     if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2182       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2183                                          "oldload");
2184       Old = convertValue(DL, IRB, Old, IntTy);
2185       assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2186       uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2187       V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
2188                         "insert");
2189     }
2190     V = convertValue(DL, IRB, V, NewAllocaTy);
2191     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2192     Pass.DeadInsts.insert(&SI);
2193     (void)Store;
2194     DEBUG(dbgs() << "          to: " << *Store << "\n");
2195     return true;
2196   }
2197
2198   bool visitStoreInst(StoreInst &SI) {
2199     DEBUG(dbgs() << "    original: " << SI << "\n");
2200     Value *OldOp = SI.getOperand(1);
2201     assert(OldOp == OldPtr);
2202
2203     Value *V = SI.getValueOperand();
2204
2205     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2206     // alloca that should be re-examined after promoting this alloca.
2207     if (V->getType()->isPointerTy())
2208       if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2209         Pass.PostPromotionWorklist.insert(AI);
2210
2211     // Compute the intersecting offset range.
2212     assert(BeginOffset < NewAllocaEndOffset);
2213     assert(EndOffset > NewAllocaBeginOffset);
2214     uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2215     uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2216
2217     uint64_t Size = NewEndOffset - NewBeginOffset;
2218     if (Size < DL.getTypeStoreSize(V->getType())) {
2219       assert(!SI.isVolatile());
2220       assert(V->getType()->isIntegerTy() &&
2221              "Only integer type loads and stores are split");
2222       assert(V->getType()->getIntegerBitWidth() ==
2223              DL.getTypeStoreSizeInBits(V->getType()) &&
2224              "Non-byte-multiple bit width");
2225       IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2226       V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
2227                          "extract");
2228     }
2229
2230     if (VecTy)
2231       return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2232                                         NewEndOffset);
2233     if (IntTy && V->getType()->isIntegerTy())
2234       return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
2235
2236     StoreInst *NewSI;
2237     if (NewBeginOffset == NewAllocaBeginOffset &&
2238         NewEndOffset == NewAllocaEndOffset &&
2239         canConvertValue(DL, V->getType(), NewAllocaTy)) {
2240       V = convertValue(DL, IRB, V, NewAllocaTy);
2241       NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2242                                      SI.isVolatile());
2243     } else {
2244       Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2245                                            V->getType()->getPointerTo());
2246       NewSI = IRB.CreateAlignedStore(
2247           V, NewPtr, getOffsetTypeAlign(
2248                          V->getType(), NewBeginOffset - NewAllocaBeginOffset),
2249           SI.isVolatile());
2250     }
2251     (void)NewSI;
2252     Pass.DeadInsts.insert(&SI);
2253     deleteIfTriviallyDead(OldOp);
2254
2255     DEBUG(dbgs() << "          to: " << *NewSI << "\n");
2256     return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2257   }
2258
2259   /// \brief Compute an integer value from splatting an i8 across the given
2260   /// number of bytes.
2261   ///
2262   /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2263   /// call this routine.
2264   /// FIXME: Heed the advice above.
2265   ///
2266   /// \param V The i8 value to splat.
2267   /// \param Size The number of bytes in the output (assuming i8 is one byte)
2268   Value *getIntegerSplat(Value *V, unsigned Size) {
2269     assert(Size > 0 && "Expected a positive number of bytes.");
2270     IntegerType *VTy = cast<IntegerType>(V->getType());
2271     assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2272     if (Size == 1)
2273       return V;
2274
2275     Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2276     V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
2277                       ConstantExpr::getUDiv(
2278                         Constant::getAllOnesValue(SplatIntTy),
2279                         ConstantExpr::getZExt(
2280                           Constant::getAllOnesValue(V->getType()),
2281                           SplatIntTy)),
2282                       "isplat");
2283     return V;
2284   }
2285
2286   /// \brief Compute a vector splat for a given element value.
2287   Value *getVectorSplat(Value *V, unsigned NumElements) {
2288     V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2289     DEBUG(dbgs() << "       splat: " << *V << "\n");
2290     return V;
2291   }
2292
2293   bool visitMemSetInst(MemSetInst &II) {
2294     DEBUG(dbgs() << "    original: " << II << "\n");
2295     assert(II.getRawDest() == OldPtr);
2296
2297     // If the memset has a variable size, it cannot be split, just adjust the
2298     // pointer to the new alloca.
2299     if (!isa<Constant>(II.getLength())) {
2300       assert(!IsSplit);
2301       assert(BeginOffset >= NewAllocaBeginOffset);
2302       II.setDest(
2303           getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
2304       Type *CstTy = II.getAlignmentCst()->getType();
2305       II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
2306
2307       deleteIfTriviallyDead(OldPtr);
2308       return false;
2309     }
2310
2311     // Record this instruction for deletion.
2312     Pass.DeadInsts.insert(&II);
2313
2314     Type *AllocaTy = NewAI.getAllocatedType();
2315     Type *ScalarTy = AllocaTy->getScalarType();
2316
2317     // Compute the intersecting offset range.
2318     assert(BeginOffset < NewAllocaEndOffset);
2319     assert(EndOffset > NewAllocaBeginOffset);
2320     uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2321     uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2322     uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
2323
2324     // If this doesn't map cleanly onto the alloca type, and that type isn't
2325     // a single value type, just emit a memset.
2326     if (!VecTy && !IntTy &&
2327         (BeginOffset > NewAllocaBeginOffset ||
2328          EndOffset < NewAllocaEndOffset ||
2329          !AllocaTy->isSingleValueType() ||
2330          !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2331          DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
2332       Type *SizeTy = II.getLength()->getType();
2333       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2334       CallInst *New = IRB.CreateMemSet(
2335           getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getRawDest()->getType()),
2336           II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
2337       (void)New;
2338       DEBUG(dbgs() << "          to: " << *New << "\n");
2339       return false;
2340     }
2341
2342     // If we can represent this as a simple value, we have to build the actual
2343     // value to store, which requires expanding the byte present in memset to
2344     // a sensible representation for the alloca type. This is essentially
2345     // splatting the byte to a sufficiently wide integer, splatting it across
2346     // any desired vector width, and bitcasting to the final type.
2347     Value *V;
2348
2349     if (VecTy) {
2350       // If this is a memset of a vectorized alloca, insert it.
2351       assert(ElementTy == ScalarTy);
2352
2353       unsigned BeginIndex = getIndex(NewBeginOffset);
2354       unsigned EndIndex = getIndex(NewEndOffset);
2355       assert(EndIndex > BeginIndex && "Empty vector!");
2356       unsigned NumElements = EndIndex - BeginIndex;
2357       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2358
2359       Value *Splat =
2360           getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2361       Splat = convertValue(DL, IRB, Splat, ElementTy);
2362       if (NumElements > 1)
2363         Splat = getVectorSplat(Splat, NumElements);
2364
2365       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2366                                          "oldload");
2367       V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2368     } else if (IntTy) {
2369       // If this is a memset on an alloca where we can widen stores, insert the
2370       // set integer.
2371       assert(!II.isVolatile());
2372
2373       uint64_t Size = NewEndOffset - NewBeginOffset;
2374       V = getIntegerSplat(II.getValue(), Size);
2375
2376       if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2377                     EndOffset != NewAllocaBeginOffset)) {
2378         Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2379                                            "oldload");
2380         Old = convertValue(DL, IRB, Old, IntTy);
2381         uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2382         V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2383       } else {
2384         assert(V->getType() == IntTy &&
2385                "Wrong type for an alloca wide integer!");
2386       }
2387       V = convertValue(DL, IRB, V, AllocaTy);
2388     } else {
2389       // Established these invariants above.
2390       assert(NewBeginOffset == NewAllocaBeginOffset);
2391       assert(NewEndOffset == NewAllocaEndOffset);
2392
2393       V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2394       if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2395         V = getVectorSplat(V, AllocaVecTy->getNumElements());
2396
2397       V = convertValue(DL, IRB, V, AllocaTy);
2398     }
2399
2400     Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2401                                         II.isVolatile());
2402     (void)New;
2403     DEBUG(dbgs() << "          to: " << *New << "\n");
2404     return !II.isVolatile();
2405   }
2406
2407   bool visitMemTransferInst(MemTransferInst &II) {
2408     // Rewriting of memory transfer instructions can be a bit tricky. We break
2409     // them into two categories: split intrinsics and unsplit intrinsics.
2410
2411     DEBUG(dbgs() << "    original: " << II << "\n");
2412
2413     // Compute the intersecting offset range.
2414     assert(BeginOffset < NewAllocaEndOffset);
2415     assert(EndOffset > NewAllocaBeginOffset);
2416     uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2417     uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2418
2419     assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2420     bool IsDest = II.getRawDest() == OldPtr;
2421
2422     // Compute the relative offset within the transfer.
2423     unsigned IntPtrWidth = DL.getPointerSizeInBits();
2424     APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2425
2426     unsigned Align = II.getAlignment();
2427     uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
2428     if (Align > 1)
2429       Align =
2430           MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2431                    MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
2432
2433     // For unsplit intrinsics, we simply modify the source and destination
2434     // pointers in place. This isn't just an optimization, it is a matter of
2435     // correctness. With unsplit intrinsics we may be dealing with transfers
2436     // within a single alloca before SROA ran, or with transfers that have
2437     // a variable length. We may also be dealing with memmove instead of
2438     // memcpy, and so simply updating the pointers is the necessary for us to
2439     // update both source and dest of a single call.
2440     if (!IsSplittable) {
2441       Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2442       if (IsDest)
2443         II.setDest(
2444             getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
2445       else
2446         II.setSource(getAdjustedAllocaPtr(IRB, BeginOffset,
2447                                           II.getRawSource()->getType()));
2448
2449       Type *CstTy = II.getAlignmentCst()->getType();
2450       II.setAlignment(ConstantInt::get(CstTy, Align));
2451
2452       DEBUG(dbgs() << "          to: " << II << "\n");
2453       deleteIfTriviallyDead(OldOp);
2454       return false;
2455     }
2456     // For split transfer intrinsics we have an incredibly useful assurance:
2457     // the source and destination do not reside within the same alloca, and at
2458     // least one of them does not escape. This means that we can replace
2459     // memmove with memcpy, and we don't need to worry about all manner of
2460     // downsides to splitting and transforming the operations.
2461
2462     // If this doesn't map cleanly onto the alloca type, and that type isn't
2463     // a single value type, just emit a memcpy.
2464     bool EmitMemCpy
2465       = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2466                              EndOffset < NewAllocaEndOffset ||
2467                              !NewAI.getAllocatedType()->isSingleValueType());
2468
2469     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2470     // size hasn't been shrunk based on analysis of the viable range, this is
2471     // a no-op.
2472     if (EmitMemCpy && &OldAI == &NewAI) {
2473       // Ensure the start lines up.
2474       assert(NewBeginOffset == BeginOffset);
2475
2476       // Rewrite the size as needed.
2477       if (NewEndOffset != EndOffset)
2478         II.setLength(ConstantInt::get(II.getLength()->getType(),
2479                                       NewEndOffset - NewBeginOffset));
2480       return false;
2481     }
2482     // Record this instruction for deletion.
2483     Pass.DeadInsts.insert(&II);
2484
2485     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2486     // alloca that should be re-examined after rewriting this instruction.
2487     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2488     if (AllocaInst *AI
2489           = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2490       Pass.Worklist.insert(AI);
2491
2492     if (EmitMemCpy) {
2493       Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2494                                 : II.getRawDest()->getType();
2495
2496       // Compute the other pointer, folding as much as possible to produce
2497       // a single, simple GEP in most cases.
2498       OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
2499
2500       Value *OurPtr = getAdjustedAllocaPtr(
2501           IRB, NewBeginOffset,
2502           IsDest ? II.getRawDest()->getType() : II.getRawSource()->getType());
2503       Type *SizeTy = II.getLength()->getType();
2504       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2505
2506       CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2507                                        IsDest ? OtherPtr : OurPtr,
2508                                        Size, Align, II.isVolatile());
2509       (void)New;
2510       DEBUG(dbgs() << "          to: " << *New << "\n");
2511       return false;
2512     }
2513
2514     // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2515     // is equivalent to 1, but that isn't true if we end up rewriting this as
2516     // a load or store.
2517     if (!Align)
2518       Align = 1;
2519
2520     bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2521                          NewEndOffset == NewAllocaEndOffset;
2522     uint64_t Size = NewEndOffset - NewBeginOffset;
2523     unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2524     unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2525     unsigned NumElements = EndIndex - BeginIndex;
2526     IntegerType *SubIntTy
2527       = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2528
2529     Type *OtherPtrTy = NewAI.getType();
2530     if (VecTy && !IsWholeAlloca) {
2531       if (NumElements == 1)
2532         OtherPtrTy = VecTy->getElementType();
2533       else
2534         OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2535
2536       OtherPtrTy = OtherPtrTy->getPointerTo();
2537     } else if (IntTy && !IsWholeAlloca) {
2538       OtherPtrTy = SubIntTy->getPointerTo();
2539     }
2540
2541     Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
2542     Value *DstPtr = &NewAI;
2543     if (!IsDest)
2544       std::swap(SrcPtr, DstPtr);
2545
2546     Value *Src;
2547     if (VecTy && !IsWholeAlloca && !IsDest) {
2548       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2549                                   "load");
2550       Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
2551     } else if (IntTy && !IsWholeAlloca && !IsDest) {
2552       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2553                                   "load");
2554       Src = convertValue(DL, IRB, Src, IntTy);
2555       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2556       Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
2557     } else {
2558       Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2559                                   "copyload");
2560     }
2561
2562     if (VecTy && !IsWholeAlloca && IsDest) {
2563       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2564                                          "oldload");
2565       Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
2566     } else if (IntTy && !IsWholeAlloca && IsDest) {
2567       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2568                                          "oldload");
2569       Old = convertValue(DL, IRB, Old, IntTy);
2570       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2571       Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2572       Src = convertValue(DL, IRB, Src, NewAllocaTy);
2573     }
2574
2575     StoreInst *Store = cast<StoreInst>(
2576       IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2577     (void)Store;
2578     DEBUG(dbgs() << "          to: " << *Store << "\n");
2579     return !II.isVolatile();
2580   }
2581
2582   bool visitIntrinsicInst(IntrinsicInst &II) {
2583     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2584            II.getIntrinsicID() == Intrinsic::lifetime_end);
2585     DEBUG(dbgs() << "    original: " << II << "\n");
2586     assert(II.getArgOperand(1) == OldPtr);
2587
2588     // Compute the intersecting offset range.
2589     assert(BeginOffset < NewAllocaEndOffset);
2590     assert(EndOffset > NewAllocaBeginOffset);
2591     uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2592     uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2593
2594     // Record this instruction for deletion.
2595     Pass.DeadInsts.insert(&II);
2596
2597     ConstantInt *Size
2598       = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2599                          NewEndOffset - NewBeginOffset);
2600     Value *Ptr =
2601         getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getArgOperand(1)->getType());
2602     Value *New;
2603     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2604       New = IRB.CreateLifetimeStart(Ptr, Size);
2605     else
2606       New = IRB.CreateLifetimeEnd(Ptr, Size);
2607
2608     (void)New;
2609     DEBUG(dbgs() << "          to: " << *New << "\n");
2610     return true;
2611   }
2612
2613   bool visitPHINode(PHINode &PN) {
2614     DEBUG(dbgs() << "    original: " << PN << "\n");
2615     assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2616     assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
2617
2618     // We would like to compute a new pointer in only one place, but have it be
2619     // as local as possible to the PHI. To do that, we re-use the location of
2620     // the old pointer, which necessarily must be in the right position to
2621     // dominate the PHI.
2622     IRBuilderTy PtrBuilder(OldPtr);
2623     PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2624                              ".");
2625
2626     Value *NewPtr =
2627         getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
2628     // Replace the operands which were using the old pointer.
2629     std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
2630
2631     DEBUG(dbgs() << "          to: " << PN << "\n");
2632     deleteIfTriviallyDead(OldPtr);
2633
2634     // Check whether we can speculate this PHI node, and if so remember that
2635     // fact and queue it up for another iteration after the speculation
2636     // occurs.
2637     if (isSafePHIToSpeculate(PN, &DL)) {
2638       Pass.SpeculatablePHIs.insert(&PN);
2639       IsUsedByRewrittenSpeculatableInstructions = true;
2640       return true;
2641     }
2642
2643     return false; // PHIs can't be promoted on their own.
2644   }
2645
2646   bool visitSelectInst(SelectInst &SI) {
2647     DEBUG(dbgs() << "    original: " << SI << "\n");
2648     assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2649            "Pointer isn't an operand!");
2650     assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2651     assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
2652
2653     Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
2654     // Replace the operands which were using the old pointer.
2655     if (SI.getOperand(1) == OldPtr)
2656       SI.setOperand(1, NewPtr);
2657     if (SI.getOperand(2) == OldPtr)
2658       SI.setOperand(2, NewPtr);
2659
2660     DEBUG(dbgs() << "          to: " << SI << "\n");
2661     deleteIfTriviallyDead(OldPtr);
2662
2663     // Check whether we can speculate this select instruction, and if so
2664     // remember that fact and queue it up for another iteration after the
2665     // speculation occurs.
2666     if (isSafeSelectToSpeculate(SI, &DL)) {
2667       Pass.SpeculatableSelects.insert(&SI);
2668       IsUsedByRewrittenSpeculatableInstructions = true;
2669       return true;
2670     }
2671
2672     return false; // Selects can't be promoted on their own.
2673   }
2674
2675 };
2676 }
2677
2678 namespace {
2679 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2680 ///
2681 /// This pass aggressively rewrites all aggregate loads and stores on
2682 /// a particular pointer (or any pointer derived from it which we can identify)
2683 /// with scalar loads and stores.
2684 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2685   // Befriend the base class so it can delegate to private visit methods.
2686   friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2687
2688   const DataLayout &DL;
2689
2690   /// Queue of pointer uses to analyze and potentially rewrite.
2691   SmallVector<Use *, 8> Queue;
2692
2693   /// Set to prevent us from cycling with phi nodes and loops.
2694   SmallPtrSet<User *, 8> Visited;
2695
2696   /// The current pointer use being rewritten. This is used to dig up the used
2697   /// value (as opposed to the user).
2698   Use *U;
2699
2700 public:
2701   AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
2702
2703   /// Rewrite loads and stores through a pointer and all pointers derived from
2704   /// it.
2705   bool rewrite(Instruction &I) {
2706     DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
2707     enqueueUsers(I);
2708     bool Changed = false;
2709     while (!Queue.empty()) {
2710       U = Queue.pop_back_val();
2711       Changed |= visit(cast<Instruction>(U->getUser()));
2712     }
2713     return Changed;
2714   }
2715
2716 private:
2717   /// Enqueue all the users of the given instruction for further processing.
2718   /// This uses a set to de-duplicate users.
2719   void enqueueUsers(Instruction &I) {
2720     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2721          ++UI)
2722       if (Visited.insert(*UI))
2723         Queue.push_back(&UI.getUse());
2724   }
2725
2726   // Conservative default is to not rewrite anything.
2727   bool visitInstruction(Instruction &I) { return false; }
2728
2729   /// \brief Generic recursive split emission class.
2730   template <typename Derived>
2731   class OpSplitter {
2732   protected:
2733     /// The builder used to form new instructions.
2734     IRBuilderTy IRB;
2735     /// The indices which to be used with insert- or extractvalue to select the
2736     /// appropriate value within the aggregate.
2737     SmallVector<unsigned, 4> Indices;
2738     /// The indices to a GEP instruction which will move Ptr to the correct slot
2739     /// within the aggregate.
2740     SmallVector<Value *, 4> GEPIndices;
2741     /// The base pointer of the original op, used as a base for GEPing the
2742     /// split operations.
2743     Value *Ptr;
2744
2745     /// Initialize the splitter with an insertion point, Ptr and start with a
2746     /// single zero GEP index.
2747     OpSplitter(Instruction *InsertionPoint, Value *Ptr)
2748       : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
2749
2750   public:
2751     /// \brief Generic recursive split emission routine.
2752     ///
2753     /// This method recursively splits an aggregate op (load or store) into
2754     /// scalar or vector ops. It splits recursively until it hits a single value
2755     /// and emits that single value operation via the template argument.
2756     ///
2757     /// The logic of this routine relies on GEPs and insertvalue and
2758     /// extractvalue all operating with the same fundamental index list, merely
2759     /// formatted differently (GEPs need actual values).
2760     ///
2761     /// \param Ty  The type being split recursively into smaller ops.
2762     /// \param Agg The aggregate value being built up or stored, depending on
2763     /// whether this is splitting a load or a store respectively.
2764     void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2765       if (Ty->isSingleValueType())
2766         return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
2767
2768       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2769         unsigned OldSize = Indices.size();
2770         (void)OldSize;
2771         for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2772              ++Idx) {
2773           assert(Indices.size() == OldSize && "Did not return to the old size");
2774           Indices.push_back(Idx);
2775           GEPIndices.push_back(IRB.getInt32(Idx));
2776           emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2777           GEPIndices.pop_back();
2778           Indices.pop_back();
2779         }
2780         return;
2781       }
2782
2783       if (StructType *STy = dyn_cast<StructType>(Ty)) {
2784         unsigned OldSize = Indices.size();
2785         (void)OldSize;
2786         for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2787              ++Idx) {
2788           assert(Indices.size() == OldSize && "Did not return to the old size");
2789           Indices.push_back(Idx);
2790           GEPIndices.push_back(IRB.getInt32(Idx));
2791           emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2792           GEPIndices.pop_back();
2793           Indices.pop_back();
2794         }
2795         return;
2796       }
2797
2798       llvm_unreachable("Only arrays and structs are aggregate loadable types");
2799     }
2800   };
2801
2802   struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
2803     LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2804       : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
2805
2806     /// Emit a leaf load of a single value. This is called at the leaves of the
2807     /// recursive emission to actually load values.
2808     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2809       assert(Ty->isSingleValueType());
2810       // Load the single value and insert it using the indices.
2811       Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2812       Value *Load = IRB.CreateLoad(GEP, Name + ".load");
2813       Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2814       DEBUG(dbgs() << "          to: " << *Load << "\n");
2815     }
2816   };
2817
2818   bool visitLoadInst(LoadInst &LI) {
2819     assert(LI.getPointerOperand() == *U);
2820     if (!LI.isSimple() || LI.getType()->isSingleValueType())
2821       return false;
2822
2823     // We have an aggregate being loaded, split it apart.
2824     DEBUG(dbgs() << "    original: " << LI << "\n");
2825     LoadOpSplitter Splitter(&LI, *U);
2826     Value *V = UndefValue::get(LI.getType());
2827     Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
2828     LI.replaceAllUsesWith(V);
2829     LI.eraseFromParent();
2830     return true;
2831   }
2832
2833   struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
2834     StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2835       : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
2836
2837     /// Emit a leaf store of a single value. This is called at the leaves of the
2838     /// recursive emission to actually produce stores.
2839     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2840       assert(Ty->isSingleValueType());
2841       // Extract the single value and store it using the indices.
2842       Value *Store = IRB.CreateStore(
2843         IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2844         IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2845       (void)Store;
2846       DEBUG(dbgs() << "          to: " << *Store << "\n");
2847     }
2848   };
2849
2850   bool visitStoreInst(StoreInst &SI) {
2851     if (!SI.isSimple() || SI.getPointerOperand() != *U)
2852       return false;
2853     Value *V = SI.getValueOperand();
2854     if (V->getType()->isSingleValueType())
2855       return false;
2856
2857     // We have an aggregate being stored, split it apart.
2858     DEBUG(dbgs() << "    original: " << SI << "\n");
2859     StoreOpSplitter Splitter(&SI, *U);
2860     Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
2861     SI.eraseFromParent();
2862     return true;
2863   }
2864
2865   bool visitBitCastInst(BitCastInst &BC) {
2866     enqueueUsers(BC);
2867     return false;
2868   }
2869
2870   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2871     enqueueUsers(GEPI);
2872     return false;
2873   }
2874
2875   bool visitPHINode(PHINode &PN) {
2876     enqueueUsers(PN);
2877     return false;
2878   }
2879
2880   bool visitSelectInst(SelectInst &SI) {
2881     enqueueUsers(SI);
2882     return false;
2883   }
2884 };
2885 }
2886
2887 /// \brief Strip aggregate type wrapping.
2888 ///
2889 /// This removes no-op aggregate types wrapping an underlying type. It will
2890 /// strip as many layers of types as it can without changing either the type
2891 /// size or the allocated size.
2892 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2893   if (Ty->isSingleValueType())
2894     return Ty;
2895
2896   uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2897   uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2898
2899   Type *InnerTy;
2900   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2901     InnerTy = ArrTy->getElementType();
2902   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2903     const StructLayout *SL = DL.getStructLayout(STy);
2904     unsigned Index = SL->getElementContainingOffset(0);
2905     InnerTy = STy->getElementType(Index);
2906   } else {
2907     return Ty;
2908   }
2909
2910   if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2911       TypeSize > DL.getTypeSizeInBits(InnerTy))
2912     return Ty;
2913
2914   return stripAggregateTypeWrapping(DL, InnerTy);
2915 }
2916
2917 /// \brief Try to find a partition of the aggregate type passed in for a given
2918 /// offset and size.
2919 ///
2920 /// This recurses through the aggregate type and tries to compute a subtype
2921 /// based on the offset and size. When the offset and size span a sub-section
2922 /// of an array, it will even compute a new array type for that sub-section,
2923 /// and the same for structs.
2924 ///
2925 /// Note that this routine is very strict and tries to find a partition of the
2926 /// type which produces the *exact* right offset and size. It is not forgiving
2927 /// when the size or offset cause either end of type-based partition to be off.
2928 /// Also, this is a best-effort routine. It is reasonable to give up and not
2929 /// return a type if necessary.
2930 static Type *getTypePartition(const DataLayout &DL, Type *Ty,
2931                               uint64_t Offset, uint64_t Size) {
2932   if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2933     return stripAggregateTypeWrapping(DL, Ty);
2934   if (Offset > DL.getTypeAllocSize(Ty) ||
2935       (DL.getTypeAllocSize(Ty) - Offset) < Size)
2936     return 0;
2937
2938   if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2939     // We can't partition pointers...
2940     if (SeqTy->isPointerTy())
2941       return 0;
2942
2943     Type *ElementTy = SeqTy->getElementType();
2944     uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
2945     uint64_t NumSkippedElements = Offset / ElementSize;
2946     if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
2947       if (NumSkippedElements >= ArrTy->getNumElements())
2948         return 0;
2949     } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
2950       if (NumSkippedElements >= VecTy->getNumElements())
2951         return 0;
2952     }
2953     Offset -= NumSkippedElements * ElementSize;
2954
2955     // First check if we need to recurse.
2956     if (Offset > 0 || Size < ElementSize) {
2957       // Bail if the partition ends in a different array element.
2958       if ((Offset + Size) > ElementSize)
2959         return 0;
2960       // Recurse through the element type trying to peel off offset bytes.
2961       return getTypePartition(DL, ElementTy, Offset, Size);
2962     }
2963     assert(Offset == 0);
2964
2965     if (Size == ElementSize)
2966       return stripAggregateTypeWrapping(DL, ElementTy);
2967     assert(Size > ElementSize);
2968     uint64_t NumElements = Size / ElementSize;
2969     if (NumElements * ElementSize != Size)
2970       return 0;
2971     return ArrayType::get(ElementTy, NumElements);
2972   }
2973
2974   StructType *STy = dyn_cast<StructType>(Ty);
2975   if (!STy)
2976     return 0;
2977
2978   const StructLayout *SL = DL.getStructLayout(STy);
2979   if (Offset >= SL->getSizeInBytes())
2980     return 0;
2981   uint64_t EndOffset = Offset + Size;
2982   if (EndOffset > SL->getSizeInBytes())
2983     return 0;
2984
2985   unsigned Index = SL->getElementContainingOffset(Offset);
2986   Offset -= SL->getElementOffset(Index);
2987
2988   Type *ElementTy = STy->getElementType(Index);
2989   uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
2990   if (Offset >= ElementSize)
2991     return 0; // The offset points into alignment padding.
2992
2993   // See if any partition must be contained by the element.
2994   if (Offset > 0 || Size < ElementSize) {
2995     if ((Offset + Size) > ElementSize)
2996       return 0;
2997     return getTypePartition(DL, ElementTy, Offset, Size);
2998   }
2999   assert(Offset == 0);
3000
3001   if (Size == ElementSize)
3002     return stripAggregateTypeWrapping(DL, ElementTy);
3003
3004   StructType::element_iterator EI = STy->element_begin() + Index,
3005                                EE = STy->element_end();
3006   if (EndOffset < SL->getSizeInBytes()) {
3007     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3008     if (Index == EndIndex)
3009       return 0; // Within a single element and its padding.
3010
3011     // Don't try to form "natural" types if the elements don't line up with the
3012     // expected size.
3013     // FIXME: We could potentially recurse down through the last element in the
3014     // sub-struct to find a natural end point.
3015     if (SL->getElementOffset(EndIndex) != EndOffset)
3016       return 0;
3017
3018     assert(Index < EndIndex);
3019     EE = STy->element_begin() + EndIndex;
3020   }
3021
3022   // Try to build up a sub-structure.
3023   StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
3024                                       STy->isPacked());
3025   const StructLayout *SubSL = DL.getStructLayout(SubTy);
3026   if (Size != SubSL->getSizeInBytes())
3027     return 0; // The sub-struct doesn't have quite the size needed.
3028
3029   return SubTy;
3030 }
3031
3032 /// \brief Rewrite an alloca partition's users.
3033 ///
3034 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3035 /// to rewrite uses of an alloca partition to be conducive for SSA value
3036 /// promotion. If the partition needs a new, more refined alloca, this will
3037 /// build that new alloca, preserving as much type information as possible, and
3038 /// rewrite the uses of the old alloca to point at the new one and have the
3039 /// appropriate new offsets. It also evaluates how successful the rewrite was
3040 /// at enabling promotion and if it was successful queues the alloca to be
3041 /// promoted.
3042 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3043                             AllocaSlices::iterator B, AllocaSlices::iterator E,
3044                             int64_t BeginOffset, int64_t EndOffset,
3045                             ArrayRef<AllocaSlices::iterator> SplitUses) {
3046   assert(BeginOffset < EndOffset);
3047   uint64_t SliceSize = EndOffset - BeginOffset;
3048
3049   // Try to compute a friendly type for this partition of the alloca. This
3050   // won't always succeed, in which case we fall back to a legal integer type
3051   // or an i8 array of an appropriate size.
3052   Type *SliceTy = 0;
3053   if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
3054     if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3055       SliceTy = CommonUseTy;
3056   if (!SliceTy)
3057     if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
3058                                                  BeginOffset, SliceSize))
3059       SliceTy = TypePartitionTy;
3060   if ((!SliceTy || (SliceTy->isArrayTy() &&
3061                     SliceTy->getArrayElementType()->isIntegerTy())) &&
3062       DL->isLegalInteger(SliceSize * 8))
3063     SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3064   if (!SliceTy)
3065     SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3066   assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
3067
3068   bool IsVectorPromotable = isVectorPromotionViable(
3069       *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
3070
3071   bool IsIntegerPromotable =
3072       !IsVectorPromotable &&
3073       isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
3074
3075   // Check for the case where we're going to rewrite to a new alloca of the
3076   // exact same type as the original, and with the same access offsets. In that
3077   // case, re-use the existing alloca, but still run through the rewriter to
3078   // perform phi and select speculation.
3079   AllocaInst *NewAI;
3080   if (SliceTy == AI.getAllocatedType()) {
3081     assert(BeginOffset == 0 &&
3082            "Non-zero begin offset but same alloca type");
3083     NewAI = &AI;
3084     // FIXME: We should be able to bail at this point with "nothing changed".
3085     // FIXME: We might want to defer PHI speculation until after here.
3086   } else {
3087     unsigned Alignment = AI.getAlignment();
3088     if (!Alignment) {
3089       // The minimum alignment which users can rely on when the explicit
3090       // alignment is omitted or zero is that required by the ABI for this
3091       // type.
3092       Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
3093     }
3094     Alignment = MinAlign(Alignment, BeginOffset);
3095     // If we will get at least this much alignment from the type alone, leave
3096     // the alloca's alignment unconstrained.
3097     if (Alignment <= DL->getABITypeAlignment(SliceTy))
3098       Alignment = 0;
3099     NewAI = new AllocaInst(SliceTy, 0, Alignment,
3100                            AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
3101     ++NumNewAllocas;
3102   }
3103
3104   DEBUG(dbgs() << "Rewriting alloca partition "
3105                << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3106                << "\n");
3107
3108   // Track the high watermark on several worklists that are only relevant for
3109   // promoted allocas. We will reset it to this point if the alloca is not in
3110   // fact scheduled for promotion.
3111   unsigned PPWOldSize = PostPromotionWorklist.size();
3112   unsigned SPOldSize = SpeculatablePHIs.size();
3113   unsigned SSOldSize = SpeculatableSelects.size();
3114   unsigned NumUses = 0;
3115
3116   AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3117                                EndOffset, IsVectorPromotable,
3118                                IsIntegerPromotable);
3119   bool Promotable = true;
3120   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3121                                                         SUE = SplitUses.end();
3122        SUI != SUE; ++SUI) {
3123     DEBUG(dbgs() << "  rewriting split ");
3124     DEBUG(S.printSlice(dbgs(), *SUI, ""));
3125     Promotable &= Rewriter.visit(*SUI);
3126     ++NumUses;
3127   }
3128   for (AllocaSlices::iterator I = B; I != E; ++I) {
3129     DEBUG(dbgs() << "  rewriting ");
3130     DEBUG(S.printSlice(dbgs(), I, ""));
3131     Promotable &= Rewriter.visit(I);
3132     ++NumUses;
3133   }
3134
3135   NumAllocaPartitionUses += NumUses;
3136   MaxUsesPerAllocaPartition =
3137       std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
3138
3139   if (Promotable && !Rewriter.isUsedByRewrittenSpeculatableInstructions()) {
3140     DEBUG(dbgs() << "  and queuing for promotion\n");
3141     PromotableAllocas.push_back(NewAI);
3142   } else if (NewAI != &AI ||
3143              (Promotable &&
3144               Rewriter.isUsedByRewrittenSpeculatableInstructions())) {
3145     // If we can't promote the alloca, iterate on it to check for new
3146     // refinements exposed by splitting the current alloca. Don't iterate on an
3147     // alloca which didn't actually change and didn't get promoted.
3148     //
3149     // Alternatively, if we could promote the alloca but have speculatable
3150     // instructions then we will speculate them after finishing our processing
3151     // of the original alloca. Mark the new one for re-visiting in the next
3152     // iteration so the speculated operations can be rewritten.
3153     //
3154     // FIXME: We should actually track whether the rewriter changed anything.
3155     Worklist.insert(NewAI);
3156   }
3157
3158   // Drop any post-promotion work items if promotion didn't happen.
3159   if (!Promotable) {
3160     while (PostPromotionWorklist.size() > PPWOldSize)
3161       PostPromotionWorklist.pop_back();
3162     while (SpeculatablePHIs.size() > SPOldSize)
3163       SpeculatablePHIs.pop_back();
3164     while (SpeculatableSelects.size() > SSOldSize)
3165       SpeculatableSelects.pop_back();
3166   }
3167
3168   return true;
3169 }
3170
3171 namespace {
3172 struct IsSliceEndLessOrEqualTo {
3173   uint64_t UpperBound;
3174
3175   IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
3176
3177   bool operator()(const AllocaSlices::iterator &I) {
3178     return I->endOffset() <= UpperBound;
3179   }
3180 };
3181 }
3182
3183 static void
3184 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3185                         uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
3186   if (Offset >= MaxSplitUseEndOffset) {
3187     SplitUses.clear();
3188     MaxSplitUseEndOffset = 0;
3189     return;
3190   }
3191
3192   size_t SplitUsesOldSize = SplitUses.size();
3193   SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
3194                                  IsSliceEndLessOrEqualTo(Offset)),
3195                   SplitUses.end());
3196   if (SplitUsesOldSize == SplitUses.size())
3197     return;
3198
3199   // Recompute the max. While this is linear, so is remove_if.
3200   MaxSplitUseEndOffset = 0;
3201   for (SmallVectorImpl<AllocaSlices::iterator>::iterator
3202            SUI = SplitUses.begin(),
3203            SUE = SplitUses.end();
3204        SUI != SUE; ++SUI)
3205     MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3206 }
3207
3208 /// \brief Walks the slices of an alloca and form partitions based on them,
3209 /// rewriting each of their uses.
3210 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3211   if (S.begin() == S.end())
3212     return false;
3213
3214   unsigned NumPartitions = 0;
3215   bool Changed = false;
3216   SmallVector<AllocaSlices::iterator, 4> SplitUses;
3217   uint64_t MaxSplitUseEndOffset = 0;
3218
3219   uint64_t BeginOffset = S.begin()->beginOffset();
3220
3221   for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3222        SI != SE; SI = SJ) {
3223     uint64_t MaxEndOffset = SI->endOffset();
3224
3225     if (!SI->isSplittable()) {
3226       // When we're forming an unsplittable region, it must always start at the
3227       // first slice and will extend through its end.
3228       assert(BeginOffset == SI->beginOffset());
3229
3230       // Form a partition including all of the overlapping slices with this
3231       // unsplittable slice.
3232       while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3233         if (!SJ->isSplittable())
3234           MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3235         ++SJ;
3236       }
3237     } else {
3238       assert(SI->isSplittable()); // Established above.
3239
3240       // Collect all of the overlapping splittable slices.
3241       while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3242              SJ->isSplittable()) {
3243         MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3244         ++SJ;
3245       }
3246
3247       // Back up MaxEndOffset and SJ if we ended the span early when
3248       // encountering an unsplittable slice.
3249       if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3250         assert(!SJ->isSplittable());
3251         MaxEndOffset = SJ->beginOffset();
3252       }
3253     }
3254
3255     // Check if we have managed to move the end offset forward yet. If so,
3256     // we'll have to rewrite uses and erase old split uses.
3257     if (BeginOffset < MaxEndOffset) {
3258       // Rewrite a sequence of overlapping slices.
3259       Changed |=
3260           rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
3261       ++NumPartitions;
3262
3263       removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3264     }
3265
3266     // Accumulate all the splittable slices from the [SI,SJ) region which
3267     // overlap going forward.
3268     for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3269       if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3270         SplitUses.push_back(SK);
3271         MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
3272       }
3273
3274     // If we're already at the end and we have no split uses, we're done.
3275     if (SJ == SE && SplitUses.empty())
3276       break;
3277
3278     // If we have no split uses or no gap in offsets, we're ready to move to
3279     // the next slice.
3280     if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3281       BeginOffset = SJ->beginOffset();
3282       continue;
3283     }
3284
3285     // Even if we have split slices, if the next slice is splittable and the
3286     // split slices reach it, we can simply set up the beginning offset of the
3287     // next iteration to bridge between them.
3288     if (SJ != SE && SJ->isSplittable() &&
3289         MaxSplitUseEndOffset > SJ->beginOffset()) {
3290       BeginOffset = MaxEndOffset;
3291       continue;
3292     }
3293
3294     // Otherwise, we have a tail of split slices. Rewrite them with an empty
3295     // range of slices.
3296     uint64_t PostSplitEndOffset =
3297         SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
3298
3299     Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3300                                 SplitUses);
3301     ++NumPartitions;
3302
3303     if (SJ == SE)
3304       break; // Skip the rest, we don't need to do any cleanup.
3305
3306     removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3307                             PostSplitEndOffset);
3308
3309     // Now just reset the begin offset for the next iteration.
3310     BeginOffset = SJ->beginOffset();
3311   }
3312
3313   NumAllocaPartitions += NumPartitions;
3314   MaxPartitionsPerAlloca =
3315       std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
3316
3317   return Changed;
3318 }
3319
3320 /// \brief Analyze an alloca for SROA.
3321 ///
3322 /// This analyzes the alloca to ensure we can reason about it, builds
3323 /// the slices of the alloca, and then hands it off to be split and
3324 /// rewritten as needed.
3325 bool SROA::runOnAlloca(AllocaInst &AI) {
3326   DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3327   ++NumAllocasAnalyzed;
3328
3329   // Special case dead allocas, as they're trivial.
3330   if (AI.use_empty()) {
3331     AI.eraseFromParent();
3332     return true;
3333   }
3334
3335   // Skip alloca forms that this analysis can't handle.
3336   if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3337       DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
3338     return false;
3339
3340   bool Changed = false;
3341
3342   // First, split any FCA loads and stores touching this alloca to promote
3343   // better splitting and promotion opportunities.
3344   AggLoadStoreRewriter AggRewriter(*DL);
3345   Changed |= AggRewriter.rewrite(AI);
3346
3347   // Build the slices using a recursive instruction-visiting builder.
3348   AllocaSlices S(*DL, AI);
3349   DEBUG(S.print(dbgs()));
3350   if (S.isEscaped())
3351     return Changed;
3352
3353   // Delete all the dead users of this alloca before splitting and rewriting it.
3354   for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3355                                         DE = S.dead_user_end();
3356        DI != DE; ++DI) {
3357     Changed = true;
3358     (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3359     DeadInsts.insert(*DI);
3360   }
3361   for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3362                                       DE = S.dead_op_end();
3363        DO != DE; ++DO) {
3364     Value *OldV = **DO;
3365     // Clobber the use with an undef value.
3366     **DO = UndefValue::get(OldV->getType());
3367     if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3368       if (isInstructionTriviallyDead(OldI)) {
3369         Changed = true;
3370         DeadInsts.insert(OldI);
3371       }
3372   }
3373
3374   // No slices to split. Leave the dead alloca for a later pass to clean up.
3375   if (S.begin() == S.end())
3376     return Changed;
3377
3378   Changed |= splitAlloca(AI, S);
3379
3380   DEBUG(dbgs() << "  Speculating PHIs\n");
3381   while (!SpeculatablePHIs.empty())
3382     speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3383
3384   DEBUG(dbgs() << "  Speculating Selects\n");
3385   while (!SpeculatableSelects.empty())
3386     speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3387
3388   return Changed;
3389 }
3390
3391 /// \brief Delete the dead instructions accumulated in this run.
3392 ///
3393 /// Recursively deletes the dead instructions we've accumulated. This is done
3394 /// at the very end to maximize locality of the recursive delete and to
3395 /// minimize the problems of invalidated instruction pointers as such pointers
3396 /// are used heavily in the intermediate stages of the algorithm.
3397 ///
3398 /// We also record the alloca instructions deleted here so that they aren't
3399 /// subsequently handed to mem2reg to promote.
3400 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3401   while (!DeadInsts.empty()) {
3402     Instruction *I = DeadInsts.pop_back_val();
3403     DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3404
3405     I->replaceAllUsesWith(UndefValue::get(I->getType()));
3406
3407     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3408       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3409         // Zero out the operand and see if it becomes trivially dead.
3410         *OI = 0;
3411         if (isInstructionTriviallyDead(U))
3412           DeadInsts.insert(U);
3413       }
3414
3415     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3416       DeletedAllocas.insert(AI);
3417
3418     ++NumDeleted;
3419     I->eraseFromParent();
3420   }
3421 }
3422
3423 static void enqueueUsersInWorklist(Instruction &I,
3424                                    SmallVectorImpl<Instruction *> &Worklist,
3425                                    SmallPtrSet<Instruction *, 8> &Visited) {
3426   for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3427        ++UI)
3428     if (Visited.insert(cast<Instruction>(*UI)))
3429       Worklist.push_back(cast<Instruction>(*UI));
3430 }
3431
3432 /// \brief Promote the allocas, using the best available technique.
3433 ///
3434 /// This attempts to promote whatever allocas have been identified as viable in
3435 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3436 /// If there is a domtree available, we attempt to promote using the full power
3437 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3438 /// based on the SSAUpdater utilities. This function returns whether any
3439 /// promotion occurred.
3440 bool SROA::promoteAllocas(Function &F) {
3441   if (PromotableAllocas.empty())
3442     return false;
3443
3444   NumPromoted += PromotableAllocas.size();
3445
3446   if (DT && !ForceSSAUpdater) {
3447     DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3448     PromoteMemToReg(PromotableAllocas, *DT);
3449     PromotableAllocas.clear();
3450     return true;
3451   }
3452
3453   DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3454   SSAUpdater SSA;
3455   DIBuilder DIB(*F.getParent());
3456   SmallVector<Instruction *, 64> Insts;
3457
3458   // We need a worklist to walk the uses of each alloca.
3459   SmallVector<Instruction *, 8> Worklist;
3460   SmallPtrSet<Instruction *, 8> Visited;
3461   SmallVector<Instruction *, 32> DeadInsts;
3462
3463   for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3464     AllocaInst *AI = PromotableAllocas[Idx];
3465     Insts.clear();
3466     Worklist.clear();
3467     Visited.clear();
3468
3469     enqueueUsersInWorklist(*AI, Worklist, Visited);
3470
3471     while (!Worklist.empty()) {
3472       Instruction *I = Worklist.pop_back_val();
3473
3474       // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3475       // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3476       // leading to them) here. Eventually it should use them to optimize the
3477       // scalar values produced.
3478       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3479         assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3480                II->getIntrinsicID() == Intrinsic::lifetime_end);
3481         II->eraseFromParent();
3482         continue;
3483       }
3484
3485       // Push the loads and stores we find onto the list. SROA will already
3486       // have validated that all loads and stores are viable candidates for
3487       // promotion.
3488       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3489         assert(LI->getType() == AI->getAllocatedType());
3490         Insts.push_back(LI);
3491         continue;
3492       }
3493       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3494         assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3495         Insts.push_back(SI);
3496         continue;
3497       }
3498
3499       // For everything else, we know that only no-op bitcasts and GEPs will
3500       // make it this far, just recurse through them and recall them for later
3501       // removal.
3502       DeadInsts.push_back(I);
3503       enqueueUsersInWorklist(*I, Worklist, Visited);
3504     }
3505     AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3506     while (!DeadInsts.empty())
3507       DeadInsts.pop_back_val()->eraseFromParent();
3508     AI->eraseFromParent();
3509   }
3510
3511   PromotableAllocas.clear();
3512   return true;
3513 }
3514
3515 namespace {
3516   /// \brief A predicate to test whether an alloca belongs to a set.
3517   class IsAllocaInSet {
3518     typedef SmallPtrSet<AllocaInst *, 4> SetType;
3519     const SetType &Set;
3520
3521   public:
3522     typedef AllocaInst *argument_type;
3523
3524     IsAllocaInSet(const SetType &Set) : Set(Set) {}
3525     bool operator()(AllocaInst *AI) const { return Set.count(AI); }
3526   };
3527 }
3528
3529 bool SROA::runOnFunction(Function &F) {
3530   DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3531   C = &F.getContext();
3532   DL = getAnalysisIfAvailable<DataLayout>();
3533   if (!DL) {
3534     DEBUG(dbgs() << "  Skipping SROA -- no target data!\n");
3535     return false;
3536   }
3537   DT = getAnalysisIfAvailable<DominatorTree>();
3538
3539   BasicBlock &EntryBB = F.getEntryBlock();
3540   for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3541        I != E; ++I)
3542     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3543       Worklist.insert(AI);
3544
3545   bool Changed = false;
3546   // A set of deleted alloca instruction pointers which should be removed from
3547   // the list of promotable allocas.
3548   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3549
3550   do {
3551     while (!Worklist.empty()) {
3552       Changed |= runOnAlloca(*Worklist.pop_back_val());
3553       deleteDeadInstructions(DeletedAllocas);
3554
3555       // Remove the deleted allocas from various lists so that we don't try to
3556       // continue processing them.
3557       if (!DeletedAllocas.empty()) {
3558         Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3559         PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3560         PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3561                                                PromotableAllocas.end(),
3562                                                IsAllocaInSet(DeletedAllocas)),
3563                                 PromotableAllocas.end());
3564         DeletedAllocas.clear();
3565       }
3566     }
3567
3568     Changed |= promoteAllocas(F);
3569
3570     Worklist = PostPromotionWorklist;
3571     PostPromotionWorklist.clear();
3572   } while (!Worklist.empty());
3573
3574   return Changed;
3575 }
3576
3577 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3578   if (RequiresDomTree)
3579     AU.addRequired<DominatorTree>();
3580   AU.setPreservesCFG();
3581 }