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