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.
83 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
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",
93 cl::init(false), cl::Hidden);
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,
125 IRBuilderPrefixedInserter<true> > IRBuilderTy;
127 typedef llvm::IRBuilder<false, ConstantFolder,
128 IRBuilderPrefixedInserter<false> > IRBuilderTy;
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()) return true;
175 if (beginOffset() > RHS.beginOffset()) return false;
176 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
177 if (endOffset() > RHS.endOffset()) return true;
181 /// \brief Support comparison with a single offset to allow binary searches.
182 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
183 uint64_t RHSOffset) {
184 return LHS.beginOffset() < RHSOffset;
186 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
188 return LHSOffset < RHS.beginOffset();
191 bool operator==(const Slice &RHS) const {
192 return isSplittable() == RHS.isSplittable() &&
193 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
195 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
197 } // end anonymous namespace
200 template <typename T> struct isPodLike;
201 template <> struct isPodLike<Slice> {
202 static const bool value = true;
207 /// \brief Representation of the alloca slices.
209 /// This class represents the slices of an alloca which are formed by its
210 /// various uses. If a pointer escapes, we can't fully build a representation
211 /// for the slices used and we reflect that in this structure. The uses are
212 /// stored, sorted by increasing beginning offset and with unsplittable slices
213 /// starting at a particular offset before splittable slices.
216 /// \brief Construct the slices of a particular alloca.
217 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
219 /// \brief Test whether a pointer to the allocation escapes our analysis.
221 /// If this is true, the slices are never fully built and should be
223 bool isEscaped() const { return PointerEscapingInstr; }
225 /// \brief Support for iterating over the slices.
227 typedef SmallVectorImpl<Slice>::iterator iterator;
228 typedef iterator_range<iterator> range;
229 iterator begin() { return Slices.begin(); }
230 iterator end() { return Slices.end(); }
232 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
233 typedef iterator_range<const_iterator> const_range;
234 const_iterator begin() const { return Slices.begin(); }
235 const_iterator end() const { return Slices.end(); }
238 /// \brief Allow iterating the dead users for this alloca.
240 /// These are instructions which will never actually use the alloca as they
241 /// are outside the allocated range. They are safe to replace with undef and
244 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
245 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
246 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
249 /// \brief Allow iterating the dead expressions referring to this alloca.
251 /// These are operands which have cannot actually be used to refer to the
252 /// alloca as they are outside its range and the user doesn't correct for
253 /// that. These mostly consist of PHI node inputs and the like which we just
254 /// need to replace with undef.
256 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
257 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
258 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
261 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
262 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
263 void printSlice(raw_ostream &OS, const_iterator I,
264 StringRef Indent = " ") const;
265 void printUse(raw_ostream &OS, const_iterator I,
266 StringRef Indent = " ") const;
267 void print(raw_ostream &OS) const;
268 void dump(const_iterator I) const;
273 template <typename DerivedT, typename RetT = void> class BuilderBase;
275 friend class AllocaSlices::SliceBuilder;
277 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
278 /// \brief Handle to alloca instruction to simplify method interfaces.
282 /// \brief The instruction responsible for this alloca not having a known set
285 /// When an instruction (potentially) escapes the pointer to the alloca, we
286 /// store a pointer to that here and abort trying to form slices of the
287 /// alloca. This will be null if the alloca slices are analyzed successfully.
288 Instruction *PointerEscapingInstr;
290 /// \brief The slices of the alloca.
292 /// We store a vector of the slices formed by uses of the alloca here. This
293 /// vector is sorted by increasing begin offset, and then the unsplittable
294 /// slices before the splittable ones. See the Slice inner class for more
296 SmallVector<Slice, 8> Slices;
298 /// \brief Instructions which will become dead if we rewrite the alloca.
300 /// Note that these are not separated by slice. This is because we expect an
301 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
302 /// all these instructions can simply be removed and replaced with undef as
303 /// they come from outside of the allocated space.
304 SmallVector<Instruction *, 8> DeadUsers;
306 /// \brief Operands which will become dead if we rewrite the alloca.
308 /// These are operands that in their particular use can be replaced with
309 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
310 /// to PHI nodes and the like. They aren't entirely dead (there might be
311 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
312 /// want to swap this particular input for undef to simplify the use lists of
314 SmallVector<Use *, 8> DeadOperands;
318 static Value *foldSelectInst(SelectInst &SI) {
319 // If the condition being selected on is a constant or the same value is
320 // being selected between, fold the select. Yes this does (rarely) happen
322 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
323 return SI.getOperand(1+CI->isZero());
324 if (SI.getOperand(1) == SI.getOperand(2))
325 return SI.getOperand(1);
330 /// \brief A helper that folds a PHI node or a select.
331 static Value *foldPHINodeOrSelectInst(Instruction &I) {
332 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
333 // If PN merges together the same value, return that value.
334 return PN->hasConstantValue();
336 return foldSelectInst(cast<SelectInst>(I));
339 /// \brief Builder for the alloca slices.
341 /// This class builds a set of alloca slices by recursively visiting the uses
342 /// of an alloca and making a slice for each load and store at each offset.
343 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
344 friend class PtrUseVisitor<SliceBuilder>;
345 friend class InstVisitor<SliceBuilder>;
346 typedef PtrUseVisitor<SliceBuilder> Base;
348 const uint64_t AllocSize;
351 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
352 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
354 /// \brief Set to de-duplicate dead instructions found in the use walk.
355 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
358 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
359 : PtrUseVisitor<SliceBuilder>(DL),
360 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
363 void markAsDead(Instruction &I) {
364 if (VisitedDeadInsts.insert(&I))
365 S.DeadUsers.push_back(&I);
368 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
369 bool IsSplittable = false) {
370 // Completely skip uses which have a zero size or start either before or
371 // past the end of the allocation.
372 if (Size == 0 || Offset.uge(AllocSize)) {
373 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
374 << " which has zero size or starts outside of the "
375 << AllocSize << " byte alloca:\n"
376 << " alloca: " << S.AI << "\n"
377 << " use: " << I << "\n");
378 return markAsDead(I);
381 uint64_t BeginOffset = Offset.getZExtValue();
382 uint64_t EndOffset = BeginOffset + Size;
384 // Clamp the end offset to the end of the allocation. Note that this is
385 // formulated to handle even the case where "BeginOffset + Size" overflows.
386 // This may appear superficially to be something we could ignore entirely,
387 // but that is not so! There may be widened loads or PHI-node uses where
388 // some instructions are dead but not others. We can't completely ignore
389 // them, and so have to record at least the information here.
390 assert(AllocSize >= BeginOffset); // Established above.
391 if (Size > AllocSize - BeginOffset) {
392 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
393 << " to remain within the " << AllocSize << " byte alloca:\n"
394 << " alloca: " << S.AI << "\n"
395 << " use: " << I << "\n");
396 EndOffset = AllocSize;
399 S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
402 void visitBitCastInst(BitCastInst &BC) {
404 return markAsDead(BC);
406 return Base::visitBitCastInst(BC);
409 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
410 if (GEPI.use_empty())
411 return markAsDead(GEPI);
413 if (SROAStrictInbounds && GEPI.isInBounds()) {
414 // FIXME: This is a manually un-factored variant of the basic code inside
415 // of GEPs with checking of the inbounds invariant specified in the
416 // langref in a very strict sense. If we ever want to enable
417 // SROAStrictInbounds, this code should be factored cleanly into
418 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
419 // by writing out the code here where we have tho underlying allocation
420 // size readily available.
421 APInt GEPOffset = Offset;
422 for (gep_type_iterator GTI = gep_type_begin(GEPI),
423 GTE = gep_type_end(GEPI);
425 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
429 // Handle a struct index, which adds its field offset to the pointer.
430 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
431 unsigned ElementIdx = OpC->getZExtValue();
432 const StructLayout *SL = DL.getStructLayout(STy);
434 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
436 // For array or vector indices, scale the index by the size of the type.
437 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
438 GEPOffset += Index * APInt(Offset.getBitWidth(),
439 DL.getTypeAllocSize(GTI.getIndexedType()));
442 // If this index has computed an intermediate pointer which is not
443 // inbounds, then the result of the GEP is a poison value and we can
444 // delete it and all uses.
445 if (GEPOffset.ugt(AllocSize))
446 return markAsDead(GEPI);
450 return Base::visitGetElementPtrInst(GEPI);
453 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
454 uint64_t Size, bool IsVolatile) {
455 // We allow splitting of loads and stores where the type is an integer type
456 // and cover the entire alloca. This prevents us from splitting over
458 // FIXME: In the great blue eventually, we should eagerly split all integer
459 // loads and stores, and then have a separate step that merges adjacent
460 // alloca partitions into a single partition suitable for integer widening.
461 // Or we should skip the merge step and rely on GVN and other passes to
462 // merge adjacent loads and stores that survive mem2reg.
464 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
466 insertUse(I, Offset, Size, IsSplittable);
469 void visitLoadInst(LoadInst &LI) {
470 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
471 "All simple FCA loads should have been pre-split");
474 return PI.setAborted(&LI);
476 uint64_t Size = DL.getTypeStoreSize(LI.getType());
477 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
480 void visitStoreInst(StoreInst &SI) {
481 Value *ValOp = SI.getValueOperand();
483 return PI.setEscapedAndAborted(&SI);
485 return PI.setAborted(&SI);
487 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
489 // If this memory access can be shown to *statically* extend outside the
490 // bounds of of the allocation, it's behavior is undefined, so simply
491 // ignore it. Note that this is more strict than the generic clamping
492 // behavior of insertUse. We also try to handle cases which might run the
494 // FIXME: We should instead consider the pointer to have escaped if this
495 // function is being instrumented for addressing bugs or race conditions.
496 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
497 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
498 << " which extends past the end of the " << AllocSize
500 << " alloca: " << S.AI << "\n"
501 << " use: " << SI << "\n");
502 return markAsDead(SI);
505 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
506 "All simple FCA stores should have been pre-split");
507 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
511 void visitMemSetInst(MemSetInst &II) {
512 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
513 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
514 if ((Length && Length->getValue() == 0) ||
515 (IsOffsetKnown && Offset.uge(AllocSize)))
516 // Zero-length mem transfer intrinsics can be ignored entirely.
517 return markAsDead(II);
520 return PI.setAborted(&II);
522 insertUse(II, Offset,
523 Length ? Length->getLimitedValue()
524 : AllocSize - Offset.getLimitedValue(),
528 void visitMemTransferInst(MemTransferInst &II) {
529 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
530 if (Length && Length->getValue() == 0)
531 // Zero-length mem transfer intrinsics can be ignored entirely.
532 return markAsDead(II);
534 // Because we can visit these intrinsics twice, also check to see if the
535 // first time marked this instruction as dead. If so, skip it.
536 if (VisitedDeadInsts.count(&II))
540 return PI.setAborted(&II);
542 // This side of the transfer is completely out-of-bounds, and so we can
543 // nuke the entire transfer. However, we also need to nuke the other side
544 // if already added to our partitions.
545 // FIXME: Yet another place we really should bypass this when
546 // instrumenting for ASan.
547 if (Offset.uge(AllocSize)) {
548 SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II);
549 if (MTPI != MemTransferSliceMap.end())
550 S.Slices[MTPI->second].kill();
551 return markAsDead(II);
554 uint64_t RawOffset = Offset.getLimitedValue();
555 uint64_t Size = Length ? Length->getLimitedValue()
556 : AllocSize - RawOffset;
558 // Check for the special case where the same exact value is used for both
560 if (*U == II.getRawDest() && *U == II.getRawSource()) {
561 // For non-volatile transfers this is a no-op.
562 if (!II.isVolatile())
563 return markAsDead(II);
565 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
568 // If we have seen both source and destination for a mem transfer, then
569 // they both point to the same alloca.
571 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
572 std::tie(MTPI, Inserted) =
573 MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
574 unsigned PrevIdx = MTPI->second;
576 Slice &PrevP = S.Slices[PrevIdx];
578 // Check if the begin offsets match and this is a non-volatile transfer.
579 // In that case, we can completely elide the transfer.
580 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
582 return markAsDead(II);
585 // Otherwise we have an offset transfer within the same alloca. We can't
587 PrevP.makeUnsplittable();
590 // Insert the use now that we've fixed up the splittable nature.
591 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
593 // Check that we ended up with a valid index in the map.
594 assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
595 "Map index doesn't point back to a slice with this user.");
598 // Disable SRoA for any intrinsics except for lifetime invariants.
599 // FIXME: What about debug intrinsics? This matches old behavior, but
600 // doesn't make sense.
601 void visitIntrinsicInst(IntrinsicInst &II) {
603 return PI.setAborted(&II);
605 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
606 II.getIntrinsicID() == Intrinsic::lifetime_end) {
607 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
608 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
609 Length->getLimitedValue());
610 insertUse(II, Offset, Size, true);
614 Base::visitIntrinsicInst(II);
617 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
618 // We consider any PHI or select that results in a direct load or store of
619 // the same offset to be a viable use for slicing purposes. These uses
620 // are considered unsplittable and the size is the maximum loaded or stored
622 SmallPtrSet<Instruction *, 4> Visited;
623 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
624 Visited.insert(Root);
625 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
626 // If there are no loads or stores, the access is dead. We mark that as
627 // a size zero access.
630 Instruction *I, *UsedI;
631 std::tie(UsedI, I) = Uses.pop_back_val();
633 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
634 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
637 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
638 Value *Op = SI->getOperand(0);
641 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
645 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
646 if (!GEP->hasAllZeroIndices())
648 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
649 !isa<SelectInst>(I)) {
653 for (User *U : I->users())
654 if (Visited.insert(cast<Instruction>(U)))
655 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
656 } while (!Uses.empty());
661 void visitPHINodeOrSelectInst(Instruction &I) {
662 assert(isa<PHINode>(I) || isa<SelectInst>(I));
664 return markAsDead(I);
666 // TODO: We could use SimplifyInstruction here to fold PHINodes and
667 // SelectInsts. However, doing so requires to change the current
668 // dead-operand-tracking mechanism. For instance, suppose neither loading
669 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
670 // trap either. However, if we simply replace %U with undef using the
671 // current dead-operand-tracking mechanism, "load (select undef, undef,
672 // %other)" may trap because the select may return the first operand
674 if (Value *Result = foldPHINodeOrSelectInst(I)) {
676 // If the result of the constant fold will be the pointer, recurse
677 // through the PHI/select as if we had RAUW'ed it.
680 // Otherwise the operand to the PHI/select is dead, and we can replace
682 S.DeadOperands.push_back(U);
688 return PI.setAborted(&I);
690 // See if we already have computed info on this node.
691 uint64_t &Size = PHIOrSelectSizes[&I];
693 // This is a new PHI/Select, check for an unsafe use of it.
694 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
695 return PI.setAborted(UnsafeI);
698 // For PHI and select operands outside the alloca, we can't nuke the entire
699 // phi or select -- the other side might still be relevant, so we special
700 // case them here and use a separate structure to track the operands
701 // themselves which should be replaced with undef.
702 // FIXME: This should instead be escaped in the event we're instrumenting
703 // for address sanitization.
704 if (Offset.uge(AllocSize)) {
705 S.DeadOperands.push_back(U);
709 insertUse(I, Offset, Size);
712 void visitPHINode(PHINode &PN) {
713 visitPHINodeOrSelectInst(PN);
716 void visitSelectInst(SelectInst &SI) {
717 visitPHINodeOrSelectInst(SI);
720 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
721 void visitInstruction(Instruction &I) {
726 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
728 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
731 PointerEscapingInstr(nullptr) {
732 SliceBuilder PB(DL, AI, *this);
733 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
734 if (PtrI.isEscaped() || PtrI.isAborted()) {
735 // FIXME: We should sink the escape vs. abort info into the caller nicely,
736 // possibly by just storing the PtrInfo in the AllocaSlices.
737 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
738 : PtrI.getAbortingInst();
739 assert(PointerEscapingInstr && "Did not track a bad instruction");
743 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
744 std::mem_fun_ref(&Slice::isDead)),
747 #if __cplusplus >= 201103L && !defined(NDEBUG)
748 if (SROARandomShuffleSlices) {
749 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
750 std::shuffle(Slices.begin(), Slices.end(), MT);
754 // Sort the uses. This arranges for the offsets to be in ascending order,
755 // and the sizes to be in descending order.
756 std::sort(Slices.begin(), Slices.end());
759 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
761 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
762 StringRef Indent) const {
763 printSlice(OS, I, Indent);
764 printUse(OS, I, Indent);
767 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
768 StringRef Indent) const {
769 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
770 << " slice #" << (I - begin())
771 << (I->isSplittable() ? " (splittable)" : "") << "\n";
774 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
775 StringRef Indent) const {
776 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
779 void AllocaSlices::print(raw_ostream &OS) const {
780 if (PointerEscapingInstr) {
781 OS << "Can't analyze slices for alloca: " << AI << "\n"
782 << " A pointer to this alloca escaped by:\n"
783 << " " << *PointerEscapingInstr << "\n";
787 OS << "Slices of alloca: " << AI << "\n";
788 for (const_iterator I = begin(), E = end(); I != E; ++I)
792 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
795 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
797 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
800 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
802 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
803 /// the loads and stores of an alloca instruction, as well as updating its
804 /// debug information. This is used when a domtree is unavailable and thus
805 /// mem2reg in its full form can't be used to handle promotion of allocas to
807 class AllocaPromoter : public LoadAndStorePromoter {
811 SmallVector<DbgDeclareInst *, 4> DDIs;
812 SmallVector<DbgValueInst *, 4> DVIs;
815 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
816 AllocaInst &AI, DIBuilder &DIB)
817 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
819 void run(const SmallVectorImpl<Instruction*> &Insts) {
820 // Retain the debug information attached to the alloca for use when
821 // rewriting loads and stores.
822 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
823 for (User *U : DebugNode->users())
824 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
826 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
830 LoadAndStorePromoter::run(Insts);
832 // While we have the debug information, clear it off of the alloca. The
833 // caller takes care of deleting the alloca.
834 while (!DDIs.empty())
835 DDIs.pop_back_val()->eraseFromParent();
836 while (!DVIs.empty())
837 DVIs.pop_back_val()->eraseFromParent();
840 bool isInstInList(Instruction *I,
841 const SmallVectorImpl<Instruction*> &Insts) const override {
843 if (LoadInst *LI = dyn_cast<LoadInst>(I))
844 Ptr = LI->getOperand(0);
846 Ptr = cast<StoreInst>(I)->getPointerOperand();
848 // Only used to detect cycles, which will be rare and quickly found as
849 // we're walking up a chain of defs rather than down through uses.
850 SmallPtrSet<Value *, 4> Visited;
856 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
857 Ptr = BCI->getOperand(0);
858 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
859 Ptr = GEPI->getPointerOperand();
863 } while (Visited.insert(Ptr));
868 void updateDebugInfo(Instruction *Inst) const override {
869 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
870 E = DDIs.end(); I != E; ++I) {
871 DbgDeclareInst *DDI = *I;
872 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
873 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
874 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
875 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
877 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
878 E = DVIs.end(); I != E; ++I) {
879 DbgValueInst *DVI = *I;
880 Value *Arg = nullptr;
881 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
882 // If an argument is zero extended then use argument directly. The ZExt
883 // may be zapped by an optimization pass in future.
884 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
885 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
886 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
887 Arg = dyn_cast<Argument>(SExt->getOperand(0));
889 Arg = SI->getValueOperand();
890 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
891 Arg = LI->getPointerOperand();
895 Instruction *DbgVal =
896 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
897 DIExpression(DVI->getExpression()), Inst);
898 DbgVal->setDebugLoc(DVI->getDebugLoc());
902 } // end anon namespace
906 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
908 /// This pass takes allocations which can be completely analyzed (that is, they
909 /// don't escape) and tries to turn them into scalar SSA values. There are
910 /// a few steps to this process.
912 /// 1) It takes allocations of aggregates and analyzes the ways in which they
913 /// are used to try to split them into smaller allocations, ideally of
914 /// a single scalar data type. It will split up memcpy and memset accesses
915 /// as necessary and try to isolate individual scalar accesses.
916 /// 2) It will transform accesses into forms which are suitable for SSA value
917 /// promotion. This can be replacing a memset with a scalar store of an
918 /// integer value, or it can involve speculating operations on a PHI or
919 /// select to be a PHI or select of the results.
920 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
921 /// onto insert and extract operations on a vector value, and convert them to
922 /// this form. By doing so, it will enable promotion of vector aggregates to
923 /// SSA vector values.
924 class SROA : public FunctionPass {
925 const bool RequiresDomTree;
928 const DataLayout *DL;
930 AssumptionTracker *AT;
932 /// \brief Worklist of alloca instructions to simplify.
934 /// Each alloca in the function is added to this. Each new alloca formed gets
935 /// added to it as well to recursively simplify unless that alloca can be
936 /// directly promoted. Finally, each time we rewrite a use of an alloca other
937 /// the one being actively rewritten, we add it back onto the list if not
938 /// already present to ensure it is re-visited.
939 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
941 /// \brief A collection of instructions to delete.
942 /// We try to batch deletions to simplify code and make things a bit more
944 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
946 /// \brief Post-promotion worklist.
948 /// Sometimes we discover an alloca which has a high probability of becoming
949 /// viable for SROA after a round of promotion takes place. In those cases,
950 /// the alloca is enqueued here for re-processing.
952 /// Note that we have to be very careful to clear allocas out of this list in
953 /// the event they are deleted.
954 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
956 /// \brief A collection of alloca instructions we can directly promote.
957 std::vector<AllocaInst *> PromotableAllocas;
959 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
961 /// All of these PHIs have been checked for the safety of speculation and by
962 /// being speculated will allow promoting allocas currently in the promotable
964 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
966 /// \brief A worklist of select instructions to speculate prior to promoting
969 /// All of these select instructions have been checked for the safety of
970 /// speculation and by being speculated will allow promoting allocas
971 /// currently in the promotable queue.
972 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
975 SROA(bool RequiresDomTree = true)
976 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
977 C(nullptr), DL(nullptr), DT(nullptr) {
978 initializeSROAPass(*PassRegistry::getPassRegistry());
980 bool runOnFunction(Function &F) override;
981 void getAnalysisUsage(AnalysisUsage &AU) const override;
983 const char *getPassName() const override { return "SROA"; }
987 friend class PHIOrSelectSpeculator;
988 friend class AllocaSliceRewriter;
990 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
991 AllocaSlices::iterator B, AllocaSlices::iterator E,
992 int64_t BeginOffset, int64_t EndOffset,
993 ArrayRef<AllocaSlices::iterator> SplitUses);
994 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
995 bool runOnAlloca(AllocaInst &AI);
996 void clobberUse(Use &U);
997 void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
998 bool promoteAllocas(Function &F);
1004 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1005 return new SROA(RequiresDomTree);
1008 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1010 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
1011 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1012 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1015 /// Walk the range of a partitioning looking for a common type to cover this
1016 /// sequence of slices.
1017 static Type *findCommonType(AllocaSlices::const_iterator B,
1018 AllocaSlices::const_iterator E,
1019 uint64_t EndOffset) {
1021 bool TyIsCommon = true;
1022 IntegerType *ITy = nullptr;
1024 // Note that we need to look at *every* alloca slice's Use to ensure we
1025 // always get consistent results regardless of the order of slices.
1026 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1027 Use *U = I->getUse();
1028 if (isa<IntrinsicInst>(*U->getUser()))
1030 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1033 Type *UserTy = nullptr;
1034 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1035 UserTy = LI->getType();
1036 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1037 UserTy = SI->getValueOperand()->getType();
1040 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1041 // If the type is larger than the partition, skip it. We only encounter
1042 // this for split integer operations where we want to use the type of the
1043 // entity causing the split. Also skip if the type is not a byte width
1045 if (UserITy->getBitWidth() % 8 != 0 ||
1046 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1049 // Track the largest bitwidth integer type used in this way in case there
1050 // is no common type.
1051 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1055 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1056 // depend on types skipped above.
1057 if (!UserTy || (Ty && Ty != UserTy))
1058 TyIsCommon = false; // Give up on anything but an iN type.
1063 return TyIsCommon ? Ty : ITy;
1066 /// PHI instructions that use an alloca and are subsequently loaded can be
1067 /// rewritten to load both input pointers in the pred blocks and then PHI the
1068 /// results, allowing the load of the alloca to be promoted.
1070 /// %P2 = phi [i32* %Alloca, i32* %Other]
1071 /// %V = load i32* %P2
1073 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1075 /// %V2 = load i32* %Other
1077 /// %V = phi [i32 %V1, i32 %V2]
1079 /// We can do this to a select if its only uses are loads and if the operands
1080 /// to the select can be loaded unconditionally.
1082 /// FIXME: This should be hoisted into a generic utility, likely in
1083 /// Transforms/Util/Local.h
1084 static bool isSafePHIToSpeculate(PHINode &PN,
1085 const DataLayout *DL = nullptr) {
1086 // For now, we can only do this promotion if the load is in the same block
1087 // as the PHI, and if there are no stores between the phi and load.
1088 // TODO: Allow recursive phi users.
1089 // TODO: Allow stores.
1090 BasicBlock *BB = PN.getParent();
1091 unsigned MaxAlign = 0;
1092 bool HaveLoad = false;
1093 for (User *U : PN.users()) {
1094 LoadInst *LI = dyn_cast<LoadInst>(U);
1095 if (!LI || !LI->isSimple())
1098 // For now we only allow loads in the same block as the PHI. This is
1099 // a common case that happens when instcombine merges two loads through
1101 if (LI->getParent() != BB)
1104 // Ensure that there are no instructions between the PHI and the load that
1106 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1107 if (BBI->mayWriteToMemory())
1110 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1117 // We can only transform this if it is safe to push the loads into the
1118 // predecessor blocks. The only thing to watch out for is that we can't put
1119 // a possibly trapping load in the predecessor if it is a critical edge.
1120 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1121 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1122 Value *InVal = PN.getIncomingValue(Idx);
1124 // If the value is produced by the terminator of the predecessor (an
1125 // invoke) or it has side-effects, there is no valid place to put a load
1126 // in the predecessor.
1127 if (TI == InVal || TI->mayHaveSideEffects())
1130 // If the predecessor has a single successor, then the edge isn't
1132 if (TI->getNumSuccessors() == 1)
1135 // If this pointer is always safe to load, or if we can prove that there
1136 // is already a load in the block, then we can move the load to the pred
1138 if (InVal->isDereferenceablePointer(DL) ||
1139 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
1148 static void speculatePHINodeLoads(PHINode &PN) {
1149 DEBUG(dbgs() << " original: " << PN << "\n");
1151 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1152 IRBuilderTy PHIBuilder(&PN);
1153 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1154 PN.getName() + ".sroa.speculated");
1156 // Get the AA tags and alignment to use from one of the loads. It doesn't
1157 // matter which one we get and if any differ.
1158 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1161 SomeLoad->getAAMetadata(AATags);
1162 unsigned Align = SomeLoad->getAlignment();
1164 // Rewrite all loads of the PN to use the new PHI.
1165 while (!PN.use_empty()) {
1166 LoadInst *LI = cast<LoadInst>(PN.user_back());
1167 LI->replaceAllUsesWith(NewPN);
1168 LI->eraseFromParent();
1171 // Inject loads into all of the pred blocks.
1172 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1173 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1174 TerminatorInst *TI = Pred->getTerminator();
1175 Value *InVal = PN.getIncomingValue(Idx);
1176 IRBuilderTy PredBuilder(TI);
1178 LoadInst *Load = PredBuilder.CreateLoad(
1179 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1180 ++NumLoadsSpeculated;
1181 Load->setAlignment(Align);
1183 Load->setAAMetadata(AATags);
1184 NewPN->addIncoming(Load, Pred);
1187 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1188 PN.eraseFromParent();
1191 /// Select instructions that use an alloca and are subsequently loaded can be
1192 /// rewritten to load both input pointers and then select between the result,
1193 /// allowing the load of the alloca to be promoted.
1195 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1196 /// %V = load i32* %P2
1198 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1199 /// %V2 = load i32* %Other
1200 /// %V = select i1 %cond, i32 %V1, i32 %V2
1202 /// We can do this to a select if its only uses are loads and if the operand
1203 /// to the select can be loaded unconditionally.
1204 static bool isSafeSelectToSpeculate(SelectInst &SI,
1205 const DataLayout *DL = nullptr) {
1206 Value *TValue = SI.getTrueValue();
1207 Value *FValue = SI.getFalseValue();
1208 bool TDerefable = TValue->isDereferenceablePointer(DL);
1209 bool FDerefable = FValue->isDereferenceablePointer(DL);
1211 for (User *U : SI.users()) {
1212 LoadInst *LI = dyn_cast<LoadInst>(U);
1213 if (!LI || !LI->isSimple())
1216 // Both operands to the select need to be dereferencable, either
1217 // absolutely (e.g. allocas) or at this point because we can see other
1220 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
1223 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
1230 static void speculateSelectInstLoads(SelectInst &SI) {
1231 DEBUG(dbgs() << " original: " << SI << "\n");
1233 IRBuilderTy IRB(&SI);
1234 Value *TV = SI.getTrueValue();
1235 Value *FV = SI.getFalseValue();
1236 // Replace the loads of the select with a select of two loads.
1237 while (!SI.use_empty()) {
1238 LoadInst *LI = cast<LoadInst>(SI.user_back());
1239 assert(LI->isSimple() && "We only speculate simple loads");
1241 IRB.SetInsertPoint(LI);
1243 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1245 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1246 NumLoadsSpeculated += 2;
1248 // Transfer alignment and AA info if present.
1249 TL->setAlignment(LI->getAlignment());
1250 FL->setAlignment(LI->getAlignment());
1253 LI->getAAMetadata(Tags);
1255 TL->setAAMetadata(Tags);
1256 FL->setAAMetadata(Tags);
1259 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1260 LI->getName() + ".sroa.speculated");
1262 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1263 LI->replaceAllUsesWith(V);
1264 LI->eraseFromParent();
1266 SI.eraseFromParent();
1269 /// \brief Build a GEP out of a base pointer and indices.
1271 /// This will return the BasePtr if that is valid, or build a new GEP
1272 /// instruction using the IRBuilder if GEP-ing is needed.
1273 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1274 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
1275 if (Indices.empty())
1278 // A single zero index is a no-op, so check for this and avoid building a GEP
1280 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1283 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
1286 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1287 /// TargetTy without changing the offset of the pointer.
1289 /// This routine assumes we've already established a properly offset GEP with
1290 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1291 /// zero-indices down through type layers until we find one the same as
1292 /// TargetTy. If we can't find one with the same type, we at least try to use
1293 /// one with the same size. If none of that works, we just produce the GEP as
1294 /// indicated by Indices to have the correct offset.
1295 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1296 Value *BasePtr, Type *Ty, Type *TargetTy,
1297 SmallVectorImpl<Value *> &Indices,
1300 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1302 // Pointer size to use for the indices.
1303 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1305 // See if we can descend into a struct and locate a field with the correct
1307 unsigned NumLayers = 0;
1308 Type *ElementTy = Ty;
1310 if (ElementTy->isPointerTy())
1313 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1314 ElementTy = ArrayTy->getElementType();
1315 Indices.push_back(IRB.getIntN(PtrSize, 0));
1316 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1317 ElementTy = VectorTy->getElementType();
1318 Indices.push_back(IRB.getInt32(0));
1319 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1320 if (STy->element_begin() == STy->element_end())
1321 break; // Nothing left to descend into.
1322 ElementTy = *STy->element_begin();
1323 Indices.push_back(IRB.getInt32(0));
1328 } while (ElementTy != TargetTy);
1329 if (ElementTy != TargetTy)
1330 Indices.erase(Indices.end() - NumLayers, Indices.end());
1332 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1335 /// \brief Recursively compute indices for a natural GEP.
1337 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1338 /// element types adding appropriate indices for the GEP.
1339 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1340 Value *Ptr, Type *Ty, APInt &Offset,
1342 SmallVectorImpl<Value *> &Indices,
1345 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
1347 // We can't recurse through pointer types.
1348 if (Ty->isPointerTy())
1351 // We try to analyze GEPs over vectors here, but note that these GEPs are
1352 // extremely poorly defined currently. The long-term goal is to remove GEPing
1353 // over a vector from the IR completely.
1354 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1355 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1356 if (ElementSizeInBits % 8 != 0) {
1357 // GEPs over non-multiple of 8 size vector elements are invalid.
1360 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1361 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1362 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1364 Offset -= NumSkippedElements * ElementSize;
1365 Indices.push_back(IRB.getInt(NumSkippedElements));
1366 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1367 Offset, TargetTy, Indices, NamePrefix);
1370 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1371 Type *ElementTy = ArrTy->getElementType();
1372 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1373 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1374 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1377 Offset -= NumSkippedElements * ElementSize;
1378 Indices.push_back(IRB.getInt(NumSkippedElements));
1379 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1380 Indices, NamePrefix);
1383 StructType *STy = dyn_cast<StructType>(Ty);
1387 const StructLayout *SL = DL.getStructLayout(STy);
1388 uint64_t StructOffset = Offset.getZExtValue();
1389 if (StructOffset >= SL->getSizeInBytes())
1391 unsigned Index = SL->getElementContainingOffset(StructOffset);
1392 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1393 Type *ElementTy = STy->getElementType(Index);
1394 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1395 return nullptr; // The offset points into alignment padding.
1397 Indices.push_back(IRB.getInt32(Index));
1398 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1399 Indices, NamePrefix);
1402 /// \brief Get a natural GEP from a base pointer to a particular offset and
1403 /// resulting in a particular type.
1405 /// The goal is to produce a "natural" looking GEP that works with the existing
1406 /// composite types to arrive at the appropriate offset and element type for
1407 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1408 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1409 /// Indices, and setting Ty to the result subtype.
1411 /// If no natural GEP can be constructed, this function returns null.
1412 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1413 Value *Ptr, APInt Offset, Type *TargetTy,
1414 SmallVectorImpl<Value *> &Indices,
1416 PointerType *Ty = cast<PointerType>(Ptr->getType());
1418 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1420 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
1423 Type *ElementTy = Ty->getElementType();
1424 if (!ElementTy->isSized())
1425 return nullptr; // We can't GEP through an unsized element.
1426 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1427 if (ElementSize == 0)
1428 return nullptr; // Zero-length arrays can't help us build a natural GEP.
1429 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1431 Offset -= NumSkippedElements * ElementSize;
1432 Indices.push_back(IRB.getInt(NumSkippedElements));
1433 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1434 Indices, NamePrefix);
1437 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1438 /// resulting pointer has PointerTy.
1440 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1441 /// and produces the pointer type desired. Where it cannot, it will try to use
1442 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1443 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1444 /// bitcast to the type.
1446 /// The strategy for finding the more natural GEPs is to peel off layers of the
1447 /// pointer, walking back through bit casts and GEPs, searching for a base
1448 /// pointer from which we can compute a natural GEP with the desired
1449 /// properties. The algorithm tries to fold as many constant indices into
1450 /// a single GEP as possible, thus making each GEP more independent of the
1451 /// surrounding code.
1452 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1453 APInt Offset, Type *PointerTy,
1455 // Even though we don't look through PHI nodes, we could be called on an
1456 // instruction in an unreachable block, which may be on a cycle.
1457 SmallPtrSet<Value *, 4> Visited;
1458 Visited.insert(Ptr);
1459 SmallVector<Value *, 4> Indices;
1461 // We may end up computing an offset pointer that has the wrong type. If we
1462 // never are able to compute one directly that has the correct type, we'll
1463 // fall back to it, so keep it around here.
1464 Value *OffsetPtr = nullptr;
1466 // Remember any i8 pointer we come across to re-use if we need to do a raw
1468 Value *Int8Ptr = nullptr;
1469 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1471 Type *TargetTy = PointerTy->getPointerElementType();
1474 // First fold any existing GEPs into the offset.
1475 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1476 APInt GEPOffset(Offset.getBitWidth(), 0);
1477 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1479 Offset += GEPOffset;
1480 Ptr = GEP->getPointerOperand();
1481 if (!Visited.insert(Ptr))
1485 // See if we can perform a natural GEP here.
1487 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1488 Indices, NamePrefix)) {
1489 if (P->getType() == PointerTy) {
1490 // Zap any offset pointer that we ended up computing in previous rounds.
1491 if (OffsetPtr && OffsetPtr->use_empty())
1492 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1493 I->eraseFromParent();
1501 // Stash this pointer if we've found an i8*.
1502 if (Ptr->getType()->isIntegerTy(8)) {
1504 Int8PtrOffset = Offset;
1507 // Peel off a layer of the pointer and update the offset appropriately.
1508 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1509 Ptr = cast<Operator>(Ptr)->getOperand(0);
1510 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1511 if (GA->mayBeOverridden())
1513 Ptr = GA->getAliasee();
1517 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1518 } while (Visited.insert(Ptr));
1522 Int8Ptr = IRB.CreateBitCast(
1523 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1524 NamePrefix + "sroa_raw_cast");
1525 Int8PtrOffset = Offset;
1528 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1529 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1530 NamePrefix + "sroa_raw_idx");
1534 // On the off chance we were targeting i8*, guard the bitcast here.
1535 if (Ptr->getType() != PointerTy)
1536 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
1541 /// \brief Test whether we can convert a value from the old to the new type.
1543 /// This predicate should be used to guard calls to convertValue in order to
1544 /// ensure that we only try to convert viable values. The strategy is that we
1545 /// will peel off single element struct and array wrappings to get to an
1546 /// underlying value, and convert that value.
1547 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1550 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1551 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1552 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1554 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1556 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1559 // We can convert pointers to integers and vice-versa. Same for vectors
1560 // of pointers and integers.
1561 OldTy = OldTy->getScalarType();
1562 NewTy = NewTy->getScalarType();
1563 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1564 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1566 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1574 /// \brief Generic routine to convert an SSA value to a value of a different
1577 /// This will try various different casting techniques, such as bitcasts,
1578 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1579 /// two types for viability with this routine.
1580 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1582 Type *OldTy = V->getType();
1583 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1588 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1589 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1590 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1591 return IRB.CreateZExt(V, NewITy);
1593 // See if we need inttoptr for this type pair. A cast involving both scalars
1594 // and vectors requires and additional bitcast.
1595 if (OldTy->getScalarType()->isIntegerTy() &&
1596 NewTy->getScalarType()->isPointerTy()) {
1597 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1598 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1599 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1602 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1603 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1604 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1607 return IRB.CreateIntToPtr(V, NewTy);
1610 // See if we need ptrtoint for this type pair. A cast involving both scalars
1611 // and vectors requires and additional bitcast.
1612 if (OldTy->getScalarType()->isPointerTy() &&
1613 NewTy->getScalarType()->isIntegerTy()) {
1614 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1615 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1616 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1619 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1620 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1621 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1624 return IRB.CreatePtrToInt(V, NewTy);
1627 return IRB.CreateBitCast(V, NewTy);
1630 /// \brief Test whether the given slice use can be promoted to a vector.
1632 /// This function is called to test each entry in a partioning which is slated
1633 /// for a single slice.
1635 isVectorPromotionViableForSlice(const DataLayout &DL, uint64_t SliceBeginOffset,
1636 uint64_t SliceEndOffset, VectorType *Ty,
1637 uint64_t ElementSize, const Slice &S) {
1638 // First validate the slice offsets.
1639 uint64_t BeginOffset =
1640 std::max(S.beginOffset(), SliceBeginOffset) - SliceBeginOffset;
1641 uint64_t BeginIndex = BeginOffset / ElementSize;
1642 if (BeginIndex * ElementSize != BeginOffset ||
1643 BeginIndex >= Ty->getNumElements())
1645 uint64_t EndOffset =
1646 std::min(S.endOffset(), SliceEndOffset) - SliceBeginOffset;
1647 uint64_t EndIndex = EndOffset / ElementSize;
1648 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1651 assert(EndIndex > BeginIndex && "Empty vector!");
1652 uint64_t NumElements = EndIndex - BeginIndex;
1653 Type *SliceTy = (NumElements == 1)
1654 ? Ty->getElementType()
1655 : VectorType::get(Ty->getElementType(), NumElements);
1658 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1660 Use *U = S.getUse();
1662 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1663 if (MI->isVolatile())
1665 if (!S.isSplittable())
1666 return false; // Skip any unsplittable intrinsics.
1667 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1668 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1669 II->getIntrinsicID() != Intrinsic::lifetime_end)
1671 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1672 // Disable vector promotion when there are loads or stores of an FCA.
1674 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1675 if (LI->isVolatile())
1677 Type *LTy = LI->getType();
1678 if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) {
1679 assert(LTy->isIntegerTy());
1682 if (!canConvertValue(DL, SliceTy, LTy))
1684 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1685 if (SI->isVolatile())
1687 Type *STy = SI->getValueOperand()->getType();
1688 if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) {
1689 assert(STy->isIntegerTy());
1692 if (!canConvertValue(DL, STy, SliceTy))
1701 /// \brief Test whether the given alloca partitioning and range of slices can be
1702 /// promoted to a vector.
1704 /// This is a quick test to check whether we can rewrite a particular alloca
1705 /// partition (and its newly formed alloca) into a vector alloca with only
1706 /// whole-vector loads and stores such that it could be promoted to a vector
1707 /// SSA value. We only can ensure this for a limited set of operations, and we
1708 /// don't want to do the rewrites unless we are confident that the result will
1709 /// be promotable, so we have an early test here.
1711 isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy,
1712 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1713 AllocaSlices::const_range Slices,
1714 ArrayRef<AllocaSlices::iterator> SplitUses) {
1715 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1719 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
1721 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1722 // that aren't byte sized.
1723 if (ElementSize % 8)
1725 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
1726 "vector size not a multiple of element size?");
1729 for (const auto &S : Slices)
1730 if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
1731 Ty, ElementSize, S))
1734 for (const auto &SI : SplitUses)
1735 if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
1736 Ty, ElementSize, *SI))
1742 /// \brief Test whether a slice of an alloca is valid for integer widening.
1744 /// This implements the necessary checking for the \c isIntegerWideningViable
1745 /// test below on a single slice of the alloca.
1746 static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1748 uint64_t AllocBeginOffset,
1751 bool &WholeAllocaOp) {
1752 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1753 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
1755 // We can't reasonably handle cases where the load or store extends past
1756 // the end of the aloca's type and into its padding.
1760 Use *U = S.getUse();
1762 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1763 if (LI->isVolatile())
1765 if (RelBegin == 0 && RelEnd == Size)
1766 WholeAllocaOp = true;
1767 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1768 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1770 } else if (RelBegin != 0 || RelEnd != Size ||
1771 !canConvertValue(DL, AllocaTy, LI->getType())) {
1772 // Non-integer loads need to be convertible from the alloca type so that
1773 // they are promotable.
1776 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1777 Type *ValueTy = SI->getValueOperand()->getType();
1778 if (SI->isVolatile())
1780 if (RelBegin == 0 && RelEnd == Size)
1781 WholeAllocaOp = true;
1782 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
1783 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1785 } else if (RelBegin != 0 || RelEnd != Size ||
1786 !canConvertValue(DL, ValueTy, AllocaTy)) {
1787 // Non-integer stores need to be convertible to the alloca type so that
1788 // they are promotable.
1791 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1792 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1794 if (!S.isSplittable())
1795 return false; // Skip any unsplittable intrinsics.
1796 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1797 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1798 II->getIntrinsicID() != Intrinsic::lifetime_end)
1807 /// \brief Test whether the given alloca partition's integer operations can be
1808 /// widened to promotable ones.
1810 /// This is a quick test to check whether we can rewrite the integer loads and
1811 /// stores to a particular alloca into wider loads and stores and be able to
1812 /// promote the resulting alloca.
1814 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
1815 uint64_t AllocBeginOffset,
1816 AllocaSlices::const_range Slices,
1817 ArrayRef<AllocaSlices::iterator> SplitUses) {
1818 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
1819 // Don't create integer types larger than the maximum bitwidth.
1820 if (SizeInBits > IntegerType::MAX_INT_BITS)
1823 // Don't try to handle allocas with bit-padding.
1824 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
1827 // We need to ensure that an integer type with the appropriate bitwidth can
1828 // be converted to the alloca type, whatever that is. We don't want to force
1829 // the alloca itself to have an integer type if there is a more suitable one.
1830 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
1831 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1832 !canConvertValue(DL, IntTy, AllocaTy))
1835 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1837 // While examining uses, we ensure that the alloca has a covering load or
1838 // store. We don't want to widen the integer operations only to fail to
1839 // promote due to some other unsplittable entry (which we may make splittable
1840 // later). However, if there are only splittable uses, go ahead and assume
1841 // that we cover the alloca.
1842 bool WholeAllocaOp =
1843 Slices.begin() != Slices.end() ? false : DL.isLegalInteger(SizeInBits);
1845 for (const auto &S : Slices)
1846 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1850 for (const auto &SI : SplitUses)
1851 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1852 *SI, WholeAllocaOp))
1855 return WholeAllocaOp;
1858 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1859 IntegerType *Ty, uint64_t Offset,
1860 const Twine &Name) {
1861 DEBUG(dbgs() << " start: " << *V << "\n");
1862 IntegerType *IntTy = cast<IntegerType>(V->getType());
1863 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1864 "Element extends past full value");
1865 uint64_t ShAmt = 8*Offset;
1866 if (DL.isBigEndian())
1867 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1869 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
1870 DEBUG(dbgs() << " shifted: " << *V << "\n");
1872 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1873 "Cannot extract to a larger integer!");
1875 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
1876 DEBUG(dbgs() << " trunced: " << *V << "\n");
1881 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
1882 Value *V, uint64_t Offset, const Twine &Name) {
1883 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1884 IntegerType *Ty = cast<IntegerType>(V->getType());
1885 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1886 "Cannot insert a larger integer!");
1887 DEBUG(dbgs() << " start: " << *V << "\n");
1889 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
1890 DEBUG(dbgs() << " extended: " << *V << "\n");
1892 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1893 "Element store outside of alloca store");
1894 uint64_t ShAmt = 8*Offset;
1895 if (DL.isBigEndian())
1896 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1898 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
1899 DEBUG(dbgs() << " shifted: " << *V << "\n");
1902 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1903 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1904 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
1905 DEBUG(dbgs() << " masked: " << *Old << "\n");
1906 V = IRB.CreateOr(Old, V, Name + ".insert");
1907 DEBUG(dbgs() << " inserted: " << *V << "\n");
1912 static Value *extractVector(IRBuilderTy &IRB, Value *V,
1913 unsigned BeginIndex, unsigned EndIndex,
1914 const Twine &Name) {
1915 VectorType *VecTy = cast<VectorType>(V->getType());
1916 unsigned NumElements = EndIndex - BeginIndex;
1917 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1919 if (NumElements == VecTy->getNumElements())
1922 if (NumElements == 1) {
1923 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1925 DEBUG(dbgs() << " extract: " << *V << "\n");
1929 SmallVector<Constant*, 8> Mask;
1930 Mask.reserve(NumElements);
1931 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1932 Mask.push_back(IRB.getInt32(i));
1933 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1934 ConstantVector::get(Mask),
1936 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1940 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
1941 unsigned BeginIndex, const Twine &Name) {
1942 VectorType *VecTy = cast<VectorType>(Old->getType());
1943 assert(VecTy && "Can only insert a vector into a vector");
1945 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1947 // Single element to insert.
1948 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1950 DEBUG(dbgs() << " insert: " << *V << "\n");
1954 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1955 "Too many elements!");
1956 if (Ty->getNumElements() == VecTy->getNumElements()) {
1957 assert(V->getType() == VecTy && "Vector type mismatch");
1960 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1962 // When inserting a smaller vector into the larger to store, we first
1963 // use a shuffle vector to widen it with undef elements, and then
1964 // a second shuffle vector to select between the loaded vector and the
1966 SmallVector<Constant*, 8> Mask;
1967 Mask.reserve(VecTy->getNumElements());
1968 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1969 if (i >= BeginIndex && i < EndIndex)
1970 Mask.push_back(IRB.getInt32(i - BeginIndex));
1972 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1973 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1974 ConstantVector::get(Mask),
1976 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1979 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1980 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1982 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1984 DEBUG(dbgs() << " blend: " << *V << "\n");
1989 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
1990 /// to use a new alloca.
1992 /// Also implements the rewriting to vector-based accesses when the partition
1993 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1995 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
1996 // Befriend the base class so it can delegate to private visit methods.
1997 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1998 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
2000 const DataLayout &DL;
2003 AllocaInst &OldAI, &NewAI;
2004 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2007 // If we are rewriting an alloca partition which can be written as pure
2008 // vector operations, we stash extra information here. When VecTy is
2009 // non-null, we have some strict guarantees about the rewritten alloca:
2010 // - The new alloca is exactly the size of the vector type here.
2011 // - The accesses all either map to the entire vector or to a single
2013 // - The set of accessing instructions is only one of those handled above
2014 // in isVectorPromotionViable. Generally these are the same access kinds
2015 // which are promotable via mem2reg.
2018 uint64_t ElementSize;
2020 // This is a convenience and flag variable that will be null unless the new
2021 // alloca's integer operations should be widened to this integer type due to
2022 // passing isIntegerWideningViable above. If it is non-null, the desired
2023 // integer type will be stored here for easy access during rewriting.
2026 // The original offset of the slice currently being rewritten relative to
2027 // the original alloca.
2028 uint64_t BeginOffset, EndOffset;
2029 // The new offsets of the slice currently being rewritten relative to the
2031 uint64_t NewBeginOffset, NewEndOffset;
2037 Instruction *OldPtr;
2039 // Track post-rewrite users which are PHI nodes and Selects.
2040 SmallPtrSetImpl<PHINode *> &PHIUsers;
2041 SmallPtrSetImpl<SelectInst *> &SelectUsers;
2043 // Utility IR builder, whose name prefix is setup for each visited use, and
2044 // the insertion point is set to point to the user.
2048 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
2049 AllocaInst &OldAI, AllocaInst &NewAI,
2050 uint64_t NewAllocaBeginOffset,
2051 uint64_t NewAllocaEndOffset, bool IsVectorPromotable,
2052 bool IsIntegerPromotable,
2053 SmallPtrSetImpl<PHINode *> &PHIUsers,
2054 SmallPtrSetImpl<SelectInst *> &SelectUsers)
2055 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2056 NewAllocaBeginOffset(NewAllocaBeginOffset),
2057 NewAllocaEndOffset(NewAllocaEndOffset),
2058 NewAllocaTy(NewAI.getAllocatedType()),
2059 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : nullptr),
2060 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2061 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2062 IntTy(IsIntegerPromotable
2065 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2067 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
2068 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2069 IRB(NewAI.getContext(), ConstantFolder()) {
2071 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
2072 "Only multiple-of-8 sized vector elements are viable");
2075 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
2076 IsVectorPromotable != IsIntegerPromotable);
2079 bool visit(AllocaSlices::const_iterator I) {
2080 bool CanSROA = true;
2081 BeginOffset = I->beginOffset();
2082 EndOffset = I->endOffset();
2083 IsSplittable = I->isSplittable();
2085 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2087 // Compute the intersecting offset range.
2088 assert(BeginOffset < NewAllocaEndOffset);
2089 assert(EndOffset > NewAllocaBeginOffset);
2090 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2091 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2093 SliceSize = NewEndOffset - NewBeginOffset;
2095 OldUse = I->getUse();
2096 OldPtr = cast<Instruction>(OldUse->get());
2098 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2099 IRB.SetInsertPoint(OldUserI);
2100 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2101 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2103 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2110 // Make sure the other visit overloads are visible.
2113 // Every instruction which can end up as a user must have a rewrite rule.
2114 bool visitInstruction(Instruction &I) {
2115 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2116 llvm_unreachable("No rewrite rule for this instruction!");
2119 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2120 // Note that the offset computation can use BeginOffset or NewBeginOffset
2121 // interchangeably for unsplit slices.
2122 assert(IsSplit || BeginOffset == NewBeginOffset);
2123 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2126 StringRef OldName = OldPtr->getName();
2127 // Skip through the last '.sroa.' component of the name.
2128 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2129 if (LastSROAPrefix != StringRef::npos) {
2130 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2131 // Look for an SROA slice index.
2132 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2133 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2134 // Strip the index and look for the offset.
2135 OldName = OldName.substr(IndexEnd + 1);
2136 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2137 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2138 // Strip the offset.
2139 OldName = OldName.substr(OffsetEnd + 1);
2142 // Strip any SROA suffixes as well.
2143 OldName = OldName.substr(0, OldName.find(".sroa_"));
2146 return getAdjustedPtr(IRB, DL, &NewAI,
2147 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
2149 Twine(OldName) + "."
2156 /// \brief Compute suitable alignment to access this slice of the *new* alloca.
2158 /// You can optionally pass a type to this routine and if that type's ABI
2159 /// alignment is itself suitable, this will return zero.
2160 unsigned getSliceAlign(Type *Ty = nullptr) {
2161 unsigned NewAIAlign = NewAI.getAlignment();
2163 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2164 unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2165 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
2168 unsigned getIndex(uint64_t Offset) {
2169 assert(VecTy && "Can only call getIndex when rewriting a vector");
2170 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2171 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2172 uint32_t Index = RelOffset / ElementSize;
2173 assert(Index * ElementSize == RelOffset);
2177 void deleteIfTriviallyDead(Value *V) {
2178 Instruction *I = cast<Instruction>(V);
2179 if (isInstructionTriviallyDead(I))
2180 Pass.DeadInsts.insert(I);
2183 Value *rewriteVectorizedLoadInst() {
2184 unsigned BeginIndex = getIndex(NewBeginOffset);
2185 unsigned EndIndex = getIndex(NewEndOffset);
2186 assert(EndIndex > BeginIndex && "Empty vector!");
2188 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2190 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2193 Value *rewriteIntegerLoad(LoadInst &LI) {
2194 assert(IntTy && "We cannot insert an integer to the alloca");
2195 assert(!LI.isVolatile());
2196 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2198 V = convertValue(DL, IRB, V, IntTy);
2199 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2200 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2201 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
2202 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2207 bool visitLoadInst(LoadInst &LI) {
2208 DEBUG(dbgs() << " original: " << LI << "\n");
2209 Value *OldOp = LI.getOperand(0);
2210 assert(OldOp == OldPtr);
2212 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2214 bool IsPtrAdjusted = false;
2217 V = rewriteVectorizedLoadInst();
2218 } else if (IntTy && LI.getType()->isIntegerTy()) {
2219 V = rewriteIntegerLoad(LI);
2220 } else if (NewBeginOffset == NewAllocaBeginOffset &&
2221 canConvertValue(DL, NewAllocaTy, LI.getType())) {
2222 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2223 LI.isVolatile(), LI.getName());
2225 Type *LTy = TargetTy->getPointerTo();
2226 V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2227 getSliceAlign(TargetTy), LI.isVolatile(),
2229 IsPtrAdjusted = true;
2231 V = convertValue(DL, IRB, V, TargetTy);
2234 assert(!LI.isVolatile());
2235 assert(LI.getType()->isIntegerTy() &&
2236 "Only integer type loads and stores are split");
2237 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
2238 "Split load isn't smaller than original load");
2239 assert(LI.getType()->getIntegerBitWidth() ==
2240 DL.getTypeStoreSizeInBits(LI.getType()) &&
2241 "Non-byte-multiple bit width");
2242 // Move the insertion point just past the load so that we can refer to it.
2243 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
2244 // Create a placeholder value with the same type as LI to use as the
2245 // basis for the new value. This allows us to replace the uses of LI with
2246 // the computed value, and then replace the placeholder with LI, leaving
2247 // LI only used for this computation.
2249 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2250 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
2252 LI.replaceAllUsesWith(V);
2253 Placeholder->replaceAllUsesWith(&LI);
2256 LI.replaceAllUsesWith(V);
2259 Pass.DeadInsts.insert(&LI);
2260 deleteIfTriviallyDead(OldOp);
2261 DEBUG(dbgs() << " to: " << *V << "\n");
2262 return !LI.isVolatile() && !IsPtrAdjusted;
2265 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
2266 if (V->getType() != VecTy) {
2267 unsigned BeginIndex = getIndex(NewBeginOffset);
2268 unsigned EndIndex = getIndex(NewEndOffset);
2269 assert(EndIndex > BeginIndex && "Empty vector!");
2270 unsigned NumElements = EndIndex - BeginIndex;
2271 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2273 (NumElements == 1) ? ElementTy
2274 : VectorType::get(ElementTy, NumElements);
2275 if (V->getType() != SliceTy)
2276 V = convertValue(DL, IRB, V, SliceTy);
2278 // Mix in the existing elements.
2279 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2281 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2283 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2284 Pass.DeadInsts.insert(&SI);
2287 DEBUG(dbgs() << " to: " << *Store << "\n");
2291 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
2292 assert(IntTy && "We cannot extract an integer from the alloca");
2293 assert(!SI.isVolatile());
2294 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2295 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2297 Old = convertValue(DL, IRB, Old, IntTy);
2298 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2299 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2300 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
2303 V = convertValue(DL, IRB, V, NewAllocaTy);
2304 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2305 Pass.DeadInsts.insert(&SI);
2307 DEBUG(dbgs() << " to: " << *Store << "\n");
2311 bool visitStoreInst(StoreInst &SI) {
2312 DEBUG(dbgs() << " original: " << SI << "\n");
2313 Value *OldOp = SI.getOperand(1);
2314 assert(OldOp == OldPtr);
2316 Value *V = SI.getValueOperand();
2318 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2319 // alloca that should be re-examined after promoting this alloca.
2320 if (V->getType()->isPointerTy())
2321 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2322 Pass.PostPromotionWorklist.insert(AI);
2324 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
2325 assert(!SI.isVolatile());
2326 assert(V->getType()->isIntegerTy() &&
2327 "Only integer type loads and stores are split");
2328 assert(V->getType()->getIntegerBitWidth() ==
2329 DL.getTypeStoreSizeInBits(V->getType()) &&
2330 "Non-byte-multiple bit width");
2331 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2332 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
2337 return rewriteVectorizedStoreInst(V, SI, OldOp);
2338 if (IntTy && V->getType()->isIntegerTy())
2339 return rewriteIntegerStore(V, SI);
2342 if (NewBeginOffset == NewAllocaBeginOffset &&
2343 NewEndOffset == NewAllocaEndOffset &&
2344 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2345 V = convertValue(DL, IRB, V, NewAllocaTy);
2346 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2349 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
2350 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2354 Pass.DeadInsts.insert(&SI);
2355 deleteIfTriviallyDead(OldOp);
2357 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2358 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2361 /// \brief Compute an integer value from splatting an i8 across the given
2362 /// number of bytes.
2364 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2365 /// call this routine.
2366 /// FIXME: Heed the advice above.
2368 /// \param V The i8 value to splat.
2369 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2370 Value *getIntegerSplat(Value *V, unsigned Size) {
2371 assert(Size > 0 && "Expected a positive number of bytes.");
2372 IntegerType *VTy = cast<IntegerType>(V->getType());
2373 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2377 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2378 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
2379 ConstantExpr::getUDiv(
2380 Constant::getAllOnesValue(SplatIntTy),
2381 ConstantExpr::getZExt(
2382 Constant::getAllOnesValue(V->getType()),
2388 /// \brief Compute a vector splat for a given element value.
2389 Value *getVectorSplat(Value *V, unsigned NumElements) {
2390 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2391 DEBUG(dbgs() << " splat: " << *V << "\n");
2395 bool visitMemSetInst(MemSetInst &II) {
2396 DEBUG(dbgs() << " original: " << II << "\n");
2397 assert(II.getRawDest() == OldPtr);
2399 // If the memset has a variable size, it cannot be split, just adjust the
2400 // pointer to the new alloca.
2401 if (!isa<Constant>(II.getLength())) {
2403 assert(NewBeginOffset == BeginOffset);
2404 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2405 Type *CstTy = II.getAlignmentCst()->getType();
2406 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
2408 deleteIfTriviallyDead(OldPtr);
2412 // Record this instruction for deletion.
2413 Pass.DeadInsts.insert(&II);
2415 Type *AllocaTy = NewAI.getAllocatedType();
2416 Type *ScalarTy = AllocaTy->getScalarType();
2418 // If this doesn't map cleanly onto the alloca type, and that type isn't
2419 // a single value type, just emit a memset.
2420 if (!VecTy && !IntTy &&
2421 (BeginOffset > NewAllocaBeginOffset ||
2422 EndOffset < NewAllocaEndOffset ||
2423 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
2424 !AllocaTy->isSingleValueType() ||
2425 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2426 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
2427 Type *SizeTy = II.getLength()->getType();
2428 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2429 CallInst *New = IRB.CreateMemSet(
2430 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2431 getSliceAlign(), II.isVolatile());
2433 DEBUG(dbgs() << " to: " << *New << "\n");
2437 // If we can represent this as a simple value, we have to build the actual
2438 // value to store, which requires expanding the byte present in memset to
2439 // a sensible representation for the alloca type. This is essentially
2440 // splatting the byte to a sufficiently wide integer, splatting it across
2441 // any desired vector width, and bitcasting to the final type.
2445 // If this is a memset of a vectorized alloca, insert it.
2446 assert(ElementTy == ScalarTy);
2448 unsigned BeginIndex = getIndex(NewBeginOffset);
2449 unsigned EndIndex = getIndex(NewEndOffset);
2450 assert(EndIndex > BeginIndex && "Empty vector!");
2451 unsigned NumElements = EndIndex - BeginIndex;
2452 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2455 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2456 Splat = convertValue(DL, IRB, Splat, ElementTy);
2457 if (NumElements > 1)
2458 Splat = getVectorSplat(Splat, NumElements);
2460 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2462 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2464 // If this is a memset on an alloca where we can widen stores, insert the
2466 assert(!II.isVolatile());
2468 uint64_t Size = NewEndOffset - NewBeginOffset;
2469 V = getIntegerSplat(II.getValue(), Size);
2471 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2472 EndOffset != NewAllocaBeginOffset)) {
2473 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2475 Old = convertValue(DL, IRB, Old, IntTy);
2476 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2477 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2479 assert(V->getType() == IntTy &&
2480 "Wrong type for an alloca wide integer!");
2482 V = convertValue(DL, IRB, V, AllocaTy);
2484 // Established these invariants above.
2485 assert(NewBeginOffset == NewAllocaBeginOffset);
2486 assert(NewEndOffset == NewAllocaEndOffset);
2488 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2489 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2490 V = getVectorSplat(V, AllocaVecTy->getNumElements());
2492 V = convertValue(DL, IRB, V, AllocaTy);
2495 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2498 DEBUG(dbgs() << " to: " << *New << "\n");
2499 return !II.isVolatile();
2502 bool visitMemTransferInst(MemTransferInst &II) {
2503 // Rewriting of memory transfer instructions can be a bit tricky. We break
2504 // them into two categories: split intrinsics and unsplit intrinsics.
2506 DEBUG(dbgs() << " original: " << II << "\n");
2508 bool IsDest = &II.getRawDestUse() == OldUse;
2509 assert((IsDest && II.getRawDest() == OldPtr) ||
2510 (!IsDest && II.getRawSource() == OldPtr));
2512 unsigned SliceAlign = getSliceAlign();
2514 // For unsplit intrinsics, we simply modify the source and destination
2515 // pointers in place. This isn't just an optimization, it is a matter of
2516 // correctness. With unsplit intrinsics we may be dealing with transfers
2517 // within a single alloca before SROA ran, or with transfers that have
2518 // a variable length. We may also be dealing with memmove instead of
2519 // memcpy, and so simply updating the pointers is the necessary for us to
2520 // update both source and dest of a single call.
2521 if (!IsSplittable) {
2522 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2524 II.setDest(AdjustedPtr);
2526 II.setSource(AdjustedPtr);
2528 if (II.getAlignment() > SliceAlign) {
2529 Type *CstTy = II.getAlignmentCst()->getType();
2531 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
2534 DEBUG(dbgs() << " to: " << II << "\n");
2535 deleteIfTriviallyDead(OldPtr);
2538 // For split transfer intrinsics we have an incredibly useful assurance:
2539 // the source and destination do not reside within the same alloca, and at
2540 // least one of them does not escape. This means that we can replace
2541 // memmove with memcpy, and we don't need to worry about all manner of
2542 // downsides to splitting and transforming the operations.
2544 // If this doesn't map cleanly onto the alloca type, and that type isn't
2545 // a single value type, just emit a memcpy.
2548 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2549 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2550 !NewAI.getAllocatedType()->isSingleValueType());
2552 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2553 // size hasn't been shrunk based on analysis of the viable range, this is
2555 if (EmitMemCpy && &OldAI == &NewAI) {
2556 // Ensure the start lines up.
2557 assert(NewBeginOffset == BeginOffset);
2559 // Rewrite the size as needed.
2560 if (NewEndOffset != EndOffset)
2561 II.setLength(ConstantInt::get(II.getLength()->getType(),
2562 NewEndOffset - NewBeginOffset));
2565 // Record this instruction for deletion.
2566 Pass.DeadInsts.insert(&II);
2568 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2569 // alloca that should be re-examined after rewriting this instruction.
2570 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2572 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2573 assert(AI != &OldAI && AI != &NewAI &&
2574 "Splittable transfers cannot reach the same alloca on both ends.");
2575 Pass.Worklist.insert(AI);
2578 Type *OtherPtrTy = OtherPtr->getType();
2579 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2581 // Compute the relative offset for the other pointer within the transfer.
2582 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
2583 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2584 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2585 OtherOffset.zextOrTrunc(64).getZExtValue());
2588 // Compute the other pointer, folding as much as possible to produce
2589 // a single, simple GEP in most cases.
2590 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2591 OtherPtr->getName() + ".");
2593 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2594 Type *SizeTy = II.getLength()->getType();
2595 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2597 CallInst *New = IRB.CreateMemCpy(
2598 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2599 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
2601 DEBUG(dbgs() << " to: " << *New << "\n");
2605 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2606 NewEndOffset == NewAllocaEndOffset;
2607 uint64_t Size = NewEndOffset - NewBeginOffset;
2608 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2609 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2610 unsigned NumElements = EndIndex - BeginIndex;
2611 IntegerType *SubIntTy
2612 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : nullptr;
2614 // Reset the other pointer type to match the register type we're going to
2615 // use, but using the address space of the original other pointer.
2616 if (VecTy && !IsWholeAlloca) {
2617 if (NumElements == 1)
2618 OtherPtrTy = VecTy->getElementType();
2620 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2622 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
2623 } else if (IntTy && !IsWholeAlloca) {
2624 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2626 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
2629 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2630 OtherPtr->getName() + ".");
2631 unsigned SrcAlign = OtherAlign;
2632 Value *DstPtr = &NewAI;
2633 unsigned DstAlign = SliceAlign;
2635 std::swap(SrcPtr, DstPtr);
2636 std::swap(SrcAlign, DstAlign);
2640 if (VecTy && !IsWholeAlloca && !IsDest) {
2641 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2643 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
2644 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2645 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2647 Src = convertValue(DL, IRB, Src, IntTy);
2648 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2649 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
2651 Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
2655 if (VecTy && !IsWholeAlloca && IsDest) {
2656 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2658 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
2659 } else if (IntTy && !IsWholeAlloca && IsDest) {
2660 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2662 Old = convertValue(DL, IRB, Old, IntTy);
2663 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2664 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2665 Src = convertValue(DL, IRB, Src, NewAllocaTy);
2668 StoreInst *Store = cast<StoreInst>(
2669 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
2671 DEBUG(dbgs() << " to: " << *Store << "\n");
2672 return !II.isVolatile();
2675 bool visitIntrinsicInst(IntrinsicInst &II) {
2676 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2677 II.getIntrinsicID() == Intrinsic::lifetime_end);
2678 DEBUG(dbgs() << " original: " << II << "\n");
2679 assert(II.getArgOperand(1) == OldPtr);
2681 // Record this instruction for deletion.
2682 Pass.DeadInsts.insert(&II);
2685 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2686 NewEndOffset - NewBeginOffset);
2687 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2689 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2690 New = IRB.CreateLifetimeStart(Ptr, Size);
2692 New = IRB.CreateLifetimeEnd(Ptr, Size);
2695 DEBUG(dbgs() << " to: " << *New << "\n");
2699 bool visitPHINode(PHINode &PN) {
2700 DEBUG(dbgs() << " original: " << PN << "\n");
2701 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2702 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
2704 // We would like to compute a new pointer in only one place, but have it be
2705 // as local as possible to the PHI. To do that, we re-use the location of
2706 // the old pointer, which necessarily must be in the right position to
2707 // dominate the PHI.
2708 IRBuilderTy PtrBuilder(IRB);
2709 if (isa<PHINode>(OldPtr))
2710 PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
2712 PtrBuilder.SetInsertPoint(OldPtr);
2713 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
2715 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
2716 // Replace the operands which were using the old pointer.
2717 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
2719 DEBUG(dbgs() << " to: " << PN << "\n");
2720 deleteIfTriviallyDead(OldPtr);
2722 // PHIs can't be promoted on their own, but often can be speculated. We
2723 // check the speculation outside of the rewriter so that we see the
2724 // fully-rewritten alloca.
2725 PHIUsers.insert(&PN);
2729 bool visitSelectInst(SelectInst &SI) {
2730 DEBUG(dbgs() << " original: " << SI << "\n");
2731 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2732 "Pointer isn't an operand!");
2733 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2734 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
2736 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2737 // Replace the operands which were using the old pointer.
2738 if (SI.getOperand(1) == OldPtr)
2739 SI.setOperand(1, NewPtr);
2740 if (SI.getOperand(2) == OldPtr)
2741 SI.setOperand(2, NewPtr);
2743 DEBUG(dbgs() << " to: " << SI << "\n");
2744 deleteIfTriviallyDead(OldPtr);
2746 // Selects can't be promoted on their own, but often can be speculated. We
2747 // check the speculation outside of the rewriter so that we see the
2748 // fully-rewritten alloca.
2749 SelectUsers.insert(&SI);
2757 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2759 /// This pass aggressively rewrites all aggregate loads and stores on
2760 /// a particular pointer (or any pointer derived from it which we can identify)
2761 /// with scalar loads and stores.
2762 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2763 // Befriend the base class so it can delegate to private visit methods.
2764 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2766 const DataLayout &DL;
2768 /// Queue of pointer uses to analyze and potentially rewrite.
2769 SmallVector<Use *, 8> Queue;
2771 /// Set to prevent us from cycling with phi nodes and loops.
2772 SmallPtrSet<User *, 8> Visited;
2774 /// The current pointer use being rewritten. This is used to dig up the used
2775 /// value (as opposed to the user).
2779 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
2781 /// Rewrite loads and stores through a pointer and all pointers derived from
2783 bool rewrite(Instruction &I) {
2784 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2786 bool Changed = false;
2787 while (!Queue.empty()) {
2788 U = Queue.pop_back_val();
2789 Changed |= visit(cast<Instruction>(U->getUser()));
2795 /// Enqueue all the users of the given instruction for further processing.
2796 /// This uses a set to de-duplicate users.
2797 void enqueueUsers(Instruction &I) {
2798 for (Use &U : I.uses())
2799 if (Visited.insert(U.getUser()))
2800 Queue.push_back(&U);
2803 // Conservative default is to not rewrite anything.
2804 bool visitInstruction(Instruction &I) { return false; }
2806 /// \brief Generic recursive split emission class.
2807 template <typename Derived>
2810 /// The builder used to form new instructions.
2812 /// The indices which to be used with insert- or extractvalue to select the
2813 /// appropriate value within the aggregate.
2814 SmallVector<unsigned, 4> Indices;
2815 /// The indices to a GEP instruction which will move Ptr to the correct slot
2816 /// within the aggregate.
2817 SmallVector<Value *, 4> GEPIndices;
2818 /// The base pointer of the original op, used as a base for GEPing the
2819 /// split operations.
2822 /// Initialize the splitter with an insertion point, Ptr and start with a
2823 /// single zero GEP index.
2824 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
2825 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
2828 /// \brief Generic recursive split emission routine.
2830 /// This method recursively splits an aggregate op (load or store) into
2831 /// scalar or vector ops. It splits recursively until it hits a single value
2832 /// and emits that single value operation via the template argument.
2834 /// The logic of this routine relies on GEPs and insertvalue and
2835 /// extractvalue all operating with the same fundamental index list, merely
2836 /// formatted differently (GEPs need actual values).
2838 /// \param Ty The type being split recursively into smaller ops.
2839 /// \param Agg The aggregate value being built up or stored, depending on
2840 /// whether this is splitting a load or a store respectively.
2841 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2842 if (Ty->isSingleValueType())
2843 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
2845 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2846 unsigned OldSize = Indices.size();
2848 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2850 assert(Indices.size() == OldSize && "Did not return to the old size");
2851 Indices.push_back(Idx);
2852 GEPIndices.push_back(IRB.getInt32(Idx));
2853 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2854 GEPIndices.pop_back();
2860 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2861 unsigned OldSize = Indices.size();
2863 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2865 assert(Indices.size() == OldSize && "Did not return to the old size");
2866 Indices.push_back(Idx);
2867 GEPIndices.push_back(IRB.getInt32(Idx));
2868 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2869 GEPIndices.pop_back();
2875 llvm_unreachable("Only arrays and structs are aggregate loadable types");
2879 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
2880 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2881 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
2883 /// Emit a leaf load of a single value. This is called at the leaves of the
2884 /// recursive emission to actually load values.
2885 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2886 assert(Ty->isSingleValueType());
2887 // Load the single value and insert it using the indices.
2888 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2889 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
2890 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2891 DEBUG(dbgs() << " to: " << *Load << "\n");
2895 bool visitLoadInst(LoadInst &LI) {
2896 assert(LI.getPointerOperand() == *U);
2897 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2900 // We have an aggregate being loaded, split it apart.
2901 DEBUG(dbgs() << " original: " << LI << "\n");
2902 LoadOpSplitter Splitter(&LI, *U);
2903 Value *V = UndefValue::get(LI.getType());
2904 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
2905 LI.replaceAllUsesWith(V);
2906 LI.eraseFromParent();
2910 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
2911 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2912 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
2914 /// Emit a leaf store of a single value. This is called at the leaves of the
2915 /// recursive emission to actually produce stores.
2916 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2917 assert(Ty->isSingleValueType());
2918 // Extract the single value and store it using the indices.
2919 Value *Store = IRB.CreateStore(
2920 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2921 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2923 DEBUG(dbgs() << " to: " << *Store << "\n");
2927 bool visitStoreInst(StoreInst &SI) {
2928 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2930 Value *V = SI.getValueOperand();
2931 if (V->getType()->isSingleValueType())
2934 // We have an aggregate being stored, split it apart.
2935 DEBUG(dbgs() << " original: " << SI << "\n");
2936 StoreOpSplitter Splitter(&SI, *U);
2937 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
2938 SI.eraseFromParent();
2942 bool visitBitCastInst(BitCastInst &BC) {
2947 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2952 bool visitPHINode(PHINode &PN) {
2957 bool visitSelectInst(SelectInst &SI) {
2964 /// \brief Strip aggregate type wrapping.
2966 /// This removes no-op aggregate types wrapping an underlying type. It will
2967 /// strip as many layers of types as it can without changing either the type
2968 /// size or the allocated size.
2969 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2970 if (Ty->isSingleValueType())
2973 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2974 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2977 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2978 InnerTy = ArrTy->getElementType();
2979 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2980 const StructLayout *SL = DL.getStructLayout(STy);
2981 unsigned Index = SL->getElementContainingOffset(0);
2982 InnerTy = STy->getElementType(Index);
2987 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2988 TypeSize > DL.getTypeSizeInBits(InnerTy))
2991 return stripAggregateTypeWrapping(DL, InnerTy);
2994 /// \brief Try to find a partition of the aggregate type passed in for a given
2995 /// offset and size.
2997 /// This recurses through the aggregate type and tries to compute a subtype
2998 /// based on the offset and size. When the offset and size span a sub-section
2999 /// of an array, it will even compute a new array type for that sub-section,
3000 /// and the same for structs.
3002 /// Note that this routine is very strict and tries to find a partition of the
3003 /// type which produces the *exact* right offset and size. It is not forgiving
3004 /// when the size or offset cause either end of type-based partition to be off.
3005 /// Also, this is a best-effort routine. It is reasonable to give up and not
3006 /// return a type if necessary.
3007 static Type *getTypePartition(const DataLayout &DL, Type *Ty,
3008 uint64_t Offset, uint64_t Size) {
3009 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3010 return stripAggregateTypeWrapping(DL, Ty);
3011 if (Offset > DL.getTypeAllocSize(Ty) ||
3012 (DL.getTypeAllocSize(Ty) - Offset) < Size)
3015 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3016 // We can't partition pointers...
3017 if (SeqTy->isPointerTy())
3020 Type *ElementTy = SeqTy->getElementType();
3021 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3022 uint64_t NumSkippedElements = Offset / ElementSize;
3023 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
3024 if (NumSkippedElements >= ArrTy->getNumElements())
3026 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
3027 if (NumSkippedElements >= VecTy->getNumElements())
3030 Offset -= NumSkippedElements * ElementSize;
3032 // First check if we need to recurse.
3033 if (Offset > 0 || Size < ElementSize) {
3034 // Bail if the partition ends in a different array element.
3035 if ((Offset + Size) > ElementSize)
3037 // Recurse through the element type trying to peel off offset bytes.
3038 return getTypePartition(DL, ElementTy, Offset, Size);
3040 assert(Offset == 0);
3042 if (Size == ElementSize)
3043 return stripAggregateTypeWrapping(DL, ElementTy);
3044 assert(Size > ElementSize);
3045 uint64_t NumElements = Size / ElementSize;
3046 if (NumElements * ElementSize != Size)
3048 return ArrayType::get(ElementTy, NumElements);
3051 StructType *STy = dyn_cast<StructType>(Ty);
3055 const StructLayout *SL = DL.getStructLayout(STy);
3056 if (Offset >= SL->getSizeInBytes())
3058 uint64_t EndOffset = Offset + Size;
3059 if (EndOffset > SL->getSizeInBytes())
3062 unsigned Index = SL->getElementContainingOffset(Offset);
3063 Offset -= SL->getElementOffset(Index);
3065 Type *ElementTy = STy->getElementType(Index);
3066 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3067 if (Offset >= ElementSize)
3068 return nullptr; // The offset points into alignment padding.
3070 // See if any partition must be contained by the element.
3071 if (Offset > 0 || Size < ElementSize) {
3072 if ((Offset + Size) > ElementSize)
3074 return getTypePartition(DL, ElementTy, Offset, Size);
3076 assert(Offset == 0);
3078 if (Size == ElementSize)
3079 return stripAggregateTypeWrapping(DL, ElementTy);
3081 StructType::element_iterator EI = STy->element_begin() + Index,
3082 EE = STy->element_end();
3083 if (EndOffset < SL->getSizeInBytes()) {
3084 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3085 if (Index == EndIndex)
3086 return nullptr; // Within a single element and its padding.
3088 // Don't try to form "natural" types if the elements don't line up with the
3090 // FIXME: We could potentially recurse down through the last element in the
3091 // sub-struct to find a natural end point.
3092 if (SL->getElementOffset(EndIndex) != EndOffset)
3095 assert(Index < EndIndex);
3096 EE = STy->element_begin() + EndIndex;
3099 // Try to build up a sub-structure.
3100 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
3102 const StructLayout *SubSL = DL.getStructLayout(SubTy);
3103 if (Size != SubSL->getSizeInBytes())
3104 return nullptr; // The sub-struct doesn't have quite the size needed.
3109 /// \brief Rewrite an alloca partition's users.
3111 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3112 /// to rewrite uses of an alloca partition to be conducive for SSA value
3113 /// promotion. If the partition needs a new, more refined alloca, this will
3114 /// build that new alloca, preserving as much type information as possible, and
3115 /// rewrite the uses of the old alloca to point at the new one and have the
3116 /// appropriate new offsets. It also evaluates how successful the rewrite was
3117 /// at enabling promotion and if it was successful queues the alloca to be
3119 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3120 AllocaSlices::iterator B, AllocaSlices::iterator E,
3121 int64_t BeginOffset, int64_t EndOffset,
3122 ArrayRef<AllocaSlices::iterator> SplitUses) {
3123 assert(BeginOffset < EndOffset);
3124 uint64_t SliceSize = EndOffset - BeginOffset;
3126 // Try to compute a friendly type for this partition of the alloca. This
3127 // won't always succeed, in which case we fall back to a legal integer type
3128 // or an i8 array of an appropriate size.
3129 Type *SliceTy = nullptr;
3130 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
3131 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3132 SliceTy = CommonUseTy;
3134 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
3135 BeginOffset, SliceSize))
3136 SliceTy = TypePartitionTy;
3137 if ((!SliceTy || (SliceTy->isArrayTy() &&
3138 SliceTy->getArrayElementType()->isIntegerTy())) &&
3139 DL->isLegalInteger(SliceSize * 8))
3140 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3142 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3143 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
3145 bool IsVectorPromotable =
3146 isVectorPromotionViable(*DL, SliceTy, BeginOffset, EndOffset,
3147 AllocaSlices::const_range(B, E), SplitUses);
3149 bool IsIntegerPromotable =
3150 !IsVectorPromotable &&
3151 isIntegerWideningViable(*DL, SliceTy, BeginOffset,
3152 AllocaSlices::const_range(B, E), SplitUses);
3154 // Check for the case where we're going to rewrite to a new alloca of the
3155 // exact same type as the original, and with the same access offsets. In that
3156 // case, re-use the existing alloca, but still run through the rewriter to
3157 // perform phi and select speculation.
3159 if (SliceTy == AI.getAllocatedType()) {
3160 assert(BeginOffset == 0 &&
3161 "Non-zero begin offset but same alloca type");
3163 // FIXME: We should be able to bail at this point with "nothing changed".
3164 // FIXME: We might want to defer PHI speculation until after here.
3166 unsigned Alignment = AI.getAlignment();
3168 // The minimum alignment which users can rely on when the explicit
3169 // alignment is omitted or zero is that required by the ABI for this
3171 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
3173 Alignment = MinAlign(Alignment, BeginOffset);
3174 // If we will get at least this much alignment from the type alone, leave
3175 // the alloca's alignment unconstrained.
3176 if (Alignment <= DL->getABITypeAlignment(SliceTy))
3178 NewAI = new AllocaInst(SliceTy, nullptr, Alignment,
3179 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
3183 DEBUG(dbgs() << "Rewriting alloca partition "
3184 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3187 // Track the high watermark on the worklist as it is only relevant for
3188 // promoted allocas. We will reset it to this point if the alloca is not in
3189 // fact scheduled for promotion.
3190 unsigned PPWOldSize = PostPromotionWorklist.size();
3191 unsigned NumUses = 0;
3192 SmallPtrSet<PHINode *, 8> PHIUsers;
3193 SmallPtrSet<SelectInst *, 8> SelectUsers;
3195 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3196 EndOffset, IsVectorPromotable,
3197 IsIntegerPromotable, PHIUsers, SelectUsers);
3198 bool Promotable = true;
3199 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3200 SUE = SplitUses.end();
3201 SUI != SUE; ++SUI) {
3202 DEBUG(dbgs() << " rewriting split ");
3203 DEBUG(S.printSlice(dbgs(), *SUI, ""));
3204 Promotable &= Rewriter.visit(*SUI);
3207 for (AllocaSlices::iterator I = B; I != E; ++I) {
3208 DEBUG(dbgs() << " rewriting ");
3209 DEBUG(S.printSlice(dbgs(), I, ""));
3210 Promotable &= Rewriter.visit(I);
3214 NumAllocaPartitionUses += NumUses;
3215 MaxUsesPerAllocaPartition =
3216 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
3218 // Now that we've processed all the slices in the new partition, check if any
3219 // PHIs or Selects would block promotion.
3220 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3223 if (!isSafePHIToSpeculate(**I, DL)) {
3226 SelectUsers.clear();
3229 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3230 E = SelectUsers.end();
3232 if (!isSafeSelectToSpeculate(**I, DL)) {
3235 SelectUsers.clear();
3240 if (PHIUsers.empty() && SelectUsers.empty()) {
3241 // Promote the alloca.
3242 PromotableAllocas.push_back(NewAI);
3244 // If we have either PHIs or Selects to speculate, add them to those
3245 // worklists and re-queue the new alloca so that we promote in on the
3247 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3250 SpeculatablePHIs.insert(*I);
3251 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3252 E = SelectUsers.end();
3254 SpeculatableSelects.insert(*I);
3255 Worklist.insert(NewAI);
3258 // If we can't promote the alloca, iterate on it to check for new
3259 // refinements exposed by splitting the current alloca. Don't iterate on an
3260 // alloca which didn't actually change and didn't get promoted.
3262 Worklist.insert(NewAI);
3264 // Drop any post-promotion work items if promotion didn't happen.
3265 while (PostPromotionWorklist.size() > PPWOldSize)
3266 PostPromotionWorklist.pop_back();
3273 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3274 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
3275 if (Offset >= MaxSplitUseEndOffset) {
3277 MaxSplitUseEndOffset = 0;
3281 size_t SplitUsesOldSize = SplitUses.size();
3282 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
3283 [Offset](const AllocaSlices::iterator &I) {
3284 return I->endOffset() <= Offset;
3287 if (SplitUsesOldSize == SplitUses.size())
3290 // Recompute the max. While this is linear, so is remove_if.
3291 MaxSplitUseEndOffset = 0;
3292 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
3293 SUI = SplitUses.begin(),
3294 SUE = SplitUses.end();
3296 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3299 /// \brief Walks the slices of an alloca and form partitions based on them,
3300 /// rewriting each of their uses.
3301 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3302 if (S.begin() == S.end())
3305 unsigned NumPartitions = 0;
3306 bool Changed = false;
3307 SmallVector<AllocaSlices::iterator, 4> SplitUses;
3308 uint64_t MaxSplitUseEndOffset = 0;
3310 uint64_t BeginOffset = S.begin()->beginOffset();
3312 for (AllocaSlices::iterator SI = S.begin(), SJ = std::next(SI), SE = S.end();
3313 SI != SE; SI = SJ) {
3314 uint64_t MaxEndOffset = SI->endOffset();
3316 if (!SI->isSplittable()) {
3317 // When we're forming an unsplittable region, it must always start at the
3318 // first slice and will extend through its end.
3319 assert(BeginOffset == SI->beginOffset());
3321 // Form a partition including all of the overlapping slices with this
3322 // unsplittable slice.
3323 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3324 if (!SJ->isSplittable())
3325 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3329 assert(SI->isSplittable()); // Established above.
3331 // Collect all of the overlapping splittable slices.
3332 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3333 SJ->isSplittable()) {
3334 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3338 // Back up MaxEndOffset and SJ if we ended the span early when
3339 // encountering an unsplittable slice.
3340 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3341 assert(!SJ->isSplittable());
3342 MaxEndOffset = SJ->beginOffset();
3346 // Check if we have managed to move the end offset forward yet. If so,
3347 // we'll have to rewrite uses and erase old split uses.
3348 if (BeginOffset < MaxEndOffset) {
3349 // Rewrite a sequence of overlapping slices.
3351 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
3354 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3357 // Accumulate all the splittable slices from the [SI,SJ) region which
3358 // overlap going forward.
3359 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3360 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3361 SplitUses.push_back(SK);
3362 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
3365 // If we're already at the end and we have no split uses, we're done.
3366 if (SJ == SE && SplitUses.empty())
3369 // If we have no split uses or no gap in offsets, we're ready to move to
3371 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3372 BeginOffset = SJ->beginOffset();
3376 // Even if we have split slices, if the next slice is splittable and the
3377 // split slices reach it, we can simply set up the beginning offset of the
3378 // next iteration to bridge between them.
3379 if (SJ != SE && SJ->isSplittable() &&
3380 MaxSplitUseEndOffset > SJ->beginOffset()) {
3381 BeginOffset = MaxEndOffset;
3385 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3387 uint64_t PostSplitEndOffset =
3388 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
3390 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3395 break; // Skip the rest, we don't need to do any cleanup.
3397 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3398 PostSplitEndOffset);
3400 // Now just reset the begin offset for the next iteration.
3401 BeginOffset = SJ->beginOffset();
3404 NumAllocaPartitions += NumPartitions;
3405 MaxPartitionsPerAlloca =
3406 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
3411 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3412 void SROA::clobberUse(Use &U) {
3414 // Replace the use with an undef value.
3415 U = UndefValue::get(OldV->getType());
3417 // Check for this making an instruction dead. We have to garbage collect
3418 // all the dead instructions to ensure the uses of any alloca end up being
3420 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3421 if (isInstructionTriviallyDead(OldI)) {
3422 DeadInsts.insert(OldI);
3426 /// \brief Analyze an alloca for SROA.
3428 /// This analyzes the alloca to ensure we can reason about it, builds
3429 /// the slices of the alloca, and then hands it off to be split and
3430 /// rewritten as needed.
3431 bool SROA::runOnAlloca(AllocaInst &AI) {
3432 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3433 ++NumAllocasAnalyzed;
3435 // Special case dead allocas, as they're trivial.
3436 if (AI.use_empty()) {
3437 AI.eraseFromParent();
3441 // Skip alloca forms that this analysis can't handle.
3442 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3443 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
3446 bool Changed = false;
3448 // First, split any FCA loads and stores touching this alloca to promote
3449 // better splitting and promotion opportunities.
3450 AggLoadStoreRewriter AggRewriter(*DL);
3451 Changed |= AggRewriter.rewrite(AI);
3453 // Build the slices using a recursive instruction-visiting builder.
3454 AllocaSlices S(*DL, AI);
3455 DEBUG(S.print(dbgs()));
3459 // Delete all the dead users of this alloca before splitting and rewriting it.
3460 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3461 DE = S.dead_user_end();
3463 // Free up everything used by this instruction.
3464 for (Use &DeadOp : (*DI)->operands())
3467 // Now replace the uses of this instruction.
3468 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3470 // And mark it for deletion.
3471 DeadInsts.insert(*DI);
3474 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3475 DE = S.dead_op_end();
3481 // No slices to split. Leave the dead alloca for a later pass to clean up.
3482 if (S.begin() == S.end())
3485 Changed |= splitAlloca(AI, S);
3487 DEBUG(dbgs() << " Speculating PHIs\n");
3488 while (!SpeculatablePHIs.empty())
3489 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3491 DEBUG(dbgs() << " Speculating Selects\n");
3492 while (!SpeculatableSelects.empty())
3493 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3498 /// \brief Delete the dead instructions accumulated in this run.
3500 /// Recursively deletes the dead instructions we've accumulated. This is done
3501 /// at the very end to maximize locality of the recursive delete and to
3502 /// minimize the problems of invalidated instruction pointers as such pointers
3503 /// are used heavily in the intermediate stages of the algorithm.
3505 /// We also record the alloca instructions deleted here so that they aren't
3506 /// subsequently handed to mem2reg to promote.
3507 void SROA::deleteDeadInstructions(SmallPtrSetImpl<AllocaInst*> &DeletedAllocas) {
3508 while (!DeadInsts.empty()) {
3509 Instruction *I = DeadInsts.pop_back_val();
3510 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3512 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3514 for (Use &Operand : I->operands())
3515 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
3516 // Zero out the operand and see if it becomes trivially dead.
3518 if (isInstructionTriviallyDead(U))
3519 DeadInsts.insert(U);
3522 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3523 DeletedAllocas.insert(AI);
3526 I->eraseFromParent();
3530 static void enqueueUsersInWorklist(Instruction &I,
3531 SmallVectorImpl<Instruction *> &Worklist,
3532 SmallPtrSetImpl<Instruction *> &Visited) {
3533 for (User *U : I.users())
3534 if (Visited.insert(cast<Instruction>(U)))
3535 Worklist.push_back(cast<Instruction>(U));
3538 /// \brief Promote the allocas, using the best available technique.
3540 /// This attempts to promote whatever allocas have been identified as viable in
3541 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3542 /// If there is a domtree available, we attempt to promote using the full power
3543 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3544 /// based on the SSAUpdater utilities. This function returns whether any
3545 /// promotion occurred.
3546 bool SROA::promoteAllocas(Function &F) {
3547 if (PromotableAllocas.empty())
3550 NumPromoted += PromotableAllocas.size();
3552 if (DT && !ForceSSAUpdater) {
3553 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3554 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AT);
3555 PromotableAllocas.clear();
3559 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3561 DIBuilder DIB(*F.getParent());
3562 SmallVector<Instruction *, 64> Insts;
3564 // We need a worklist to walk the uses of each alloca.
3565 SmallVector<Instruction *, 8> Worklist;
3566 SmallPtrSet<Instruction *, 8> Visited;
3567 SmallVector<Instruction *, 32> DeadInsts;
3569 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3570 AllocaInst *AI = PromotableAllocas[Idx];
3575 enqueueUsersInWorklist(*AI, Worklist, Visited);
3577 while (!Worklist.empty()) {
3578 Instruction *I = Worklist.pop_back_val();
3580 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3581 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3582 // leading to them) here. Eventually it should use them to optimize the
3583 // scalar values produced.
3584 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3585 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3586 II->getIntrinsicID() == Intrinsic::lifetime_end);
3587 II->eraseFromParent();
3591 // Push the loads and stores we find onto the list. SROA will already
3592 // have validated that all loads and stores are viable candidates for
3594 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3595 assert(LI->getType() == AI->getAllocatedType());
3596 Insts.push_back(LI);
3599 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3600 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3601 Insts.push_back(SI);
3605 // For everything else, we know that only no-op bitcasts and GEPs will
3606 // make it this far, just recurse through them and recall them for later
3608 DeadInsts.push_back(I);
3609 enqueueUsersInWorklist(*I, Worklist, Visited);
3611 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3612 while (!DeadInsts.empty())
3613 DeadInsts.pop_back_val()->eraseFromParent();
3614 AI->eraseFromParent();
3617 PromotableAllocas.clear();
3621 bool SROA::runOnFunction(Function &F) {
3622 if (skipOptnoneFunction(F))
3625 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3626 C = &F.getContext();
3627 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3629 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3632 DL = &DLP->getDataLayout();
3633 DominatorTreeWrapperPass *DTWP =
3634 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
3635 DT = DTWP ? &DTWP->getDomTree() : nullptr;
3636 AT = &getAnalysis<AssumptionTracker>();
3638 BasicBlock &EntryBB = F.getEntryBlock();
3639 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
3641 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3642 Worklist.insert(AI);
3644 bool Changed = false;
3645 // A set of deleted alloca instruction pointers which should be removed from
3646 // the list of promotable allocas.
3647 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3650 while (!Worklist.empty()) {
3651 Changed |= runOnAlloca(*Worklist.pop_back_val());
3652 deleteDeadInstructions(DeletedAllocas);
3654 // Remove the deleted allocas from various lists so that we don't try to
3655 // continue processing them.
3656 if (!DeletedAllocas.empty()) {
3657 auto IsInSet = [&](AllocaInst *AI) {
3658 return DeletedAllocas.count(AI);
3660 Worklist.remove_if(IsInSet);
3661 PostPromotionWorklist.remove_if(IsInSet);
3662 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3663 PromotableAllocas.end(),
3665 PromotableAllocas.end());
3666 DeletedAllocas.clear();
3670 Changed |= promoteAllocas(F);
3672 Worklist = PostPromotionWorklist;
3673 PostPromotionWorklist.clear();
3674 } while (!Worklist.empty());
3679 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3680 AU.addRequired<AssumptionTracker>();
3681 if (RequiresDomTree)
3682 AU.addRequired<DominatorTreeWrapperPass>();
3683 AU.setPreservesCFG();