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/ADT/STLExtras.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/Dominators.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/PtrUseVisitor.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/DIBuilder.h"
37 #include "llvm/DebugInfo.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/LLVMContext.h"
46 #include "llvm/IR/Operator.h"
47 #include "llvm/InstVisitor.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Transforms/Utils/Local.h"
55 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
56 #include "llvm/Transforms/Utils/SSAUpdater.h"
59 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
60 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
61 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions");
62 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses found");
63 STATISTIC(MaxPartitionUsesPerAlloca, "Maximum number of partition uses");
64 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
65 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
66 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
67 STATISTIC(NumDeleted, "Number of instructions deleted");
68 STATISTIC(NumVectorized, "Number of vectorized aggregates");
70 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
71 /// forming SSA values through the SSAUpdater infrastructure.
73 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
76 /// \brief A common base class for representing a half-open byte range.
78 /// \brief The beginning offset of the range.
81 /// \brief The ending offset, not included in the range.
84 ByteRange() : BeginOffset(), EndOffset() {}
85 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
86 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
88 /// \brief Support for ordering ranges.
90 /// This provides an ordering over ranges such that start offsets are
91 /// always increasing, and within equal start offsets, the end offsets are
92 /// decreasing. Thus the spanning range comes first in a cluster with the
93 /// same start position.
94 bool operator<(const ByteRange &RHS) const {
95 if (BeginOffset < RHS.BeginOffset) return true;
96 if (BeginOffset > RHS.BeginOffset) return false;
97 if (EndOffset > RHS.EndOffset) return true;
101 /// \brief Support comparison with a single offset to allow binary searches.
102 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
103 return LHS.BeginOffset < RHSOffset;
106 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
107 const ByteRange &RHS) {
108 return LHSOffset < RHS.BeginOffset;
111 bool operator==(const ByteRange &RHS) const {
112 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
114 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
117 /// \brief A partition of an alloca.
119 /// This structure represents a contiguous partition of the alloca. These are
120 /// formed by examining the uses of the alloca. During formation, they may
121 /// overlap but once an AllocaPartitioning is built, the Partitions within it
122 /// are all disjoint.
123 struct Partition : public ByteRange {
124 /// \brief Whether this partition is splittable into smaller partitions.
126 /// We flag partitions as splittable when they are formed entirely due to
127 /// accesses by trivially splittable operations such as memset and memcpy.
130 /// \brief Test whether a partition has been marked as dead.
131 bool isDead() const {
132 if (BeginOffset == UINT64_MAX) {
133 assert(EndOffset == UINT64_MAX);
139 /// \brief Kill a partition.
140 /// This is accomplished by setting both its beginning and end offset to
141 /// the maximum possible value.
143 assert(!isDead() && "He's Dead, Jim!");
144 BeginOffset = EndOffset = UINT64_MAX;
147 Partition() : ByteRange(), IsSplittable() {}
148 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
149 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
152 /// \brief A particular use of a partition of the alloca.
154 /// This structure is used to associate uses of a partition with it. They
155 /// mark the range of bytes which are referenced by a particular instruction,
156 /// and includes a handle to the user itself and the pointer value in use.
157 /// The bounds of these uses are determined by intersecting the bounds of the
158 /// memory use itself with a particular partition. As a consequence there is
159 /// intentionally overlap between various uses of the same partition.
160 class PartitionUse : public ByteRange {
161 /// \brief Combined storage for both the Use* and split state.
162 PointerIntPair<Use*, 1, bool> UsePtrAndIsSplit;
165 PartitionUse() : ByteRange(), UsePtrAndIsSplit() {}
166 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U,
168 : ByteRange(BeginOffset, EndOffset), UsePtrAndIsSplit(U, IsSplit) {}
170 /// \brief The use in question. Provides access to both user and used value.
172 /// Note that this may be null if the partition use is *dead*, that is, it
173 /// should be ignored.
174 Use *getUse() const { return UsePtrAndIsSplit.getPointer(); }
176 /// \brief Set the use for this partition use range.
177 void setUse(Use *U) { UsePtrAndIsSplit.setPointer(U); }
179 /// \brief Whether this use is split across multiple partitions.
180 bool isSplit() const { return UsePtrAndIsSplit.getInt(); }
185 template <> struct isPodLike<Partition> : llvm::true_type {};
186 template <> struct isPodLike<PartitionUse> : llvm::true_type {};
190 /// \brief Alloca partitioning representation.
192 /// This class represents a partitioning of an alloca into slices, and
193 /// information about the nature of uses of each slice of the alloca. The goal
194 /// is that this information is sufficient to decide if and how to split the
195 /// alloca apart and replace slices with scalars. It is also intended that this
196 /// structure can capture the relevant information needed both to decide about
197 /// and to enact these transformations.
198 class AllocaPartitioning {
200 /// \brief Construct a partitioning of a particular alloca.
202 /// Construction does most of the work for partitioning the alloca. This
203 /// performs the necessary walks of users and builds a partitioning from it.
204 AllocaPartitioning(const DataLayout &TD, AllocaInst &AI);
206 /// \brief Test whether a pointer to the allocation escapes our analysis.
208 /// If this is true, the partitioning is never fully built and should be
210 bool isEscaped() const { return PointerEscapingInstr; }
212 /// \brief Support for iterating over the partitions.
214 typedef SmallVectorImpl<Partition>::iterator iterator;
215 iterator begin() { return Partitions.begin(); }
216 iterator end() { return Partitions.end(); }
218 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
219 const_iterator begin() const { return Partitions.begin(); }
220 const_iterator end() const { return Partitions.end(); }
223 /// \brief Support for iterating over and manipulating a particular
224 /// partition's uses.
226 /// The iteration support provided for uses is more limited, but also
227 /// includes some manipulation routines to support rewriting the uses of
228 /// partitions during SROA.
230 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
231 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
232 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
233 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
234 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
236 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
237 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
238 const_use_iterator use_begin(const_iterator I) const {
239 return Uses[I - begin()].begin();
241 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
242 const_use_iterator use_end(const_iterator I) const {
243 return Uses[I - begin()].end();
246 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
247 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
248 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
249 return Uses[PIdx][UIdx];
251 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
252 return Uses[I - begin()][UIdx];
255 void use_push_back(unsigned Idx, const PartitionUse &PU) {
256 Uses[Idx].push_back(PU);
258 void use_push_back(const_iterator I, const PartitionUse &PU) {
259 Uses[I - begin()].push_back(PU);
263 /// \brief Allow iterating the dead users for this alloca.
265 /// These are instructions which will never actually use the alloca as they
266 /// are outside the allocated range. They are safe to replace with undef and
269 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
270 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
271 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
274 /// \brief Allow iterating the dead expressions referring to this alloca.
276 /// These are operands which have cannot actually be used to refer to the
277 /// alloca as they are outside its range and the user doesn't correct for
278 /// that. These mostly consist of PHI node inputs and the like which we just
279 /// need to replace with undef.
281 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
282 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
283 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
286 /// \brief MemTransferInst auxiliary data.
287 /// This struct provides some auxiliary data about memory transfer
288 /// intrinsics such as memcpy and memmove. These intrinsics can use two
289 /// different ranges within the same alloca, and provide other challenges to
290 /// correctly represent. We stash extra data to help us untangle this
291 /// after the partitioning is complete.
292 struct MemTransferOffsets {
293 /// The destination begin and end offsets when the destination is within
294 /// this alloca. If the end offset is zero the destination is not within
296 uint64_t DestBegin, DestEnd;
298 /// The source begin and end offsets when the source is within this alloca.
299 /// If the end offset is zero, the source is not within this alloca.
300 uint64_t SourceBegin, SourceEnd;
302 /// Flag for whether an alloca is splittable.
305 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
306 return MemTransferInstData.lookup(&II);
309 /// \brief Map from a PHI or select operand back to a partition.
311 /// When manipulating PHI nodes or selects, they can use more than one
312 /// partition of an alloca. We store a special mapping to allow finding the
313 /// partition referenced by each of these operands, if any.
314 iterator findPartitionForPHIOrSelectOperand(Use *U) {
315 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
316 = PHIOrSelectOpMap.find(U);
317 if (MapIt == PHIOrSelectOpMap.end())
320 return begin() + MapIt->second.first;
323 /// \brief Map from a PHI or select operand back to the specific use of
326 /// Similar to mapping these operands back to the partitions, this maps
327 /// directly to the use structure of that partition.
328 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
329 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
330 = PHIOrSelectOpMap.find(U);
331 assert(MapIt != PHIOrSelectOpMap.end());
332 return Uses[MapIt->second.first].begin() + MapIt->second.second;
335 /// \brief Compute a common type among the uses of a particular partition.
337 /// This routines walks all of the uses of a particular partition and tries
338 /// to find a common type between them. Untyped operations such as memset and
339 /// memcpy are ignored.
340 Type *getCommonType(iterator I) const;
342 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
343 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
344 void printUsers(raw_ostream &OS, const_iterator I,
345 StringRef Indent = " ") const;
346 void print(raw_ostream &OS) const;
347 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
348 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
352 template <typename DerivedT, typename RetT = void> class BuilderBase;
353 class PartitionBuilder;
354 friend class AllocaPartitioning::PartitionBuilder;
356 friend class AllocaPartitioning::UseBuilder;
358 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
359 /// \brief Handle to alloca instruction to simplify method interfaces.
363 /// \brief The instruction responsible for this alloca having no partitioning.
365 /// When an instruction (potentially) escapes the pointer to the alloca, we
366 /// store a pointer to that here and abort trying to partition the alloca.
367 /// This will be null if the alloca is partitioned successfully.
368 Instruction *PointerEscapingInstr;
370 /// \brief The partitions of the alloca.
372 /// We store a vector of the partitions over the alloca here. This vector is
373 /// sorted by increasing begin offset, and then by decreasing end offset. See
374 /// the Partition inner class for more details. Initially (during
375 /// construction) there are overlaps, but we form a disjoint sequence of
376 /// partitions while finishing construction and a fully constructed object is
377 /// expected to always have this as a disjoint space.
378 SmallVector<Partition, 8> Partitions;
380 /// \brief The uses of the partitions.
382 /// This is essentially a mapping from each partition to a list of uses of
383 /// that partition. The mapping is done with a Uses vector that has the exact
384 /// same number of entries as the partition vector. Each entry is itself
385 /// a vector of the uses.
386 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
388 /// \brief Instructions which will become dead if we rewrite the alloca.
390 /// Note that these are not separated by partition. This is because we expect
391 /// a partitioned alloca to be completely rewritten or not rewritten at all.
392 /// If rewritten, all these instructions can simply be removed and replaced
393 /// with undef as they come from outside of the allocated space.
394 SmallVector<Instruction *, 8> DeadUsers;
396 /// \brief Operands which will become dead if we rewrite the alloca.
398 /// These are operands that in their particular use can be replaced with
399 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
400 /// to PHI nodes and the like. They aren't entirely dead (there might be
401 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
402 /// want to swap this particular input for undef to simplify the use lists of
404 SmallVector<Use *, 8> DeadOperands;
406 /// \brief The underlying storage for auxiliary memcpy and memset info.
407 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
409 /// \brief A side datastructure used when building up the partitions and uses.
411 /// This mapping is only really used during the initial building of the
412 /// partitioning so that we can retain information about PHI and select nodes
414 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
416 /// \brief Auxiliary information for particular PHI or select operands.
417 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
419 /// \brief A utility routine called from the constructor.
421 /// This does what it says on the tin. It is the key of the alloca partition
422 /// splitting and merging. After it is called we have the desired disjoint
423 /// collection of partitions.
424 void splitAndMergePartitions();
428 static Value *foldSelectInst(SelectInst &SI) {
429 // If the condition being selected on is a constant or the same value is
430 // being selected between, fold the select. Yes this does (rarely) happen
432 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
433 return SI.getOperand(1+CI->isZero());
434 if (SI.getOperand(1) == SI.getOperand(2))
435 return SI.getOperand(1);
440 /// \brief Builder for the alloca partitioning.
442 /// This class builds an alloca partitioning by recursively visiting the uses
443 /// of an alloca and splitting the partitions for each load and store at each
445 class AllocaPartitioning::PartitionBuilder
446 : public PtrUseVisitor<PartitionBuilder> {
447 friend class PtrUseVisitor<PartitionBuilder>;
448 friend class InstVisitor<PartitionBuilder>;
449 typedef PtrUseVisitor<PartitionBuilder> Base;
451 const uint64_t AllocSize;
452 AllocaPartitioning &P;
454 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
457 PartitionBuilder(const DataLayout &DL, AllocaInst &AI, AllocaPartitioning &P)
458 : PtrUseVisitor<PartitionBuilder>(DL),
459 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())),
463 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
464 bool IsSplittable = false) {
465 // Completely skip uses which have a zero size or start either before or
466 // past the end of the allocation.
467 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
468 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
469 << " which has zero size or starts outside of the "
470 << AllocSize << " byte alloca:\n"
471 << " alloca: " << P.AI << "\n"
472 << " use: " << I << "\n");
476 uint64_t BeginOffset = Offset.getZExtValue();
477 uint64_t EndOffset = BeginOffset + Size;
479 // Clamp the end offset to the end of the allocation. Note that this is
480 // formulated to handle even the case where "BeginOffset + Size" overflows.
481 // This may appear superficially to be something we could ignore entirely,
482 // but that is not so! There may be widened loads or PHI-node uses where
483 // some instructions are dead but not others. We can't completely ignore
484 // them, and so have to record at least the information here.
485 assert(AllocSize >= BeginOffset); // Established above.
486 if (Size > AllocSize - BeginOffset) {
487 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
488 << " to remain within the " << AllocSize << " byte alloca:\n"
489 << " alloca: " << P.AI << "\n"
490 << " use: " << I << "\n");
491 EndOffset = AllocSize;
494 Partition New(BeginOffset, EndOffset, IsSplittable);
495 P.Partitions.push_back(New);
498 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
499 uint64_t Size, bool IsVolatile) {
500 // We allow splitting of loads and stores where the type is an integer type
501 // and cover the entire alloca. This prevents us from splitting over
503 // FIXME: In the great blue eventually, we should eagerly split all integer
504 // loads and stores, and then have a separate step that merges adjacent
505 // alloca partitions into a single partition suitable for integer widening.
506 // Or we should skip the merge step and rely on GVN and other passes to
507 // merge adjacent loads and stores that survive mem2reg.
509 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
511 insertUse(I, Offset, Size, IsSplittable);
514 void visitLoadInst(LoadInst &LI) {
515 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
516 "All simple FCA loads should have been pre-split");
519 return PI.setAborted(&LI);
521 uint64_t Size = DL.getTypeStoreSize(LI.getType());
522 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
525 void visitStoreInst(StoreInst &SI) {
526 Value *ValOp = SI.getValueOperand();
528 return PI.setEscapedAndAborted(&SI);
530 return PI.setAborted(&SI);
532 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
534 // If this memory access can be shown to *statically* extend outside the
535 // bounds of of the allocation, it's behavior is undefined, so simply
536 // ignore it. Note that this is more strict than the generic clamping
537 // behavior of insertUse. We also try to handle cases which might run the
539 // FIXME: We should instead consider the pointer to have escaped if this
540 // function is being instrumented for addressing bugs or race conditions.
541 if (Offset.isNegative() || Size > AllocSize ||
542 Offset.ugt(AllocSize - Size)) {
543 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
544 << " which extends past the end of the " << AllocSize
546 << " alloca: " << P.AI << "\n"
547 << " use: " << SI << "\n");
551 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
552 "All simple FCA stores should have been pre-split");
553 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
557 void visitMemSetInst(MemSetInst &II) {
558 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
559 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
560 if ((Length && Length->getValue() == 0) ||
561 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
562 // Zero-length mem transfer intrinsics can be ignored entirely.
566 return PI.setAborted(&II);
568 insertUse(II, Offset,
569 Length ? Length->getLimitedValue()
570 : AllocSize - Offset.getLimitedValue(),
574 void visitMemTransferInst(MemTransferInst &II) {
575 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
576 if ((Length && Length->getValue() == 0) ||
577 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
578 // Zero-length mem transfer intrinsics can be ignored entirely.
582 return PI.setAborted(&II);
584 uint64_t RawOffset = Offset.getLimitedValue();
585 uint64_t Size = Length ? Length->getLimitedValue()
586 : AllocSize - RawOffset;
588 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
590 // Only intrinsics with a constant length can be split.
591 Offsets.IsSplittable = Length;
593 if (*U == II.getRawDest()) {
594 Offsets.DestBegin = RawOffset;
595 Offsets.DestEnd = RawOffset + Size;
597 if (*U == II.getRawSource()) {
598 Offsets.SourceBegin = RawOffset;
599 Offsets.SourceEnd = RawOffset + Size;
602 // If we have set up end offsets for both the source and the destination,
603 // we have found both sides of this transfer pointing at the same alloca.
604 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
605 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
606 unsigned PrevIdx = MemTransferPartitionMap[&II];
608 // Check if the begin offsets match and this is a non-volatile transfer.
609 // In that case, we can completely elide the transfer.
610 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
611 P.Partitions[PrevIdx].kill();
615 // Otherwise we have an offset transfer within the same alloca. We can't
617 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
618 } else if (SeenBothEnds) {
619 // Handle the case where this exact use provides both ends of the
621 assert(II.getRawDest() == II.getRawSource());
623 // For non-volatile transfers this is a no-op.
624 if (!II.isVolatile())
627 // Otherwise just suppress splitting.
628 Offsets.IsSplittable = false;
632 // Insert the use now that we've fixed up the splittable nature.
633 insertUse(II, Offset, Size, Offsets.IsSplittable);
635 // Setup the mapping from intrinsic to partition of we've not seen both
636 // ends of this transfer.
638 unsigned NewIdx = P.Partitions.size() - 1;
640 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
642 "Already have intrinsic in map but haven't seen both ends");
647 // Disable SRoA for any intrinsics except for lifetime invariants.
648 // FIXME: What about debug intrinsics? This matches old behavior, but
649 // doesn't make sense.
650 void visitIntrinsicInst(IntrinsicInst &II) {
652 return PI.setAborted(&II);
654 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
655 II.getIntrinsicID() == Intrinsic::lifetime_end) {
656 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
657 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
658 Length->getLimitedValue());
659 insertUse(II, Offset, Size, true);
663 Base::visitIntrinsicInst(II);
666 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
667 // We consider any PHI or select that results in a direct load or store of
668 // the same offset to be a viable use for partitioning purposes. These uses
669 // are considered unsplittable and the size is the maximum loaded or stored
671 SmallPtrSet<Instruction *, 4> Visited;
672 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
673 Visited.insert(Root);
674 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
675 // If there are no loads or stores, the access is dead. We mark that as
676 // a size zero access.
679 Instruction *I, *UsedI;
680 llvm::tie(UsedI, I) = Uses.pop_back_val();
682 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
683 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
686 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
687 Value *Op = SI->getOperand(0);
690 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
694 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
695 if (!GEP->hasAllZeroIndices())
697 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
698 !isa<SelectInst>(I)) {
702 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
704 if (Visited.insert(cast<Instruction>(*UI)))
705 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
706 } while (!Uses.empty());
711 void visitPHINode(PHINode &PN) {
715 return PI.setAborted(&PN);
717 // See if we already have computed info on this node.
718 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
720 PHIInfo.second = true;
721 insertUse(PN, Offset, PHIInfo.first);
725 // Check for an unsafe use of the PHI node.
726 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
727 return PI.setAborted(UnsafeI);
729 insertUse(PN, Offset, PHIInfo.first);
732 void visitSelectInst(SelectInst &SI) {
735 if (Value *Result = foldSelectInst(SI)) {
737 // If the result of the constant fold will be the pointer, recurse
738 // through the select as if we had RAUW'ed it.
744 return PI.setAborted(&SI);
746 // See if we already have computed info on this node.
747 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
748 if (SelectInfo.first) {
749 SelectInfo.second = true;
750 insertUse(SI, Offset, SelectInfo.first);
754 // Check for an unsafe use of the PHI node.
755 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
756 return PI.setAborted(UnsafeI);
758 insertUse(SI, Offset, SelectInfo.first);
761 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
762 void visitInstruction(Instruction &I) {
767 /// \brief Use adder for the alloca partitioning.
769 /// This class adds the uses of an alloca to all of the partitions which they
770 /// use. For splittable partitions, this can end up doing essentially a linear
771 /// walk of the partitions, but the number of steps remains bounded by the
772 /// total result instruction size:
773 /// - The number of partitions is a result of the number unsplittable
774 /// instructions using the alloca.
775 /// - The number of users of each partition is at worst the total number of
776 /// splittable instructions using the alloca.
777 /// Thus we will produce N * M instructions in the end, where N are the number
778 /// of unsplittable uses and M are the number of splittable. This visitor does
779 /// the exact same number of updates to the partitioning.
781 /// In the more common case, this visitor will leverage the fact that the
782 /// partition space is pre-sorted, and do a logarithmic search for the
783 /// partition needed, making the total visit a classical ((N + M) * log(N))
784 /// complexity operation.
785 class AllocaPartitioning::UseBuilder : public PtrUseVisitor<UseBuilder> {
786 friend class PtrUseVisitor<UseBuilder>;
787 friend class InstVisitor<UseBuilder>;
788 typedef PtrUseVisitor<UseBuilder> Base;
790 const uint64_t AllocSize;
791 AllocaPartitioning &P;
793 /// \brief Set to de-duplicate dead instructions found in the use walk.
794 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
797 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
798 : PtrUseVisitor<UseBuilder>(TD),
799 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
803 void markAsDead(Instruction &I) {
804 if (VisitedDeadInsts.insert(&I))
805 P.DeadUsers.push_back(&I);
808 void insertUse(Instruction &User, const APInt &Offset, uint64_t Size) {
809 // If the use has a zero size or extends outside of the allocation, record
810 // it as a dead use for elimination later.
811 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize))
812 return markAsDead(User);
814 uint64_t BeginOffset = Offset.getZExtValue();
815 uint64_t EndOffset = BeginOffset + Size;
817 // Clamp the end offset to the end of the allocation. Note that this is
818 // formulated to handle even the case where "BeginOffset + Size" overflows.
819 assert(AllocSize >= BeginOffset); // Established above.
820 if (Size > AllocSize - BeginOffset)
821 EndOffset = AllocSize;
823 // NB: This only works if we have zero overlapping partitions.
824 iterator I = std::lower_bound(P.begin(), P.end(), BeginOffset);
825 if (I != P.begin() && llvm::prior(I)->EndOffset > BeginOffset)
827 iterator E = P.end();
828 bool IsSplit = llvm::next(I) != E && llvm::next(I)->BeginOffset < EndOffset;
829 for (; I != E && I->BeginOffset < EndOffset; ++I) {
830 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
831 std::min(I->EndOffset, EndOffset), U, IsSplit);
832 P.use_push_back(I, NewPU);
833 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
834 P.PHIOrSelectOpMap[U]
835 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
839 void visitBitCastInst(BitCastInst &BC) {
841 return markAsDead(BC);
843 return Base::visitBitCastInst(BC);
846 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
847 if (GEPI.use_empty())
848 return markAsDead(GEPI);
850 return Base::visitGetElementPtrInst(GEPI);
853 void visitLoadInst(LoadInst &LI) {
854 assert(IsOffsetKnown);
855 uint64_t Size = DL.getTypeStoreSize(LI.getType());
856 insertUse(LI, Offset, Size);
859 void visitStoreInst(StoreInst &SI) {
860 assert(IsOffsetKnown);
861 uint64_t Size = DL.getTypeStoreSize(SI.getOperand(0)->getType());
863 // If this memory access can be shown to *statically* extend outside the
864 // bounds of of the allocation, it's behavior is undefined, so simply
865 // ignore it. Note that this is more strict than the generic clamping
866 // behavior of insertUse.
867 if (Offset.isNegative() || Size > AllocSize ||
868 Offset.ugt(AllocSize - Size))
869 return markAsDead(SI);
871 insertUse(SI, Offset, Size);
874 void visitMemSetInst(MemSetInst &II) {
875 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
876 if ((Length && Length->getValue() == 0) ||
877 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
878 return markAsDead(II);
880 assert(IsOffsetKnown);
881 insertUse(II, Offset, Length ? Length->getLimitedValue()
882 : AllocSize - Offset.getLimitedValue());
885 void visitMemTransferInst(MemTransferInst &II) {
886 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
887 if ((Length && Length->getValue() == 0) ||
888 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
889 return markAsDead(II);
891 assert(IsOffsetKnown);
892 uint64_t Size = Length ? Length->getLimitedValue()
893 : AllocSize - Offset.getLimitedValue();
895 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
896 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
897 Offsets.DestBegin == Offsets.SourceBegin)
898 return markAsDead(II); // Skip identity transfers without side-effects.
900 insertUse(II, Offset, Size);
903 void visitIntrinsicInst(IntrinsicInst &II) {
904 assert(IsOffsetKnown);
905 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
906 II.getIntrinsicID() == Intrinsic::lifetime_end);
908 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
909 insertUse(II, Offset, std::min(Length->getLimitedValue(),
910 AllocSize - Offset.getLimitedValue()));
913 void insertPHIOrSelect(Instruction &User, const APInt &Offset) {
914 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
916 // For PHI and select operands outside the alloca, we can't nuke the entire
917 // phi or select -- the other side might still be relevant, so we special
918 // case them here and use a separate structure to track the operands
919 // themselves which should be replaced with undef.
920 if ((Offset.isNegative() && Offset.uge(Size)) ||
921 (!Offset.isNegative() && Offset.uge(AllocSize))) {
922 P.DeadOperands.push_back(U);
926 insertUse(User, Offset, Size);
929 void visitPHINode(PHINode &PN) {
931 return markAsDead(PN);
933 assert(IsOffsetKnown);
934 insertPHIOrSelect(PN, Offset);
937 void visitSelectInst(SelectInst &SI) {
939 return markAsDead(SI);
941 if (Value *Result = foldSelectInst(SI)) {
943 // If the result of the constant fold will be the pointer, recurse
944 // through the select as if we had RAUW'ed it.
947 // Otherwise the operand to the select is dead, and we can replace it
949 P.DeadOperands.push_back(U);
954 assert(IsOffsetKnown);
955 insertPHIOrSelect(SI, Offset);
958 /// \brief Unreachable, we've already visited the alloca once.
959 void visitInstruction(Instruction &I) {
960 llvm_unreachable("Unhandled instruction in use builder.");
964 void AllocaPartitioning::splitAndMergePartitions() {
965 size_t NumDeadPartitions = 0;
967 // Track the range of splittable partitions that we pass when accumulating
968 // overlapping unsplittable partitions.
969 uint64_t SplitEndOffset = 0ull;
971 Partition New(0ull, 0ull, false);
973 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
976 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
977 assert(New.BeginOffset == New.EndOffset);
980 assert(New.IsSplittable);
981 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
983 assert(New.BeginOffset != New.EndOffset);
985 // Scan the overlapping partitions.
986 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
987 // If the new partition we are forming is splittable, stop at the first
988 // unsplittable partition.
989 if (New.IsSplittable && !Partitions[j].IsSplittable)
992 // Grow the new partition to include any equally splittable range. 'j' is
993 // always equally splittable when New is splittable, but when New is not
994 // splittable, we may subsume some (or part of some) splitable partition
995 // without growing the new one.
996 if (New.IsSplittable == Partitions[j].IsSplittable) {
997 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
999 assert(!New.IsSplittable);
1000 assert(Partitions[j].IsSplittable);
1001 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1004 Partitions[j].kill();
1005 ++NumDeadPartitions;
1009 // If the new partition is splittable, chop off the end as soon as the
1010 // unsplittable subsequent partition starts and ensure we eventually cover
1011 // the splittable area.
1012 if (j != e && New.IsSplittable) {
1013 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1014 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1017 // Add the new partition if it differs from the original one and is
1018 // non-empty. We can end up with an empty partition here if it was
1019 // splittable but there is an unsplittable one that starts at the same
1021 if (New != Partitions[i]) {
1022 if (New.BeginOffset != New.EndOffset)
1023 Partitions.push_back(New);
1024 // Mark the old one for removal.
1025 Partitions[i].kill();
1026 ++NumDeadPartitions;
1029 New.BeginOffset = New.EndOffset;
1030 if (!New.IsSplittable) {
1031 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1032 if (j != e && !Partitions[j].IsSplittable)
1033 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1034 New.IsSplittable = true;
1035 // If there is a trailing splittable partition which won't be fused into
1036 // the next splittable partition go ahead and add it onto the partitions
1038 if (New.BeginOffset < New.EndOffset &&
1039 (j == e || !Partitions[j].IsSplittable ||
1040 New.EndOffset < Partitions[j].BeginOffset)) {
1041 Partitions.push_back(New);
1042 New.BeginOffset = New.EndOffset = 0ull;
1047 // Re-sort the partitions now that they have been split and merged into
1048 // disjoint set of partitions. Also remove any of the dead partitions we've
1049 // replaced in the process.
1050 std::sort(Partitions.begin(), Partitions.end());
1051 if (NumDeadPartitions) {
1052 assert(Partitions.back().isDead());
1053 assert((ptrdiff_t)NumDeadPartitions ==
1054 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1056 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1059 AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
1061 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1064 PointerEscapingInstr(0) {
1065 PartitionBuilder PB(TD, AI, *this);
1066 PartitionBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1067 if (PtrI.isEscaped() || PtrI.isAborted()) {
1068 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1069 // possibly by just storing the PtrInfo in the AllocaPartitioning.
1070 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1071 : PtrI.getAbortingInst();
1072 assert(PointerEscapingInstr && "Did not track a bad instruction");
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 // Remove any partitions from the back which are marked as dead.
1081 while (!Partitions.empty() && Partitions.back().isDead())
1082 Partitions.pop_back();
1084 if (Partitions.size() > 1) {
1085 // Intersect splittability for all partitions with equal offsets and sizes.
1086 // Then remove all but the first so that we have a sequence of non-equal but
1087 // potentially overlapping partitions.
1088 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1091 while (J != E && *I == *J) {
1092 I->IsSplittable &= J->IsSplittable;
1096 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1099 // Split splittable and merge unsplittable partitions into a disjoint set
1100 // of partitions over the used space of the allocation.
1101 splitAndMergePartitions();
1104 // Record how many partitions we end up with.
1105 NumAllocaPartitions += Partitions.size();
1106 MaxPartitionsPerAlloca = std::max<unsigned>(Partitions.size(), MaxPartitionsPerAlloca);
1108 // Now build up the user lists for each of these disjoint partitions by
1109 // re-walking the recursive users of the alloca.
1110 Uses.resize(Partitions.size());
1111 UseBuilder UB(TD, AI, *this);
1112 PtrI = UB.visitPtr(AI);
1113 assert(!PtrI.isEscaped() && "Previously analyzed pointer now escapes!");
1114 assert(!PtrI.isAborted() && "Early aborted the visit of the pointer.");
1116 unsigned NumUses = 0;
1117 #if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
1118 for (unsigned Idx = 0, Size = Uses.size(); Idx != Size; ++Idx)
1119 NumUses += Uses[Idx].size();
1121 NumAllocaPartitionUses += NumUses;
1122 MaxPartitionUsesPerAlloca = std::max<unsigned>(NumUses, MaxPartitionUsesPerAlloca);
1125 Type *AllocaPartitioning::getCommonType(iterator I) const {
1127 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1128 Use *U = UI->getUse();
1130 continue; // Skip dead uses.
1131 if (isa<IntrinsicInst>(*U->getUser()))
1133 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1137 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
1138 UserTy = LI->getType();
1139 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
1140 UserTy = SI->getValueOperand()->getType();
1142 return 0; // Bail if we have weird uses.
1144 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1145 // If the type is larger than the partition, skip it. We only encounter
1146 // this for split integer operations where we want to use the type of the
1147 // entity causing the split.
1148 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1151 // If we have found an integer type use covering the alloca, use that
1152 // regardless of the other types, as integers are often used for a "bucket
1157 if (Ty && Ty != UserTy)
1165 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1167 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1168 StringRef Indent) const {
1169 OS << Indent << "partition #" << (I - begin())
1170 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1171 << (I->IsSplittable ? " (splittable)" : "")
1172 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1176 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1177 StringRef Indent) const {
1178 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1180 continue; // Skip dead uses.
1181 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1182 << "used by: " << *UI->getUse()->getUser() << "\n";
1183 if (MemTransferInst *II =
1184 dyn_cast<MemTransferInst>(UI->getUse()->getUser())) {
1185 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1187 if (!MTO.IsSplittable)
1188 IsDest = UI->BeginOffset == MTO.DestBegin;
1190 IsDest = MTO.DestBegin != 0u;
1191 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1192 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1193 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1198 void AllocaPartitioning::print(raw_ostream &OS) const {
1199 if (PointerEscapingInstr) {
1200 OS << "No partitioning for alloca: " << AI << "\n"
1201 << " A pointer to this alloca escaped by:\n"
1202 << " " << *PointerEscapingInstr << "\n";
1206 OS << "Partitioning of alloca: " << AI << "\n";
1207 for (const_iterator I = begin(), E = end(); I != E; ++I) {
1213 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1214 void AllocaPartitioning::dump() const { print(dbgs()); }
1216 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1220 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1222 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1223 /// the loads and stores of an alloca instruction, as well as updating its
1224 /// debug information. This is used when a domtree is unavailable and thus
1225 /// mem2reg in its full form can't be used to handle promotion of allocas to
1227 class AllocaPromoter : public LoadAndStorePromoter {
1231 SmallVector<DbgDeclareInst *, 4> DDIs;
1232 SmallVector<DbgValueInst *, 4> DVIs;
1235 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1236 AllocaInst &AI, DIBuilder &DIB)
1237 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1239 void run(const SmallVectorImpl<Instruction*> &Insts) {
1240 // Remember which alloca we're promoting (for isInstInList).
1241 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1242 for (Value::use_iterator UI = DebugNode->use_begin(),
1243 UE = DebugNode->use_end();
1245 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1246 DDIs.push_back(DDI);
1247 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1248 DVIs.push_back(DVI);
1251 LoadAndStorePromoter::run(Insts);
1252 AI.eraseFromParent();
1253 while (!DDIs.empty())
1254 DDIs.pop_back_val()->eraseFromParent();
1255 while (!DVIs.empty())
1256 DVIs.pop_back_val()->eraseFromParent();
1259 virtual bool isInstInList(Instruction *I,
1260 const SmallVectorImpl<Instruction*> &Insts) const {
1261 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1262 return LI->getOperand(0) == &AI;
1263 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1266 virtual void updateDebugInfo(Instruction *Inst) const {
1267 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1268 E = DDIs.end(); I != E; ++I) {
1269 DbgDeclareInst *DDI = *I;
1270 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1271 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1272 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1273 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1275 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1276 E = DVIs.end(); I != E; ++I) {
1277 DbgValueInst *DVI = *I;
1279 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1280 // If an argument is zero extended then use argument directly. The ZExt
1281 // may be zapped by an optimization pass in future.
1282 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1283 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1284 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1285 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1287 Arg = SI->getOperand(0);
1288 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1289 Arg = LI->getOperand(0);
1293 Instruction *DbgVal =
1294 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1296 DbgVal->setDebugLoc(DVI->getDebugLoc());
1300 } // end anon namespace
1304 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1306 /// This pass takes allocations which can be completely analyzed (that is, they
1307 /// don't escape) and tries to turn them into scalar SSA values. There are
1308 /// a few steps to this process.
1310 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1311 /// are used to try to split them into smaller allocations, ideally of
1312 /// a single scalar data type. It will split up memcpy and memset accesses
1313 /// as necessary and try to isolate individual scalar accesses.
1314 /// 2) It will transform accesses into forms which are suitable for SSA value
1315 /// promotion. This can be replacing a memset with a scalar store of an
1316 /// integer value, or it can involve speculating operations on a PHI or
1317 /// select to be a PHI or select of the results.
1318 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1319 /// onto insert and extract operations on a vector value, and convert them to
1320 /// this form. By doing so, it will enable promotion of vector aggregates to
1321 /// SSA vector values.
1322 class SROA : public FunctionPass {
1323 const bool RequiresDomTree;
1326 const DataLayout *TD;
1329 /// \brief Worklist of alloca instructions to simplify.
1331 /// Each alloca in the function is added to this. Each new alloca formed gets
1332 /// added to it as well to recursively simplify unless that alloca can be
1333 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1334 /// the one being actively rewritten, we add it back onto the list if not
1335 /// already present to ensure it is re-visited.
1336 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1338 /// \brief A collection of instructions to delete.
1339 /// We try to batch deletions to simplify code and make things a bit more
1341 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
1343 /// \brief Post-promotion worklist.
1345 /// Sometimes we discover an alloca which has a high probability of becoming
1346 /// viable for SROA after a round of promotion takes place. In those cases,
1347 /// the alloca is enqueued here for re-processing.
1349 /// Note that we have to be very careful to clear allocas out of this list in
1350 /// the event they are deleted.
1351 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1353 /// \brief A collection of alloca instructions we can directly promote.
1354 std::vector<AllocaInst *> PromotableAllocas;
1357 SROA(bool RequiresDomTree = true)
1358 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1359 C(0), TD(0), DT(0) {
1360 initializeSROAPass(*PassRegistry::getPassRegistry());
1362 bool runOnFunction(Function &F);
1363 void getAnalysisUsage(AnalysisUsage &AU) const;
1365 const char *getPassName() const { return "SROA"; }
1369 friend class PHIOrSelectSpeculator;
1370 friend class AllocaPartitionRewriter;
1371 friend class AllocaPartitionVectorRewriter;
1373 bool rewriteAllocaPartition(AllocaInst &AI,
1374 AllocaPartitioning &P,
1375 AllocaPartitioning::iterator PI);
1376 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1377 bool runOnAlloca(AllocaInst &AI);
1378 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
1379 bool promoteAllocas(Function &F);
1385 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1386 return new SROA(RequiresDomTree);
1389 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1391 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1392 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1396 /// \brief Visitor to speculate PHIs and Selects where possible.
1397 class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1398 // Befriend the base class so it can delegate to private visit methods.
1399 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1401 const DataLayout &TD;
1402 AllocaPartitioning &P;
1406 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
1407 : TD(TD), P(P), Pass(Pass) {}
1409 /// \brief Visit the users of an alloca partition and rewrite them.
1410 void visitUsers(AllocaPartitioning::const_iterator PI) {
1411 // Note that we need to use an index here as the underlying vector of uses
1412 // may be grown during speculation. However, we never need to re-visit the
1413 // new uses, and so we can use the initial size bound.
1414 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1415 const PartitionUse &PU = P.getUse(PI, Idx);
1417 continue; // Skip dead use.
1419 visit(cast<Instruction>(PU.getUse()->getUser()));
1424 // By default, skip this instruction.
1425 void visitInstruction(Instruction &I) {}
1427 /// PHI instructions that use an alloca and are subsequently loaded can be
1428 /// rewritten to load both input pointers in the pred blocks and then PHI the
1429 /// results, allowing the load of the alloca to be promoted.
1431 /// %P2 = phi [i32* %Alloca, i32* %Other]
1432 /// %V = load i32* %P2
1434 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1436 /// %V2 = load i32* %Other
1438 /// %V = phi [i32 %V1, i32 %V2]
1440 /// We can do this to a select if its only uses are loads and if the operands
1441 /// to the select can be loaded unconditionally.
1443 /// FIXME: This should be hoisted into a generic utility, likely in
1444 /// Transforms/Util/Local.h
1445 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1446 // For now, we can only do this promotion if the load is in the same block
1447 // as the PHI, and if there are no stores between the phi and load.
1448 // TODO: Allow recursive phi users.
1449 // TODO: Allow stores.
1450 BasicBlock *BB = PN.getParent();
1451 unsigned MaxAlign = 0;
1452 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1454 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1455 if (LI == 0 || !LI->isSimple()) return false;
1457 // For now we only allow loads in the same block as the PHI. This is
1458 // a common case that happens when instcombine merges two loads through
1460 if (LI->getParent() != BB) return false;
1462 // Ensure that there are no instructions between the PHI and the load that
1464 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1465 if (BBI->mayWriteToMemory())
1468 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1469 Loads.push_back(LI);
1472 // We can only transform this if it is safe to push the loads into the
1473 // predecessor blocks. The only thing to watch out for is that we can't put
1474 // a possibly trapping load in the predecessor if it is a critical edge.
1475 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1476 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1477 Value *InVal = PN.getIncomingValue(Idx);
1479 // If the value is produced by the terminator of the predecessor (an
1480 // invoke) or it has side-effects, there is no valid place to put a load
1481 // in the predecessor.
1482 if (TI == InVal || TI->mayHaveSideEffects())
1485 // If the predecessor has a single successor, then the edge isn't
1487 if (TI->getNumSuccessors() == 1)
1490 // If this pointer is always safe to load, or if we can prove that there
1491 // is already a load in the block, then we can move the load to the pred
1493 if (InVal->isDereferenceablePointer() ||
1494 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1503 void visitPHINode(PHINode &PN) {
1504 DEBUG(dbgs() << " original: " << PN << "\n");
1506 SmallVector<LoadInst *, 4> Loads;
1507 if (!isSafePHIToSpeculate(PN, Loads))
1510 assert(!Loads.empty());
1512 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1513 IRBuilder<> PHIBuilder(&PN);
1514 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1515 PN.getName() + ".sroa.speculated");
1517 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1518 // matter which one we get and if any differ.
1519 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1520 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1521 unsigned Align = SomeLoad->getAlignment();
1523 // Rewrite all loads of the PN to use the new PHI.
1525 LoadInst *LI = Loads.pop_back_val();
1526 LI->replaceAllUsesWith(NewPN);
1527 Pass.DeadInsts.insert(LI);
1528 } while (!Loads.empty());
1530 // Inject loads into all of the pred blocks.
1531 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1532 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1533 TerminatorInst *TI = Pred->getTerminator();
1534 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1535 Value *InVal = PN.getIncomingValue(Idx);
1536 IRBuilder<> PredBuilder(TI);
1539 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1541 ++NumLoadsSpeculated;
1542 Load->setAlignment(Align);
1544 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1545 NewPN->addIncoming(Load, Pred);
1547 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1549 // No uses to rewrite.
1552 // Try to lookup and rewrite any partition uses corresponding to this phi
1554 AllocaPartitioning::iterator PI
1555 = P.findPartitionForPHIOrSelectOperand(InUse);
1559 // Replace the Use in the PartitionUse for this operand with the Use
1561 AllocaPartitioning::use_iterator UI
1562 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1563 assert(isa<PHINode>(*UI->getUse()->getUser()));
1564 UI->setUse(&Load->getOperandUse(Load->getPointerOperandIndex()));
1566 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1569 /// Select instructions that use an alloca and are subsequently loaded can be
1570 /// rewritten to load both input pointers and then select between the result,
1571 /// allowing the load of the alloca to be promoted.
1573 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1574 /// %V = load i32* %P2
1576 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1577 /// %V2 = load i32* %Other
1578 /// %V = select i1 %cond, i32 %V1, i32 %V2
1580 /// We can do this to a select if its only uses are loads and if the operand
1581 /// to the select can be loaded unconditionally.
1582 bool isSafeSelectToSpeculate(SelectInst &SI,
1583 SmallVectorImpl<LoadInst *> &Loads) {
1584 Value *TValue = SI.getTrueValue();
1585 Value *FValue = SI.getFalseValue();
1586 bool TDerefable = TValue->isDereferenceablePointer();
1587 bool FDerefable = FValue->isDereferenceablePointer();
1589 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1591 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1592 if (LI == 0 || !LI->isSimple()) return false;
1594 // Both operands to the select need to be dereferencable, either
1595 // absolutely (e.g. allocas) or at this point because we can see other
1597 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1598 LI->getAlignment(), &TD))
1600 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1601 LI->getAlignment(), &TD))
1603 Loads.push_back(LI);
1609 void visitSelectInst(SelectInst &SI) {
1610 DEBUG(dbgs() << " original: " << SI << "\n");
1612 // If the select isn't safe to speculate, just use simple logic to emit it.
1613 SmallVector<LoadInst *, 4> Loads;
1614 if (!isSafeSelectToSpeculate(SI, Loads))
1617 IRBuilder<> IRB(&SI);
1618 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1619 AllocaPartitioning::iterator PIs[2];
1620 PartitionUse PUs[2];
1621 for (unsigned i = 0, e = 2; i != e; ++i) {
1622 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1623 if (PIs[i] != P.end()) {
1624 // If the pointer is within the partitioning, remove the select from
1625 // its uses. We'll add in the new loads below.
1626 AllocaPartitioning::use_iterator UI
1627 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1629 // Clear out the use here so that the offsets into the use list remain
1630 // stable but this use is ignored when rewriting.
1635 Value *TV = SI.getTrueValue();
1636 Value *FV = SI.getFalseValue();
1637 // Replace the loads of the select with a select of two loads.
1638 while (!Loads.empty()) {
1639 LoadInst *LI = Loads.pop_back_val();
1641 IRB.SetInsertPoint(LI);
1643 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1645 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1646 NumLoadsSpeculated += 2;
1648 // Transfer alignment and TBAA info if present.
1649 TL->setAlignment(LI->getAlignment());
1650 FL->setAlignment(LI->getAlignment());
1651 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1652 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1653 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1656 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1657 LI->getName() + ".sroa.speculated");
1659 LoadInst *Loads[2] = { TL, FL };
1660 for (unsigned i = 0, e = 2; i != e; ++i) {
1661 if (PIs[i] != P.end()) {
1662 Use *LoadUse = &Loads[i]->getOperandUse(0);
1663 assert(PUs[i].getUse()->get() == LoadUse->get());
1664 PUs[i].setUse(LoadUse);
1665 P.use_push_back(PIs[i], PUs[i]);
1669 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1670 LI->replaceAllUsesWith(V);
1671 Pass.DeadInsts.insert(LI);
1677 /// \brief Build a GEP out of a base pointer and indices.
1679 /// This will return the BasePtr if that is valid, or build a new GEP
1680 /// instruction using the IRBuilder if GEP-ing is needed.
1681 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1682 SmallVectorImpl<Value *> &Indices,
1683 const Twine &Prefix) {
1684 if (Indices.empty())
1687 // A single zero index is a no-op, so check for this and avoid building a GEP
1689 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1692 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1695 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1696 /// TargetTy without changing the offset of the pointer.
1698 /// This routine assumes we've already established a properly offset GEP with
1699 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1700 /// zero-indices down through type layers until we find one the same as
1701 /// TargetTy. If we can't find one with the same type, we at least try to use
1702 /// one with the same size. If none of that works, we just produce the GEP as
1703 /// indicated by Indices to have the correct offset.
1704 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
1705 Value *BasePtr, Type *Ty, Type *TargetTy,
1706 SmallVectorImpl<Value *> &Indices,
1707 const Twine &Prefix) {
1709 return buildGEP(IRB, BasePtr, Indices, Prefix);
1711 // See if we can descend into a struct and locate a field with the correct
1713 unsigned NumLayers = 0;
1714 Type *ElementTy = Ty;
1716 if (ElementTy->isPointerTy())
1718 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1719 ElementTy = SeqTy->getElementType();
1720 // Note that we use the default address space as this index is over an
1721 // array or a vector, not a pointer.
1722 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
1723 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1724 if (STy->element_begin() == STy->element_end())
1725 break; // Nothing left to descend into.
1726 ElementTy = *STy->element_begin();
1727 Indices.push_back(IRB.getInt32(0));
1732 } while (ElementTy != TargetTy);
1733 if (ElementTy != TargetTy)
1734 Indices.erase(Indices.end() - NumLayers, Indices.end());
1736 return buildGEP(IRB, BasePtr, Indices, Prefix);
1739 /// \brief Recursively compute indices for a natural GEP.
1741 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1742 /// element types adding appropriate indices for the GEP.
1743 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
1744 Value *Ptr, Type *Ty, APInt &Offset,
1746 SmallVectorImpl<Value *> &Indices,
1747 const Twine &Prefix) {
1749 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1751 // We can't recurse through pointer types.
1752 if (Ty->isPointerTy())
1755 // We try to analyze GEPs over vectors here, but note that these GEPs are
1756 // extremely poorly defined currently. The long-term goal is to remove GEPing
1757 // over a vector from the IR completely.
1758 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1759 unsigned ElementSizeInBits = TD.getTypeSizeInBits(VecTy->getScalarType());
1760 if (ElementSizeInBits % 8)
1761 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1762 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1763 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1764 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1766 Offset -= NumSkippedElements * ElementSize;
1767 Indices.push_back(IRB.getInt(NumSkippedElements));
1768 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1769 Offset, TargetTy, Indices, Prefix);
1772 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1773 Type *ElementTy = ArrTy->getElementType();
1774 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1775 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1776 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1779 Offset -= NumSkippedElements * ElementSize;
1780 Indices.push_back(IRB.getInt(NumSkippedElements));
1781 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1785 StructType *STy = dyn_cast<StructType>(Ty);
1789 const StructLayout *SL = TD.getStructLayout(STy);
1790 uint64_t StructOffset = Offset.getZExtValue();
1791 if (StructOffset >= SL->getSizeInBytes())
1793 unsigned Index = SL->getElementContainingOffset(StructOffset);
1794 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1795 Type *ElementTy = STy->getElementType(Index);
1796 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1797 return 0; // The offset points into alignment padding.
1799 Indices.push_back(IRB.getInt32(Index));
1800 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1804 /// \brief Get a natural GEP from a base pointer to a particular offset and
1805 /// resulting in a particular type.
1807 /// The goal is to produce a "natural" looking GEP that works with the existing
1808 /// composite types to arrive at the appropriate offset and element type for
1809 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1810 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1811 /// Indices, and setting Ty to the result subtype.
1813 /// If no natural GEP can be constructed, this function returns null.
1814 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
1815 Value *Ptr, APInt Offset, Type *TargetTy,
1816 SmallVectorImpl<Value *> &Indices,
1817 const Twine &Prefix) {
1818 PointerType *Ty = cast<PointerType>(Ptr->getType());
1820 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1822 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1825 Type *ElementTy = Ty->getElementType();
1826 if (!ElementTy->isSized())
1827 return 0; // We can't GEP through an unsized element.
1828 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1829 if (ElementSize == 0)
1830 return 0; // Zero-length arrays can't help us build a natural GEP.
1831 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1833 Offset -= NumSkippedElements * ElementSize;
1834 Indices.push_back(IRB.getInt(NumSkippedElements));
1835 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1839 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1840 /// resulting pointer has PointerTy.
1842 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1843 /// and produces the pointer type desired. Where it cannot, it will try to use
1844 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1845 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1846 /// bitcast to the type.
1848 /// The strategy for finding the more natural GEPs is to peel off layers of the
1849 /// pointer, walking back through bit casts and GEPs, searching for a base
1850 /// pointer from which we can compute a natural GEP with the desired
1851 /// properties. The algorithm tries to fold as many constant indices into
1852 /// a single GEP as possible, thus making each GEP more independent of the
1853 /// surrounding code.
1854 static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
1855 Value *Ptr, APInt Offset, Type *PointerTy,
1856 const Twine &Prefix) {
1857 // Even though we don't look through PHI nodes, we could be called on an
1858 // instruction in an unreachable block, which may be on a cycle.
1859 SmallPtrSet<Value *, 4> Visited;
1860 Visited.insert(Ptr);
1861 SmallVector<Value *, 4> Indices;
1863 // We may end up computing an offset pointer that has the wrong type. If we
1864 // never are able to compute one directly that has the correct type, we'll
1865 // fall back to it, so keep it around here.
1866 Value *OffsetPtr = 0;
1868 // Remember any i8 pointer we come across to re-use if we need to do a raw
1871 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1873 Type *TargetTy = PointerTy->getPointerElementType();
1876 // First fold any existing GEPs into the offset.
1877 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1878 APInt GEPOffset(Offset.getBitWidth(), 0);
1879 if (!GEP->accumulateConstantOffset(TD, GEPOffset))
1881 Offset += GEPOffset;
1882 Ptr = GEP->getPointerOperand();
1883 if (!Visited.insert(Ptr))
1887 // See if we can perform a natural GEP here.
1889 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1891 if (P->getType() == PointerTy) {
1892 // Zap any offset pointer that we ended up computing in previous rounds.
1893 if (OffsetPtr && OffsetPtr->use_empty())
1894 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1895 I->eraseFromParent();
1903 // Stash this pointer if we've found an i8*.
1904 if (Ptr->getType()->isIntegerTy(8)) {
1906 Int8PtrOffset = Offset;
1909 // Peel off a layer of the pointer and update the offset appropriately.
1910 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1911 Ptr = cast<Operator>(Ptr)->getOperand(0);
1912 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1913 if (GA->mayBeOverridden())
1915 Ptr = GA->getAliasee();
1919 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1920 } while (Visited.insert(Ptr));
1924 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1925 Prefix + ".raw_cast");
1926 Int8PtrOffset = Offset;
1929 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1930 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1931 Prefix + ".raw_idx");
1935 // On the off chance we were targeting i8*, guard the bitcast here.
1936 if (Ptr->getType() != PointerTy)
1937 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1942 /// \brief Test whether we can convert a value from the old to the new type.
1944 /// This predicate should be used to guard calls to convertValue in order to
1945 /// ensure that we only try to convert viable values. The strategy is that we
1946 /// will peel off single element struct and array wrappings to get to an
1947 /// underlying value, and convert that value.
1948 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1951 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1952 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1953 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1955 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1957 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1960 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1961 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1963 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1971 /// \brief Generic routine to convert an SSA value to a value of a different
1974 /// This will try various different casting techniques, such as bitcasts,
1975 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1976 /// two types for viability with this routine.
1977 static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
1979 assert(canConvertValue(DL, V->getType(), Ty) &&
1980 "Value not convertable to type");
1981 if (V->getType() == Ty)
1983 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
1984 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
1985 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1986 return IRB.CreateZExt(V, NewITy);
1987 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1988 return IRB.CreateIntToPtr(V, Ty);
1989 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1990 return IRB.CreatePtrToInt(V, Ty);
1992 return IRB.CreateBitCast(V, Ty);
1995 /// \brief Test whether the given alloca partition can be promoted to a vector.
1997 /// This is a quick test to check whether we can rewrite a particular alloca
1998 /// partition (and its newly formed alloca) into a vector alloca with only
1999 /// whole-vector loads and stores such that it could be promoted to a vector
2000 /// SSA value. We only can ensure this for a limited set of operations, and we
2001 /// don't want to do the rewrites unless we are confident that the result will
2002 /// be promotable, so we have an early test here.
2003 static bool isVectorPromotionViable(const DataLayout &TD,
2005 AllocaPartitioning &P,
2006 uint64_t PartitionBeginOffset,
2007 uint64_t PartitionEndOffset,
2008 AllocaPartitioning::const_use_iterator I,
2009 AllocaPartitioning::const_use_iterator E) {
2010 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2014 uint64_t ElementSize = TD.getTypeSizeInBits(Ty->getScalarType());
2016 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2017 // that aren't byte sized.
2018 if (ElementSize % 8)
2020 assert((TD.getTypeSizeInBits(Ty) % 8) == 0 &&
2021 "vector size not a multiple of element size?");
2024 for (; I != E; ++I) {
2025 Use *U = I->getUse();
2027 continue; // Skip dead use.
2029 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2030 uint64_t BeginIndex = BeginOffset / ElementSize;
2031 if (BeginIndex * ElementSize != BeginOffset ||
2032 BeginIndex >= Ty->getNumElements())
2034 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2035 uint64_t EndIndex = EndOffset / ElementSize;
2036 if (EndIndex * ElementSize != EndOffset ||
2037 EndIndex > Ty->getNumElements())
2040 assert(EndIndex > BeginIndex && "Empty vector!");
2041 uint64_t NumElements = EndIndex - BeginIndex;
2043 = (NumElements == 1) ? Ty->getElementType()
2044 : VectorType::get(Ty->getElementType(), NumElements);
2046 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2047 if (MI->isVolatile())
2049 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U->getUser())) {
2050 const AllocaPartitioning::MemTransferOffsets &MTO
2051 = P.getMemTransferOffsets(*MTI);
2052 if (!MTO.IsSplittable)
2055 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
2056 // Disable vector promotion when there are loads or stores of an FCA.
2058 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2059 if (LI->isVolatile())
2061 if (!canConvertValue(TD, PartitionTy, LI->getType()))
2063 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2064 if (SI->isVolatile())
2066 if (!canConvertValue(TD, SI->getValueOperand()->getType(), PartitionTy))
2075 /// \brief Test whether the given alloca partition's integer operations can be
2076 /// widened to promotable ones.
2078 /// This is a quick test to check whether we can rewrite the integer loads and
2079 /// stores to a particular alloca into wider loads and stores and be able to
2080 /// promote the resulting alloca.
2081 static bool isIntegerWideningViable(const DataLayout &TD,
2083 uint64_t AllocBeginOffset,
2084 AllocaPartitioning &P,
2085 AllocaPartitioning::const_use_iterator I,
2086 AllocaPartitioning::const_use_iterator E) {
2087 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
2088 // Don't create integer types larger than the maximum bitwidth.
2089 if (SizeInBits > IntegerType::MAX_INT_BITS)
2092 // Don't try to handle allocas with bit-padding.
2093 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
2096 // We need to ensure that an integer type with the appropriate bitwidth can
2097 // be converted to the alloca type, whatever that is. We don't want to force
2098 // the alloca itself to have an integer type if there is a more suitable one.
2099 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2100 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2101 !canConvertValue(TD, IntTy, AllocaTy))
2104 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2106 // Check the uses to ensure the uses are (likely) promotable integer uses.
2107 // Also ensure that the alloca has a covering load or store. We don't want
2108 // to widen the integer operations only to fail to promote due to some other
2109 // unsplittable entry (which we may make splittable later).
2110 bool WholeAllocaOp = false;
2111 for (; I != E; ++I) {
2112 Use *U = I->getUse();
2114 continue; // Skip dead use.
2116 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2117 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2119 // We can't reasonably handle cases where the load or store extends past
2120 // the end of the aloca's type and into its padding.
2124 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2125 if (LI->isVolatile())
2127 if (RelBegin == 0 && RelEnd == Size)
2128 WholeAllocaOp = true;
2129 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2130 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
2134 // Non-integer loads need to be convertible from the alloca type so that
2135 // they are promotable.
2136 if (RelBegin != 0 || RelEnd != Size ||
2137 !canConvertValue(TD, AllocaTy, LI->getType()))
2139 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2140 Type *ValueTy = SI->getValueOperand()->getType();
2141 if (SI->isVolatile())
2143 if (RelBegin == 0 && RelEnd == Size)
2144 WholeAllocaOp = true;
2145 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2146 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
2150 // Non-integer stores need to be convertible to the alloca type so that
2151 // they are promotable.
2152 if (RelBegin != 0 || RelEnd != Size ||
2153 !canConvertValue(TD, ValueTy, AllocaTy))
2155 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2156 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2158 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U->getUser())) {
2159 const AllocaPartitioning::MemTransferOffsets &MTO
2160 = P.getMemTransferOffsets(*MTI);
2161 if (!MTO.IsSplittable)
2164 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2165 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2166 II->getIntrinsicID() != Intrinsic::lifetime_end)
2172 return WholeAllocaOp;
2175 static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2176 IntegerType *Ty, uint64_t Offset,
2177 const Twine &Name) {
2178 DEBUG(dbgs() << " start: " << *V << "\n");
2179 IntegerType *IntTy = cast<IntegerType>(V->getType());
2180 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2181 "Element extends past full value");
2182 uint64_t ShAmt = 8*Offset;
2183 if (DL.isBigEndian())
2184 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2186 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2187 DEBUG(dbgs() << " shifted: " << *V << "\n");
2189 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2190 "Cannot extract to a larger integer!");
2192 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2193 DEBUG(dbgs() << " trunced: " << *V << "\n");
2198 static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2199 Value *V, uint64_t Offset, const Twine &Name) {
2200 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2201 IntegerType *Ty = cast<IntegerType>(V->getType());
2202 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2203 "Cannot insert a larger integer!");
2204 DEBUG(dbgs() << " start: " << *V << "\n");
2206 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2207 DEBUG(dbgs() << " extended: " << *V << "\n");
2209 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2210 "Element store outside of alloca store");
2211 uint64_t ShAmt = 8*Offset;
2212 if (DL.isBigEndian())
2213 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2215 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2216 DEBUG(dbgs() << " shifted: " << *V << "\n");
2219 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2220 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2221 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2222 DEBUG(dbgs() << " masked: " << *Old << "\n");
2223 V = IRB.CreateOr(Old, V, Name + ".insert");
2224 DEBUG(dbgs() << " inserted: " << *V << "\n");
2229 static Value *extractVector(IRBuilder<> &IRB, Value *V,
2230 unsigned BeginIndex, unsigned EndIndex,
2231 const Twine &Name) {
2232 VectorType *VecTy = cast<VectorType>(V->getType());
2233 unsigned NumElements = EndIndex - BeginIndex;
2234 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2236 if (NumElements == VecTy->getNumElements())
2239 if (NumElements == 1) {
2240 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2242 DEBUG(dbgs() << " extract: " << *V << "\n");
2246 SmallVector<Constant*, 8> Mask;
2247 Mask.reserve(NumElements);
2248 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2249 Mask.push_back(IRB.getInt32(i));
2250 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2251 ConstantVector::get(Mask),
2253 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2257 static Value *insertVector(IRBuilder<> &IRB, Value *Old, Value *V,
2258 unsigned BeginIndex, const Twine &Name) {
2259 VectorType *VecTy = cast<VectorType>(Old->getType());
2260 assert(VecTy && "Can only insert a vector into a vector");
2262 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2264 // Single element to insert.
2265 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2267 DEBUG(dbgs() << " insert: " << *V << "\n");
2271 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2272 "Too many elements!");
2273 if (Ty->getNumElements() == VecTy->getNumElements()) {
2274 assert(V->getType() == VecTy && "Vector type mismatch");
2277 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2279 // When inserting a smaller vector into the larger to store, we first
2280 // use a shuffle vector to widen it with undef elements, and then
2281 // a second shuffle vector to select between the loaded vector and the
2283 SmallVector<Constant*, 8> Mask;
2284 Mask.reserve(VecTy->getNumElements());
2285 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2286 if (i >= BeginIndex && i < EndIndex)
2287 Mask.push_back(IRB.getInt32(i - BeginIndex));
2289 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2290 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2291 ConstantVector::get(Mask),
2293 DEBUG(dbgs() << " shuffle1: " << *V << "\n");
2296 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2297 if (i >= BeginIndex && i < EndIndex)
2298 Mask.push_back(IRB.getInt32(i));
2300 Mask.push_back(IRB.getInt32(i + VecTy->getNumElements()));
2301 V = IRB.CreateShuffleVector(V, Old, ConstantVector::get(Mask),
2303 DEBUG(dbgs() << " shuffle2: " << *V << "\n");
2308 /// \brief Visitor to rewrite instructions using a partition of an alloca to
2309 /// use a new alloca.
2311 /// Also implements the rewriting to vector-based accesses when the partition
2312 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2314 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2316 // Befriend the base class so it can delegate to private visit methods.
2317 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2319 const DataLayout &TD;
2320 AllocaPartitioning &P;
2322 AllocaInst &OldAI, &NewAI;
2323 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2326 // If we are rewriting an alloca partition which can be written as pure
2327 // vector operations, we stash extra information here. When VecTy is
2328 // non-null, we have some strict guarantees about the rewritten alloca:
2329 // - The new alloca is exactly the size of the vector type here.
2330 // - The accesses all either map to the entire vector or to a single
2332 // - The set of accessing instructions is only one of those handled above
2333 // in isVectorPromotionViable. Generally these are the same access kinds
2334 // which are promotable via mem2reg.
2337 uint64_t ElementSize;
2339 // This is a convenience and flag variable that will be null unless the new
2340 // alloca's integer operations should be widened to this integer type due to
2341 // passing isIntegerWideningViable above. If it is non-null, the desired
2342 // integer type will be stored here for easy access during rewriting.
2345 // The offset of the partition user currently being rewritten.
2346 uint64_t BeginOffset, EndOffset;
2349 Instruction *OldPtr;
2351 // The name prefix to use when rewriting instructions for this alloca.
2352 std::string NamePrefix;
2355 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
2356 AllocaPartitioning::iterator PI,
2357 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2358 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2359 : TD(TD), P(P), Pass(Pass),
2360 OldAI(OldAI), NewAI(NewAI),
2361 NewAllocaBeginOffset(NewBeginOffset),
2362 NewAllocaEndOffset(NewEndOffset),
2363 NewAllocaTy(NewAI.getAllocatedType()),
2364 VecTy(), ElementTy(), ElementSize(), IntTy(),
2365 BeginOffset(), EndOffset(), IsSplit(), OldUse(), OldPtr() {
2368 /// \brief Visit the users of the alloca partition and rewrite them.
2369 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2370 AllocaPartitioning::const_use_iterator E) {
2371 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2372 NewAllocaBeginOffset, NewAllocaEndOffset,
2375 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2376 ElementTy = VecTy->getElementType();
2377 assert((TD.getTypeSizeInBits(VecTy->getScalarType()) % 8) == 0 &&
2378 "Only multiple-of-8 sized vector elements are viable");
2379 ElementSize = TD.getTypeSizeInBits(VecTy->getScalarType()) / 8;
2380 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2381 NewAllocaBeginOffset, P, I, E)) {
2382 IntTy = Type::getIntNTy(NewAI.getContext(),
2383 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
2385 bool CanSROA = true;
2386 for (; I != E; ++I) {
2388 continue; // Skip dead uses.
2389 BeginOffset = I->BeginOffset;
2390 EndOffset = I->EndOffset;
2391 IsSplit = I->isSplit();
2392 OldUse = I->getUse();
2393 OldPtr = cast<Instruction>(OldUse->get());
2394 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
2395 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2411 // Every instruction which can end up as a user must have a rewrite rule.
2412 bool visitInstruction(Instruction &I) {
2413 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2414 llvm_unreachable("No rewrite rule for this instruction!");
2417 Twine getName(const Twine &Suffix) {
2418 return NamePrefix + Suffix;
2421 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2422 assert(BeginOffset >= NewAllocaBeginOffset);
2423 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
2424 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2427 /// \brief Compute suitable alignment to access an offset into the new alloca.
2428 unsigned getOffsetAlign(uint64_t Offset) {
2429 unsigned NewAIAlign = NewAI.getAlignment();
2431 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2432 return MinAlign(NewAIAlign, Offset);
2435 /// \brief Compute suitable alignment to access this partition of the new
2437 unsigned getPartitionAlign() {
2438 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
2441 /// \brief Compute suitable alignment to access a type at an offset of the
2444 /// \returns zero if the type's ABI alignment is a suitable alignment,
2445 /// otherwise returns the maximal suitable alignment.
2446 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2447 unsigned Align = getOffsetAlign(Offset);
2448 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2451 /// \brief Compute suitable alignment to access a type at the beginning of
2452 /// this partition of the new alloca.
2454 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2455 unsigned getPartitionTypeAlign(Type *Ty) {
2456 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
2459 unsigned getIndex(uint64_t Offset) {
2460 assert(VecTy && "Can only call getIndex when rewriting a vector");
2461 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2462 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2463 uint32_t Index = RelOffset / ElementSize;
2464 assert(Index * ElementSize == RelOffset);
2468 void deleteIfTriviallyDead(Value *V) {
2469 Instruction *I = cast<Instruction>(V);
2470 if (isInstructionTriviallyDead(I))
2471 Pass.DeadInsts.insert(I);
2474 Value *rewriteVectorizedLoadInst(IRBuilder<> &IRB) {
2475 unsigned BeginIndex = getIndex(BeginOffset);
2476 unsigned EndIndex = getIndex(EndOffset);
2477 assert(EndIndex > BeginIndex && "Empty vector!");
2479 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2481 return extractVector(IRB, V, BeginIndex, EndIndex, getName(".vec"));
2484 Value *rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
2485 assert(IntTy && "We cannot insert an integer to the alloca");
2486 assert(!LI.isVolatile());
2487 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2489 V = convertValue(TD, IRB, V, IntTy);
2490 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2491 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2492 if (Offset > 0 || EndOffset < NewAllocaEndOffset)
2493 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2494 getName(".extract"));
2498 bool visitLoadInst(LoadInst &LI) {
2499 DEBUG(dbgs() << " original: " << LI << "\n");
2500 Value *OldOp = LI.getOperand(0);
2501 assert(OldOp == OldPtr);
2503 uint64_t Size = EndOffset - BeginOffset;
2505 IRBuilder<> IRB(&LI);
2506 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2508 bool IsPtrAdjusted = false;
2511 V = rewriteVectorizedLoadInst(IRB);
2512 } else if (IntTy && LI.getType()->isIntegerTy()) {
2513 V = rewriteIntegerLoad(IRB, LI);
2514 } else if (BeginOffset == NewAllocaBeginOffset &&
2515 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2516 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2517 LI.isVolatile(), getName(".load"));
2519 Type *LTy = TargetTy->getPointerTo();
2520 V = IRB.CreateAlignedLoad(getAdjustedAllocaPtr(IRB, LTy),
2521 getPartitionTypeAlign(TargetTy),
2522 LI.isVolatile(), getName(".load"));
2523 IsPtrAdjusted = true;
2525 V = convertValue(TD, IRB, V, TargetTy);
2528 assert(!LI.isVolatile());
2529 assert(LI.getType()->isIntegerTy() &&
2530 "Only integer type loads and stores are split");
2531 assert(Size < TD.getTypeStoreSize(LI.getType()) &&
2532 "Split load isn't smaller than original load");
2533 assert(LI.getType()->getIntegerBitWidth() ==
2534 TD.getTypeStoreSizeInBits(LI.getType()) &&
2535 "Non-byte-multiple bit width");
2536 // Move the insertion point just past the load so that we can refer to it.
2537 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
2538 // Create a placeholder value with the same type as LI to use as the
2539 // basis for the new value. This allows us to replace the uses of LI with
2540 // the computed value, and then replace the placeholder with LI, leaving
2541 // LI only used for this computation.
2543 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2544 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2545 getName(".insert"));
2546 LI.replaceAllUsesWith(V);
2547 Placeholder->replaceAllUsesWith(&LI);
2550 LI.replaceAllUsesWith(V);
2553 Pass.DeadInsts.insert(&LI);
2554 deleteIfTriviallyDead(OldOp);
2555 DEBUG(dbgs() << " to: " << *V << "\n");
2556 return !LI.isVolatile() && !IsPtrAdjusted;
2559 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, Value *V,
2560 StoreInst &SI, Value *OldOp) {
2561 unsigned BeginIndex = getIndex(BeginOffset);
2562 unsigned EndIndex = getIndex(EndOffset);
2563 assert(EndIndex > BeginIndex && "Empty vector!");
2564 unsigned NumElements = EndIndex - BeginIndex;
2565 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2567 = (NumElements == 1) ? ElementTy
2568 : VectorType::get(ElementTy, NumElements);
2569 if (V->getType() != PartitionTy)
2570 V = convertValue(TD, IRB, V, PartitionTy);
2572 // Mix in the existing elements.
2573 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2575 V = insertVector(IRB, Old, V, BeginIndex, getName(".vec"));
2577 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2578 Pass.DeadInsts.insert(&SI);
2581 DEBUG(dbgs() << " to: " << *Store << "\n");
2585 bool rewriteIntegerStore(IRBuilder<> &IRB, Value *V, StoreInst &SI) {
2586 assert(IntTy && "We cannot extract an integer from the alloca");
2587 assert(!SI.isVolatile());
2588 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2589 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2590 getName(".oldload"));
2591 Old = convertValue(TD, IRB, Old, IntTy);
2592 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2593 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2594 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2595 getName(".insert"));
2597 V = convertValue(TD, IRB, V, NewAllocaTy);
2598 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2599 Pass.DeadInsts.insert(&SI);
2601 DEBUG(dbgs() << " to: " << *Store << "\n");
2605 bool visitStoreInst(StoreInst &SI) {
2606 DEBUG(dbgs() << " original: " << SI << "\n");
2607 Value *OldOp = SI.getOperand(1);
2608 assert(OldOp == OldPtr);
2609 IRBuilder<> IRB(&SI);
2611 Value *V = SI.getValueOperand();
2613 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2614 // alloca that should be re-examined after promoting this alloca.
2615 if (V->getType()->isPointerTy())
2616 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2617 Pass.PostPromotionWorklist.insert(AI);
2619 uint64_t Size = EndOffset - BeginOffset;
2620 if (Size < TD.getTypeStoreSize(V->getType())) {
2621 assert(!SI.isVolatile());
2622 assert(IsSplit && "A seemingly split store isn't splittable");
2623 assert(V->getType()->isIntegerTy() &&
2624 "Only integer type loads and stores are split");
2625 assert(V->getType()->getIntegerBitWidth() ==
2626 TD.getTypeStoreSizeInBits(V->getType()) &&
2627 "Non-byte-multiple bit width");
2628 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2629 V = extractInteger(TD, IRB, V, NarrowTy, BeginOffset,
2630 getName(".extract"));
2634 return rewriteVectorizedStoreInst(IRB, V, SI, OldOp);
2635 if (IntTy && V->getType()->isIntegerTy())
2636 return rewriteIntegerStore(IRB, V, SI);
2639 if (BeginOffset == NewAllocaBeginOffset &&
2640 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2641 V = convertValue(TD, IRB, V, NewAllocaTy);
2642 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2645 Value *NewPtr = getAdjustedAllocaPtr(IRB, V->getType()->getPointerTo());
2646 NewSI = IRB.CreateAlignedStore(V, NewPtr,
2647 getPartitionTypeAlign(V->getType()),
2651 Pass.DeadInsts.insert(&SI);
2652 deleteIfTriviallyDead(OldOp);
2654 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2655 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2658 /// \brief Compute an integer value from splatting an i8 across the given
2659 /// number of bytes.
2661 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2662 /// call this routine.
2663 /// FIXME: Heed the advice above.
2665 /// \param V The i8 value to splat.
2666 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2667 Value *getIntegerSplat(IRBuilder<> &IRB, Value *V, unsigned Size) {
2668 assert(Size > 0 && "Expected a positive number of bytes.");
2669 IntegerType *VTy = cast<IntegerType>(V->getType());
2670 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2674 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2675 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
2676 ConstantExpr::getUDiv(
2677 Constant::getAllOnesValue(SplatIntTy),
2678 ConstantExpr::getZExt(
2679 Constant::getAllOnesValue(V->getType()),
2681 getName(".isplat"));
2685 /// \brief Compute a vector splat for a given element value.
2686 Value *getVectorSplat(IRBuilder<> &IRB, Value *V, unsigned NumElements) {
2687 V = IRB.CreateVectorSplat(NumElements, V, NamePrefix);
2688 DEBUG(dbgs() << " splat: " << *V << "\n");
2692 bool visitMemSetInst(MemSetInst &II) {
2693 DEBUG(dbgs() << " original: " << II << "\n");
2694 IRBuilder<> IRB(&II);
2695 assert(II.getRawDest() == OldPtr);
2697 // If the memset has a variable size, it cannot be split, just adjust the
2698 // pointer to the new alloca.
2699 if (!isa<Constant>(II.getLength())) {
2700 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2701 Type *CstTy = II.getAlignmentCst()->getType();
2702 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
2704 deleteIfTriviallyDead(OldPtr);
2708 // Record this instruction for deletion.
2709 Pass.DeadInsts.insert(&II);
2711 Type *AllocaTy = NewAI.getAllocatedType();
2712 Type *ScalarTy = AllocaTy->getScalarType();
2714 // If this doesn't map cleanly onto the alloca type, and that type isn't
2715 // a single value type, just emit a memset.
2716 if (!VecTy && !IntTy &&
2717 (BeginOffset != NewAllocaBeginOffset ||
2718 EndOffset != NewAllocaEndOffset ||
2719 !AllocaTy->isSingleValueType() ||
2720 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)) ||
2721 TD.getTypeSizeInBits(ScalarTy)%8 != 0)) {
2722 Type *SizeTy = II.getLength()->getType();
2723 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2725 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2726 II.getRawDest()->getType()),
2727 II.getValue(), Size, getPartitionAlign(),
2730 DEBUG(dbgs() << " to: " << *New << "\n");
2734 // If we can represent this as a simple value, we have to build the actual
2735 // value to store, which requires expanding the byte present in memset to
2736 // a sensible representation for the alloca type. This is essentially
2737 // splatting the byte to a sufficiently wide integer, splatting it across
2738 // any desired vector width, and bitcasting to the final type.
2742 // If this is a memset of a vectorized alloca, insert it.
2743 assert(ElementTy == ScalarTy);
2745 unsigned BeginIndex = getIndex(BeginOffset);
2746 unsigned EndIndex = getIndex(EndOffset);
2747 assert(EndIndex > BeginIndex && "Empty vector!");
2748 unsigned NumElements = EndIndex - BeginIndex;
2749 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2751 Value *Splat = getIntegerSplat(IRB, II.getValue(),
2752 TD.getTypeSizeInBits(ElementTy)/8);
2753 Splat = convertValue(TD, IRB, Splat, ElementTy);
2754 if (NumElements > 1)
2755 Splat = getVectorSplat(IRB, Splat, NumElements);
2757 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2758 getName(".oldload"));
2759 V = insertVector(IRB, Old, Splat, BeginIndex, getName(".vec"));
2761 // If this is a memset on an alloca where we can widen stores, insert the
2763 assert(!II.isVolatile());
2765 uint64_t Size = EndOffset - BeginOffset;
2766 V = getIntegerSplat(IRB, II.getValue(), Size);
2768 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2769 EndOffset != NewAllocaBeginOffset)) {
2770 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2771 getName(".oldload"));
2772 Old = convertValue(TD, IRB, Old, IntTy);
2773 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2774 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2775 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
2777 assert(V->getType() == IntTy &&
2778 "Wrong type for an alloca wide integer!");
2780 V = convertValue(TD, IRB, V, AllocaTy);
2782 // Established these invariants above.
2783 assert(BeginOffset == NewAllocaBeginOffset);
2784 assert(EndOffset == NewAllocaEndOffset);
2786 V = getIntegerSplat(IRB, II.getValue(),
2787 TD.getTypeSizeInBits(ScalarTy)/8);
2788 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2789 V = getVectorSplat(IRB, V, AllocaVecTy->getNumElements());
2791 V = convertValue(TD, IRB, V, AllocaTy);
2794 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2797 DEBUG(dbgs() << " to: " << *New << "\n");
2798 return !II.isVolatile();
2801 bool visitMemTransferInst(MemTransferInst &II) {
2802 // Rewriting of memory transfer instructions can be a bit tricky. We break
2803 // them into two categories: split intrinsics and unsplit intrinsics.
2805 DEBUG(dbgs() << " original: " << II << "\n");
2806 IRBuilder<> IRB(&II);
2808 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2809 bool IsDest = II.getRawDest() == OldPtr;
2811 const AllocaPartitioning::MemTransferOffsets &MTO
2812 = P.getMemTransferOffsets(II);
2814 // Compute the relative offset within the transfer.
2815 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2816 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2817 : MTO.SourceBegin));
2819 unsigned Align = II.getAlignment();
2821 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2822 MinAlign(II.getAlignment(), getPartitionAlign()));
2824 // For unsplit intrinsics, we simply modify the source and destination
2825 // pointers in place. This isn't just an optimization, it is a matter of
2826 // correctness. With unsplit intrinsics we may be dealing with transfers
2827 // within a single alloca before SROA ran, or with transfers that have
2828 // a variable length. We may also be dealing with memmove instead of
2829 // memcpy, and so simply updating the pointers is the necessary for us to
2830 // update both source and dest of a single call.
2831 if (!MTO.IsSplittable) {
2832 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2834 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2836 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2838 Type *CstTy = II.getAlignmentCst()->getType();
2839 II.setAlignment(ConstantInt::get(CstTy, Align));
2841 DEBUG(dbgs() << " to: " << II << "\n");
2842 deleteIfTriviallyDead(OldOp);
2845 // For split transfer intrinsics we have an incredibly useful assurance:
2846 // the source and destination do not reside within the same alloca, and at
2847 // least one of them does not escape. This means that we can replace
2848 // memmove with memcpy, and we don't need to worry about all manner of
2849 // downsides to splitting and transforming the operations.
2851 // If this doesn't map cleanly onto the alloca type, and that type isn't
2852 // a single value type, just emit a memcpy.
2854 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2855 EndOffset != NewAllocaEndOffset ||
2856 !NewAI.getAllocatedType()->isSingleValueType());
2858 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2859 // size hasn't been shrunk based on analysis of the viable range, this is
2861 if (EmitMemCpy && &OldAI == &NewAI) {
2862 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2863 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2864 // Ensure the start lines up.
2865 assert(BeginOffset == OrigBegin);
2868 // Rewrite the size as needed.
2869 if (EndOffset != OrigEnd)
2870 II.setLength(ConstantInt::get(II.getLength()->getType(),
2871 EndOffset - BeginOffset));
2874 // Record this instruction for deletion.
2875 Pass.DeadInsts.insert(&II);
2877 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2878 // alloca that should be re-examined after rewriting this instruction.
2879 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2881 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2882 Pass.Worklist.insert(AI);
2885 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2886 : II.getRawDest()->getType();
2888 // Compute the other pointer, folding as much as possible to produce
2889 // a single, simple GEP in most cases.
2890 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2891 getName("." + OtherPtr->getName()));
2894 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2895 : II.getRawSource()->getType());
2896 Type *SizeTy = II.getLength()->getType();
2897 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2899 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2900 IsDest ? OtherPtr : OurPtr,
2901 Size, Align, II.isVolatile());
2903 DEBUG(dbgs() << " to: " << *New << "\n");
2907 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2908 // is equivalent to 1, but that isn't true if we end up rewriting this as
2913 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2914 EndOffset == NewAllocaEndOffset;
2915 uint64_t Size = EndOffset - BeginOffset;
2916 unsigned BeginIndex = VecTy ? getIndex(BeginOffset) : 0;
2917 unsigned EndIndex = VecTy ? getIndex(EndOffset) : 0;
2918 unsigned NumElements = EndIndex - BeginIndex;
2919 IntegerType *SubIntTy
2920 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2922 Type *OtherPtrTy = NewAI.getType();
2923 if (VecTy && !IsWholeAlloca) {
2924 if (NumElements == 1)
2925 OtherPtrTy = VecTy->getElementType();
2927 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2929 OtherPtrTy = OtherPtrTy->getPointerTo();
2930 } else if (IntTy && !IsWholeAlloca) {
2931 OtherPtrTy = SubIntTy->getPointerTo();
2934 Value *SrcPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2935 getName("." + OtherPtr->getName()));
2936 Value *DstPtr = &NewAI;
2938 std::swap(SrcPtr, DstPtr);
2941 if (VecTy && !IsWholeAlloca && !IsDest) {
2942 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2944 Src = extractVector(IRB, Src, BeginIndex, EndIndex, getName(".vec"));
2945 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2946 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2948 Src = convertValue(TD, IRB, Src, IntTy);
2949 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2950 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2951 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
2953 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2954 getName(".copyload"));
2957 if (VecTy && !IsWholeAlloca && IsDest) {
2958 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2959 getName(".oldload"));
2960 Src = insertVector(IRB, Old, Src, BeginIndex, getName(".vec"));
2961 } else if (IntTy && !IsWholeAlloca && IsDest) {
2962 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2963 getName(".oldload"));
2964 Old = convertValue(TD, IRB, Old, IntTy);
2965 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2966 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2967 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2968 Src = convertValue(TD, IRB, Src, NewAllocaTy);
2971 StoreInst *Store = cast<StoreInst>(
2972 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2974 DEBUG(dbgs() << " to: " << *Store << "\n");
2975 return !II.isVolatile();
2978 bool visitIntrinsicInst(IntrinsicInst &II) {
2979 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2980 II.getIntrinsicID() == Intrinsic::lifetime_end);
2981 DEBUG(dbgs() << " original: " << II << "\n");
2982 IRBuilder<> IRB(&II);
2983 assert(II.getArgOperand(1) == OldPtr);
2985 // Record this instruction for deletion.
2986 Pass.DeadInsts.insert(&II);
2989 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2990 EndOffset - BeginOffset);
2991 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2993 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2994 New = IRB.CreateLifetimeStart(Ptr, Size);
2996 New = IRB.CreateLifetimeEnd(Ptr, Size);
2999 DEBUG(dbgs() << " to: " << *New << "\n");
3003 bool visitPHINode(PHINode &PN) {
3004 DEBUG(dbgs() << " original: " << PN << "\n");
3006 // We would like to compute a new pointer in only one place, but have it be
3007 // as local as possible to the PHI. To do that, we re-use the location of
3008 // the old pointer, which necessarily must be in the right position to
3009 // dominate the PHI.
3010 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
3012 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
3013 // Replace the operands which were using the old pointer.
3014 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3016 DEBUG(dbgs() << " to: " << PN << "\n");
3017 deleteIfTriviallyDead(OldPtr);
3021 bool visitSelectInst(SelectInst &SI) {
3022 DEBUG(dbgs() << " original: " << SI << "\n");
3023 IRBuilder<> IRB(&SI);
3025 // Find the operand we need to rewrite here.
3026 bool IsTrueVal = SI.getTrueValue() == OldPtr;
3028 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
3030 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
3032 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
3033 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
3034 DEBUG(dbgs() << " to: " << SI << "\n");
3035 deleteIfTriviallyDead(OldPtr);
3043 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
3045 /// This pass aggressively rewrites all aggregate loads and stores on
3046 /// a particular pointer (or any pointer derived from it which we can identify)
3047 /// with scalar loads and stores.
3048 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3049 // Befriend the base class so it can delegate to private visit methods.
3050 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3052 const DataLayout &TD;
3054 /// Queue of pointer uses to analyze and potentially rewrite.
3055 SmallVector<Use *, 8> Queue;
3057 /// Set to prevent us from cycling with phi nodes and loops.
3058 SmallPtrSet<User *, 8> Visited;
3060 /// The current pointer use being rewritten. This is used to dig up the used
3061 /// value (as opposed to the user).
3065 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
3067 /// Rewrite loads and stores through a pointer and all pointers derived from
3069 bool rewrite(Instruction &I) {
3070 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3072 bool Changed = false;
3073 while (!Queue.empty()) {
3074 U = Queue.pop_back_val();
3075 Changed |= visit(cast<Instruction>(U->getUser()));
3081 /// Enqueue all the users of the given instruction for further processing.
3082 /// This uses a set to de-duplicate users.
3083 void enqueueUsers(Instruction &I) {
3084 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3086 if (Visited.insert(*UI))
3087 Queue.push_back(&UI.getUse());
3090 // Conservative default is to not rewrite anything.
3091 bool visitInstruction(Instruction &I) { return false; }
3093 /// \brief Generic recursive split emission class.
3094 template <typename Derived>
3097 /// The builder used to form new instructions.
3099 /// The indices which to be used with insert- or extractvalue to select the
3100 /// appropriate value within the aggregate.
3101 SmallVector<unsigned, 4> Indices;
3102 /// The indices to a GEP instruction which will move Ptr to the correct slot
3103 /// within the aggregate.
3104 SmallVector<Value *, 4> GEPIndices;
3105 /// The base pointer of the original op, used as a base for GEPing the
3106 /// split operations.
3109 /// Initialize the splitter with an insertion point, Ptr and start with a
3110 /// single zero GEP index.
3111 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
3112 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3115 /// \brief Generic recursive split emission routine.
3117 /// This method recursively splits an aggregate op (load or store) into
3118 /// scalar or vector ops. It splits recursively until it hits a single value
3119 /// and emits that single value operation via the template argument.
3121 /// The logic of this routine relies on GEPs and insertvalue and
3122 /// extractvalue all operating with the same fundamental index list, merely
3123 /// formatted differently (GEPs need actual values).
3125 /// \param Ty The type being split recursively into smaller ops.
3126 /// \param Agg The aggregate value being built up or stored, depending on
3127 /// whether this is splitting a load or a store respectively.
3128 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3129 if (Ty->isSingleValueType())
3130 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
3132 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3133 unsigned OldSize = Indices.size();
3135 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3137 assert(Indices.size() == OldSize && "Did not return to the old size");
3138 Indices.push_back(Idx);
3139 GEPIndices.push_back(IRB.getInt32(Idx));
3140 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3141 GEPIndices.pop_back();
3147 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3148 unsigned OldSize = Indices.size();
3150 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3152 assert(Indices.size() == OldSize && "Did not return to the old size");
3153 Indices.push_back(Idx);
3154 GEPIndices.push_back(IRB.getInt32(Idx));
3155 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3156 GEPIndices.pop_back();
3162 llvm_unreachable("Only arrays and structs are aggregate loadable types");
3166 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3167 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3168 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
3170 /// Emit a leaf load of a single value. This is called at the leaves of the
3171 /// recursive emission to actually load values.
3172 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3173 assert(Ty->isSingleValueType());
3174 // Load the single value and insert it using the indices.
3175 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
3176 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
3177 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3178 DEBUG(dbgs() << " to: " << *Load << "\n");
3182 bool visitLoadInst(LoadInst &LI) {
3183 assert(LI.getPointerOperand() == *U);
3184 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3187 // We have an aggregate being loaded, split it apart.
3188 DEBUG(dbgs() << " original: " << LI << "\n");
3189 LoadOpSplitter Splitter(&LI, *U);
3190 Value *V = UndefValue::get(LI.getType());
3191 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3192 LI.replaceAllUsesWith(V);
3193 LI.eraseFromParent();
3197 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
3198 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3199 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
3201 /// Emit a leaf store of a single value. This is called at the leaves of the
3202 /// recursive emission to actually produce stores.
3203 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3204 assert(Ty->isSingleValueType());
3205 // Extract the single value and store it using the indices.
3206 Value *Store = IRB.CreateStore(
3207 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3208 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3210 DEBUG(dbgs() << " to: " << *Store << "\n");
3214 bool visitStoreInst(StoreInst &SI) {
3215 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3217 Value *V = SI.getValueOperand();
3218 if (V->getType()->isSingleValueType())
3221 // We have an aggregate being stored, split it apart.
3222 DEBUG(dbgs() << " original: " << SI << "\n");
3223 StoreOpSplitter Splitter(&SI, *U);
3224 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3225 SI.eraseFromParent();
3229 bool visitBitCastInst(BitCastInst &BC) {
3234 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3239 bool visitPHINode(PHINode &PN) {
3244 bool visitSelectInst(SelectInst &SI) {
3251 /// \brief Strip aggregate type wrapping.
3253 /// This removes no-op aggregate types wrapping an underlying type. It will
3254 /// strip as many layers of types as it can without changing either the type
3255 /// size or the allocated size.
3256 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3257 if (Ty->isSingleValueType())
3260 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3261 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3264 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3265 InnerTy = ArrTy->getElementType();
3266 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3267 const StructLayout *SL = DL.getStructLayout(STy);
3268 unsigned Index = SL->getElementContainingOffset(0);
3269 InnerTy = STy->getElementType(Index);
3274 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3275 TypeSize > DL.getTypeSizeInBits(InnerTy))
3278 return stripAggregateTypeWrapping(DL, InnerTy);
3281 /// \brief Try to find a partition of the aggregate type passed in for a given
3282 /// offset and size.
3284 /// This recurses through the aggregate type and tries to compute a subtype
3285 /// based on the offset and size. When the offset and size span a sub-section
3286 /// of an array, it will even compute a new array type for that sub-section,
3287 /// and the same for structs.
3289 /// Note that this routine is very strict and tries to find a partition of the
3290 /// type which produces the *exact* right offset and size. It is not forgiving
3291 /// when the size or offset cause either end of type-based partition to be off.
3292 /// Also, this is a best-effort routine. It is reasonable to give up and not
3293 /// return a type if necessary.
3294 static Type *getTypePartition(const DataLayout &TD, Type *Ty,
3295 uint64_t Offset, uint64_t Size) {
3296 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
3297 return stripAggregateTypeWrapping(TD, Ty);
3298 if (Offset > TD.getTypeAllocSize(Ty) ||
3299 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3302 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3303 // We can't partition pointers...
3304 if (SeqTy->isPointerTy())
3307 Type *ElementTy = SeqTy->getElementType();
3308 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3309 uint64_t NumSkippedElements = Offset / ElementSize;
3310 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3311 if (NumSkippedElements >= ArrTy->getNumElements())
3313 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3314 if (NumSkippedElements >= VecTy->getNumElements())
3316 Offset -= NumSkippedElements * ElementSize;
3318 // First check if we need to recurse.
3319 if (Offset > 0 || Size < ElementSize) {
3320 // Bail if the partition ends in a different array element.
3321 if ((Offset + Size) > ElementSize)
3323 // Recurse through the element type trying to peel off offset bytes.
3324 return getTypePartition(TD, ElementTy, Offset, Size);
3326 assert(Offset == 0);
3328 if (Size == ElementSize)
3329 return stripAggregateTypeWrapping(TD, ElementTy);
3330 assert(Size > ElementSize);
3331 uint64_t NumElements = Size / ElementSize;
3332 if (NumElements * ElementSize != Size)
3334 return ArrayType::get(ElementTy, NumElements);
3337 StructType *STy = dyn_cast<StructType>(Ty);
3341 const StructLayout *SL = TD.getStructLayout(STy);
3342 if (Offset >= SL->getSizeInBytes())
3344 uint64_t EndOffset = Offset + Size;
3345 if (EndOffset > SL->getSizeInBytes())
3348 unsigned Index = SL->getElementContainingOffset(Offset);
3349 Offset -= SL->getElementOffset(Index);
3351 Type *ElementTy = STy->getElementType(Index);
3352 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3353 if (Offset >= ElementSize)
3354 return 0; // The offset points into alignment padding.
3356 // See if any partition must be contained by the element.
3357 if (Offset > 0 || Size < ElementSize) {
3358 if ((Offset + Size) > ElementSize)
3360 return getTypePartition(TD, ElementTy, Offset, Size);
3362 assert(Offset == 0);
3364 if (Size == ElementSize)
3365 return stripAggregateTypeWrapping(TD, ElementTy);
3367 StructType::element_iterator EI = STy->element_begin() + Index,
3368 EE = STy->element_end();
3369 if (EndOffset < SL->getSizeInBytes()) {
3370 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3371 if (Index == EndIndex)
3372 return 0; // Within a single element and its padding.
3374 // Don't try to form "natural" types if the elements don't line up with the
3376 // FIXME: We could potentially recurse down through the last element in the
3377 // sub-struct to find a natural end point.
3378 if (SL->getElementOffset(EndIndex) != EndOffset)
3381 assert(Index < EndIndex);
3382 EE = STy->element_begin() + EndIndex;
3385 // Try to build up a sub-structure.
3386 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
3388 const StructLayout *SubSL = TD.getStructLayout(SubTy);
3389 if (Size != SubSL->getSizeInBytes())
3390 return 0; // The sub-struct doesn't have quite the size needed.
3395 /// \brief Rewrite an alloca partition's users.
3397 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3398 /// to rewrite uses of an alloca partition to be conducive for SSA value
3399 /// promotion. If the partition needs a new, more refined alloca, this will
3400 /// build that new alloca, preserving as much type information as possible, and
3401 /// rewrite the uses of the old alloca to point at the new one and have the
3402 /// appropriate new offsets. It also evaluates how successful the rewrite was
3403 /// at enabling promotion and if it was successful queues the alloca to be
3405 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3406 AllocaPartitioning &P,
3407 AllocaPartitioning::iterator PI) {
3408 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
3409 bool IsLive = false;
3410 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3412 UI != UE && !IsLive; ++UI)
3416 return false; // No live uses left of this partition.
3418 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3419 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3421 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3422 DEBUG(dbgs() << " speculating ");
3423 DEBUG(P.print(dbgs(), PI, ""));
3424 Speculator.visitUsers(PI);
3426 // Try to compute a friendly type for this partition of the alloca. This
3427 // won't always succeed, in which case we fall back to a legal integer type
3428 // or an i8 array of an appropriate size.
3430 if (Type *PartitionTy = P.getCommonType(PI))
3431 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3432 AllocaTy = PartitionTy;
3434 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3435 PI->BeginOffset, AllocaSize))
3436 AllocaTy = PartitionTy;
3438 (AllocaTy->isArrayTy() &&
3439 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3440 TD->isLegalInteger(AllocaSize * 8))
3441 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3443 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
3444 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
3446 // Check for the case where we're going to rewrite to a new alloca of the
3447 // exact same type as the original, and with the same access offsets. In that
3448 // case, re-use the existing alloca, but still run through the rewriter to
3449 // perform phi and select speculation.
3451 if (AllocaTy == AI.getAllocatedType()) {
3452 assert(PI->BeginOffset == 0 &&
3453 "Non-zero begin offset but same alloca type");
3454 assert(PI == P.begin() && "Begin offset is zero on later partition");
3457 unsigned Alignment = AI.getAlignment();
3459 // The minimum alignment which users can rely on when the explicit
3460 // alignment is omitted or zero is that required by the ABI for this
3462 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3464 Alignment = MinAlign(Alignment, PI->BeginOffset);
3465 // If we will get at least this much alignment from the type alone, leave
3466 // the alloca's alignment unconstrained.
3467 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3469 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
3470 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3475 DEBUG(dbgs() << "Rewriting alloca partition "
3476 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3479 // Track the high watermark of the post-promotion worklist. We will reset it
3480 // to this point if the alloca is not in fact scheduled for promotion.
3481 unsigned PPWOldSize = PostPromotionWorklist.size();
3483 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3484 PI->BeginOffset, PI->EndOffset);
3485 DEBUG(dbgs() << " rewriting ");
3486 DEBUG(P.print(dbgs(), PI, ""));
3487 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3489 DEBUG(dbgs() << " and queuing for promotion\n");
3490 PromotableAllocas.push_back(NewAI);
3491 } else if (NewAI != &AI) {
3492 // If we can't promote the alloca, iterate on it to check for new
3493 // refinements exposed by splitting the current alloca. Don't iterate on an
3494 // alloca which didn't actually change and didn't get promoted.
3495 Worklist.insert(NewAI);
3498 // Drop any post-promotion work items if promotion didn't happen.
3500 while (PostPromotionWorklist.size() > PPWOldSize)
3501 PostPromotionWorklist.pop_back();
3506 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3507 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3508 bool Changed = false;
3509 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3511 Changed |= rewriteAllocaPartition(AI, P, PI);
3516 /// \brief Analyze an alloca for SROA.
3518 /// This analyzes the alloca to ensure we can reason about it, builds
3519 /// a partitioning of the alloca, and then hands it off to be split and
3520 /// rewritten as needed.
3521 bool SROA::runOnAlloca(AllocaInst &AI) {
3522 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3523 ++NumAllocasAnalyzed;
3525 // Special case dead allocas, as they're trivial.
3526 if (AI.use_empty()) {
3527 AI.eraseFromParent();
3531 // Skip alloca forms that this analysis can't handle.
3532 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3533 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3536 bool Changed = false;
3538 // First, split any FCA loads and stores touching this alloca to promote
3539 // better splitting and promotion opportunities.
3540 AggLoadStoreRewriter AggRewriter(*TD);
3541 Changed |= AggRewriter.rewrite(AI);
3543 // Build the partition set using a recursive instruction-visiting builder.
3544 AllocaPartitioning P(*TD, AI);
3545 DEBUG(P.print(dbgs()));
3549 // Delete all the dead users of this alloca before splitting and rewriting it.
3550 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3551 DE = P.dead_user_end();
3554 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3555 DeadInsts.insert(*DI);
3557 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3558 DE = P.dead_op_end();
3561 // Clobber the use with an undef value.
3562 **DO = UndefValue::get(OldV->getType());
3563 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3564 if (isInstructionTriviallyDead(OldI)) {
3566 DeadInsts.insert(OldI);
3570 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3571 if (P.begin() == P.end())
3574 return splitAlloca(AI, P) || Changed;
3577 /// \brief Delete the dead instructions accumulated in this run.
3579 /// Recursively deletes the dead instructions we've accumulated. This is done
3580 /// at the very end to maximize locality of the recursive delete and to
3581 /// minimize the problems of invalidated instruction pointers as such pointers
3582 /// are used heavily in the intermediate stages of the algorithm.
3584 /// We also record the alloca instructions deleted here so that they aren't
3585 /// subsequently handed to mem2reg to promote.
3586 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3587 while (!DeadInsts.empty()) {
3588 Instruction *I = DeadInsts.pop_back_val();
3589 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3591 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3593 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3594 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3595 // Zero out the operand and see if it becomes trivially dead.
3597 if (isInstructionTriviallyDead(U))
3598 DeadInsts.insert(U);
3601 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3602 DeletedAllocas.insert(AI);
3605 I->eraseFromParent();
3609 /// \brief Promote the allocas, using the best available technique.
3611 /// This attempts to promote whatever allocas have been identified as viable in
3612 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3613 /// If there is a domtree available, we attempt to promote using the full power
3614 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3615 /// based on the SSAUpdater utilities. This function returns whether any
3616 /// promotion occurred.
3617 bool SROA::promoteAllocas(Function &F) {
3618 if (PromotableAllocas.empty())
3621 NumPromoted += PromotableAllocas.size();
3623 if (DT && !ForceSSAUpdater) {
3624 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3625 PromoteMemToReg(PromotableAllocas, *DT);
3626 PromotableAllocas.clear();
3630 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3632 DIBuilder DIB(*F.getParent());
3633 SmallVector<Instruction*, 64> Insts;
3635 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3636 AllocaInst *AI = PromotableAllocas[Idx];
3637 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3639 Instruction *I = cast<Instruction>(*UI++);
3640 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3641 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3642 // leading to them) here. Eventually it should use them to optimize the
3643 // scalar values produced.
3644 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3645 assert(onlyUsedByLifetimeMarkers(I) &&
3646 "Found a bitcast used outside of a lifetime marker.");
3647 while (!I->use_empty())
3648 cast<Instruction>(*I->use_begin())->eraseFromParent();
3649 I->eraseFromParent();
3652 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3653 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3654 II->getIntrinsicID() == Intrinsic::lifetime_end);
3655 II->eraseFromParent();
3661 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3665 PromotableAllocas.clear();
3670 /// \brief A predicate to test whether an alloca belongs to a set.
3671 class IsAllocaInSet {
3672 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3676 typedef AllocaInst *argument_type;
3678 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3679 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
3683 bool SROA::runOnFunction(Function &F) {
3684 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3685 C = &F.getContext();
3686 TD = getAnalysisIfAvailable<DataLayout>();
3688 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3691 DT = getAnalysisIfAvailable<DominatorTree>();
3693 BasicBlock &EntryBB = F.getEntryBlock();
3694 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3696 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3697 Worklist.insert(AI);
3699 bool Changed = false;
3700 // A set of deleted alloca instruction pointers which should be removed from
3701 // the list of promotable allocas.
3702 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3705 while (!Worklist.empty()) {
3706 Changed |= runOnAlloca(*Worklist.pop_back_val());
3707 deleteDeadInstructions(DeletedAllocas);
3709 // Remove the deleted allocas from various lists so that we don't try to
3710 // continue processing them.
3711 if (!DeletedAllocas.empty()) {
3712 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3713 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3714 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3715 PromotableAllocas.end(),
3716 IsAllocaInSet(DeletedAllocas)),
3717 PromotableAllocas.end());
3718 DeletedAllocas.clear();
3722 Changed |= promoteAllocas(F);
3724 Worklist = PostPromotionWorklist;
3725 PostPromotionWorklist.clear();
3726 } while (!Worklist.empty());
3731 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3732 if (RequiresDomTree)
3733 AU.addRequired<DominatorTree>();
3734 AU.setPreservesCFG();