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/InstVisitor.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/IntrinsicInst.h"
37 #include "llvm/LLVMContext.h"
38 #include "llvm/Module.h"
39 #include "llvm/Operator.h"
40 #include "llvm/Pass.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/Analysis/Dominators.h"
46 #include "llvm/Analysis/Loads.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/GetElementPtrTypeIterator.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/DataLayout.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
57 #include "llvm/Transforms/Utils/SSAUpdater.h"
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;
337 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
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 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
449 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
455 // Handle a struct index, which adds its field offset to the pointer.
456 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
457 unsigned ElementIdx = OpC->getZExtValue();
458 const StructLayout *SL = TD.getStructLayout(STy);
459 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
460 // Check that we can continue to model this GEP in a signed 64-bit offset.
461 if (ElementOffset > INT64_MAX ||
463 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
464 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
465 << "what can be represented in an int64_t!\n"
466 << " alloca: " << P.AI << "\n");
470 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
472 GEPOffset += ElementOffset;
476 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
477 Index *= APInt(Index.getBitWidth(),
478 TD.getTypeAllocSize(GTI.getIndexedType()));
479 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
481 // Check if the result can be stored in our int64_t offset.
482 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
483 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
484 << "what can be represented in an int64_t!\n"
485 << " alloca: " << P.AI << "\n");
489 GEPOffset = Index.getSExtValue();
494 Value *foldSelectInst(SelectInst &SI) {
495 // If the condition being selected on is a constant or the same value is
496 // being selected between, fold the select. Yes this does (rarely) happen
498 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
499 return SI.getOperand(1+CI->isZero());
500 if (SI.getOperand(1) == SI.getOperand(2)) {
501 assert(*U == SI.getOperand(1));
502 return SI.getOperand(1);
508 /// \brief Builder for the alloca partitioning.
510 /// This class builds an alloca partitioning by recursively visiting the uses
511 /// of an alloca and splitting the partitions for each load and store at each
513 class AllocaPartitioning::PartitionBuilder
514 : public BuilderBase<PartitionBuilder, bool> {
515 friend class InstVisitor<PartitionBuilder, bool>;
517 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
520 PartitionBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
521 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
523 /// \brief Run the builder over the allocation.
525 // Note that we have to re-evaluate size on each trip through the loop as
526 // the queue grows at the tail.
527 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
529 Offset = Queue[Idx].Offset;
530 if (!visit(cast<Instruction>(U->getUser())))
537 bool markAsEscaping(Instruction &I) {
538 P.PointerEscapingInstr = &I;
542 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
543 bool IsSplittable = false) {
544 // Completely skip uses which have a zero size or start either before or
545 // past the end of the allocation.
546 if (Size == 0 || Offset < 0 || (uint64_t)Offset >= AllocSize) {
547 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
548 << " which has zero size or starts outside of the "
549 << AllocSize << " byte alloca:\n"
550 << " alloca: " << P.AI << "\n"
551 << " use: " << I << "\n");
555 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
557 // Clamp the end offset to the end of the allocation. Note that this is
558 // formulated to handle even the case where "BeginOffset + Size" overflows.
559 // NOTE! This may appear superficially to be something we could ignore
560 // entirely, but that is not so! There may be PHI-node uses where some
561 // instructions are dead but not others. We can't completely ignore the
562 // PHI node, and so have to record at least the information here.
563 assert(AllocSize >= BeginOffset); // Established above.
564 if (Size > AllocSize - BeginOffset) {
565 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
566 << " to remain within the " << AllocSize << " byte alloca:\n"
567 << " alloca: " << P.AI << "\n"
568 << " use: " << I << "\n");
569 EndOffset = AllocSize;
572 Partition New(BeginOffset, EndOffset, IsSplittable);
573 P.Partitions.push_back(New);
576 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset,
578 uint64_t Size = TD.getTypeStoreSize(Ty);
580 // If this memory access can be shown to *statically* extend outside the
581 // bounds of of the allocation, it's behavior is undefined, so simply
582 // ignore it. Note that this is more strict than the generic clamping
583 // behavior of insertUse. We also try to handle cases which might run the
585 // FIXME: We should instead consider the pointer to have escaped if this
586 // function is being instrumented for addressing bugs or race conditions.
587 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
588 Size > (AllocSize - (uint64_t)Offset)) {
589 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
590 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
591 << " which extends past the end of the " << AllocSize
593 << " alloca: " << P.AI << "\n"
594 << " use: " << I << "\n");
598 // We allow splitting of loads and stores where the type is an integer type
599 // and which cover the entire alloca. Such integer loads and stores
600 // often require decomposition into fine grained loads and stores.
601 bool IsSplittable = false;
602 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
603 IsSplittable = !IsVolatile && ITy->getBitWidth() == AllocSize*8;
605 insertUse(I, Offset, Size, IsSplittable);
609 bool visitBitCastInst(BitCastInst &BC) {
610 enqueueUsers(BC, Offset);
614 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
616 if (!computeConstantGEPOffset(GEPI, GEPOffset))
617 return markAsEscaping(GEPI);
619 enqueueUsers(GEPI, GEPOffset);
623 bool visitLoadInst(LoadInst &LI) {
624 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
625 "All simple FCA loads should have been pre-split");
626 return handleLoadOrStore(LI.getType(), LI, Offset, LI.isVolatile());
629 bool visitStoreInst(StoreInst &SI) {
630 Value *ValOp = SI.getValueOperand();
632 return markAsEscaping(SI);
634 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
635 "All simple FCA stores should have been pre-split");
636 return handleLoadOrStore(ValOp->getType(), SI, Offset, SI.isVolatile());
640 bool visitMemSetInst(MemSetInst &II) {
641 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
642 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
643 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
644 insertUse(II, Offset, Size, Length);
648 bool visitMemTransferInst(MemTransferInst &II) {
649 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
650 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
652 // Zero-length mem transfer intrinsics can be ignored entirely.
655 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
657 // Only intrinsics with a constant length can be split.
658 Offsets.IsSplittable = Length;
660 if (*U == II.getRawDest()) {
661 Offsets.DestBegin = Offset;
662 Offsets.DestEnd = Offset + Size;
664 if (*U == II.getRawSource()) {
665 Offsets.SourceBegin = Offset;
666 Offsets.SourceEnd = Offset + Size;
669 // If we have set up end offsets for both the source and the destination,
670 // we have found both sides of this transfer pointing at the same alloca.
671 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
672 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
673 unsigned PrevIdx = MemTransferPartitionMap[&II];
675 // Check if the begin offsets match and this is a non-volatile transfer.
676 // In that case, we can completely elide the transfer.
677 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
678 P.Partitions[PrevIdx].kill();
682 // Otherwise we have an offset transfer within the same alloca. We can't
684 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
685 } else if (SeenBothEnds) {
686 // Handle the case where this exact use provides both ends of the
688 assert(II.getRawDest() == II.getRawSource());
690 // For non-volatile transfers this is a no-op.
691 if (!II.isVolatile())
694 // Otherwise just suppress splitting.
695 Offsets.IsSplittable = false;
699 // Insert the use now that we've fixed up the splittable nature.
700 insertUse(II, Offset, Size, Offsets.IsSplittable);
702 // Setup the mapping from intrinsic to partition of we've not seen both
703 // ends of this transfer.
705 unsigned NewIdx = P.Partitions.size() - 1;
707 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
709 "Already have intrinsic in map but haven't seen both ends");
716 // Disable SRoA for any intrinsics except for lifetime invariants.
717 // FIXME: What about debug instrinsics? This matches old behavior, but
718 // doesn't make sense.
719 bool visitIntrinsicInst(IntrinsicInst &II) {
720 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
721 II.getIntrinsicID() == Intrinsic::lifetime_end) {
722 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
723 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
724 insertUse(II, Offset, Size, true);
728 return markAsEscaping(II);
731 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
732 // We consider any PHI or select that results in a direct load or store of
733 // the same offset to be a viable use for partitioning purposes. These uses
734 // are considered unsplittable and the size is the maximum loaded or stored
736 SmallPtrSet<Instruction *, 4> Visited;
737 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
738 Visited.insert(Root);
739 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
740 // If there are no loads or stores, the access is dead. We mark that as
741 // a size zero access.
744 Instruction *I, *UsedI;
745 llvm::tie(UsedI, I) = Uses.pop_back_val();
747 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
748 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
751 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
752 Value *Op = SI->getOperand(0);
755 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
759 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
760 if (!GEP->hasAllZeroIndices())
762 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
763 !isa<SelectInst>(I)) {
767 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
769 if (Visited.insert(cast<Instruction>(*UI)))
770 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
771 } while (!Uses.empty());
776 bool visitPHINode(PHINode &PN) {
777 // See if we already have computed info on this node.
778 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
780 PHIInfo.second = true;
781 insertUse(PN, Offset, PHIInfo.first);
785 // Check for an unsafe use of the PHI node.
786 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
787 return markAsEscaping(*EscapingI);
789 insertUse(PN, Offset, PHIInfo.first);
793 bool visitSelectInst(SelectInst &SI) {
794 if (Value *Result = foldSelectInst(SI)) {
796 // If the result of the constant fold will be the pointer, recurse
797 // through the select as if we had RAUW'ed it.
798 enqueueUsers(SI, Offset);
803 // See if we already have computed info on this node.
804 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
805 if (SelectInfo.first) {
806 SelectInfo.second = true;
807 insertUse(SI, Offset, SelectInfo.first);
811 // Check for an unsafe use of the PHI node.
812 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
813 return markAsEscaping(*EscapingI);
815 insertUse(SI, Offset, SelectInfo.first);
819 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
820 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
824 /// \brief Use adder for the alloca partitioning.
826 /// This class adds the uses of an alloca to all of the partitions which they
827 /// use. For splittable partitions, this can end up doing essentially a linear
828 /// walk of the partitions, but the number of steps remains bounded by the
829 /// total result instruction size:
830 /// - The number of partitions is a result of the number unsplittable
831 /// instructions using the alloca.
832 /// - The number of users of each partition is at worst the total number of
833 /// splittable instructions using the alloca.
834 /// Thus we will produce N * M instructions in the end, where N are the number
835 /// of unsplittable uses and M are the number of splittable. This visitor does
836 /// the exact same number of updates to the partitioning.
838 /// In the more common case, this visitor will leverage the fact that the
839 /// partition space is pre-sorted, and do a logarithmic search for the
840 /// partition needed, making the total visit a classical ((N + M) * log(N))
841 /// complexity operation.
842 class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
843 friend class InstVisitor<UseBuilder>;
845 /// \brief Set to de-duplicate dead instructions found in the use walk.
846 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
849 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
850 : BuilderBase<UseBuilder>(TD, AI, P) {}
852 /// \brief Run the builder over the allocation.
854 // Note that we have to re-evaluate size on each trip through the loop as
855 // the queue grows at the tail.
856 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
858 Offset = Queue[Idx].Offset;
859 this->visit(cast<Instruction>(U->getUser()));
864 void markAsDead(Instruction &I) {
865 if (VisitedDeadInsts.insert(&I))
866 P.DeadUsers.push_back(&I);
869 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
870 // If the use has a zero size or extends outside of the allocation, record
871 // it as a dead use for elimination later.
872 if (Size == 0 || Offset < 0 || (uint64_t)Offset >= AllocSize)
873 return markAsDead(User);
875 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
877 // Clamp the end offset to the end of the allocation. Note that this is
878 // formulated to handle even the case where "BeginOffset + Size" overflows.
879 assert(AllocSize >= BeginOffset); // Established above.
880 if (Size > AllocSize - BeginOffset)
881 EndOffset = AllocSize;
883 // NB: This only works if we have zero overlapping partitions.
884 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
885 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
887 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
889 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
890 std::min(I->EndOffset, EndOffset), U);
891 P.use_push_back(I, NewPU);
892 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
893 P.PHIOrSelectOpMap[U]
894 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
898 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
899 uint64_t Size = TD.getTypeStoreSize(Ty);
901 // If this memory access can be shown to *statically* extend outside the
902 // bounds of of the allocation, it's behavior is undefined, so simply
903 // ignore it. Note that this is more strict than the generic clamping
904 // behavior of insertUse.
905 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
906 Size > (AllocSize - (uint64_t)Offset))
907 return markAsDead(I);
909 insertUse(I, Offset, Size);
912 void visitBitCastInst(BitCastInst &BC) {
914 return markAsDead(BC);
916 enqueueUsers(BC, Offset);
919 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
920 if (GEPI.use_empty())
921 return markAsDead(GEPI);
924 if (!computeConstantGEPOffset(GEPI, GEPOffset))
925 llvm_unreachable("Unable to compute constant offset for use");
927 enqueueUsers(GEPI, GEPOffset);
930 void visitLoadInst(LoadInst &LI) {
931 handleLoadOrStore(LI.getType(), LI, Offset);
934 void visitStoreInst(StoreInst &SI) {
935 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
938 void visitMemSetInst(MemSetInst &II) {
939 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
940 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
941 insertUse(II, Offset, Size);
944 void visitMemTransferInst(MemTransferInst &II) {
945 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
946 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
948 return markAsDead(II);
950 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
951 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
952 Offsets.DestBegin == Offsets.SourceBegin)
953 return markAsDead(II); // Skip identity transfers without side-effects.
955 insertUse(II, Offset, Size);
958 void visitIntrinsicInst(IntrinsicInst &II) {
959 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
960 II.getIntrinsicID() == Intrinsic::lifetime_end);
962 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
963 insertUse(II, Offset,
964 std::min(AllocSize - Offset, Length->getLimitedValue()));
967 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
968 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
970 // For PHI and select operands outside the alloca, we can't nuke the entire
971 // phi or select -- the other side might still be relevant, so we special
972 // case them here and use a separate structure to track the operands
973 // themselves which should be replaced with undef.
974 if (Offset >= AllocSize) {
975 P.DeadOperands.push_back(U);
979 insertUse(User, Offset, Size);
981 void visitPHINode(PHINode &PN) {
983 return markAsDead(PN);
985 insertPHIOrSelect(PN, Offset);
987 void visitSelectInst(SelectInst &SI) {
989 return markAsDead(SI);
991 if (Value *Result = foldSelectInst(SI)) {
993 // If the result of the constant fold will be the pointer, recurse
994 // through the select as if we had RAUW'ed it.
995 enqueueUsers(SI, Offset);
997 // Otherwise the operand to the select is dead, and we can replace it
999 P.DeadOperands.push_back(U);
1004 insertPHIOrSelect(SI, Offset);
1007 /// \brief Unreachable, we've already visited the alloca once.
1008 void visitInstruction(Instruction &I) {
1009 llvm_unreachable("Unhandled instruction in use builder.");
1013 void AllocaPartitioning::splitAndMergePartitions() {
1014 size_t NumDeadPartitions = 0;
1016 // Track the range of splittable partitions that we pass when accumulating
1017 // overlapping unsplittable partitions.
1018 uint64_t SplitEndOffset = 0ull;
1020 Partition New(0ull, 0ull, false);
1022 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
1025 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
1026 assert(New.BeginOffset == New.EndOffset);
1027 New = Partitions[i];
1029 assert(New.IsSplittable);
1030 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
1032 assert(New.BeginOffset != New.EndOffset);
1034 // Scan the overlapping partitions.
1035 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
1036 // If the new partition we are forming is splittable, stop at the first
1037 // unsplittable partition.
1038 if (New.IsSplittable && !Partitions[j].IsSplittable)
1041 // Grow the new partition to include any equally splittable range. 'j' is
1042 // always equally splittable when New is splittable, but when New is not
1043 // splittable, we may subsume some (or part of some) splitable partition
1044 // without growing the new one.
1045 if (New.IsSplittable == Partitions[j].IsSplittable) {
1046 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1048 assert(!New.IsSplittable);
1049 assert(Partitions[j].IsSplittable);
1050 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1053 Partitions[j].kill();
1054 ++NumDeadPartitions;
1058 // If the new partition is splittable, chop off the end as soon as the
1059 // unsplittable subsequent partition starts and ensure we eventually cover
1060 // the splittable area.
1061 if (j != e && New.IsSplittable) {
1062 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1063 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1066 // Add the new partition if it differs from the original one and is
1067 // non-empty. We can end up with an empty partition here if it was
1068 // splittable but there is an unsplittable one that starts at the same
1070 if (New != Partitions[i]) {
1071 if (New.BeginOffset != New.EndOffset)
1072 Partitions.push_back(New);
1073 // Mark the old one for removal.
1074 Partitions[i].kill();
1075 ++NumDeadPartitions;
1078 New.BeginOffset = New.EndOffset;
1079 if (!New.IsSplittable) {
1080 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1081 if (j != e && !Partitions[j].IsSplittable)
1082 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1083 New.IsSplittable = true;
1084 // If there is a trailing splittable partition which won't be fused into
1085 // the next splittable partition go ahead and add it onto the partitions
1087 if (New.BeginOffset < New.EndOffset &&
1088 (j == e || !Partitions[j].IsSplittable ||
1089 New.EndOffset < Partitions[j].BeginOffset)) {
1090 Partitions.push_back(New);
1091 New.BeginOffset = New.EndOffset = 0ull;
1096 // Re-sort the partitions now that they have been split and merged into
1097 // disjoint set of partitions. Also remove any of the dead partitions we've
1098 // replaced in the process.
1099 std::sort(Partitions.begin(), Partitions.end());
1100 if (NumDeadPartitions) {
1101 assert(Partitions.back().isDead());
1102 assert((ptrdiff_t)NumDeadPartitions ==
1103 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1105 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1108 AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
1110 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1113 PointerEscapingInstr(0) {
1114 PartitionBuilder PB(TD, AI, *this);
1118 // Sort the uses. This arranges for the offsets to be in ascending order,
1119 // and the sizes to be in descending order.
1120 std::sort(Partitions.begin(), Partitions.end());
1122 // Remove any partitions from the back which are marked as dead.
1123 while (!Partitions.empty() && Partitions.back().isDead())
1124 Partitions.pop_back();
1126 if (Partitions.size() > 1) {
1127 // Intersect splittability for all partitions with equal offsets and sizes.
1128 // Then remove all but the first so that we have a sequence of non-equal but
1129 // potentially overlapping partitions.
1130 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1133 while (J != E && *I == *J) {
1134 I->IsSplittable &= J->IsSplittable;
1138 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1141 // Split splittable and merge unsplittable partitions into a disjoint set
1142 // of partitions over the used space of the allocation.
1143 splitAndMergePartitions();
1146 // Now build up the user lists for each of these disjoint partitions by
1147 // re-walking the recursive users of the alloca.
1148 Uses.resize(Partitions.size());
1149 UseBuilder UB(TD, AI, *this);
1153 Type *AllocaPartitioning::getCommonType(iterator I) const {
1155 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1157 continue; // Skip dead uses.
1158 if (isa<IntrinsicInst>(*UI->U->getUser()))
1160 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1164 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
1165 UserTy = LI->getType();
1166 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
1167 UserTy = SI->getValueOperand()->getType();
1169 return 0; // Bail if we have weird uses.
1172 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1173 // If the type is larger than the partition, skip it. We only encounter
1174 // this for split integer operations where we want to use the type of the
1175 // entity causing the split.
1176 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1179 // If we have found an integer type use covering the alloca, use that
1180 // regardless of the other types, as integers are often used for a "bucket
1185 if (Ty && Ty != UserTy)
1193 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1195 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1196 StringRef Indent) const {
1197 OS << Indent << "partition #" << (I - begin())
1198 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1199 << (I->IsSplittable ? " (splittable)" : "")
1200 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1204 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1205 StringRef Indent) const {
1206 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1209 continue; // Skip dead uses.
1210 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1211 << "used by: " << *UI->U->getUser() << "\n";
1212 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
1213 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1215 if (!MTO.IsSplittable)
1216 IsDest = UI->BeginOffset == MTO.DestBegin;
1218 IsDest = MTO.DestBegin != 0u;
1219 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1220 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1221 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1226 void AllocaPartitioning::print(raw_ostream &OS) const {
1227 if (PointerEscapingInstr) {
1228 OS << "No partitioning for alloca: " << AI << "\n"
1229 << " A pointer to this alloca escaped by:\n"
1230 << " " << *PointerEscapingInstr << "\n";
1234 OS << "Partitioning of alloca: " << AI << "\n";
1236 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1242 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1243 void AllocaPartitioning::dump() const { print(dbgs()); }
1245 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1249 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1251 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1252 /// the loads and stores of an alloca instruction, as well as updating its
1253 /// debug information. This is used when a domtree is unavailable and thus
1254 /// mem2reg in its full form can't be used to handle promotion of allocas to
1256 class AllocaPromoter : public LoadAndStorePromoter {
1260 SmallVector<DbgDeclareInst *, 4> DDIs;
1261 SmallVector<DbgValueInst *, 4> DVIs;
1264 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1265 AllocaInst &AI, DIBuilder &DIB)
1266 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1268 void run(const SmallVectorImpl<Instruction*> &Insts) {
1269 // Remember which alloca we're promoting (for isInstInList).
1270 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1271 for (Value::use_iterator UI = DebugNode->use_begin(),
1272 UE = DebugNode->use_end();
1274 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1275 DDIs.push_back(DDI);
1276 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1277 DVIs.push_back(DVI);
1280 LoadAndStorePromoter::run(Insts);
1281 AI.eraseFromParent();
1282 while (!DDIs.empty())
1283 DDIs.pop_back_val()->eraseFromParent();
1284 while (!DVIs.empty())
1285 DVIs.pop_back_val()->eraseFromParent();
1288 virtual bool isInstInList(Instruction *I,
1289 const SmallVectorImpl<Instruction*> &Insts) const {
1290 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1291 return LI->getOperand(0) == &AI;
1292 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1295 virtual void updateDebugInfo(Instruction *Inst) const {
1296 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1297 E = DDIs.end(); I != E; ++I) {
1298 DbgDeclareInst *DDI = *I;
1299 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1300 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1301 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1302 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1304 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1305 E = DVIs.end(); I != E; ++I) {
1306 DbgValueInst *DVI = *I;
1308 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1309 // If an argument is zero extended then use argument directly. The ZExt
1310 // may be zapped by an optimization pass in future.
1311 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1312 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1313 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1314 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1316 Arg = SI->getOperand(0);
1317 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1318 Arg = LI->getOperand(0);
1322 Instruction *DbgVal =
1323 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1325 DbgVal->setDebugLoc(DVI->getDebugLoc());
1329 } // end anon namespace
1333 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1335 /// This pass takes allocations which can be completely analyzed (that is, they
1336 /// don't escape) and tries to turn them into scalar SSA values. There are
1337 /// a few steps to this process.
1339 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1340 /// are used to try to split them into smaller allocations, ideally of
1341 /// a single scalar data type. It will split up memcpy and memset accesses
1342 /// as necessary and try to isolate invidual scalar accesses.
1343 /// 2) It will transform accesses into forms which are suitable for SSA value
1344 /// promotion. This can be replacing a memset with a scalar store of an
1345 /// integer value, or it can involve speculating operations on a PHI or
1346 /// select to be a PHI or select of the results.
1347 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1348 /// onto insert and extract operations on a vector value, and convert them to
1349 /// this form. By doing so, it will enable promotion of vector aggregates to
1350 /// SSA vector values.
1351 class SROA : public FunctionPass {
1352 const bool RequiresDomTree;
1355 const DataLayout *TD;
1358 /// \brief Worklist of alloca instructions to simplify.
1360 /// Each alloca in the function is added to this. Each new alloca formed gets
1361 /// added to it as well to recursively simplify unless that alloca can be
1362 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1363 /// the one being actively rewritten, we add it back onto the list if not
1364 /// already present to ensure it is re-visited.
1365 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1367 /// \brief A collection of instructions to delete.
1368 /// We try to batch deletions to simplify code and make things a bit more
1370 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
1372 /// \brief Post-promotion worklist.
1374 /// Sometimes we discover an alloca which has a high probability of becoming
1375 /// viable for SROA after a round of promotion takes place. In those cases,
1376 /// the alloca is enqueued here for re-processing.
1378 /// Note that we have to be very careful to clear allocas out of this list in
1379 /// the event they are deleted.
1380 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1382 /// \brief A collection of alloca instructions we can directly promote.
1383 std::vector<AllocaInst *> PromotableAllocas;
1386 SROA(bool RequiresDomTree = true)
1387 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1388 C(0), TD(0), DT(0) {
1389 initializeSROAPass(*PassRegistry::getPassRegistry());
1391 bool runOnFunction(Function &F);
1392 void getAnalysisUsage(AnalysisUsage &AU) const;
1394 const char *getPassName() const { return "SROA"; }
1398 friend class PHIOrSelectSpeculator;
1399 friend class AllocaPartitionRewriter;
1400 friend class AllocaPartitionVectorRewriter;
1402 bool rewriteAllocaPartition(AllocaInst &AI,
1403 AllocaPartitioning &P,
1404 AllocaPartitioning::iterator PI);
1405 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1406 bool runOnAlloca(AllocaInst &AI);
1407 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
1408 bool promoteAllocas(Function &F);
1414 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1415 return new SROA(RequiresDomTree);
1418 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1420 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1421 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1425 /// \brief Visitor to speculate PHIs and Selects where possible.
1426 class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1427 // Befriend the base class so it can delegate to private visit methods.
1428 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1430 const DataLayout &TD;
1431 AllocaPartitioning &P;
1435 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
1436 : TD(TD), P(P), Pass(Pass) {}
1438 /// \brief Visit the users of an alloca partition and rewrite them.
1439 void visitUsers(AllocaPartitioning::const_iterator PI) {
1440 // Note that we need to use an index here as the underlying vector of uses
1441 // may be grown during speculation. However, we never need to re-visit the
1442 // new uses, and so we can use the initial size bound.
1443 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1444 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1446 continue; // Skip dead use.
1448 visit(cast<Instruction>(PU.U->getUser()));
1453 // By default, skip this instruction.
1454 void visitInstruction(Instruction &I) {}
1456 /// PHI instructions that use an alloca and are subsequently loaded can be
1457 /// rewritten to load both input pointers in the pred blocks and then PHI the
1458 /// results, allowing the load of the alloca to be promoted.
1460 /// %P2 = phi [i32* %Alloca, i32* %Other]
1461 /// %V = load i32* %P2
1463 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1465 /// %V2 = load i32* %Other
1467 /// %V = phi [i32 %V1, i32 %V2]
1469 /// We can do this to a select if its only uses are loads and if the operands
1470 /// to the select can be loaded unconditionally.
1472 /// FIXME: This should be hoisted into a generic utility, likely in
1473 /// Transforms/Util/Local.h
1474 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1475 // For now, we can only do this promotion if the load is in the same block
1476 // as the PHI, and if there are no stores between the phi and load.
1477 // TODO: Allow recursive phi users.
1478 // TODO: Allow stores.
1479 BasicBlock *BB = PN.getParent();
1480 unsigned MaxAlign = 0;
1481 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1483 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1484 if (LI == 0 || !LI->isSimple()) return false;
1486 // For now we only allow loads in the same block as the PHI. This is
1487 // a common case that happens when instcombine merges two loads through
1489 if (LI->getParent() != BB) return false;
1491 // Ensure that there are no instructions between the PHI and the load that
1493 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1494 if (BBI->mayWriteToMemory())
1497 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1498 Loads.push_back(LI);
1501 // We can only transform this if it is safe to push the loads into the
1502 // predecessor blocks. The only thing to watch out for is that we can't put
1503 // a possibly trapping load in the predecessor if it is a critical edge.
1504 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1506 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1507 Value *InVal = PN.getIncomingValue(Idx);
1509 // If the value is produced by the terminator of the predecessor (an
1510 // invoke) or it has side-effects, there is no valid place to put a load
1511 // in the predecessor.
1512 if (TI == InVal || TI->mayHaveSideEffects())
1515 // If the predecessor has a single successor, then the edge isn't
1517 if (TI->getNumSuccessors() == 1)
1520 // If this pointer is always safe to load, or if we can prove that there
1521 // is already a load in the block, then we can move the load to the pred
1523 if (InVal->isDereferenceablePointer() ||
1524 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1533 void visitPHINode(PHINode &PN) {
1534 DEBUG(dbgs() << " original: " << PN << "\n");
1536 SmallVector<LoadInst *, 4> Loads;
1537 if (!isSafePHIToSpeculate(PN, Loads))
1540 assert(!Loads.empty());
1542 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1543 IRBuilder<> PHIBuilder(&PN);
1544 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1545 PN.getName() + ".sroa.speculated");
1547 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1548 // matter which one we get and if any differ, it doesn't matter.
1549 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1550 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1551 unsigned Align = SomeLoad->getAlignment();
1553 // Rewrite all loads of the PN to use the new PHI.
1555 LoadInst *LI = Loads.pop_back_val();
1556 LI->replaceAllUsesWith(NewPN);
1557 Pass.DeadInsts.insert(LI);
1558 } while (!Loads.empty());
1560 // Inject loads into all of the pred blocks.
1561 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1562 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1563 TerminatorInst *TI = Pred->getTerminator();
1564 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1565 Value *InVal = PN.getIncomingValue(Idx);
1566 IRBuilder<> PredBuilder(TI);
1569 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1571 ++NumLoadsSpeculated;
1572 Load->setAlignment(Align);
1574 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1575 NewPN->addIncoming(Load, Pred);
1577 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1579 // No uses to rewrite.
1582 // Try to lookup and rewrite any partition uses corresponding to this phi
1584 AllocaPartitioning::iterator PI
1585 = P.findPartitionForPHIOrSelectOperand(InUse);
1589 // Replace the Use in the PartitionUse for this operand with the Use
1591 AllocaPartitioning::use_iterator UI
1592 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1593 assert(isa<PHINode>(*UI->U->getUser()));
1594 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1596 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1599 /// Select instructions that use an alloca and are subsequently loaded can be
1600 /// rewritten to load both input pointers and then select between the result,
1601 /// allowing the load of the alloca to be promoted.
1603 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1604 /// %V = load i32* %P2
1606 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1607 /// %V2 = load i32* %Other
1608 /// %V = select i1 %cond, i32 %V1, i32 %V2
1610 /// We can do this to a select if its only uses are loads and if the operand
1611 /// to the select can be loaded unconditionally.
1612 bool isSafeSelectToSpeculate(SelectInst &SI,
1613 SmallVectorImpl<LoadInst *> &Loads) {
1614 Value *TValue = SI.getTrueValue();
1615 Value *FValue = SI.getFalseValue();
1616 bool TDerefable = TValue->isDereferenceablePointer();
1617 bool FDerefable = FValue->isDereferenceablePointer();
1619 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1621 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1622 if (LI == 0 || !LI->isSimple()) return false;
1624 // Both operands to the select need to be dereferencable, either
1625 // absolutely (e.g. allocas) or at this point because we can see other
1627 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1628 LI->getAlignment(), &TD))
1630 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1631 LI->getAlignment(), &TD))
1633 Loads.push_back(LI);
1639 void visitSelectInst(SelectInst &SI) {
1640 DEBUG(dbgs() << " original: " << SI << "\n");
1641 IRBuilder<> IRB(&SI);
1643 // If the select isn't safe to speculate, just use simple logic to emit it.
1644 SmallVector<LoadInst *, 4> Loads;
1645 if (!isSafeSelectToSpeculate(SI, Loads))
1648 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1649 AllocaPartitioning::iterator PIs[2];
1650 AllocaPartitioning::PartitionUse PUs[2];
1651 for (unsigned i = 0, e = 2; i != e; ++i) {
1652 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1653 if (PIs[i] != P.end()) {
1654 // If the pointer is within the partitioning, remove the select from
1655 // its uses. We'll add in the new loads below.
1656 AllocaPartitioning::use_iterator UI
1657 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1659 // Clear out the use here so that the offsets into the use list remain
1660 // stable but this use is ignored when rewriting.
1665 Value *TV = SI.getTrueValue();
1666 Value *FV = SI.getFalseValue();
1667 // Replace the loads of the select with a select of two loads.
1668 while (!Loads.empty()) {
1669 LoadInst *LI = Loads.pop_back_val();
1671 IRB.SetInsertPoint(LI);
1673 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1675 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1676 NumLoadsSpeculated += 2;
1678 // Transfer alignment and TBAA info if present.
1679 TL->setAlignment(LI->getAlignment());
1680 FL->setAlignment(LI->getAlignment());
1681 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1682 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1683 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1686 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1687 LI->getName() + ".sroa.speculated");
1689 LoadInst *Loads[2] = { TL, FL };
1690 for (unsigned i = 0, e = 2; i != e; ++i) {
1691 if (PIs[i] != P.end()) {
1692 Use *LoadUse = &Loads[i]->getOperandUse(0);
1693 assert(PUs[i].U->get() == LoadUse->get());
1695 P.use_push_back(PIs[i], PUs[i]);
1699 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1700 LI->replaceAllUsesWith(V);
1701 Pass.DeadInsts.insert(LI);
1707 /// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1709 /// If the provided GEP is all-constant, the total byte offset formed by the
1710 /// GEP is computed and Offset is set to it. If the GEP has any non-constant
1711 /// operands, the function returns false and the value of Offset is unmodified.
1712 static bool accumulateGEPOffsets(const DataLayout &TD, GEPOperator &GEP,
1714 APInt GEPOffset(Offset.getBitWidth(), 0);
1715 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1716 GTI != GTE; ++GTI) {
1717 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1720 if (OpC->isZero()) continue;
1722 // Handle a struct index, which adds its field offset to the pointer.
1723 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1724 unsigned ElementIdx = OpC->getZExtValue();
1725 const StructLayout *SL = TD.getStructLayout(STy);
1726 GEPOffset += APInt(Offset.getBitWidth(),
1727 SL->getElementOffset(ElementIdx));
1731 APInt TypeSize(Offset.getBitWidth(),
1732 TD.getTypeAllocSize(GTI.getIndexedType()));
1733 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1734 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1735 "vector element size is not a multiple of 8, cannot GEP over it");
1736 TypeSize = VTy->getScalarSizeInBits() / 8;
1739 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1745 /// \brief Build a GEP out of a base pointer and indices.
1747 /// This will return the BasePtr if that is valid, or build a new GEP
1748 /// instruction using the IRBuilder if GEP-ing is needed.
1749 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1750 SmallVectorImpl<Value *> &Indices,
1751 const Twine &Prefix) {
1752 if (Indices.empty())
1755 // A single zero index is a no-op, so check for this and avoid building a GEP
1757 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1760 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1763 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1764 /// TargetTy without changing the offset of the pointer.
1766 /// This routine assumes we've already established a properly offset GEP with
1767 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1768 /// zero-indices down through type layers until we find one the same as
1769 /// TargetTy. If we can't find one with the same type, we at least try to use
1770 /// one with the same size. If none of that works, we just produce the GEP as
1771 /// indicated by Indices to have the correct offset.
1772 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
1773 Value *BasePtr, Type *Ty, Type *TargetTy,
1774 SmallVectorImpl<Value *> &Indices,
1775 const Twine &Prefix) {
1777 return buildGEP(IRB, BasePtr, Indices, Prefix);
1779 // See if we can descend into a struct and locate a field with the correct
1781 unsigned NumLayers = 0;
1782 Type *ElementTy = Ty;
1784 if (ElementTy->isPointerTy())
1786 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1787 ElementTy = SeqTy->getElementType();
1788 // Note that we use the default address space as this index is over an
1789 // array or a vector, not a pointer.
1790 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
1791 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1792 if (STy->element_begin() == STy->element_end())
1793 break; // Nothing left to descend into.
1794 ElementTy = *STy->element_begin();
1795 Indices.push_back(IRB.getInt32(0));
1800 } while (ElementTy != TargetTy);
1801 if (ElementTy != TargetTy)
1802 Indices.erase(Indices.end() - NumLayers, Indices.end());
1804 return buildGEP(IRB, BasePtr, Indices, Prefix);
1807 /// \brief Recursively compute indices for a natural GEP.
1809 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1810 /// element types adding appropriate indices for the GEP.
1811 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
1812 Value *Ptr, Type *Ty, APInt &Offset,
1814 SmallVectorImpl<Value *> &Indices,
1815 const Twine &Prefix) {
1817 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1819 // We can't recurse through pointer types.
1820 if (Ty->isPointerTy())
1823 // We try to analyze GEPs over vectors here, but note that these GEPs are
1824 // extremely poorly defined currently. The long-term goal is to remove GEPing
1825 // over a vector from the IR completely.
1826 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1827 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1828 if (ElementSizeInBits % 8)
1829 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1830 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1831 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1832 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1834 Offset -= NumSkippedElements * ElementSize;
1835 Indices.push_back(IRB.getInt(NumSkippedElements));
1836 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1837 Offset, TargetTy, Indices, Prefix);
1840 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1841 Type *ElementTy = ArrTy->getElementType();
1842 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1843 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1844 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1847 Offset -= NumSkippedElements * ElementSize;
1848 Indices.push_back(IRB.getInt(NumSkippedElements));
1849 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1853 StructType *STy = dyn_cast<StructType>(Ty);
1857 const StructLayout *SL = TD.getStructLayout(STy);
1858 uint64_t StructOffset = Offset.getZExtValue();
1859 if (StructOffset >= SL->getSizeInBytes())
1861 unsigned Index = SL->getElementContainingOffset(StructOffset);
1862 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1863 Type *ElementTy = STy->getElementType(Index);
1864 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1865 return 0; // The offset points into alignment padding.
1867 Indices.push_back(IRB.getInt32(Index));
1868 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1872 /// \brief Get a natural GEP from a base pointer to a particular offset and
1873 /// resulting in a particular type.
1875 /// The goal is to produce a "natural" looking GEP that works with the existing
1876 /// composite types to arrive at the appropriate offset and element type for
1877 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1878 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1879 /// Indices, and setting Ty to the result subtype.
1881 /// If no natural GEP can be constructed, this function returns null.
1882 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
1883 Value *Ptr, APInt Offset, Type *TargetTy,
1884 SmallVectorImpl<Value *> &Indices,
1885 const Twine &Prefix) {
1886 PointerType *Ty = cast<PointerType>(Ptr->getType());
1888 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1890 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1893 Type *ElementTy = Ty->getElementType();
1894 if (!ElementTy->isSized())
1895 return 0; // We can't GEP through an unsized element.
1896 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1897 if (ElementSize == 0)
1898 return 0; // Zero-length arrays can't help us build a natural GEP.
1899 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1901 Offset -= NumSkippedElements * ElementSize;
1902 Indices.push_back(IRB.getInt(NumSkippedElements));
1903 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1907 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1908 /// resulting pointer has PointerTy.
1910 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1911 /// and produces the pointer type desired. Where it cannot, it will try to use
1912 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1913 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1914 /// bitcast to the type.
1916 /// The strategy for finding the more natural GEPs is to peel off layers of the
1917 /// pointer, walking back through bit casts and GEPs, searching for a base
1918 /// pointer from which we can compute a natural GEP with the desired
1919 /// properities. The algorithm tries to fold as many constant indices into
1920 /// a single GEP as possible, thus making each GEP more independent of the
1921 /// surrounding code.
1922 static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
1923 Value *Ptr, APInt Offset, Type *PointerTy,
1924 const Twine &Prefix) {
1925 // Even though we don't look through PHI nodes, we could be called on an
1926 // instruction in an unreachable block, which may be on a cycle.
1927 SmallPtrSet<Value *, 4> Visited;
1928 Visited.insert(Ptr);
1929 SmallVector<Value *, 4> Indices;
1931 // We may end up computing an offset pointer that has the wrong type. If we
1932 // never are able to compute one directly that has the correct type, we'll
1933 // fall back to it, so keep it around here.
1934 Value *OffsetPtr = 0;
1936 // Remember any i8 pointer we come across to re-use if we need to do a raw
1939 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1941 Type *TargetTy = PointerTy->getPointerElementType();
1944 // First fold any existing GEPs into the offset.
1945 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1946 APInt GEPOffset(Offset.getBitWidth(), 0);
1947 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1949 Offset += GEPOffset;
1950 Ptr = GEP->getPointerOperand();
1951 if (!Visited.insert(Ptr))
1955 // See if we can perform a natural GEP here.
1957 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1959 if (P->getType() == PointerTy) {
1960 // Zap any offset pointer that we ended up computing in previous rounds.
1961 if (OffsetPtr && OffsetPtr->use_empty())
1962 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1963 I->eraseFromParent();
1971 // Stash this pointer if we've found an i8*.
1972 if (Ptr->getType()->isIntegerTy(8)) {
1974 Int8PtrOffset = Offset;
1977 // Peel off a layer of the pointer and update the offset appropriately.
1978 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1979 Ptr = cast<Operator>(Ptr)->getOperand(0);
1980 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1981 if (GA->mayBeOverridden())
1983 Ptr = GA->getAliasee();
1987 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1988 } while (Visited.insert(Ptr));
1992 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1993 Prefix + ".raw_cast");
1994 Int8PtrOffset = Offset;
1997 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1998 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1999 Prefix + ".raw_idx");
2003 // On the off chance we were targeting i8*, guard the bitcast here.
2004 if (Ptr->getType() != PointerTy)
2005 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
2010 /// \brief Test whether we can convert a value from the old to the new type.
2012 /// This predicate should be used to guard calls to convertValue in order to
2013 /// ensure that we only try to convert viable values. The strategy is that we
2014 /// will peel off single element struct and array wrappings to get to an
2015 /// underlying value, and convert that value.
2016 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
2019 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
2021 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
2024 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
2025 if (NewTy->isPointerTy() && OldTy->isPointerTy())
2027 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
2035 /// \brief Generic routine to convert an SSA value to a value of a different
2038 /// This will try various different casting techniques, such as bitcasts,
2039 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
2040 /// two types for viability with this routine.
2041 static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2043 assert(canConvertValue(DL, V->getType(), Ty) &&
2044 "Value not convertable to type");
2045 if (V->getType() == Ty)
2047 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2048 return IRB.CreateIntToPtr(V, Ty);
2049 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2050 return IRB.CreatePtrToInt(V, Ty);
2052 return IRB.CreateBitCast(V, Ty);
2055 /// \brief Test whether the given alloca partition can be promoted to a vector.
2057 /// This is a quick test to check whether we can rewrite a particular alloca
2058 /// partition (and its newly formed alloca) into a vector alloca with only
2059 /// whole-vector loads and stores such that it could be promoted to a vector
2060 /// SSA value. We only can ensure this for a limited set of operations, and we
2061 /// don't want to do the rewrites unless we are confident that the result will
2062 /// be promotable, so we have an early test here.
2063 static bool isVectorPromotionViable(const DataLayout &TD,
2065 AllocaPartitioning &P,
2066 uint64_t PartitionBeginOffset,
2067 uint64_t PartitionEndOffset,
2068 AllocaPartitioning::const_use_iterator I,
2069 AllocaPartitioning::const_use_iterator E) {
2070 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2074 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
2075 uint64_t ElementSize = Ty->getScalarSizeInBits();
2077 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2078 // that aren't byte sized.
2079 if (ElementSize % 8)
2081 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
2085 for (; I != E; ++I) {
2087 continue; // Skip dead use.
2089 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2090 uint64_t BeginIndex = BeginOffset / ElementSize;
2091 if (BeginIndex * ElementSize != BeginOffset ||
2092 BeginIndex >= Ty->getNumElements())
2094 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2095 uint64_t EndIndex = EndOffset / ElementSize;
2096 if (EndIndex * ElementSize != EndOffset ||
2097 EndIndex > Ty->getNumElements())
2100 assert(EndIndex > BeginIndex && "Empty vector!");
2101 uint64_t NumElements = EndIndex - BeginIndex;
2103 = (NumElements == 1) ? Ty->getElementType()
2104 : VectorType::get(Ty->getElementType(), NumElements);
2106 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
2107 if (MI->isVolatile())
2109 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
2110 const AllocaPartitioning::MemTransferOffsets &MTO
2111 = P.getMemTransferOffsets(*MTI);
2112 if (!MTO.IsSplittable)
2115 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
2116 // Disable vector promotion when there are loads or stores of an FCA.
2118 } else if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
2119 if (LI->isVolatile())
2121 if (!canConvertValue(TD, PartitionTy, LI->getType()))
2123 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
2124 if (SI->isVolatile())
2126 if (!canConvertValue(TD, SI->getValueOperand()->getType(), PartitionTy))
2135 /// \brief Test whether the given alloca partition's integer operations can be
2136 /// widened to promotable ones.
2138 /// This is a quick test to check whether we can rewrite the integer loads and
2139 /// stores to a particular alloca into wider loads and stores and be able to
2140 /// promote the resulting alloca.
2141 static bool isIntegerWideningViable(const DataLayout &TD,
2143 uint64_t AllocBeginOffset,
2144 AllocaPartitioning &P,
2145 AllocaPartitioning::const_use_iterator I,
2146 AllocaPartitioning::const_use_iterator E) {
2147 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
2148 // Don't create integer types larger than the maximum bitwidth.
2149 if (SizeInBits > IntegerType::MAX_INT_BITS)
2152 // Don't try to handle allocas with bit-padding.
2153 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
2156 // We need to ensure that an integer type with the appropriate bitwidth can
2157 // be converted to the alloca type, whatever that is. We don't want to force
2158 // the alloca itself to have an integer type if there is a more suitable one.
2159 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2160 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2161 !canConvertValue(TD, IntTy, AllocaTy))
2164 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2166 // Check the uses to ensure the uses are (likely) promoteable integer uses.
2167 // Also ensure that the alloca has a covering load or store. We don't want
2168 // to widen the integer operotains only to fail to promote due to some other
2169 // unsplittable entry (which we may make splittable later).
2170 bool WholeAllocaOp = false;
2171 for (; I != E; ++I) {
2173 continue; // Skip dead use.
2175 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2176 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2178 // We can't reasonably handle cases where the load or store extends past
2179 // the end of the aloca's type and into its padding.
2183 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
2184 if (LI->isVolatile())
2186 if (RelBegin == 0 && RelEnd == Size)
2187 WholeAllocaOp = true;
2188 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2189 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2193 // Non-integer loads need to be convertible from the alloca type so that
2194 // they are promotable.
2195 if (RelBegin != 0 || RelEnd != Size ||
2196 !canConvertValue(TD, AllocaTy, LI->getType()))
2198 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
2199 Type *ValueTy = SI->getValueOperand()->getType();
2200 if (SI->isVolatile())
2202 if (RelBegin == 0 && RelEnd == Size)
2203 WholeAllocaOp = true;
2204 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2205 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2209 // Non-integer stores need to be convertible to the alloca type so that
2210 // they are promotable.
2211 if (RelBegin != 0 || RelEnd != Size ||
2212 !canConvertValue(TD, ValueTy, AllocaTy))
2214 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
2215 if (MI->isVolatile())
2217 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
2218 const AllocaPartitioning::MemTransferOffsets &MTO
2219 = P.getMemTransferOffsets(*MTI);
2220 if (!MTO.IsSplittable)
2223 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->U->getUser())) {
2224 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2225 II->getIntrinsicID() != Intrinsic::lifetime_end)
2231 return WholeAllocaOp;
2234 static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2235 IntegerType *Ty, uint64_t Offset,
2236 const Twine &Name) {
2237 DEBUG(dbgs() << " start: " << *V << "\n");
2238 IntegerType *IntTy = cast<IntegerType>(V->getType());
2239 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2240 "Element extends past full value");
2241 uint64_t ShAmt = 8*Offset;
2242 if (DL.isBigEndian())
2243 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2245 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2246 DEBUG(dbgs() << " shifted: " << *V << "\n");
2248 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2249 "Cannot extract to a larger integer!");
2251 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2252 DEBUG(dbgs() << " trunced: " << *V << "\n");
2257 static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2258 Value *V, uint64_t Offset, const Twine &Name) {
2259 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2260 IntegerType *Ty = cast<IntegerType>(V->getType());
2261 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2262 "Cannot insert a larger integer!");
2263 DEBUG(dbgs() << " start: " << *V << "\n");
2265 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2266 DEBUG(dbgs() << " extended: " << *V << "\n");
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");
2275 DEBUG(dbgs() << " shifted: " << *V << "\n");
2278 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2279 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2280 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2281 DEBUG(dbgs() << " masked: " << *Old << "\n");
2282 V = IRB.CreateOr(Old, V, Name + ".insert");
2283 DEBUG(dbgs() << " inserted: " << *V << "\n");
2289 /// \brief Visitor to rewrite instructions using a partition of an alloca to
2290 /// use a new alloca.
2292 /// Also implements the rewriting to vector-based accesses when the partition
2293 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2295 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2297 // Befriend the base class so it can delegate to private visit methods.
2298 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2300 const DataLayout &TD;
2301 AllocaPartitioning &P;
2303 AllocaInst &OldAI, &NewAI;
2304 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2307 // If we are rewriting an alloca partition which can be written as pure
2308 // vector operations, we stash extra information here. When VecTy is
2309 // non-null, we have some strict guarantees about the rewriten alloca:
2310 // - The new alloca is exactly the size of the vector type here.
2311 // - The accesses all either map to the entire vector or to a single
2313 // - The set of accessing instructions is only one of those handled above
2314 // in isVectorPromotionViable. Generally these are the same access kinds
2315 // which are promotable via mem2reg.
2318 uint64_t ElementSize;
2320 // This is a convenience and flag variable that will be null unless the new
2321 // alloca's integer operations should be widened to this integer type due to
2322 // passing isIntegerWideningViable above. If it is non-null, the desired
2323 // integer type will be stored here for easy access during rewriting.
2326 // The offset of the partition user currently being rewritten.
2327 uint64_t BeginOffset, EndOffset;
2329 Instruction *OldPtr;
2331 // The name prefix to use when rewriting instructions for this alloca.
2332 std::string NamePrefix;
2335 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
2336 AllocaPartitioning::iterator PI,
2337 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2338 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2339 : TD(TD), P(P), Pass(Pass),
2340 OldAI(OldAI), NewAI(NewAI),
2341 NewAllocaBeginOffset(NewBeginOffset),
2342 NewAllocaEndOffset(NewEndOffset),
2343 NewAllocaTy(NewAI.getAllocatedType()),
2344 VecTy(), ElementTy(), ElementSize(), IntTy(),
2345 BeginOffset(), EndOffset() {
2348 /// \brief Visit the users of the alloca partition and rewrite them.
2349 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2350 AllocaPartitioning::const_use_iterator E) {
2351 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2352 NewAllocaBeginOffset, NewAllocaEndOffset,
2355 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2356 ElementTy = VecTy->getElementType();
2357 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2358 "Only multiple-of-8 sized vector elements are viable");
2359 ElementSize = VecTy->getScalarSizeInBits() / 8;
2360 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2361 NewAllocaBeginOffset, P, I, E)) {
2362 IntTy = Type::getIntNTy(NewAI.getContext(),
2363 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
2365 bool CanSROA = true;
2366 for (; I != E; ++I) {
2368 continue; // Skip dead uses.
2369 BeginOffset = I->BeginOffset;
2370 EndOffset = I->EndOffset;
2372 OldPtr = cast<Instruction>(I->U->get());
2373 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
2374 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
2390 // Every instruction which can end up as a user must have a rewrite rule.
2391 bool visitInstruction(Instruction &I) {
2392 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2393 llvm_unreachable("No rewrite rule for this instruction!");
2396 Twine getName(const Twine &Suffix) {
2397 return NamePrefix + Suffix;
2400 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2401 assert(BeginOffset >= NewAllocaBeginOffset);
2402 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
2403 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2406 /// \brief Compute suitable alignment to access an offset into the new alloca.
2407 unsigned getOffsetAlign(uint64_t Offset) {
2408 unsigned NewAIAlign = NewAI.getAlignment();
2410 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2411 return MinAlign(NewAIAlign, Offset);
2414 /// \brief Compute suitable alignment to access this partition of the new
2416 unsigned getPartitionAlign() {
2417 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
2420 /// \brief Compute suitable alignment to access a type at an offset of the
2423 /// \returns zero if the type's ABI alignment is a suitable alignment,
2424 /// otherwise returns the maximal suitable alignment.
2425 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2426 unsigned Align = getOffsetAlign(Offset);
2427 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2430 /// \brief Compute suitable alignment to access a type at the beginning of
2431 /// this partition of the new alloca.
2433 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2434 unsigned getPartitionTypeAlign(Type *Ty) {
2435 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
2438 unsigned getIndex(uint64_t Offset) {
2439 assert(VecTy && "Can only call getIndex when rewriting a vector");
2440 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2441 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2442 uint32_t Index = RelOffset / ElementSize;
2443 assert(Index * ElementSize == RelOffset);
2447 void deleteIfTriviallyDead(Value *V) {
2448 Instruction *I = cast<Instruction>(V);
2449 if (isInstructionTriviallyDead(I))
2450 Pass.DeadInsts.insert(I);
2453 Value *rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2454 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2456 unsigned BeginIndex = getIndex(BeginOffset);
2457 unsigned EndIndex = getIndex(EndOffset);
2458 assert(EndIndex > BeginIndex && "Empty vector!");
2459 unsigned NumElements = EndIndex - BeginIndex;
2460 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2461 if (NumElements == 1) {
2462 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2463 getName(".extract"));
2464 DEBUG(dbgs() << " extract: " << *V << "\n");
2465 } else if (NumElements < VecTy->getNumElements()) {
2466 SmallVector<Constant*, 8> Mask;
2467 Mask.reserve(NumElements);
2468 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2469 Mask.push_back(IRB.getInt32(i));
2470 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2471 ConstantVector::get(Mask),
2472 getName(".extract"));
2473 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2478 Value *rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
2479 assert(IntTy && "We cannot insert an integer to the alloca");
2480 assert(!LI.isVolatile());
2481 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2483 V = convertValue(TD, IRB, V, IntTy);
2484 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2485 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2486 if (Offset > 0 || EndOffset < NewAllocaEndOffset)
2487 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2488 getName(".extract"));
2492 bool visitLoadInst(LoadInst &LI) {
2493 DEBUG(dbgs() << " original: " << LI << "\n");
2494 Value *OldOp = LI.getOperand(0);
2495 assert(OldOp == OldPtr);
2496 IRBuilder<> IRB(&LI);
2498 uint64_t Size = EndOffset - BeginOffset;
2499 bool IsSplitIntLoad = Size < TD.getTypeStoreSize(LI.getType());
2501 // If this memory access can be shown to *statically* extend outside the
2502 // bounds of the original allocation it's behavior is undefined. Rather
2503 // than trying to transform it, just replace it with undef.
2504 // FIXME: We should do something more clever for functions being
2505 // instrumented by asan.
2506 // FIXME: Eventually, once ASan and friends can flush out bugs here, this
2507 // should be transformed to a load of null making it unreachable.
2508 uint64_t OldAllocSize = TD.getTypeAllocSize(OldAI.getAllocatedType());
2509 if (TD.getTypeStoreSize(LI.getType()) > OldAllocSize) {
2510 LI.replaceAllUsesWith(UndefValue::get(LI.getType()));
2511 Pass.DeadInsts.insert(&LI);
2512 deleteIfTriviallyDead(OldOp);
2513 DEBUG(dbgs() << " to: undef!!\n");
2517 Type *TargetTy = IsSplitIntLoad ? Type::getIntNTy(LI.getContext(), Size * 8)
2519 bool IsPtrAdjusted = false;
2522 V = rewriteVectorizedLoadInst(IRB, LI, OldOp);
2523 } else if (IntTy && LI.getType()->isIntegerTy()) {
2524 V = rewriteIntegerLoad(IRB, LI);
2525 } else if (BeginOffset == NewAllocaBeginOffset &&
2526 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2527 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2528 LI.isVolatile(), getName(".load"));
2530 Type *LTy = TargetTy->getPointerTo();
2531 V = IRB.CreateAlignedLoad(getAdjustedAllocaPtr(IRB, LTy),
2532 getPartitionTypeAlign(TargetTy),
2533 LI.isVolatile(), getName(".load"));
2534 IsPtrAdjusted = true;
2536 V = convertValue(TD, IRB, V, TargetTy);
2538 if (IsSplitIntLoad) {
2539 assert(!LI.isVolatile());
2540 assert(LI.getType()->isIntegerTy() &&
2541 "Only integer type loads and stores are split");
2542 assert(LI.getType()->getIntegerBitWidth() ==
2543 TD.getTypeStoreSizeInBits(LI.getType()) &&
2544 "Non-byte-multiple bit width");
2545 assert(LI.getType()->getIntegerBitWidth() ==
2546 TD.getTypeAllocSizeInBits(OldAI.getAllocatedType()) &&
2547 "Only alloca-wide loads can be split and recomposed");
2548 // Move the insertion point just past the load so that we can refer to it.
2549 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
2550 // Create a placeholder value with the same type as LI to use as the
2551 // basis for the new value. This allows us to replace the uses of LI with
2552 // the computed value, and then replace the placeholder with LI, leaving
2553 // LI only used for this computation.
2555 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2556 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2557 getName(".insert"));
2558 LI.replaceAllUsesWith(V);
2559 Placeholder->replaceAllUsesWith(&LI);
2562 LI.replaceAllUsesWith(V);
2565 Pass.DeadInsts.insert(&LI);
2566 deleteIfTriviallyDead(OldOp);
2567 DEBUG(dbgs() << " to: " << *V << "\n");
2568 return !LI.isVolatile() && !IsPtrAdjusted;
2571 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, Value *V,
2572 StoreInst &SI, Value *OldOp) {
2573 unsigned BeginIndex = getIndex(BeginOffset);
2574 unsigned EndIndex = getIndex(EndOffset);
2575 assert(EndIndex > BeginIndex && "Empty vector!");
2576 unsigned NumElements = EndIndex - BeginIndex;
2577 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2579 = (NumElements == 1) ? ElementTy
2580 : VectorType::get(ElementTy, NumElements);
2581 if (V->getType() != PartitionTy)
2582 V = convertValue(TD, IRB, V, PartitionTy);
2583 if (NumElements < VecTy->getNumElements()) {
2584 // We need to mix in the existing elements.
2585 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2587 if (NumElements == 1) {
2588 V = IRB.CreateInsertElement(LI, V, IRB.getInt32(BeginIndex),
2589 getName(".insert"));
2590 DEBUG(dbgs() << " insert: " << *V << "\n");
2592 // When inserting a smaller vector into the larger to store, we first
2593 // use a shuffle vector to widen it with undef elements, and then
2594 // a second shuffle vector to select between the loaded vector and the
2596 SmallVector<Constant*, 8> Mask;
2597 Mask.reserve(VecTy->getNumElements());
2598 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2599 if (i >= BeginIndex && i < EndIndex)
2600 Mask.push_back(IRB.getInt32(i - BeginIndex));
2602 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2603 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2604 ConstantVector::get(Mask),
2605 getName(".expand"));
2606 DEBUG(dbgs() << " shuffle1: " << *V << "\n");
2609 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2610 if (i >= BeginIndex && i < EndIndex)
2611 Mask.push_back(IRB.getInt32(i));
2613 Mask.push_back(IRB.getInt32(i + VecTy->getNumElements()));
2614 V = IRB.CreateShuffleVector(V, LI, ConstantVector::get(Mask),
2616 DEBUG(dbgs() << " shuffle2: " << *V << "\n");
2619 V = convertValue(TD, IRB, V, VecTy);
2621 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2622 Pass.DeadInsts.insert(&SI);
2625 DEBUG(dbgs() << " to: " << *Store << "\n");
2629 bool rewriteIntegerStore(IRBuilder<> &IRB, Value *V, StoreInst &SI) {
2630 assert(IntTy && "We cannot extract an integer from the alloca");
2631 assert(!SI.isVolatile());
2632 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2633 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2634 getName(".oldload"));
2635 Old = convertValue(TD, IRB, Old, IntTy);
2636 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2637 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2638 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2639 getName(".insert"));
2641 V = convertValue(TD, IRB, V, NewAllocaTy);
2642 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2643 Pass.DeadInsts.insert(&SI);
2645 DEBUG(dbgs() << " to: " << *Store << "\n");
2649 bool visitStoreInst(StoreInst &SI) {
2650 DEBUG(dbgs() << " original: " << SI << "\n");
2651 Value *OldOp = SI.getOperand(1);
2652 assert(OldOp == OldPtr);
2653 IRBuilder<> IRB(&SI);
2655 Value *V = SI.getValueOperand();
2657 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2658 // alloca that should be re-examined after promoting this alloca.
2659 if (V->getType()->isPointerTy())
2660 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2661 Pass.PostPromotionWorklist.insert(AI);
2663 uint64_t Size = EndOffset - BeginOffset;
2664 if (Size < TD.getTypeStoreSize(V->getType())) {
2665 assert(!SI.isVolatile());
2666 assert(V->getType()->isIntegerTy() &&
2667 "Only integer type loads and stores are split");
2668 assert(V->getType()->getIntegerBitWidth() ==
2669 TD.getTypeStoreSizeInBits(V->getType()) &&
2670 "Non-byte-multiple bit width");
2671 assert(V->getType()->getIntegerBitWidth() ==
2672 TD.getTypeSizeInBits(OldAI.getAllocatedType()) &&
2673 "Only alloca-wide stores can be split and recomposed");
2674 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2675 V = extractInteger(TD, IRB, V, NarrowTy, BeginOffset,
2676 getName(".extract"));
2680 return rewriteVectorizedStoreInst(IRB, V, SI, OldOp);
2681 if (IntTy && V->getType()->isIntegerTy())
2682 return rewriteIntegerStore(IRB, V, SI);
2685 if (BeginOffset == NewAllocaBeginOffset &&
2686 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2687 V = convertValue(TD, IRB, V, NewAllocaTy);
2688 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2691 Value *NewPtr = getAdjustedAllocaPtr(IRB, V->getType()->getPointerTo());
2692 NewSI = IRB.CreateAlignedStore(V, NewPtr,
2693 getPartitionTypeAlign(V->getType()),
2697 Pass.DeadInsts.insert(&SI);
2698 deleteIfTriviallyDead(OldOp);
2700 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2701 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2704 bool visitMemSetInst(MemSetInst &II) {
2705 DEBUG(dbgs() << " original: " << II << "\n");
2706 IRBuilder<> IRB(&II);
2707 assert(II.getRawDest() == OldPtr);
2709 // If the memset has a variable size, it cannot be split, just adjust the
2710 // pointer to the new alloca.
2711 if (!isa<Constant>(II.getLength())) {
2712 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2713 Type *CstTy = II.getAlignmentCst()->getType();
2714 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
2716 deleteIfTriviallyDead(OldPtr);
2720 // Record this instruction for deletion.
2721 Pass.DeadInsts.insert(&II);
2723 Type *AllocaTy = NewAI.getAllocatedType();
2724 Type *ScalarTy = AllocaTy->getScalarType();
2726 // If this doesn't map cleanly onto the alloca type, and that type isn't
2727 // a single value type, just emit a memset.
2728 if (!VecTy && !IntTy &&
2729 (BeginOffset != NewAllocaBeginOffset ||
2730 EndOffset != NewAllocaEndOffset ||
2731 !AllocaTy->isSingleValueType() ||
2732 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
2733 Type *SizeTy = II.getLength()->getType();
2734 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2736 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2737 II.getRawDest()->getType()),
2738 II.getValue(), Size, getPartitionAlign(),
2741 DEBUG(dbgs() << " to: " << *New << "\n");
2745 // If we can represent this as a simple value, we have to build the actual
2746 // value to store, which requires expanding the byte present in memset to
2747 // a sensible representation for the alloca type. This is essentially
2748 // splatting the byte to a sufficiently wide integer, bitcasting to the
2749 // desired scalar type, and splatting it across any desired vector type.
2750 uint64_t Size = EndOffset - BeginOffset;
2751 Value *V = II.getValue();
2752 IntegerType *VTy = cast<IntegerType>(V->getType());
2753 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2754 if (Size*8 > VTy->getBitWidth())
2755 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
2756 ConstantExpr::getUDiv(
2757 Constant::getAllOnesValue(SplatIntTy),
2758 ConstantExpr::getZExt(
2759 Constant::getAllOnesValue(V->getType()),
2761 getName(".isplat"));
2763 // If this is an element-wide memset of a vectorizable alloca, insert it.
2764 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2765 EndOffset < NewAllocaEndOffset)) {
2766 if (V->getType() != ScalarTy)
2767 V = convertValue(TD, IRB, V, ScalarTy);
2768 StoreInst *Store = IRB.CreateAlignedStore(
2769 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2770 NewAI.getAlignment(),
2772 V, IRB.getInt32(getIndex(BeginOffset)),
2773 getName(".insert")),
2774 &NewAI, NewAI.getAlignment());
2776 DEBUG(dbgs() << " to: " << *Store << "\n");
2780 // If this is a memset on an alloca where we can widen stores, insert the
2782 if (IntTy && (BeginOffset > NewAllocaBeginOffset ||
2783 EndOffset < NewAllocaEndOffset)) {
2784 assert(!II.isVolatile());
2785 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2786 getName(".oldload"));
2787 Old = convertValue(TD, IRB, Old, IntTy);
2788 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2789 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2790 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
2793 if (V->getType() != AllocaTy)
2794 V = convertValue(TD, IRB, V, AllocaTy);
2796 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2799 DEBUG(dbgs() << " to: " << *New << "\n");
2800 return !II.isVolatile();
2803 bool visitMemTransferInst(MemTransferInst &II) {
2804 // Rewriting of memory transfer instructions can be a bit tricky. We break
2805 // them into two categories: split intrinsics and unsplit intrinsics.
2807 DEBUG(dbgs() << " original: " << II << "\n");
2808 IRBuilder<> IRB(&II);
2810 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2811 bool IsDest = II.getRawDest() == OldPtr;
2813 const AllocaPartitioning::MemTransferOffsets &MTO
2814 = P.getMemTransferOffsets(II);
2816 // Compute the relative offset within the transfer.
2817 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2818 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2819 : MTO.SourceBegin));
2821 unsigned Align = II.getAlignment();
2823 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2824 MinAlign(II.getAlignment(), getPartitionAlign()));
2826 // For unsplit intrinsics, we simply modify the source and destination
2827 // pointers in place. This isn't just an optimization, it is a matter of
2828 // correctness. With unsplit intrinsics we may be dealing with transfers
2829 // within a single alloca before SROA ran, or with transfers that have
2830 // a variable length. We may also be dealing with memmove instead of
2831 // memcpy, and so simply updating the pointers is the necessary for us to
2832 // update both source and dest of a single call.
2833 if (!MTO.IsSplittable) {
2834 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2836 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2838 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2840 Type *CstTy = II.getAlignmentCst()->getType();
2841 II.setAlignment(ConstantInt::get(CstTy, Align));
2843 DEBUG(dbgs() << " to: " << II << "\n");
2844 deleteIfTriviallyDead(OldOp);
2847 // For split transfer intrinsics we have an incredibly useful assurance:
2848 // the source and destination do not reside within the same alloca, and at
2849 // least one of them does not escape. This means that we can replace
2850 // memmove with memcpy, and we don't need to worry about all manner of
2851 // downsides to splitting and transforming the operations.
2853 // If this doesn't map cleanly onto the alloca type, and that type isn't
2854 // a single value type, just emit a memcpy.
2856 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2857 EndOffset != NewAllocaEndOffset ||
2858 !NewAI.getAllocatedType()->isSingleValueType());
2860 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2861 // size hasn't been shrunk based on analysis of the viable range, this is
2863 if (EmitMemCpy && &OldAI == &NewAI) {
2864 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2865 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2866 // Ensure the start lines up.
2867 assert(BeginOffset == OrigBegin);
2870 // Rewrite the size as needed.
2871 if (EndOffset != OrigEnd)
2872 II.setLength(ConstantInt::get(II.getLength()->getType(),
2873 EndOffset - BeginOffset));
2876 // Record this instruction for deletion.
2877 Pass.DeadInsts.insert(&II);
2879 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2880 EndOffset == NewAllocaEndOffset;
2881 bool IsVectorElement = VecTy && !IsWholeAlloca;
2882 uint64_t Size = EndOffset - BeginOffset;
2883 IntegerType *SubIntTy
2884 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2886 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2887 : II.getRawDest()->getType();
2889 if (IsVectorElement)
2890 OtherPtrTy = VecTy->getElementType()->getPointerTo();
2891 else if (IntTy && !IsWholeAlloca)
2892 OtherPtrTy = SubIntTy->getPointerTo();
2894 OtherPtrTy = NewAI.getType();
2897 // Compute the other pointer, folding as much as possible to produce
2898 // a single, simple GEP in most cases.
2899 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2900 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2901 getName("." + OtherPtr->getName()));
2903 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2904 // alloca that should be re-examined after rewriting this instruction.
2906 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2907 Pass.Worklist.insert(AI);
2911 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2912 : II.getRawSource()->getType());
2913 Type *SizeTy = II.getLength()->getType();
2914 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2916 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2917 IsDest ? OtherPtr : OurPtr,
2918 Size, Align, II.isVolatile());
2920 DEBUG(dbgs() << " to: " << *New << "\n");
2924 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2925 // is equivalent to 1, but that isn't true if we end up rewriting this as
2930 Value *SrcPtr = OtherPtr;
2931 Value *DstPtr = &NewAI;
2933 std::swap(SrcPtr, DstPtr);
2936 if (IsVectorElement && !IsDest) {
2937 // We have to extract rather than load.
2938 Src = IRB.CreateExtractElement(
2939 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
2940 IRB.getInt32(getIndex(BeginOffset)),
2941 getName(".copyextract"));
2942 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2943 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2945 Src = convertValue(TD, IRB, Src, IntTy);
2946 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2947 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2948 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
2950 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2951 getName(".copyload"));
2954 if (IntTy && !IsWholeAlloca && IsDest) {
2955 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2956 getName(".oldload"));
2957 Old = convertValue(TD, IRB, Old, IntTy);
2958 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2959 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2960 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2961 Src = convertValue(TD, IRB, Src, NewAllocaTy);
2964 if (IsVectorElement && IsDest) {
2965 // We have to insert into a loaded copy before storing.
2966 Src = IRB.CreateInsertElement(
2967 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2968 Src, IRB.getInt32(getIndex(BeginOffset)),
2969 getName(".insert"));
2972 StoreInst *Store = cast<StoreInst>(
2973 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2975 DEBUG(dbgs() << " to: " << *Store << "\n");
2976 return !II.isVolatile();
2979 bool visitIntrinsicInst(IntrinsicInst &II) {
2980 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2981 II.getIntrinsicID() == Intrinsic::lifetime_end);
2982 DEBUG(dbgs() << " original: " << II << "\n");
2983 IRBuilder<> IRB(&II);
2984 assert(II.getArgOperand(1) == OldPtr);
2986 // Record this instruction for deletion.
2987 Pass.DeadInsts.insert(&II);
2990 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2991 EndOffset - BeginOffset);
2992 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2994 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2995 New = IRB.CreateLifetimeStart(Ptr, Size);
2997 New = IRB.CreateLifetimeEnd(Ptr, Size);
2999 DEBUG(dbgs() << " to: " << *New << "\n");
3003 bool visitPHINode(PHINode &PN) {
3004 DEBUG(dbgs() << " original: " << PN << "\n");
3006 // We would like to compute a new pointer in only one place, but have it be
3007 // as local as possible to the PHI. To do that, we re-use the location of
3008 // the old pointer, which necessarily must be in the right position to
3009 // dominate the PHI.
3010 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
3012 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
3013 // Replace the operands which were using the old pointer.
3014 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3016 DEBUG(dbgs() << " to: " << PN << "\n");
3017 deleteIfTriviallyDead(OldPtr);
3021 bool visitSelectInst(SelectInst &SI) {
3022 DEBUG(dbgs() << " original: " << SI << "\n");
3023 IRBuilder<> IRB(&SI);
3025 // Find the operand we need to rewrite here.
3026 bool IsTrueVal = SI.getTrueValue() == OldPtr;
3028 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
3030 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
3032 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
3033 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
3034 DEBUG(dbgs() << " to: " << SI << "\n");
3035 deleteIfTriviallyDead(OldPtr);
3043 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
3045 /// This pass aggressively rewrites all aggregate loads and stores on
3046 /// a particular pointer (or any pointer derived from it which we can identify)
3047 /// with scalar loads and stores.
3048 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3049 // Befriend the base class so it can delegate to private visit methods.
3050 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3052 const DataLayout &TD;
3054 /// Queue of pointer uses to analyze and potentially rewrite.
3055 SmallVector<Use *, 8> Queue;
3057 /// Set to prevent us from cycling with phi nodes and loops.
3058 SmallPtrSet<User *, 8> Visited;
3060 /// The current pointer use being rewritten. This is used to dig up the used
3061 /// value (as opposed to the user).
3065 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
3067 /// Rewrite loads and stores through a pointer and all pointers derived from
3069 bool rewrite(Instruction &I) {
3070 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3072 bool Changed = false;
3073 while (!Queue.empty()) {
3074 U = Queue.pop_back_val();
3075 Changed |= visit(cast<Instruction>(U->getUser()));
3081 /// Enqueue all the users of the given instruction for further processing.
3082 /// This uses a set to de-duplicate users.
3083 void enqueueUsers(Instruction &I) {
3084 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3086 if (Visited.insert(*UI))
3087 Queue.push_back(&UI.getUse());
3090 // Conservative default is to not rewrite anything.
3091 bool visitInstruction(Instruction &I) { return false; }
3093 /// \brief Generic recursive split emission class.
3094 template <typename Derived>
3097 /// The builder used to form new instructions.
3099 /// The indices which to be used with insert- or extractvalue to select the
3100 /// appropriate value within the aggregate.
3101 SmallVector<unsigned, 4> Indices;
3102 /// The indices to a GEP instruction which will move Ptr to the correct slot
3103 /// within the aggregate.
3104 SmallVector<Value *, 4> GEPIndices;
3105 /// The base pointer of the original op, used as a base for GEPing the
3106 /// split operations.
3109 /// Initialize the splitter with an insertion point, Ptr and start with a
3110 /// single zero GEP index.
3111 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
3112 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3115 /// \brief Generic recursive split emission routine.
3117 /// This method recursively splits an aggregate op (load or store) into
3118 /// scalar or vector ops. It splits recursively until it hits a single value
3119 /// and emits that single value operation via the template argument.
3121 /// The logic of this routine relies on GEPs and insertvalue and
3122 /// extractvalue all operating with the same fundamental index list, merely
3123 /// formatted differently (GEPs need actual values).
3125 /// \param Ty The type being split recursively into smaller ops.
3126 /// \param Agg The aggregate value being built up or stored, depending on
3127 /// whether this is splitting a load or a store respectively.
3128 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3129 if (Ty->isSingleValueType())
3130 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
3132 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3133 unsigned OldSize = Indices.size();
3135 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3137 assert(Indices.size() == OldSize && "Did not return to the old size");
3138 Indices.push_back(Idx);
3139 GEPIndices.push_back(IRB.getInt32(Idx));
3140 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3141 GEPIndices.pop_back();
3147 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3148 unsigned OldSize = Indices.size();
3150 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3152 assert(Indices.size() == OldSize && "Did not return to the old size");
3153 Indices.push_back(Idx);
3154 GEPIndices.push_back(IRB.getInt32(Idx));
3155 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3156 GEPIndices.pop_back();
3162 llvm_unreachable("Only arrays and structs are aggregate loadable types");
3166 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3167 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3168 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
3170 /// Emit a leaf load of a single value. This is called at the leaves of the
3171 /// recursive emission to actually load values.
3172 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3173 assert(Ty->isSingleValueType());
3174 // Load the single value and insert it using the indices.
3175 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
3178 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3179 DEBUG(dbgs() << " to: " << *Load << "\n");
3183 bool visitLoadInst(LoadInst &LI) {
3184 assert(LI.getPointerOperand() == *U);
3185 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3188 // We have an aggregate being loaded, split it apart.
3189 DEBUG(dbgs() << " original: " << LI << "\n");
3190 LoadOpSplitter Splitter(&LI, *U);
3191 Value *V = UndefValue::get(LI.getType());
3192 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3193 LI.replaceAllUsesWith(V);
3194 LI.eraseFromParent();
3198 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
3199 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3200 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
3202 /// Emit a leaf store of a single value. This is called at the leaves of the
3203 /// recursive emission to actually produce stores.
3204 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3205 assert(Ty->isSingleValueType());
3206 // Extract the single value and store it using the indices.
3207 Value *Store = IRB.CreateStore(
3208 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3209 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3211 DEBUG(dbgs() << " to: " << *Store << "\n");
3215 bool visitStoreInst(StoreInst &SI) {
3216 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3218 Value *V = SI.getValueOperand();
3219 if (V->getType()->isSingleValueType())
3222 // We have an aggregate being stored, split it apart.
3223 DEBUG(dbgs() << " original: " << SI << "\n");
3224 StoreOpSplitter Splitter(&SI, *U);
3225 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3226 SI.eraseFromParent();
3230 bool visitBitCastInst(BitCastInst &BC) {
3235 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3240 bool visitPHINode(PHINode &PN) {
3245 bool visitSelectInst(SelectInst &SI) {
3252 /// \brief Strip aggregate type wrapping.
3254 /// This removes no-op aggregate types wrapping an underlying type. It will
3255 /// strip as many layers of types as it can without changing either the type
3256 /// size or the allocated size.
3257 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3258 if (Ty->isSingleValueType())
3261 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3262 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3265 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3266 InnerTy = ArrTy->getElementType();
3267 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3268 const StructLayout *SL = DL.getStructLayout(STy);
3269 unsigned Index = SL->getElementContainingOffset(0);
3270 InnerTy = STy->getElementType(Index);
3275 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3276 TypeSize > DL.getTypeSizeInBits(InnerTy))
3279 return stripAggregateTypeWrapping(DL, InnerTy);
3282 /// \brief Try to find a partition of the aggregate type passed in for a given
3283 /// offset and size.
3285 /// This recurses through the aggregate type and tries to compute a subtype
3286 /// based on the offset and size. When the offset and size span a sub-section
3287 /// of an array, it will even compute a new array type for that sub-section,
3288 /// and the same for structs.
3290 /// Note that this routine is very strict and tries to find a partition of the
3291 /// type which produces the *exact* right offset and size. It is not forgiving
3292 /// when the size or offset cause either end of type-based partition to be off.
3293 /// Also, this is a best-effort routine. It is reasonable to give up and not
3294 /// return a type if necessary.
3295 static Type *getTypePartition(const DataLayout &TD, Type *Ty,
3296 uint64_t Offset, uint64_t Size) {
3297 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
3298 return stripAggregateTypeWrapping(TD, Ty);
3299 if (Offset > TD.getTypeAllocSize(Ty) ||
3300 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3303 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3304 // We can't partition pointers...
3305 if (SeqTy->isPointerTy())
3308 Type *ElementTy = SeqTy->getElementType();
3309 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3310 uint64_t NumSkippedElements = Offset / ElementSize;
3311 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3312 if (NumSkippedElements >= ArrTy->getNumElements())
3314 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3315 if (NumSkippedElements >= VecTy->getNumElements())
3317 Offset -= NumSkippedElements * ElementSize;
3319 // First check if we need to recurse.
3320 if (Offset > 0 || Size < ElementSize) {
3321 // Bail if the partition ends in a different array element.
3322 if ((Offset + Size) > ElementSize)
3324 // Recurse through the element type trying to peel off offset bytes.
3325 return getTypePartition(TD, ElementTy, Offset, Size);
3327 assert(Offset == 0);
3329 if (Size == ElementSize)
3330 return stripAggregateTypeWrapping(TD, ElementTy);
3331 assert(Size > ElementSize);
3332 uint64_t NumElements = Size / ElementSize;
3333 if (NumElements * ElementSize != Size)
3335 return ArrayType::get(ElementTy, NumElements);
3338 StructType *STy = dyn_cast<StructType>(Ty);
3342 const StructLayout *SL = TD.getStructLayout(STy);
3343 if (Offset >= SL->getSizeInBytes())
3345 uint64_t EndOffset = Offset + Size;
3346 if (EndOffset > SL->getSizeInBytes())
3349 unsigned Index = SL->getElementContainingOffset(Offset);
3350 Offset -= SL->getElementOffset(Index);
3352 Type *ElementTy = STy->getElementType(Index);
3353 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3354 if (Offset >= ElementSize)
3355 return 0; // The offset points into alignment padding.
3357 // See if any partition must be contained by the element.
3358 if (Offset > 0 || Size < ElementSize) {
3359 if ((Offset + Size) > ElementSize)
3361 return getTypePartition(TD, ElementTy, Offset, Size);
3363 assert(Offset == 0);
3365 if (Size == ElementSize)
3366 return stripAggregateTypeWrapping(TD, ElementTy);
3368 StructType::element_iterator EI = STy->element_begin() + Index,
3369 EE = STy->element_end();
3370 if (EndOffset < SL->getSizeInBytes()) {
3371 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3372 if (Index == EndIndex)
3373 return 0; // Within a single element and its padding.
3375 // Don't try to form "natural" types if the elements don't line up with the
3377 // FIXME: We could potentially recurse down through the last element in the
3378 // sub-struct to find a natural end point.
3379 if (SL->getElementOffset(EndIndex) != EndOffset)
3382 assert(Index < EndIndex);
3383 EE = STy->element_begin() + EndIndex;
3386 // Try to build up a sub-structure.
3387 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
3389 const StructLayout *SubSL = TD.getStructLayout(SubTy);
3390 if (Size != SubSL->getSizeInBytes())
3391 return 0; // The sub-struct doesn't have quite the size needed.
3396 /// \brief Rewrite an alloca partition's users.
3398 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3399 /// to rewrite uses of an alloca partition to be conducive for SSA value
3400 /// promotion. If the partition needs a new, more refined alloca, this will
3401 /// build that new alloca, preserving as much type information as possible, and
3402 /// rewrite the uses of the old alloca to point at the new one and have the
3403 /// appropriate new offsets. It also evaluates how successful the rewrite was
3404 /// at enabling promotion and if it was successful queues the alloca to be
3406 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3407 AllocaPartitioning &P,
3408 AllocaPartitioning::iterator PI) {
3409 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
3410 bool IsLive = false;
3411 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3413 UI != UE && !IsLive; ++UI)
3417 return false; // No live uses left of this partition.
3419 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3420 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3422 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3423 DEBUG(dbgs() << " speculating ");
3424 DEBUG(P.print(dbgs(), PI, ""));
3425 Speculator.visitUsers(PI);
3427 // Try to compute a friendly type for this partition of the alloca. This
3428 // won't always succeed, in which case we fall back to a legal integer type
3429 // or an i8 array of an appropriate size.
3431 if (Type *PartitionTy = P.getCommonType(PI))
3432 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3433 AllocaTy = PartitionTy;
3435 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3436 PI->BeginOffset, AllocaSize))
3437 AllocaTy = PartitionTy;
3439 (AllocaTy->isArrayTy() &&
3440 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3441 TD->isLegalInteger(AllocaSize * 8))
3442 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3444 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
3445 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
3447 // Check for the case where we're going to rewrite to a new alloca of the
3448 // exact same type as the original, and with the same access offsets. In that
3449 // case, re-use the existing alloca, but still run through the rewriter to
3450 // performe phi and select speculation.
3452 if (AllocaTy == AI.getAllocatedType()) {
3453 assert(PI->BeginOffset == 0 &&
3454 "Non-zero begin offset but same alloca type");
3455 assert(PI == P.begin() && "Begin offset is zero on later partition");
3458 unsigned Alignment = AI.getAlignment();
3460 // The minimum alignment which users can rely on when the explicit
3461 // alignment is omitted or zero is that required by the ABI for this
3463 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3465 Alignment = MinAlign(Alignment, PI->BeginOffset);
3466 // If we will get at least this much alignment from the type alone, leave
3467 // the alloca's alignment unconstrained.
3468 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3470 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
3471 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3476 DEBUG(dbgs() << "Rewriting alloca partition "
3477 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3480 // Track the high watermark of the post-promotion worklist. We will reset it
3481 // to this point if the alloca is not in fact scheduled for promotion.
3482 unsigned PPWOldSize = PostPromotionWorklist.size();
3484 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3485 PI->BeginOffset, PI->EndOffset);
3486 DEBUG(dbgs() << " rewriting ");
3487 DEBUG(P.print(dbgs(), PI, ""));
3488 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3490 DEBUG(dbgs() << " and queuing for promotion\n");
3491 PromotableAllocas.push_back(NewAI);
3492 } else if (NewAI != &AI) {
3493 // If we can't promote the alloca, iterate on it to check for new
3494 // refinements exposed by splitting the current alloca. Don't iterate on an
3495 // alloca which didn't actually change and didn't get promoted.
3496 Worklist.insert(NewAI);
3499 // Drop any post-promotion work items if promotion didn't happen.
3501 while (PostPromotionWorklist.size() > PPWOldSize)
3502 PostPromotionWorklist.pop_back();
3507 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3508 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3509 bool Changed = false;
3510 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3512 Changed |= rewriteAllocaPartition(AI, P, PI);
3517 /// \brief Analyze an alloca for SROA.
3519 /// This analyzes the alloca to ensure we can reason about it, builds
3520 /// a partitioning of the alloca, and then hands it off to be split and
3521 /// rewritten as needed.
3522 bool SROA::runOnAlloca(AllocaInst &AI) {
3523 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3524 ++NumAllocasAnalyzed;
3526 // Special case dead allocas, as they're trivial.
3527 if (AI.use_empty()) {
3528 AI.eraseFromParent();
3532 // Skip alloca forms that this analysis can't handle.
3533 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3534 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3537 bool Changed = false;
3539 // First, split any FCA loads and stores touching this alloca to promote
3540 // better splitting and promotion opportunities.
3541 AggLoadStoreRewriter AggRewriter(*TD);
3542 Changed |= AggRewriter.rewrite(AI);
3544 // Build the partition set using a recursive instruction-visiting builder.
3545 AllocaPartitioning P(*TD, AI);
3546 DEBUG(P.print(dbgs()));
3550 // Delete all the dead users of this alloca before splitting and rewriting it.
3551 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3552 DE = P.dead_user_end();
3555 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3556 DeadInsts.insert(*DI);
3558 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3559 DE = P.dead_op_end();
3562 // Clobber the use with an undef value.
3563 **DO = UndefValue::get(OldV->getType());
3564 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3565 if (isInstructionTriviallyDead(OldI)) {
3567 DeadInsts.insert(OldI);
3571 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3572 if (P.begin() == P.end())
3575 return splitAlloca(AI, P) || Changed;
3578 /// \brief Delete the dead instructions accumulated in this run.
3580 /// Recursively deletes the dead instructions we've accumulated. This is done
3581 /// at the very end to maximize locality of the recursive delete and to
3582 /// minimize the problems of invalidated instruction pointers as such pointers
3583 /// are used heavily in the intermediate stages of the algorithm.
3585 /// We also record the alloca instructions deleted here so that they aren't
3586 /// subsequently handed to mem2reg to promote.
3587 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3588 while (!DeadInsts.empty()) {
3589 Instruction *I = DeadInsts.pop_back_val();
3590 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3592 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3594 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3595 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3596 // Zero out the operand and see if it becomes trivially dead.
3598 if (isInstructionTriviallyDead(U))
3599 DeadInsts.insert(U);
3602 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3603 DeletedAllocas.insert(AI);
3606 I->eraseFromParent();
3610 /// \brief Promote the allocas, using the best available technique.
3612 /// This attempts to promote whatever allocas have been identified as viable in
3613 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3614 /// If there is a domtree available, we attempt to promote using the full power
3615 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3616 /// based on the SSAUpdater utilities. This function returns whether any
3617 /// promotion occured.
3618 bool SROA::promoteAllocas(Function &F) {
3619 if (PromotableAllocas.empty())
3622 NumPromoted += PromotableAllocas.size();
3624 if (DT && !ForceSSAUpdater) {
3625 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3626 PromoteMemToReg(PromotableAllocas, *DT);
3627 PromotableAllocas.clear();
3631 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3633 DIBuilder DIB(*F.getParent());
3634 SmallVector<Instruction*, 64> Insts;
3636 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3637 AllocaInst *AI = PromotableAllocas[Idx];
3638 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3640 Instruction *I = cast<Instruction>(*UI++);
3641 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3642 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3643 // leading to them) here. Eventually it should use them to optimize the
3644 // scalar values produced.
3645 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3646 assert(onlyUsedByLifetimeMarkers(I) &&
3647 "Found a bitcast used outside of a lifetime marker.");
3648 while (!I->use_empty())
3649 cast<Instruction>(*I->use_begin())->eraseFromParent();
3650 I->eraseFromParent();
3653 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3654 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3655 II->getIntrinsicID() == Intrinsic::lifetime_end);
3656 II->eraseFromParent();
3662 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3666 PromotableAllocas.clear();
3671 /// \brief A predicate to test whether an alloca belongs to a set.
3672 class IsAllocaInSet {
3673 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3677 typedef AllocaInst *argument_type;
3679 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3680 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
3684 bool SROA::runOnFunction(Function &F) {
3685 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3686 C = &F.getContext();
3687 TD = getAnalysisIfAvailable<DataLayout>();
3689 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3692 DT = getAnalysisIfAvailable<DominatorTree>();
3694 BasicBlock &EntryBB = F.getEntryBlock();
3695 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3697 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3698 Worklist.insert(AI);
3700 bool Changed = false;
3701 // A set of deleted alloca instruction pointers which should be removed from
3702 // the list of promotable allocas.
3703 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3706 while (!Worklist.empty()) {
3707 Changed |= runOnAlloca(*Worklist.pop_back_val());
3708 deleteDeadInstructions(DeletedAllocas);
3710 // Remove the deleted allocas from various lists so that we don't try to
3711 // continue processing them.
3712 if (!DeletedAllocas.empty()) {
3713 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3714 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3715 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3716 PromotableAllocas.end(),
3717 IsAllocaInSet(DeletedAllocas)),
3718 PromotableAllocas.end());
3719 DeletedAllocas.clear();
3723 Changed |= promoteAllocas(F);
3725 Worklist = PostPromotionWorklist;
3726 PostPromotionWorklist.clear();
3727 } while (!Worklist.empty());
3732 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3733 if (RequiresDomTree)
3734 AU.addRequired<DominatorTree>();
3735 AU.setPreservesCFG();