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/GlobalVariable.h"
34 #include "llvm/IRBuilder.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/IntrinsicInst.h"
37 #include "llvm/LLVMContext.h"
38 #include "llvm/Module.h"
39 #include "llvm/Operator.h"
40 #include "llvm/Pass.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/TinyPtrVector.h"
46 #include "llvm/Analysis/Dominators.h"
47 #include "llvm/Analysis/Loads.h"
48 #include "llvm/Analysis/ValueTracking.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/ValueHandle.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetData.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
61 #include "llvm/Transforms/Utils/SSAUpdater.h"
64 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
65 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
66 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
67 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
68 STATISTIC(NumDeleted, "Number of instructions deleted");
69 STATISTIC(NumVectorized, "Number of vectorized aggregates");
71 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
72 /// forming SSA values through the SSAUpdater infrastructure.
74 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
77 /// \brief Alloca partitioning representation.
79 /// This class represents a partitioning of an alloca into slices, and
80 /// information about the nature of uses of each slice of the alloca. The goal
81 /// is that this information is sufficient to decide if and how to split the
82 /// alloca apart and replace slices with scalars. It is also intended that this
83 /// structure can capture the relevant information needed both to decide about
84 /// and to enact these transformations.
85 class AllocaPartitioning {
87 /// \brief A common base class for representing a half-open byte range.
89 /// \brief The beginning offset of the range.
92 /// \brief The ending offset, not included in the range.
95 ByteRange() : BeginOffset(), EndOffset() {}
96 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
97 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
99 /// \brief Support for ordering ranges.
101 /// This provides an ordering over ranges such that start offsets are
102 /// always increasing, and within equal start offsets, the end offsets are
103 /// decreasing. Thus the spanning range comes first in a cluster with the
104 /// same start position.
105 bool operator<(const ByteRange &RHS) const {
106 if (BeginOffset < RHS.BeginOffset) return true;
107 if (BeginOffset > RHS.BeginOffset) return false;
108 if (EndOffset > RHS.EndOffset) return true;
112 /// \brief Support comparison with a single offset to allow binary searches.
113 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
114 return LHS.BeginOffset < RHSOffset;
117 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
118 const ByteRange &RHS) {
119 return LHSOffset < RHS.BeginOffset;
122 bool operator==(const ByteRange &RHS) const {
123 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
125 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
128 /// \brief A partition of an alloca.
130 /// This structure represents a contiguous partition of the alloca. These are
131 /// formed by examining the uses of the alloca. During formation, they may
132 /// overlap but once an AllocaPartitioning is built, the Partitions within it
133 /// are all disjoint.
134 struct Partition : public ByteRange {
135 /// \brief Whether this partition is splittable into smaller partitions.
137 /// We flag partitions as splittable when they are formed entirely due to
138 /// accesses by trivially splittable operations such as memset and memcpy.
140 /// FIXME: At some point we should consider loads and stores of FCAs to be
141 /// splittable and eagerly split them into scalar values.
144 Partition() : ByteRange(), IsSplittable() {}
145 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
146 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
149 /// \brief A particular use of a partition of the alloca.
151 /// This structure is used to associate uses of a partition with it. They
152 /// mark the range of bytes which are referenced by a particular instruction,
153 /// and includes a handle to the user itself and the pointer value in use.
154 /// The bounds of these uses are determined by intersecting the bounds of the
155 /// memory use itself with a particular partition. As a consequence there is
156 /// intentionally overlap between various uses of the same partition.
157 struct PartitionUse : public ByteRange {
158 /// \brief The use in question. Provides access to both user and used value.
161 PartitionUse() : ByteRange(), U() {}
162 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
163 : ByteRange(BeginOffset, EndOffset), U(U) {}
166 /// \brief Construct a partitioning of a particular alloca.
168 /// Construction does most of the work for partitioning the alloca. This
169 /// performs the necessary walks of users and builds a partitioning from it.
170 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
172 /// \brief Test whether a pointer to the allocation escapes our analysis.
174 /// If this is true, the partitioning is never fully built and should be
176 bool isEscaped() const { return PointerEscapingInstr; }
178 /// \brief Support for iterating over the partitions.
180 typedef SmallVectorImpl<Partition>::iterator iterator;
181 iterator begin() { return Partitions.begin(); }
182 iterator end() { return Partitions.end(); }
184 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
185 const_iterator begin() const { return Partitions.begin(); }
186 const_iterator end() const { return Partitions.end(); }
189 /// \brief Support for iterating over and manipulating a particular
190 /// partition's uses.
192 /// The iteration support provided for uses is more limited, but also
193 /// includes some manipulation routines to support rewriting the uses of
194 /// partitions during SROA.
196 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
197 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
198 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
199 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
200 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
201 void use_push_back(unsigned Idx, const PartitionUse &PU) {
202 Uses[Idx].push_back(PU);
204 void use_push_back(const_iterator I, const PartitionUse &PU) {
205 Uses[I - begin()].push_back(PU);
207 void use_erase(unsigned Idx, use_iterator UI) { Uses[Idx].erase(UI); }
208 void use_erase(const_iterator I, use_iterator UI) {
209 Uses[I - begin()].erase(UI);
212 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
213 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
214 const_use_iterator use_begin(const_iterator I) const {
215 return Uses[I - begin()].begin();
217 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
218 const_use_iterator use_end(const_iterator I) const {
219 return Uses[I - begin()].end();
223 /// \brief Allow iterating the dead users for this alloca.
225 /// These are instructions which will never actually use the alloca as they
226 /// are outside the allocated range. They are safe to replace with undef and
229 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
230 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
231 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
234 /// \brief Allow iterating the dead expressions referring to this alloca.
236 /// These are operands which have cannot actually be used to refer to the
237 /// alloca as they are outside its range and the user doesn't correct for
238 /// that. These mostly consist of PHI node inputs and the like which we just
239 /// need to replace with undef.
241 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
242 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
243 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
246 /// \brief MemTransferInst auxiliary data.
247 /// This struct provides some auxiliary data about memory transfer
248 /// intrinsics such as memcpy and memmove. These intrinsics can use two
249 /// different ranges within the same alloca, and provide other challenges to
250 /// correctly represent. We stash extra data to help us untangle this
251 /// after the partitioning is complete.
252 struct MemTransferOffsets {
253 uint64_t DestBegin, DestEnd;
254 uint64_t SourceBegin, SourceEnd;
257 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
258 return MemTransferInstData.lookup(&II);
261 /// \brief Map from a PHI or select operand back to a partition.
263 /// When manipulating PHI nodes or selects, they can use more than one
264 /// partition of an alloca. We store a special mapping to allow finding the
265 /// partition referenced by each of these operands, if any.
266 iterator findPartitionForPHIOrSelectOperand(Use *U) {
267 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
268 = PHIOrSelectOpMap.find(U);
269 if (MapIt == PHIOrSelectOpMap.end())
272 return begin() + MapIt->second.first;
275 /// \brief Map from a PHI or select operand back to the specific use of
278 /// Similar to mapping these operands back to the partitions, this maps
279 /// directly to the use structure of that partition.
280 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
281 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
282 = PHIOrSelectOpMap.find(U);
283 assert(MapIt != PHIOrSelectOpMap.end());
284 return Uses[MapIt->second.first].begin() + MapIt->second.second;
287 /// \brief Compute a common type among the uses of a particular partition.
289 /// This routines walks all of the uses of a particular partition and tries
290 /// to find a common type between them. Untyped operations such as memset and
291 /// memcpy are ignored.
292 Type *getCommonType(iterator I) const;
294 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
295 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
296 void printUsers(raw_ostream &OS, const_iterator I,
297 StringRef Indent = " ") const;
298 void print(raw_ostream &OS) const;
299 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
300 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
304 template <typename DerivedT, typename RetT = void> class BuilderBase;
305 class PartitionBuilder;
306 friend class AllocaPartitioning::PartitionBuilder;
308 friend class AllocaPartitioning::UseBuilder;
311 /// \brief Handle to alloca instruction to simplify method interfaces.
315 /// \brief The instruction responsible for this alloca having no partitioning.
317 /// When an instruction (potentially) escapes the pointer to the alloca, we
318 /// store a pointer to that here and abort trying to partition the alloca.
319 /// This will be null if the alloca is partitioned successfully.
320 Instruction *PointerEscapingInstr;
322 /// \brief The partitions of the alloca.
324 /// We store a vector of the partitions over the alloca here. This vector is
325 /// sorted by increasing begin offset, and then by decreasing end offset. See
326 /// the Partition inner class for more details. Initially (during
327 /// construction) there are overlaps, but we form a disjoint sequence of
328 /// partitions while finishing construction and a fully constructed object is
329 /// expected to always have this as a disjoint space.
330 SmallVector<Partition, 8> Partitions;
332 /// \brief The uses of the partitions.
334 /// This is essentially a mapping from each partition to a list of uses of
335 /// that partition. The mapping is done with a Uses vector that has the exact
336 /// same number of entries as the partition vector. Each entry is itself
337 /// a vector of the uses.
338 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
340 /// \brief Instructions which will become dead if we rewrite the alloca.
342 /// Note that these are not separated by partition. This is because we expect
343 /// a partitioned alloca to be completely rewritten or not rewritten at all.
344 /// If rewritten, all these instructions can simply be removed and replaced
345 /// with undef as they come from outside of the allocated space.
346 SmallVector<Instruction *, 8> DeadUsers;
348 /// \brief Operands which will become dead if we rewrite the alloca.
350 /// These are operands that in their particular use can be replaced with
351 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
352 /// to PHI nodes and the like. They aren't entirely dead (there might be
353 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
354 /// want to swap this particular input for undef to simplify the use lists of
356 SmallVector<Use *, 8> DeadOperands;
358 /// \brief The underlying storage for auxiliary memcpy and memset info.
359 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
361 /// \brief A side datastructure used when building up the partitions and uses.
363 /// This mapping is only really used during the initial building of the
364 /// partitioning so that we can retain information about PHI and select nodes
366 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
368 /// \brief Auxiliary information for particular PHI or select operands.
369 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
371 /// \brief A utility routine called from the constructor.
373 /// This does what it says on the tin. It is the key of the alloca partition
374 /// splitting and merging. After it is called we have the desired disjoint
375 /// collection of partitions.
376 void splitAndMergePartitions();
380 template <typename DerivedT, typename RetT>
381 class AllocaPartitioning::BuilderBase
382 : public InstVisitor<DerivedT, RetT> {
384 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
386 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
392 const TargetData &TD;
393 const uint64_t AllocSize;
394 AllocaPartitioning &P;
396 SmallPtrSet<Use *, 8> VisitedUses;
402 SmallVector<OffsetUse, 8> Queue;
404 // The active offset and use while visiting.
408 void enqueueUsers(Instruction &I, int64_t UserOffset) {
409 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
411 if (VisitedUses.insert(&UI.getUse())) {
412 OffsetUse OU = { &UI.getUse(), UserOffset };
418 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
420 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
422 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
428 // Handle a struct index, which adds its field offset to the pointer.
429 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
430 unsigned ElementIdx = OpC->getZExtValue();
431 const StructLayout *SL = TD.getStructLayout(STy);
432 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
433 // Check that we can continue to model this GEP in a signed 64-bit offset.
434 if (ElementOffset > INT64_MAX ||
436 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
437 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
438 << "what can be represented in an int64_t!\n"
439 << " alloca: " << P.AI << "\n");
443 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
445 GEPOffset += ElementOffset;
449 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
450 Index *= APInt(Index.getBitWidth(),
451 TD.getTypeAllocSize(GTI.getIndexedType()));
452 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
454 // Check if the result can be stored in our int64_t offset.
455 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
456 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
457 << "what can be represented in an int64_t!\n"
458 << " alloca: " << P.AI << "\n");
462 GEPOffset = Index.getSExtValue();
467 Value *foldSelectInst(SelectInst &SI) {
468 // If the condition being selected on is a constant or the same value is
469 // being selected between, fold the select. Yes this does (rarely) happen
471 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
472 return SI.getOperand(1+CI->isZero());
473 if (SI.getOperand(1) == SI.getOperand(2)) {
474 assert(*U == SI.getOperand(1));
475 return SI.getOperand(1);
481 /// \brief Builder for the alloca partitioning.
483 /// This class builds an alloca partitioning by recursively visiting the uses
484 /// of an alloca and splitting the partitions for each load and store at each
486 class AllocaPartitioning::PartitionBuilder
487 : public BuilderBase<PartitionBuilder, bool> {
488 friend class InstVisitor<PartitionBuilder, bool>;
490 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
493 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
494 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
496 /// \brief Run the builder over the allocation.
498 // Note that we have to re-evaluate size on each trip through the loop as
499 // the queue grows at the tail.
500 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
502 Offset = Queue[Idx].Offset;
503 if (!visit(cast<Instruction>(U->getUser())))
510 bool markAsEscaping(Instruction &I) {
511 P.PointerEscapingInstr = &I;
515 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
516 bool IsSplittable = false) {
517 // Completely skip uses which have a zero size or don't overlap the
520 (Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
521 (Offset < 0 && (uint64_t)-Offset >= Size)) {
522 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
523 << " which starts past the end of the " << AllocSize
525 << " alloca: " << P.AI << "\n"
526 << " use: " << I << "\n");
530 // Clamp the start to the beginning of the allocation.
532 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
533 << " to start at the beginning of the alloca:\n"
534 << " alloca: " << P.AI << "\n"
535 << " use: " << I << "\n");
536 Size -= (uint64_t)-Offset;
540 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
542 // Clamp the end offset to the end of the allocation. Note that this is
543 // formulated to handle even the case where "BeginOffset + Size" overflows.
544 assert(AllocSize >= BeginOffset); // Established above.
545 if (Size > AllocSize - BeginOffset) {
546 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
547 << " to remain within the " << AllocSize << " byte alloca:\n"
548 << " alloca: " << P.AI << "\n"
549 << " use: " << I << "\n");
550 EndOffset = AllocSize;
553 // See if we can just add a user onto the last slot currently occupied.
554 if (!P.Partitions.empty() &&
555 P.Partitions.back().BeginOffset == BeginOffset &&
556 P.Partitions.back().EndOffset == EndOffset) {
557 P.Partitions.back().IsSplittable &= IsSplittable;
561 Partition New(BeginOffset, EndOffset, IsSplittable);
562 P.Partitions.push_back(New);
565 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
566 uint64_t Size = TD.getTypeStoreSize(Ty);
568 // If this memory access can be shown to *statically* extend outside the
569 // bounds of of the allocation, it's behavior is undefined, so simply
570 // ignore it. Note that this is more strict than the generic clamping
571 // behavior of insertUse. We also try to handle cases which might run the
573 // FIXME: We should instead consider the pointer to have escaped if this
574 // function is being instrumented for addressing bugs or race conditions.
575 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
576 Size > (AllocSize - (uint64_t)Offset)) {
577 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
578 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
579 << " which extends past the end of the " << AllocSize
581 << " alloca: " << P.AI << "\n"
582 << " use: " << I << "\n");
586 insertUse(I, Offset, Size);
590 bool visitBitCastInst(BitCastInst &BC) {
591 enqueueUsers(BC, Offset);
595 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
597 if (!computeConstantGEPOffset(GEPI, GEPOffset))
598 return markAsEscaping(GEPI);
600 enqueueUsers(GEPI, GEPOffset);
604 bool visitLoadInst(LoadInst &LI) {
605 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
606 "All simple FCA loads should have been pre-split");
607 return handleLoadOrStore(LI.getType(), LI, Offset);
610 bool visitStoreInst(StoreInst &SI) {
611 Value *ValOp = SI.getValueOperand();
613 return markAsEscaping(SI);
615 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
616 "All simple FCA stores should have been pre-split");
617 return handleLoadOrStore(ValOp->getType(), SI, Offset);
621 bool visitMemSetInst(MemSetInst &II) {
622 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
623 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
624 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
625 insertUse(II, Offset, Size, Length);
629 bool visitMemTransferInst(MemTransferInst &II) {
630 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
631 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
633 // Zero-length mem transfer intrinsics can be ignored entirely.
636 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
638 // Only intrinsics with a constant length can be split.
639 Offsets.IsSplittable = Length;
641 if (*U != II.getRawDest()) {
642 assert(*U == II.getRawSource());
643 Offsets.SourceBegin = Offset;
644 Offsets.SourceEnd = Offset + Size;
646 Offsets.DestBegin = Offset;
647 Offsets.DestEnd = Offset + Size;
650 insertUse(II, Offset, Size, Offsets.IsSplittable);
651 unsigned NewIdx = P.Partitions.size() - 1;
653 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
654 bool Inserted = false;
655 llvm::tie(PMI, Inserted)
656 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
657 if (Offsets.IsSplittable &&
658 (!Inserted || II.getRawSource() == II.getRawDest())) {
659 // We've found a memory transfer intrinsic which refers to the alloca as
660 // both a source and dest. This is detected either by direct equality of
661 // the operand values, or when we visit the intrinsic twice due to two
662 // different chains of values leading to it. We refuse to split these to
663 // simplify splitting logic. If possible, SROA will still split them into
664 // separate allocas and then re-analyze.
665 Offsets.IsSplittable = false;
666 P.Partitions[PMI->second].IsSplittable = false;
667 P.Partitions[NewIdx].IsSplittable = false;
673 // Disable SRoA for any intrinsics except for lifetime invariants.
674 // FIXME: What about debug instrinsics? This matches old behavior, but
675 // doesn't make sense.
676 bool visitIntrinsicInst(IntrinsicInst &II) {
677 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
678 II.getIntrinsicID() == Intrinsic::lifetime_end) {
679 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
680 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
681 insertUse(II, Offset, Size, true);
685 return markAsEscaping(II);
688 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
689 // We consider any PHI or select that results in a direct load or store of
690 // the same offset to be a viable use for partitioning purposes. These uses
691 // are considered unsplittable and the size is the maximum loaded or stored
693 SmallPtrSet<Instruction *, 4> Visited;
694 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
695 Visited.insert(Root);
696 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
697 // If there are no loads or stores, the access is dead. We mark that as
698 // a size zero access.
701 Instruction *I, *UsedI;
702 llvm::tie(UsedI, I) = Uses.pop_back_val();
704 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
705 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
708 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
709 Value *Op = SI->getOperand(0);
712 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
716 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
717 if (!GEP->hasAllZeroIndices())
719 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
720 !isa<SelectInst>(I)) {
724 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
726 if (Visited.insert(cast<Instruction>(*UI)))
727 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
728 } while (!Uses.empty());
733 bool visitPHINode(PHINode &PN) {
734 // See if we already have computed info on this node.
735 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
737 PHIInfo.second = true;
738 insertUse(PN, Offset, PHIInfo.first);
742 // Check for an unsafe use of the PHI node.
743 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
744 return markAsEscaping(*EscapingI);
746 insertUse(PN, Offset, PHIInfo.first);
750 bool visitSelectInst(SelectInst &SI) {
751 if (Value *Result = foldSelectInst(SI)) {
753 // If the result of the constant fold will be the pointer, recurse
754 // through the select as if we had RAUW'ed it.
755 enqueueUsers(SI, Offset);
760 // See if we already have computed info on this node.
761 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
762 if (SelectInfo.first) {
763 SelectInfo.second = true;
764 insertUse(SI, Offset, SelectInfo.first);
768 // Check for an unsafe use of the PHI node.
769 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
770 return markAsEscaping(*EscapingI);
772 insertUse(SI, Offset, SelectInfo.first);
776 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
777 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
781 /// \brief Use adder for the alloca partitioning.
783 /// This class adds the uses of an alloca to all of the partitions which they
784 /// use. For splittable partitions, this can end up doing essentially a linear
785 /// walk of the partitions, but the number of steps remains bounded by the
786 /// total result instruction size:
787 /// - The number of partitions is a result of the number unsplittable
788 /// instructions using the alloca.
789 /// - The number of users of each partition is at worst the total number of
790 /// splittable instructions using the alloca.
791 /// Thus we will produce N * M instructions in the end, where N are the number
792 /// of unsplittable uses and M are the number of splittable. This visitor does
793 /// the exact same number of updates to the partitioning.
795 /// In the more common case, this visitor will leverage the fact that the
796 /// partition space is pre-sorted, and do a logarithmic search for the
797 /// partition needed, making the total visit a classical ((N + M) * log(N))
798 /// complexity operation.
799 class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
800 friend class InstVisitor<UseBuilder>;
802 /// \brief Set to de-duplicate dead instructions found in the use walk.
803 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
806 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
807 : BuilderBase<UseBuilder>(TD, AI, P) {}
809 /// \brief Run the builder over the allocation.
811 // Note that we have to re-evaluate size on each trip through the loop as
812 // the queue grows at the tail.
813 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
815 Offset = Queue[Idx].Offset;
816 this->visit(cast<Instruction>(U->getUser()));
821 void markAsDead(Instruction &I) {
822 if (VisitedDeadInsts.insert(&I))
823 P.DeadUsers.push_back(&I);
826 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
827 // If the use has a zero size or extends outside of the allocation, record
828 // it as a dead use for elimination later.
829 if (Size == 0 || (uint64_t)Offset >= AllocSize ||
830 (Offset < 0 && (uint64_t)-Offset >= Size))
831 return markAsDead(User);
833 // Clamp the start to the beginning of the allocation.
835 Size -= (uint64_t)-Offset;
839 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
841 // Clamp the end offset to the end of the allocation. Note that this is
842 // formulated to handle even the case where "BeginOffset + Size" overflows.
843 assert(AllocSize >= BeginOffset); // Established above.
844 if (Size > AllocSize - BeginOffset)
845 EndOffset = AllocSize;
847 // NB: This only works if we have zero overlapping partitions.
848 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
849 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
851 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
853 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
854 std::min(I->EndOffset, EndOffset), U);
855 P.use_push_back(I, NewPU);
856 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
857 P.PHIOrSelectOpMap[U]
858 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
862 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
863 uint64_t Size = TD.getTypeStoreSize(Ty);
865 // If this memory access can be shown to *statically* extend outside the
866 // bounds of of the allocation, it's behavior is undefined, so simply
867 // ignore it. Note that this is more strict than the generic clamping
868 // behavior of insertUse.
869 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
870 Size > (AllocSize - (uint64_t)Offset))
871 return markAsDead(I);
873 insertUse(I, Offset, Size);
876 void visitBitCastInst(BitCastInst &BC) {
878 return markAsDead(BC);
880 enqueueUsers(BC, Offset);
883 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
884 if (GEPI.use_empty())
885 return markAsDead(GEPI);
888 if (!computeConstantGEPOffset(GEPI, GEPOffset))
889 llvm_unreachable("Unable to compute constant offset for use");
891 enqueueUsers(GEPI, GEPOffset);
894 void visitLoadInst(LoadInst &LI) {
895 handleLoadOrStore(LI.getType(), LI, Offset);
898 void visitStoreInst(StoreInst &SI) {
899 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
902 void visitMemSetInst(MemSetInst &II) {
903 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
904 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
905 insertUse(II, Offset, Size);
908 void visitMemTransferInst(MemTransferInst &II) {
909 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
910 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
911 insertUse(II, Offset, Size);
914 void visitIntrinsicInst(IntrinsicInst &II) {
915 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
916 II.getIntrinsicID() == Intrinsic::lifetime_end);
918 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
919 insertUse(II, Offset,
920 std::min(AllocSize - Offset, Length->getLimitedValue()));
923 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
924 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
926 // For PHI and select operands outside the alloca, we can't nuke the entire
927 // phi or select -- the other side might still be relevant, so we special
928 // case them here and use a separate structure to track the operands
929 // themselves which should be replaced with undef.
930 if (Offset >= AllocSize) {
931 P.DeadOperands.push_back(U);
935 insertUse(User, Offset, Size);
937 void visitPHINode(PHINode &PN) {
939 return markAsDead(PN);
941 insertPHIOrSelect(PN, Offset);
943 void visitSelectInst(SelectInst &SI) {
945 return markAsDead(SI);
947 if (Value *Result = foldSelectInst(SI)) {
949 // If the result of the constant fold will be the pointer, recurse
950 // through the select as if we had RAUW'ed it.
951 enqueueUsers(SI, Offset);
953 // Otherwise the operand to the select is dead, and we can replace it
955 P.DeadOperands.push_back(U);
960 insertPHIOrSelect(SI, Offset);
963 /// \brief Unreachable, we've already visited the alloca once.
964 void visitInstruction(Instruction &I) {
965 llvm_unreachable("Unhandled instruction in use builder.");
969 void AllocaPartitioning::splitAndMergePartitions() {
970 size_t NumDeadPartitions = 0;
972 // Track the range of splittable partitions that we pass when accumulating
973 // overlapping unsplittable partitions.
974 uint64_t SplitEndOffset = 0ull;
976 Partition New(0ull, 0ull, false);
978 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
981 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
982 assert(New.BeginOffset == New.EndOffset);
985 assert(New.IsSplittable);
986 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
988 assert(New.BeginOffset != New.EndOffset);
990 // Scan the overlapping partitions.
991 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
992 // If the new partition we are forming is splittable, stop at the first
993 // unsplittable partition.
994 if (New.IsSplittable && !Partitions[j].IsSplittable)
997 // Grow the new partition to include any equally splittable range. 'j' is
998 // always equally splittable when New is splittable, but when New is not
999 // splittable, we may subsume some (or part of some) splitable partition
1000 // without growing the new one.
1001 if (New.IsSplittable == Partitions[j].IsSplittable) {
1002 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1004 assert(!New.IsSplittable);
1005 assert(Partitions[j].IsSplittable);
1006 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1009 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
1010 ++NumDeadPartitions;
1014 // If the new partition is splittable, chop off the end as soon as the
1015 // unsplittable subsequent partition starts and ensure we eventually cover
1016 // the splittable area.
1017 if (j != e && New.IsSplittable) {
1018 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1019 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1022 // Add the new partition if it differs from the original one and is
1023 // non-empty. We can end up with an empty partition here if it was
1024 // splittable but there is an unsplittable one that starts at the same
1026 if (New != Partitions[i]) {
1027 if (New.BeginOffset != New.EndOffset)
1028 Partitions.push_back(New);
1029 // Mark the old one for removal.
1030 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
1031 ++NumDeadPartitions;
1034 New.BeginOffset = New.EndOffset;
1035 if (!New.IsSplittable) {
1036 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1037 if (j != e && !Partitions[j].IsSplittable)
1038 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1039 New.IsSplittable = true;
1040 // If there is a trailing splittable partition which won't be fused into
1041 // the next splittable partition go ahead and add it onto the partitions
1043 if (New.BeginOffset < New.EndOffset &&
1044 (j == e || !Partitions[j].IsSplittable ||
1045 New.EndOffset < Partitions[j].BeginOffset)) {
1046 Partitions.push_back(New);
1047 New.BeginOffset = New.EndOffset = 0ull;
1052 // Re-sort the partitions now that they have been split and merged into
1053 // disjoint set of partitions. Also remove any of the dead partitions we've
1054 // replaced in the process.
1055 std::sort(Partitions.begin(), Partitions.end());
1056 if (NumDeadPartitions) {
1057 assert(Partitions.back().BeginOffset == UINT64_MAX);
1058 assert(Partitions.back().EndOffset == UINT64_MAX);
1059 assert((ptrdiff_t)NumDeadPartitions ==
1060 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1062 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1065 AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
1070 PointerEscapingInstr(0) {
1071 PartitionBuilder PB(TD, AI, *this);
1075 if (Partitions.size() > 1) {
1076 // Sort the uses. This arranges for the offsets to be in ascending order,
1077 // and the sizes to be in descending order.
1078 std::sort(Partitions.begin(), Partitions.end());
1080 // Intersect splittability for all partitions with equal offsets and sizes.
1081 // Then remove all but the first so that we have a sequence of non-equal but
1082 // potentially overlapping partitions.
1083 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1086 while (J != E && *I == *J) {
1087 I->IsSplittable &= J->IsSplittable;
1091 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1094 // Split splittable and merge unsplittable partitions into a disjoint set
1095 // of partitions over the used space of the allocation.
1096 splitAndMergePartitions();
1099 // Now build up the user lists for each of these disjoint partitions by
1100 // re-walking the recursive users of the alloca.
1101 Uses.resize(Partitions.size());
1102 UseBuilder UB(TD, AI, *this);
1106 Type *AllocaPartitioning::getCommonType(iterator I) const {
1108 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1109 if (isa<IntrinsicInst>(*UI->U->getUser()))
1111 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1115 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
1116 UserTy = LI->getType();
1117 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
1118 UserTy = SI->getValueOperand()->getType();
1119 } else if (SelectInst *SI = dyn_cast<SelectInst>(UI->U->getUser())) {
1120 if (PointerType *PtrTy = dyn_cast<PointerType>(SI->getType()))
1121 UserTy = PtrTy->getElementType();
1122 } else if (PHINode *PN = dyn_cast<PHINode>(UI->U->getUser())) {
1123 if (PointerType *PtrTy = dyn_cast<PointerType>(PN->getType()))
1124 UserTy = PtrTy->getElementType();
1127 if (Ty && Ty != UserTy)
1135 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1137 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1138 StringRef Indent) const {
1139 OS << Indent << "partition #" << (I - begin())
1140 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1141 << (I->IsSplittable ? " (splittable)" : "")
1142 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1146 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1147 StringRef Indent) const {
1148 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1150 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1151 << "used by: " << *UI->U->getUser() << "\n";
1152 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
1153 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1155 if (!MTO.IsSplittable)
1156 IsDest = UI->BeginOffset == MTO.DestBegin;
1158 IsDest = MTO.DestBegin != 0u;
1159 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1160 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1161 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1166 void AllocaPartitioning::print(raw_ostream &OS) const {
1167 if (PointerEscapingInstr) {
1168 OS << "No partitioning for alloca: " << AI << "\n"
1169 << " A pointer to this alloca escaped by:\n"
1170 << " " << *PointerEscapingInstr << "\n";
1174 OS << "Partitioning of alloca: " << AI << "\n";
1176 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1182 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1183 void AllocaPartitioning::dump() const { print(dbgs()); }
1185 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1189 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1191 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1192 /// the loads and stores of an alloca instruction, as well as updating its
1193 /// debug information. This is used when a domtree is unavailable and thus
1194 /// mem2reg in its full form can't be used to handle promotion of allocas to
1196 class AllocaPromoter : public LoadAndStorePromoter {
1200 SmallVector<DbgDeclareInst *, 4> DDIs;
1201 SmallVector<DbgValueInst *, 4> DVIs;
1204 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1205 AllocaInst &AI, DIBuilder &DIB)
1206 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1208 void run(const SmallVectorImpl<Instruction*> &Insts) {
1209 // Remember which alloca we're promoting (for isInstInList).
1210 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1211 for (Value::use_iterator UI = DebugNode->use_begin(),
1212 UE = DebugNode->use_end();
1214 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1215 DDIs.push_back(DDI);
1216 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1217 DVIs.push_back(DVI);
1220 LoadAndStorePromoter::run(Insts);
1221 AI.eraseFromParent();
1222 while (!DDIs.empty())
1223 DDIs.pop_back_val()->eraseFromParent();
1224 while (!DVIs.empty())
1225 DVIs.pop_back_val()->eraseFromParent();
1228 virtual bool isInstInList(Instruction *I,
1229 const SmallVectorImpl<Instruction*> &Insts) const {
1230 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1231 return LI->getOperand(0) == &AI;
1232 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1235 virtual void updateDebugInfo(Instruction *Inst) const {
1236 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1237 E = DDIs.end(); I != E; ++I) {
1238 DbgDeclareInst *DDI = *I;
1239 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1240 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1241 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1242 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1244 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1245 E = DVIs.end(); I != E; ++I) {
1246 DbgValueInst *DVI = *I;
1248 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1249 // If an argument is zero extended then use argument directly. The ZExt
1250 // may be zapped by an optimization pass in future.
1251 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1252 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1253 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1254 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1256 Arg = SI->getOperand(0);
1257 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1258 Arg = LI->getOperand(0);
1262 Instruction *DbgVal =
1263 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1265 DbgVal->setDebugLoc(DVI->getDebugLoc());
1269 } // end anon namespace
1273 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1275 /// This pass takes allocations which can be completely analyzed (that is, they
1276 /// don't escape) and tries to turn them into scalar SSA values. There are
1277 /// a few steps to this process.
1279 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1280 /// are used to try to split them into smaller allocations, ideally of
1281 /// a single scalar data type. It will split up memcpy and memset accesses
1282 /// as necessary and try to isolate invidual scalar accesses.
1283 /// 2) It will transform accesses into forms which are suitable for SSA value
1284 /// promotion. This can be replacing a memset with a scalar store of an
1285 /// integer value, or it can involve speculating operations on a PHI or
1286 /// select to be a PHI or select of the results.
1287 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1288 /// onto insert and extract operations on a vector value, and convert them to
1289 /// this form. By doing so, it will enable promotion of vector aggregates to
1290 /// SSA vector values.
1291 class SROA : public FunctionPass {
1292 const bool RequiresDomTree;
1295 const TargetData *TD;
1298 /// \brief Worklist of alloca instructions to simplify.
1300 /// Each alloca in the function is added to this. Each new alloca formed gets
1301 /// added to it as well to recursively simplify unless that alloca can be
1302 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1303 /// the one being actively rewritten, we add it back onto the list if not
1304 /// already present to ensure it is re-visited.
1305 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1307 /// \brief A collection of instructions to delete.
1308 /// We try to batch deletions to simplify code and make things a bit more
1310 SmallVector<Instruction *, 8> DeadInsts;
1312 /// \brief A set to prevent repeatedly marking an instruction split into many
1313 /// uses as dead. Only used to guard insertion into DeadInsts.
1314 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1316 /// \brief A collection of alloca instructions we can directly promote.
1317 std::vector<AllocaInst *> PromotableAllocas;
1320 SROA(bool RequiresDomTree = true)
1321 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1322 C(0), TD(0), DT(0) {
1323 initializeSROAPass(*PassRegistry::getPassRegistry());
1325 bool runOnFunction(Function &F);
1326 void getAnalysisUsage(AnalysisUsage &AU) const;
1328 const char *getPassName() const { return "SROA"; }
1332 friend class AllocaPartitionRewriter;
1333 friend class AllocaPartitionVectorRewriter;
1335 bool rewriteAllocaPartition(AllocaInst &AI,
1336 AllocaPartitioning &P,
1337 AllocaPartitioning::iterator PI);
1338 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1339 bool runOnAlloca(AllocaInst &AI);
1340 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
1341 bool promoteAllocas(Function &F);
1347 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1348 return new SROA(RequiresDomTree);
1351 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1353 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1354 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1357 /// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1359 /// If the provided GEP is all-constant, the total byte offset formed by the
1360 /// GEP is computed and Offset is set to it. If the GEP has any non-constant
1361 /// operands, the function returns false and the value of Offset is unmodified.
1362 static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1364 APInt GEPOffset(Offset.getBitWidth(), 0);
1365 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1366 GTI != GTE; ++GTI) {
1367 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1370 if (OpC->isZero()) continue;
1372 // Handle a struct index, which adds its field offset to the pointer.
1373 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1374 unsigned ElementIdx = OpC->getZExtValue();
1375 const StructLayout *SL = TD.getStructLayout(STy);
1376 GEPOffset += APInt(Offset.getBitWidth(),
1377 SL->getElementOffset(ElementIdx));
1381 APInt TypeSize(Offset.getBitWidth(),
1382 TD.getTypeAllocSize(GTI.getIndexedType()));
1383 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1384 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1385 "vector element size is not a multiple of 8, cannot GEP over it");
1386 TypeSize = VTy->getScalarSizeInBits() / 8;
1389 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1395 /// \brief Build a GEP out of a base pointer and indices.
1397 /// This will return the BasePtr if that is valid, or build a new GEP
1398 /// instruction using the IRBuilder if GEP-ing is needed.
1399 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1400 SmallVectorImpl<Value *> &Indices,
1401 const Twine &Prefix) {
1402 if (Indices.empty())
1405 // A single zero index is a no-op, so check for this and avoid building a GEP
1407 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1410 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1413 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1414 /// TargetTy without changing the offset of the pointer.
1416 /// This routine assumes we've already established a properly offset GEP with
1417 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1418 /// zero-indices down through type layers until we find one the same as
1419 /// TargetTy. If we can't find one with the same type, we at least try to use
1420 /// one with the same size. If none of that works, we just produce the GEP as
1421 /// indicated by Indices to have the correct offset.
1422 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1423 Value *BasePtr, Type *Ty, Type *TargetTy,
1424 SmallVectorImpl<Value *> &Indices,
1425 const Twine &Prefix) {
1427 return buildGEP(IRB, BasePtr, Indices, Prefix);
1429 // See if we can descend into a struct and locate a field with the correct
1431 unsigned NumLayers = 0;
1432 Type *ElementTy = Ty;
1434 if (ElementTy->isPointerTy())
1436 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1437 ElementTy = SeqTy->getElementType();
1438 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1439 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1440 ElementTy = *STy->element_begin();
1441 Indices.push_back(IRB.getInt32(0));
1446 } while (ElementTy != TargetTy);
1447 if (ElementTy != TargetTy)
1448 Indices.erase(Indices.end() - NumLayers, Indices.end());
1450 return buildGEP(IRB, BasePtr, Indices, Prefix);
1453 /// \brief Recursively compute indices for a natural GEP.
1455 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1456 /// element types adding appropriate indices for the GEP.
1457 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1458 Value *Ptr, Type *Ty, APInt &Offset,
1460 SmallVectorImpl<Value *> &Indices,
1461 const Twine &Prefix) {
1463 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1465 // We can't recurse through pointer types.
1466 if (Ty->isPointerTy())
1469 // We try to analyze GEPs over vectors here, but note that these GEPs are
1470 // extremely poorly defined currently. The long-term goal is to remove GEPing
1471 // over a vector from the IR completely.
1472 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1473 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1474 if (ElementSizeInBits % 8)
1475 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1476 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1477 APInt NumSkippedElements = Offset.udiv(ElementSize);
1478 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1480 Offset -= NumSkippedElements * ElementSize;
1481 Indices.push_back(IRB.getInt(NumSkippedElements));
1482 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1483 Offset, TargetTy, Indices, Prefix);
1486 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1487 Type *ElementTy = ArrTy->getElementType();
1488 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1489 APInt NumSkippedElements = Offset.udiv(ElementSize);
1490 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1493 Offset -= NumSkippedElements * ElementSize;
1494 Indices.push_back(IRB.getInt(NumSkippedElements));
1495 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1499 StructType *STy = dyn_cast<StructType>(Ty);
1503 const StructLayout *SL = TD.getStructLayout(STy);
1504 uint64_t StructOffset = Offset.getZExtValue();
1505 if (StructOffset >= SL->getSizeInBytes())
1507 unsigned Index = SL->getElementContainingOffset(StructOffset);
1508 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1509 Type *ElementTy = STy->getElementType(Index);
1510 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1511 return 0; // The offset points into alignment padding.
1513 Indices.push_back(IRB.getInt32(Index));
1514 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1518 /// \brief Get a natural GEP from a base pointer to a particular offset and
1519 /// resulting in a particular type.
1521 /// The goal is to produce a "natural" looking GEP that works with the existing
1522 /// composite types to arrive at the appropriate offset and element type for
1523 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1524 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1525 /// Indices, and setting Ty to the result subtype.
1527 /// If no natural GEP can be constructed, this function returns null.
1528 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1529 Value *Ptr, APInt Offset, Type *TargetTy,
1530 SmallVectorImpl<Value *> &Indices,
1531 const Twine &Prefix) {
1532 PointerType *Ty = cast<PointerType>(Ptr->getType());
1534 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1536 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1539 Type *ElementTy = Ty->getElementType();
1540 if (!ElementTy->isSized())
1541 return 0; // We can't GEP through an unsized element.
1542 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1543 if (ElementSize == 0)
1544 return 0; // Zero-length arrays can't help us build a natural GEP.
1545 APInt NumSkippedElements = Offset.udiv(ElementSize);
1547 Offset -= NumSkippedElements * ElementSize;
1548 Indices.push_back(IRB.getInt(NumSkippedElements));
1549 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1553 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1554 /// resulting pointer has PointerTy.
1556 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1557 /// and produces the pointer type desired. Where it cannot, it will try to use
1558 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1559 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1560 /// bitcast to the type.
1562 /// The strategy for finding the more natural GEPs is to peel off layers of the
1563 /// pointer, walking back through bit casts and GEPs, searching for a base
1564 /// pointer from which we can compute a natural GEP with the desired
1565 /// properities. The algorithm tries to fold as many constant indices into
1566 /// a single GEP as possible, thus making each GEP more independent of the
1567 /// surrounding code.
1568 static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1569 Value *Ptr, APInt Offset, Type *PointerTy,
1570 const Twine &Prefix) {
1571 // Even though we don't look through PHI nodes, we could be called on an
1572 // instruction in an unreachable block, which may be on a cycle.
1573 SmallPtrSet<Value *, 4> Visited;
1574 Visited.insert(Ptr);
1575 SmallVector<Value *, 4> Indices;
1577 // We may end up computing an offset pointer that has the wrong type. If we
1578 // never are able to compute one directly that has the correct type, we'll
1579 // fall back to it, so keep it around here.
1580 Value *OffsetPtr = 0;
1582 // Remember any i8 pointer we come across to re-use if we need to do a raw
1585 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1587 Type *TargetTy = PointerTy->getPointerElementType();
1590 // First fold any existing GEPs into the offset.
1591 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1592 APInt GEPOffset(Offset.getBitWidth(), 0);
1593 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1595 Offset += GEPOffset;
1596 Ptr = GEP->getPointerOperand();
1597 if (!Visited.insert(Ptr))
1601 // See if we can perform a natural GEP here.
1603 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1605 if (P->getType() == PointerTy) {
1606 // Zap any offset pointer that we ended up computing in previous rounds.
1607 if (OffsetPtr && OffsetPtr->use_empty())
1608 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1609 I->eraseFromParent();
1617 // Stash this pointer if we've found an i8*.
1618 if (Ptr->getType()->isIntegerTy(8)) {
1620 Int8PtrOffset = Offset;
1623 // Peel off a layer of the pointer and update the offset appropriately.
1624 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1625 Ptr = cast<Operator>(Ptr)->getOperand(0);
1626 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1627 if (GA->mayBeOverridden())
1629 Ptr = GA->getAliasee();
1633 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1634 } while (Visited.insert(Ptr));
1638 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1639 Prefix + ".raw_cast");
1640 Int8PtrOffset = Offset;
1643 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1644 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1645 Prefix + ".raw_idx");
1649 // On the off chance we were targeting i8*, guard the bitcast here.
1650 if (Ptr->getType() != PointerTy)
1651 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1656 /// \brief Test whether the given alloca partition can be promoted to a vector.
1658 /// This is a quick test to check whether we can rewrite a particular alloca
1659 /// partition (and its newly formed alloca) into a vector alloca with only
1660 /// whole-vector loads and stores such that it could be promoted to a vector
1661 /// SSA value. We only can ensure this for a limited set of operations, and we
1662 /// don't want to do the rewrites unless we are confident that the result will
1663 /// be promotable, so we have an early test here.
1664 static bool isVectorPromotionViable(const TargetData &TD,
1666 AllocaPartitioning &P,
1667 uint64_t PartitionBeginOffset,
1668 uint64_t PartitionEndOffset,
1669 AllocaPartitioning::const_use_iterator I,
1670 AllocaPartitioning::const_use_iterator E) {
1671 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1675 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1676 uint64_t ElementSize = Ty->getScalarSizeInBits();
1678 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1679 // that aren't byte sized.
1680 if (ElementSize % 8)
1682 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1686 for (; I != E; ++I) {
1687 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1688 uint64_t BeginIndex = BeginOffset / ElementSize;
1689 if (BeginIndex * ElementSize != BeginOffset ||
1690 BeginIndex >= Ty->getNumElements())
1692 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1693 uint64_t EndIndex = EndOffset / ElementSize;
1694 if (EndIndex * ElementSize != EndOffset ||
1695 EndIndex > Ty->getNumElements())
1698 // FIXME: We should build shuffle vector instructions to handle
1699 // non-element-sized accesses.
1700 if ((EndOffset - BeginOffset) != ElementSize &&
1701 (EndOffset - BeginOffset) != VecSize)
1704 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
1705 if (MI->isVolatile())
1707 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
1708 const AllocaPartitioning::MemTransferOffsets &MTO
1709 = P.getMemTransferOffsets(*MTI);
1710 if (!MTO.IsSplittable)
1713 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
1714 // Disable vector promotion when there are loads or stores of an FCA.
1716 } else if (!isa<LoadInst>(I->U->getUser()) &&
1717 !isa<StoreInst>(I->U->getUser())) {
1724 /// \brief Test whether the given alloca partition can be promoted to an int.
1726 /// This is a quick test to check whether we can rewrite a particular alloca
1727 /// partition (and its newly formed alloca) into an integer alloca suitable for
1728 /// promotion to an SSA value. We only can ensure this for a limited set of
1729 /// operations, and we don't want to do the rewrites unless we are confident
1730 /// that the result will be promotable, so we have an early test here.
1731 static bool isIntegerPromotionViable(const TargetData &TD,
1733 AllocaPartitioning &P,
1734 AllocaPartitioning::const_use_iterator I,
1735 AllocaPartitioning::const_use_iterator E) {
1736 IntegerType *Ty = dyn_cast<IntegerType>(AllocaTy);
1740 // Check the uses to ensure the uses are (likely) promoteable integer uses.
1741 // Also ensure that the alloca has a covering load or store. We don't want
1742 // promote because of some other unsplittable entry (which we may make
1743 // splittable later) and lose the ability to promote each element access.
1744 bool WholeAllocaOp = false;
1745 for (; I != E; ++I) {
1746 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
1747 if (LI->isVolatile() || !LI->getType()->isIntegerTy())
1749 if (LI->getType() == Ty)
1750 WholeAllocaOp = true;
1751 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
1752 if (SI->isVolatile() || !SI->getValueOperand()->getType()->isIntegerTy())
1754 if (SI->getValueOperand()->getType() == Ty)
1755 WholeAllocaOp = true;
1756 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
1757 if (MI->isVolatile())
1759 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
1760 const AllocaPartitioning::MemTransferOffsets &MTO
1761 = P.getMemTransferOffsets(*MTI);
1762 if (!MTO.IsSplittable)
1769 return WholeAllocaOp;
1773 /// \brief Visitor to rewrite instructions using a partition of an alloca to
1774 /// use a new alloca.
1776 /// Also implements the rewriting to vector-based accesses when the partition
1777 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1779 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
1781 // Befriend the base class so it can delegate to private visit methods.
1782 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
1784 const TargetData &TD;
1785 AllocaPartitioning &P;
1787 AllocaInst &OldAI, &NewAI;
1788 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1790 // If we are rewriting an alloca partition which can be written as pure
1791 // vector operations, we stash extra information here. When VecTy is
1792 // non-null, we have some strict guarantees about the rewriten alloca:
1793 // - The new alloca is exactly the size of the vector type here.
1794 // - The accesses all either map to the entire vector or to a single
1796 // - The set of accessing instructions is only one of those handled above
1797 // in isVectorPromotionViable. Generally these are the same access kinds
1798 // which are promotable via mem2reg.
1801 uint64_t ElementSize;
1803 // This is a convenience and flag variable that will be null unless the new
1804 // alloca has a promotion-targeted integer type due to passing
1805 // isIntegerPromotionViable above. If it is non-null does, the desired
1806 // integer type will be stored here for easy access during rewriting.
1807 IntegerType *IntPromotionTy;
1809 // The offset of the partition user currently being rewritten.
1810 uint64_t BeginOffset, EndOffset;
1812 Instruction *OldPtr;
1814 // The name prefix to use when rewriting instructions for this alloca.
1815 std::string NamePrefix;
1818 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
1819 AllocaPartitioning::iterator PI,
1820 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
1821 uint64_t NewBeginOffset, uint64_t NewEndOffset)
1822 : TD(TD), P(P), Pass(Pass),
1823 OldAI(OldAI), NewAI(NewAI),
1824 NewAllocaBeginOffset(NewBeginOffset),
1825 NewAllocaEndOffset(NewEndOffset),
1826 VecTy(), ElementTy(), ElementSize(), IntPromotionTy(),
1827 BeginOffset(), EndOffset() {
1830 /// \brief Visit the users of the alloca partition and rewrite them.
1831 bool visitUsers(AllocaPartitioning::const_use_iterator I,
1832 AllocaPartitioning::const_use_iterator E) {
1833 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
1834 NewAllocaBeginOffset, NewAllocaEndOffset,
1837 VecTy = cast<VectorType>(NewAI.getAllocatedType());
1838 ElementTy = VecTy->getElementType();
1839 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
1840 "Only multiple-of-8 sized vector elements are viable");
1841 ElementSize = VecTy->getScalarSizeInBits() / 8;
1842 } else if (isIntegerPromotionViable(TD, NewAI.getAllocatedType(),
1844 IntPromotionTy = cast<IntegerType>(NewAI.getAllocatedType());
1846 bool CanSROA = true;
1847 for (; I != E; ++I) {
1848 BeginOffset = I->BeginOffset;
1849 EndOffset = I->EndOffset;
1851 OldPtr = cast<Instruction>(I->U->get());
1852 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
1853 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
1865 // Every instruction which can end up as a user must have a rewrite rule.
1866 bool visitInstruction(Instruction &I) {
1867 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1868 llvm_unreachable("No rewrite rule for this instruction!");
1871 Twine getName(const Twine &Suffix) {
1872 return NamePrefix + Suffix;
1875 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
1876 assert(BeginOffset >= NewAllocaBeginOffset);
1877 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
1878 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
1881 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
1882 assert(VecTy && "Can only call getIndex when rewriting a vector");
1883 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1884 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1885 uint32_t Index = RelOffset / ElementSize;
1886 assert(Index * ElementSize == RelOffset);
1887 return IRB.getInt32(Index);
1890 Value *extractInteger(IRBuilder<> &IRB, IntegerType *TargetTy,
1892 assert(IntPromotionTy && "Alloca is not an integer we can extract from");
1893 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
1895 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
1896 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1898 V = IRB.CreateLShr(V, RelOffset*8, getName(".shift"));
1899 if (TargetTy != IntPromotionTy) {
1900 assert(TargetTy->getBitWidth() < IntPromotionTy->getBitWidth() &&
1901 "Cannot extract to a larger integer!");
1902 V = IRB.CreateTrunc(V, TargetTy, getName(".trunc"));
1907 StoreInst *insertInteger(IRBuilder<> &IRB, Value *V, uint64_t Offset) {
1908 IntegerType *Ty = cast<IntegerType>(V->getType());
1909 if (Ty == IntPromotionTy)
1910 return IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
1912 assert(Ty->getBitWidth() < IntPromotionTy->getBitWidth() &&
1913 "Cannot insert a larger integer!");
1914 V = IRB.CreateZExt(V, IntPromotionTy, getName(".ext"));
1915 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
1916 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1918 V = IRB.CreateShl(V, RelOffset*8, getName(".shift"));
1920 APInt Mask = ~Ty->getMask().zext(IntPromotionTy->getBitWidth())
1922 Value *Old = IRB.CreateAnd(IRB.CreateAlignedLoad(&NewAI,
1923 NewAI.getAlignment(),
1924 getName(".oldload")),
1925 Mask, getName(".mask"));
1926 return IRB.CreateAlignedStore(IRB.CreateOr(Old, V, getName(".insert")),
1927 &NewAI, NewAI.getAlignment());
1930 void deleteIfTriviallyDead(Value *V) {
1931 Instruction *I = cast<Instruction>(V);
1932 if (isInstructionTriviallyDead(I))
1933 Pass.DeadInsts.push_back(I);
1936 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
1937 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1938 return IRB.CreateIntToPtr(V, Ty);
1939 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1940 return IRB.CreatePtrToInt(V, Ty);
1942 return IRB.CreateBitCast(V, Ty);
1945 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
1947 if (LI.getType() == VecTy->getElementType() ||
1948 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1949 Result = IRB.CreateExtractElement(
1950 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
1951 getIndex(IRB, BeginOffset), getName(".extract"));
1953 Result = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
1956 if (Result->getType() != LI.getType())
1957 Result = getValueCast(IRB, Result, LI.getType());
1958 LI.replaceAllUsesWith(Result);
1959 Pass.DeadInsts.push_back(&LI);
1961 DEBUG(dbgs() << " to: " << *Result << "\n");
1965 bool rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
1966 assert(!LI.isVolatile());
1967 Value *Result = extractInteger(IRB, cast<IntegerType>(LI.getType()),
1969 LI.replaceAllUsesWith(Result);
1970 Pass.DeadInsts.push_back(&LI);
1971 DEBUG(dbgs() << " to: " << *Result << "\n");
1975 bool visitLoadInst(LoadInst &LI) {
1976 DEBUG(dbgs() << " original: " << LI << "\n");
1977 Value *OldOp = LI.getOperand(0);
1978 assert(OldOp == OldPtr);
1979 IRBuilder<> IRB(&LI);
1982 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
1984 return rewriteIntegerLoad(IRB, LI);
1986 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1987 LI.getPointerOperand()->getType());
1988 LI.setOperand(0, NewPtr);
1989 if (LI.getAlignment())
1990 LI.setAlignment(MinAlign(NewAI.getAlignment(),
1991 BeginOffset - NewAllocaBeginOffset));
1992 DEBUG(dbgs() << " to: " << LI << "\n");
1994 deleteIfTriviallyDead(OldOp);
1995 return NewPtr == &NewAI && !LI.isVolatile();
1998 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
2000 Value *V = SI.getValueOperand();
2001 if (V->getType() == ElementTy ||
2002 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2003 if (V->getType() != ElementTy)
2004 V = getValueCast(IRB, V, ElementTy);
2005 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2007 V = IRB.CreateInsertElement(LI, V, getIndex(IRB, BeginOffset),
2008 getName(".insert"));
2009 } else if (V->getType() != VecTy) {
2010 V = getValueCast(IRB, V, VecTy);
2012 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2013 Pass.DeadInsts.push_back(&SI);
2016 DEBUG(dbgs() << " to: " << *Store << "\n");
2020 bool rewriteIntegerStore(IRBuilder<> &IRB, StoreInst &SI) {
2021 assert(!SI.isVolatile());
2022 StoreInst *Store = insertInteger(IRB, SI.getValueOperand(), BeginOffset);
2023 Pass.DeadInsts.push_back(&SI);
2025 DEBUG(dbgs() << " to: " << *Store << "\n");
2029 bool visitStoreInst(StoreInst &SI) {
2030 DEBUG(dbgs() << " original: " << SI << "\n");
2031 Value *OldOp = SI.getOperand(1);
2032 assert(OldOp == OldPtr);
2033 IRBuilder<> IRB(&SI);
2036 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
2038 return rewriteIntegerStore(IRB, SI);
2040 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2041 SI.getPointerOperand()->getType());
2042 SI.setOperand(1, NewPtr);
2043 if (SI.getAlignment())
2044 SI.setAlignment(MinAlign(NewAI.getAlignment(),
2045 BeginOffset - NewAllocaBeginOffset));
2046 DEBUG(dbgs() << " to: " << SI << "\n");
2048 deleteIfTriviallyDead(OldOp);
2049 return NewPtr == &NewAI && !SI.isVolatile();
2052 bool visitMemSetInst(MemSetInst &II) {
2053 DEBUG(dbgs() << " original: " << II << "\n");
2054 IRBuilder<> IRB(&II);
2055 assert(II.getRawDest() == OldPtr);
2057 // If the memset has a variable size, it cannot be split, just adjust the
2058 // pointer to the new alloca.
2059 if (!isa<Constant>(II.getLength())) {
2060 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2062 Type *CstTy = II.getAlignmentCst()->getType();
2063 if (!NewAI.getAlignment())
2064 II.setAlignment(ConstantInt::get(CstTy, 0));
2067 ConstantInt::get(CstTy, MinAlign(NewAI.getAlignment(),
2068 BeginOffset - NewAllocaBeginOffset)));
2070 deleteIfTriviallyDead(OldPtr);
2074 // Record this instruction for deletion.
2075 if (Pass.DeadSplitInsts.insert(&II))
2076 Pass.DeadInsts.push_back(&II);
2078 Type *AllocaTy = NewAI.getAllocatedType();
2079 Type *ScalarTy = AllocaTy->getScalarType();
2081 // If this doesn't map cleanly onto the alloca type, and that type isn't
2082 // a single value type, just emit a memset.
2083 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
2084 EndOffset != NewAllocaEndOffset ||
2085 !AllocaTy->isSingleValueType() ||
2086 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
2087 Type *SizeTy = II.getLength()->getType();
2088 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2090 if (NewAI.getAlignment())
2091 Align = MinAlign(NewAI.getAlignment(),
2092 BeginOffset - NewAllocaBeginOffset);
2095 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2096 II.getRawDest()->getType()),
2097 II.getValue(), Size, Align,
2100 DEBUG(dbgs() << " to: " << *New << "\n");
2104 // If we can represent this as a simple value, we have to build the actual
2105 // value to store, which requires expanding the byte present in memset to
2106 // a sensible representation for the alloca type. This is essentially
2107 // splatting the byte to a sufficiently wide integer, bitcasting to the
2108 // desired scalar type, and splatting it across any desired vector type.
2109 Value *V = II.getValue();
2110 IntegerType *VTy = cast<IntegerType>(V->getType());
2111 Type *IntTy = Type::getIntNTy(VTy->getContext(),
2112 TD.getTypeSizeInBits(ScalarTy));
2113 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
2114 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
2115 ConstantExpr::getUDiv(
2116 Constant::getAllOnesValue(IntTy),
2117 ConstantExpr::getZExt(
2118 Constant::getAllOnesValue(V->getType()),
2120 getName(".isplat"));
2121 if (V->getType() != ScalarTy) {
2122 if (ScalarTy->isPointerTy())
2123 V = IRB.CreateIntToPtr(V, ScalarTy);
2124 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
2125 V = IRB.CreateBitCast(V, ScalarTy);
2126 else if (ScalarTy->isIntegerTy())
2127 llvm_unreachable("Computed different integer types with equal widths");
2129 llvm_unreachable("Invalid scalar type");
2132 // If this is an element-wide memset of a vectorizable alloca, insert it.
2133 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2134 EndOffset < NewAllocaEndOffset)) {
2135 StoreInst *Store = IRB.CreateAlignedStore(
2136 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2137 NewAI.getAlignment(),
2139 V, getIndex(IRB, BeginOffset),
2140 getName(".insert")),
2141 &NewAI, NewAI.getAlignment());
2143 DEBUG(dbgs() << " to: " << *Store << "\n");
2147 // Splat to a vector if needed.
2148 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
2149 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
2150 V = IRB.CreateShuffleVector(
2151 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
2152 IRB.getInt32(0), getName(".vsplat.insert")),
2153 UndefValue::get(SplatSourceTy),
2154 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
2155 getName(".vsplat.shuffle"));
2156 assert(V->getType() == VecTy);
2159 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2162 DEBUG(dbgs() << " to: " << *New << "\n");
2163 return !II.isVolatile();
2166 bool visitMemTransferInst(MemTransferInst &II) {
2167 // Rewriting of memory transfer instructions can be a bit tricky. We break
2168 // them into two categories: split intrinsics and unsplit intrinsics.
2170 DEBUG(dbgs() << " original: " << II << "\n");
2171 IRBuilder<> IRB(&II);
2173 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2174 bool IsDest = II.getRawDest() == OldPtr;
2176 const AllocaPartitioning::MemTransferOffsets &MTO
2177 = P.getMemTransferOffsets(II);
2179 // For unsplit intrinsics, we simply modify the source and destination
2180 // pointers in place. This isn't just an optimization, it is a matter of
2181 // correctness. With unsplit intrinsics we may be dealing with transfers
2182 // within a single alloca before SROA ran, or with transfers that have
2183 // a variable length. We may also be dealing with memmove instead of
2184 // memcpy, and so simply updating the pointers is the necessary for us to
2185 // update both source and dest of a single call.
2186 if (!MTO.IsSplittable) {
2187 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2189 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2191 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2193 Type *CstTy = II.getAlignmentCst()->getType();
2194 if (II.getAlignment() > 1)
2195 II.setAlignment(ConstantInt::get(
2196 CstTy, MinAlign(II.getAlignment(),
2197 MinAlign(NewAI.getAlignment(),
2198 BeginOffset - NewAllocaBeginOffset))));
2200 DEBUG(dbgs() << " to: " << II << "\n");
2201 deleteIfTriviallyDead(OldOp);
2204 // For split transfer intrinsics we have an incredibly useful assurance:
2205 // the source and destination do not reside within the same alloca, and at
2206 // least one of them does not escape. This means that we can replace
2207 // memmove with memcpy, and we don't need to worry about all manner of
2208 // downsides to splitting and transforming the operations.
2210 // Compute the relative offset within the transfer.
2211 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2212 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2213 : MTO.SourceBegin));
2215 // If this doesn't map cleanly onto the alloca type, and that type isn't
2216 // a single value type, just emit a memcpy.
2218 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
2219 EndOffset != NewAllocaEndOffset ||
2220 !NewAI.getAllocatedType()->isSingleValueType());
2222 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2223 // size hasn't been shrunk based on analysis of the viable range, this is
2225 if (EmitMemCpy && &OldAI == &NewAI) {
2226 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2227 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2228 // Ensure the start lines up.
2229 assert(BeginOffset == OrigBegin);
2232 // Rewrite the size as needed.
2233 if (EndOffset != OrigEnd)
2234 II.setLength(ConstantInt::get(II.getLength()->getType(),
2235 EndOffset - BeginOffset));
2238 // Record this instruction for deletion.
2239 if (Pass.DeadSplitInsts.insert(&II))
2240 Pass.DeadInsts.push_back(&II);
2242 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
2243 EndOffset < NewAllocaEndOffset);
2245 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2246 : II.getRawDest()->getType();
2248 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
2251 // Compute the other pointer, folding as much as possible to produce
2252 // a single, simple GEP in most cases.
2253 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2254 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2255 getName("." + OtherPtr->getName()));
2257 unsigned Align = II.getAlignment();
2259 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2260 MinAlign(II.getAlignment(), NewAI.getAlignment()));
2262 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2263 // alloca that should be re-examined after rewriting this instruction.
2265 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2266 Pass.Worklist.insert(AI);
2270 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2271 : II.getRawSource()->getType());
2272 Type *SizeTy = II.getLength()->getType();
2273 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2275 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2276 IsDest ? OtherPtr : OurPtr,
2277 Size, Align, II.isVolatile());
2279 DEBUG(dbgs() << " to: " << *New << "\n");
2283 Value *SrcPtr = OtherPtr;
2284 Value *DstPtr = &NewAI;
2286 std::swap(SrcPtr, DstPtr);
2289 if (IsVectorElement && !IsDest) {
2290 // We have to extract rather than load.
2291 Src = IRB.CreateExtractElement(
2292 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
2293 getIndex(IRB, BeginOffset),
2294 getName(".copyextract"));
2296 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2297 getName(".copyload"));
2300 if (IsVectorElement && IsDest) {
2301 // We have to insert into a loaded copy before storing.
2302 Src = IRB.CreateInsertElement(
2303 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2304 Src, getIndex(IRB, BeginOffset),
2305 getName(".insert"));
2308 StoreInst *Store = cast<StoreInst>(
2309 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2311 DEBUG(dbgs() << " to: " << *Store << "\n");
2312 return !II.isVolatile();
2315 bool visitIntrinsicInst(IntrinsicInst &II) {
2316 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2317 II.getIntrinsicID() == Intrinsic::lifetime_end);
2318 DEBUG(dbgs() << " original: " << II << "\n");
2319 IRBuilder<> IRB(&II);
2320 assert(II.getArgOperand(1) == OldPtr);
2322 // Record this instruction for deletion.
2323 if (Pass.DeadSplitInsts.insert(&II))
2324 Pass.DeadInsts.push_back(&II);
2327 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2328 EndOffset - BeginOffset);
2329 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2331 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2332 New = IRB.CreateLifetimeStart(Ptr, Size);
2334 New = IRB.CreateLifetimeEnd(Ptr, Size);
2336 DEBUG(dbgs() << " to: " << *New << "\n");
2340 /// PHI instructions that use an alloca and are subsequently loaded can be
2341 /// rewritten to load both input pointers in the pred blocks and then PHI the
2342 /// results, allowing the load of the alloca to be promoted.
2344 /// %P2 = phi [i32* %Alloca, i32* %Other]
2345 /// %V = load i32* %P2
2347 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2349 /// %V2 = load i32* %Other
2351 /// %V = phi [i32 %V1, i32 %V2]
2353 /// We can do this to a select if its only uses are loads and if the operand
2354 /// to the select can be loaded unconditionally.
2356 /// FIXME: This should be hoisted into a generic utility, likely in
2357 /// Transforms/Util/Local.h
2358 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
2359 // For now, we can only do this promotion if the load is in the same block
2360 // as the PHI, and if there are no stores between the phi and load.
2361 // TODO: Allow recursive phi users.
2362 // TODO: Allow stores.
2363 BasicBlock *BB = PN.getParent();
2364 unsigned MaxAlign = 0;
2365 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
2367 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2368 if (LI == 0 || !LI->isSimple()) return false;
2370 // For now we only allow loads in the same block as the PHI. This is
2371 // a common case that happens when instcombine merges two loads through
2373 if (LI->getParent() != BB) return false;
2375 // Ensure that there are no instructions between the PHI and the load that
2377 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
2378 if (BBI->mayWriteToMemory())
2381 MaxAlign = std::max(MaxAlign, LI->getAlignment());
2382 Loads.push_back(LI);
2385 // We can only transform this if it is safe to push the loads into the
2386 // predecessor blocks. The only thing to watch out for is that we can't put
2387 // a possibly trapping load in the predecessor if it is a critical edge.
2388 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
2390 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
2391 Value *InVal = PN.getIncomingValue(Idx);
2393 // If the value is produced by the terminator of the predecessor (an
2394 // invoke) or it has side-effects, there is no valid place to put a load
2395 // in the predecessor.
2396 if (TI == InVal || TI->mayHaveSideEffects())
2399 // If the predecessor has a single successor, then the edge isn't
2401 if (TI->getNumSuccessors() == 1)
2404 // If this pointer is always safe to load, or if we can prove that there
2405 // is already a load in the block, then we can move the load to the pred
2407 if (InVal->isDereferenceablePointer() ||
2408 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
2417 bool visitPHINode(PHINode &PN) {
2418 DEBUG(dbgs() << " original: " << PN << "\n");
2419 // We would like to compute a new pointer in only one place, but have it be
2420 // as local as possible to the PHI. To do that, we re-use the location of
2421 // the old pointer, which necessarily must be in the right position to
2422 // dominate the PHI.
2423 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2425 SmallVector<LoadInst *, 4> Loads;
2426 if (!isSafePHIToSpeculate(PN, Loads)) {
2427 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2428 // Replace the operands which were using the old pointer.
2429 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2430 for (; OI != OE; ++OI)
2434 DEBUG(dbgs() << " to: " << PN << "\n");
2435 deleteIfTriviallyDead(OldPtr);
2438 assert(!Loads.empty());
2440 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
2441 IRBuilder<> PHIBuilder(&PN);
2442 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues());
2443 NewPN->takeName(&PN);
2445 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
2446 // matter which one we get and if any differ, it doesn't matter.
2447 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
2448 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
2449 unsigned Align = SomeLoad->getAlignment();
2450 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2452 // Rewrite all loads of the PN to use the new PHI.
2454 LoadInst *LI = Loads.pop_back_val();
2455 LI->replaceAllUsesWith(NewPN);
2456 Pass.DeadInsts.push_back(LI);
2457 } while (!Loads.empty());
2459 // Inject loads into all of the pred blocks.
2460 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
2461 BasicBlock *Pred = PN.getIncomingBlock(Idx);
2462 TerminatorInst *TI = Pred->getTerminator();
2463 Value *InVal = PN.getIncomingValue(Idx);
2464 IRBuilder<> PredBuilder(TI);
2466 // Map the value to the new alloca pointer if this was the old alloca
2468 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
2469 bool ThisOperand = InUse == OldUse;
2474 = PredBuilder.CreateLoad(InVal, getName(".sroa.speculate." +
2476 ++NumLoadsSpeculated;
2477 Load->setAlignment(Align);
2479 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
2480 NewPN->addIncoming(Load, Pred);
2482 Instruction *Ptr = dyn_cast<Instruction>(InVal);
2484 // No uses to rewrite.
2487 // Try to lookup and rewrite any partition uses corresponding to this phi
2489 AllocaPartitioning::iterator PI
2490 = P.findPartitionForPHIOrSelectOperand(InUse);
2494 // Replace the Use in the PartitionUse for this operand with the Use
2495 // inside the load. This will already have been re-written for the
2496 // partition use currently being processed.
2497 // FIXME: This is really gross. We should do PHI and select speculation
2498 // as a pre-processing pass first, and then use the existing
2499 // load-rewriting logic.
2500 AllocaPartitioning::use_iterator UI
2501 = P.findPartitionUseForPHIOrSelectOperand(InUse);
2502 assert(isa<PHINode>(*UI->U->getUser()));
2503 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
2505 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
2506 return NewPtr == &NewAI;
2509 /// Select instructions that use an alloca and are subsequently loaded can be
2510 /// rewritten to load both input pointers and then select between the result,
2511 /// allowing the load of the alloca to be promoted.
2513 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
2514 /// %V = load i32* %P2
2516 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2517 /// %V2 = load i32* %Other
2518 /// %V = select i1 %cond, i32 %V1, i32 %V2
2520 /// We can do this to a select if its only uses are loads and if the operand
2521 /// to the select can be loaded unconditionally.
2522 bool isSafeSelectToSpeculate(SelectInst &SI,
2523 SmallVectorImpl<LoadInst *> &Loads) {
2524 Value *TValue = SI.getTrueValue();
2525 Value *FValue = SI.getFalseValue();
2526 bool TDerefable = TValue->isDereferenceablePointer();
2527 bool FDerefable = FValue->isDereferenceablePointer();
2529 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
2531 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2532 if (LI == 0 || !LI->isSimple()) return false;
2534 // Both operands to the select need to be dereferencable, either
2535 // absolutely (e.g. allocas) or at this point because we can see other
2537 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
2538 LI->getAlignment(), &TD))
2540 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
2541 LI->getAlignment(), &TD))
2543 Loads.push_back(LI);
2549 bool visitSelectInst(SelectInst &SI) {
2550 DEBUG(dbgs() << " original: " << SI << "\n");
2551 IRBuilder<> IRB(&SI);
2553 // Find the operand we need to rewrite here.
2554 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2556 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2558 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2559 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2561 // If the select isn't safe to speculate, just use simple logic to emit it.
2562 SmallVector<LoadInst *, 4> Loads;
2563 if (!isSafeSelectToSpeculate(SI, Loads)) {
2564 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2565 DEBUG(dbgs() << " to: " << SI << "\n");
2566 deleteIfTriviallyDead(OldPtr);
2570 Use *OtherOp = &SI.getOperandUse(IsTrueVal ? 2 : 1);
2571 AllocaPartitioning::iterator PI
2572 = P.findPartitionForPHIOrSelectOperand(OtherOp);
2573 AllocaPartitioning::PartitionUse OtherUse;
2574 if (PI != P.end()) {
2575 // If the other pointer is within the partitioning, remove the select
2576 // from its uses. We'll add in the new loads below.
2577 AllocaPartitioning::use_iterator UI
2578 = P.findPartitionUseForPHIOrSelectOperand(OtherOp);
2580 P.use_erase(PI, UI);
2583 Value *TV = IsTrueVal ? NewPtr : SI.getTrueValue();
2584 Value *FV = IsTrueVal ? SI.getFalseValue() : NewPtr;
2585 // Replace the loads of the select with a select of two loads.
2586 while (!Loads.empty()) {
2587 LoadInst *LI = Loads.pop_back_val();
2589 IRB.SetInsertPoint(LI);
2591 IRB.CreateLoad(TV, getName("." + LI->getName() + ".true"));
2593 IRB.CreateLoad(FV, getName("." + LI->getName() + ".false"));
2594 NumLoadsSpeculated += 2;
2596 // Transfer alignment and TBAA info if present.
2597 TL->setAlignment(LI->getAlignment());
2598 FL->setAlignment(LI->getAlignment());
2599 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2600 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2601 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2605 = cast<SelectInst>(IRB.CreateSelect(SI.getCondition(), TL, FL));
2606 NewSI->takeName(LI);
2607 if (PI != P.end()) {
2608 LoadInst *OtherLoad = IsTrueVal ? FL : TL;
2609 Use *OtherLoadUse = &OtherLoad->getOperandUse(0);
2610 assert(OtherUse.U->get() == OtherLoadUse->get());
2611 OtherUse.U = OtherLoadUse;
2612 P.use_push_back(PI, OtherUse);
2614 DEBUG(dbgs() << " speculated to: " << *NewSI << "\n");
2615 LI->replaceAllUsesWith(NewSI);
2616 Pass.DeadInsts.push_back(LI);
2619 deleteIfTriviallyDead(OldPtr);
2620 return NewPtr == &NewAI;
2627 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2629 /// This pass aggressively rewrites all aggregate loads and stores on
2630 /// a particular pointer (or any pointer derived from it which we can identify)
2631 /// with scalar loads and stores.
2632 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2633 // Befriend the base class so it can delegate to private visit methods.
2634 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2636 const TargetData &TD;
2638 /// Queue of pointer uses to analyze and potentially rewrite.
2639 SmallVector<Use *, 8> Queue;
2641 /// Set to prevent us from cycling with phi nodes and loops.
2642 SmallPtrSet<User *, 8> Visited;
2644 /// The current pointer use being rewritten. This is used to dig up the used
2645 /// value (as opposed to the user).
2649 AggLoadStoreRewriter(const TargetData &TD) : TD(TD) {}
2651 /// Rewrite loads and stores through a pointer and all pointers derived from
2653 bool rewrite(Instruction &I) {
2654 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2656 bool Changed = false;
2657 while (!Queue.empty()) {
2658 U = Queue.pop_back_val();
2659 Changed |= visit(cast<Instruction>(U->getUser()));
2665 /// Enqueue all the users of the given instruction for further processing.
2666 /// This uses a set to de-duplicate users.
2667 void enqueueUsers(Instruction &I) {
2668 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2670 if (Visited.insert(*UI))
2671 Queue.push_back(&UI.getUse());
2674 // Conservative default is to not rewrite anything.
2675 bool visitInstruction(Instruction &I) { return false; }
2677 /// \brief Generic recursive split emission class.
2678 template <typename Derived>
2681 /// The builder used to form new instructions.
2683 /// The indices which to be used with insert- or extractvalue to select the
2684 /// appropriate value within the aggregate.
2685 SmallVector<unsigned, 4> Indices;
2686 /// The indices to a GEP instruction which will move Ptr to the correct slot
2687 /// within the aggregate.
2688 SmallVector<Value *, 4> GEPIndices;
2689 /// The base pointer of the original op, used as a base for GEPing the
2690 /// split operations.
2693 /// Initialize the splitter with an insertion point, Ptr and start with a
2694 /// single zero GEP index.
2695 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
2696 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
2699 /// \brief Generic recursive split emission routine.
2701 /// This method recursively splits an aggregate op (load or store) into
2702 /// scalar or vector ops. It splits recursively until it hits a single value
2703 /// and emits that single value operation via the template argument.
2705 /// The logic of this routine relies on GEPs and insertvalue and
2706 /// extractvalue all operating with the same fundamental index list, merely
2707 /// formatted differently (GEPs need actual values).
2709 /// \param Ty The type being split recursively into smaller ops.
2710 /// \param Agg The aggregate value being built up or stored, depending on
2711 /// whether this is splitting a load or a store respectively.
2712 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2713 if (Ty->isSingleValueType())
2714 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
2716 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2717 unsigned OldSize = Indices.size();
2719 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2721 assert(Indices.size() == OldSize && "Did not return to the old size");
2722 Indices.push_back(Idx);
2723 GEPIndices.push_back(IRB.getInt32(Idx));
2724 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2725 GEPIndices.pop_back();
2731 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2732 unsigned OldSize = Indices.size();
2734 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2736 assert(Indices.size() == OldSize && "Did not return to the old size");
2737 Indices.push_back(Idx);
2738 GEPIndices.push_back(IRB.getInt32(Idx));
2739 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2740 GEPIndices.pop_back();
2746 llvm_unreachable("Only arrays and structs are aggregate loadable types");
2750 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
2751 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2752 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
2754 /// Emit a leaf load of a single value. This is called at the leaves of the
2755 /// recursive emission to actually load values.
2756 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2757 assert(Ty->isSingleValueType());
2758 // Load the single value and insert it using the indices.
2759 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
2762 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2763 DEBUG(dbgs() << " to: " << *Load << "\n");
2767 bool visitLoadInst(LoadInst &LI) {
2768 assert(LI.getPointerOperand() == *U);
2769 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2772 // We have an aggregate being loaded, split it apart.
2773 DEBUG(dbgs() << " original: " << LI << "\n");
2774 LoadOpSplitter Splitter(&LI, *U);
2775 Value *V = UndefValue::get(LI.getType());
2776 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
2777 LI.replaceAllUsesWith(V);
2778 LI.eraseFromParent();
2782 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
2783 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2784 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
2786 /// Emit a leaf store of a single value. This is called at the leaves of the
2787 /// recursive emission to actually produce stores.
2788 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2789 assert(Ty->isSingleValueType());
2790 // Extract the single value and store it using the indices.
2791 Value *Store = IRB.CreateStore(
2792 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2793 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2795 DEBUG(dbgs() << " to: " << *Store << "\n");
2799 bool visitStoreInst(StoreInst &SI) {
2800 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2802 Value *V = SI.getValueOperand();
2803 if (V->getType()->isSingleValueType())
2806 // We have an aggregate being stored, split it apart.
2807 DEBUG(dbgs() << " original: " << SI << "\n");
2808 StoreOpSplitter Splitter(&SI, *U);
2809 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
2810 SI.eraseFromParent();
2814 bool visitBitCastInst(BitCastInst &BC) {
2819 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2824 bool visitPHINode(PHINode &PN) {
2829 bool visitSelectInst(SelectInst &SI) {
2836 /// \brief Try to find a partition of the aggregate type passed in for a given
2837 /// offset and size.
2839 /// This recurses through the aggregate type and tries to compute a subtype
2840 /// based on the offset and size. When the offset and size span a sub-section
2841 /// of an array, it will even compute a new array type for that sub-section,
2842 /// and the same for structs.
2844 /// Note that this routine is very strict and tries to find a partition of the
2845 /// type which produces the *exact* right offset and size. It is not forgiving
2846 /// when the size or offset cause either end of type-based partition to be off.
2847 /// Also, this is a best-effort routine. It is reasonable to give up and not
2848 /// return a type if necessary.
2849 static Type *getTypePartition(const TargetData &TD, Type *Ty,
2850 uint64_t Offset, uint64_t Size) {
2851 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2854 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2855 // We can't partition pointers...
2856 if (SeqTy->isPointerTy())
2859 Type *ElementTy = SeqTy->getElementType();
2860 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2861 uint64_t NumSkippedElements = Offset / ElementSize;
2862 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2863 if (NumSkippedElements >= ArrTy->getNumElements())
2865 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2866 if (NumSkippedElements >= VecTy->getNumElements())
2868 Offset -= NumSkippedElements * ElementSize;
2870 // First check if we need to recurse.
2871 if (Offset > 0 || Size < ElementSize) {
2872 // Bail if the partition ends in a different array element.
2873 if ((Offset + Size) > ElementSize)
2875 // Recurse through the element type trying to peel off offset bytes.
2876 return getTypePartition(TD, ElementTy, Offset, Size);
2878 assert(Offset == 0);
2880 if (Size == ElementSize)
2882 assert(Size > ElementSize);
2883 uint64_t NumElements = Size / ElementSize;
2884 if (NumElements * ElementSize != Size)
2886 return ArrayType::get(ElementTy, NumElements);
2889 StructType *STy = dyn_cast<StructType>(Ty);
2893 const StructLayout *SL = TD.getStructLayout(STy);
2894 if (Offset >= SL->getSizeInBytes())
2896 uint64_t EndOffset = Offset + Size;
2897 if (EndOffset > SL->getSizeInBytes())
2900 unsigned Index = SL->getElementContainingOffset(Offset);
2901 Offset -= SL->getElementOffset(Index);
2903 Type *ElementTy = STy->getElementType(Index);
2904 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2905 if (Offset >= ElementSize)
2906 return 0; // The offset points into alignment padding.
2908 // See if any partition must be contained by the element.
2909 if (Offset > 0 || Size < ElementSize) {
2910 if ((Offset + Size) > ElementSize)
2912 return getTypePartition(TD, ElementTy, Offset, Size);
2914 assert(Offset == 0);
2916 if (Size == ElementSize)
2919 StructType::element_iterator EI = STy->element_begin() + Index,
2920 EE = STy->element_end();
2921 if (EndOffset < SL->getSizeInBytes()) {
2922 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2923 if (Index == EndIndex)
2924 return 0; // Within a single element and its padding.
2926 // Don't try to form "natural" types if the elements don't line up with the
2928 // FIXME: We could potentially recurse down through the last element in the
2929 // sub-struct to find a natural end point.
2930 if (SL->getElementOffset(EndIndex) != EndOffset)
2933 assert(Index < EndIndex);
2934 EE = STy->element_begin() + EndIndex;
2937 // Try to build up a sub-structure.
2938 SmallVector<Type *, 4> ElementTys;
2940 ElementTys.push_back(*EI++);
2942 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
2944 const StructLayout *SubSL = TD.getStructLayout(SubTy);
2945 if (Size != SubSL->getSizeInBytes())
2946 return 0; // The sub-struct doesn't have quite the size needed.
2951 /// \brief Rewrite an alloca partition's users.
2953 /// This routine drives both of the rewriting goals of the SROA pass. It tries
2954 /// to rewrite uses of an alloca partition to be conducive for SSA value
2955 /// promotion. If the partition needs a new, more refined alloca, this will
2956 /// build that new alloca, preserving as much type information as possible, and
2957 /// rewrite the uses of the old alloca to point at the new one and have the
2958 /// appropriate new offsets. It also evaluates how successful the rewrite was
2959 /// at enabling promotion and if it was successful queues the alloca to be
2961 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
2962 AllocaPartitioning &P,
2963 AllocaPartitioning::iterator PI) {
2964 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
2965 if (P.use_begin(PI) == P.use_end(PI))
2966 return false; // No live uses left of this partition.
2968 // Try to compute a friendly type for this partition of the alloca. This
2969 // won't always succeed, in which case we fall back to a legal integer type
2970 // or an i8 array of an appropriate size.
2972 if (Type *PartitionTy = P.getCommonType(PI))
2973 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
2974 AllocaTy = PartitionTy;
2976 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
2977 PI->BeginOffset, AllocaSize))
2978 AllocaTy = PartitionTy;
2980 (AllocaTy->isArrayTy() &&
2981 AllocaTy->getArrayElementType()->isIntegerTy())) &&
2982 TD->isLegalInteger(AllocaSize * 8))
2983 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
2985 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
2986 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
2988 // Check for the case where we're going to rewrite to a new alloca of the
2989 // exact same type as the original, and with the same access offsets. In that
2990 // case, re-use the existing alloca, but still run through the rewriter to
2991 // performe phi and select speculation.
2993 if (AllocaTy == AI.getAllocatedType()) {
2994 assert(PI->BeginOffset == 0 &&
2995 "Non-zero begin offset but same alloca type");
2996 assert(PI == P.begin() && "Begin offset is zero on later partition");
2999 unsigned Alignment = AI.getAlignment();
3001 // The minimum alignment which users can rely on when the explicit
3002 // alignment is omitted or zero is that required by the ABI for this
3004 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3006 Alignment = MinAlign(Alignment, PI->BeginOffset);
3007 // If we will get at least this much alignment from the type alone, leave
3008 // the alloca's alignment unconstrained.
3009 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3011 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
3012 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3017 DEBUG(dbgs() << "Rewriting alloca partition "
3018 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3021 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3022 PI->BeginOffset, PI->EndOffset);
3023 DEBUG(dbgs() << " rewriting ");
3024 DEBUG(P.print(dbgs(), PI, ""));
3025 if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
3026 DEBUG(dbgs() << " and queuing for promotion\n");
3027 PromotableAllocas.push_back(NewAI);
3028 } else if (NewAI != &AI) {
3029 // If we can't promote the alloca, iterate on it to check for new
3030 // refinements exposed by splitting the current alloca. Don't iterate on an
3031 // alloca which didn't actually change and didn't get promoted.
3032 Worklist.insert(NewAI);
3037 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3038 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3039 bool Changed = false;
3040 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3042 Changed |= rewriteAllocaPartition(AI, P, PI);
3047 /// \brief Analyze an alloca for SROA.
3049 /// This analyzes the alloca to ensure we can reason about it, builds
3050 /// a partitioning of the alloca, and then hands it off to be split and
3051 /// rewritten as needed.
3052 bool SROA::runOnAlloca(AllocaInst &AI) {
3053 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3054 ++NumAllocasAnalyzed;
3056 // Special case dead allocas, as they're trivial.
3057 if (AI.use_empty()) {
3058 AI.eraseFromParent();
3062 // Skip alloca forms that this analysis can't handle.
3063 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3064 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3067 // First check if this is a non-aggregate type that we should simply promote.
3068 if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
3069 DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
3070 PromotableAllocas.push_back(&AI);
3074 bool Changed = false;
3076 // First, split any FCA loads and stores touching this alloca to promote
3077 // better splitting and promotion opportunities.
3078 AggLoadStoreRewriter AggRewriter(*TD);
3079 Changed |= AggRewriter.rewrite(AI);
3081 // Build the partition set using a recursive instruction-visiting builder.
3082 AllocaPartitioning P(*TD, AI);
3083 DEBUG(P.print(dbgs()));
3087 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3088 if (P.begin() == P.end())
3091 // Delete all the dead users of this alloca before splitting and rewriting it.
3092 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3093 DE = P.dead_user_end();
3096 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3097 DeadInsts.push_back(*DI);
3099 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3100 DE = P.dead_op_end();
3103 // Clobber the use with an undef value.
3104 **DO = UndefValue::get(OldV->getType());
3105 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3106 if (isInstructionTriviallyDead(OldI)) {
3108 DeadInsts.push_back(OldI);
3112 return splitAlloca(AI, P) || Changed;
3115 /// \brief Delete the dead instructions accumulated in this run.
3117 /// Recursively deletes the dead instructions we've accumulated. This is done
3118 /// at the very end to maximize locality of the recursive delete and to
3119 /// minimize the problems of invalidated instruction pointers as such pointers
3120 /// are used heavily in the intermediate stages of the algorithm.
3122 /// We also record the alloca instructions deleted here so that they aren't
3123 /// subsequently handed to mem2reg to promote.
3124 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3125 DeadSplitInsts.clear();
3126 while (!DeadInsts.empty()) {
3127 Instruction *I = DeadInsts.pop_back_val();
3128 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3130 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3131 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3132 // Zero out the operand and see if it becomes trivially dead.
3134 if (isInstructionTriviallyDead(U))
3135 DeadInsts.push_back(U);
3138 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3139 DeletedAllocas.insert(AI);
3142 I->eraseFromParent();
3146 /// \brief Promote the allocas, using the best available technique.
3148 /// This attempts to promote whatever allocas have been identified as viable in
3149 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3150 /// If there is a domtree available, we attempt to promote using the full power
3151 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3152 /// based on the SSAUpdater utilities. This function returns whether any
3153 /// promotion occured.
3154 bool SROA::promoteAllocas(Function &F) {
3155 if (PromotableAllocas.empty())
3158 NumPromoted += PromotableAllocas.size();
3160 if (DT && !ForceSSAUpdater) {
3161 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3162 PromoteMemToReg(PromotableAllocas, *DT);
3163 PromotableAllocas.clear();
3167 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3169 DIBuilder DIB(*F.getParent());
3170 SmallVector<Instruction*, 64> Insts;
3172 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3173 AllocaInst *AI = PromotableAllocas[Idx];
3174 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3176 Instruction *I = cast<Instruction>(*UI++);
3177 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3178 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3179 // leading to them) here. Eventually it should use them to optimize the
3180 // scalar values produced.
3181 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3182 assert(onlyUsedByLifetimeMarkers(I) &&
3183 "Found a bitcast used outside of a lifetime marker.");
3184 while (!I->use_empty())
3185 cast<Instruction>(*I->use_begin())->eraseFromParent();
3186 I->eraseFromParent();
3189 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3190 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3191 II->getIntrinsicID() == Intrinsic::lifetime_end);
3192 II->eraseFromParent();
3198 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3202 PromotableAllocas.clear();
3207 /// \brief A predicate to test whether an alloca belongs to a set.
3208 class IsAllocaInSet {
3209 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3213 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3214 bool operator()(AllocaInst *AI) { return Set.count(AI); }
3218 bool SROA::runOnFunction(Function &F) {
3219 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3220 C = &F.getContext();
3221 TD = getAnalysisIfAvailable<TargetData>();
3223 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3226 DT = getAnalysisIfAvailable<DominatorTree>();
3228 BasicBlock &EntryBB = F.getEntryBlock();
3229 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3231 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3232 Worklist.insert(AI);
3234 bool Changed = false;
3235 // A set of deleted alloca instruction pointers which should be removed from
3236 // the list of promotable allocas.
3237 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3239 while (!Worklist.empty()) {
3240 Changed |= runOnAlloca(*Worklist.pop_back_val());
3241 deleteDeadInstructions(DeletedAllocas);
3242 if (!DeletedAllocas.empty()) {
3243 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3244 PromotableAllocas.end(),
3245 IsAllocaInSet(DeletedAllocas)),
3246 PromotableAllocas.end());
3247 DeletedAllocas.clear();
3251 Changed |= promoteAllocas(F);
3256 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3257 if (RequiresDomTree)
3258 AU.addRequired<DominatorTree>();
3259 AU.setPreservesCFG();