1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This transformation implements the well known scalar replacement of
11 /// aggregates transformation. It tries to identify promotable elements of an
12 /// aggregate alloca, and promote them to registers. It will also try to
13 /// convert uses of an element (or set of elements) of an alloca into a vector
14 /// or bitfield-style integer scalar if appropriate.
16 /// It works to do this with minimal slicing of the alloca so that regions
17 /// which are merely transferred in and out of external memory remain unchanged
18 /// and are not decomposed to scalar code.
20 /// Because this also performs alloca promotion, it can be thought of as also
21 /// serving the purpose of SSA formation. The algorithm iterates on the
22 /// function until all opportunities for promotion have been realized.
24 //===----------------------------------------------------------------------===//
26 #define DEBUG_TYPE "sroa"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DIBuilder.h"
30 #include "llvm/DebugInfo.h"
31 #include "llvm/DerivedTypes.h"
32 #include "llvm/Function.h"
33 #include "llvm/IRBuilder.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/IntrinsicInst.h"
36 #include "llvm/LLVMContext.h"
37 #include "llvm/Module.h"
38 #include "llvm/Operator.h"
39 #include "llvm/Pass.h"
40 #include "llvm/ADT/SetVector.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/Analysis/Dominators.h"
45 #include "llvm/Analysis/Loads.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetData.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.
136 /// FIXME: At some point we should consider loads and stores of FCAs to be
137 /// splittable and eagerly split them into scalar values.
140 Partition() : ByteRange(), IsSplittable() {}
141 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
142 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
145 /// \brief A particular use of a partition of the alloca.
147 /// This structure is used to associate uses of a partition with it. They
148 /// mark the range of bytes which are referenced by a particular instruction,
149 /// and includes a handle to the user itself and the pointer value in use.
150 /// The bounds of these uses are determined by intersecting the bounds of the
151 /// memory use itself with a particular partition. As a consequence there is
152 /// intentionally overlap between various uses of the same partition.
153 struct PartitionUse : public ByteRange {
154 /// \brief The use in question. Provides access to both user and used value.
156 /// Note that this may be null if the partition use is *dead*, that is, it
157 /// should be ignored.
160 PartitionUse() : ByteRange(), U() {}
161 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
162 : ByteRange(BeginOffset, EndOffset), U(U) {}
165 /// \brief Construct a partitioning of a particular alloca.
167 /// Construction does most of the work for partitioning the alloca. This
168 /// performs the necessary walks of users and builds a partitioning from it.
169 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
171 /// \brief Test whether a pointer to the allocation escapes our analysis.
173 /// If this is true, the partitioning is never fully built and should be
175 bool isEscaped() const { return PointerEscapingInstr; }
177 /// \brief Support for iterating over the partitions.
179 typedef SmallVectorImpl<Partition>::iterator iterator;
180 iterator begin() { return Partitions.begin(); }
181 iterator end() { return Partitions.end(); }
183 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
184 const_iterator begin() const { return Partitions.begin(); }
185 const_iterator end() const { return Partitions.end(); }
188 /// \brief Support for iterating over and manipulating a particular
189 /// partition's uses.
191 /// The iteration support provided for uses is more limited, but also
192 /// includes some manipulation routines to support rewriting the uses of
193 /// partitions during SROA.
195 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
196 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
197 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
198 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
199 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
201 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
202 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
203 const_use_iterator use_begin(const_iterator I) const {
204 return Uses[I - begin()].begin();
206 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
207 const_use_iterator use_end(const_iterator I) const {
208 return Uses[I - begin()].end();
211 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
212 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
213 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
214 return Uses[PIdx][UIdx];
216 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
217 return Uses[I - begin()][UIdx];
220 void use_push_back(unsigned Idx, const PartitionUse &PU) {
221 Uses[Idx].push_back(PU);
223 void use_push_back(const_iterator I, const PartitionUse &PU) {
224 Uses[I - begin()].push_back(PU);
228 /// \brief Allow iterating the dead users for this alloca.
230 /// These are instructions which will never actually use the alloca as they
231 /// are outside the allocated range. They are safe to replace with undef and
234 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
235 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
236 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
239 /// \brief Allow iterating the dead expressions referring to this alloca.
241 /// These are operands which have cannot actually be used to refer to the
242 /// alloca as they are outside its range and the user doesn't correct for
243 /// that. These mostly consist of PHI node inputs and the like which we just
244 /// need to replace with undef.
246 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
247 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
248 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
251 /// \brief MemTransferInst auxiliary data.
252 /// This struct provides some auxiliary data about memory transfer
253 /// intrinsics such as memcpy and memmove. These intrinsics can use two
254 /// different ranges within the same alloca, and provide other challenges to
255 /// correctly represent. We stash extra data to help us untangle this
256 /// after the partitioning is complete.
257 struct MemTransferOffsets {
258 uint64_t DestBegin, DestEnd;
259 uint64_t SourceBegin, SourceEnd;
262 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
263 return MemTransferInstData.lookup(&II);
266 /// \brief Map from a PHI or select operand back to a partition.
268 /// When manipulating PHI nodes or selects, they can use more than one
269 /// partition of an alloca. We store a special mapping to allow finding the
270 /// partition referenced by each of these operands, if any.
271 iterator findPartitionForPHIOrSelectOperand(Use *U) {
272 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
273 = PHIOrSelectOpMap.find(U);
274 if (MapIt == PHIOrSelectOpMap.end())
277 return begin() + MapIt->second.first;
280 /// \brief Map from a PHI or select operand back to the specific use of
283 /// Similar to mapping these operands back to the partitions, this maps
284 /// directly to the use structure of that partition.
285 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
286 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
287 = PHIOrSelectOpMap.find(U);
288 assert(MapIt != PHIOrSelectOpMap.end());
289 return Uses[MapIt->second.first].begin() + MapIt->second.second;
292 /// \brief Compute a common type among the uses of a particular partition.
294 /// This routines walks all of the uses of a particular partition and tries
295 /// to find a common type between them. Untyped operations such as memset and
296 /// memcpy are ignored.
297 Type *getCommonType(iterator I) const;
299 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
300 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
301 void printUsers(raw_ostream &OS, const_iterator I,
302 StringRef Indent = " ") const;
303 void print(raw_ostream &OS) const;
304 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
305 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
309 template <typename DerivedT, typename RetT = void> class BuilderBase;
310 class PartitionBuilder;
311 friend class AllocaPartitioning::PartitionBuilder;
313 friend class AllocaPartitioning::UseBuilder;
316 /// \brief Handle to alloca instruction to simplify method interfaces.
320 /// \brief The instruction responsible for this alloca having no partitioning.
322 /// When an instruction (potentially) escapes the pointer to the alloca, we
323 /// store a pointer to that here and abort trying to partition the alloca.
324 /// This will be null if the alloca is partitioned successfully.
325 Instruction *PointerEscapingInstr;
327 /// \brief The partitions of the alloca.
329 /// We store a vector of the partitions over the alloca here. This vector is
330 /// sorted by increasing begin offset, and then by decreasing end offset. See
331 /// the Partition inner class for more details. Initially (during
332 /// construction) there are overlaps, but we form a disjoint sequence of
333 /// partitions while finishing construction and a fully constructed object is
334 /// expected to always have this as a disjoint space.
335 SmallVector<Partition, 8> Partitions;
337 /// \brief The uses of the partitions.
339 /// This is essentially a mapping from each partition to a list of uses of
340 /// that partition. The mapping is done with a Uses vector that has the exact
341 /// same number of entries as the partition vector. Each entry is itself
342 /// a vector of the uses.
343 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
345 /// \brief Instructions which will become dead if we rewrite the alloca.
347 /// Note that these are not separated by partition. This is because we expect
348 /// a partitioned alloca to be completely rewritten or not rewritten at all.
349 /// If rewritten, all these instructions can simply be removed and replaced
350 /// with undef as they come from outside of the allocated space.
351 SmallVector<Instruction *, 8> DeadUsers;
353 /// \brief Operands which will become dead if we rewrite the alloca.
355 /// These are operands that in their particular use can be replaced with
356 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
357 /// to PHI nodes and the like. They aren't entirely dead (there might be
358 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
359 /// want to swap this particular input for undef to simplify the use lists of
361 SmallVector<Use *, 8> DeadOperands;
363 /// \brief The underlying storage for auxiliary memcpy and memset info.
364 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
366 /// \brief A side datastructure used when building up the partitions and uses.
368 /// This mapping is only really used during the initial building of the
369 /// partitioning so that we can retain information about PHI and select nodes
371 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
373 /// \brief Auxiliary information for particular PHI or select operands.
374 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
376 /// \brief A utility routine called from the constructor.
378 /// This does what it says on the tin. It is the key of the alloca partition
379 /// splitting and merging. After it is called we have the desired disjoint
380 /// collection of partitions.
381 void splitAndMergePartitions();
385 template <typename DerivedT, typename RetT>
386 class AllocaPartitioning::BuilderBase
387 : public InstVisitor<DerivedT, RetT> {
389 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
391 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
397 const TargetData &TD;
398 const uint64_t AllocSize;
399 AllocaPartitioning &P;
401 SmallPtrSet<Use *, 8> VisitedUses;
407 SmallVector<OffsetUse, 8> Queue;
409 // The active offset and use while visiting.
413 void enqueueUsers(Instruction &I, int64_t UserOffset) {
414 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
416 if (VisitedUses.insert(&UI.getUse())) {
417 OffsetUse OU = { &UI.getUse(), UserOffset };
423 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
425 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
427 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
433 // Handle a struct index, which adds its field offset to the pointer.
434 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
435 unsigned ElementIdx = OpC->getZExtValue();
436 const StructLayout *SL = TD.getStructLayout(STy);
437 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
438 // Check that we can continue to model this GEP in a signed 64-bit offset.
439 if (ElementOffset > INT64_MAX ||
441 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
442 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
443 << "what can be represented in an int64_t!\n"
444 << " alloca: " << P.AI << "\n");
448 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
450 GEPOffset += ElementOffset;
454 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
455 Index *= APInt(Index.getBitWidth(),
456 TD.getTypeAllocSize(GTI.getIndexedType()));
457 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
459 // Check if the result can be stored in our int64_t offset.
460 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
461 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
462 << "what can be represented in an int64_t!\n"
463 << " alloca: " << P.AI << "\n");
467 GEPOffset = Index.getSExtValue();
472 Value *foldSelectInst(SelectInst &SI) {
473 // If the condition being selected on is a constant or the same value is
474 // being selected between, fold the select. Yes this does (rarely) happen
476 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
477 return SI.getOperand(1+CI->isZero());
478 if (SI.getOperand(1) == SI.getOperand(2)) {
479 assert(*U == SI.getOperand(1));
480 return SI.getOperand(1);
486 /// \brief Builder for the alloca partitioning.
488 /// This class builds an alloca partitioning by recursively visiting the uses
489 /// of an alloca and splitting the partitions for each load and store at each
491 class AllocaPartitioning::PartitionBuilder
492 : public BuilderBase<PartitionBuilder, bool> {
493 friend class InstVisitor<PartitionBuilder, bool>;
495 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
498 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
499 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
501 /// \brief Run the builder over the allocation.
503 // Note that we have to re-evaluate size on each trip through the loop as
504 // the queue grows at the tail.
505 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
507 Offset = Queue[Idx].Offset;
508 if (!visit(cast<Instruction>(U->getUser())))
515 bool markAsEscaping(Instruction &I) {
516 P.PointerEscapingInstr = &I;
520 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
521 bool IsSplittable = false) {
522 // Completely skip uses which have a zero size or don't overlap the
525 (Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
526 (Offset < 0 && (uint64_t)-Offset >= Size)) {
527 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
528 << " which starts past the end of the " << AllocSize
530 << " alloca: " << P.AI << "\n"
531 << " use: " << I << "\n");
535 // Clamp the start to the beginning of the allocation.
537 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
538 << " to start at the beginning of the alloca:\n"
539 << " alloca: " << P.AI << "\n"
540 << " use: " << I << "\n");
541 Size -= (uint64_t)-Offset;
545 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
547 // Clamp the end offset to the end of the allocation. Note that this is
548 // formulated to handle even the case where "BeginOffset + Size" overflows.
549 assert(AllocSize >= BeginOffset); // Established above.
550 if (Size > AllocSize - BeginOffset) {
551 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
552 << " to remain within the " << AllocSize << " byte alloca:\n"
553 << " alloca: " << P.AI << "\n"
554 << " use: " << I << "\n");
555 EndOffset = AllocSize;
558 // See if we can just add a user onto the last slot currently occupied.
559 if (!P.Partitions.empty() &&
560 P.Partitions.back().BeginOffset == BeginOffset &&
561 P.Partitions.back().EndOffset == EndOffset) {
562 P.Partitions.back().IsSplittable &= IsSplittable;
566 Partition New(BeginOffset, EndOffset, IsSplittable);
567 P.Partitions.push_back(New);
570 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
571 uint64_t Size = TD.getTypeStoreSize(Ty);
573 // If this memory access can be shown to *statically* extend outside the
574 // bounds of of the allocation, it's behavior is undefined, so simply
575 // ignore it. Note that this is more strict than the generic clamping
576 // behavior of insertUse. We also try to handle cases which might run the
578 // FIXME: We should instead consider the pointer to have escaped if this
579 // function is being instrumented for addressing bugs or race conditions.
580 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
581 Size > (AllocSize - (uint64_t)Offset)) {
582 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
583 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
584 << " which extends past the end of the " << AllocSize
586 << " alloca: " << P.AI << "\n"
587 << " use: " << I << "\n");
591 insertUse(I, Offset, Size);
595 bool visitBitCastInst(BitCastInst &BC) {
596 enqueueUsers(BC, Offset);
600 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
602 if (!computeConstantGEPOffset(GEPI, GEPOffset))
603 return markAsEscaping(GEPI);
605 enqueueUsers(GEPI, GEPOffset);
609 bool visitLoadInst(LoadInst &LI) {
610 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
611 "All simple FCA loads should have been pre-split");
612 return handleLoadOrStore(LI.getType(), LI, Offset);
615 bool visitStoreInst(StoreInst &SI) {
616 Value *ValOp = SI.getValueOperand();
618 return markAsEscaping(SI);
620 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
621 "All simple FCA stores should have been pre-split");
622 return handleLoadOrStore(ValOp->getType(), SI, Offset);
626 bool visitMemSetInst(MemSetInst &II) {
627 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
628 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
629 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
630 insertUse(II, Offset, Size, Length);
634 bool visitMemTransferInst(MemTransferInst &II) {
635 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
636 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
638 // Zero-length mem transfer intrinsics can be ignored entirely.
641 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
643 // Only intrinsics with a constant length can be split.
644 Offsets.IsSplittable = Length;
646 if (*U != II.getRawDest()) {
647 assert(*U == II.getRawSource());
648 Offsets.SourceBegin = Offset;
649 Offsets.SourceEnd = Offset + Size;
651 Offsets.DestBegin = Offset;
652 Offsets.DestEnd = Offset + Size;
655 insertUse(II, Offset, Size, Offsets.IsSplittable);
656 unsigned NewIdx = P.Partitions.size() - 1;
658 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
659 bool Inserted = false;
660 llvm::tie(PMI, Inserted)
661 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
662 if (Offsets.IsSplittable &&
663 (!Inserted || II.getRawSource() == II.getRawDest())) {
664 // We've found a memory transfer intrinsic which refers to the alloca as
665 // both a source and dest. This is detected either by direct equality of
666 // the operand values, or when we visit the intrinsic twice due to two
667 // different chains of values leading to it. We refuse to split these to
668 // simplify splitting logic. If possible, SROA will still split them into
669 // separate allocas and then re-analyze.
670 Offsets.IsSplittable = false;
671 P.Partitions[PMI->second].IsSplittable = false;
672 P.Partitions[NewIdx].IsSplittable = false;
678 // Disable SRoA for any intrinsics except for lifetime invariants.
679 // FIXME: What about debug instrinsics? This matches old behavior, but
680 // doesn't make sense.
681 bool visitIntrinsicInst(IntrinsicInst &II) {
682 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
683 II.getIntrinsicID() == Intrinsic::lifetime_end) {
684 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
685 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
686 insertUse(II, Offset, Size, true);
690 return markAsEscaping(II);
693 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
694 // We consider any PHI or select that results in a direct load or store of
695 // the same offset to be a viable use for partitioning purposes. These uses
696 // are considered unsplittable and the size is the maximum loaded or stored
698 SmallPtrSet<Instruction *, 4> Visited;
699 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
700 Visited.insert(Root);
701 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
702 // If there are no loads or stores, the access is dead. We mark that as
703 // a size zero access.
706 Instruction *I, *UsedI;
707 llvm::tie(UsedI, I) = Uses.pop_back_val();
709 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
710 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
713 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
714 Value *Op = SI->getOperand(0);
717 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
721 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
722 if (!GEP->hasAllZeroIndices())
724 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
725 !isa<SelectInst>(I)) {
729 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
731 if (Visited.insert(cast<Instruction>(*UI)))
732 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
733 } while (!Uses.empty());
738 bool visitPHINode(PHINode &PN) {
739 // See if we already have computed info on this node.
740 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
742 PHIInfo.second = true;
743 insertUse(PN, Offset, PHIInfo.first);
747 // Check for an unsafe use of the PHI node.
748 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
749 return markAsEscaping(*EscapingI);
751 insertUse(PN, Offset, PHIInfo.first);
755 bool visitSelectInst(SelectInst &SI) {
756 if (Value *Result = foldSelectInst(SI)) {
758 // If the result of the constant fold will be the pointer, recurse
759 // through the select as if we had RAUW'ed it.
760 enqueueUsers(SI, Offset);
765 // See if we already have computed info on this node.
766 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
767 if (SelectInfo.first) {
768 SelectInfo.second = true;
769 insertUse(SI, Offset, SelectInfo.first);
773 // Check for an unsafe use of the PHI node.
774 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
775 return markAsEscaping(*EscapingI);
777 insertUse(SI, Offset, SelectInfo.first);
781 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
782 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
786 /// \brief Use adder for the alloca partitioning.
788 /// This class adds the uses of an alloca to all of the partitions which they
789 /// use. For splittable partitions, this can end up doing essentially a linear
790 /// walk of the partitions, but the number of steps remains bounded by the
791 /// total result instruction size:
792 /// - The number of partitions is a result of the number unsplittable
793 /// instructions using the alloca.
794 /// - The number of users of each partition is at worst the total number of
795 /// splittable instructions using the alloca.
796 /// Thus we will produce N * M instructions in the end, where N are the number
797 /// of unsplittable uses and M are the number of splittable. This visitor does
798 /// the exact same number of updates to the partitioning.
800 /// In the more common case, this visitor will leverage the fact that the
801 /// partition space is pre-sorted, and do a logarithmic search for the
802 /// partition needed, making the total visit a classical ((N + M) * log(N))
803 /// complexity operation.
804 class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
805 friend class InstVisitor<UseBuilder>;
807 /// \brief Set to de-duplicate dead instructions found in the use walk.
808 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
811 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
812 : BuilderBase<UseBuilder>(TD, AI, P) {}
814 /// \brief Run the builder over the allocation.
816 // Note that we have to re-evaluate size on each trip through the loop as
817 // the queue grows at the tail.
818 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
820 Offset = Queue[Idx].Offset;
821 this->visit(cast<Instruction>(U->getUser()));
826 void markAsDead(Instruction &I) {
827 if (VisitedDeadInsts.insert(&I))
828 P.DeadUsers.push_back(&I);
831 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
832 // If the use has a zero size or extends outside of the allocation, record
833 // it as a dead use for elimination later.
834 if (Size == 0 || (uint64_t)Offset >= AllocSize ||
835 (Offset < 0 && (uint64_t)-Offset >= Size))
836 return markAsDead(User);
838 // Clamp the start to the beginning of the allocation.
840 Size -= (uint64_t)-Offset;
844 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
846 // Clamp the end offset to the end of the allocation. Note that this is
847 // formulated to handle even the case where "BeginOffset + Size" overflows.
848 assert(AllocSize >= BeginOffset); // Established above.
849 if (Size > AllocSize - BeginOffset)
850 EndOffset = AllocSize;
852 // NB: This only works if we have zero overlapping partitions.
853 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
854 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
856 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
858 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
859 std::min(I->EndOffset, EndOffset), U);
860 P.use_push_back(I, NewPU);
861 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
862 P.PHIOrSelectOpMap[U]
863 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
867 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
868 uint64_t Size = TD.getTypeStoreSize(Ty);
870 // If this memory access can be shown to *statically* extend outside the
871 // bounds of of the allocation, it's behavior is undefined, so simply
872 // ignore it. Note that this is more strict than the generic clamping
873 // behavior of insertUse.
874 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
875 Size > (AllocSize - (uint64_t)Offset))
876 return markAsDead(I);
878 insertUse(I, Offset, Size);
881 void visitBitCastInst(BitCastInst &BC) {
883 return markAsDead(BC);
885 enqueueUsers(BC, Offset);
888 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
889 if (GEPI.use_empty())
890 return markAsDead(GEPI);
893 if (!computeConstantGEPOffset(GEPI, GEPOffset))
894 llvm_unreachable("Unable to compute constant offset for use");
896 enqueueUsers(GEPI, GEPOffset);
899 void visitLoadInst(LoadInst &LI) {
900 handleLoadOrStore(LI.getType(), LI, Offset);
903 void visitStoreInst(StoreInst &SI) {
904 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
907 void visitMemSetInst(MemSetInst &II) {
908 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
909 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
910 insertUse(II, Offset, Size);
913 void visitMemTransferInst(MemTransferInst &II) {
914 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
915 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
916 insertUse(II, Offset, Size);
919 void visitIntrinsicInst(IntrinsicInst &II) {
920 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
921 II.getIntrinsicID() == Intrinsic::lifetime_end);
923 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
924 insertUse(II, Offset,
925 std::min(AllocSize - Offset, Length->getLimitedValue()));
928 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
929 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
931 // For PHI and select operands outside the alloca, we can't nuke the entire
932 // phi or select -- the other side might still be relevant, so we special
933 // case them here and use a separate structure to track the operands
934 // themselves which should be replaced with undef.
935 if (Offset >= AllocSize) {
936 P.DeadOperands.push_back(U);
940 insertUse(User, Offset, Size);
942 void visitPHINode(PHINode &PN) {
944 return markAsDead(PN);
946 insertPHIOrSelect(PN, Offset);
948 void visitSelectInst(SelectInst &SI) {
950 return markAsDead(SI);
952 if (Value *Result = foldSelectInst(SI)) {
954 // If the result of the constant fold will be the pointer, recurse
955 // through the select as if we had RAUW'ed it.
956 enqueueUsers(SI, Offset);
958 // Otherwise the operand to the select is dead, and we can replace it
960 P.DeadOperands.push_back(U);
965 insertPHIOrSelect(SI, Offset);
968 /// \brief Unreachable, we've already visited the alloca once.
969 void visitInstruction(Instruction &I) {
970 llvm_unreachable("Unhandled instruction in use builder.");
974 void AllocaPartitioning::splitAndMergePartitions() {
975 size_t NumDeadPartitions = 0;
977 // Track the range of splittable partitions that we pass when accumulating
978 // overlapping unsplittable partitions.
979 uint64_t SplitEndOffset = 0ull;
981 Partition New(0ull, 0ull, false);
983 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
986 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
987 assert(New.BeginOffset == New.EndOffset);
990 assert(New.IsSplittable);
991 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
993 assert(New.BeginOffset != New.EndOffset);
995 // Scan the overlapping partitions.
996 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
997 // If the new partition we are forming is splittable, stop at the first
998 // unsplittable partition.
999 if (New.IsSplittable && !Partitions[j].IsSplittable)
1002 // Grow the new partition to include any equally splittable range. 'j' is
1003 // always equally splittable when New is splittable, but when New is not
1004 // splittable, we may subsume some (or part of some) splitable partition
1005 // without growing the new one.
1006 if (New.IsSplittable == Partitions[j].IsSplittable) {
1007 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1009 assert(!New.IsSplittable);
1010 assert(Partitions[j].IsSplittable);
1011 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1014 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
1015 ++NumDeadPartitions;
1019 // If the new partition is splittable, chop off the end as soon as the
1020 // unsplittable subsequent partition starts and ensure we eventually cover
1021 // the splittable area.
1022 if (j != e && New.IsSplittable) {
1023 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1024 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1027 // Add the new partition if it differs from the original one and is
1028 // non-empty. We can end up with an empty partition here if it was
1029 // splittable but there is an unsplittable one that starts at the same
1031 if (New != Partitions[i]) {
1032 if (New.BeginOffset != New.EndOffset)
1033 Partitions.push_back(New);
1034 // Mark the old one for removal.
1035 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
1036 ++NumDeadPartitions;
1039 New.BeginOffset = New.EndOffset;
1040 if (!New.IsSplittable) {
1041 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1042 if (j != e && !Partitions[j].IsSplittable)
1043 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1044 New.IsSplittable = true;
1045 // If there is a trailing splittable partition which won't be fused into
1046 // the next splittable partition go ahead and add it onto the partitions
1048 if (New.BeginOffset < New.EndOffset &&
1049 (j == e || !Partitions[j].IsSplittable ||
1050 New.EndOffset < Partitions[j].BeginOffset)) {
1051 Partitions.push_back(New);
1052 New.BeginOffset = New.EndOffset = 0ull;
1057 // Re-sort the partitions now that they have been split and merged into
1058 // disjoint set of partitions. Also remove any of the dead partitions we've
1059 // replaced in the process.
1060 std::sort(Partitions.begin(), Partitions.end());
1061 if (NumDeadPartitions) {
1062 assert(Partitions.back().BeginOffset == UINT64_MAX);
1063 assert(Partitions.back().EndOffset == UINT64_MAX);
1064 assert((ptrdiff_t)NumDeadPartitions ==
1065 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1067 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1070 AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
1075 PointerEscapingInstr(0) {
1076 PartitionBuilder PB(TD, AI, *this);
1080 if (Partitions.size() > 1) {
1081 // Sort the uses. This arranges for the offsets to be in ascending order,
1082 // and the sizes to be in descending order.
1083 std::sort(Partitions.begin(), Partitions.end());
1085 // Intersect splittability for all partitions with equal offsets and sizes.
1086 // Then remove all but the first so that we have a sequence of non-equal but
1087 // potentially overlapping partitions.
1088 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1091 while (J != E && *I == *J) {
1092 I->IsSplittable &= J->IsSplittable;
1096 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1099 // Split splittable and merge unsplittable partitions into a disjoint set
1100 // of partitions over the used space of the allocation.
1101 splitAndMergePartitions();
1104 // Now build up the user lists for each of these disjoint partitions by
1105 // re-walking the recursive users of the alloca.
1106 Uses.resize(Partitions.size());
1107 UseBuilder UB(TD, AI, *this);
1111 Type *AllocaPartitioning::getCommonType(iterator I) const {
1113 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1115 continue; // Skip dead uses.
1116 if (isa<IntrinsicInst>(*UI->U->getUser()))
1118 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1122 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
1123 UserTy = LI->getType();
1124 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
1125 UserTy = SI->getValueOperand()->getType();
1128 if (Ty && Ty != UserTy)
1136 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1138 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1139 StringRef Indent) const {
1140 OS << Indent << "partition #" << (I - begin())
1141 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1142 << (I->IsSplittable ? " (splittable)" : "")
1143 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1147 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1148 StringRef Indent) const {
1149 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1152 continue; // Skip dead uses.
1153 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1154 << "used by: " << *UI->U->getUser() << "\n";
1155 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
1156 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1158 if (!MTO.IsSplittable)
1159 IsDest = UI->BeginOffset == MTO.DestBegin;
1161 IsDest = MTO.DestBegin != 0u;
1162 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1163 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1164 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1169 void AllocaPartitioning::print(raw_ostream &OS) const {
1170 if (PointerEscapingInstr) {
1171 OS << "No partitioning for alloca: " << AI << "\n"
1172 << " A pointer to this alloca escaped by:\n"
1173 << " " << *PointerEscapingInstr << "\n";
1177 OS << "Partitioning of alloca: " << AI << "\n";
1179 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1185 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1186 void AllocaPartitioning::dump() const { print(dbgs()); }
1188 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1192 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1194 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1195 /// the loads and stores of an alloca instruction, as well as updating its
1196 /// debug information. This is used when a domtree is unavailable and thus
1197 /// mem2reg in its full form can't be used to handle promotion of allocas to
1199 class AllocaPromoter : public LoadAndStorePromoter {
1203 SmallVector<DbgDeclareInst *, 4> DDIs;
1204 SmallVector<DbgValueInst *, 4> DVIs;
1207 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1208 AllocaInst &AI, DIBuilder &DIB)
1209 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1211 void run(const SmallVectorImpl<Instruction*> &Insts) {
1212 // Remember which alloca we're promoting (for isInstInList).
1213 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1214 for (Value::use_iterator UI = DebugNode->use_begin(),
1215 UE = DebugNode->use_end();
1217 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1218 DDIs.push_back(DDI);
1219 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1220 DVIs.push_back(DVI);
1223 LoadAndStorePromoter::run(Insts);
1224 AI.eraseFromParent();
1225 while (!DDIs.empty())
1226 DDIs.pop_back_val()->eraseFromParent();
1227 while (!DVIs.empty())
1228 DVIs.pop_back_val()->eraseFromParent();
1231 virtual bool isInstInList(Instruction *I,
1232 const SmallVectorImpl<Instruction*> &Insts) const {
1233 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1234 return LI->getOperand(0) == &AI;
1235 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1238 virtual void updateDebugInfo(Instruction *Inst) const {
1239 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1240 E = DDIs.end(); I != E; ++I) {
1241 DbgDeclareInst *DDI = *I;
1242 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1243 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1244 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1245 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1247 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1248 E = DVIs.end(); I != E; ++I) {
1249 DbgValueInst *DVI = *I;
1251 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1252 // If an argument is zero extended then use argument directly. The ZExt
1253 // may be zapped by an optimization pass in future.
1254 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1255 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1256 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1257 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1259 Arg = SI->getOperand(0);
1260 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1261 Arg = LI->getOperand(0);
1265 Instruction *DbgVal =
1266 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1268 DbgVal->setDebugLoc(DVI->getDebugLoc());
1272 } // end anon namespace
1276 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1278 /// This pass takes allocations which can be completely analyzed (that is, they
1279 /// don't escape) and tries to turn them into scalar SSA values. There are
1280 /// a few steps to this process.
1282 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1283 /// are used to try to split them into smaller allocations, ideally of
1284 /// a single scalar data type. It will split up memcpy and memset accesses
1285 /// as necessary and try to isolate invidual scalar accesses.
1286 /// 2) It will transform accesses into forms which are suitable for SSA value
1287 /// promotion. This can be replacing a memset with a scalar store of an
1288 /// integer value, or it can involve speculating operations on a PHI or
1289 /// select to be a PHI or select of the results.
1290 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1291 /// onto insert and extract operations on a vector value, and convert them to
1292 /// this form. By doing so, it will enable promotion of vector aggregates to
1293 /// SSA vector values.
1294 class SROA : public FunctionPass {
1295 const bool RequiresDomTree;
1298 const TargetData *TD;
1301 /// \brief Worklist of alloca instructions to simplify.
1303 /// Each alloca in the function is added to this. Each new alloca formed gets
1304 /// added to it as well to recursively simplify unless that alloca can be
1305 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1306 /// the one being actively rewritten, we add it back onto the list if not
1307 /// already present to ensure it is re-visited.
1308 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1310 /// \brief A collection of instructions to delete.
1311 /// We try to batch deletions to simplify code and make things a bit more
1313 SmallVector<Instruction *, 8> DeadInsts;
1315 /// \brief A set to prevent repeatedly marking an instruction split into many
1316 /// uses as dead. Only used to guard insertion into DeadInsts.
1317 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1319 /// \brief Post-promotion worklist.
1321 /// Sometimes we discover an alloca which has a high probability of becoming
1322 /// viable for SROA after a round of promotion takes place. In those cases,
1323 /// the alloca is enqueued here for re-processing.
1325 /// Note that we have to be very careful to clear allocas out of this list in
1326 /// the event they are deleted.
1327 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1329 /// \brief A collection of alloca instructions we can directly promote.
1330 std::vector<AllocaInst *> PromotableAllocas;
1333 SROA(bool RequiresDomTree = true)
1334 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1335 C(0), TD(0), DT(0) {
1336 initializeSROAPass(*PassRegistry::getPassRegistry());
1338 bool runOnFunction(Function &F);
1339 void getAnalysisUsage(AnalysisUsage &AU) const;
1341 const char *getPassName() const { return "SROA"; }
1345 friend class PHIOrSelectSpeculator;
1346 friend class AllocaPartitionRewriter;
1347 friend class AllocaPartitionVectorRewriter;
1349 bool rewriteAllocaPartition(AllocaInst &AI,
1350 AllocaPartitioning &P,
1351 AllocaPartitioning::iterator PI);
1352 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1353 bool runOnAlloca(AllocaInst &AI);
1354 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
1355 bool promoteAllocas(Function &F);
1361 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1362 return new SROA(RequiresDomTree);
1365 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1367 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1368 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1371 /// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1373 /// If the provided GEP is all-constant, the total byte offset formed by the
1374 /// GEP is computed and Offset is set to it. If the GEP has any non-constant
1375 /// operands, the function returns false and the value of Offset is unmodified.
1376 static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1378 APInt GEPOffset(Offset.getBitWidth(), 0);
1379 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1380 GTI != GTE; ++GTI) {
1381 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1384 if (OpC->isZero()) continue;
1386 // Handle a struct index, which adds its field offset to the pointer.
1387 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1388 unsigned ElementIdx = OpC->getZExtValue();
1389 const StructLayout *SL = TD.getStructLayout(STy);
1390 GEPOffset += APInt(Offset.getBitWidth(),
1391 SL->getElementOffset(ElementIdx));
1395 APInt TypeSize(Offset.getBitWidth(),
1396 TD.getTypeAllocSize(GTI.getIndexedType()));
1397 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1398 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1399 "vector element size is not a multiple of 8, cannot GEP over it");
1400 TypeSize = VTy->getScalarSizeInBits() / 8;
1403 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1409 /// \brief Build a GEP out of a base pointer and indices.
1411 /// This will return the BasePtr if that is valid, or build a new GEP
1412 /// instruction using the IRBuilder if GEP-ing is needed.
1413 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1414 SmallVectorImpl<Value *> &Indices,
1415 const Twine &Prefix) {
1416 if (Indices.empty())
1419 // A single zero index is a no-op, so check for this and avoid building a GEP
1421 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1424 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1427 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1428 /// TargetTy without changing the offset of the pointer.
1430 /// This routine assumes we've already established a properly offset GEP with
1431 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1432 /// zero-indices down through type layers until we find one the same as
1433 /// TargetTy. If we can't find one with the same type, we at least try to use
1434 /// one with the same size. If none of that works, we just produce the GEP as
1435 /// indicated by Indices to have the correct offset.
1436 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1437 Value *BasePtr, Type *Ty, Type *TargetTy,
1438 SmallVectorImpl<Value *> &Indices,
1439 const Twine &Prefix) {
1441 return buildGEP(IRB, BasePtr, Indices, Prefix);
1443 // See if we can descend into a struct and locate a field with the correct
1445 unsigned NumLayers = 0;
1446 Type *ElementTy = Ty;
1448 if (ElementTy->isPointerTy())
1450 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1451 ElementTy = SeqTy->getElementType();
1452 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1453 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1454 ElementTy = *STy->element_begin();
1455 Indices.push_back(IRB.getInt32(0));
1460 } while (ElementTy != TargetTy);
1461 if (ElementTy != TargetTy)
1462 Indices.erase(Indices.end() - NumLayers, Indices.end());
1464 return buildGEP(IRB, BasePtr, Indices, Prefix);
1467 /// \brief Recursively compute indices for a natural GEP.
1469 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1470 /// element types adding appropriate indices for the GEP.
1471 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1472 Value *Ptr, Type *Ty, APInt &Offset,
1474 SmallVectorImpl<Value *> &Indices,
1475 const Twine &Prefix) {
1477 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1479 // We can't recurse through pointer types.
1480 if (Ty->isPointerTy())
1483 // We try to analyze GEPs over vectors here, but note that these GEPs are
1484 // extremely poorly defined currently. The long-term goal is to remove GEPing
1485 // over a vector from the IR completely.
1486 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1487 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1488 if (ElementSizeInBits % 8)
1489 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1490 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1491 APInt NumSkippedElements = Offset.udiv(ElementSize);
1492 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1494 Offset -= NumSkippedElements * ElementSize;
1495 Indices.push_back(IRB.getInt(NumSkippedElements));
1496 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1497 Offset, TargetTy, Indices, Prefix);
1500 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1501 Type *ElementTy = ArrTy->getElementType();
1502 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1503 APInt NumSkippedElements = Offset.udiv(ElementSize);
1504 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1507 Offset -= NumSkippedElements * ElementSize;
1508 Indices.push_back(IRB.getInt(NumSkippedElements));
1509 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1513 StructType *STy = dyn_cast<StructType>(Ty);
1517 const StructLayout *SL = TD.getStructLayout(STy);
1518 uint64_t StructOffset = Offset.getZExtValue();
1519 if (StructOffset >= SL->getSizeInBytes())
1521 unsigned Index = SL->getElementContainingOffset(StructOffset);
1522 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1523 Type *ElementTy = STy->getElementType(Index);
1524 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1525 return 0; // The offset points into alignment padding.
1527 Indices.push_back(IRB.getInt32(Index));
1528 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1532 /// \brief Get a natural GEP from a base pointer to a particular offset and
1533 /// resulting in a particular type.
1535 /// The goal is to produce a "natural" looking GEP that works with the existing
1536 /// composite types to arrive at the appropriate offset and element type for
1537 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1538 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1539 /// Indices, and setting Ty to the result subtype.
1541 /// If no natural GEP can be constructed, this function returns null.
1542 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1543 Value *Ptr, APInt Offset, Type *TargetTy,
1544 SmallVectorImpl<Value *> &Indices,
1545 const Twine &Prefix) {
1546 PointerType *Ty = cast<PointerType>(Ptr->getType());
1548 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1550 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1553 Type *ElementTy = Ty->getElementType();
1554 if (!ElementTy->isSized())
1555 return 0; // We can't GEP through an unsized element.
1556 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1557 if (ElementSize == 0)
1558 return 0; // Zero-length arrays can't help us build a natural GEP.
1559 APInt NumSkippedElements = Offset.udiv(ElementSize);
1561 Offset -= NumSkippedElements * ElementSize;
1562 Indices.push_back(IRB.getInt(NumSkippedElements));
1563 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1567 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1568 /// resulting pointer has PointerTy.
1570 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1571 /// and produces the pointer type desired. Where it cannot, it will try to use
1572 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1573 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1574 /// bitcast to the type.
1576 /// The strategy for finding the more natural GEPs is to peel off layers of the
1577 /// pointer, walking back through bit casts and GEPs, searching for a base
1578 /// pointer from which we can compute a natural GEP with the desired
1579 /// properities. The algorithm tries to fold as many constant indices into
1580 /// a single GEP as possible, thus making each GEP more independent of the
1581 /// surrounding code.
1582 static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1583 Value *Ptr, APInt Offset, Type *PointerTy,
1584 const Twine &Prefix) {
1585 // Even though we don't look through PHI nodes, we could be called on an
1586 // instruction in an unreachable block, which may be on a cycle.
1587 SmallPtrSet<Value *, 4> Visited;
1588 Visited.insert(Ptr);
1589 SmallVector<Value *, 4> Indices;
1591 // We may end up computing an offset pointer that has the wrong type. If we
1592 // never are able to compute one directly that has the correct type, we'll
1593 // fall back to it, so keep it around here.
1594 Value *OffsetPtr = 0;
1596 // Remember any i8 pointer we come across to re-use if we need to do a raw
1599 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1601 Type *TargetTy = PointerTy->getPointerElementType();
1604 // First fold any existing GEPs into the offset.
1605 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1606 APInt GEPOffset(Offset.getBitWidth(), 0);
1607 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1609 Offset += GEPOffset;
1610 Ptr = GEP->getPointerOperand();
1611 if (!Visited.insert(Ptr))
1615 // See if we can perform a natural GEP here.
1617 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1619 if (P->getType() == PointerTy) {
1620 // Zap any offset pointer that we ended up computing in previous rounds.
1621 if (OffsetPtr && OffsetPtr->use_empty())
1622 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1623 I->eraseFromParent();
1631 // Stash this pointer if we've found an i8*.
1632 if (Ptr->getType()->isIntegerTy(8)) {
1634 Int8PtrOffset = Offset;
1637 // Peel off a layer of the pointer and update the offset appropriately.
1638 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1639 Ptr = cast<Operator>(Ptr)->getOperand(0);
1640 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1641 if (GA->mayBeOverridden())
1643 Ptr = GA->getAliasee();
1647 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1648 } while (Visited.insert(Ptr));
1652 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1653 Prefix + ".raw_cast");
1654 Int8PtrOffset = Offset;
1657 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1658 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1659 Prefix + ".raw_idx");
1663 // On the off chance we were targeting i8*, guard the bitcast here.
1664 if (Ptr->getType() != PointerTy)
1665 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1670 /// \brief Test whether the given alloca partition can be promoted to a vector.
1672 /// This is a quick test to check whether we can rewrite a particular alloca
1673 /// partition (and its newly formed alloca) into a vector alloca with only
1674 /// whole-vector loads and stores such that it could be promoted to a vector
1675 /// SSA value. We only can ensure this for a limited set of operations, and we
1676 /// don't want to do the rewrites unless we are confident that the result will
1677 /// be promotable, so we have an early test here.
1678 static bool isVectorPromotionViable(const TargetData &TD,
1680 AllocaPartitioning &P,
1681 uint64_t PartitionBeginOffset,
1682 uint64_t PartitionEndOffset,
1683 AllocaPartitioning::const_use_iterator I,
1684 AllocaPartitioning::const_use_iterator E) {
1685 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1689 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1690 uint64_t ElementSize = Ty->getScalarSizeInBits();
1692 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1693 // that aren't byte sized.
1694 if (ElementSize % 8)
1696 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1700 for (; I != E; ++I) {
1702 continue; // Skip dead use.
1704 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1705 uint64_t BeginIndex = BeginOffset / ElementSize;
1706 if (BeginIndex * ElementSize != BeginOffset ||
1707 BeginIndex >= Ty->getNumElements())
1709 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1710 uint64_t EndIndex = EndOffset / ElementSize;
1711 if (EndIndex * ElementSize != EndOffset ||
1712 EndIndex > Ty->getNumElements())
1715 // FIXME: We should build shuffle vector instructions to handle
1716 // non-element-sized accesses.
1717 if ((EndOffset - BeginOffset) != ElementSize &&
1718 (EndOffset - BeginOffset) != VecSize)
1721 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
1722 if (MI->isVolatile())
1724 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
1725 const AllocaPartitioning::MemTransferOffsets &MTO
1726 = P.getMemTransferOffsets(*MTI);
1727 if (!MTO.IsSplittable)
1730 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
1731 // Disable vector promotion when there are loads or stores of an FCA.
1733 } else if (!isa<LoadInst>(I->U->getUser()) &&
1734 !isa<StoreInst>(I->U->getUser())) {
1741 /// \brief Test whether the given alloca partition can be promoted to an int.
1743 /// This is a quick test to check whether we can rewrite a particular alloca
1744 /// partition (and its newly formed alloca) into an integer alloca suitable for
1745 /// promotion to an SSA value. We only can ensure this for a limited set of
1746 /// operations, and we don't want to do the rewrites unless we are confident
1747 /// that the result will be promotable, so we have an early test here.
1748 static bool isIntegerPromotionViable(const TargetData &TD,
1750 uint64_t AllocBeginOffset,
1751 AllocaPartitioning &P,
1752 AllocaPartitioning::const_use_iterator I,
1753 AllocaPartitioning::const_use_iterator E) {
1754 IntegerType *Ty = dyn_cast<IntegerType>(AllocaTy);
1755 if (!Ty || 8*TD.getTypeStoreSize(Ty) != Ty->getBitWidth())
1758 // Check the uses to ensure the uses are (likely) promoteable integer uses.
1759 // Also ensure that the alloca has a covering load or store. We don't want
1760 // promote because of some other unsplittable entry (which we may make
1761 // splittable later) and lose the ability to promote each element access.
1762 bool WholeAllocaOp = false;
1763 for (; I != E; ++I) {
1765 continue; // Skip dead use.
1767 // We can't reasonably handle cases where the load or store extends past
1768 // the end of the aloca's type and into its padding.
1769 if ((I->EndOffset - AllocBeginOffset) > TD.getTypeStoreSize(Ty))
1772 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
1773 if (LI->isVolatile() || !LI->getType()->isIntegerTy())
1775 if (LI->getType() == Ty)
1776 WholeAllocaOp = true;
1777 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
1778 if (SI->isVolatile() || !SI->getValueOperand()->getType()->isIntegerTy())
1780 if (SI->getValueOperand()->getType() == Ty)
1781 WholeAllocaOp = true;
1782 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
1783 if (MI->isVolatile())
1785 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
1786 const AllocaPartitioning::MemTransferOffsets &MTO
1787 = P.getMemTransferOffsets(*MTI);
1788 if (!MTO.IsSplittable)
1795 return WholeAllocaOp;
1799 /// \brief Visitor to speculate PHIs and Selects where possible.
1800 class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1801 // Befriend the base class so it can delegate to private visit methods.
1802 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1804 const TargetData &TD;
1805 AllocaPartitioning &P;
1809 PHIOrSelectSpeculator(const TargetData &TD, AllocaPartitioning &P, SROA &Pass)
1810 : TD(TD), P(P), Pass(Pass) {}
1812 /// \brief Visit the users of an alloca partition and rewrite them.
1813 void visitUsers(AllocaPartitioning::const_iterator PI) {
1814 // Note that we need to use an index here as the underlying vector of uses
1815 // may be grown during speculation. However, we never need to re-visit the
1816 // new uses, and so we can use the initial size bound.
1817 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1818 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1820 continue; // Skip dead use.
1822 visit(cast<Instruction>(PU.U->getUser()));
1827 // By default, skip this instruction.
1828 void visitInstruction(Instruction &I) {}
1830 /// PHI instructions that use an alloca and are subsequently loaded can be
1831 /// rewritten to load both input pointers in the pred blocks and then PHI the
1832 /// results, allowing the load of the alloca to be promoted.
1834 /// %P2 = phi [i32* %Alloca, i32* %Other]
1835 /// %V = load i32* %P2
1837 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1839 /// %V2 = load i32* %Other
1841 /// %V = phi [i32 %V1, i32 %V2]
1843 /// We can do this to a select if its only uses are loads and if the operands
1844 /// to the select can be loaded unconditionally.
1846 /// FIXME: This should be hoisted into a generic utility, likely in
1847 /// Transforms/Util/Local.h
1848 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1849 // For now, we can only do this promotion if the load is in the same block
1850 // as the PHI, and if there are no stores between the phi and load.
1851 // TODO: Allow recursive phi users.
1852 // TODO: Allow stores.
1853 BasicBlock *BB = PN.getParent();
1854 unsigned MaxAlign = 0;
1855 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1857 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1858 if (LI == 0 || !LI->isSimple()) return false;
1860 // For now we only allow loads in the same block as the PHI. This is
1861 // a common case that happens when instcombine merges two loads through
1863 if (LI->getParent() != BB) return false;
1865 // Ensure that there are no instructions between the PHI and the load that
1867 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1868 if (BBI->mayWriteToMemory())
1871 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1872 Loads.push_back(LI);
1875 // We can only transform this if it is safe to push the loads into the
1876 // predecessor blocks. The only thing to watch out for is that we can't put
1877 // a possibly trapping load in the predecessor if it is a critical edge.
1878 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1880 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1881 Value *InVal = PN.getIncomingValue(Idx);
1883 // If the value is produced by the terminator of the predecessor (an
1884 // invoke) or it has side-effects, there is no valid place to put a load
1885 // in the predecessor.
1886 if (TI == InVal || TI->mayHaveSideEffects())
1889 // If the predecessor has a single successor, then the edge isn't
1891 if (TI->getNumSuccessors() == 1)
1894 // If this pointer is always safe to load, or if we can prove that there
1895 // is already a load in the block, then we can move the load to the pred
1897 if (InVal->isDereferenceablePointer() ||
1898 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1907 void visitPHINode(PHINode &PN) {
1908 DEBUG(dbgs() << " original: " << PN << "\n");
1910 SmallVector<LoadInst *, 4> Loads;
1911 if (!isSafePHIToSpeculate(PN, Loads))
1914 assert(!Loads.empty());
1916 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1917 IRBuilder<> PHIBuilder(&PN);
1918 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1919 PN.getName() + ".sroa.speculated");
1921 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1922 // matter which one we get and if any differ, it doesn't matter.
1923 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1924 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1925 unsigned Align = SomeLoad->getAlignment();
1927 // Rewrite all loads of the PN to use the new PHI.
1929 LoadInst *LI = Loads.pop_back_val();
1930 LI->replaceAllUsesWith(NewPN);
1931 Pass.DeadInsts.push_back(LI);
1932 } while (!Loads.empty());
1934 // Inject loads into all of the pred blocks.
1935 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1936 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1937 TerminatorInst *TI = Pred->getTerminator();
1938 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1939 Value *InVal = PN.getIncomingValue(Idx);
1940 IRBuilder<> PredBuilder(TI);
1943 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1945 ++NumLoadsSpeculated;
1946 Load->setAlignment(Align);
1948 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1949 NewPN->addIncoming(Load, Pred);
1951 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1953 // No uses to rewrite.
1956 // Try to lookup and rewrite any partition uses corresponding to this phi
1958 AllocaPartitioning::iterator PI
1959 = P.findPartitionForPHIOrSelectOperand(InUse);
1963 // Replace the Use in the PartitionUse for this operand with the Use
1965 AllocaPartitioning::use_iterator UI
1966 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1967 assert(isa<PHINode>(*UI->U->getUser()));
1968 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1970 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1973 /// Select instructions that use an alloca and are subsequently loaded can be
1974 /// rewritten to load both input pointers and then select between the result,
1975 /// allowing the load of the alloca to be promoted.
1977 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1978 /// %V = load i32* %P2
1980 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1981 /// %V2 = load i32* %Other
1982 /// %V = select i1 %cond, i32 %V1, i32 %V2
1984 /// We can do this to a select if its only uses are loads and if the operand
1985 /// to the select can be loaded unconditionally.
1986 bool isSafeSelectToSpeculate(SelectInst &SI,
1987 SmallVectorImpl<LoadInst *> &Loads) {
1988 Value *TValue = SI.getTrueValue();
1989 Value *FValue = SI.getFalseValue();
1990 bool TDerefable = TValue->isDereferenceablePointer();
1991 bool FDerefable = FValue->isDereferenceablePointer();
1993 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1995 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1996 if (LI == 0 || !LI->isSimple()) return false;
1998 // Both operands to the select need to be dereferencable, either
1999 // absolutely (e.g. allocas) or at this point because we can see other
2001 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
2002 LI->getAlignment(), &TD))
2004 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
2005 LI->getAlignment(), &TD))
2007 Loads.push_back(LI);
2013 void visitSelectInst(SelectInst &SI) {
2014 DEBUG(dbgs() << " original: " << SI << "\n");
2015 IRBuilder<> IRB(&SI);
2017 // If the select isn't safe to speculate, just use simple logic to emit it.
2018 SmallVector<LoadInst *, 4> Loads;
2019 if (!isSafeSelectToSpeculate(SI, Loads))
2022 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
2023 AllocaPartitioning::iterator PIs[2];
2024 AllocaPartitioning::PartitionUse PUs[2];
2025 for (unsigned i = 0, e = 2; i != e; ++i) {
2026 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
2027 if (PIs[i] != P.end()) {
2028 // If the pointer is within the partitioning, remove the select from
2029 // its uses. We'll add in the new loads below.
2030 AllocaPartitioning::use_iterator UI
2031 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
2033 // Clear out the use here so that the offsets into the use list remain
2034 // stable but this use is ignored when rewriting.
2039 Value *TV = SI.getTrueValue();
2040 Value *FV = SI.getFalseValue();
2041 // Replace the loads of the select with a select of two loads.
2042 while (!Loads.empty()) {
2043 LoadInst *LI = Loads.pop_back_val();
2045 IRB.SetInsertPoint(LI);
2047 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
2049 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
2050 NumLoadsSpeculated += 2;
2052 // Transfer alignment and TBAA info if present.
2053 TL->setAlignment(LI->getAlignment());
2054 FL->setAlignment(LI->getAlignment());
2055 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2056 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2057 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2060 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
2061 LI->getName() + ".sroa.speculated");
2063 LoadInst *Loads[2] = { TL, FL };
2064 for (unsigned i = 0, e = 2; i != e; ++i) {
2065 if (PIs[i] != P.end()) {
2066 Use *LoadUse = &Loads[i]->getOperandUse(0);
2067 assert(PUs[i].U->get() == LoadUse->get());
2069 P.use_push_back(PIs[i], PUs[i]);
2073 DEBUG(dbgs() << " speculated to: " << *V << "\n");
2074 LI->replaceAllUsesWith(V);
2075 Pass.DeadInsts.push_back(LI);
2080 /// \brief Visitor to rewrite instructions using a partition of an alloca to
2081 /// use a new alloca.
2083 /// Also implements the rewriting to vector-based accesses when the partition
2084 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2086 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2088 // Befriend the base class so it can delegate to private visit methods.
2089 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2091 const TargetData &TD;
2092 AllocaPartitioning &P;
2094 AllocaInst &OldAI, &NewAI;
2095 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2097 // If we are rewriting an alloca partition which can be written as pure
2098 // vector operations, we stash extra information here. When VecTy is
2099 // non-null, we have some strict guarantees about the rewriten alloca:
2100 // - The new alloca is exactly the size of the vector type here.
2101 // - The accesses all either map to the entire vector or to a single
2103 // - The set of accessing instructions is only one of those handled above
2104 // in isVectorPromotionViable. Generally these are the same access kinds
2105 // which are promotable via mem2reg.
2108 uint64_t ElementSize;
2110 // This is a convenience and flag variable that will be null unless the new
2111 // alloca has a promotion-targeted integer type due to passing
2112 // isIntegerPromotionViable above. If it is non-null does, the desired
2113 // integer type will be stored here for easy access during rewriting.
2114 IntegerType *IntPromotionTy;
2116 // The offset of the partition user currently being rewritten.
2117 uint64_t BeginOffset, EndOffset;
2119 Instruction *OldPtr;
2121 // The name prefix to use when rewriting instructions for this alloca.
2122 std::string NamePrefix;
2125 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
2126 AllocaPartitioning::iterator PI,
2127 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2128 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2129 : TD(TD), P(P), Pass(Pass),
2130 OldAI(OldAI), NewAI(NewAI),
2131 NewAllocaBeginOffset(NewBeginOffset),
2132 NewAllocaEndOffset(NewEndOffset),
2133 VecTy(), ElementTy(), ElementSize(), IntPromotionTy(),
2134 BeginOffset(), EndOffset() {
2137 /// \brief Visit the users of the alloca partition and rewrite them.
2138 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2139 AllocaPartitioning::const_use_iterator E) {
2140 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2141 NewAllocaBeginOffset, NewAllocaEndOffset,
2144 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2145 ElementTy = VecTy->getElementType();
2146 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2147 "Only multiple-of-8 sized vector elements are viable");
2148 ElementSize = VecTy->getScalarSizeInBits() / 8;
2149 } else if (isIntegerPromotionViable(TD, NewAI.getAllocatedType(),
2150 NewAllocaBeginOffset, P, I, E)) {
2151 IntPromotionTy = cast<IntegerType>(NewAI.getAllocatedType());
2153 bool CanSROA = true;
2154 for (; I != E; ++I) {
2156 continue; // Skip dead uses.
2157 BeginOffset = I->BeginOffset;
2158 EndOffset = I->EndOffset;
2160 OldPtr = cast<Instruction>(I->U->get());
2161 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
2162 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
2174 // Every instruction which can end up as a user must have a rewrite rule.
2175 bool visitInstruction(Instruction &I) {
2176 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2177 llvm_unreachable("No rewrite rule for this instruction!");
2180 Twine getName(const Twine &Suffix) {
2181 return NamePrefix + Suffix;
2184 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2185 assert(BeginOffset >= NewAllocaBeginOffset);
2186 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
2187 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2190 /// \brief Compute suitable alignment to access an offset into the new alloca.
2191 unsigned getOffsetAlign(uint64_t Offset) {
2192 unsigned NewAIAlign = NewAI.getAlignment();
2194 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2195 return MinAlign(NewAIAlign, Offset);
2198 /// \brief Compute suitable alignment to access this partition of the new
2200 unsigned getPartitionAlign() {
2201 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
2204 /// \brief Compute suitable alignment to access a type at an offset of the
2207 /// \returns zero if the type's ABI alignment is a suitable alignment,
2208 /// otherwise returns the maximal suitable alignment.
2209 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2210 unsigned Align = getOffsetAlign(Offset);
2211 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2214 /// \brief Compute suitable alignment to access a type at the beginning of
2215 /// this partition of the new alloca.
2217 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2218 unsigned getPartitionTypeAlign(Type *Ty) {
2219 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
2222 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
2223 assert(VecTy && "Can only call getIndex when rewriting a vector");
2224 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2225 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2226 uint32_t Index = RelOffset / ElementSize;
2227 assert(Index * ElementSize == RelOffset);
2228 return IRB.getInt32(Index);
2231 Value *extractInteger(IRBuilder<> &IRB, IntegerType *TargetTy,
2233 assert(IntPromotionTy && "Alloca is not an integer we can extract from");
2234 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2236 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
2237 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2238 assert(TD.getTypeStoreSize(TargetTy) + RelOffset <=
2239 TD.getTypeStoreSize(IntPromotionTy) &&
2240 "Element load outside of alloca store");
2241 uint64_t ShAmt = 8*RelOffset;
2242 if (TD.isBigEndian())
2243 ShAmt = 8*(TD.getTypeStoreSize(IntPromotionTy) -
2244 TD.getTypeStoreSize(TargetTy) - RelOffset);
2246 V = IRB.CreateLShr(V, ShAmt, getName(".shift"));
2247 if (TargetTy != IntPromotionTy) {
2248 assert(TargetTy->getBitWidth() < IntPromotionTy->getBitWidth() &&
2249 "Cannot extract to a larger integer!");
2250 V = IRB.CreateTrunc(V, TargetTy, getName(".trunc"));
2255 StoreInst *insertInteger(IRBuilder<> &IRB, Value *V, uint64_t Offset) {
2256 IntegerType *Ty = cast<IntegerType>(V->getType());
2257 if (Ty == IntPromotionTy)
2258 return IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2260 assert(Ty->getBitWidth() < IntPromotionTy->getBitWidth() &&
2261 "Cannot insert a larger integer!");
2262 V = IRB.CreateZExt(V, IntPromotionTy, getName(".ext"));
2263 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
2264 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2265 assert(TD.getTypeStoreSize(Ty) + RelOffset <=
2266 TD.getTypeStoreSize(IntPromotionTy) &&
2267 "Element store outside of alloca store");
2268 uint64_t ShAmt = 8*RelOffset;
2269 if (TD.isBigEndian())
2270 ShAmt = 8*(TD.getTypeStoreSize(IntPromotionTy) - TD.getTypeStoreSize(Ty)
2273 V = IRB.CreateShl(V, ShAmt, getName(".shift"));
2275 APInt Mask = ~Ty->getMask().zext(IntPromotionTy->getBitWidth()).shl(ShAmt);
2276 Value *Old = IRB.CreateAnd(IRB.CreateAlignedLoad(&NewAI,
2277 NewAI.getAlignment(),
2278 getName(".oldload")),
2279 Mask, getName(".mask"));
2280 return IRB.CreateAlignedStore(IRB.CreateOr(Old, V, getName(".insert")),
2281 &NewAI, NewAI.getAlignment());
2284 void deleteIfTriviallyDead(Value *V) {
2285 Instruction *I = cast<Instruction>(V);
2286 if (isInstructionTriviallyDead(I))
2287 Pass.DeadInsts.push_back(I);
2290 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
2291 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2292 return IRB.CreateIntToPtr(V, Ty);
2293 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2294 return IRB.CreatePtrToInt(V, Ty);
2296 return IRB.CreateBitCast(V, Ty);
2299 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2301 if (LI.getType() == VecTy->getElementType() ||
2302 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2303 Result = IRB.CreateExtractElement(
2304 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2305 getIndex(IRB, BeginOffset), getName(".extract"));
2307 Result = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2310 if (Result->getType() != LI.getType())
2311 Result = getValueCast(IRB, Result, LI.getType());
2312 LI.replaceAllUsesWith(Result);
2313 Pass.DeadInsts.push_back(&LI);
2315 DEBUG(dbgs() << " to: " << *Result << "\n");
2319 bool rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
2320 assert(!LI.isVolatile());
2321 Value *Result = extractInteger(IRB, cast<IntegerType>(LI.getType()),
2323 LI.replaceAllUsesWith(Result);
2324 Pass.DeadInsts.push_back(&LI);
2325 DEBUG(dbgs() << " to: " << *Result << "\n");
2329 bool visitLoadInst(LoadInst &LI) {
2330 DEBUG(dbgs() << " original: " << LI << "\n");
2331 Value *OldOp = LI.getOperand(0);
2332 assert(OldOp == OldPtr);
2333 IRBuilder<> IRB(&LI);
2336 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
2338 return rewriteIntegerLoad(IRB, LI);
2340 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2341 LI.getPointerOperand()->getType());
2342 LI.setOperand(0, NewPtr);
2343 LI.setAlignment(getPartitionTypeAlign(LI.getType()));
2344 DEBUG(dbgs() << " to: " << LI << "\n");
2346 deleteIfTriviallyDead(OldOp);
2347 return NewPtr == &NewAI && !LI.isVolatile();
2350 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
2352 Value *V = SI.getValueOperand();
2353 if (V->getType() == ElementTy ||
2354 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2355 if (V->getType() != ElementTy)
2356 V = getValueCast(IRB, V, ElementTy);
2357 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2359 V = IRB.CreateInsertElement(LI, V, getIndex(IRB, BeginOffset),
2360 getName(".insert"));
2361 } else if (V->getType() != VecTy) {
2362 V = getValueCast(IRB, V, VecTy);
2364 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2365 Pass.DeadInsts.push_back(&SI);
2368 DEBUG(dbgs() << " to: " << *Store << "\n");
2372 bool rewriteIntegerStore(IRBuilder<> &IRB, StoreInst &SI) {
2373 assert(!SI.isVolatile());
2374 StoreInst *Store = insertInteger(IRB, SI.getValueOperand(), BeginOffset);
2375 Pass.DeadInsts.push_back(&SI);
2377 DEBUG(dbgs() << " to: " << *Store << "\n");
2381 bool visitStoreInst(StoreInst &SI) {
2382 DEBUG(dbgs() << " original: " << SI << "\n");
2383 Value *OldOp = SI.getOperand(1);
2384 assert(OldOp == OldPtr);
2385 IRBuilder<> IRB(&SI);
2388 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
2390 return rewriteIntegerStore(IRB, SI);
2392 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2393 // alloca that should be re-examined after promoting this alloca.
2394 if (SI.getValueOperand()->getType()->isPointerTy())
2395 if (AllocaInst *AI = dyn_cast<AllocaInst>(SI.getValueOperand()
2396 ->stripInBoundsOffsets()))
2397 Pass.PostPromotionWorklist.insert(AI);
2399 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2400 SI.getPointerOperand()->getType());
2401 SI.setOperand(1, NewPtr);
2402 SI.setAlignment(getPartitionTypeAlign(SI.getValueOperand()->getType()));
2403 DEBUG(dbgs() << " to: " << SI << "\n");
2405 deleteIfTriviallyDead(OldOp);
2406 return NewPtr == &NewAI && !SI.isVolatile();
2409 bool visitMemSetInst(MemSetInst &II) {
2410 DEBUG(dbgs() << " original: " << II << "\n");
2411 IRBuilder<> IRB(&II);
2412 assert(II.getRawDest() == OldPtr);
2414 // If the memset has a variable size, it cannot be split, just adjust the
2415 // pointer to the new alloca.
2416 if (!isa<Constant>(II.getLength())) {
2417 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2418 Type *CstTy = II.getAlignmentCst()->getType();
2419 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
2421 deleteIfTriviallyDead(OldPtr);
2425 // Record this instruction for deletion.
2426 if (Pass.DeadSplitInsts.insert(&II))
2427 Pass.DeadInsts.push_back(&II);
2429 Type *AllocaTy = NewAI.getAllocatedType();
2430 Type *ScalarTy = AllocaTy->getScalarType();
2432 // If this doesn't map cleanly onto the alloca type, and that type isn't
2433 // a single value type, just emit a memset.
2434 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
2435 EndOffset != NewAllocaEndOffset ||
2436 !AllocaTy->isSingleValueType() ||
2437 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
2438 Type *SizeTy = II.getLength()->getType();
2439 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2441 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2442 II.getRawDest()->getType()),
2443 II.getValue(), Size, getPartitionAlign(),
2446 DEBUG(dbgs() << " to: " << *New << "\n");
2450 // If we can represent this as a simple value, we have to build the actual
2451 // value to store, which requires expanding the byte present in memset to
2452 // a sensible representation for the alloca type. This is essentially
2453 // splatting the byte to a sufficiently wide integer, bitcasting to the
2454 // desired scalar type, and splatting it across any desired vector type.
2455 Value *V = II.getValue();
2456 IntegerType *VTy = cast<IntegerType>(V->getType());
2457 Type *IntTy = Type::getIntNTy(VTy->getContext(),
2458 TD.getTypeSizeInBits(ScalarTy));
2459 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
2460 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
2461 ConstantExpr::getUDiv(
2462 Constant::getAllOnesValue(IntTy),
2463 ConstantExpr::getZExt(
2464 Constant::getAllOnesValue(V->getType()),
2466 getName(".isplat"));
2467 if (V->getType() != ScalarTy) {
2468 if (ScalarTy->isPointerTy())
2469 V = IRB.CreateIntToPtr(V, ScalarTy);
2470 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
2471 V = IRB.CreateBitCast(V, ScalarTy);
2472 else if (ScalarTy->isIntegerTy())
2473 llvm_unreachable("Computed different integer types with equal widths");
2475 llvm_unreachable("Invalid scalar type");
2478 // If this is an element-wide memset of a vectorizable alloca, insert it.
2479 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2480 EndOffset < NewAllocaEndOffset)) {
2481 StoreInst *Store = IRB.CreateAlignedStore(
2482 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2483 NewAI.getAlignment(),
2485 V, getIndex(IRB, BeginOffset),
2486 getName(".insert")),
2487 &NewAI, NewAI.getAlignment());
2489 DEBUG(dbgs() << " to: " << *Store << "\n");
2493 // Splat to a vector if needed.
2494 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
2495 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
2496 V = IRB.CreateShuffleVector(
2497 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
2498 IRB.getInt32(0), getName(".vsplat.insert")),
2499 UndefValue::get(SplatSourceTy),
2500 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
2501 getName(".vsplat.shuffle"));
2502 assert(V->getType() == VecTy);
2505 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2508 DEBUG(dbgs() << " to: " << *New << "\n");
2509 return !II.isVolatile();
2512 bool visitMemTransferInst(MemTransferInst &II) {
2513 // Rewriting of memory transfer instructions can be a bit tricky. We break
2514 // them into two categories: split intrinsics and unsplit intrinsics.
2516 DEBUG(dbgs() << " original: " << II << "\n");
2517 IRBuilder<> IRB(&II);
2519 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2520 bool IsDest = II.getRawDest() == OldPtr;
2522 const AllocaPartitioning::MemTransferOffsets &MTO
2523 = P.getMemTransferOffsets(II);
2525 // Compute the relative offset within the transfer.
2526 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2527 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2528 : MTO.SourceBegin));
2530 unsigned Align = II.getAlignment();
2532 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2533 MinAlign(II.getAlignment(), getPartitionAlign()));
2535 // For unsplit intrinsics, we simply modify the source and destination
2536 // pointers in place. This isn't just an optimization, it is a matter of
2537 // correctness. With unsplit intrinsics we may be dealing with transfers
2538 // within a single alloca before SROA ran, or with transfers that have
2539 // a variable length. We may also be dealing with memmove instead of
2540 // memcpy, and so simply updating the pointers is the necessary for us to
2541 // update both source and dest of a single call.
2542 if (!MTO.IsSplittable) {
2543 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2545 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2547 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2549 Type *CstTy = II.getAlignmentCst()->getType();
2550 II.setAlignment(ConstantInt::get(CstTy, Align));
2552 DEBUG(dbgs() << " to: " << II << "\n");
2553 deleteIfTriviallyDead(OldOp);
2556 // For split transfer intrinsics we have an incredibly useful assurance:
2557 // the source and destination do not reside within the same alloca, and at
2558 // least one of them does not escape. This means that we can replace
2559 // memmove with memcpy, and we don't need to worry about all manner of
2560 // downsides to splitting and transforming the operations.
2562 // If this doesn't map cleanly onto the alloca type, and that type isn't
2563 // a single value type, just emit a memcpy.
2565 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
2566 EndOffset != NewAllocaEndOffset ||
2567 !NewAI.getAllocatedType()->isSingleValueType());
2569 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2570 // size hasn't been shrunk based on analysis of the viable range, this is
2572 if (EmitMemCpy && &OldAI == &NewAI) {
2573 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2574 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2575 // Ensure the start lines up.
2576 assert(BeginOffset == OrigBegin);
2579 // Rewrite the size as needed.
2580 if (EndOffset != OrigEnd)
2581 II.setLength(ConstantInt::get(II.getLength()->getType(),
2582 EndOffset - BeginOffset));
2585 // Record this instruction for deletion.
2586 if (Pass.DeadSplitInsts.insert(&II))
2587 Pass.DeadInsts.push_back(&II);
2589 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
2590 EndOffset < NewAllocaEndOffset);
2592 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2593 : II.getRawDest()->getType();
2595 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
2598 // Compute the other pointer, folding as much as possible to produce
2599 // a single, simple GEP in most cases.
2600 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2601 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2602 getName("." + OtherPtr->getName()));
2604 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2605 // alloca that should be re-examined after rewriting this instruction.
2607 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2608 Pass.Worklist.insert(AI);
2612 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2613 : II.getRawSource()->getType());
2614 Type *SizeTy = II.getLength()->getType();
2615 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2617 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2618 IsDest ? OtherPtr : OurPtr,
2619 Size, Align, II.isVolatile());
2621 DEBUG(dbgs() << " to: " << *New << "\n");
2625 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2626 // is equivalent to 1, but that isn't true if we end up rewriting this as
2631 Value *SrcPtr = OtherPtr;
2632 Value *DstPtr = &NewAI;
2634 std::swap(SrcPtr, DstPtr);
2637 if (IsVectorElement && !IsDest) {
2638 // We have to extract rather than load.
2639 Src = IRB.CreateExtractElement(
2640 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
2641 getIndex(IRB, BeginOffset),
2642 getName(".copyextract"));
2644 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2645 getName(".copyload"));
2648 if (IsVectorElement && IsDest) {
2649 // We have to insert into a loaded copy before storing.
2650 Src = IRB.CreateInsertElement(
2651 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2652 Src, getIndex(IRB, BeginOffset),
2653 getName(".insert"));
2656 StoreInst *Store = cast<StoreInst>(
2657 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2659 DEBUG(dbgs() << " to: " << *Store << "\n");
2660 return !II.isVolatile();
2663 bool visitIntrinsicInst(IntrinsicInst &II) {
2664 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2665 II.getIntrinsicID() == Intrinsic::lifetime_end);
2666 DEBUG(dbgs() << " original: " << II << "\n");
2667 IRBuilder<> IRB(&II);
2668 assert(II.getArgOperand(1) == OldPtr);
2670 // Record this instruction for deletion.
2671 if (Pass.DeadSplitInsts.insert(&II))
2672 Pass.DeadInsts.push_back(&II);
2675 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2676 EndOffset - BeginOffset);
2677 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2679 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2680 New = IRB.CreateLifetimeStart(Ptr, Size);
2682 New = IRB.CreateLifetimeEnd(Ptr, Size);
2684 DEBUG(dbgs() << " to: " << *New << "\n");
2688 bool visitPHINode(PHINode &PN) {
2689 DEBUG(dbgs() << " original: " << PN << "\n");
2691 // We would like to compute a new pointer in only one place, but have it be
2692 // as local as possible to the PHI. To do that, we re-use the location of
2693 // the old pointer, which necessarily must be in the right position to
2694 // dominate the PHI.
2695 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2697 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2698 // Replace the operands which were using the old pointer.
2699 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2700 for (; OI != OE; ++OI)
2704 DEBUG(dbgs() << " to: " << PN << "\n");
2705 deleteIfTriviallyDead(OldPtr);
2709 bool visitSelectInst(SelectInst &SI) {
2710 DEBUG(dbgs() << " original: " << SI << "\n");
2711 IRBuilder<> IRB(&SI);
2713 // Find the operand we need to rewrite here.
2714 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2716 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2718 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2720 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2721 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2722 DEBUG(dbgs() << " to: " << SI << "\n");
2723 deleteIfTriviallyDead(OldPtr);
2731 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2733 /// This pass aggressively rewrites all aggregate loads and stores on
2734 /// a particular pointer (or any pointer derived from it which we can identify)
2735 /// with scalar loads and stores.
2736 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2737 // Befriend the base class so it can delegate to private visit methods.
2738 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2740 const TargetData &TD;
2742 /// Queue of pointer uses to analyze and potentially rewrite.
2743 SmallVector<Use *, 8> Queue;
2745 /// Set to prevent us from cycling with phi nodes and loops.
2746 SmallPtrSet<User *, 8> Visited;
2748 /// The current pointer use being rewritten. This is used to dig up the used
2749 /// value (as opposed to the user).
2753 AggLoadStoreRewriter(const TargetData &TD) : TD(TD) {}
2755 /// Rewrite loads and stores through a pointer and all pointers derived from
2757 bool rewrite(Instruction &I) {
2758 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2760 bool Changed = false;
2761 while (!Queue.empty()) {
2762 U = Queue.pop_back_val();
2763 Changed |= visit(cast<Instruction>(U->getUser()));
2769 /// Enqueue all the users of the given instruction for further processing.
2770 /// This uses a set to de-duplicate users.
2771 void enqueueUsers(Instruction &I) {
2772 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2774 if (Visited.insert(*UI))
2775 Queue.push_back(&UI.getUse());
2778 // Conservative default is to not rewrite anything.
2779 bool visitInstruction(Instruction &I) { return false; }
2781 /// \brief Generic recursive split emission class.
2782 template <typename Derived>
2785 /// The builder used to form new instructions.
2787 /// The indices which to be used with insert- or extractvalue to select the
2788 /// appropriate value within the aggregate.
2789 SmallVector<unsigned, 4> Indices;
2790 /// The indices to a GEP instruction which will move Ptr to the correct slot
2791 /// within the aggregate.
2792 SmallVector<Value *, 4> GEPIndices;
2793 /// The base pointer of the original op, used as a base for GEPing the
2794 /// split operations.
2797 /// Initialize the splitter with an insertion point, Ptr and start with a
2798 /// single zero GEP index.
2799 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
2800 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
2803 /// \brief Generic recursive split emission routine.
2805 /// This method recursively splits an aggregate op (load or store) into
2806 /// scalar or vector ops. It splits recursively until it hits a single value
2807 /// and emits that single value operation via the template argument.
2809 /// The logic of this routine relies on GEPs and insertvalue and
2810 /// extractvalue all operating with the same fundamental index list, merely
2811 /// formatted differently (GEPs need actual values).
2813 /// \param Ty The type being split recursively into smaller ops.
2814 /// \param Agg The aggregate value being built up or stored, depending on
2815 /// whether this is splitting a load or a store respectively.
2816 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2817 if (Ty->isSingleValueType())
2818 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
2820 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2821 unsigned OldSize = Indices.size();
2823 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2825 assert(Indices.size() == OldSize && "Did not return to the old size");
2826 Indices.push_back(Idx);
2827 GEPIndices.push_back(IRB.getInt32(Idx));
2828 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2829 GEPIndices.pop_back();
2835 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2836 unsigned OldSize = Indices.size();
2838 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2840 assert(Indices.size() == OldSize && "Did not return to the old size");
2841 Indices.push_back(Idx);
2842 GEPIndices.push_back(IRB.getInt32(Idx));
2843 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2844 GEPIndices.pop_back();
2850 llvm_unreachable("Only arrays and structs are aggregate loadable types");
2854 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
2855 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2856 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
2858 /// Emit a leaf load of a single value. This is called at the leaves of the
2859 /// recursive emission to actually load values.
2860 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2861 assert(Ty->isSingleValueType());
2862 // Load the single value and insert it using the indices.
2863 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
2866 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2867 DEBUG(dbgs() << " to: " << *Load << "\n");
2871 bool visitLoadInst(LoadInst &LI) {
2872 assert(LI.getPointerOperand() == *U);
2873 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2876 // We have an aggregate being loaded, split it apart.
2877 DEBUG(dbgs() << " original: " << LI << "\n");
2878 LoadOpSplitter Splitter(&LI, *U);
2879 Value *V = UndefValue::get(LI.getType());
2880 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
2881 LI.replaceAllUsesWith(V);
2882 LI.eraseFromParent();
2886 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
2887 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2888 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
2890 /// Emit a leaf store of a single value. This is called at the leaves of the
2891 /// recursive emission to actually produce stores.
2892 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2893 assert(Ty->isSingleValueType());
2894 // Extract the single value and store it using the indices.
2895 Value *Store = IRB.CreateStore(
2896 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2897 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2899 DEBUG(dbgs() << " to: " << *Store << "\n");
2903 bool visitStoreInst(StoreInst &SI) {
2904 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2906 Value *V = SI.getValueOperand();
2907 if (V->getType()->isSingleValueType())
2910 // We have an aggregate being stored, split it apart.
2911 DEBUG(dbgs() << " original: " << SI << "\n");
2912 StoreOpSplitter Splitter(&SI, *U);
2913 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
2914 SI.eraseFromParent();
2918 bool visitBitCastInst(BitCastInst &BC) {
2923 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2928 bool visitPHINode(PHINode &PN) {
2933 bool visitSelectInst(SelectInst &SI) {
2940 /// \brief Try to find a partition of the aggregate type passed in for a given
2941 /// offset and size.
2943 /// This recurses through the aggregate type and tries to compute a subtype
2944 /// based on the offset and size. When the offset and size span a sub-section
2945 /// of an array, it will even compute a new array type for that sub-section,
2946 /// and the same for structs.
2948 /// Note that this routine is very strict and tries to find a partition of the
2949 /// type which produces the *exact* right offset and size. It is not forgiving
2950 /// when the size or offset cause either end of type-based partition to be off.
2951 /// Also, this is a best-effort routine. It is reasonable to give up and not
2952 /// return a type if necessary.
2953 static Type *getTypePartition(const TargetData &TD, Type *Ty,
2954 uint64_t Offset, uint64_t Size) {
2955 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2958 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2959 // We can't partition pointers...
2960 if (SeqTy->isPointerTy())
2963 Type *ElementTy = SeqTy->getElementType();
2964 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2965 uint64_t NumSkippedElements = Offset / ElementSize;
2966 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2967 if (NumSkippedElements >= ArrTy->getNumElements())
2969 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2970 if (NumSkippedElements >= VecTy->getNumElements())
2972 Offset -= NumSkippedElements * ElementSize;
2974 // First check if we need to recurse.
2975 if (Offset > 0 || Size < ElementSize) {
2976 // Bail if the partition ends in a different array element.
2977 if ((Offset + Size) > ElementSize)
2979 // Recurse through the element type trying to peel off offset bytes.
2980 return getTypePartition(TD, ElementTy, Offset, Size);
2982 assert(Offset == 0);
2984 if (Size == ElementSize)
2986 assert(Size > ElementSize);
2987 uint64_t NumElements = Size / ElementSize;
2988 if (NumElements * ElementSize != Size)
2990 return ArrayType::get(ElementTy, NumElements);
2993 StructType *STy = dyn_cast<StructType>(Ty);
2997 const StructLayout *SL = TD.getStructLayout(STy);
2998 if (Offset >= SL->getSizeInBytes())
3000 uint64_t EndOffset = Offset + Size;
3001 if (EndOffset > SL->getSizeInBytes())
3004 unsigned Index = SL->getElementContainingOffset(Offset);
3005 Offset -= SL->getElementOffset(Index);
3007 Type *ElementTy = STy->getElementType(Index);
3008 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3009 if (Offset >= ElementSize)
3010 return 0; // The offset points into alignment padding.
3012 // See if any partition must be contained by the element.
3013 if (Offset > 0 || Size < ElementSize) {
3014 if ((Offset + Size) > ElementSize)
3016 return getTypePartition(TD, ElementTy, Offset, Size);
3018 assert(Offset == 0);
3020 if (Size == ElementSize)
3023 StructType::element_iterator EI = STy->element_begin() + Index,
3024 EE = STy->element_end();
3025 if (EndOffset < SL->getSizeInBytes()) {
3026 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3027 if (Index == EndIndex)
3028 return 0; // Within a single element and its padding.
3030 // Don't try to form "natural" types if the elements don't line up with the
3032 // FIXME: We could potentially recurse down through the last element in the
3033 // sub-struct to find a natural end point.
3034 if (SL->getElementOffset(EndIndex) != EndOffset)
3037 assert(Index < EndIndex);
3038 EE = STy->element_begin() + EndIndex;
3041 // Try to build up a sub-structure.
3042 SmallVector<Type *, 4> ElementTys;
3044 ElementTys.push_back(*EI++);
3046 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
3048 const StructLayout *SubSL = TD.getStructLayout(SubTy);
3049 if (Size != SubSL->getSizeInBytes())
3050 return 0; // The sub-struct doesn't have quite the size needed.
3055 /// \brief Rewrite an alloca partition's users.
3057 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3058 /// to rewrite uses of an alloca partition to be conducive for SSA value
3059 /// promotion. If the partition needs a new, more refined alloca, this will
3060 /// build that new alloca, preserving as much type information as possible, and
3061 /// rewrite the uses of the old alloca to point at the new one and have the
3062 /// appropriate new offsets. It also evaluates how successful the rewrite was
3063 /// at enabling promotion and if it was successful queues the alloca to be
3065 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3066 AllocaPartitioning &P,
3067 AllocaPartitioning::iterator PI) {
3068 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
3069 bool IsLive = false;
3070 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3072 UI != UE && !IsLive; ++UI)
3076 return false; // No live uses left of this partition.
3078 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3079 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3081 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3082 DEBUG(dbgs() << " speculating ");
3083 DEBUG(P.print(dbgs(), PI, ""));
3084 Speculator.visitUsers(PI);
3086 // Try to compute a friendly type for this partition of the alloca. This
3087 // won't always succeed, in which case we fall back to a legal integer type
3088 // or an i8 array of an appropriate size.
3090 if (Type *PartitionTy = P.getCommonType(PI))
3091 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3092 AllocaTy = PartitionTy;
3094 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3095 PI->BeginOffset, AllocaSize))
3096 AllocaTy = PartitionTy;
3098 (AllocaTy->isArrayTy() &&
3099 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3100 TD->isLegalInteger(AllocaSize * 8))
3101 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3103 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
3104 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
3106 // Check for the case where we're going to rewrite to a new alloca of the
3107 // exact same type as the original, and with the same access offsets. In that
3108 // case, re-use the existing alloca, but still run through the rewriter to
3109 // performe phi and select speculation.
3111 if (AllocaTy == AI.getAllocatedType()) {
3112 assert(PI->BeginOffset == 0 &&
3113 "Non-zero begin offset but same alloca type");
3114 assert(PI == P.begin() && "Begin offset is zero on later partition");
3117 unsigned Alignment = AI.getAlignment();
3119 // The minimum alignment which users can rely on when the explicit
3120 // alignment is omitted or zero is that required by the ABI for this
3122 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3124 Alignment = MinAlign(Alignment, PI->BeginOffset);
3125 // If we will get at least this much alignment from the type alone, leave
3126 // the alloca's alignment unconstrained.
3127 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3129 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
3130 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3135 DEBUG(dbgs() << "Rewriting alloca partition "
3136 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3139 // Track the high watermark of the post-promotion worklist. We will reset it
3140 // to this point if the alloca is not in fact scheduled for promotion.
3141 unsigned PPWOldSize = PostPromotionWorklist.size();
3143 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3144 PI->BeginOffset, PI->EndOffset);
3145 DEBUG(dbgs() << " rewriting ");
3146 DEBUG(P.print(dbgs(), PI, ""));
3147 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3149 DEBUG(dbgs() << " and queuing for promotion\n");
3150 PromotableAllocas.push_back(NewAI);
3151 } else if (NewAI != &AI) {
3152 // If we can't promote the alloca, iterate on it to check for new
3153 // refinements exposed by splitting the current alloca. Don't iterate on an
3154 // alloca which didn't actually change and didn't get promoted.
3155 Worklist.insert(NewAI);
3158 // Drop any post-promotion work items if promotion didn't happen.
3160 while (PostPromotionWorklist.size() > PPWOldSize)
3161 PostPromotionWorklist.pop_back();
3166 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3167 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3168 bool Changed = false;
3169 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3171 Changed |= rewriteAllocaPartition(AI, P, PI);
3176 /// \brief Analyze an alloca for SROA.
3178 /// This analyzes the alloca to ensure we can reason about it, builds
3179 /// a partitioning of the alloca, and then hands it off to be split and
3180 /// rewritten as needed.
3181 bool SROA::runOnAlloca(AllocaInst &AI) {
3182 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3183 ++NumAllocasAnalyzed;
3185 // Special case dead allocas, as they're trivial.
3186 if (AI.use_empty()) {
3187 AI.eraseFromParent();
3191 // Skip alloca forms that this analysis can't handle.
3192 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3193 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3196 bool Changed = false;
3198 // First, split any FCA loads and stores touching this alloca to promote
3199 // better splitting and promotion opportunities.
3200 AggLoadStoreRewriter AggRewriter(*TD);
3201 Changed |= AggRewriter.rewrite(AI);
3203 // Build the partition set using a recursive instruction-visiting builder.
3204 AllocaPartitioning P(*TD, AI);
3205 DEBUG(P.print(dbgs()));
3209 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3210 if (P.begin() == P.end())
3213 // Delete all the dead users of this alloca before splitting and rewriting it.
3214 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3215 DE = P.dead_user_end();
3218 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3219 DeadInsts.push_back(*DI);
3221 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3222 DE = P.dead_op_end();
3225 // Clobber the use with an undef value.
3226 **DO = UndefValue::get(OldV->getType());
3227 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3228 if (isInstructionTriviallyDead(OldI)) {
3230 DeadInsts.push_back(OldI);
3234 return splitAlloca(AI, P) || Changed;
3237 /// \brief Delete the dead instructions accumulated in this run.
3239 /// Recursively deletes the dead instructions we've accumulated. This is done
3240 /// at the very end to maximize locality of the recursive delete and to
3241 /// minimize the problems of invalidated instruction pointers as such pointers
3242 /// are used heavily in the intermediate stages of the algorithm.
3244 /// We also record the alloca instructions deleted here so that they aren't
3245 /// subsequently handed to mem2reg to promote.
3246 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3247 DeadSplitInsts.clear();
3248 while (!DeadInsts.empty()) {
3249 Instruction *I = DeadInsts.pop_back_val();
3250 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3252 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3253 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3254 // Zero out the operand and see if it becomes trivially dead.
3256 if (isInstructionTriviallyDead(U))
3257 DeadInsts.push_back(U);
3260 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3261 DeletedAllocas.insert(AI);
3264 I->eraseFromParent();
3268 /// \brief Promote the allocas, using the best available technique.
3270 /// This attempts to promote whatever allocas have been identified as viable in
3271 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3272 /// If there is a domtree available, we attempt to promote using the full power
3273 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3274 /// based on the SSAUpdater utilities. This function returns whether any
3275 /// promotion occured.
3276 bool SROA::promoteAllocas(Function &F) {
3277 if (PromotableAllocas.empty())
3280 NumPromoted += PromotableAllocas.size();
3282 if (DT && !ForceSSAUpdater) {
3283 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3284 PromoteMemToReg(PromotableAllocas, *DT);
3285 PromotableAllocas.clear();
3289 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3291 DIBuilder DIB(*F.getParent());
3292 SmallVector<Instruction*, 64> Insts;
3294 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3295 AllocaInst *AI = PromotableAllocas[Idx];
3296 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3298 Instruction *I = cast<Instruction>(*UI++);
3299 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3300 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3301 // leading to them) here. Eventually it should use them to optimize the
3302 // scalar values produced.
3303 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3304 assert(onlyUsedByLifetimeMarkers(I) &&
3305 "Found a bitcast used outside of a lifetime marker.");
3306 while (!I->use_empty())
3307 cast<Instruction>(*I->use_begin())->eraseFromParent();
3308 I->eraseFromParent();
3311 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3312 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3313 II->getIntrinsicID() == Intrinsic::lifetime_end);
3314 II->eraseFromParent();
3320 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3324 PromotableAllocas.clear();
3329 /// \brief A predicate to test whether an alloca belongs to a set.
3330 class IsAllocaInSet {
3331 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3335 typedef AllocaInst *argument_type;
3337 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3338 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
3342 bool SROA::runOnFunction(Function &F) {
3343 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3344 C = &F.getContext();
3345 TD = getAnalysisIfAvailable<TargetData>();
3347 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3350 DT = getAnalysisIfAvailable<DominatorTree>();
3352 BasicBlock &EntryBB = F.getEntryBlock();
3353 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3355 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3356 Worklist.insert(AI);
3358 bool Changed = false;
3359 // A set of deleted alloca instruction pointers which should be removed from
3360 // the list of promotable allocas.
3361 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3364 while (!Worklist.empty()) {
3365 Changed |= runOnAlloca(*Worklist.pop_back_val());
3366 deleteDeadInstructions(DeletedAllocas);
3368 // Remove the deleted allocas from various lists so that we don't try to
3369 // continue processing them.
3370 if (!DeletedAllocas.empty()) {
3371 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3372 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3373 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3374 PromotableAllocas.end(),
3375 IsAllocaInSet(DeletedAllocas)),
3376 PromotableAllocas.end());
3377 DeletedAllocas.clear();
3381 Changed |= promoteAllocas(F);
3383 Worklist = PostPromotionWorklist;
3384 PostPromotionWorklist.clear();
3385 } while (!Worklist.empty());
3390 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3391 if (RequiresDomTree)
3392 AU.addRequired<DominatorTree>();
3393 AU.setPreservesCFG();