1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
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.
24 //===----------------------------------------------------------------------===//
26 #define DEBUG_TYPE "sroa"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DIBuilder.h"
30 #include "llvm/DebugInfo.h"
31 #include "llvm/DerivedTypes.h"
32 #include "llvm/Function.h"
33 #include "llvm/IRBuilder.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/IntrinsicInst.h"
36 #include "llvm/LLVMContext.h"
37 #include "llvm/Module.h"
38 #include "llvm/Operator.h"
39 #include "llvm/Pass.h"
40 #include "llvm/ADT/SetVector.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/Analysis/Dominators.h"
45 #include "llvm/Analysis/Loads.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/DataLayout.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
57 #include "llvm/Transforms/Utils/SSAUpdater.h"
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");
67 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
68 /// forming SSA values through the SSAUpdater infrastructure.
70 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
73 /// \brief Alloca partitioning representation.
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 {
83 /// \brief A common base class for representing a half-open byte range.
85 /// \brief The beginning offset of the range.
88 /// \brief The ending offset, not included in the range.
91 ByteRange() : BeginOffset(), EndOffset() {}
92 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
93 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
95 /// \brief Support for ordering ranges.
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;
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;
113 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
114 const ByteRange &RHS) {
115 return LHSOffset < RHS.BeginOffset;
118 bool operator==(const ByteRange &RHS) const {
119 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
121 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
124 /// \brief A partition of an alloca.
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.
133 /// We flag partitions as splittable when they are formed entirely due to
134 /// accesses by trivially splittable operations such as memset and memcpy.
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);
146 /// \brief Kill a partition.
147 /// This is accomplished by setting both its beginning and end offset to
148 /// the maximum possible value.
150 assert(!isDead() && "He's Dead, Jim!");
151 BeginOffset = EndOffset = UINT64_MAX;
154 Partition() : ByteRange(), IsSplittable() {}
155 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
156 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
159 /// \brief A particular use of a partition of the alloca.
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.
170 /// Note that this may be null if the partition use is *dead*, that is, it
171 /// should be ignored.
174 PartitionUse() : ByteRange(), U() {}
175 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
176 : ByteRange(BeginOffset, EndOffset), U(U) {}
179 /// \brief Construct a partitioning of a particular alloca.
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);
185 /// \brief Test whether a pointer to the allocation escapes our analysis.
187 /// If this is true, the partitioning is never fully built and should be
189 bool isEscaped() const { return PointerEscapingInstr; }
191 /// \brief Support for iterating over the partitions.
193 typedef SmallVectorImpl<Partition>::iterator iterator;
194 iterator begin() { return Partitions.begin(); }
195 iterator end() { return Partitions.end(); }
197 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
198 const_iterator begin() const { return Partitions.begin(); }
199 const_iterator end() const { return Partitions.end(); }
202 /// \brief Support for iterating over and manipulating a particular
203 /// partition's uses.
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.
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(); }
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();
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();
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];
230 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
231 return Uses[I - begin()][UIdx];
234 void use_push_back(unsigned Idx, const PartitionUse &PU) {
235 Uses[Idx].push_back(PU);
237 void use_push_back(const_iterator I, const PartitionUse &PU) {
238 Uses[I - begin()].push_back(PU);
242 /// \brief Allow iterating the dead users for this alloca.
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
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(); }
253 /// \brief Allow iterating the dead expressions referring to this alloca.
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.
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(); }
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
275 uint64_t DestBegin, DestEnd;
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;
281 /// Flag for whether an alloca is splittable.
284 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
285 return MemTransferInstData.lookup(&II);
288 /// \brief Map from a PHI or select operand back to a partition.
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())
299 return begin() + MapIt->second.first;
302 /// \brief Map from a PHI or select operand back to the specific use of
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;
314 /// \brief Compute a common type among the uses of a particular partition.
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;
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;
331 template <typename DerivedT, typename RetT = void> class BuilderBase;
332 class PartitionBuilder;
333 friend class AllocaPartitioning::PartitionBuilder;
335 friend class AllocaPartitioning::UseBuilder;
338 /// \brief Handle to alloca instruction to simplify method interfaces.
342 /// \brief The instruction responsible for this alloca having no partitioning.
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;
349 /// \brief The partitions of the alloca.
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;
359 /// \brief The uses of the partitions.
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;
367 /// \brief Instructions which will become dead if we rewrite the alloca.
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;
375 /// \brief Operands which will become dead if we rewrite the alloca.
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
383 SmallVector<Use *, 8> DeadOperands;
385 /// \brief The underlying storage for auxiliary memcpy and memset info.
386 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
388 /// \brief A side datastructure used when building up the partitions and uses.
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
393 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
395 /// \brief Auxiliary information for particular PHI or select operands.
396 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
398 /// \brief A utility routine called from the constructor.
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();
407 template <typename DerivedT, typename RetT>
408 class AllocaPartitioning::BuilderBase
409 : public InstVisitor<DerivedT, RetT> {
411 BuilderBase(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
413 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
419 const DataLayout &TD;
420 const uint64_t AllocSize;
421 AllocaPartitioning &P;
423 SmallPtrSet<Use *, 8> VisitedUses;
429 SmallVector<OffsetUse, 8> Queue;
431 // The active offset and use while visiting.
435 void enqueueUsers(Instruction &I, int64_t UserOffset) {
436 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
438 if (VisitedUses.insert(&UI.getUse())) {
439 OffsetUse OU = { &UI.getUse(), UserOffset };
445 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
447 unsigned int AS = GEPI.getPointerAddressSpace();
448 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
450 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
456 // Handle a struct index, which adds its field offset to the pointer.
457 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
458 unsigned ElementIdx = OpC->getZExtValue();
459 const StructLayout *SL = TD.getStructLayout(STy);
460 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
461 // Check that we can continue to model this GEP in a signed 64-bit offset.
462 if (ElementOffset > INT64_MAX ||
464 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
465 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
466 << "what can be represented in an int64_t!\n"
467 << " alloca: " << P.AI << "\n");
471 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
473 GEPOffset += ElementOffset;
477 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits(AS));
478 Index *= APInt(Index.getBitWidth(),
479 TD.getTypeAllocSize(GTI.getIndexedType()));
480 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
482 // Check if the result can be stored in our int64_t offset.
483 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
484 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
485 << "what can be represented in an int64_t!\n"
486 << " alloca: " << P.AI << "\n");
490 GEPOffset = Index.getSExtValue();
495 Value *foldSelectInst(SelectInst &SI) {
496 // If the condition being selected on is a constant or the same value is
497 // being selected between, fold the select. Yes this does (rarely) happen
499 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
500 return SI.getOperand(1+CI->isZero());
501 if (SI.getOperand(1) == SI.getOperand(2)) {
502 assert(*U == SI.getOperand(1));
503 return SI.getOperand(1);
509 /// \brief Builder for the alloca partitioning.
511 /// This class builds an alloca partitioning by recursively visiting the uses
512 /// of an alloca and splitting the partitions for each load and store at each
514 class AllocaPartitioning::PartitionBuilder
515 : public BuilderBase<PartitionBuilder, bool> {
516 friend class InstVisitor<PartitionBuilder, bool>;
518 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
521 PartitionBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
522 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
524 /// \brief Run the builder over the allocation.
526 // Note that we have to re-evaluate size on each trip through the loop as
527 // the queue grows at the tail.
528 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
530 Offset = Queue[Idx].Offset;
531 if (!visit(cast<Instruction>(U->getUser())))
538 bool markAsEscaping(Instruction &I) {
539 P.PointerEscapingInstr = &I;
543 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
544 bool IsSplittable = false) {
545 // Completely skip uses which have a zero size or don't overlap the
548 (Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
549 (Offset < 0 && (uint64_t)-Offset >= Size)) {
550 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
551 << " which starts past the end of the " << AllocSize
553 << " alloca: " << P.AI << "\n"
554 << " use: " << I << "\n");
558 // Clamp the start to the beginning of the allocation.
560 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
561 << " to start at the beginning of the alloca:\n"
562 << " alloca: " << P.AI << "\n"
563 << " use: " << I << "\n");
564 Size -= (uint64_t)-Offset;
568 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
570 // Clamp the end offset to the end of the allocation. Note that this is
571 // formulated to handle even the case where "BeginOffset + Size" overflows.
572 assert(AllocSize >= BeginOffset); // Established above.
573 if (Size > AllocSize - BeginOffset) {
574 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
575 << " to remain within the " << AllocSize << " byte alloca:\n"
576 << " alloca: " << P.AI << "\n"
577 << " use: " << I << "\n");
578 EndOffset = AllocSize;
581 Partition New(BeginOffset, EndOffset, IsSplittable);
582 P.Partitions.push_back(New);
585 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset,
587 uint64_t Size = TD.getTypeStoreSize(Ty);
589 // If this memory access can be shown to *statically* extend outside the
590 // bounds of of the allocation, it's behavior is undefined, so simply
591 // ignore it. Note that this is more strict than the generic clamping
592 // behavior of insertUse. We also try to handle cases which might run the
594 // FIXME: We should instead consider the pointer to have escaped if this
595 // function is being instrumented for addressing bugs or race conditions.
596 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
597 Size > (AllocSize - (uint64_t)Offset)) {
598 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
599 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
600 << " which extends past the end of the " << AllocSize
602 << " alloca: " << P.AI << "\n"
603 << " use: " << I << "\n");
607 // We allow splitting of loads and stores where the type is an integer type
608 // and which cover the entire alloca. Such integer loads and stores
609 // often require decomposition into fine grained loads and stores.
610 bool IsSplittable = false;
611 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
612 IsSplittable = !IsVolatile && ITy->getBitWidth() == AllocSize*8;
614 insertUse(I, Offset, Size, IsSplittable);
618 bool visitBitCastInst(BitCastInst &BC) {
619 enqueueUsers(BC, Offset);
623 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
625 if (!computeConstantGEPOffset(GEPI, GEPOffset))
626 return markAsEscaping(GEPI);
628 enqueueUsers(GEPI, GEPOffset);
632 bool visitLoadInst(LoadInst &LI) {
633 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
634 "All simple FCA loads should have been pre-split");
635 return handleLoadOrStore(LI.getType(), LI, Offset, LI.isVolatile());
638 bool visitStoreInst(StoreInst &SI) {
639 Value *ValOp = SI.getValueOperand();
641 return markAsEscaping(SI);
643 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
644 "All simple FCA stores should have been pre-split");
645 return handleLoadOrStore(ValOp->getType(), SI, Offset, SI.isVolatile());
649 bool visitMemSetInst(MemSetInst &II) {
650 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
651 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
652 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
653 insertUse(II, Offset, Size, Length);
657 bool visitMemTransferInst(MemTransferInst &II) {
658 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
659 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
661 // Zero-length mem transfer intrinsics can be ignored entirely.
664 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
666 // Only intrinsics with a constant length can be split.
667 Offsets.IsSplittable = Length;
669 if (*U == II.getRawDest()) {
670 Offsets.DestBegin = Offset;
671 Offsets.DestEnd = Offset + Size;
673 if (*U == II.getRawSource()) {
674 Offsets.SourceBegin = Offset;
675 Offsets.SourceEnd = Offset + Size;
678 // If we have set up end offsets for both the source and the destination,
679 // we have found both sides of this transfer pointing at the same alloca.
680 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
681 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
682 unsigned PrevIdx = MemTransferPartitionMap[&II];
684 // Check if the begin offsets match and this is a non-volatile transfer.
685 // In that case, we can completely elide the transfer.
686 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
687 P.Partitions[PrevIdx].kill();
691 // Otherwise we have an offset transfer within the same alloca. We can't
693 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
694 } else if (SeenBothEnds) {
695 // Handle the case where this exact use provides both ends of the
697 assert(II.getRawDest() == II.getRawSource());
699 // For non-volatile transfers this is a no-op.
700 if (!II.isVolatile())
703 // Otherwise just suppress splitting.
704 Offsets.IsSplittable = false;
708 // Insert the use now that we've fixed up the splittable nature.
709 insertUse(II, Offset, Size, Offsets.IsSplittable);
711 // Setup the mapping from intrinsic to partition of we've not seen both
712 // ends of this transfer.
714 unsigned NewIdx = P.Partitions.size() - 1;
716 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
718 "Already have intrinsic in map but haven't seen both ends");
725 // Disable SRoA for any intrinsics except for lifetime invariants.
726 // FIXME: What about debug instrinsics? This matches old behavior, but
727 // doesn't make sense.
728 bool visitIntrinsicInst(IntrinsicInst &II) {
729 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
730 II.getIntrinsicID() == Intrinsic::lifetime_end) {
731 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
732 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
733 insertUse(II, Offset, Size, true);
737 return markAsEscaping(II);
740 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
741 // We consider any PHI or select that results in a direct load or store of
742 // the same offset to be a viable use for partitioning purposes. These uses
743 // are considered unsplittable and the size is the maximum loaded or stored
745 SmallPtrSet<Instruction *, 4> Visited;
746 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
747 Visited.insert(Root);
748 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
749 // If there are no loads or stores, the access is dead. We mark that as
750 // a size zero access.
753 Instruction *I, *UsedI;
754 llvm::tie(UsedI, I) = Uses.pop_back_val();
756 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
757 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
760 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
761 Value *Op = SI->getOperand(0);
764 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
768 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
769 if (!GEP->hasAllZeroIndices())
771 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
772 !isa<SelectInst>(I)) {
776 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
778 if (Visited.insert(cast<Instruction>(*UI)))
779 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
780 } while (!Uses.empty());
785 bool visitPHINode(PHINode &PN) {
786 // See if we already have computed info on this node.
787 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
789 PHIInfo.second = true;
790 insertUse(PN, Offset, PHIInfo.first);
794 // Check for an unsafe use of the PHI node.
795 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
796 return markAsEscaping(*EscapingI);
798 insertUse(PN, Offset, PHIInfo.first);
802 bool visitSelectInst(SelectInst &SI) {
803 if (Value *Result = foldSelectInst(SI)) {
805 // If the result of the constant fold will be the pointer, recurse
806 // through the select as if we had RAUW'ed it.
807 enqueueUsers(SI, Offset);
812 // See if we already have computed info on this node.
813 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
814 if (SelectInfo.first) {
815 SelectInfo.second = true;
816 insertUse(SI, Offset, SelectInfo.first);
820 // Check for an unsafe use of the PHI node.
821 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
822 return markAsEscaping(*EscapingI);
824 insertUse(SI, Offset, SelectInfo.first);
828 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
829 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
833 /// \brief Use adder for the alloca partitioning.
835 /// This class adds the uses of an alloca to all of the partitions which they
836 /// use. For splittable partitions, this can end up doing essentially a linear
837 /// walk of the partitions, but the number of steps remains bounded by the
838 /// total result instruction size:
839 /// - The number of partitions is a result of the number unsplittable
840 /// instructions using the alloca.
841 /// - The number of users of each partition is at worst the total number of
842 /// splittable instructions using the alloca.
843 /// Thus we will produce N * M instructions in the end, where N are the number
844 /// of unsplittable uses and M are the number of splittable. This visitor does
845 /// the exact same number of updates to the partitioning.
847 /// In the more common case, this visitor will leverage the fact that the
848 /// partition space is pre-sorted, and do a logarithmic search for the
849 /// partition needed, making the total visit a classical ((N + M) * log(N))
850 /// complexity operation.
851 class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
852 friend class InstVisitor<UseBuilder>;
854 /// \brief Set to de-duplicate dead instructions found in the use walk.
855 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
858 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
859 : BuilderBase<UseBuilder>(TD, AI, P) {}
861 /// \brief Run the builder over the allocation.
863 // Note that we have to re-evaluate size on each trip through the loop as
864 // the queue grows at the tail.
865 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
867 Offset = Queue[Idx].Offset;
868 this->visit(cast<Instruction>(U->getUser()));
873 void markAsDead(Instruction &I) {
874 if (VisitedDeadInsts.insert(&I))
875 P.DeadUsers.push_back(&I);
878 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
879 // If the use has a zero size or extends outside of the allocation, record
880 // it as a dead use for elimination later.
881 if (Size == 0 || (uint64_t)Offset >= AllocSize ||
882 (Offset < 0 && (uint64_t)-Offset >= Size))
883 return markAsDead(User);
885 // Clamp the start to the beginning of the allocation.
887 Size -= (uint64_t)-Offset;
891 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
893 // Clamp the end offset to the end of the allocation. Note that this is
894 // formulated to handle even the case where "BeginOffset + Size" overflows.
895 assert(AllocSize >= BeginOffset); // Established above.
896 if (Size > AllocSize - BeginOffset)
897 EndOffset = AllocSize;
899 // NB: This only works if we have zero overlapping partitions.
900 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
901 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
903 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
905 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
906 std::min(I->EndOffset, EndOffset), U);
907 P.use_push_back(I, NewPU);
908 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
909 P.PHIOrSelectOpMap[U]
910 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
914 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
915 uint64_t Size = TD.getTypeStoreSize(Ty);
917 // If this memory access can be shown to *statically* extend outside the
918 // bounds of of the allocation, it's behavior is undefined, so simply
919 // ignore it. Note that this is more strict than the generic clamping
920 // behavior of insertUse.
921 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
922 Size > (AllocSize - (uint64_t)Offset))
923 return markAsDead(I);
925 insertUse(I, Offset, Size);
928 void visitBitCastInst(BitCastInst &BC) {
930 return markAsDead(BC);
932 enqueueUsers(BC, Offset);
935 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
936 if (GEPI.use_empty())
937 return markAsDead(GEPI);
940 if (!computeConstantGEPOffset(GEPI, GEPOffset))
941 llvm_unreachable("Unable to compute constant offset for use");
943 enqueueUsers(GEPI, GEPOffset);
946 void visitLoadInst(LoadInst &LI) {
947 handleLoadOrStore(LI.getType(), LI, Offset);
950 void visitStoreInst(StoreInst &SI) {
951 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
954 void visitMemSetInst(MemSetInst &II) {
955 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
956 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
957 insertUse(II, Offset, Size);
960 void visitMemTransferInst(MemTransferInst &II) {
961 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
962 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
964 return markAsDead(II);
966 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
967 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
968 Offsets.DestBegin == Offsets.SourceBegin)
969 return markAsDead(II); // Skip identity transfers without side-effects.
971 insertUse(II, Offset, Size);
974 void visitIntrinsicInst(IntrinsicInst &II) {
975 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
976 II.getIntrinsicID() == Intrinsic::lifetime_end);
978 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
979 insertUse(II, Offset,
980 std::min(AllocSize - Offset, Length->getLimitedValue()));
983 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
984 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
986 // For PHI and select operands outside the alloca, we can't nuke the entire
987 // phi or select -- the other side might still be relevant, so we special
988 // case them here and use a separate structure to track the operands
989 // themselves which should be replaced with undef.
990 if (Offset >= AllocSize) {
991 P.DeadOperands.push_back(U);
995 insertUse(User, Offset, Size);
997 void visitPHINode(PHINode &PN) {
999 return markAsDead(PN);
1001 insertPHIOrSelect(PN, Offset);
1003 void visitSelectInst(SelectInst &SI) {
1005 return markAsDead(SI);
1007 if (Value *Result = foldSelectInst(SI)) {
1009 // If the result of the constant fold will be the pointer, recurse
1010 // through the select as if we had RAUW'ed it.
1011 enqueueUsers(SI, Offset);
1013 // Otherwise the operand to the select is dead, and we can replace it
1015 P.DeadOperands.push_back(U);
1020 insertPHIOrSelect(SI, Offset);
1023 /// \brief Unreachable, we've already visited the alloca once.
1024 void visitInstruction(Instruction &I) {
1025 llvm_unreachable("Unhandled instruction in use builder.");
1029 void AllocaPartitioning::splitAndMergePartitions() {
1030 size_t NumDeadPartitions = 0;
1032 // Track the range of splittable partitions that we pass when accumulating
1033 // overlapping unsplittable partitions.
1034 uint64_t SplitEndOffset = 0ull;
1036 Partition New(0ull, 0ull, false);
1038 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
1041 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
1042 assert(New.BeginOffset == New.EndOffset);
1043 New = Partitions[i];
1045 assert(New.IsSplittable);
1046 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
1048 assert(New.BeginOffset != New.EndOffset);
1050 // Scan the overlapping partitions.
1051 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
1052 // If the new partition we are forming is splittable, stop at the first
1053 // unsplittable partition.
1054 if (New.IsSplittable && !Partitions[j].IsSplittable)
1057 // Grow the new partition to include any equally splittable range. 'j' is
1058 // always equally splittable when New is splittable, but when New is not
1059 // splittable, we may subsume some (or part of some) splitable partition
1060 // without growing the new one.
1061 if (New.IsSplittable == Partitions[j].IsSplittable) {
1062 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1064 assert(!New.IsSplittable);
1065 assert(Partitions[j].IsSplittable);
1066 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1069 Partitions[j].kill();
1070 ++NumDeadPartitions;
1074 // If the new partition is splittable, chop off the end as soon as the
1075 // unsplittable subsequent partition starts and ensure we eventually cover
1076 // the splittable area.
1077 if (j != e && New.IsSplittable) {
1078 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1079 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1082 // Add the new partition if it differs from the original one and is
1083 // non-empty. We can end up with an empty partition here if it was
1084 // splittable but there is an unsplittable one that starts at the same
1086 if (New != Partitions[i]) {
1087 if (New.BeginOffset != New.EndOffset)
1088 Partitions.push_back(New);
1089 // Mark the old one for removal.
1090 Partitions[i].kill();
1091 ++NumDeadPartitions;
1094 New.BeginOffset = New.EndOffset;
1095 if (!New.IsSplittable) {
1096 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1097 if (j != e && !Partitions[j].IsSplittable)
1098 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1099 New.IsSplittable = true;
1100 // If there is a trailing splittable partition which won't be fused into
1101 // the next splittable partition go ahead and add it onto the partitions
1103 if (New.BeginOffset < New.EndOffset &&
1104 (j == e || !Partitions[j].IsSplittable ||
1105 New.EndOffset < Partitions[j].BeginOffset)) {
1106 Partitions.push_back(New);
1107 New.BeginOffset = New.EndOffset = 0ull;
1112 // Re-sort the partitions now that they have been split and merged into
1113 // disjoint set of partitions. Also remove any of the dead partitions we've
1114 // replaced in the process.
1115 std::sort(Partitions.begin(), Partitions.end());
1116 if (NumDeadPartitions) {
1117 assert(Partitions.back().isDead());
1118 assert((ptrdiff_t)NumDeadPartitions ==
1119 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1121 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1124 AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
1129 PointerEscapingInstr(0) {
1130 PartitionBuilder PB(TD, AI, *this);
1134 // Sort the uses. This arranges for the offsets to be in ascending order,
1135 // and the sizes to be in descending order.
1136 std::sort(Partitions.begin(), Partitions.end());
1138 // Remove any partitions from the back which are marked as dead.
1139 while (!Partitions.empty() && Partitions.back().isDead())
1140 Partitions.pop_back();
1142 if (Partitions.size() > 1) {
1143 // Intersect splittability for all partitions with equal offsets and sizes.
1144 // Then remove all but the first so that we have a sequence of non-equal but
1145 // potentially overlapping partitions.
1146 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1149 while (J != E && *I == *J) {
1150 I->IsSplittable &= J->IsSplittable;
1154 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1157 // Split splittable and merge unsplittable partitions into a disjoint set
1158 // of partitions over the used space of the allocation.
1159 splitAndMergePartitions();
1162 // Now build up the user lists for each of these disjoint partitions by
1163 // re-walking the recursive users of the alloca.
1164 Uses.resize(Partitions.size());
1165 UseBuilder UB(TD, AI, *this);
1169 Type *AllocaPartitioning::getCommonType(iterator I) const {
1171 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1173 continue; // Skip dead uses.
1174 if (isa<IntrinsicInst>(*UI->U->getUser()))
1176 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1180 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
1181 UserTy = LI->getType();
1182 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
1183 UserTy = SI->getValueOperand()->getType();
1185 return 0; // Bail if we have weird uses.
1188 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1189 // If the type is larger than the partition, skip it. We only encounter
1190 // this for split integer operations where we want to use the type of the
1191 // entity causing the split.
1192 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1195 // If we have found an integer type use covering the alloca, use that
1196 // regardless of the other types, as integers are often used for a "bucket
1201 if (Ty && Ty != UserTy)
1209 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1211 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1212 StringRef Indent) const {
1213 OS << Indent << "partition #" << (I - begin())
1214 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1215 << (I->IsSplittable ? " (splittable)" : "")
1216 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1220 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1221 StringRef Indent) const {
1222 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1225 continue; // Skip dead uses.
1226 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1227 << "used by: " << *UI->U->getUser() << "\n";
1228 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
1229 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1231 if (!MTO.IsSplittable)
1232 IsDest = UI->BeginOffset == MTO.DestBegin;
1234 IsDest = MTO.DestBegin != 0u;
1235 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1236 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1237 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1242 void AllocaPartitioning::print(raw_ostream &OS) const {
1243 if (PointerEscapingInstr) {
1244 OS << "No partitioning for alloca: " << AI << "\n"
1245 << " A pointer to this alloca escaped by:\n"
1246 << " " << *PointerEscapingInstr << "\n";
1250 OS << "Partitioning of alloca: " << AI << "\n";
1252 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1258 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1259 void AllocaPartitioning::dump() const { print(dbgs()); }
1261 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1265 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1267 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1268 /// the loads and stores of an alloca instruction, as well as updating its
1269 /// debug information. This is used when a domtree is unavailable and thus
1270 /// mem2reg in its full form can't be used to handle promotion of allocas to
1272 class AllocaPromoter : public LoadAndStorePromoter {
1276 SmallVector<DbgDeclareInst *, 4> DDIs;
1277 SmallVector<DbgValueInst *, 4> DVIs;
1280 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1281 AllocaInst &AI, DIBuilder &DIB)
1282 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1284 void run(const SmallVectorImpl<Instruction*> &Insts) {
1285 // Remember which alloca we're promoting (for isInstInList).
1286 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1287 for (Value::use_iterator UI = DebugNode->use_begin(),
1288 UE = DebugNode->use_end();
1290 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1291 DDIs.push_back(DDI);
1292 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1293 DVIs.push_back(DVI);
1296 LoadAndStorePromoter::run(Insts);
1297 AI.eraseFromParent();
1298 while (!DDIs.empty())
1299 DDIs.pop_back_val()->eraseFromParent();
1300 while (!DVIs.empty())
1301 DVIs.pop_back_val()->eraseFromParent();
1304 virtual bool isInstInList(Instruction *I,
1305 const SmallVectorImpl<Instruction*> &Insts) const {
1306 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1307 return LI->getOperand(0) == &AI;
1308 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1311 virtual void updateDebugInfo(Instruction *Inst) const {
1312 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1313 E = DDIs.end(); I != E; ++I) {
1314 DbgDeclareInst *DDI = *I;
1315 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1316 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1317 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1318 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1320 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1321 E = DVIs.end(); I != E; ++I) {
1322 DbgValueInst *DVI = *I;
1324 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1325 // If an argument is zero extended then use argument directly. The ZExt
1326 // may be zapped by an optimization pass in future.
1327 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1328 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1329 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1330 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1332 Arg = SI->getOperand(0);
1333 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1334 Arg = LI->getOperand(0);
1338 Instruction *DbgVal =
1339 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1341 DbgVal->setDebugLoc(DVI->getDebugLoc());
1345 } // end anon namespace
1349 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1351 /// This pass takes allocations which can be completely analyzed (that is, they
1352 /// don't escape) and tries to turn them into scalar SSA values. There are
1353 /// a few steps to this process.
1355 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1356 /// are used to try to split them into smaller allocations, ideally of
1357 /// a single scalar data type. It will split up memcpy and memset accesses
1358 /// as necessary and try to isolate invidual scalar accesses.
1359 /// 2) It will transform accesses into forms which are suitable for SSA value
1360 /// promotion. This can be replacing a memset with a scalar store of an
1361 /// integer value, or it can involve speculating operations on a PHI or
1362 /// select to be a PHI or select of the results.
1363 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1364 /// onto insert and extract operations on a vector value, and convert them to
1365 /// this form. By doing so, it will enable promotion of vector aggregates to
1366 /// SSA vector values.
1367 class SROA : public FunctionPass {
1368 const bool RequiresDomTree;
1371 const DataLayout *TD;
1374 /// \brief Worklist of alloca instructions to simplify.
1376 /// Each alloca in the function is added to this. Each new alloca formed gets
1377 /// added to it as well to recursively simplify unless that alloca can be
1378 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1379 /// the one being actively rewritten, we add it back onto the list if not
1380 /// already present to ensure it is re-visited.
1381 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1383 /// \brief A collection of instructions to delete.
1384 /// We try to batch deletions to simplify code and make things a bit more
1386 SmallVector<Instruction *, 8> DeadInsts;
1388 /// \brief A set to prevent repeatedly marking an instruction split into many
1389 /// uses as dead. Only used to guard insertion into DeadInsts.
1390 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1392 /// \brief Post-promotion worklist.
1394 /// Sometimes we discover an alloca which has a high probability of becoming
1395 /// viable for SROA after a round of promotion takes place. In those cases,
1396 /// the alloca is enqueued here for re-processing.
1398 /// Note that we have to be very careful to clear allocas out of this list in
1399 /// the event they are deleted.
1400 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1402 /// \brief A collection of alloca instructions we can directly promote.
1403 std::vector<AllocaInst *> PromotableAllocas;
1406 SROA(bool RequiresDomTree = true)
1407 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1408 C(0), TD(0), DT(0) {
1409 initializeSROAPass(*PassRegistry::getPassRegistry());
1411 bool runOnFunction(Function &F);
1412 void getAnalysisUsage(AnalysisUsage &AU) const;
1414 const char *getPassName() const { return "SROA"; }
1418 friend class PHIOrSelectSpeculator;
1419 friend class AllocaPartitionRewriter;
1420 friend class AllocaPartitionVectorRewriter;
1422 bool rewriteAllocaPartition(AllocaInst &AI,
1423 AllocaPartitioning &P,
1424 AllocaPartitioning::iterator PI);
1425 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1426 bool runOnAlloca(AllocaInst &AI);
1427 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
1428 bool promoteAllocas(Function &F);
1434 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1435 return new SROA(RequiresDomTree);
1438 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1440 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1441 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1445 /// \brief Visitor to speculate PHIs and Selects where possible.
1446 class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1447 // Befriend the base class so it can delegate to private visit methods.
1448 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1450 const DataLayout &TD;
1451 AllocaPartitioning &P;
1455 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
1456 : TD(TD), P(P), Pass(Pass) {}
1458 /// \brief Visit the users of an alloca partition and rewrite them.
1459 void visitUsers(AllocaPartitioning::const_iterator PI) {
1460 // Note that we need to use an index here as the underlying vector of uses
1461 // may be grown during speculation. However, we never need to re-visit the
1462 // new uses, and so we can use the initial size bound.
1463 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1464 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1466 continue; // Skip dead use.
1468 visit(cast<Instruction>(PU.U->getUser()));
1473 // By default, skip this instruction.
1474 void visitInstruction(Instruction &I) {}
1476 /// PHI instructions that use an alloca and are subsequently loaded can be
1477 /// rewritten to load both input pointers in the pred blocks and then PHI the
1478 /// results, allowing the load of the alloca to be promoted.
1480 /// %P2 = phi [i32* %Alloca, i32* %Other]
1481 /// %V = load i32* %P2
1483 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1485 /// %V2 = load i32* %Other
1487 /// %V = phi [i32 %V1, i32 %V2]
1489 /// We can do this to a select if its only uses are loads and if the operands
1490 /// to the select can be loaded unconditionally.
1492 /// FIXME: This should be hoisted into a generic utility, likely in
1493 /// Transforms/Util/Local.h
1494 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1495 // For now, we can only do this promotion if the load is in the same block
1496 // as the PHI, and if there are no stores between the phi and load.
1497 // TODO: Allow recursive phi users.
1498 // TODO: Allow stores.
1499 BasicBlock *BB = PN.getParent();
1500 unsigned MaxAlign = 0;
1501 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1503 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1504 if (LI == 0 || !LI->isSimple()) return false;
1506 // For now we only allow loads in the same block as the PHI. This is
1507 // a common case that happens when instcombine merges two loads through
1509 if (LI->getParent() != BB) return false;
1511 // Ensure that there are no instructions between the PHI and the load that
1513 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1514 if (BBI->mayWriteToMemory())
1517 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1518 Loads.push_back(LI);
1521 // We can only transform this if it is safe to push the loads into the
1522 // predecessor blocks. The only thing to watch out for is that we can't put
1523 // a possibly trapping load in the predecessor if it is a critical edge.
1524 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1526 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1527 Value *InVal = PN.getIncomingValue(Idx);
1529 // If the value is produced by the terminator of the predecessor (an
1530 // invoke) or it has side-effects, there is no valid place to put a load
1531 // in the predecessor.
1532 if (TI == InVal || TI->mayHaveSideEffects())
1535 // If the predecessor has a single successor, then the edge isn't
1537 if (TI->getNumSuccessors() == 1)
1540 // If this pointer is always safe to load, or if we can prove that there
1541 // is already a load in the block, then we can move the load to the pred
1543 if (InVal->isDereferenceablePointer() ||
1544 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1553 void visitPHINode(PHINode &PN) {
1554 DEBUG(dbgs() << " original: " << PN << "\n");
1556 SmallVector<LoadInst *, 4> Loads;
1557 if (!isSafePHIToSpeculate(PN, Loads))
1560 assert(!Loads.empty());
1562 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1563 IRBuilder<> PHIBuilder(&PN);
1564 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1565 PN.getName() + ".sroa.speculated");
1567 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1568 // matter which one we get and if any differ, it doesn't matter.
1569 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1570 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1571 unsigned Align = SomeLoad->getAlignment();
1573 // Rewrite all loads of the PN to use the new PHI.
1575 LoadInst *LI = Loads.pop_back_val();
1576 LI->replaceAllUsesWith(NewPN);
1577 Pass.DeadInsts.push_back(LI);
1578 } while (!Loads.empty());
1580 // Inject loads into all of the pred blocks.
1581 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1582 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1583 TerminatorInst *TI = Pred->getTerminator();
1584 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1585 Value *InVal = PN.getIncomingValue(Idx);
1586 IRBuilder<> PredBuilder(TI);
1589 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1591 ++NumLoadsSpeculated;
1592 Load->setAlignment(Align);
1594 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1595 NewPN->addIncoming(Load, Pred);
1597 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1599 // No uses to rewrite.
1602 // Try to lookup and rewrite any partition uses corresponding to this phi
1604 AllocaPartitioning::iterator PI
1605 = P.findPartitionForPHIOrSelectOperand(InUse);
1609 // Replace the Use in the PartitionUse for this operand with the Use
1611 AllocaPartitioning::use_iterator UI
1612 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1613 assert(isa<PHINode>(*UI->U->getUser()));
1614 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1616 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1619 /// Select instructions that use an alloca and are subsequently loaded can be
1620 /// rewritten to load both input pointers and then select between the result,
1621 /// allowing the load of the alloca to be promoted.
1623 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1624 /// %V = load i32* %P2
1626 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1627 /// %V2 = load i32* %Other
1628 /// %V = select i1 %cond, i32 %V1, i32 %V2
1630 /// We can do this to a select if its only uses are loads and if the operand
1631 /// to the select can be loaded unconditionally.
1632 bool isSafeSelectToSpeculate(SelectInst &SI,
1633 SmallVectorImpl<LoadInst *> &Loads) {
1634 Value *TValue = SI.getTrueValue();
1635 Value *FValue = SI.getFalseValue();
1636 bool TDerefable = TValue->isDereferenceablePointer();
1637 bool FDerefable = FValue->isDereferenceablePointer();
1639 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1641 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1642 if (LI == 0 || !LI->isSimple()) return false;
1644 // Both operands to the select need to be dereferencable, either
1645 // absolutely (e.g. allocas) or at this point because we can see other
1647 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1648 LI->getAlignment(), &TD))
1650 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1651 LI->getAlignment(), &TD))
1653 Loads.push_back(LI);
1659 void visitSelectInst(SelectInst &SI) {
1660 DEBUG(dbgs() << " original: " << SI << "\n");
1661 IRBuilder<> IRB(&SI);
1663 // If the select isn't safe to speculate, just use simple logic to emit it.
1664 SmallVector<LoadInst *, 4> Loads;
1665 if (!isSafeSelectToSpeculate(SI, Loads))
1668 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1669 AllocaPartitioning::iterator PIs[2];
1670 AllocaPartitioning::PartitionUse PUs[2];
1671 for (unsigned i = 0, e = 2; i != e; ++i) {
1672 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1673 if (PIs[i] != P.end()) {
1674 // If the pointer is within the partitioning, remove the select from
1675 // its uses. We'll add in the new loads below.
1676 AllocaPartitioning::use_iterator UI
1677 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1679 // Clear out the use here so that the offsets into the use list remain
1680 // stable but this use is ignored when rewriting.
1685 Value *TV = SI.getTrueValue();
1686 Value *FV = SI.getFalseValue();
1687 // Replace the loads of the select with a select of two loads.
1688 while (!Loads.empty()) {
1689 LoadInst *LI = Loads.pop_back_val();
1691 IRB.SetInsertPoint(LI);
1693 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1695 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1696 NumLoadsSpeculated += 2;
1698 // Transfer alignment and TBAA info if present.
1699 TL->setAlignment(LI->getAlignment());
1700 FL->setAlignment(LI->getAlignment());
1701 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1702 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1703 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1706 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1707 LI->getName() + ".sroa.speculated");
1709 LoadInst *Loads[2] = { TL, FL };
1710 for (unsigned i = 0, e = 2; i != e; ++i) {
1711 if (PIs[i] != P.end()) {
1712 Use *LoadUse = &Loads[i]->getOperandUse(0);
1713 assert(PUs[i].U->get() == LoadUse->get());
1715 P.use_push_back(PIs[i], PUs[i]);
1719 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1720 LI->replaceAllUsesWith(V);
1721 Pass.DeadInsts.push_back(LI);
1727 /// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1729 /// If the provided GEP is all-constant, the total byte offset formed by the
1730 /// GEP is computed and Offset is set to it. If the GEP has any non-constant
1731 /// operands, the function returns false and the value of Offset is unmodified.
1732 static bool accumulateGEPOffsets(const DataLayout &TD, GEPOperator &GEP,
1734 APInt GEPOffset(Offset.getBitWidth(), 0);
1735 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1736 GTI != GTE; ++GTI) {
1737 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1740 if (OpC->isZero()) continue;
1742 // Handle a struct index, which adds its field offset to the pointer.
1743 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1744 unsigned ElementIdx = OpC->getZExtValue();
1745 const StructLayout *SL = TD.getStructLayout(STy);
1746 GEPOffset += APInt(Offset.getBitWidth(),
1747 SL->getElementOffset(ElementIdx));
1751 APInt TypeSize(Offset.getBitWidth(),
1752 TD.getTypeAllocSize(GTI.getIndexedType()));
1753 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1754 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1755 "vector element size is not a multiple of 8, cannot GEP over it");
1756 TypeSize = VTy->getScalarSizeInBits() / 8;
1759 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1765 /// \brief Build a GEP out of a base pointer and indices.
1767 /// This will return the BasePtr if that is valid, or build a new GEP
1768 /// instruction using the IRBuilder if GEP-ing is needed.
1769 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1770 SmallVectorImpl<Value *> &Indices,
1771 const Twine &Prefix) {
1772 if (Indices.empty())
1775 // A single zero index is a no-op, so check for this and avoid building a GEP
1777 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1780 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1783 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1784 /// TargetTy without changing the offset of the pointer.
1786 /// This routine assumes we've already established a properly offset GEP with
1787 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1788 /// zero-indices down through type layers until we find one the same as
1789 /// TargetTy. If we can't find one with the same type, we at least try to use
1790 /// one with the same size. If none of that works, we just produce the GEP as
1791 /// indicated by Indices to have the correct offset.
1792 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
1793 Value *BasePtr, Type *Ty, Type *TargetTy,
1794 SmallVectorImpl<Value *> &Indices,
1795 const Twine &Prefix) {
1797 return buildGEP(IRB, BasePtr, Indices, Prefix);
1799 // See if we can descend into a struct and locate a field with the correct
1801 unsigned NumLayers = 0;
1802 Type *ElementTy = Ty;
1804 if (ElementTy->isPointerTy())
1806 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1807 ElementTy = SeqTy->getElementType();
1808 // Note that we use the default address space as this index is over an
1809 // array or a vector, not a pointer.
1810 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
1811 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1812 if (STy->element_begin() == STy->element_end())
1813 break; // Nothing left to descend into.
1814 ElementTy = *STy->element_begin();
1815 Indices.push_back(IRB.getInt32(0));
1820 } while (ElementTy != TargetTy);
1821 if (ElementTy != TargetTy)
1822 Indices.erase(Indices.end() - NumLayers, Indices.end());
1824 return buildGEP(IRB, BasePtr, Indices, Prefix);
1827 /// \brief Recursively compute indices for a natural GEP.
1829 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1830 /// element types adding appropriate indices for the GEP.
1831 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
1832 Value *Ptr, Type *Ty, APInt &Offset,
1834 SmallVectorImpl<Value *> &Indices,
1835 const Twine &Prefix) {
1837 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1839 // We can't recurse through pointer types.
1840 if (Ty->isPointerTy())
1843 // We try to analyze GEPs over vectors here, but note that these GEPs are
1844 // extremely poorly defined currently. The long-term goal is to remove GEPing
1845 // over a vector from the IR completely.
1846 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1847 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1848 if (ElementSizeInBits % 8)
1849 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1850 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1851 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1852 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1854 Offset -= NumSkippedElements * ElementSize;
1855 Indices.push_back(IRB.getInt(NumSkippedElements));
1856 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1857 Offset, TargetTy, Indices, Prefix);
1860 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1861 Type *ElementTy = ArrTy->getElementType();
1862 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1863 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1864 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1867 Offset -= NumSkippedElements * ElementSize;
1868 Indices.push_back(IRB.getInt(NumSkippedElements));
1869 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1873 StructType *STy = dyn_cast<StructType>(Ty);
1877 const StructLayout *SL = TD.getStructLayout(STy);
1878 uint64_t StructOffset = Offset.getZExtValue();
1879 if (StructOffset >= SL->getSizeInBytes())
1881 unsigned Index = SL->getElementContainingOffset(StructOffset);
1882 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1883 Type *ElementTy = STy->getElementType(Index);
1884 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1885 return 0; // The offset points into alignment padding.
1887 Indices.push_back(IRB.getInt32(Index));
1888 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1892 /// \brief Get a natural GEP from a base pointer to a particular offset and
1893 /// resulting in a particular type.
1895 /// The goal is to produce a "natural" looking GEP that works with the existing
1896 /// composite types to arrive at the appropriate offset and element type for
1897 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1898 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1899 /// Indices, and setting Ty to the result subtype.
1901 /// If no natural GEP can be constructed, this function returns null.
1902 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
1903 Value *Ptr, APInt Offset, Type *TargetTy,
1904 SmallVectorImpl<Value *> &Indices,
1905 const Twine &Prefix) {
1906 PointerType *Ty = cast<PointerType>(Ptr->getType());
1908 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1910 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1913 Type *ElementTy = Ty->getElementType();
1914 if (!ElementTy->isSized())
1915 return 0; // We can't GEP through an unsized element.
1916 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1917 if (ElementSize == 0)
1918 return 0; // Zero-length arrays can't help us build a natural GEP.
1919 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1921 Offset -= NumSkippedElements * ElementSize;
1922 Indices.push_back(IRB.getInt(NumSkippedElements));
1923 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1927 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1928 /// resulting pointer has PointerTy.
1930 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1931 /// and produces the pointer type desired. Where it cannot, it will try to use
1932 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1933 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1934 /// bitcast to the type.
1936 /// The strategy for finding the more natural GEPs is to peel off layers of the
1937 /// pointer, walking back through bit casts and GEPs, searching for a base
1938 /// pointer from which we can compute a natural GEP with the desired
1939 /// properities. The algorithm tries to fold as many constant indices into
1940 /// a single GEP as possible, thus making each GEP more independent of the
1941 /// surrounding code.
1942 static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
1943 Value *Ptr, APInt Offset, Type *PointerTy,
1944 const Twine &Prefix) {
1945 // Even though we don't look through PHI nodes, we could be called on an
1946 // instruction in an unreachable block, which may be on a cycle.
1947 SmallPtrSet<Value *, 4> Visited;
1948 Visited.insert(Ptr);
1949 SmallVector<Value *, 4> Indices;
1951 // We may end up computing an offset pointer that has the wrong type. If we
1952 // never are able to compute one directly that has the correct type, we'll
1953 // fall back to it, so keep it around here.
1954 Value *OffsetPtr = 0;
1956 // Remember any i8 pointer we come across to re-use if we need to do a raw
1959 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1961 Type *TargetTy = PointerTy->getPointerElementType();
1964 // First fold any existing GEPs into the offset.
1965 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1966 APInt GEPOffset(Offset.getBitWidth(), 0);
1967 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1969 Offset += GEPOffset;
1970 Ptr = GEP->getPointerOperand();
1971 if (!Visited.insert(Ptr))
1975 // See if we can perform a natural GEP here.
1977 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1979 if (P->getType() == PointerTy) {
1980 // Zap any offset pointer that we ended up computing in previous rounds.
1981 if (OffsetPtr && OffsetPtr->use_empty())
1982 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1983 I->eraseFromParent();
1991 // Stash this pointer if we've found an i8*.
1992 if (Ptr->getType()->isIntegerTy(8)) {
1994 Int8PtrOffset = Offset;
1997 // Peel off a layer of the pointer and update the offset appropriately.
1998 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1999 Ptr = cast<Operator>(Ptr)->getOperand(0);
2000 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2001 if (GA->mayBeOverridden())
2003 Ptr = GA->getAliasee();
2007 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
2008 } while (Visited.insert(Ptr));
2012 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
2013 Prefix + ".raw_cast");
2014 Int8PtrOffset = Offset;
2017 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
2018 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
2019 Prefix + ".raw_idx");
2023 // On the off chance we were targeting i8*, guard the bitcast here.
2024 if (Ptr->getType() != PointerTy)
2025 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
2030 /// \brief Test whether we can convert a value from the old to the new type.
2032 /// This predicate should be used to guard calls to convertValue in order to
2033 /// ensure that we only try to convert viable values. The strategy is that we
2034 /// will peel off single element struct and array wrappings to get to an
2035 /// underlying value, and convert that value.
2036 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
2039 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
2041 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
2044 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
2045 if (NewTy->isPointerTy() && OldTy->isPointerTy())
2047 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
2055 /// \brief Generic routine to convert an SSA value to a value of a different
2058 /// This will try various different casting techniques, such as bitcasts,
2059 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
2060 /// two types for viability with this routine.
2061 static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2063 assert(canConvertValue(DL, V->getType(), Ty) &&
2064 "Value not convertable to type");
2065 if (V->getType() == Ty)
2067 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2068 return IRB.CreateIntToPtr(V, Ty);
2069 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2070 return IRB.CreatePtrToInt(V, Ty);
2072 return IRB.CreateBitCast(V, Ty);
2075 /// \brief Test whether the given alloca partition can be promoted to a vector.
2077 /// This is a quick test to check whether we can rewrite a particular alloca
2078 /// partition (and its newly formed alloca) into a vector alloca with only
2079 /// whole-vector loads and stores such that it could be promoted to a vector
2080 /// SSA value. We only can ensure this for a limited set of operations, and we
2081 /// don't want to do the rewrites unless we are confident that the result will
2082 /// be promotable, so we have an early test here.
2083 static bool isVectorPromotionViable(const DataLayout &TD,
2085 AllocaPartitioning &P,
2086 uint64_t PartitionBeginOffset,
2087 uint64_t PartitionEndOffset,
2088 AllocaPartitioning::const_use_iterator I,
2089 AllocaPartitioning::const_use_iterator E) {
2090 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2094 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
2095 uint64_t ElementSize = Ty->getScalarSizeInBits();
2097 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2098 // that aren't byte sized.
2099 if (ElementSize % 8)
2101 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
2105 for (; I != E; ++I) {
2107 continue; // Skip dead use.
2109 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2110 uint64_t BeginIndex = BeginOffset / ElementSize;
2111 if (BeginIndex * ElementSize != BeginOffset ||
2112 BeginIndex >= Ty->getNumElements())
2114 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2115 uint64_t EndIndex = EndOffset / ElementSize;
2116 if (EndIndex * ElementSize != EndOffset ||
2117 EndIndex > Ty->getNumElements())
2120 // FIXME: We should build shuffle vector instructions to handle
2121 // non-element-sized accesses.
2122 if ((EndOffset - BeginOffset) != ElementSize &&
2123 (EndOffset - BeginOffset) != VecSize)
2126 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
2127 if (MI->isVolatile())
2129 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
2130 const AllocaPartitioning::MemTransferOffsets &MTO
2131 = P.getMemTransferOffsets(*MTI);
2132 if (!MTO.IsSplittable)
2135 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
2136 // Disable vector promotion when there are loads or stores of an FCA.
2138 } else if (!isa<LoadInst>(I->U->getUser()) &&
2139 !isa<StoreInst>(I->U->getUser())) {
2146 /// \brief Test whether the given alloca partition's integer operations can be
2147 /// widened to promotable ones.
2149 /// This is a quick test to check whether we can rewrite the integer loads and
2150 /// stores to a particular alloca into wider loads and stores and be able to
2151 /// promote the resulting alloca.
2152 static bool isIntegerWideningViable(const DataLayout &TD,
2154 uint64_t AllocBeginOffset,
2155 AllocaPartitioning &P,
2156 AllocaPartitioning::const_use_iterator I,
2157 AllocaPartitioning::const_use_iterator E) {
2158 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
2160 // Don't try to handle allocas with bit-padding.
2161 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
2164 // We need to ensure that an integer type with the appropriate bitwidth can
2165 // be converted to the alloca type, whatever that is. We don't want to force
2166 // the alloca itself to have an integer type if there is a more suitable one.
2167 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2168 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2169 !canConvertValue(TD, IntTy, AllocaTy))
2172 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2174 // Check the uses to ensure the uses are (likely) promoteable integer uses.
2175 // Also ensure that the alloca has a covering load or store. We don't want
2176 // to widen the integer operotains only to fail to promote due to some other
2177 // unsplittable entry (which we may make splittable later).
2178 bool WholeAllocaOp = false;
2179 for (; I != E; ++I) {
2181 continue; // Skip dead use.
2183 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2184 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2186 // We can't reasonably handle cases where the load or store extends past
2187 // the end of the aloca's type and into its padding.
2191 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
2192 if (LI->isVolatile())
2194 if (RelBegin == 0 && RelEnd == Size)
2195 WholeAllocaOp = true;
2196 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2197 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2201 // Non-integer loads need to be convertible from the alloca type so that
2202 // they are promotable.
2203 if (RelBegin != 0 || RelEnd != Size ||
2204 !canConvertValue(TD, AllocaTy, LI->getType()))
2206 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
2207 Type *ValueTy = SI->getValueOperand()->getType();
2208 if (SI->isVolatile())
2210 if (RelBegin == 0 && RelEnd == Size)
2211 WholeAllocaOp = true;
2212 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2213 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2217 // Non-integer stores need to be convertible to the alloca type so that
2218 // they are promotable.
2219 if (RelBegin != 0 || RelEnd != Size ||
2220 !canConvertValue(TD, ValueTy, AllocaTy))
2222 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
2223 if (MI->isVolatile())
2225 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
2226 const AllocaPartitioning::MemTransferOffsets &MTO
2227 = P.getMemTransferOffsets(*MTI);
2228 if (!MTO.IsSplittable)
2231 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->U->getUser())) {
2232 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2233 II->getIntrinsicID() != Intrinsic::lifetime_end)
2239 return WholeAllocaOp;
2242 static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2243 IntegerType *Ty, uint64_t Offset,
2244 const Twine &Name) {
2245 IntegerType *IntTy = cast<IntegerType>(V->getType());
2246 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2247 "Element extends past full value");
2248 uint64_t ShAmt = 8*Offset;
2249 if (DL.isBigEndian())
2250 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2252 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2253 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2254 "Cannot extract to a larger integer!");
2256 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2260 static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2261 Value *V, uint64_t Offset, const Twine &Name) {
2262 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2263 IntegerType *Ty = cast<IntegerType>(V->getType());
2264 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2265 "Cannot insert a larger integer!");
2267 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2268 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2269 "Element store outside of alloca store");
2270 uint64_t ShAmt = 8*Offset;
2271 if (DL.isBigEndian())
2272 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2274 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2276 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2277 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2278 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2279 V = IRB.CreateOr(Old, V, Name + ".insert");
2285 /// \brief Visitor to rewrite instructions using a partition of an alloca to
2286 /// use a new alloca.
2288 /// Also implements the rewriting to vector-based accesses when the partition
2289 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2291 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2293 // Befriend the base class so it can delegate to private visit methods.
2294 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2296 const DataLayout &TD;
2297 AllocaPartitioning &P;
2299 AllocaInst &OldAI, &NewAI;
2300 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2303 // If we are rewriting an alloca partition which can be written as pure
2304 // vector operations, we stash extra information here. When VecTy is
2305 // non-null, we have some strict guarantees about the rewriten alloca:
2306 // - The new alloca is exactly the size of the vector type here.
2307 // - The accesses all either map to the entire vector or to a single
2309 // - The set of accessing instructions is only one of those handled above
2310 // in isVectorPromotionViable. Generally these are the same access kinds
2311 // which are promotable via mem2reg.
2314 uint64_t ElementSize;
2316 // This is a convenience and flag variable that will be null unless the new
2317 // alloca's integer operations should be widened to this integer type due to
2318 // passing isIntegerWideningViable above. If it is non-null, the desired
2319 // integer type will be stored here for easy access during rewriting.
2322 // The offset of the partition user currently being rewritten.
2323 uint64_t BeginOffset, EndOffset;
2325 Instruction *OldPtr;
2327 // The name prefix to use when rewriting instructions for this alloca.
2328 std::string NamePrefix;
2331 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
2332 AllocaPartitioning::iterator PI,
2333 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2334 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2335 : TD(TD), P(P), Pass(Pass),
2336 OldAI(OldAI), NewAI(NewAI),
2337 NewAllocaBeginOffset(NewBeginOffset),
2338 NewAllocaEndOffset(NewEndOffset),
2339 NewAllocaTy(NewAI.getAllocatedType()),
2340 VecTy(), ElementTy(), ElementSize(), IntTy(),
2341 BeginOffset(), EndOffset() {
2344 /// \brief Visit the users of the alloca partition and rewrite them.
2345 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2346 AllocaPartitioning::const_use_iterator E) {
2347 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2348 NewAllocaBeginOffset, NewAllocaEndOffset,
2351 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2352 ElementTy = VecTy->getElementType();
2353 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2354 "Only multiple-of-8 sized vector elements are viable");
2355 ElementSize = VecTy->getScalarSizeInBits() / 8;
2356 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2357 NewAllocaBeginOffset, P, I, E)) {
2358 IntTy = Type::getIntNTy(NewAI.getContext(),
2359 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
2361 bool CanSROA = true;
2362 for (; I != E; ++I) {
2364 continue; // Skip dead uses.
2365 BeginOffset = I->BeginOffset;
2366 EndOffset = I->EndOffset;
2368 OldPtr = cast<Instruction>(I->U->get());
2369 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
2370 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
2386 // Every instruction which can end up as a user must have a rewrite rule.
2387 bool visitInstruction(Instruction &I) {
2388 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2389 llvm_unreachable("No rewrite rule for this instruction!");
2392 Twine getName(const Twine &Suffix) {
2393 return NamePrefix + Suffix;
2396 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2397 assert(BeginOffset >= NewAllocaBeginOffset);
2398 unsigned AS = cast<PointerType>(PointerTy)->getAddressSpace();
2399 APInt Offset(TD.getPointerSizeInBits(AS), BeginOffset - NewAllocaBeginOffset);
2400 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2403 /// \brief Compute suitable alignment to access an offset into the new alloca.
2404 unsigned getOffsetAlign(uint64_t Offset) {
2405 unsigned NewAIAlign = NewAI.getAlignment();
2407 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2408 return MinAlign(NewAIAlign, Offset);
2411 /// \brief Compute suitable alignment to access this partition of the new
2413 unsigned getPartitionAlign() {
2414 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
2417 /// \brief Compute suitable alignment to access a type at an offset of the
2420 /// \returns zero if the type's ABI alignment is a suitable alignment,
2421 /// otherwise returns the maximal suitable alignment.
2422 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2423 unsigned Align = getOffsetAlign(Offset);
2424 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2427 /// \brief Compute suitable alignment to access a type at the beginning of
2428 /// this partition of the new alloca.
2430 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2431 unsigned getPartitionTypeAlign(Type *Ty) {
2432 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
2435 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
2436 assert(VecTy && "Can only call getIndex when rewriting a vector");
2437 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2438 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2439 uint32_t Index = RelOffset / ElementSize;
2440 assert(Index * ElementSize == RelOffset);
2441 return IRB.getInt32(Index);
2444 void deleteIfTriviallyDead(Value *V) {
2445 Instruction *I = cast<Instruction>(V);
2446 if (isInstructionTriviallyDead(I))
2447 Pass.DeadInsts.push_back(I);
2450 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2452 if (LI.getType() == VecTy->getElementType() ||
2453 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2454 Result = IRB.CreateExtractElement(
2455 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2456 getIndex(IRB, BeginOffset), getName(".extract"));
2458 Result = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2461 if (Result->getType() != LI.getType())
2462 Result = convertValue(TD, IRB, Result, LI.getType());
2463 LI.replaceAllUsesWith(Result);
2464 Pass.DeadInsts.push_back(&LI);
2466 DEBUG(dbgs() << " to: " << *Result << "\n");
2470 bool rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
2471 assert(IntTy && "We cannot insert an integer to the alloca");
2472 assert(!LI.isVolatile());
2473 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2475 V = convertValue(TD, IRB, V, IntTy);
2476 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2477 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2478 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2479 getName(".extract"));
2480 LI.replaceAllUsesWith(V);
2481 Pass.DeadInsts.push_back(&LI);
2482 DEBUG(dbgs() << " to: " << *V << "\n");
2486 bool visitLoadInst(LoadInst &LI) {
2487 DEBUG(dbgs() << " original: " << LI << "\n");
2488 Value *OldOp = LI.getOperand(0);
2489 assert(OldOp == OldPtr);
2490 IRBuilder<> IRB(&LI);
2492 uint64_t Size = EndOffset - BeginOffset;
2493 if (Size < TD.getTypeStoreSize(LI.getType())) {
2494 assert(!LI.isVolatile());
2495 assert(LI.getType()->isIntegerTy() &&
2496 "Only integer type loads and stores are split");
2497 assert(LI.getType()->getIntegerBitWidth() ==
2498 TD.getTypeStoreSizeInBits(LI.getType()) &&
2499 "Non-byte-multiple bit width");
2500 assert(LI.getType()->getIntegerBitWidth() ==
2501 TD.getTypeAllocSizeInBits(OldAI.getAllocatedType()) &&
2502 "Only alloca-wide loads can be split and recomposed");
2503 IntegerType *NarrowTy = Type::getIntNTy(LI.getContext(), Size * 8);
2504 bool IsConvertable = (BeginOffset - NewAllocaBeginOffset == 0) &&
2505 canConvertValue(TD, NewAllocaTy, NarrowTy);
2507 // Move the insertion point just past the load so that we can refer to it.
2508 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
2510 V = convertValue(TD, IRB,
2511 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2515 V = IRB.CreateAlignedLoad(
2516 getAdjustedAllocaPtr(IRB, NarrowTy->getPointerTo()),
2517 getPartitionTypeAlign(NarrowTy), getName(".load"));
2518 // Create a placeholder value with the same type as LI to use as the
2519 // basis for the new value. This allows us to replace the uses of LI with
2520 // the computed value, and then replace the placeholder with LI, leaving
2521 // LI only used for this computation.
2523 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2524 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2525 getName(".insert"));
2526 LI.replaceAllUsesWith(V);
2527 Placeholder->replaceAllUsesWith(&LI);
2529 if (Pass.DeadSplitInsts.insert(&LI))
2530 Pass.DeadInsts.push_back(&LI);
2531 DEBUG(dbgs() << " to: " << *V << "\n");
2532 return IsConvertable;
2536 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
2537 if (IntTy && LI.getType()->isIntegerTy())
2538 return rewriteIntegerLoad(IRB, LI);
2540 if (BeginOffset == NewAllocaBeginOffset &&
2541 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2542 Value *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2543 LI.isVolatile(), getName(".load"));
2544 Value *NewV = convertValue(TD, IRB, NewLI, LI.getType());
2545 LI.replaceAllUsesWith(NewV);
2546 Pass.DeadInsts.push_back(&LI);
2548 DEBUG(dbgs() << " to: " << *NewLI << "\n");
2549 return !LI.isVolatile();
2552 assert(!IntTy && "Invalid load found with int-op widening enabled");
2554 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2555 LI.getPointerOperand()->getType());
2556 LI.setOperand(0, NewPtr);
2557 LI.setAlignment(getPartitionTypeAlign(LI.getType()));
2558 DEBUG(dbgs() << " to: " << LI << "\n");
2560 deleteIfTriviallyDead(OldOp);
2561 return NewPtr == &NewAI && !LI.isVolatile();
2564 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
2566 Value *V = SI.getValueOperand();
2567 if (V->getType() == ElementTy ||
2568 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2569 if (V->getType() != ElementTy)
2570 V = convertValue(TD, IRB, V, ElementTy);
2571 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2573 V = IRB.CreateInsertElement(LI, V, getIndex(IRB, BeginOffset),
2574 getName(".insert"));
2575 } else if (V->getType() != VecTy) {
2576 V = convertValue(TD, IRB, V, VecTy);
2578 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2579 Pass.DeadInsts.push_back(&SI);
2582 DEBUG(dbgs() << " to: " << *Store << "\n");
2586 bool rewriteIntegerStore(IRBuilder<> &IRB, StoreInst &SI) {
2587 assert(IntTy && "We cannot extract an integer from the alloca");
2588 assert(!SI.isVolatile());
2589 Value *V = SI.getValueOperand();
2590 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2591 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2592 getName(".oldload"));
2593 Old = convertValue(TD, IRB, Old, IntTy);
2594 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2595 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2596 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2597 getName(".insert"));
2599 V = convertValue(TD, IRB, V, NewAllocaTy);
2600 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2601 Pass.DeadInsts.push_back(&SI);
2603 DEBUG(dbgs() << " to: " << *Store << "\n");
2607 bool visitStoreInst(StoreInst &SI) {
2608 DEBUG(dbgs() << " original: " << SI << "\n");
2609 Value *OldOp = SI.getOperand(1);
2610 assert(OldOp == OldPtr);
2611 IRBuilder<> IRB(&SI);
2614 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
2615 Type *ValueTy = SI.getValueOperand()->getType();
2617 uint64_t Size = EndOffset - BeginOffset;
2618 if (Size < TD.getTypeStoreSize(ValueTy)) {
2619 assert(!SI.isVolatile());
2620 assert(ValueTy->isIntegerTy() &&
2621 "Only integer type loads and stores are split");
2622 assert(ValueTy->getIntegerBitWidth() ==
2623 TD.getTypeStoreSizeInBits(ValueTy) &&
2624 "Non-byte-multiple bit width");
2625 assert(ValueTy->getIntegerBitWidth() ==
2626 TD.getTypeSizeInBits(OldAI.getAllocatedType()) &&
2627 "Only alloca-wide stores can be split and recomposed");
2628 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2629 Value *V = extractInteger(TD, IRB, SI.getValueOperand(), NarrowTy,
2630 BeginOffset, getName(".extract"));
2632 bool IsConvertable = (BeginOffset - NewAllocaBeginOffset == 0) &&
2633 canConvertValue(TD, NarrowTy, NewAllocaTy);
2635 NewSI = IRB.CreateAlignedStore(convertValue(TD, IRB, V, NewAllocaTy),
2636 &NewAI, NewAI.getAlignment());
2638 NewSI = IRB.CreateAlignedStore(
2639 V, getAdjustedAllocaPtr(IRB, NarrowTy->getPointerTo()),
2640 getPartitionTypeAlign(NarrowTy));
2642 if (Pass.DeadSplitInsts.insert(&SI))
2643 Pass.DeadInsts.push_back(&SI);
2645 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2646 return IsConvertable;
2649 if (IntTy && ValueTy->isIntegerTy())
2650 return rewriteIntegerStore(IRB, SI);
2652 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2653 // alloca that should be re-examined after promoting this alloca.
2654 if (ValueTy->isPointerTy())
2655 if (AllocaInst *AI = dyn_cast<AllocaInst>(SI.getValueOperand()
2656 ->stripInBoundsOffsets()))
2657 Pass.PostPromotionWorklist.insert(AI);
2659 if (BeginOffset == NewAllocaBeginOffset &&
2660 canConvertValue(TD, ValueTy, NewAllocaTy)) {
2661 Value *NewV = convertValue(TD, IRB, SI.getValueOperand(), NewAllocaTy);
2662 StoreInst *NewSI = IRB.CreateAlignedStore(NewV, &NewAI, NewAI.getAlignment(),
2665 Pass.DeadInsts.push_back(&SI);
2667 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2668 return !SI.isVolatile();
2671 assert(!IntTy && "Invalid store found with int-op widening enabled");
2673 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2674 SI.getPointerOperand()->getType());
2675 SI.setOperand(1, NewPtr);
2676 SI.setAlignment(getPartitionTypeAlign(SI.getValueOperand()->getType()));
2677 DEBUG(dbgs() << " to: " << SI << "\n");
2679 deleteIfTriviallyDead(OldOp);
2680 return NewPtr == &NewAI && !SI.isVolatile();
2683 bool visitMemSetInst(MemSetInst &II) {
2684 DEBUG(dbgs() << " original: " << II << "\n");
2685 IRBuilder<> IRB(&II);
2686 assert(II.getRawDest() == OldPtr);
2688 // If the memset has a variable size, it cannot be split, just adjust the
2689 // pointer to the new alloca.
2690 if (!isa<Constant>(II.getLength())) {
2691 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2692 Type *CstTy = II.getAlignmentCst()->getType();
2693 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
2695 deleteIfTriviallyDead(OldPtr);
2699 // Record this instruction for deletion.
2700 if (Pass.DeadSplitInsts.insert(&II))
2701 Pass.DeadInsts.push_back(&II);
2703 Type *AllocaTy = NewAI.getAllocatedType();
2704 Type *ScalarTy = AllocaTy->getScalarType();
2706 // If this doesn't map cleanly onto the alloca type, and that type isn't
2707 // a single value type, just emit a memset.
2708 if (!VecTy && !IntTy &&
2709 (BeginOffset != NewAllocaBeginOffset ||
2710 EndOffset != NewAllocaEndOffset ||
2711 !AllocaTy->isSingleValueType() ||
2712 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
2713 Type *SizeTy = II.getLength()->getType();
2714 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2716 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2717 II.getRawDest()->getType()),
2718 II.getValue(), Size, getPartitionAlign(),
2721 DEBUG(dbgs() << " to: " << *New << "\n");
2725 // If we can represent this as a simple value, we have to build the actual
2726 // value to store, which requires expanding the byte present in memset to
2727 // a sensible representation for the alloca type. This is essentially
2728 // splatting the byte to a sufficiently wide integer, bitcasting to the
2729 // desired scalar type, and splatting it across any desired vector type.
2730 uint64_t Size = EndOffset - BeginOffset;
2731 Value *V = II.getValue();
2732 IntegerType *VTy = cast<IntegerType>(V->getType());
2733 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2734 if (Size*8 > VTy->getBitWidth())
2735 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
2736 ConstantExpr::getUDiv(
2737 Constant::getAllOnesValue(SplatIntTy),
2738 ConstantExpr::getZExt(
2739 Constant::getAllOnesValue(V->getType()),
2741 getName(".isplat"));
2743 // If this is an element-wide memset of a vectorizable alloca, insert it.
2744 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2745 EndOffset < NewAllocaEndOffset)) {
2746 if (V->getType() != ScalarTy)
2747 V = convertValue(TD, IRB, V, ScalarTy);
2748 StoreInst *Store = IRB.CreateAlignedStore(
2749 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2750 NewAI.getAlignment(),
2752 V, getIndex(IRB, BeginOffset),
2753 getName(".insert")),
2754 &NewAI, NewAI.getAlignment());
2756 DEBUG(dbgs() << " to: " << *Store << "\n");
2760 // If this is a memset on an alloca where we can widen stores, insert the
2762 if (IntTy && (BeginOffset > NewAllocaBeginOffset ||
2763 EndOffset < NewAllocaEndOffset)) {
2764 assert(!II.isVolatile());
2765 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2766 getName(".oldload"));
2767 Old = convertValue(TD, IRB, Old, IntTy);
2768 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2769 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2770 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
2773 if (V->getType() != AllocaTy)
2774 V = convertValue(TD, IRB, V, AllocaTy);
2776 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2779 DEBUG(dbgs() << " to: " << *New << "\n");
2780 return !II.isVolatile();
2783 bool visitMemTransferInst(MemTransferInst &II) {
2784 // Rewriting of memory transfer instructions can be a bit tricky. We break
2785 // them into two categories: split intrinsics and unsplit intrinsics.
2787 DEBUG(dbgs() << " original: " << II << "\n");
2788 IRBuilder<> IRB(&II);
2790 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2791 bool IsDest = II.getRawDest() == OldPtr;
2793 const AllocaPartitioning::MemTransferOffsets &MTO
2794 = P.getMemTransferOffsets(II);
2796 assert(OldPtr->getType()->isPointerTy() && "Must be a pointer type!");
2797 unsigned AS = cast<PointerType>(OldPtr->getType())->getAddressSpace();
2798 // Compute the relative offset within the transfer.
2799 unsigned IntPtrWidth = TD.getPointerSizeInBits(AS);
2800 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2801 : MTO.SourceBegin));
2803 unsigned Align = II.getAlignment();
2805 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2806 MinAlign(II.getAlignment(), getPartitionAlign()));
2808 // For unsplit intrinsics, we simply modify the source and destination
2809 // pointers in place. This isn't just an optimization, it is a matter of
2810 // correctness. With unsplit intrinsics we may be dealing with transfers
2811 // within a single alloca before SROA ran, or with transfers that have
2812 // a variable length. We may also be dealing with memmove instead of
2813 // memcpy, and so simply updating the pointers is the necessary for us to
2814 // update both source and dest of a single call.
2815 if (!MTO.IsSplittable) {
2816 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2818 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2820 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2822 Type *CstTy = II.getAlignmentCst()->getType();
2823 II.setAlignment(ConstantInt::get(CstTy, Align));
2825 DEBUG(dbgs() << " to: " << II << "\n");
2826 deleteIfTriviallyDead(OldOp);
2829 // For split transfer intrinsics we have an incredibly useful assurance:
2830 // the source and destination do not reside within the same alloca, and at
2831 // least one of them does not escape. This means that we can replace
2832 // memmove with memcpy, and we don't need to worry about all manner of
2833 // downsides to splitting and transforming the operations.
2835 // If this doesn't map cleanly onto the alloca type, and that type isn't
2836 // a single value type, just emit a memcpy.
2838 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2839 EndOffset != NewAllocaEndOffset ||
2840 !NewAI.getAllocatedType()->isSingleValueType());
2842 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2843 // size hasn't been shrunk based on analysis of the viable range, this is
2845 if (EmitMemCpy && &OldAI == &NewAI) {
2846 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2847 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2848 // Ensure the start lines up.
2849 assert(BeginOffset == OrigBegin);
2852 // Rewrite the size as needed.
2853 if (EndOffset != OrigEnd)
2854 II.setLength(ConstantInt::get(II.getLength()->getType(),
2855 EndOffset - BeginOffset));
2858 // Record this instruction for deletion.
2859 if (Pass.DeadSplitInsts.insert(&II))
2860 Pass.DeadInsts.push_back(&II);
2862 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2863 EndOffset == NewAllocaEndOffset;
2864 bool IsVectorElement = VecTy && !IsWholeAlloca;
2865 uint64_t Size = EndOffset - BeginOffset;
2866 IntegerType *SubIntTy
2867 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2869 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2870 : II.getRawDest()->getType();
2872 if (IsVectorElement)
2873 OtherPtrTy = VecTy->getElementType()->getPointerTo();
2874 else if (IntTy && !IsWholeAlloca)
2875 OtherPtrTy = SubIntTy->getPointerTo();
2877 OtherPtrTy = NewAI.getType();
2880 // Compute the other pointer, folding as much as possible to produce
2881 // a single, simple GEP in most cases.
2882 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2883 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2884 getName("." + OtherPtr->getName()));
2886 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2887 // alloca that should be re-examined after rewriting this instruction.
2889 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2890 Pass.Worklist.insert(AI);
2894 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2895 : II.getRawSource()->getType());
2896 Type *SizeTy = II.getLength()->getType();
2897 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2899 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2900 IsDest ? OtherPtr : OurPtr,
2901 Size, Align, II.isVolatile());
2903 DEBUG(dbgs() << " to: " << *New << "\n");
2907 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2908 // is equivalent to 1, but that isn't true if we end up rewriting this as
2913 Value *SrcPtr = OtherPtr;
2914 Value *DstPtr = &NewAI;
2916 std::swap(SrcPtr, DstPtr);
2919 if (IsVectorElement && !IsDest) {
2920 // We have to extract rather than load.
2921 Src = IRB.CreateExtractElement(
2922 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
2923 getIndex(IRB, BeginOffset),
2924 getName(".copyextract"));
2925 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2926 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2928 Src = convertValue(TD, IRB, Src, IntTy);
2929 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2930 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2931 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
2933 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2934 getName(".copyload"));
2937 if (IntTy && !IsWholeAlloca && IsDest) {
2938 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2939 getName(".oldload"));
2940 Old = convertValue(TD, IRB, Old, IntTy);
2941 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2942 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2943 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2944 Src = convertValue(TD, IRB, Src, NewAllocaTy);
2947 if (IsVectorElement && IsDest) {
2948 // We have to insert into a loaded copy before storing.
2949 Src = IRB.CreateInsertElement(
2950 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2951 Src, getIndex(IRB, BeginOffset),
2952 getName(".insert"));
2955 StoreInst *Store = cast<StoreInst>(
2956 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2958 DEBUG(dbgs() << " to: " << *Store << "\n");
2959 return !II.isVolatile();
2962 bool visitIntrinsicInst(IntrinsicInst &II) {
2963 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2964 II.getIntrinsicID() == Intrinsic::lifetime_end);
2965 DEBUG(dbgs() << " original: " << II << "\n");
2966 IRBuilder<> IRB(&II);
2967 assert(II.getArgOperand(1) == OldPtr);
2969 // Record this instruction for deletion.
2970 if (Pass.DeadSplitInsts.insert(&II))
2971 Pass.DeadInsts.push_back(&II);
2974 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2975 EndOffset - BeginOffset);
2976 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2978 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2979 New = IRB.CreateLifetimeStart(Ptr, Size);
2981 New = IRB.CreateLifetimeEnd(Ptr, Size);
2983 DEBUG(dbgs() << " to: " << *New << "\n");
2987 bool visitPHINode(PHINode &PN) {
2988 DEBUG(dbgs() << " original: " << PN << "\n");
2990 // We would like to compute a new pointer in only one place, but have it be
2991 // as local as possible to the PHI. To do that, we re-use the location of
2992 // the old pointer, which necessarily must be in the right position to
2993 // dominate the PHI.
2994 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2996 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2997 // Replace the operands which were using the old pointer.
2998 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3000 DEBUG(dbgs() << " to: " << PN << "\n");
3001 deleteIfTriviallyDead(OldPtr);
3005 bool visitSelectInst(SelectInst &SI) {
3006 DEBUG(dbgs() << " original: " << SI << "\n");
3007 IRBuilder<> IRB(&SI);
3009 // Find the operand we need to rewrite here.
3010 bool IsTrueVal = SI.getTrueValue() == OldPtr;
3012 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
3014 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
3016 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
3017 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
3018 DEBUG(dbgs() << " to: " << SI << "\n");
3019 deleteIfTriviallyDead(OldPtr);
3027 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
3029 /// This pass aggressively rewrites all aggregate loads and stores on
3030 /// a particular pointer (or any pointer derived from it which we can identify)
3031 /// with scalar loads and stores.
3032 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3033 // Befriend the base class so it can delegate to private visit methods.
3034 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3036 const DataLayout &TD;
3038 /// Queue of pointer uses to analyze and potentially rewrite.
3039 SmallVector<Use *, 8> Queue;
3041 /// Set to prevent us from cycling with phi nodes and loops.
3042 SmallPtrSet<User *, 8> Visited;
3044 /// The current pointer use being rewritten. This is used to dig up the used
3045 /// value (as opposed to the user).
3049 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
3051 /// Rewrite loads and stores through a pointer and all pointers derived from
3053 bool rewrite(Instruction &I) {
3054 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3056 bool Changed = false;
3057 while (!Queue.empty()) {
3058 U = Queue.pop_back_val();
3059 Changed |= visit(cast<Instruction>(U->getUser()));
3065 /// Enqueue all the users of the given instruction for further processing.
3066 /// This uses a set to de-duplicate users.
3067 void enqueueUsers(Instruction &I) {
3068 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3070 if (Visited.insert(*UI))
3071 Queue.push_back(&UI.getUse());
3074 // Conservative default is to not rewrite anything.
3075 bool visitInstruction(Instruction &I) { return false; }
3077 /// \brief Generic recursive split emission class.
3078 template <typename Derived>
3081 /// The builder used to form new instructions.
3083 /// The indices which to be used with insert- or extractvalue to select the
3084 /// appropriate value within the aggregate.
3085 SmallVector<unsigned, 4> Indices;
3086 /// The indices to a GEP instruction which will move Ptr to the correct slot
3087 /// within the aggregate.
3088 SmallVector<Value *, 4> GEPIndices;
3089 /// The base pointer of the original op, used as a base for GEPing the
3090 /// split operations.
3093 /// Initialize the splitter with an insertion point, Ptr and start with a
3094 /// single zero GEP index.
3095 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
3096 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3099 /// \brief Generic recursive split emission routine.
3101 /// This method recursively splits an aggregate op (load or store) into
3102 /// scalar or vector ops. It splits recursively until it hits a single value
3103 /// and emits that single value operation via the template argument.
3105 /// The logic of this routine relies on GEPs and insertvalue and
3106 /// extractvalue all operating with the same fundamental index list, merely
3107 /// formatted differently (GEPs need actual values).
3109 /// \param Ty The type being split recursively into smaller ops.
3110 /// \param Agg The aggregate value being built up or stored, depending on
3111 /// whether this is splitting a load or a store respectively.
3112 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3113 if (Ty->isSingleValueType())
3114 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
3116 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3117 unsigned OldSize = Indices.size();
3119 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3121 assert(Indices.size() == OldSize && "Did not return to the old size");
3122 Indices.push_back(Idx);
3123 GEPIndices.push_back(IRB.getInt32(Idx));
3124 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3125 GEPIndices.pop_back();
3131 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3132 unsigned OldSize = Indices.size();
3134 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3136 assert(Indices.size() == OldSize && "Did not return to the old size");
3137 Indices.push_back(Idx);
3138 GEPIndices.push_back(IRB.getInt32(Idx));
3139 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3140 GEPIndices.pop_back();
3146 llvm_unreachable("Only arrays and structs are aggregate loadable types");
3150 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3151 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3152 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
3154 /// Emit a leaf load of a single value. This is called at the leaves of the
3155 /// recursive emission to actually load values.
3156 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3157 assert(Ty->isSingleValueType());
3158 // Load the single value and insert it using the indices.
3159 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
3162 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3163 DEBUG(dbgs() << " to: " << *Load << "\n");
3167 bool visitLoadInst(LoadInst &LI) {
3168 assert(LI.getPointerOperand() == *U);
3169 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3172 // We have an aggregate being loaded, split it apart.
3173 DEBUG(dbgs() << " original: " << LI << "\n");
3174 LoadOpSplitter Splitter(&LI, *U);
3175 Value *V = UndefValue::get(LI.getType());
3176 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3177 LI.replaceAllUsesWith(V);
3178 LI.eraseFromParent();
3182 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
3183 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3184 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
3186 /// Emit a leaf store of a single value. This is called at the leaves of the
3187 /// recursive emission to actually produce stores.
3188 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3189 assert(Ty->isSingleValueType());
3190 // Extract the single value and store it using the indices.
3191 Value *Store = IRB.CreateStore(
3192 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3193 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3195 DEBUG(dbgs() << " to: " << *Store << "\n");
3199 bool visitStoreInst(StoreInst &SI) {
3200 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3202 Value *V = SI.getValueOperand();
3203 if (V->getType()->isSingleValueType())
3206 // We have an aggregate being stored, split it apart.
3207 DEBUG(dbgs() << " original: " << SI << "\n");
3208 StoreOpSplitter Splitter(&SI, *U);
3209 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3210 SI.eraseFromParent();
3214 bool visitBitCastInst(BitCastInst &BC) {
3219 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3224 bool visitPHINode(PHINode &PN) {
3229 bool visitSelectInst(SelectInst &SI) {
3236 /// \brief Strip aggregate type wrapping.
3238 /// This removes no-op aggregate types wrapping an underlying type. It will
3239 /// strip as many layers of types as it can without changing either the type
3240 /// size or the allocated size.
3241 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3242 if (Ty->isSingleValueType())
3245 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3246 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3249 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3250 InnerTy = ArrTy->getElementType();
3251 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3252 const StructLayout *SL = DL.getStructLayout(STy);
3253 unsigned Index = SL->getElementContainingOffset(0);
3254 InnerTy = STy->getElementType(Index);
3259 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3260 TypeSize > DL.getTypeSizeInBits(InnerTy))
3263 return stripAggregateTypeWrapping(DL, InnerTy);
3266 /// \brief Try to find a partition of the aggregate type passed in for a given
3267 /// offset and size.
3269 /// This recurses through the aggregate type and tries to compute a subtype
3270 /// based on the offset and size. When the offset and size span a sub-section
3271 /// of an array, it will even compute a new array type for that sub-section,
3272 /// and the same for structs.
3274 /// Note that this routine is very strict and tries to find a partition of the
3275 /// type which produces the *exact* right offset and size. It is not forgiving
3276 /// when the size or offset cause either end of type-based partition to be off.
3277 /// Also, this is a best-effort routine. It is reasonable to give up and not
3278 /// return a type if necessary.
3279 static Type *getTypePartition(const DataLayout &TD, Type *Ty,
3280 uint64_t Offset, uint64_t Size) {
3281 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
3282 return stripAggregateTypeWrapping(TD, Ty);
3283 if (Offset > TD.getTypeAllocSize(Ty) ||
3284 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3287 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3288 // We can't partition pointers...
3289 if (SeqTy->isPointerTy())
3292 Type *ElementTy = SeqTy->getElementType();
3293 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3294 uint64_t NumSkippedElements = Offset / ElementSize;
3295 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3296 if (NumSkippedElements >= ArrTy->getNumElements())
3298 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3299 if (NumSkippedElements >= VecTy->getNumElements())
3301 Offset -= NumSkippedElements * ElementSize;
3303 // First check if we need to recurse.
3304 if (Offset > 0 || Size < ElementSize) {
3305 // Bail if the partition ends in a different array element.
3306 if ((Offset + Size) > ElementSize)
3308 // Recurse through the element type trying to peel off offset bytes.
3309 return getTypePartition(TD, ElementTy, Offset, Size);
3311 assert(Offset == 0);
3313 if (Size == ElementSize)
3314 return stripAggregateTypeWrapping(TD, ElementTy);
3315 assert(Size > ElementSize);
3316 uint64_t NumElements = Size / ElementSize;
3317 if (NumElements * ElementSize != Size)
3319 return ArrayType::get(ElementTy, NumElements);
3322 StructType *STy = dyn_cast<StructType>(Ty);
3326 const StructLayout *SL = TD.getStructLayout(STy);
3327 if (Offset >= SL->getSizeInBytes())
3329 uint64_t EndOffset = Offset + Size;
3330 if (EndOffset > SL->getSizeInBytes())
3333 unsigned Index = SL->getElementContainingOffset(Offset);
3334 Offset -= SL->getElementOffset(Index);
3336 Type *ElementTy = STy->getElementType(Index);
3337 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3338 if (Offset >= ElementSize)
3339 return 0; // The offset points into alignment padding.
3341 // See if any partition must be contained by the element.
3342 if (Offset > 0 || Size < ElementSize) {
3343 if ((Offset + Size) > ElementSize)
3345 return getTypePartition(TD, ElementTy, Offset, Size);
3347 assert(Offset == 0);
3349 if (Size == ElementSize)
3350 return stripAggregateTypeWrapping(TD, ElementTy);
3352 StructType::element_iterator EI = STy->element_begin() + Index,
3353 EE = STy->element_end();
3354 if (EndOffset < SL->getSizeInBytes()) {
3355 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3356 if (Index == EndIndex)
3357 return 0; // Within a single element and its padding.
3359 // Don't try to form "natural" types if the elements don't line up with the
3361 // FIXME: We could potentially recurse down through the last element in the
3362 // sub-struct to find a natural end point.
3363 if (SL->getElementOffset(EndIndex) != EndOffset)
3366 assert(Index < EndIndex);
3367 EE = STy->element_begin() + EndIndex;
3370 // Try to build up a sub-structure.
3371 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
3373 const StructLayout *SubSL = TD.getStructLayout(SubTy);
3374 if (Size != SubSL->getSizeInBytes())
3375 return 0; // The sub-struct doesn't have quite the size needed.
3380 /// \brief Rewrite an alloca partition's users.
3382 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3383 /// to rewrite uses of an alloca partition to be conducive for SSA value
3384 /// promotion. If the partition needs a new, more refined alloca, this will
3385 /// build that new alloca, preserving as much type information as possible, and
3386 /// rewrite the uses of the old alloca to point at the new one and have the
3387 /// appropriate new offsets. It also evaluates how successful the rewrite was
3388 /// at enabling promotion and if it was successful queues the alloca to be
3390 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3391 AllocaPartitioning &P,
3392 AllocaPartitioning::iterator PI) {
3393 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
3394 bool IsLive = false;
3395 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3397 UI != UE && !IsLive; ++UI)
3401 return false; // No live uses left of this partition.
3403 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3404 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3406 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3407 DEBUG(dbgs() << " speculating ");
3408 DEBUG(P.print(dbgs(), PI, ""));
3409 Speculator.visitUsers(PI);
3411 // Try to compute a friendly type for this partition of the alloca. This
3412 // won't always succeed, in which case we fall back to a legal integer type
3413 // or an i8 array of an appropriate size.
3415 if (Type *PartitionTy = P.getCommonType(PI))
3416 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3417 AllocaTy = PartitionTy;
3419 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3420 PI->BeginOffset, AllocaSize))
3421 AllocaTy = PartitionTy;
3423 (AllocaTy->isArrayTy() &&
3424 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3425 TD->isLegalInteger(AllocaSize * 8))
3426 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3428 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
3429 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
3431 // Check for the case where we're going to rewrite to a new alloca of the
3432 // exact same type as the original, and with the same access offsets. In that
3433 // case, re-use the existing alloca, but still run through the rewriter to
3434 // performe phi and select speculation.
3436 if (AllocaTy == AI.getAllocatedType()) {
3437 assert(PI->BeginOffset == 0 &&
3438 "Non-zero begin offset but same alloca type");
3439 assert(PI == P.begin() && "Begin offset is zero on later partition");
3442 unsigned Alignment = AI.getAlignment();
3444 // The minimum alignment which users can rely on when the explicit
3445 // alignment is omitted or zero is that required by the ABI for this
3447 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3449 Alignment = MinAlign(Alignment, PI->BeginOffset);
3450 // If we will get at least this much alignment from the type alone, leave
3451 // the alloca's alignment unconstrained.
3452 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3454 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
3455 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3460 DEBUG(dbgs() << "Rewriting alloca partition "
3461 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3464 // Track the high watermark of the post-promotion worklist. We will reset it
3465 // to this point if the alloca is not in fact scheduled for promotion.
3466 unsigned PPWOldSize = PostPromotionWorklist.size();
3468 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3469 PI->BeginOffset, PI->EndOffset);
3470 DEBUG(dbgs() << " rewriting ");
3471 DEBUG(P.print(dbgs(), PI, ""));
3472 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3474 DEBUG(dbgs() << " and queuing for promotion\n");
3475 PromotableAllocas.push_back(NewAI);
3476 } else if (NewAI != &AI) {
3477 // If we can't promote the alloca, iterate on it to check for new
3478 // refinements exposed by splitting the current alloca. Don't iterate on an
3479 // alloca which didn't actually change and didn't get promoted.
3480 Worklist.insert(NewAI);
3483 // Drop any post-promotion work items if promotion didn't happen.
3485 while (PostPromotionWorklist.size() > PPWOldSize)
3486 PostPromotionWorklist.pop_back();
3491 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3492 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3493 bool Changed = false;
3494 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3496 Changed |= rewriteAllocaPartition(AI, P, PI);
3501 /// \brief Analyze an alloca for SROA.
3503 /// This analyzes the alloca to ensure we can reason about it, builds
3504 /// a partitioning of the alloca, and then hands it off to be split and
3505 /// rewritten as needed.
3506 bool SROA::runOnAlloca(AllocaInst &AI) {
3507 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3508 ++NumAllocasAnalyzed;
3510 // Special case dead allocas, as they're trivial.
3511 if (AI.use_empty()) {
3512 AI.eraseFromParent();
3516 // Skip alloca forms that this analysis can't handle.
3517 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3518 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3521 bool Changed = false;
3523 // First, split any FCA loads and stores touching this alloca to promote
3524 // better splitting and promotion opportunities.
3525 AggLoadStoreRewriter AggRewriter(*TD);
3526 Changed |= AggRewriter.rewrite(AI);
3528 // Build the partition set using a recursive instruction-visiting builder.
3529 AllocaPartitioning P(*TD, AI);
3530 DEBUG(P.print(dbgs()));
3534 // Delete all the dead users of this alloca before splitting and rewriting it.
3535 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3536 DE = P.dead_user_end();
3539 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3540 DeadInsts.push_back(*DI);
3542 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3543 DE = P.dead_op_end();
3546 // Clobber the use with an undef value.
3547 **DO = UndefValue::get(OldV->getType());
3548 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3549 if (isInstructionTriviallyDead(OldI)) {
3551 DeadInsts.push_back(OldI);
3555 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3556 if (P.begin() == P.end())
3559 return splitAlloca(AI, P) || Changed;
3562 /// \brief Delete the dead instructions accumulated in this run.
3564 /// Recursively deletes the dead instructions we've accumulated. This is done
3565 /// at the very end to maximize locality of the recursive delete and to
3566 /// minimize the problems of invalidated instruction pointers as such pointers
3567 /// are used heavily in the intermediate stages of the algorithm.
3569 /// We also record the alloca instructions deleted here so that they aren't
3570 /// subsequently handed to mem2reg to promote.
3571 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3572 DeadSplitInsts.clear();
3573 while (!DeadInsts.empty()) {
3574 Instruction *I = DeadInsts.pop_back_val();
3575 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3577 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3579 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3580 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3581 // Zero out the operand and see if it becomes trivially dead.
3583 if (isInstructionTriviallyDead(U))
3584 DeadInsts.push_back(U);
3587 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3588 DeletedAllocas.insert(AI);
3591 I->eraseFromParent();
3595 /// \brief Promote the allocas, using the best available technique.
3597 /// This attempts to promote whatever allocas have been identified as viable in
3598 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3599 /// If there is a domtree available, we attempt to promote using the full power
3600 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3601 /// based on the SSAUpdater utilities. This function returns whether any
3602 /// promotion occured.
3603 bool SROA::promoteAllocas(Function &F) {
3604 if (PromotableAllocas.empty())
3607 NumPromoted += PromotableAllocas.size();
3609 if (DT && !ForceSSAUpdater) {
3610 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3611 PromoteMemToReg(PromotableAllocas, *DT);
3612 PromotableAllocas.clear();
3616 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3618 DIBuilder DIB(*F.getParent());
3619 SmallVector<Instruction*, 64> Insts;
3621 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3622 AllocaInst *AI = PromotableAllocas[Idx];
3623 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3625 Instruction *I = cast<Instruction>(*UI++);
3626 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3627 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3628 // leading to them) here. Eventually it should use them to optimize the
3629 // scalar values produced.
3630 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3631 assert(onlyUsedByLifetimeMarkers(I) &&
3632 "Found a bitcast used outside of a lifetime marker.");
3633 while (!I->use_empty())
3634 cast<Instruction>(*I->use_begin())->eraseFromParent();
3635 I->eraseFromParent();
3638 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3639 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3640 II->getIntrinsicID() == Intrinsic::lifetime_end);
3641 II->eraseFromParent();
3647 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3651 PromotableAllocas.clear();
3656 /// \brief A predicate to test whether an alloca belongs to a set.
3657 class IsAllocaInSet {
3658 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3662 typedef AllocaInst *argument_type;
3664 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3665 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
3669 bool SROA::runOnFunction(Function &F) {
3670 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3671 C = &F.getContext();
3672 TD = getAnalysisIfAvailable<DataLayout>();
3674 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3677 DT = getAnalysisIfAvailable<DominatorTree>();
3679 BasicBlock &EntryBB = F.getEntryBlock();
3680 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3682 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3683 Worklist.insert(AI);
3685 bool Changed = false;
3686 // A set of deleted alloca instruction pointers which should be removed from
3687 // the list of promotable allocas.
3688 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3691 while (!Worklist.empty()) {
3692 Changed |= runOnAlloca(*Worklist.pop_back_val());
3693 deleteDeadInstructions(DeletedAllocas);
3695 // Remove the deleted allocas from various lists so that we don't try to
3696 // continue processing them.
3697 if (!DeletedAllocas.empty()) {
3698 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3699 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3700 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3701 PromotableAllocas.end(),
3702 IsAllocaInSet(DeletedAllocas)),
3703 PromotableAllocas.end());
3704 DeletedAllocas.clear();
3708 Changed |= promoteAllocas(F);
3710 Worklist = PostPromotionWorklist;
3711 PostPromotionWorklist.clear();
3712 } while (!Worklist.empty());
3717 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3718 if (RequiresDomTree)
3719 AU.addRequired<DominatorTree>();
3720 AU.setPreservesCFG();