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