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 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/AssumptionTracker.h"
32 #include "llvm/Analysis/Loads.h"
33 #include "llvm/Analysis/PtrUseVisitor.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DIBuilder.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DebugInfo.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Dominators.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/InstVisitor.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/IntrinsicInst.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Operator.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/TimeValue.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
58 #include "llvm/Transforms/Utils/SSAUpdater.h"
60 #if __cplusplus >= 201103L && !defined(NDEBUG)
61 // We only use this for a debug check in C++11
67 #define DEBUG_TYPE "sroa"
69 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
70 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
71 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
72 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
73 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
74 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
75 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
76 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
77 STATISTIC(NumDeleted, "Number of instructions deleted");
78 STATISTIC(NumVectorized, "Number of vectorized aggregates");
80 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
81 /// forming SSA values through the SSAUpdater infrastructure.
82 static cl::opt<bool> ForceSSAUpdater("force-ssa-updater", cl::init(false),
85 /// Hidden option to enable randomly shuffling the slices to help uncover
86 /// instability in their order.
87 static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
88 cl::init(false), cl::Hidden);
90 /// Hidden option to experiment with completely strict handling of inbounds
92 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
96 /// \brief A custom IRBuilder inserter which prefixes all names if they are
98 template <bool preserveNames = true>
99 class IRBuilderPrefixedInserter
100 : public IRBuilderDefaultInserter<preserveNames> {
104 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
107 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
108 BasicBlock::iterator InsertPt) const {
109 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
110 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
114 // Specialization for not preserving the name is trivial.
116 class IRBuilderPrefixedInserter<false>
117 : public IRBuilderDefaultInserter<false> {
119 void SetNamePrefix(const Twine &P) {}
122 /// \brief Provide a typedef for IRBuilder that drops names in release builds.
124 typedef llvm::IRBuilder<true, ConstantFolder, IRBuilderPrefixedInserter<true>>
127 typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
133 /// \brief A used slice of an alloca.
135 /// This structure represents a slice of an alloca used by some instruction. It
136 /// stores both the begin and end offsets of this use, a pointer to the use
137 /// itself, and a flag indicating whether we can classify the use as splittable
138 /// or not when forming partitions of the alloca.
140 /// \brief The beginning offset of the range.
141 uint64_t BeginOffset;
143 /// \brief The ending offset, not included in the range.
146 /// \brief Storage for both the use of this slice and whether it can be
148 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
151 Slice() : BeginOffset(), EndOffset() {}
152 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
153 : BeginOffset(BeginOffset), EndOffset(EndOffset),
154 UseAndIsSplittable(U, IsSplittable) {}
156 uint64_t beginOffset() const { return BeginOffset; }
157 uint64_t endOffset() const { return EndOffset; }
159 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
160 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
162 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
164 bool isDead() const { return getUse() == nullptr; }
165 void kill() { UseAndIsSplittable.setPointer(nullptr); }
167 /// \brief Support for ordering ranges.
169 /// This provides an ordering over ranges such that start offsets are
170 /// always increasing, and within equal start offsets, the end offsets are
171 /// decreasing. Thus the spanning range comes first in a cluster with the
172 /// same start position.
173 bool operator<(const Slice &RHS) const {
174 if (beginOffset() < RHS.beginOffset())
176 if (beginOffset() > RHS.beginOffset())
178 if (isSplittable() != RHS.isSplittable())
179 return !isSplittable();
180 if (endOffset() > RHS.endOffset())
185 /// \brief Support comparison with a single offset to allow binary searches.
186 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
187 uint64_t RHSOffset) {
188 return LHS.beginOffset() < RHSOffset;
190 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
192 return LHSOffset < RHS.beginOffset();
195 bool operator==(const Slice &RHS) const {
196 return isSplittable() == RHS.isSplittable() &&
197 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
199 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
201 } // end anonymous namespace
204 template <typename T> struct isPodLike;
205 template <> struct isPodLike<Slice> { static const bool value = true; };
209 /// \brief Representation of the alloca slices.
211 /// This class represents the slices of an alloca which are formed by its
212 /// various uses. If a pointer escapes, we can't fully build a representation
213 /// for the slices used and we reflect that in this structure. The uses are
214 /// stored, sorted by increasing beginning offset and with unsplittable slices
215 /// starting at a particular offset before splittable slices.
218 /// \brief Construct the slices of a particular alloca.
219 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
221 /// \brief Test whether a pointer to the allocation escapes our analysis.
223 /// If this is true, the slices are never fully built and should be
225 bool isEscaped() const { return PointerEscapingInstr; }
227 /// \brief Support for iterating over the slices.
229 typedef SmallVectorImpl<Slice>::iterator iterator;
230 typedef iterator_range<iterator> range;
231 iterator begin() { return Slices.begin(); }
232 iterator end() { return Slices.end(); }
234 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
235 typedef iterator_range<const_iterator> const_range;
236 const_iterator begin() const { return Slices.begin(); }
237 const_iterator end() const { return Slices.end(); }
240 /// \brief Erase a range of slices.
241 void erase(iterator Start, iterator Stop) {
242 Slices.erase(Start, Stop);
245 /// \brief Insert new slices for this alloca.
247 /// This moves the slices into the alloca's slices collection, and re-sorts
248 /// everything so that the usual ordering properties of the alloca's slices
250 void insert(ArrayRef<Slice> NewSlices) {
251 int OldSize = Slices.size();
252 std::move(NewSlices.begin(), NewSlices.end(), std::back_inserter(Slices));
253 auto SliceI = Slices.begin() + OldSize;
254 std::sort(SliceI, Slices.end());
255 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
258 // Forward declare an iterator to befriend it.
259 class partition_iterator;
261 /// \brief A partition of the slices.
263 /// An ephemeral representation for a range of slices which can be viewed as
264 /// a partition of the alloca. This range represents a span of the alloca's
265 /// memory which cannot be split, and provides access to all of the slices
266 /// overlapping some part of the partition.
268 /// Objects of this type are produced by traversing the alloca's slices, but
269 /// are only ephemeral and not persistent.
272 friend class AllocaSlices;
273 friend class AllocaSlices::partition_iterator;
275 /// \brief The begining and ending offsets of the alloca for this partition.
276 uint64_t BeginOffset, EndOffset;
278 /// \brief The start end end iterators of this partition.
281 /// \brief A collection of split slice tails overlapping the partition.
282 SmallVector<Slice *, 4> SplitTails;
284 /// \brief Raw constructor builds an empty partition starting and ending at
285 /// the given iterator.
286 Partition(iterator SI) : SI(SI), SJ(SI) {}
289 /// \brief The start offset of this partition.
291 /// All of the contained slices start at or after this offset.
292 uint64_t beginOffset() const { return BeginOffset; }
294 /// \brief The end offset of this partition.
296 /// All of the contained slices end at or before this offset.
297 uint64_t endOffset() const { return EndOffset; }
299 /// \brief The size of the partition.
301 /// Note that this can never be zero.
302 uint64_t size() const {
303 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
304 return EndOffset - BeginOffset;
307 /// \brief Test whether this partition contains no slices, and merely spans
308 /// a region occupied by split slices.
309 bool empty() const { return SI == SJ; }
311 /// \name Iterate slices that start within the partition.
312 /// These may be splittable or unsplittable. They have a begin offset >= the
313 /// partition begin offset.
315 // FIXME: We should probably define a "concat_iterator" helper and use that
316 // to stitch together pointee_iterators over the split tails and the
317 // contiguous iterators of the partition. That would give a much nicer
318 // interface here. We could then additionally expose filtered iterators for
319 // split, unsplit, and unsplittable splices based on the usage patterns.
320 iterator begin() const { return SI; }
321 iterator end() const { return SJ; }
324 /// \brief Get the sequence of split slice tails.
326 /// These tails are of slices which start before this partition but are
327 /// split and overlap into the partition. We accumulate these while forming
329 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
332 /// \brief An iterator over partitions of the alloca's slices.
334 /// This iterator implements the core algorithm for partitioning the alloca's
335 /// slices. It is a forward iterator as we don't support backtracking for
336 /// efficiency reasons, and re-use a single storage area to maintain the
337 /// current set of split slices.
339 /// It is templated on the slice iterator type to use so that it can operate
340 /// with either const or non-const slice iterators.
341 class partition_iterator
342 : public iterator_facade_base<partition_iterator,
343 std::forward_iterator_tag, Partition> {
344 friend class AllocaSlices;
346 /// \brief Most of the state for walking the partitions is held in a class
347 /// with a nice interface for examining them.
350 /// \brief We need to keep the end of the slices to know when to stop.
351 AllocaSlices::iterator SE;
353 /// \brief We also need to keep track of the maximum split end offset seen.
354 /// FIXME: Do we really?
355 uint64_t MaxSplitSliceEndOffset;
357 /// \brief Sets the partition to be empty at given iterator, and sets the
359 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
360 : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
361 // If not already at the end, advance our state to form the initial
367 /// \brief Advance the iterator to the next partition.
369 /// Requires that the iterator not be at the end of the slices.
371 assert((P.SI != SE || !P.SplitTails.empty()) &&
372 "Cannot advance past the end of the slices!");
374 // Clear out any split uses which have ended.
375 if (!P.SplitTails.empty()) {
376 if (P.EndOffset >= MaxSplitSliceEndOffset) {
377 // If we've finished all splits, this is easy.
378 P.SplitTails.clear();
379 MaxSplitSliceEndOffset = 0;
381 // Remove the uses which have ended in the prior partition. This
382 // cannot change the max split slice end because we just checked that
383 // the prior partition ended prior to that max.
386 P.SplitTails.begin(), P.SplitTails.end(),
387 [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
389 assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
391 return S->endOffset() == MaxSplitSliceEndOffset;
393 "Could not find the current max split slice offset!");
394 assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
396 return S->endOffset() <= MaxSplitSliceEndOffset;
398 "Max split slice end offset is not actually the max!");
402 // If P.SI is already at the end, then we've cleared the split tail and
403 // now have an end iterator.
405 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
409 // If we had a non-empty partition previously, set up the state for
410 // subsequent partitions.
412 // Accumulate all the splittable slices which started in the old
413 // partition into the split list.
415 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
416 P.SplitTails.push_back(&S);
417 MaxSplitSliceEndOffset =
418 std::max(S.endOffset(), MaxSplitSliceEndOffset);
421 // Start from the end of the previous partition.
424 // If P.SI is now at the end, we at most have a tail of split slices.
426 P.BeginOffset = P.EndOffset;
427 P.EndOffset = MaxSplitSliceEndOffset;
431 // If the we have split slices and the next slice is after a gap and is
432 // not splittable immediately form an empty partition for the split
433 // slices up until the next slice begins.
434 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
435 !P.SI->isSplittable()) {
436 P.BeginOffset = P.EndOffset;
437 P.EndOffset = P.SI->beginOffset();
442 // OK, we need to consume new slices. Set the end offset based on the
443 // current slice, and step SJ past it. The beginning offset of the
444 // parttion is the beginning offset of the next slice unless we have
445 // pre-existing split slices that are continuing, in which case we begin
446 // at the prior end offset.
447 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
448 P.EndOffset = P.SI->endOffset();
451 // There are two strategies to form a partition based on whether the
452 // partition starts with an unsplittable slice or a splittable slice.
453 if (!P.SI->isSplittable()) {
454 // When we're forming an unsplittable region, it must always start at
455 // the first slice and will extend through its end.
456 assert(P.BeginOffset == P.SI->beginOffset());
458 // Form a partition including all of the overlapping slices with this
459 // unsplittable slice.
460 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
461 if (!P.SJ->isSplittable())
462 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
466 // We have a partition across a set of overlapping unsplittable
471 // If we're starting with a splittable slice, then we need to form
472 // a synthetic partition spanning it and any other overlapping splittable
474 assert(P.SI->isSplittable() && "Forming a splittable partition!");
476 // Collect all of the overlapping splittable slices.
477 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
478 P.SJ->isSplittable()) {
479 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
483 // Back upiP.EndOffset if we ended the span early when encountering an
484 // unsplittable slice. This synthesizes the early end offset of
485 // a partition spanning only splittable slices.
486 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
487 assert(!P.SJ->isSplittable());
488 P.EndOffset = P.SJ->beginOffset();
493 bool operator==(const partition_iterator &RHS) const {
494 assert(SE == RHS.SE &&
495 "End iterators don't match between compared partition iterators!");
497 // The observed positions of partitions is marked by the P.SI iterator and
498 // the emptyness of the split slices. The latter is only relevant when
499 // P.SI == SE, as the end iterator will additionally have an empty split
500 // slices list, but the prior may have the same P.SI and a tail of split
502 if (P.SI == RHS.P.SI &&
503 P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
504 assert(P.SJ == RHS.P.SJ &&
505 "Same set of slices formed two different sized partitions!");
506 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
507 "Same slice position with differently sized non-empty split "
514 partition_iterator &operator++() {
519 Partition &operator*() { return P; }
522 /// \brief A forward range over the partitions of the alloca's slices.
524 /// This accesses an iterator range over the partitions of the alloca's
525 /// slices. It computes these partitions on the fly based on the overlapping
526 /// offsets of the slices and the ability to split them. It will visit "empty"
527 /// partitions to cover regions of the alloca only accessed via split
529 iterator_range<partition_iterator> partitions() {
530 return make_range(partition_iterator(begin(), end()),
531 partition_iterator(end(), end()));
534 /// \brief Access the dead users for this alloca.
535 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
537 /// \brief Access the dead operands referring to this alloca.
539 /// These are operands which have cannot actually be used to refer to the
540 /// alloca as they are outside its range and the user doesn't correct for
541 /// that. These mostly consist of PHI node inputs and the like which we just
542 /// need to replace with undef.
543 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
545 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
546 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
547 void printSlice(raw_ostream &OS, const_iterator I,
548 StringRef Indent = " ") const;
549 void printUse(raw_ostream &OS, const_iterator I,
550 StringRef Indent = " ") const;
551 void print(raw_ostream &OS) const;
552 void dump(const_iterator I) const;
557 template <typename DerivedT, typename RetT = void> class BuilderBase;
559 friend class AllocaSlices::SliceBuilder;
561 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
562 /// \brief Handle to alloca instruction to simplify method interfaces.
566 /// \brief The instruction responsible for this alloca not having a known set
569 /// When an instruction (potentially) escapes the pointer to the alloca, we
570 /// store a pointer to that here and abort trying to form slices of the
571 /// alloca. This will be null if the alloca slices are analyzed successfully.
572 Instruction *PointerEscapingInstr;
574 /// \brief The slices of the alloca.
576 /// We store a vector of the slices formed by uses of the alloca here. This
577 /// vector is sorted by increasing begin offset, and then the unsplittable
578 /// slices before the splittable ones. See the Slice inner class for more
580 SmallVector<Slice, 8> Slices;
582 /// \brief Instructions which will become dead if we rewrite the alloca.
584 /// Note that these are not separated by slice. This is because we expect an
585 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
586 /// all these instructions can simply be removed and replaced with undef as
587 /// they come from outside of the allocated space.
588 SmallVector<Instruction *, 8> DeadUsers;
590 /// \brief Operands which will become dead if we rewrite the alloca.
592 /// These are operands that in their particular use can be replaced with
593 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
594 /// to PHI nodes and the like. They aren't entirely dead (there might be
595 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
596 /// want to swap this particular input for undef to simplify the use lists of
598 SmallVector<Use *, 8> DeadOperands;
602 static Value *foldSelectInst(SelectInst &SI) {
603 // If the condition being selected on is a constant or the same value is
604 // being selected between, fold the select. Yes this does (rarely) happen
606 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
607 return SI.getOperand(1 + CI->isZero());
608 if (SI.getOperand(1) == SI.getOperand(2))
609 return SI.getOperand(1);
614 /// \brief A helper that folds a PHI node or a select.
615 static Value *foldPHINodeOrSelectInst(Instruction &I) {
616 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
617 // If PN merges together the same value, return that value.
618 return PN->hasConstantValue();
620 return foldSelectInst(cast<SelectInst>(I));
623 /// \brief Builder for the alloca slices.
625 /// This class builds a set of alloca slices by recursively visiting the uses
626 /// of an alloca and making a slice for each load and store at each offset.
627 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
628 friend class PtrUseVisitor<SliceBuilder>;
629 friend class InstVisitor<SliceBuilder>;
630 typedef PtrUseVisitor<SliceBuilder> Base;
632 const uint64_t AllocSize;
635 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
636 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
638 /// \brief Set to de-duplicate dead instructions found in the use walk.
639 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
642 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
643 : PtrUseVisitor<SliceBuilder>(DL),
644 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
647 void markAsDead(Instruction &I) {
648 if (VisitedDeadInsts.insert(&I).second)
649 AS.DeadUsers.push_back(&I);
652 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
653 bool IsSplittable = false) {
654 // Completely skip uses which have a zero size or start either before or
655 // past the end of the allocation.
656 if (Size == 0 || Offset.uge(AllocSize)) {
657 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
658 << " which has zero size or starts outside of the "
659 << AllocSize << " byte alloca:\n"
660 << " alloca: " << AS.AI << "\n"
661 << " use: " << I << "\n");
662 return markAsDead(I);
665 uint64_t BeginOffset = Offset.getZExtValue();
666 uint64_t EndOffset = BeginOffset + Size;
668 // Clamp the end offset to the end of the allocation. Note that this is
669 // formulated to handle even the case where "BeginOffset + Size" overflows.
670 // This may appear superficially to be something we could ignore entirely,
671 // but that is not so! There may be widened loads or PHI-node uses where
672 // some instructions are dead but not others. We can't completely ignore
673 // them, and so have to record at least the information here.
674 assert(AllocSize >= BeginOffset); // Established above.
675 if (Size > AllocSize - BeginOffset) {
676 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
677 << " to remain within the " << AllocSize << " byte alloca:\n"
678 << " alloca: " << AS.AI << "\n"
679 << " use: " << I << "\n");
680 EndOffset = AllocSize;
683 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
686 void visitBitCastInst(BitCastInst &BC) {
688 return markAsDead(BC);
690 return Base::visitBitCastInst(BC);
693 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
694 if (GEPI.use_empty())
695 return markAsDead(GEPI);
697 if (SROAStrictInbounds && GEPI.isInBounds()) {
698 // FIXME: This is a manually un-factored variant of the basic code inside
699 // of GEPs with checking of the inbounds invariant specified in the
700 // langref in a very strict sense. If we ever want to enable
701 // SROAStrictInbounds, this code should be factored cleanly into
702 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
703 // by writing out the code here where we have tho underlying allocation
704 // size readily available.
705 APInt GEPOffset = Offset;
706 for (gep_type_iterator GTI = gep_type_begin(GEPI),
707 GTE = gep_type_end(GEPI);
709 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
713 // Handle a struct index, which adds its field offset to the pointer.
714 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
715 unsigned ElementIdx = OpC->getZExtValue();
716 const StructLayout *SL = DL.getStructLayout(STy);
718 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
720 // For array or vector indices, scale the index by the size of the
722 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
723 GEPOffset += Index * APInt(Offset.getBitWidth(),
724 DL.getTypeAllocSize(GTI.getIndexedType()));
727 // If this index has computed an intermediate pointer which is not
728 // inbounds, then the result of the GEP is a poison value and we can
729 // delete it and all uses.
730 if (GEPOffset.ugt(AllocSize))
731 return markAsDead(GEPI);
735 return Base::visitGetElementPtrInst(GEPI);
738 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
739 uint64_t Size, bool IsVolatile) {
740 // We allow splitting of loads and stores where the type is an integer type
741 // and cover the entire alloca. This prevents us from splitting over
743 // FIXME: In the great blue eventually, we should eagerly split all integer
744 // loads and stores, and then have a separate step that merges adjacent
745 // alloca partitions into a single partition suitable for integer widening.
746 // Or we should skip the merge step and rely on GVN and other passes to
747 // merge adjacent loads and stores that survive mem2reg.
749 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
751 insertUse(I, Offset, Size, IsSplittable);
754 void visitLoadInst(LoadInst &LI) {
755 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
756 "All simple FCA loads should have been pre-split");
759 return PI.setAborted(&LI);
761 uint64_t Size = DL.getTypeStoreSize(LI.getType());
762 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
765 void visitStoreInst(StoreInst &SI) {
766 Value *ValOp = SI.getValueOperand();
768 return PI.setEscapedAndAborted(&SI);
770 return PI.setAborted(&SI);
772 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
774 // If this memory access can be shown to *statically* extend outside the
775 // bounds of of the allocation, it's behavior is undefined, so simply
776 // ignore it. Note that this is more strict than the generic clamping
777 // behavior of insertUse. We also try to handle cases which might run the
779 // FIXME: We should instead consider the pointer to have escaped if this
780 // function is being instrumented for addressing bugs or race conditions.
781 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
782 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
783 << " which extends past the end of the " << AllocSize
785 << " alloca: " << AS.AI << "\n"
786 << " use: " << SI << "\n");
787 return markAsDead(SI);
790 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
791 "All simple FCA stores should have been pre-split");
792 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
795 void visitMemSetInst(MemSetInst &II) {
796 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
797 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
798 if ((Length && Length->getValue() == 0) ||
799 (IsOffsetKnown && Offset.uge(AllocSize)))
800 // Zero-length mem transfer intrinsics can be ignored entirely.
801 return markAsDead(II);
804 return PI.setAborted(&II);
806 insertUse(II, Offset, Length ? Length->getLimitedValue()
807 : AllocSize - Offset.getLimitedValue(),
811 void visitMemTransferInst(MemTransferInst &II) {
812 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
813 if (Length && Length->getValue() == 0)
814 // Zero-length mem transfer intrinsics can be ignored entirely.
815 return markAsDead(II);
817 // Because we can visit these intrinsics twice, also check to see if the
818 // first time marked this instruction as dead. If so, skip it.
819 if (VisitedDeadInsts.count(&II))
823 return PI.setAborted(&II);
825 // This side of the transfer is completely out-of-bounds, and so we can
826 // nuke the entire transfer. However, we also need to nuke the other side
827 // if already added to our partitions.
828 // FIXME: Yet another place we really should bypass this when
829 // instrumenting for ASan.
830 if (Offset.uge(AllocSize)) {
831 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
832 MemTransferSliceMap.find(&II);
833 if (MTPI != MemTransferSliceMap.end())
834 AS.Slices[MTPI->second].kill();
835 return markAsDead(II);
838 uint64_t RawOffset = Offset.getLimitedValue();
839 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
841 // Check for the special case where the same exact value is used for both
843 if (*U == II.getRawDest() && *U == II.getRawSource()) {
844 // For non-volatile transfers this is a no-op.
845 if (!II.isVolatile())
846 return markAsDead(II);
848 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
851 // If we have seen both source and destination for a mem transfer, then
852 // they both point to the same alloca.
854 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
855 std::tie(MTPI, Inserted) =
856 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
857 unsigned PrevIdx = MTPI->second;
859 Slice &PrevP = AS.Slices[PrevIdx];
861 // Check if the begin offsets match and this is a non-volatile transfer.
862 // In that case, we can completely elide the transfer.
863 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
865 return markAsDead(II);
868 // Otherwise we have an offset transfer within the same alloca. We can't
870 PrevP.makeUnsplittable();
873 // Insert the use now that we've fixed up the splittable nature.
874 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
876 // Check that we ended up with a valid index in the map.
877 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
878 "Map index doesn't point back to a slice with this user.");
881 // Disable SRoA for any intrinsics except for lifetime invariants.
882 // FIXME: What about debug intrinsics? This matches old behavior, but
883 // doesn't make sense.
884 void visitIntrinsicInst(IntrinsicInst &II) {
886 return PI.setAborted(&II);
888 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
889 II.getIntrinsicID() == Intrinsic::lifetime_end) {
890 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
891 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
892 Length->getLimitedValue());
893 insertUse(II, Offset, Size, true);
897 Base::visitIntrinsicInst(II);
900 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
901 // We consider any PHI or select that results in a direct load or store of
902 // the same offset to be a viable use for slicing purposes. These uses
903 // are considered unsplittable and the size is the maximum loaded or stored
905 SmallPtrSet<Instruction *, 4> Visited;
906 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
907 Visited.insert(Root);
908 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
909 // If there are no loads or stores, the access is dead. We mark that as
910 // a size zero access.
913 Instruction *I, *UsedI;
914 std::tie(UsedI, I) = Uses.pop_back_val();
916 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
917 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
920 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
921 Value *Op = SI->getOperand(0);
924 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
928 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
929 if (!GEP->hasAllZeroIndices())
931 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
932 !isa<SelectInst>(I)) {
936 for (User *U : I->users())
937 if (Visited.insert(cast<Instruction>(U)).second)
938 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
939 } while (!Uses.empty());
944 void visitPHINodeOrSelectInst(Instruction &I) {
945 assert(isa<PHINode>(I) || isa<SelectInst>(I));
947 return markAsDead(I);
949 // TODO: We could use SimplifyInstruction here to fold PHINodes and
950 // SelectInsts. However, doing so requires to change the current
951 // dead-operand-tracking mechanism. For instance, suppose neither loading
952 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
953 // trap either. However, if we simply replace %U with undef using the
954 // current dead-operand-tracking mechanism, "load (select undef, undef,
955 // %other)" may trap because the select may return the first operand
957 if (Value *Result = foldPHINodeOrSelectInst(I)) {
959 // If the result of the constant fold will be the pointer, recurse
960 // through the PHI/select as if we had RAUW'ed it.
963 // Otherwise the operand to the PHI/select is dead, and we can replace
965 AS.DeadOperands.push_back(U);
971 return PI.setAborted(&I);
973 // See if we already have computed info on this node.
974 uint64_t &Size = PHIOrSelectSizes[&I];
976 // This is a new PHI/Select, check for an unsafe use of it.
977 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
978 return PI.setAborted(UnsafeI);
981 // For PHI and select operands outside the alloca, we can't nuke the entire
982 // phi or select -- the other side might still be relevant, so we special
983 // case them here and use a separate structure to track the operands
984 // themselves which should be replaced with undef.
985 // FIXME: This should instead be escaped in the event we're instrumenting
986 // for address sanitization.
987 if (Offset.uge(AllocSize)) {
988 AS.DeadOperands.push_back(U);
992 insertUse(I, Offset, Size);
995 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
997 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
999 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
1000 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
1003 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
1005 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1008 PointerEscapingInstr(nullptr) {
1009 SliceBuilder PB(DL, AI, *this);
1010 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1011 if (PtrI.isEscaped() || PtrI.isAborted()) {
1012 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1013 // possibly by just storing the PtrInfo in the AllocaSlices.
1014 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1015 : PtrI.getAbortingInst();
1016 assert(PointerEscapingInstr && "Did not track a bad instruction");
1020 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
1021 [](const Slice &S) {
1026 #if __cplusplus >= 201103L && !defined(NDEBUG)
1027 if (SROARandomShuffleSlices) {
1028 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
1029 std::shuffle(Slices.begin(), Slices.end(), MT);
1033 // Sort the uses. This arranges for the offsets to be in ascending order,
1034 // and the sizes to be in descending order.
1035 std::sort(Slices.begin(), Slices.end());
1038 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1040 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1041 StringRef Indent) const {
1042 printSlice(OS, I, Indent);
1044 printUse(OS, I, Indent);
1047 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1048 StringRef Indent) const {
1049 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
1050 << " slice #" << (I - begin())
1051 << (I->isSplittable() ? " (splittable)" : "");
1054 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1055 StringRef Indent) const {
1056 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
1059 void AllocaSlices::print(raw_ostream &OS) const {
1060 if (PointerEscapingInstr) {
1061 OS << "Can't analyze slices for alloca: " << AI << "\n"
1062 << " A pointer to this alloca escaped by:\n"
1063 << " " << *PointerEscapingInstr << "\n";
1067 OS << "Slices of alloca: " << AI << "\n";
1068 for (const_iterator I = begin(), E = end(); I != E; ++I)
1072 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1075 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
1077 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1080 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1082 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1083 /// the loads and stores of an alloca instruction, as well as updating its
1084 /// debug information. This is used when a domtree is unavailable and thus
1085 /// mem2reg in its full form can't be used to handle promotion of allocas to
1087 class AllocaPromoter : public LoadAndStorePromoter {
1091 SmallVector<DbgDeclareInst *, 4> DDIs;
1092 SmallVector<DbgValueInst *, 4> DVIs;
1095 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
1096 AllocaInst &AI, DIBuilder &DIB)
1097 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1099 void run(const SmallVectorImpl<Instruction *> &Insts) {
1100 // Retain the debug information attached to the alloca for use when
1101 // rewriting loads and stores.
1102 if (auto *L = LocalAsMetadata::getIfExists(&AI)) {
1103 if (auto *DebugNode = MetadataAsValue::getIfExists(AI.getContext(), L)) {
1104 for (User *U : DebugNode->users())
1105 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1106 DDIs.push_back(DDI);
1107 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1108 DVIs.push_back(DVI);
1112 LoadAndStorePromoter::run(Insts);
1114 // While we have the debug information, clear it off of the alloca. The
1115 // caller takes care of deleting the alloca.
1116 while (!DDIs.empty())
1117 DDIs.pop_back_val()->eraseFromParent();
1118 while (!DVIs.empty())
1119 DVIs.pop_back_val()->eraseFromParent();
1123 isInstInList(Instruction *I,
1124 const SmallVectorImpl<Instruction *> &Insts) const override {
1126 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1127 Ptr = LI->getOperand(0);
1129 Ptr = cast<StoreInst>(I)->getPointerOperand();
1131 // Only used to detect cycles, which will be rare and quickly found as
1132 // we're walking up a chain of defs rather than down through uses.
1133 SmallPtrSet<Value *, 4> Visited;
1139 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
1140 Ptr = BCI->getOperand(0);
1141 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
1142 Ptr = GEPI->getPointerOperand();
1146 } while (Visited.insert(Ptr).second);
1151 void updateDebugInfo(Instruction *Inst) const override {
1152 for (DbgDeclareInst *DDI : DDIs)
1153 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1154 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1155 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1156 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1157 for (DbgValueInst *DVI : DVIs) {
1158 Value *Arg = nullptr;
1159 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1160 // If an argument is zero extended then use argument directly. The ZExt
1161 // may be zapped by an optimization pass in future.
1162 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1163 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1164 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1165 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1167 Arg = SI->getValueOperand();
1168 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1169 Arg = LI->getPointerOperand();
1173 Instruction *DbgVal =
1174 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1175 DIExpression(DVI->getExpression()), Inst);
1176 DbgVal->setDebugLoc(DVI->getDebugLoc());
1180 } // end anon namespace
1183 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1185 /// This pass takes allocations which can be completely analyzed (that is, they
1186 /// don't escape) and tries to turn them into scalar SSA values. There are
1187 /// a few steps to this process.
1189 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1190 /// are used to try to split them into smaller allocations, ideally of
1191 /// a single scalar data type. It will split up memcpy and memset accesses
1192 /// as necessary and try to isolate individual scalar accesses.
1193 /// 2) It will transform accesses into forms which are suitable for SSA value
1194 /// promotion. This can be replacing a memset with a scalar store of an
1195 /// integer value, or it can involve speculating operations on a PHI or
1196 /// select to be a PHI or select of the results.
1197 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1198 /// onto insert and extract operations on a vector value, and convert them to
1199 /// this form. By doing so, it will enable promotion of vector aggregates to
1200 /// SSA vector values.
1201 class SROA : public FunctionPass {
1202 const bool RequiresDomTree;
1205 const DataLayout *DL;
1207 AssumptionTracker *AT;
1209 /// \brief Worklist of alloca instructions to simplify.
1211 /// Each alloca in the function is added to this. Each new alloca formed gets
1212 /// added to it as well to recursively simplify unless that alloca can be
1213 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1214 /// the one being actively rewritten, we add it back onto the list if not
1215 /// already present to ensure it is re-visited.
1216 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> Worklist;
1218 /// \brief A collection of instructions to delete.
1219 /// We try to batch deletions to simplify code and make things a bit more
1221 SetVector<Instruction *, SmallVector<Instruction *, 8>> DeadInsts;
1223 /// \brief Post-promotion worklist.
1225 /// Sometimes we discover an alloca which has a high probability of becoming
1226 /// viable for SROA after a round of promotion takes place. In those cases,
1227 /// the alloca is enqueued here for re-processing.
1229 /// Note that we have to be very careful to clear allocas out of this list in
1230 /// the event they are deleted.
1231 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> PostPromotionWorklist;
1233 /// \brief A collection of alloca instructions we can directly promote.
1234 std::vector<AllocaInst *> PromotableAllocas;
1236 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
1238 /// All of these PHIs have been checked for the safety of speculation and by
1239 /// being speculated will allow promoting allocas currently in the promotable
1241 SetVector<PHINode *, SmallVector<PHINode *, 2>> SpeculatablePHIs;
1243 /// \brief A worklist of select instructions to speculate prior to promoting
1246 /// All of these select instructions have been checked for the safety of
1247 /// speculation and by being speculated will allow promoting allocas
1248 /// currently in the promotable queue.
1249 SetVector<SelectInst *, SmallVector<SelectInst *, 2>> SpeculatableSelects;
1252 SROA(bool RequiresDomTree = true)
1253 : FunctionPass(ID), RequiresDomTree(RequiresDomTree), C(nullptr),
1254 DL(nullptr), DT(nullptr) {
1255 initializeSROAPass(*PassRegistry::getPassRegistry());
1257 bool runOnFunction(Function &F) override;
1258 void getAnalysisUsage(AnalysisUsage &AU) const override;
1260 const char *getPassName() const override { return "SROA"; }
1264 friend class PHIOrSelectSpeculator;
1265 friend class AllocaSliceRewriter;
1267 bool presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS);
1268 bool rewritePartition(AllocaInst &AI, AllocaSlices &AS,
1269 AllocaSlices::Partition &P);
1270 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
1271 bool runOnAlloca(AllocaInst &AI);
1272 void clobberUse(Use &U);
1273 void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
1274 bool promoteAllocas(Function &F);
1280 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1281 return new SROA(RequiresDomTree);
1284 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1286 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
1287 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1288 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1291 /// Walk the range of a partitioning looking for a common type to cover this
1292 /// sequence of slices.
1293 static Type *findCommonType(AllocaSlices::const_iterator B,
1294 AllocaSlices::const_iterator E,
1295 uint64_t EndOffset) {
1297 bool TyIsCommon = true;
1298 IntegerType *ITy = nullptr;
1300 // Note that we need to look at *every* alloca slice's Use to ensure we
1301 // always get consistent results regardless of the order of slices.
1302 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1303 Use *U = I->getUse();
1304 if (isa<IntrinsicInst>(*U->getUser()))
1306 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1309 Type *UserTy = nullptr;
1310 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1311 UserTy = LI->getType();
1312 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1313 UserTy = SI->getValueOperand()->getType();
1316 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1317 // If the type is larger than the partition, skip it. We only encounter
1318 // this for split integer operations where we want to use the type of the
1319 // entity causing the split. Also skip if the type is not a byte width
1321 if (UserITy->getBitWidth() % 8 != 0 ||
1322 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1325 // Track the largest bitwidth integer type used in this way in case there
1326 // is no common type.
1327 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1331 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1332 // depend on types skipped above.
1333 if (!UserTy || (Ty && Ty != UserTy))
1334 TyIsCommon = false; // Give up on anything but an iN type.
1339 return TyIsCommon ? Ty : ITy;
1342 /// PHI instructions that use an alloca and are subsequently loaded can be
1343 /// rewritten to load both input pointers in the pred blocks and then PHI the
1344 /// results, allowing the load of the alloca to be promoted.
1346 /// %P2 = phi [i32* %Alloca, i32* %Other]
1347 /// %V = load i32* %P2
1349 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1351 /// %V2 = load i32* %Other
1353 /// %V = phi [i32 %V1, i32 %V2]
1355 /// We can do this to a select if its only uses are loads and if the operands
1356 /// to the select can be loaded unconditionally.
1358 /// FIXME: This should be hoisted into a generic utility, likely in
1359 /// Transforms/Util/Local.h
1360 static bool isSafePHIToSpeculate(PHINode &PN, const DataLayout *DL = nullptr) {
1361 // For now, we can only do this promotion if the load is in the same block
1362 // as the PHI, and if there are no stores between the phi and load.
1363 // TODO: Allow recursive phi users.
1364 // TODO: Allow stores.
1365 BasicBlock *BB = PN.getParent();
1366 unsigned MaxAlign = 0;
1367 bool HaveLoad = false;
1368 for (User *U : PN.users()) {
1369 LoadInst *LI = dyn_cast<LoadInst>(U);
1370 if (!LI || !LI->isSimple())
1373 // For now we only allow loads in the same block as the PHI. This is
1374 // a common case that happens when instcombine merges two loads through
1376 if (LI->getParent() != BB)
1379 // Ensure that there are no instructions between the PHI and the load that
1381 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1382 if (BBI->mayWriteToMemory())
1385 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1392 // We can only transform this if it is safe to push the loads into the
1393 // predecessor blocks. The only thing to watch out for is that we can't put
1394 // a possibly trapping load in the predecessor if it is a critical edge.
1395 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1396 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1397 Value *InVal = PN.getIncomingValue(Idx);
1399 // If the value is produced by the terminator of the predecessor (an
1400 // invoke) or it has side-effects, there is no valid place to put a load
1401 // in the predecessor.
1402 if (TI == InVal || TI->mayHaveSideEffects())
1405 // If the predecessor has a single successor, then the edge isn't
1407 if (TI->getNumSuccessors() == 1)
1410 // If this pointer is always safe to load, or if we can prove that there
1411 // is already a load in the block, then we can move the load to the pred
1413 if (InVal->isDereferenceablePointer(DL) ||
1414 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
1423 static void speculatePHINodeLoads(PHINode &PN) {
1424 DEBUG(dbgs() << " original: " << PN << "\n");
1426 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1427 IRBuilderTy PHIBuilder(&PN);
1428 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1429 PN.getName() + ".sroa.speculated");
1431 // Get the AA tags and alignment to use from one of the loads. It doesn't
1432 // matter which one we get and if any differ.
1433 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1436 SomeLoad->getAAMetadata(AATags);
1437 unsigned Align = SomeLoad->getAlignment();
1439 // Rewrite all loads of the PN to use the new PHI.
1440 while (!PN.use_empty()) {
1441 LoadInst *LI = cast<LoadInst>(PN.user_back());
1442 LI->replaceAllUsesWith(NewPN);
1443 LI->eraseFromParent();
1446 // Inject loads into all of the pred blocks.
1447 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1448 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1449 TerminatorInst *TI = Pred->getTerminator();
1450 Value *InVal = PN.getIncomingValue(Idx);
1451 IRBuilderTy PredBuilder(TI);
1453 LoadInst *Load = PredBuilder.CreateLoad(
1454 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1455 ++NumLoadsSpeculated;
1456 Load->setAlignment(Align);
1458 Load->setAAMetadata(AATags);
1459 NewPN->addIncoming(Load, Pred);
1462 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1463 PN.eraseFromParent();
1466 /// Select instructions that use an alloca and are subsequently loaded can be
1467 /// rewritten to load both input pointers and then select between the result,
1468 /// allowing the load of the alloca to be promoted.
1470 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1471 /// %V = load i32* %P2
1473 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1474 /// %V2 = load i32* %Other
1475 /// %V = select i1 %cond, i32 %V1, i32 %V2
1477 /// We can do this to a select if its only uses are loads and if the operand
1478 /// to the select can be loaded unconditionally.
1479 static bool isSafeSelectToSpeculate(SelectInst &SI,
1480 const DataLayout *DL = nullptr) {
1481 Value *TValue = SI.getTrueValue();
1482 Value *FValue = SI.getFalseValue();
1483 bool TDerefable = TValue->isDereferenceablePointer(DL);
1484 bool FDerefable = FValue->isDereferenceablePointer(DL);
1486 for (User *U : SI.users()) {
1487 LoadInst *LI = dyn_cast<LoadInst>(U);
1488 if (!LI || !LI->isSimple())
1491 // Both operands to the select need to be dereferencable, either
1492 // absolutely (e.g. allocas) or at this point because we can see other
1495 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
1498 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
1505 static void speculateSelectInstLoads(SelectInst &SI) {
1506 DEBUG(dbgs() << " original: " << SI << "\n");
1508 IRBuilderTy IRB(&SI);
1509 Value *TV = SI.getTrueValue();
1510 Value *FV = SI.getFalseValue();
1511 // Replace the loads of the select with a select of two loads.
1512 while (!SI.use_empty()) {
1513 LoadInst *LI = cast<LoadInst>(SI.user_back());
1514 assert(LI->isSimple() && "We only speculate simple loads");
1516 IRB.SetInsertPoint(LI);
1518 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1520 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1521 NumLoadsSpeculated += 2;
1523 // Transfer alignment and AA info if present.
1524 TL->setAlignment(LI->getAlignment());
1525 FL->setAlignment(LI->getAlignment());
1528 LI->getAAMetadata(Tags);
1530 TL->setAAMetadata(Tags);
1531 FL->setAAMetadata(Tags);
1534 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1535 LI->getName() + ".sroa.speculated");
1537 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1538 LI->replaceAllUsesWith(V);
1539 LI->eraseFromParent();
1541 SI.eraseFromParent();
1544 /// \brief Build a GEP out of a base pointer and indices.
1546 /// This will return the BasePtr if that is valid, or build a new GEP
1547 /// instruction using the IRBuilder if GEP-ing is needed.
1548 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1549 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
1550 if (Indices.empty())
1553 // A single zero index is a no-op, so check for this and avoid building a GEP
1555 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1558 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
1561 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1562 /// TargetTy without changing the offset of the pointer.
1564 /// This routine assumes we've already established a properly offset GEP with
1565 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1566 /// zero-indices down through type layers until we find one the same as
1567 /// TargetTy. If we can't find one with the same type, we at least try to use
1568 /// one with the same size. If none of that works, we just produce the GEP as
1569 /// indicated by Indices to have the correct offset.
1570 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1571 Value *BasePtr, Type *Ty, Type *TargetTy,
1572 SmallVectorImpl<Value *> &Indices,
1575 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1577 // Pointer size to use for the indices.
1578 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1580 // See if we can descend into a struct and locate a field with the correct
1582 unsigned NumLayers = 0;
1583 Type *ElementTy = Ty;
1585 if (ElementTy->isPointerTy())
1588 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1589 ElementTy = ArrayTy->getElementType();
1590 Indices.push_back(IRB.getIntN(PtrSize, 0));
1591 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1592 ElementTy = VectorTy->getElementType();
1593 Indices.push_back(IRB.getInt32(0));
1594 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1595 if (STy->element_begin() == STy->element_end())
1596 break; // Nothing left to descend into.
1597 ElementTy = *STy->element_begin();
1598 Indices.push_back(IRB.getInt32(0));
1603 } while (ElementTy != TargetTy);
1604 if (ElementTy != TargetTy)
1605 Indices.erase(Indices.end() - NumLayers, Indices.end());
1607 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1610 /// \brief Recursively compute indices for a natural GEP.
1612 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1613 /// element types adding appropriate indices for the GEP.
1614 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1615 Value *Ptr, Type *Ty, APInt &Offset,
1617 SmallVectorImpl<Value *> &Indices,
1620 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1623 // We can't recurse through pointer types.
1624 if (Ty->isPointerTy())
1627 // We try to analyze GEPs over vectors here, but note that these GEPs are
1628 // extremely poorly defined currently. The long-term goal is to remove GEPing
1629 // over a vector from the IR completely.
1630 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1631 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1632 if (ElementSizeInBits % 8 != 0) {
1633 // GEPs over non-multiple of 8 size vector elements are invalid.
1636 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1637 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1638 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1640 Offset -= NumSkippedElements * ElementSize;
1641 Indices.push_back(IRB.getInt(NumSkippedElements));
1642 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1643 Offset, TargetTy, Indices, NamePrefix);
1646 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1647 Type *ElementTy = ArrTy->getElementType();
1648 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1649 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1650 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1653 Offset -= NumSkippedElements * ElementSize;
1654 Indices.push_back(IRB.getInt(NumSkippedElements));
1655 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1656 Indices, NamePrefix);
1659 StructType *STy = dyn_cast<StructType>(Ty);
1663 const StructLayout *SL = DL.getStructLayout(STy);
1664 uint64_t StructOffset = Offset.getZExtValue();
1665 if (StructOffset >= SL->getSizeInBytes())
1667 unsigned Index = SL->getElementContainingOffset(StructOffset);
1668 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1669 Type *ElementTy = STy->getElementType(Index);
1670 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1671 return nullptr; // The offset points into alignment padding.
1673 Indices.push_back(IRB.getInt32(Index));
1674 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1675 Indices, NamePrefix);
1678 /// \brief Get a natural GEP from a base pointer to a particular offset and
1679 /// resulting in a particular type.
1681 /// The goal is to produce a "natural" looking GEP that works with the existing
1682 /// composite types to arrive at the appropriate offset and element type for
1683 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1684 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1685 /// Indices, and setting Ty to the result subtype.
1687 /// If no natural GEP can be constructed, this function returns null.
1688 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1689 Value *Ptr, APInt Offset, Type *TargetTy,
1690 SmallVectorImpl<Value *> &Indices,
1692 PointerType *Ty = cast<PointerType>(Ptr->getType());
1694 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1696 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
1699 Type *ElementTy = Ty->getElementType();
1700 if (!ElementTy->isSized())
1701 return nullptr; // We can't GEP through an unsized element.
1702 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1703 if (ElementSize == 0)
1704 return nullptr; // Zero-length arrays can't help us build a natural GEP.
1705 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1707 Offset -= NumSkippedElements * ElementSize;
1708 Indices.push_back(IRB.getInt(NumSkippedElements));
1709 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1710 Indices, NamePrefix);
1713 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1714 /// resulting pointer has PointerTy.
1716 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1717 /// and produces the pointer type desired. Where it cannot, it will try to use
1718 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1719 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1720 /// bitcast to the type.
1722 /// The strategy for finding the more natural GEPs is to peel off layers of the
1723 /// pointer, walking back through bit casts and GEPs, searching for a base
1724 /// pointer from which we can compute a natural GEP with the desired
1725 /// properties. The algorithm tries to fold as many constant indices into
1726 /// a single GEP as possible, thus making each GEP more independent of the
1727 /// surrounding code.
1728 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1729 APInt Offset, Type *PointerTy, Twine NamePrefix) {
1730 // Even though we don't look through PHI nodes, we could be called on an
1731 // instruction in an unreachable block, which may be on a cycle.
1732 SmallPtrSet<Value *, 4> Visited;
1733 Visited.insert(Ptr);
1734 SmallVector<Value *, 4> Indices;
1736 // We may end up computing an offset pointer that has the wrong type. If we
1737 // never are able to compute one directly that has the correct type, we'll
1738 // fall back to it, so keep it around here.
1739 Value *OffsetPtr = nullptr;
1741 // Remember any i8 pointer we come across to re-use if we need to do a raw
1743 Value *Int8Ptr = nullptr;
1744 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1746 Type *TargetTy = PointerTy->getPointerElementType();
1749 // First fold any existing GEPs into the offset.
1750 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1751 APInt GEPOffset(Offset.getBitWidth(), 0);
1752 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1754 Offset += GEPOffset;
1755 Ptr = GEP->getPointerOperand();
1756 if (!Visited.insert(Ptr).second)
1760 // See if we can perform a natural GEP here.
1762 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1763 Indices, NamePrefix)) {
1764 if (P->getType() == PointerTy) {
1765 // Zap any offset pointer that we ended up computing in previous rounds.
1766 if (OffsetPtr && OffsetPtr->use_empty())
1767 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1768 I->eraseFromParent();
1776 // Stash this pointer if we've found an i8*.
1777 if (Ptr->getType()->isIntegerTy(8)) {
1779 Int8PtrOffset = Offset;
1782 // Peel off a layer of the pointer and update the offset appropriately.
1783 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1784 Ptr = cast<Operator>(Ptr)->getOperand(0);
1785 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1786 if (GA->mayBeOverridden())
1788 Ptr = GA->getAliasee();
1792 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1793 } while (Visited.insert(Ptr).second);
1797 Int8Ptr = IRB.CreateBitCast(
1798 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1799 NamePrefix + "sroa_raw_cast");
1800 Int8PtrOffset = Offset;
1803 OffsetPtr = Int8PtrOffset == 0
1805 : IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1806 NamePrefix + "sroa_raw_idx");
1810 // On the off chance we were targeting i8*, guard the bitcast here.
1811 if (Ptr->getType() != PointerTy)
1812 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
1817 /// \brief Compute the adjusted alignment for a load or store from an offset.
1818 static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1819 const DataLayout &DL) {
1822 if (auto *LI = dyn_cast<LoadInst>(I)) {
1823 Alignment = LI->getAlignment();
1825 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1826 Alignment = SI->getAlignment();
1827 Ty = SI->getValueOperand()->getType();
1829 llvm_unreachable("Only loads and stores are allowed!");
1833 Alignment = DL.getABITypeAlignment(Ty);
1835 return MinAlign(Alignment, Offset);
1838 /// \brief Test whether we can convert a value from the old to the new type.
1840 /// This predicate should be used to guard calls to convertValue in order to
1841 /// ensure that we only try to convert viable values. The strategy is that we
1842 /// will peel off single element struct and array wrappings to get to an
1843 /// underlying value, and convert that value.
1844 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1847 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1848 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1849 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1851 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1853 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1856 // We can convert pointers to integers and vice-versa. Same for vectors
1857 // of pointers and integers.
1858 OldTy = OldTy->getScalarType();
1859 NewTy = NewTy->getScalarType();
1860 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1861 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1863 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1871 /// \brief Generic routine to convert an SSA value to a value of a different
1874 /// This will try various different casting techniques, such as bitcasts,
1875 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1876 /// two types for viability with this routine.
1877 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1879 Type *OldTy = V->getType();
1880 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1885 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1886 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1887 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1888 return IRB.CreateZExt(V, NewITy);
1890 // See if we need inttoptr for this type pair. A cast involving both scalars
1891 // and vectors requires and additional bitcast.
1892 if (OldTy->getScalarType()->isIntegerTy() &&
1893 NewTy->getScalarType()->isPointerTy()) {
1894 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1895 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1896 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1899 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1900 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1901 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1904 return IRB.CreateIntToPtr(V, NewTy);
1907 // See if we need ptrtoint for this type pair. A cast involving both scalars
1908 // and vectors requires and additional bitcast.
1909 if (OldTy->getScalarType()->isPointerTy() &&
1910 NewTy->getScalarType()->isIntegerTy()) {
1911 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1912 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1913 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1916 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1917 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1918 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1921 return IRB.CreatePtrToInt(V, NewTy);
1924 return IRB.CreateBitCast(V, NewTy);
1927 /// \brief Test whether the given slice use can be promoted to a vector.
1929 /// This function is called to test each entry in a partioning which is slated
1930 /// for a single slice.
1931 static bool isVectorPromotionViableForSlice(AllocaSlices::Partition &P,
1932 const Slice &S, VectorType *Ty,
1933 uint64_t ElementSize,
1934 const DataLayout &DL) {
1935 // First validate the slice offsets.
1936 uint64_t BeginOffset =
1937 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
1938 uint64_t BeginIndex = BeginOffset / ElementSize;
1939 if (BeginIndex * ElementSize != BeginOffset ||
1940 BeginIndex >= Ty->getNumElements())
1942 uint64_t EndOffset =
1943 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
1944 uint64_t EndIndex = EndOffset / ElementSize;
1945 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1948 assert(EndIndex > BeginIndex && "Empty vector!");
1949 uint64_t NumElements = EndIndex - BeginIndex;
1950 Type *SliceTy = (NumElements == 1)
1951 ? Ty->getElementType()
1952 : VectorType::get(Ty->getElementType(), NumElements);
1955 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1957 Use *U = S.getUse();
1959 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1960 if (MI->isVolatile())
1962 if (!S.isSplittable())
1963 return false; // Skip any unsplittable intrinsics.
1964 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1965 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1966 II->getIntrinsicID() != Intrinsic::lifetime_end)
1968 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1969 // Disable vector promotion when there are loads or stores of an FCA.
1971 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1972 if (LI->isVolatile())
1974 Type *LTy = LI->getType();
1975 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1976 assert(LTy->isIntegerTy());
1979 if (!canConvertValue(DL, SliceTy, LTy))
1981 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1982 if (SI->isVolatile())
1984 Type *STy = SI->getValueOperand()->getType();
1985 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1986 assert(STy->isIntegerTy());
1989 if (!canConvertValue(DL, STy, SliceTy))
1998 /// \brief Test whether the given alloca partitioning and range of slices can be
1999 /// promoted to a vector.
2001 /// This is a quick test to check whether we can rewrite a particular alloca
2002 /// partition (and its newly formed alloca) into a vector alloca with only
2003 /// whole-vector loads and stores such that it could be promoted to a vector
2004 /// SSA value. We only can ensure this for a limited set of operations, and we
2005 /// don't want to do the rewrites unless we are confident that the result will
2006 /// be promotable, so we have an early test here.
2007 static VectorType *isVectorPromotionViable(AllocaSlices::Partition &P,
2008 const DataLayout &DL) {
2009 // Collect the candidate types for vector-based promotion. Also track whether
2010 // we have different element types.
2011 SmallVector<VectorType *, 4> CandidateTys;
2012 Type *CommonEltTy = nullptr;
2013 bool HaveCommonEltTy = true;
2014 auto CheckCandidateType = [&](Type *Ty) {
2015 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
2016 CandidateTys.push_back(VTy);
2018 CommonEltTy = VTy->getElementType();
2019 else if (CommonEltTy != VTy->getElementType())
2020 HaveCommonEltTy = false;
2023 // Consider any loads or stores that are the exact size of the slice.
2024 for (const Slice &S : P)
2025 if (S.beginOffset() == P.beginOffset() &&
2026 S.endOffset() == P.endOffset()) {
2027 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
2028 CheckCandidateType(LI->getType());
2029 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
2030 CheckCandidateType(SI->getValueOperand()->getType());
2033 // If we didn't find a vector type, nothing to do here.
2034 if (CandidateTys.empty())
2037 // Remove non-integer vector types if we had multiple common element types.
2038 // FIXME: It'd be nice to replace them with integer vector types, but we can't
2039 // do that until all the backends are known to produce good code for all
2040 // integer vector types.
2041 if (!HaveCommonEltTy) {
2042 CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
2043 [](VectorType *VTy) {
2044 return !VTy->getElementType()->isIntegerTy();
2046 CandidateTys.end());
2048 // If there were no integer vector types, give up.
2049 if (CandidateTys.empty())
2052 // Rank the remaining candidate vector types. This is easy because we know
2053 // they're all integer vectors. We sort by ascending number of elements.
2054 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
2055 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
2056 "Cannot have vector types of different sizes!");
2057 assert(RHSTy->getElementType()->isIntegerTy() &&
2058 "All non-integer types eliminated!");
2059 assert(LHSTy->getElementType()->isIntegerTy() &&
2060 "All non-integer types eliminated!");
2061 return RHSTy->getNumElements() < LHSTy->getNumElements();
2063 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
2065 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
2066 CandidateTys.end());
2068 // The only way to have the same element type in every vector type is to
2069 // have the same vector type. Check that and remove all but one.
2071 for (VectorType *VTy : CandidateTys) {
2072 assert(VTy->getElementType() == CommonEltTy &&
2073 "Unaccounted for element type!");
2074 assert(VTy == CandidateTys[0] &&
2075 "Different vector types with the same element type!");
2078 CandidateTys.resize(1);
2081 // Try each vector type, and return the one which works.
2082 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
2083 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
2085 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2086 // that aren't byte sized.
2087 if (ElementSize % 8)
2089 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
2090 "vector size not a multiple of element size?");
2093 for (const Slice &S : P)
2094 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
2097 for (const Slice *S : P.splitSliceTails())
2098 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
2103 for (VectorType *VTy : CandidateTys)
2104 if (CheckVectorTypeForPromotion(VTy))
2110 /// \brief Test whether a slice of an alloca is valid for integer widening.
2112 /// This implements the necessary checking for the \c isIntegerWideningViable
2113 /// test below on a single slice of the alloca.
2114 static bool isIntegerWideningViableForSlice(const Slice &S,
2115 uint64_t AllocBeginOffset,
2117 const DataLayout &DL,
2118 bool &WholeAllocaOp) {
2119 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
2121 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2122 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
2124 // We can't reasonably handle cases where the load or store extends past
2125 // the end of the aloca's type and into its padding.
2129 Use *U = S.getUse();
2131 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2132 if (LI->isVolatile())
2134 // Note that we don't count vector loads or stores as whole-alloca
2135 // operations which enable integer widening because we would prefer to use
2136 // vector widening instead.
2137 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
2138 WholeAllocaOp = true;
2139 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2140 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
2142 } else if (RelBegin != 0 || RelEnd != Size ||
2143 !canConvertValue(DL, AllocaTy, LI->getType())) {
2144 // Non-integer loads need to be convertible from the alloca type so that
2145 // they are promotable.
2148 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2149 Type *ValueTy = SI->getValueOperand()->getType();
2150 if (SI->isVolatile())
2152 // Note that we don't count vector loads or stores as whole-alloca
2153 // operations which enable integer widening because we would prefer to use
2154 // vector widening instead.
2155 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
2156 WholeAllocaOp = true;
2157 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2158 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
2160 } else if (RelBegin != 0 || RelEnd != Size ||
2161 !canConvertValue(DL, ValueTy, AllocaTy)) {
2162 // Non-integer stores need to be convertible to the alloca type so that
2163 // they are promotable.
2166 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2167 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2169 if (!S.isSplittable())
2170 return false; // Skip any unsplittable intrinsics.
2171 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2172 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2173 II->getIntrinsicID() != Intrinsic::lifetime_end)
2182 /// \brief Test whether the given alloca partition's integer operations can be
2183 /// widened to promotable ones.
2185 /// This is a quick test to check whether we can rewrite the integer loads and
2186 /// stores to a particular alloca into wider loads and stores and be able to
2187 /// promote the resulting alloca.
2188 static bool isIntegerWideningViable(AllocaSlices::Partition &P, Type *AllocaTy,
2189 const DataLayout &DL) {
2190 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
2191 // Don't create integer types larger than the maximum bitwidth.
2192 if (SizeInBits > IntegerType::MAX_INT_BITS)
2195 // Don't try to handle allocas with bit-padding.
2196 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
2199 // We need to ensure that an integer type with the appropriate bitwidth can
2200 // be converted to the alloca type, whatever that is. We don't want to force
2201 // the alloca itself to have an integer type if there is a more suitable one.
2202 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2203 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2204 !canConvertValue(DL, IntTy, AllocaTy))
2207 // While examining uses, we ensure that the alloca has a covering load or
2208 // store. We don't want to widen the integer operations only to fail to
2209 // promote due to some other unsplittable entry (which we may make splittable
2210 // later). However, if there are only splittable uses, go ahead and assume
2211 // that we cover the alloca.
2212 // FIXME: We shouldn't consider split slices that happen to start in the
2213 // partition here...
2214 bool WholeAllocaOp =
2215 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
2217 for (const Slice &S : P)
2218 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2222 for (const Slice *S : P.splitSliceTails())
2223 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2227 return WholeAllocaOp;
2230 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2231 IntegerType *Ty, uint64_t Offset,
2232 const Twine &Name) {
2233 DEBUG(dbgs() << " start: " << *V << "\n");
2234 IntegerType *IntTy = cast<IntegerType>(V->getType());
2235 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2236 "Element extends past full value");
2237 uint64_t ShAmt = 8 * Offset;
2238 if (DL.isBigEndian())
2239 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2241 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2242 DEBUG(dbgs() << " shifted: " << *V << "\n");
2244 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2245 "Cannot extract to a larger integer!");
2247 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2248 DEBUG(dbgs() << " trunced: " << *V << "\n");
2253 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2254 Value *V, uint64_t Offset, const Twine &Name) {
2255 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2256 IntegerType *Ty = cast<IntegerType>(V->getType());
2257 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2258 "Cannot insert a larger integer!");
2259 DEBUG(dbgs() << " start: " << *V << "\n");
2261 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2262 DEBUG(dbgs() << " extended: " << *V << "\n");
2264 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2265 "Element store outside of alloca store");
2266 uint64_t ShAmt = 8 * Offset;
2267 if (DL.isBigEndian())
2268 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2270 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2271 DEBUG(dbgs() << " shifted: " << *V << "\n");
2274 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2275 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2276 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2277 DEBUG(dbgs() << " masked: " << *Old << "\n");
2278 V = IRB.CreateOr(Old, V, Name + ".insert");
2279 DEBUG(dbgs() << " inserted: " << *V << "\n");
2284 static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2285 unsigned EndIndex, const Twine &Name) {
2286 VectorType *VecTy = cast<VectorType>(V->getType());
2287 unsigned NumElements = EndIndex - BeginIndex;
2288 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2290 if (NumElements == VecTy->getNumElements())
2293 if (NumElements == 1) {
2294 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2296 DEBUG(dbgs() << " extract: " << *V << "\n");
2300 SmallVector<Constant *, 8> Mask;
2301 Mask.reserve(NumElements);
2302 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2303 Mask.push_back(IRB.getInt32(i));
2304 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2305 ConstantVector::get(Mask), Name + ".extract");
2306 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2310 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2311 unsigned BeginIndex, const Twine &Name) {
2312 VectorType *VecTy = cast<VectorType>(Old->getType());
2313 assert(VecTy && "Can only insert a vector into a vector");
2315 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2317 // Single element to insert.
2318 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2320 DEBUG(dbgs() << " insert: " << *V << "\n");
2324 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2325 "Too many elements!");
2326 if (Ty->getNumElements() == VecTy->getNumElements()) {
2327 assert(V->getType() == VecTy && "Vector type mismatch");
2330 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2332 // When inserting a smaller vector into the larger to store, we first
2333 // use a shuffle vector to widen it with undef elements, and then
2334 // a second shuffle vector to select between the loaded vector and the
2336 SmallVector<Constant *, 8> Mask;
2337 Mask.reserve(VecTy->getNumElements());
2338 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2339 if (i >= BeginIndex && i < EndIndex)
2340 Mask.push_back(IRB.getInt32(i - BeginIndex));
2342 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2343 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2344 ConstantVector::get(Mask), Name + ".expand");
2345 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2348 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2349 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2351 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2353 DEBUG(dbgs() << " blend: " << *V << "\n");
2358 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
2359 /// to use a new alloca.
2361 /// Also implements the rewriting to vector-based accesses when the partition
2362 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2364 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
2365 // Befriend the base class so it can delegate to private visit methods.
2366 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2367 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
2369 const DataLayout &DL;
2372 AllocaInst &OldAI, &NewAI;
2373 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2376 // This is a convenience and flag variable that will be null unless the new
2377 // alloca's integer operations should be widened to this integer type due to
2378 // passing isIntegerWideningViable above. If it is non-null, the desired
2379 // integer type will be stored here for easy access during rewriting.
2382 // If we are rewriting an alloca partition which can be written as pure
2383 // vector operations, we stash extra information here. When VecTy is
2384 // non-null, we have some strict guarantees about the rewritten alloca:
2385 // - The new alloca is exactly the size of the vector type here.
2386 // - The accesses all either map to the entire vector or to a single
2388 // - The set of accessing instructions is only one of those handled above
2389 // in isVectorPromotionViable. Generally these are the same access kinds
2390 // which are promotable via mem2reg.
2393 uint64_t ElementSize;
2395 // The original offset of the slice currently being rewritten relative to
2396 // the original alloca.
2397 uint64_t BeginOffset, EndOffset;
2398 // The new offsets of the slice currently being rewritten relative to the
2400 uint64_t NewBeginOffset, NewEndOffset;
2406 Instruction *OldPtr;
2408 // Track post-rewrite users which are PHI nodes and Selects.
2409 SmallPtrSetImpl<PHINode *> &PHIUsers;
2410 SmallPtrSetImpl<SelectInst *> &SelectUsers;
2412 // Utility IR builder, whose name prefix is setup for each visited use, and
2413 // the insertion point is set to point to the user.
2417 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2418 AllocaInst &OldAI, AllocaInst &NewAI,
2419 uint64_t NewAllocaBeginOffset,
2420 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2421 VectorType *PromotableVecTy,
2422 SmallPtrSetImpl<PHINode *> &PHIUsers,
2423 SmallPtrSetImpl<SelectInst *> &SelectUsers)
2424 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2425 NewAllocaBeginOffset(NewAllocaBeginOffset),
2426 NewAllocaEndOffset(NewAllocaEndOffset),
2427 NewAllocaTy(NewAI.getAllocatedType()),
2428 IntTy(IsIntegerPromotable
2431 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2433 VecTy(PromotableVecTy),
2434 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2435 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2436 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
2437 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2438 IRB(NewAI.getContext(), ConstantFolder()) {
2440 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
2441 "Only multiple-of-8 sized vector elements are viable");
2444 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2447 bool visit(AllocaSlices::const_iterator I) {
2448 bool CanSROA = true;
2449 BeginOffset = I->beginOffset();
2450 EndOffset = I->endOffset();
2451 IsSplittable = I->isSplittable();
2453 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2454 DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2455 DEBUG(AS.printSlice(dbgs(), I, ""));
2456 DEBUG(dbgs() << "\n");
2458 // Compute the intersecting offset range.
2459 assert(BeginOffset < NewAllocaEndOffset);
2460 assert(EndOffset > NewAllocaBeginOffset);
2461 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2462 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2464 SliceSize = NewEndOffset - NewBeginOffset;
2466 OldUse = I->getUse();
2467 OldPtr = cast<Instruction>(OldUse->get());
2469 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2470 IRB.SetInsertPoint(OldUserI);
2471 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2472 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2474 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2481 // Make sure the other visit overloads are visible.
2484 // Every instruction which can end up as a user must have a rewrite rule.
2485 bool visitInstruction(Instruction &I) {
2486 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2487 llvm_unreachable("No rewrite rule for this instruction!");
2490 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2491 // Note that the offset computation can use BeginOffset or NewBeginOffset
2492 // interchangeably for unsplit slices.
2493 assert(IsSplit || BeginOffset == NewBeginOffset);
2494 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2497 StringRef OldName = OldPtr->getName();
2498 // Skip through the last '.sroa.' component of the name.
2499 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2500 if (LastSROAPrefix != StringRef::npos) {
2501 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2502 // Look for an SROA slice index.
2503 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2504 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2505 // Strip the index and look for the offset.
2506 OldName = OldName.substr(IndexEnd + 1);
2507 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2508 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2509 // Strip the offset.
2510 OldName = OldName.substr(OffsetEnd + 1);
2513 // Strip any SROA suffixes as well.
2514 OldName = OldName.substr(0, OldName.find(".sroa_"));
2517 return getAdjustedPtr(IRB, DL, &NewAI,
2518 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
2520 Twine(OldName) + "."
2527 /// \brief Compute suitable alignment to access this slice of the *new*
2530 /// You can optionally pass a type to this routine and if that type's ABI
2531 /// alignment is itself suitable, this will return zero.
2532 unsigned getSliceAlign(Type *Ty = nullptr) {
2533 unsigned NewAIAlign = NewAI.getAlignment();
2535 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2537 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2538 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
2541 unsigned getIndex(uint64_t Offset) {
2542 assert(VecTy && "Can only call getIndex when rewriting a vector");
2543 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2544 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2545 uint32_t Index = RelOffset / ElementSize;
2546 assert(Index * ElementSize == RelOffset);
2550 void deleteIfTriviallyDead(Value *V) {
2551 Instruction *I = cast<Instruction>(V);
2552 if (isInstructionTriviallyDead(I))
2553 Pass.DeadInsts.insert(I);
2556 Value *rewriteVectorizedLoadInst() {
2557 unsigned BeginIndex = getIndex(NewBeginOffset);
2558 unsigned EndIndex = getIndex(NewEndOffset);
2559 assert(EndIndex > BeginIndex && "Empty vector!");
2561 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2562 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2565 Value *rewriteIntegerLoad(LoadInst &LI) {
2566 assert(IntTy && "We cannot insert an integer to the alloca");
2567 assert(!LI.isVolatile());
2568 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2569 V = convertValue(DL, IRB, V, IntTy);
2570 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2571 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2572 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
2573 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2578 bool visitLoadInst(LoadInst &LI) {
2579 DEBUG(dbgs() << " original: " << LI << "\n");
2580 Value *OldOp = LI.getOperand(0);
2581 assert(OldOp == OldPtr);
2583 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2585 bool IsPtrAdjusted = false;
2588 V = rewriteVectorizedLoadInst();
2589 } else if (IntTy && LI.getType()->isIntegerTy()) {
2590 V = rewriteIntegerLoad(LI);
2591 } else if (NewBeginOffset == NewAllocaBeginOffset &&
2592 canConvertValue(DL, NewAllocaTy, LI.getType())) {
2593 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), LI.isVolatile(),
2596 Type *LTy = TargetTy->getPointerTo();
2597 V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2598 getSliceAlign(TargetTy), LI.isVolatile(),
2600 IsPtrAdjusted = true;
2602 V = convertValue(DL, IRB, V, TargetTy);
2605 assert(!LI.isVolatile());
2606 assert(LI.getType()->isIntegerTy() &&
2607 "Only integer type loads and stores are split");
2608 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
2609 "Split load isn't smaller than original load");
2610 assert(LI.getType()->getIntegerBitWidth() ==
2611 DL.getTypeStoreSizeInBits(LI.getType()) &&
2612 "Non-byte-multiple bit width");
2613 // Move the insertion point just past the load so that we can refer to it.
2614 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
2615 // Create a placeholder value with the same type as LI to use as the
2616 // basis for the new value. This allows us to replace the uses of LI with
2617 // the computed value, and then replace the placeholder with LI, leaving
2618 // LI only used for this computation.
2619 Value *Placeholder =
2620 new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2621 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset, "insert");
2622 LI.replaceAllUsesWith(V);
2623 Placeholder->replaceAllUsesWith(&LI);
2626 LI.replaceAllUsesWith(V);
2629 Pass.DeadInsts.insert(&LI);
2630 deleteIfTriviallyDead(OldOp);
2631 DEBUG(dbgs() << " to: " << *V << "\n");
2632 return !LI.isVolatile() && !IsPtrAdjusted;
2635 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
2636 if (V->getType() != VecTy) {
2637 unsigned BeginIndex = getIndex(NewBeginOffset);
2638 unsigned EndIndex = getIndex(NewEndOffset);
2639 assert(EndIndex > BeginIndex && "Empty vector!");
2640 unsigned NumElements = EndIndex - BeginIndex;
2641 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2642 Type *SliceTy = (NumElements == 1)
2644 : VectorType::get(ElementTy, NumElements);
2645 if (V->getType() != SliceTy)
2646 V = convertValue(DL, IRB, V, SliceTy);
2648 // Mix in the existing elements.
2649 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2650 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2652 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2653 Pass.DeadInsts.insert(&SI);
2656 DEBUG(dbgs() << " to: " << *Store << "\n");
2660 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
2661 assert(IntTy && "We cannot extract an integer from the alloca");
2662 assert(!SI.isVolatile());
2663 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2665 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2666 Old = convertValue(DL, IRB, Old, IntTy);
2667 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2668 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2669 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
2671 V = convertValue(DL, IRB, V, NewAllocaTy);
2672 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2673 Pass.DeadInsts.insert(&SI);
2675 DEBUG(dbgs() << " to: " << *Store << "\n");
2679 bool visitStoreInst(StoreInst &SI) {
2680 DEBUG(dbgs() << " original: " << SI << "\n");
2681 Value *OldOp = SI.getOperand(1);
2682 assert(OldOp == OldPtr);
2684 Value *V = SI.getValueOperand();
2686 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2687 // alloca that should be re-examined after promoting this alloca.
2688 if (V->getType()->isPointerTy())
2689 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2690 Pass.PostPromotionWorklist.insert(AI);
2692 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
2693 assert(!SI.isVolatile());
2694 assert(V->getType()->isIntegerTy() &&
2695 "Only integer type loads and stores are split");
2696 assert(V->getType()->getIntegerBitWidth() ==
2697 DL.getTypeStoreSizeInBits(V->getType()) &&
2698 "Non-byte-multiple bit width");
2699 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2700 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset, "extract");
2704 return rewriteVectorizedStoreInst(V, SI, OldOp);
2705 if (IntTy && V->getType()->isIntegerTy())
2706 return rewriteIntegerStore(V, SI);
2709 if (NewBeginOffset == NewAllocaBeginOffset &&
2710 NewEndOffset == NewAllocaEndOffset &&
2711 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2712 V = convertValue(DL, IRB, V, NewAllocaTy);
2713 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2716 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
2717 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2721 Pass.DeadInsts.insert(&SI);
2722 deleteIfTriviallyDead(OldOp);
2724 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2725 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2728 /// \brief Compute an integer value from splatting an i8 across the given
2729 /// number of bytes.
2731 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2732 /// call this routine.
2733 /// FIXME: Heed the advice above.
2735 /// \param V The i8 value to splat.
2736 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2737 Value *getIntegerSplat(Value *V, unsigned Size) {
2738 assert(Size > 0 && "Expected a positive number of bytes.");
2739 IntegerType *VTy = cast<IntegerType>(V->getType());
2740 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2744 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2746 IRB.CreateZExt(V, SplatIntTy, "zext"),
2747 ConstantExpr::getUDiv(
2748 Constant::getAllOnesValue(SplatIntTy),
2749 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2755 /// \brief Compute a vector splat for a given element value.
2756 Value *getVectorSplat(Value *V, unsigned NumElements) {
2757 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2758 DEBUG(dbgs() << " splat: " << *V << "\n");
2762 bool visitMemSetInst(MemSetInst &II) {
2763 DEBUG(dbgs() << " original: " << II << "\n");
2764 assert(II.getRawDest() == OldPtr);
2766 // If the memset has a variable size, it cannot be split, just adjust the
2767 // pointer to the new alloca.
2768 if (!isa<Constant>(II.getLength())) {
2770 assert(NewBeginOffset == BeginOffset);
2771 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2772 Type *CstTy = II.getAlignmentCst()->getType();
2773 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
2775 deleteIfTriviallyDead(OldPtr);
2779 // Record this instruction for deletion.
2780 Pass.DeadInsts.insert(&II);
2782 Type *AllocaTy = NewAI.getAllocatedType();
2783 Type *ScalarTy = AllocaTy->getScalarType();
2785 // If this doesn't map cleanly onto the alloca type, and that type isn't
2786 // a single value type, just emit a memset.
2787 if (!VecTy && !IntTy &&
2788 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2789 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
2790 !AllocaTy->isSingleValueType() ||
2791 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2792 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
2793 Type *SizeTy = II.getLength()->getType();
2794 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2795 CallInst *New = IRB.CreateMemSet(
2796 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2797 getSliceAlign(), II.isVolatile());
2799 DEBUG(dbgs() << " to: " << *New << "\n");
2803 // If we can represent this as a simple value, we have to build the actual
2804 // value to store, which requires expanding the byte present in memset to
2805 // a sensible representation for the alloca type. This is essentially
2806 // splatting the byte to a sufficiently wide integer, splatting it across
2807 // any desired vector width, and bitcasting to the final type.
2811 // If this is a memset of a vectorized alloca, insert it.
2812 assert(ElementTy == ScalarTy);
2814 unsigned BeginIndex = getIndex(NewBeginOffset);
2815 unsigned EndIndex = getIndex(NewEndOffset);
2816 assert(EndIndex > BeginIndex && "Empty vector!");
2817 unsigned NumElements = EndIndex - BeginIndex;
2818 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2821 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2822 Splat = convertValue(DL, IRB, Splat, ElementTy);
2823 if (NumElements > 1)
2824 Splat = getVectorSplat(Splat, NumElements);
2827 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2828 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2830 // If this is a memset on an alloca where we can widen stores, insert the
2832 assert(!II.isVolatile());
2834 uint64_t Size = NewEndOffset - NewBeginOffset;
2835 V = getIntegerSplat(II.getValue(), Size);
2837 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2838 EndOffset != NewAllocaBeginOffset)) {
2840 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2841 Old = convertValue(DL, IRB, Old, IntTy);
2842 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2843 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2845 assert(V->getType() == IntTy &&
2846 "Wrong type for an alloca wide integer!");
2848 V = convertValue(DL, IRB, V, AllocaTy);
2850 // Established these invariants above.
2851 assert(NewBeginOffset == NewAllocaBeginOffset);
2852 assert(NewEndOffset == NewAllocaEndOffset);
2854 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2855 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2856 V = getVectorSplat(V, AllocaVecTy->getNumElements());
2858 V = convertValue(DL, IRB, V, AllocaTy);
2861 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2864 DEBUG(dbgs() << " to: " << *New << "\n");
2865 return !II.isVolatile();
2868 bool visitMemTransferInst(MemTransferInst &II) {
2869 // Rewriting of memory transfer instructions can be a bit tricky. We break
2870 // them into two categories: split intrinsics and unsplit intrinsics.
2872 DEBUG(dbgs() << " original: " << II << "\n");
2874 bool IsDest = &II.getRawDestUse() == OldUse;
2875 assert((IsDest && II.getRawDest() == OldPtr) ||
2876 (!IsDest && II.getRawSource() == OldPtr));
2878 unsigned SliceAlign = getSliceAlign();
2880 // For unsplit intrinsics, we simply modify the source and destination
2881 // pointers in place. This isn't just an optimization, it is a matter of
2882 // correctness. With unsplit intrinsics we may be dealing with transfers
2883 // within a single alloca before SROA ran, or with transfers that have
2884 // a variable length. We may also be dealing with memmove instead of
2885 // memcpy, and so simply updating the pointers is the necessary for us to
2886 // update both source and dest of a single call.
2887 if (!IsSplittable) {
2888 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2890 II.setDest(AdjustedPtr);
2892 II.setSource(AdjustedPtr);
2894 if (II.getAlignment() > SliceAlign) {
2895 Type *CstTy = II.getAlignmentCst()->getType();
2897 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
2900 DEBUG(dbgs() << " to: " << II << "\n");
2901 deleteIfTriviallyDead(OldPtr);
2904 // For split transfer intrinsics we have an incredibly useful assurance:
2905 // the source and destination do not reside within the same alloca, and at
2906 // least one of them does not escape. This means that we can replace
2907 // memmove with memcpy, and we don't need to worry about all manner of
2908 // downsides to splitting and transforming the operations.
2910 // If this doesn't map cleanly onto the alloca type, and that type isn't
2911 // a single value type, just emit a memcpy.
2914 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2915 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2916 !NewAI.getAllocatedType()->isSingleValueType());
2918 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2919 // size hasn't been shrunk based on analysis of the viable range, this is
2921 if (EmitMemCpy && &OldAI == &NewAI) {
2922 // Ensure the start lines up.
2923 assert(NewBeginOffset == BeginOffset);
2925 // Rewrite the size as needed.
2926 if (NewEndOffset != EndOffset)
2927 II.setLength(ConstantInt::get(II.getLength()->getType(),
2928 NewEndOffset - NewBeginOffset));
2931 // Record this instruction for deletion.
2932 Pass.DeadInsts.insert(&II);
2934 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2935 // alloca that should be re-examined after rewriting this instruction.
2936 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2937 if (AllocaInst *AI =
2938 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2939 assert(AI != &OldAI && AI != &NewAI &&
2940 "Splittable transfers cannot reach the same alloca on both ends.");
2941 Pass.Worklist.insert(AI);
2944 Type *OtherPtrTy = OtherPtr->getType();
2945 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2947 // Compute the relative offset for the other pointer within the transfer.
2948 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
2949 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2950 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2951 OtherOffset.zextOrTrunc(64).getZExtValue());
2954 // Compute the other pointer, folding as much as possible to produce
2955 // a single, simple GEP in most cases.
2956 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2957 OtherPtr->getName() + ".");
2959 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2960 Type *SizeTy = II.getLength()->getType();
2961 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2963 CallInst *New = IRB.CreateMemCpy(
2964 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2965 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
2967 DEBUG(dbgs() << " to: " << *New << "\n");
2971 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2972 NewEndOffset == NewAllocaEndOffset;
2973 uint64_t Size = NewEndOffset - NewBeginOffset;
2974 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2975 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2976 unsigned NumElements = EndIndex - BeginIndex;
2977 IntegerType *SubIntTy =
2978 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
2980 // Reset the other pointer type to match the register type we're going to
2981 // use, but using the address space of the original other pointer.
2982 if (VecTy && !IsWholeAlloca) {
2983 if (NumElements == 1)
2984 OtherPtrTy = VecTy->getElementType();
2986 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2988 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
2989 } else if (IntTy && !IsWholeAlloca) {
2990 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2992 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
2995 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2996 OtherPtr->getName() + ".");
2997 unsigned SrcAlign = OtherAlign;
2998 Value *DstPtr = &NewAI;
2999 unsigned DstAlign = SliceAlign;
3001 std::swap(SrcPtr, DstPtr);
3002 std::swap(SrcAlign, DstAlign);
3006 if (VecTy && !IsWholeAlloca && !IsDest) {
3007 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
3008 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
3009 } else if (IntTy && !IsWholeAlloca && !IsDest) {
3010 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
3011 Src = convertValue(DL, IRB, Src, IntTy);
3012 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3013 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
3016 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
3019 if (VecTy && !IsWholeAlloca && IsDest) {
3021 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
3022 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
3023 } else if (IntTy && !IsWholeAlloca && IsDest) {
3025 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
3026 Old = convertValue(DL, IRB, Old, IntTy);
3027 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3028 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3029 Src = convertValue(DL, IRB, Src, NewAllocaTy);
3032 StoreInst *Store = cast<StoreInst>(
3033 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
3035 DEBUG(dbgs() << " to: " << *Store << "\n");
3036 return !II.isVolatile();
3039 bool visitIntrinsicInst(IntrinsicInst &II) {
3040 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
3041 II.getIntrinsicID() == Intrinsic::lifetime_end);
3042 DEBUG(dbgs() << " original: " << II << "\n");
3043 assert(II.getArgOperand(1) == OldPtr);
3045 // Record this instruction for deletion.
3046 Pass.DeadInsts.insert(&II);
3049 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
3050 NewEndOffset - NewBeginOffset);
3051 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3053 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3054 New = IRB.CreateLifetimeStart(Ptr, Size);
3056 New = IRB.CreateLifetimeEnd(Ptr, Size);
3059 DEBUG(dbgs() << " to: " << *New << "\n");
3063 bool visitPHINode(PHINode &PN) {
3064 DEBUG(dbgs() << " original: " << PN << "\n");
3065 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3066 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
3068 // We would like to compute a new pointer in only one place, but have it be
3069 // as local as possible to the PHI. To do that, we re-use the location of
3070 // the old pointer, which necessarily must be in the right position to
3071 // dominate the PHI.
3072 IRBuilderTy PtrBuilder(IRB);
3073 if (isa<PHINode>(OldPtr))
3074 PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
3076 PtrBuilder.SetInsertPoint(OldPtr);
3077 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
3079 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
3080 // Replace the operands which were using the old pointer.
3081 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3083 DEBUG(dbgs() << " to: " << PN << "\n");
3084 deleteIfTriviallyDead(OldPtr);
3086 // PHIs can't be promoted on their own, but often can be speculated. We
3087 // check the speculation outside of the rewriter so that we see the
3088 // fully-rewritten alloca.
3089 PHIUsers.insert(&PN);
3093 bool visitSelectInst(SelectInst &SI) {
3094 DEBUG(dbgs() << " original: " << SI << "\n");
3095 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3096 "Pointer isn't an operand!");
3097 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3098 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
3100 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3101 // Replace the operands which were using the old pointer.
3102 if (SI.getOperand(1) == OldPtr)
3103 SI.setOperand(1, NewPtr);
3104 if (SI.getOperand(2) == OldPtr)
3105 SI.setOperand(2, NewPtr);
3107 DEBUG(dbgs() << " to: " << SI << "\n");
3108 deleteIfTriviallyDead(OldPtr);
3110 // Selects can't be promoted on their own, but often can be speculated. We
3111 // check the speculation outside of the rewriter so that we see the
3112 // fully-rewritten alloca.
3113 SelectUsers.insert(&SI);
3120 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
3122 /// This pass aggressively rewrites all aggregate loads and stores on
3123 /// a particular pointer (or any pointer derived from it which we can identify)
3124 /// with scalar loads and stores.
3125 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3126 // Befriend the base class so it can delegate to private visit methods.
3127 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3129 const DataLayout &DL;
3131 /// Queue of pointer uses to analyze and potentially rewrite.
3132 SmallVector<Use *, 8> Queue;
3134 /// Set to prevent us from cycling with phi nodes and loops.
3135 SmallPtrSet<User *, 8> Visited;
3137 /// The current pointer use being rewritten. This is used to dig up the used
3138 /// value (as opposed to the user).
3142 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
3144 /// Rewrite loads and stores through a pointer and all pointers derived from
3146 bool rewrite(Instruction &I) {
3147 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3149 bool Changed = false;
3150 while (!Queue.empty()) {
3151 U = Queue.pop_back_val();
3152 Changed |= visit(cast<Instruction>(U->getUser()));
3158 /// Enqueue all the users of the given instruction for further processing.
3159 /// This uses a set to de-duplicate users.
3160 void enqueueUsers(Instruction &I) {
3161 for (Use &U : I.uses())
3162 if (Visited.insert(U.getUser()).second)
3163 Queue.push_back(&U);
3166 // Conservative default is to not rewrite anything.
3167 bool visitInstruction(Instruction &I) { return false; }
3169 /// \brief Generic recursive split emission class.
3170 template <typename Derived> class OpSplitter {
3172 /// The builder used to form new instructions.
3174 /// The indices which to be used with insert- or extractvalue to select the
3175 /// appropriate value within the aggregate.
3176 SmallVector<unsigned, 4> Indices;
3177 /// The indices to a GEP instruction which will move Ptr to the correct slot
3178 /// within the aggregate.
3179 SmallVector<Value *, 4> GEPIndices;
3180 /// The base pointer of the original op, used as a base for GEPing the
3181 /// split operations.
3184 /// Initialize the splitter with an insertion point, Ptr and start with a
3185 /// single zero GEP index.
3186 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
3187 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3190 /// \brief Generic recursive split emission routine.
3192 /// This method recursively splits an aggregate op (load or store) into
3193 /// scalar or vector ops. It splits recursively until it hits a single value
3194 /// and emits that single value operation via the template argument.
3196 /// The logic of this routine relies on GEPs and insertvalue and
3197 /// extractvalue all operating with the same fundamental index list, merely
3198 /// formatted differently (GEPs need actual values).
3200 /// \param Ty The type being split recursively into smaller ops.
3201 /// \param Agg The aggregate value being built up or stored, depending on
3202 /// whether this is splitting a load or a store respectively.
3203 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3204 if (Ty->isSingleValueType())
3205 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
3207 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3208 unsigned OldSize = Indices.size();
3210 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3212 assert(Indices.size() == OldSize && "Did not return to the old size");
3213 Indices.push_back(Idx);
3214 GEPIndices.push_back(IRB.getInt32(Idx));
3215 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3216 GEPIndices.pop_back();
3222 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3223 unsigned OldSize = Indices.size();
3225 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3227 assert(Indices.size() == OldSize && "Did not return to the old size");
3228 Indices.push_back(Idx);
3229 GEPIndices.push_back(IRB.getInt32(Idx));
3230 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3231 GEPIndices.pop_back();
3237 llvm_unreachable("Only arrays and structs are aggregate loadable types");
3241 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3242 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3243 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
3245 /// Emit a leaf load of a single value. This is called at the leaves of the
3246 /// recursive emission to actually load values.
3247 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3248 assert(Ty->isSingleValueType());
3249 // Load the single value and insert it using the indices.
3250 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
3251 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
3252 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3253 DEBUG(dbgs() << " to: " << *Load << "\n");
3257 bool visitLoadInst(LoadInst &LI) {
3258 assert(LI.getPointerOperand() == *U);
3259 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3262 // We have an aggregate being loaded, split it apart.
3263 DEBUG(dbgs() << " original: " << LI << "\n");
3264 LoadOpSplitter Splitter(&LI, *U);
3265 Value *V = UndefValue::get(LI.getType());
3266 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3267 LI.replaceAllUsesWith(V);
3268 LI.eraseFromParent();
3272 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
3273 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3274 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
3276 /// Emit a leaf store of a single value. This is called at the leaves of the
3277 /// recursive emission to actually produce stores.
3278 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3279 assert(Ty->isSingleValueType());
3280 // Extract the single value and store it using the indices.
3281 Value *Store = IRB.CreateStore(
3282 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3283 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3285 DEBUG(dbgs() << " to: " << *Store << "\n");
3289 bool visitStoreInst(StoreInst &SI) {
3290 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3292 Value *V = SI.getValueOperand();
3293 if (V->getType()->isSingleValueType())
3296 // We have an aggregate being stored, split it apart.
3297 DEBUG(dbgs() << " original: " << SI << "\n");
3298 StoreOpSplitter Splitter(&SI, *U);
3299 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3300 SI.eraseFromParent();
3304 bool visitBitCastInst(BitCastInst &BC) {
3309 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3314 bool visitPHINode(PHINode &PN) {
3319 bool visitSelectInst(SelectInst &SI) {
3326 /// \brief Strip aggregate type wrapping.
3328 /// This removes no-op aggregate types wrapping an underlying type. It will
3329 /// strip as many layers of types as it can without changing either the type
3330 /// size or the allocated size.
3331 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3332 if (Ty->isSingleValueType())
3335 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3336 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3339 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3340 InnerTy = ArrTy->getElementType();
3341 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3342 const StructLayout *SL = DL.getStructLayout(STy);
3343 unsigned Index = SL->getElementContainingOffset(0);
3344 InnerTy = STy->getElementType(Index);
3349 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3350 TypeSize > DL.getTypeSizeInBits(InnerTy))
3353 return stripAggregateTypeWrapping(DL, InnerTy);
3356 /// \brief Try to find a partition of the aggregate type passed in for a given
3357 /// offset and size.
3359 /// This recurses through the aggregate type and tries to compute a subtype
3360 /// based on the offset and size. When the offset and size span a sub-section
3361 /// of an array, it will even compute a new array type for that sub-section,
3362 /// and the same for structs.
3364 /// Note that this routine is very strict and tries to find a partition of the
3365 /// type which produces the *exact* right offset and size. It is not forgiving
3366 /// when the size or offset cause either end of type-based partition to be off.
3367 /// Also, this is a best-effort routine. It is reasonable to give up and not
3368 /// return a type if necessary.
3369 static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3371 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3372 return stripAggregateTypeWrapping(DL, Ty);
3373 if (Offset > DL.getTypeAllocSize(Ty) ||
3374 (DL.getTypeAllocSize(Ty) - Offset) < Size)
3377 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3378 // We can't partition pointers...
3379 if (SeqTy->isPointerTy())
3382 Type *ElementTy = SeqTy->getElementType();
3383 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3384 uint64_t NumSkippedElements = Offset / ElementSize;
3385 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
3386 if (NumSkippedElements >= ArrTy->getNumElements())
3388 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
3389 if (NumSkippedElements >= VecTy->getNumElements())
3392 Offset -= NumSkippedElements * ElementSize;
3394 // First check if we need to recurse.
3395 if (Offset > 0 || Size < ElementSize) {
3396 // Bail if the partition ends in a different array element.
3397 if ((Offset + Size) > ElementSize)
3399 // Recurse through the element type trying to peel off offset bytes.
3400 return getTypePartition(DL, ElementTy, Offset, Size);
3402 assert(Offset == 0);
3404 if (Size == ElementSize)
3405 return stripAggregateTypeWrapping(DL, ElementTy);
3406 assert(Size > ElementSize);
3407 uint64_t NumElements = Size / ElementSize;
3408 if (NumElements * ElementSize != Size)
3410 return ArrayType::get(ElementTy, NumElements);
3413 StructType *STy = dyn_cast<StructType>(Ty);
3417 const StructLayout *SL = DL.getStructLayout(STy);
3418 if (Offset >= SL->getSizeInBytes())
3420 uint64_t EndOffset = Offset + Size;
3421 if (EndOffset > SL->getSizeInBytes())
3424 unsigned Index = SL->getElementContainingOffset(Offset);
3425 Offset -= SL->getElementOffset(Index);
3427 Type *ElementTy = STy->getElementType(Index);
3428 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3429 if (Offset >= ElementSize)
3430 return nullptr; // The offset points into alignment padding.
3432 // See if any partition must be contained by the element.
3433 if (Offset > 0 || Size < ElementSize) {
3434 if ((Offset + Size) > ElementSize)
3436 return getTypePartition(DL, ElementTy, Offset, Size);
3438 assert(Offset == 0);
3440 if (Size == ElementSize)
3441 return stripAggregateTypeWrapping(DL, ElementTy);
3443 StructType::element_iterator EI = STy->element_begin() + Index,
3444 EE = STy->element_end();
3445 if (EndOffset < SL->getSizeInBytes()) {
3446 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3447 if (Index == EndIndex)
3448 return nullptr; // Within a single element and its padding.
3450 // Don't try to form "natural" types if the elements don't line up with the
3452 // FIXME: We could potentially recurse down through the last element in the
3453 // sub-struct to find a natural end point.
3454 if (SL->getElementOffset(EndIndex) != EndOffset)
3457 assert(Index < EndIndex);
3458 EE = STy->element_begin() + EndIndex;
3461 // Try to build up a sub-structure.
3463 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
3464 const StructLayout *SubSL = DL.getStructLayout(SubTy);
3465 if (Size != SubSL->getSizeInBytes())
3466 return nullptr; // The sub-struct doesn't have quite the size needed.
3471 /// \brief Pre-split loads and stores to simplify rewriting.
3473 /// We want to break up the splittable load+store pairs as much as
3474 /// possible. This is important to do as a preprocessing step, as once we
3475 /// start rewriting the accesses to partitions of the alloca we lose the
3476 /// necessary information to correctly split apart paired loads and stores
3477 /// which both point into this alloca. The case to consider is something like
3480 /// %a = alloca [12 x i8]
3481 /// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3482 /// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3483 /// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3484 /// %iptr1 = bitcast i8* %gep1 to i64*
3485 /// %iptr2 = bitcast i8* %gep2 to i64*
3486 /// %fptr1 = bitcast i8* %gep1 to float*
3487 /// %fptr2 = bitcast i8* %gep2 to float*
3488 /// %fptr3 = bitcast i8* %gep3 to float*
3489 /// store float 0.0, float* %fptr1
3490 /// store float 1.0, float* %fptr2
3491 /// %v = load i64* %iptr1
3492 /// store i64 %v, i64* %iptr2
3493 /// %f1 = load float* %fptr2
3494 /// %f2 = load float* %fptr3
3496 /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3497 /// promote everything so we recover the 2 SSA values that should have been
3498 /// there all along.
3500 /// \returns true if any changes are made.
3501 bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3502 DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3504 // Track the loads and stores which are candidates for pre-splitting here, in
3505 // the order they first appear during the partition scan. These give stable
3506 // iteration order and a basis for tracking which loads and stores we
3508 SmallVector<LoadInst *, 4> Loads;
3509 SmallVector<StoreInst *, 4> Stores;
3511 // We need to accumulate the splits required of each load or store where we
3512 // can find them via a direct lookup. This is important to cross-check loads
3513 // and stores against each other. We also track the slice so that we can kill
3514 // all the slices that end up split.
3515 struct SplitOffsets {
3517 std::vector<uint64_t> Splits;
3519 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3521 DEBUG(dbgs() << " Searching for candidate loads and stores\n");
3522 for (auto &P : AS.partitions()) {
3523 for (Slice &S : P) {
3524 if (!S.isSplittable())
3526 if (S.endOffset() <= P.endOffset())
3528 assert(P.endOffset() > S.beginOffset() &&
3529 "Empty or backwards partition!");
3531 // Determine if this is a pre-splittable slice.
3532 Instruction *I = cast<Instruction>(S.getUse()->getUser());
3533 if (auto *LI = dyn_cast<LoadInst>(I)) {
3534 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3536 // The load must be used exclusively to store into other pointers for
3537 // us to be able to arbitrarily pre-split it. The stores must also be
3538 // simple to avoid changing semantics.
3539 auto IsLoadSimplyStored = [](LoadInst *LI) {
3540 for (User *LU : LI->users()) {
3541 auto *SI = dyn_cast<StoreInst>(LU);
3542 if (!SI || !SI->isSimple())
3547 if (!IsLoadSimplyStored(LI))
3550 Loads.push_back(LI);
3551 } else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) {
3552 if (!SI || S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3554 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3555 if (!StoredLoad || !StoredLoad->isSimple())
3557 assert(!SI->isVolatile() && "Cannot split volatile stores!");
3559 Stores.push_back(SI);
3561 // Other uses cannot be pre-split.
3565 // Record the initial split.
3566 DEBUG(dbgs() << " Candidate: " << *I << "\n");
3567 auto &Offsets = SplitOffsetsMap[I];
3568 assert(Offsets.Splits.empty() &&
3569 "Should not have splits the first time we see an instruction!");
3571 Offsets.Splits.push_back(P.endOffset());
3574 // Now scan the already split slices, and add a split for any of them which
3575 // we're going to pre-split.
3576 for (Slice *S : P.splitSliceTails()) {
3577 auto SplitOffsetsMapI =
3578 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3579 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3581 auto &Offsets = SplitOffsetsMapI->second;
3583 assert(Offsets.S == S && "Found a mismatched slice!");
3584 assert(!Offsets.Splits.empty() &&
3585 "Cannot have an empty set of splits on the second partition!");
3586 assert(Offsets.Splits.back() == P.beginOffset() &&
3587 "Previous split does not end where this one begins!");
3589 // Record each split. The last partition's end isn't needed as the size
3590 // of the slice dictates that.
3591 if (S->endOffset() > P.endOffset())
3592 Offsets.Splits.push_back(P.endOffset());
3596 // We may have split loads where some of their stores are split stores. For
3597 // such loads and stores, we can only pre-split them if their splits exactly
3598 // match relative to their starting offset. We have to verify this prior to
3600 SmallPtrSet<LoadInst *, 4> BadSplitLoads;
3603 Stores.begin(), Stores.end(),
3604 [&BadSplitLoads, &SplitOffsetsMap](
3606 // Lookup the load we are storing in our map of split offsets.
3607 auto *LI = cast<LoadInst>(SI->getValueOperand());
3608 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3609 if (LoadOffsetsI == SplitOffsetsMap.end())
3610 return false; // Unrelated loads are always safe.
3611 auto &LoadOffsets = LoadOffsetsI->second;
3613 // Now lookup the store's offsets.
3614 auto &StoreOffsets = SplitOffsetsMap[SI];
3616 // If the relative offsets of each split in the load and store
3617 // match exactly, then we can split them and we don't need to
3618 // remove them here.
3619 if (LoadOffsets.Splits == StoreOffsets.Splits)
3622 DEBUG(dbgs() << " Mismatched splits for load and store:\n"
3623 << " " << *LI << "\n"
3624 << " " << *SI << "\n");
3626 // We've found a store and load that we need to split with
3627 // mismatched relative splits. Just give up on them and remove both
3628 // instructions from our list of candidates.
3629 BadSplitLoads.insert(LI);
3633 Loads.erase(std::remove_if(Loads.begin(), Loads.end(),
3634 [&BadSplitLoads](LoadInst *LI) {
3635 return BadSplitLoads.count(LI);
3639 // If no loads or stores are left, there is no pre-splitting to be done for
3641 if (Loads.empty() && Stores.empty())
3644 // From here on, we can't fail and will be building new accesses, so rig up
3646 IRBuilderTy IRB(&AI);
3648 // Collect the new slices which we will merge into the alloca slices.
3649 SmallVector<Slice, 4> NewSlices;
3651 // Track any allocas we end up splitting loads and stores for so we iterate
3653 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3655 // At this point, we have collected all of the loads and stores we can
3656 // pre-split, and the specific splits needed for them. We actually do the
3657 // splitting in a specific order in order to handle when one of the loads in
3658 // the value operand to one of the stores.
3660 // First, we rewrite all of the split loads, and just accumulate each split
3661 // load in a parallel structure. We also build the slices for them and append
3662 // them to the alloca slices.
3663 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3664 std::vector<LoadInst *> SplitLoads;
3665 for (LoadInst *LI : Loads) {
3668 IntegerType *Ty = cast<IntegerType>(LI->getType());
3669 uint64_t LoadSize = Ty->getBitWidth() / 8;
3670 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3672 auto &Offsets = SplitOffsetsMap[LI];
3673 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3674 "Slice size should always match load size exactly!");
3675 uint64_t BaseOffset = Offsets.S->beginOffset();
3676 assert(BaseOffset + LoadSize > BaseOffset &&
3677 "Cannot represent alloca access size using 64-bit integers!");
3679 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
3680 IRB.SetInsertPoint(BasicBlock::iterator(LI));
3682 DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
3684 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3685 int Idx = 0, Size = Offsets.Splits.size();
3687 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3688 auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3689 LoadInst *PLoad = IRB.CreateAlignedLoad(
3690 getAdjustedPtr(IRB, *DL, BasePtr,
3691 APInt(DL->getPointerSizeInBits(), PartOffset), PartPtrTy,
3692 BasePtr->getName() + "."),
3693 getAdjustedAlignment(LI, PartOffset, *DL), /*IsVolatile*/ false,
3696 // Append this load onto the list of split loads so we can find it later
3697 // to rewrite the stores.
3698 SplitLoads.push_back(PLoad);
3700 // Now build a new slice for the alloca.
3701 NewSlices.push_back(Slice(BaseOffset + PartOffset,
3702 BaseOffset + PartOffset + PartSize,
3703 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
3704 /*IsSplittable*/ true));
3705 DEBUG(AS.printSlice(dbgs(), std::prev(AS.end()), " "));
3706 DEBUG(dbgs() << ": " << *PLoad << "\n");
3708 // Setup the next partition.
3709 PartOffset = Offsets.Splits[Idx];
3713 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3716 // Now that we have the split loads, do the slow walk over all uses of the
3717 // load and rewrite them as split stores, or save the split loads to use
3718 // below if the store is going to be split there anyways.
3719 bool DeferredStores = false;
3720 for (User *LU : LI->users()) {
3721 StoreInst *SI = cast<StoreInst>(LU);
3722 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3723 DeferredStores = true;
3724 DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
3728 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3729 IRB.SetInsertPoint(BasicBlock::iterator(SI));
3731 DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
3733 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3734 LoadInst *PLoad = SplitLoads[Idx];
3735 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
3736 auto *PartPtrTy = PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
3738 StoreInst *PStore = IRB.CreateAlignedStore(
3739 PLoad, getAdjustedPtr(IRB, *DL, StoreBasePtr,
3740 APInt(DL->getPointerSizeInBits(), PartOffset),
3741 PartPtrTy, StoreBasePtr->getName() + "."),
3742 getAdjustedAlignment(SI, PartOffset, *DL), /*IsVolatile*/ false);
3744 DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
3747 // We want to immediately iterate on any allocas impacted by splitting
3748 // this store, and we have to track any promotable alloca (indicated by
3749 // a direct store) as needing to be resplit because it is no longer
3751 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3752 ResplitPromotableAllocas.insert(OtherAI);
3753 Worklist.insert(OtherAI);
3754 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3755 StoreBasePtr->stripInBoundsOffsets())) {
3756 Worklist.insert(OtherAI);
3759 // Mark the original store as dead.
3760 DeadInsts.insert(SI);
3763 // Save the split loads if there are deferred stores among the users.
3765 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3767 // Mark the original load as dead and kill the original slice.
3768 DeadInsts.insert(LI);
3772 // Second, we rewrite all of the split stores. At this point, we know that
3773 // all loads from this alloca have been split already. For stores of such
3774 // loads, we can simply look up the pre-existing split loads. For stores of
3775 // other loads, we split those loads first and then write split stores of
3777 for (StoreInst *SI : Stores) {
3778 auto *LI = cast<LoadInst>(SI->getValueOperand());
3779 IntegerType *Ty = cast<IntegerType>(LI->getType());
3780 uint64_t StoreSize = Ty->getBitWidth() / 8;
3781 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3783 auto &Offsets = SplitOffsetsMap[SI];
3784 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3785 "Slice size should always match load size exactly!");
3786 uint64_t BaseOffset = Offsets.S->beginOffset();
3787 assert(BaseOffset + StoreSize > BaseOffset &&
3788 "Cannot represent alloca access size using 64-bit integers!");
3790 Instruction *LoadBasePtr = cast<Instruction>(LI->getPointerOperand());
3791 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3793 DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
3795 // Check whether we have an already split load.
3796 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3797 std::vector<LoadInst *> *SplitLoads = nullptr;
3798 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3799 SplitLoads = &SplitLoadsMapI->second;
3800 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3801 "Too few split loads for the number of splits in the store!");
3803 DEBUG(dbgs() << " of load: " << *LI << "\n");
3807 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3808 int Idx = 0, Size = Offsets.Splits.size();
3810 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3811 auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
3813 // Either lookup a split load or create one.
3816 PLoad = (*SplitLoads)[Idx];
3818 IRB.SetInsertPoint(BasicBlock::iterator(LI));
3819 PLoad = IRB.CreateAlignedLoad(
3820 getAdjustedPtr(IRB, *DL, LoadBasePtr,
3821 APInt(DL->getPointerSizeInBits(), PartOffset),
3822 PartPtrTy, LoadBasePtr->getName() + "."),
3823 getAdjustedAlignment(LI, PartOffset, *DL), /*IsVolatile*/ false,
3827 // And store this partition.
3828 IRB.SetInsertPoint(BasicBlock::iterator(SI));
3829 StoreInst *PStore = IRB.CreateAlignedStore(
3830 PLoad, getAdjustedPtr(IRB, *DL, StoreBasePtr,
3831 APInt(DL->getPointerSizeInBits(), PartOffset),
3832 PartPtrTy, StoreBasePtr->getName() + "."),
3833 getAdjustedAlignment(SI, PartOffset, *DL), /*IsVolatile*/ false);
3835 // Now build a new slice for the alloca.
3836 NewSlices.push_back(
3837 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3838 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
3839 /*IsSplittable*/ true));
3840 DEBUG(AS.printSlice(dbgs(), std::prev(AS.end()), " "));
3841 DEBUG(dbgs() << ": " << *PStore << "\n");
3843 DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
3846 // Setup the next partition.
3847 PartOffset = Offsets.Splits[Idx];
3851 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3854 // We want to immediately iterate on any allocas impacted by splitting
3855 // this load, which is only relevant if it isn't a load of this alloca and
3856 // thus we didn't already split the loads above. We also have to keep track
3857 // of any promotable allocas we split loads on as they can no longer be
3860 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3861 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3862 ResplitPromotableAllocas.insert(OtherAI);
3863 Worklist.insert(OtherAI);
3864 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3865 LoadBasePtr->stripInBoundsOffsets())) {
3866 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3867 Worklist.insert(OtherAI);
3871 // Mark the original store as dead now that we've split it up and kill its
3872 // slice. Note that we leave the original load in place. It may in turn be
3873 // split up if it is an alloca load for some other alloca, but it may be
3874 // a normal load. This may introduce redundant loads, but where those can
3875 // be merged the rest of the optimizer should handle the merging, and this
3876 // uncovers SSA splits which is more important. In practice, the original
3877 // loads will almost always be fully split and removed eventually, and the
3878 // splits will be merged by any trivial CSE, including instcombine.
3879 DeadInsts.insert(SI);
3883 // Now we need to remove the killed slices, sort the newly added slices, and
3884 // merge the two sorted ranges of slices so that the entire range is sorted
3885 // properly for us to re-compute the partitions.
3886 AS.erase(std::remove_if(AS.begin(), AS.end(), [](const Slice &S) {
3890 AS.insert(NewSlices);
3892 DEBUG(dbgs() << " Pre-split slices:\n");
3894 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3895 DEBUG(AS.print(dbgs(), I, " "));
3898 // Finally, don't try to promote any allocas that new require re-splitting.
3899 // They have already been added to the worklist above.
3900 PromotableAllocas.erase(
3902 PromotableAllocas.begin(), PromotableAllocas.end(),
3903 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3904 PromotableAllocas.end());
3909 /// \brief Rewrite an alloca partition's users.
3911 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3912 /// to rewrite uses of an alloca partition to be conducive for SSA value
3913 /// promotion. If the partition needs a new, more refined alloca, this will
3914 /// build that new alloca, preserving as much type information as possible, and
3915 /// rewrite the uses of the old alloca to point at the new one and have the
3916 /// appropriate new offsets. It also evaluates how successful the rewrite was
3917 /// at enabling promotion and if it was successful queues the alloca to be
3919 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
3920 AllocaSlices::Partition &P) {
3921 // Try to compute a friendly type for this partition of the alloca. This
3922 // won't always succeed, in which case we fall back to a legal integer type
3923 // or an i8 array of an appropriate size.
3924 Type *SliceTy = nullptr;
3925 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
3926 if (DL->getTypeAllocSize(CommonUseTy) >= P.size())
3927 SliceTy = CommonUseTy;
3929 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
3930 P.beginOffset(), P.size()))
3931 SliceTy = TypePartitionTy;
3932 if ((!SliceTy || (SliceTy->isArrayTy() &&
3933 SliceTy->getArrayElementType()->isIntegerTy())) &&
3934 DL->isLegalInteger(P.size() * 8))
3935 SliceTy = Type::getIntNTy(*C, P.size() * 8);
3937 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
3938 assert(DL->getTypeAllocSize(SliceTy) >= P.size());
3940 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, *DL);
3943 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, *DL);
3947 // Check for the case where we're going to rewrite to a new alloca of the
3948 // exact same type as the original, and with the same access offsets. In that
3949 // case, re-use the existing alloca, but still run through the rewriter to
3950 // perform phi and select speculation.
3952 if (SliceTy == AI.getAllocatedType()) {
3953 assert(P.beginOffset() == 0 &&
3954 "Non-zero begin offset but same alloca type");
3956 // FIXME: We should be able to bail at this point with "nothing changed".
3957 // FIXME: We might want to defer PHI speculation until after here.
3959 unsigned Alignment = AI.getAlignment();
3961 // The minimum alignment which users can rely on when the explicit
3962 // alignment is omitted or zero is that required by the ABI for this
3964 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
3966 Alignment = MinAlign(Alignment, P.beginOffset());
3967 // If we will get at least this much alignment from the type alone, leave
3968 // the alloca's alignment unconstrained.
3969 if (Alignment <= DL->getABITypeAlignment(SliceTy))
3971 NewAI = new AllocaInst(
3972 SliceTy, nullptr, Alignment,
3973 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
3977 DEBUG(dbgs() << "Rewriting alloca partition "
3978 << "[" << P.beginOffset() << "," << P.endOffset()
3979 << ") to: " << *NewAI << "\n");
3981 // Track the high watermark on the worklist as it is only relevant for
3982 // promoted allocas. We will reset it to this point if the alloca is not in
3983 // fact scheduled for promotion.
3984 unsigned PPWOldSize = PostPromotionWorklist.size();
3985 unsigned NumUses = 0;
3986 SmallPtrSet<PHINode *, 8> PHIUsers;
3987 SmallPtrSet<SelectInst *, 8> SelectUsers;
3989 AllocaSliceRewriter Rewriter(*DL, AS, *this, AI, *NewAI, P.beginOffset(),
3990 P.endOffset(), IsIntegerPromotable, VecTy,
3991 PHIUsers, SelectUsers);
3992 bool Promotable = true;
3993 for (Slice *S : P.splitSliceTails()) {
3994 Promotable &= Rewriter.visit(S);
3997 for (Slice &S : P) {
3998 Promotable &= Rewriter.visit(&S);
4002 NumAllocaPartitionUses += NumUses;
4003 MaxUsesPerAllocaPartition =
4004 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
4006 // Now that we've processed all the slices in the new partition, check if any
4007 // PHIs or Selects would block promotion.
4008 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
4011 if (!isSafePHIToSpeculate(**I, DL)) {
4014 SelectUsers.clear();
4017 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
4018 E = SelectUsers.end();
4020 if (!isSafeSelectToSpeculate(**I, DL)) {
4023 SelectUsers.clear();
4028 if (PHIUsers.empty() && SelectUsers.empty()) {
4029 // Promote the alloca.
4030 PromotableAllocas.push_back(NewAI);
4032 // If we have either PHIs or Selects to speculate, add them to those
4033 // worklists and re-queue the new alloca so that we promote in on the
4035 for (PHINode *PHIUser : PHIUsers)
4036 SpeculatablePHIs.insert(PHIUser);
4037 for (SelectInst *SelectUser : SelectUsers)
4038 SpeculatableSelects.insert(SelectUser);
4039 Worklist.insert(NewAI);
4042 // If we can't promote the alloca, iterate on it to check for new
4043 // refinements exposed by splitting the current alloca. Don't iterate on an
4044 // alloca which didn't actually change and didn't get promoted.
4046 Worklist.insert(NewAI);
4048 // Drop any post-promotion work items if promotion didn't happen.
4049 while (PostPromotionWorklist.size() > PPWOldSize)
4050 PostPromotionWorklist.pop_back();
4056 /// \brief Walks the slices of an alloca and form partitions based on them,
4057 /// rewriting each of their uses.
4058 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4059 if (AS.begin() == AS.end())
4062 unsigned NumPartitions = 0;
4063 bool Changed = false;
4065 Changed |= presplitLoadsAndStores(AI, AS);
4067 // Rewrite each partition.
4068 for (auto &P : AS.partitions()) {
4069 Changed |= rewritePartition(AI, AS, P);
4073 NumAllocaPartitions += NumPartitions;
4074 MaxPartitionsPerAlloca =
4075 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
4080 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
4081 void SROA::clobberUse(Use &U) {
4083 // Replace the use with an undef value.
4084 U = UndefValue::get(OldV->getType());
4086 // Check for this making an instruction dead. We have to garbage collect
4087 // all the dead instructions to ensure the uses of any alloca end up being
4089 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4090 if (isInstructionTriviallyDead(OldI)) {
4091 DeadInsts.insert(OldI);
4095 /// \brief Analyze an alloca for SROA.
4097 /// This analyzes the alloca to ensure we can reason about it, builds
4098 /// the slices of the alloca, and then hands it off to be split and
4099 /// rewritten as needed.
4100 bool SROA::runOnAlloca(AllocaInst &AI) {
4101 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4102 ++NumAllocasAnalyzed;
4104 // Special case dead allocas, as they're trivial.
4105 if (AI.use_empty()) {
4106 AI.eraseFromParent();
4110 // Skip alloca forms that this analysis can't handle.
4111 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
4112 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
4115 bool Changed = false;
4117 // First, split any FCA loads and stores touching this alloca to promote
4118 // better splitting and promotion opportunities.
4119 AggLoadStoreRewriter AggRewriter(*DL);
4120 Changed |= AggRewriter.rewrite(AI);
4122 // Build the slices using a recursive instruction-visiting builder.
4123 AllocaSlices AS(*DL, AI);
4124 DEBUG(AS.print(dbgs()));
4128 // Delete all the dead users of this alloca before splitting and rewriting it.
4129 for (Instruction *DeadUser : AS.getDeadUsers()) {
4130 // Free up everything used by this instruction.
4131 for (Use &DeadOp : DeadUser->operands())
4134 // Now replace the uses of this instruction.
4135 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
4137 // And mark it for deletion.
4138 DeadInsts.insert(DeadUser);
4141 for (Use *DeadOp : AS.getDeadOperands()) {
4142 clobberUse(*DeadOp);
4146 // No slices to split. Leave the dead alloca for a later pass to clean up.
4147 if (AS.begin() == AS.end())
4150 Changed |= splitAlloca(AI, AS);
4152 DEBUG(dbgs() << " Speculating PHIs\n");
4153 while (!SpeculatablePHIs.empty())
4154 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4156 DEBUG(dbgs() << " Speculating Selects\n");
4157 while (!SpeculatableSelects.empty())
4158 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4163 /// \brief Delete the dead instructions accumulated in this run.
4165 /// Recursively deletes the dead instructions we've accumulated. This is done
4166 /// at the very end to maximize locality of the recursive delete and to
4167 /// minimize the problems of invalidated instruction pointers as such pointers
4168 /// are used heavily in the intermediate stages of the algorithm.
4170 /// We also record the alloca instructions deleted here so that they aren't
4171 /// subsequently handed to mem2reg to promote.
4172 void SROA::deleteDeadInstructions(
4173 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
4174 while (!DeadInsts.empty()) {
4175 Instruction *I = DeadInsts.pop_back_val();
4176 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4178 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4180 for (Use &Operand : I->operands())
4181 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
4182 // Zero out the operand and see if it becomes trivially dead.
4184 if (isInstructionTriviallyDead(U))
4185 DeadInsts.insert(U);
4188 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4189 DeletedAllocas.insert(AI);
4192 I->eraseFromParent();
4196 static void enqueueUsersInWorklist(Instruction &I,
4197 SmallVectorImpl<Instruction *> &Worklist,
4198 SmallPtrSetImpl<Instruction *> &Visited) {
4199 for (User *U : I.users())
4200 if (Visited.insert(cast<Instruction>(U)).second)
4201 Worklist.push_back(cast<Instruction>(U));
4204 /// \brief Promote the allocas, using the best available technique.
4206 /// This attempts to promote whatever allocas have been identified as viable in
4207 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
4208 /// If there is a domtree available, we attempt to promote using the full power
4209 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
4210 /// based on the SSAUpdater utilities. This function returns whether any
4211 /// promotion occurred.
4212 bool SROA::promoteAllocas(Function &F) {
4213 if (PromotableAllocas.empty())
4216 NumPromoted += PromotableAllocas.size();
4218 if (DT && !ForceSSAUpdater) {
4219 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
4220 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AT);
4221 PromotableAllocas.clear();
4225 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
4227 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
4228 SmallVector<Instruction *, 64> Insts;
4230 // We need a worklist to walk the uses of each alloca.
4231 SmallVector<Instruction *, 8> Worklist;
4232 SmallPtrSet<Instruction *, 8> Visited;
4233 SmallVector<Instruction *, 32> DeadInsts;
4235 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
4236 AllocaInst *AI = PromotableAllocas[Idx];
4241 enqueueUsersInWorklist(*AI, Worklist, Visited);
4243 while (!Worklist.empty()) {
4244 Instruction *I = Worklist.pop_back_val();
4246 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
4247 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
4248 // leading to them) here. Eventually it should use them to optimize the
4249 // scalar values produced.
4250 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
4251 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
4252 II->getIntrinsicID() == Intrinsic::lifetime_end);
4253 II->eraseFromParent();
4257 // Push the loads and stores we find onto the list. SROA will already
4258 // have validated that all loads and stores are viable candidates for
4260 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4261 assert(LI->getType() == AI->getAllocatedType());
4262 Insts.push_back(LI);
4265 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
4266 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
4267 Insts.push_back(SI);
4271 // For everything else, we know that only no-op bitcasts and GEPs will
4272 // make it this far, just recurse through them and recall them for later
4274 DeadInsts.push_back(I);
4275 enqueueUsersInWorklist(*I, Worklist, Visited);
4277 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
4278 while (!DeadInsts.empty())
4279 DeadInsts.pop_back_val()->eraseFromParent();
4280 AI->eraseFromParent();
4283 PromotableAllocas.clear();
4287 bool SROA::runOnFunction(Function &F) {
4288 if (skipOptnoneFunction(F))
4291 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4292 C = &F.getContext();
4293 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
4295 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
4298 DL = &DLP->getDataLayout();
4299 DominatorTreeWrapperPass *DTWP =
4300 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
4301 DT = DTWP ? &DTWP->getDomTree() : nullptr;
4302 AT = &getAnalysis<AssumptionTracker>();
4304 BasicBlock &EntryBB = F.getEntryBlock();
4305 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
4307 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4308 Worklist.insert(AI);
4310 bool Changed = false;
4311 // A set of deleted alloca instruction pointers which should be removed from
4312 // the list of promotable allocas.
4313 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4316 while (!Worklist.empty()) {
4317 Changed |= runOnAlloca(*Worklist.pop_back_val());
4318 deleteDeadInstructions(DeletedAllocas);
4320 // Remove the deleted allocas from various lists so that we don't try to
4321 // continue processing them.
4322 if (!DeletedAllocas.empty()) {
4323 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
4324 Worklist.remove_if(IsInSet);
4325 PostPromotionWorklist.remove_if(IsInSet);
4326 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
4327 PromotableAllocas.end(),
4329 PromotableAllocas.end());
4330 DeletedAllocas.clear();
4334 Changed |= promoteAllocas(F);
4336 Worklist = PostPromotionWorklist;
4337 PostPromotionWorklist.clear();
4338 } while (!Worklist.empty());
4343 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
4344 AU.addRequired<AssumptionTracker>();
4345 if (RequiresDomTree)
4346 AU.addRequired<DominatorTreeWrapperPass>();
4347 AU.setPreservesCFG();