1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This transformation implements the well known scalar replacement of
11 /// aggregates transformation. It tries to identify promotable elements of an
12 /// aggregate alloca, and promote them to registers. It will also try to
13 /// convert uses of an element (or set of elements) of an alloca into a vector
14 /// or bitfield-style integer scalar if appropriate.
16 /// It works to do this with minimal slicing of the alloca so that regions
17 /// which are merely transferred in and out of external memory remain unchanged
18 /// and are not decomposed to scalar code.
20 /// Because this also performs alloca promotion, it can be thought of as also
21 /// serving the purpose of SSA formation. The algorithm iterates on the
22 /// function until all opportunities for promotion have been realized.
24 //===----------------------------------------------------------------------===//
26 #define DEBUG_TYPE "sroa"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/Loads.h"
33 #include "llvm/Analysis/PtrUseVisitor.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/DIBuilder.h"
36 #include "llvm/DebugInfo.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DataLayout.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/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/LLVMContext.h"
46 #include "llvm/IR/Operator.h"
47 #include "llvm/InstVisitor.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
57 #include "llvm/Transforms/Utils/SSAUpdater.h"
60 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
61 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
62 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
63 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
64 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
65 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
66 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
67 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
68 STATISTIC(NumDeleted, "Number of instructions deleted");
69 STATISTIC(NumVectorized, "Number of vectorized aggregates");
71 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
72 /// forming SSA values through the SSAUpdater infrastructure.
74 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
77 /// \brief A custom IRBuilder inserter which prefixes all names if they are
79 template <bool preserveNames = true>
80 class IRBuilderPrefixedInserter :
81 public IRBuilderDefaultInserter<preserveNames> {
85 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
88 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
89 BasicBlock::iterator InsertPt) const {
90 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
91 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
95 // Specialization for not preserving the name is trivial.
97 class IRBuilderPrefixedInserter<false> :
98 public IRBuilderDefaultInserter<false> {
100 void SetNamePrefix(const Twine &P) {}
103 /// \brief Provide a typedef for IRBuilder that drops names in release builds.
105 typedef llvm::IRBuilder<true, ConstantFolder,
106 IRBuilderPrefixedInserter<true> > IRBuilderTy;
108 typedef llvm::IRBuilder<false, ConstantFolder,
109 IRBuilderPrefixedInserter<false> > IRBuilderTy;
114 /// \brief A used slice of an alloca.
116 /// This structure represents a slice of an alloca used by some instruction. It
117 /// stores both the begin and end offsets of this use, a pointer to the use
118 /// itself, and a flag indicating whether we can classify the use as splittable
119 /// or not when forming partitions of the alloca.
121 /// \brief The beginning offset of the range.
122 uint64_t BeginOffset;
124 /// \brief The ending offset, not included in the range.
127 /// \brief Storage for both the use of this slice and whether it can be
129 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
132 Slice() : BeginOffset(), EndOffset() {}
133 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
134 : BeginOffset(BeginOffset), EndOffset(EndOffset),
135 UseAndIsSplittable(U, IsSplittable) {}
137 uint64_t beginOffset() const { return BeginOffset; }
138 uint64_t endOffset() const { return EndOffset; }
140 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
141 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
143 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
145 bool isDead() const { return getUse() == 0; }
146 void kill() { UseAndIsSplittable.setPointer(0); }
148 /// \brief Support for ordering ranges.
150 /// This provides an ordering over ranges such that start offsets are
151 /// always increasing, and within equal start offsets, the end offsets are
152 /// decreasing. Thus the spanning range comes first in a cluster with the
153 /// same start position.
154 bool operator<(const Slice &RHS) const {
155 if (beginOffset() < RHS.beginOffset()) return true;
156 if (beginOffset() > RHS.beginOffset()) return false;
157 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
158 if (endOffset() > RHS.endOffset()) return true;
162 /// \brief Support comparison with a single offset to allow binary searches.
163 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
164 uint64_t RHSOffset) {
165 return LHS.beginOffset() < RHSOffset;
167 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
169 return LHSOffset < RHS.beginOffset();
172 bool operator==(const Slice &RHS) const {
173 return isSplittable() == RHS.isSplittable() &&
174 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
176 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
178 } // end anonymous namespace
181 template <typename T> struct isPodLike;
182 template <> struct isPodLike<Slice> {
183 static const bool value = true;
188 /// \brief Representation of the alloca slices.
190 /// This class represents the slices of an alloca which are formed by its
191 /// various uses. If a pointer escapes, we can't fully build a representation
192 /// for the slices used and we reflect that in this structure. The uses are
193 /// stored, sorted by increasing beginning offset and with unsplittable slices
194 /// starting at a particular offset before splittable slices.
197 /// \brief Construct the slices of a particular alloca.
198 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
200 /// \brief Test whether a pointer to the allocation escapes our analysis.
202 /// If this is true, the slices are never fully built and should be
204 bool isEscaped() const { return PointerEscapingInstr; }
206 /// \brief Support for iterating over the slices.
208 typedef SmallVectorImpl<Slice>::iterator iterator;
209 iterator begin() { return Slices.begin(); }
210 iterator end() { return Slices.end(); }
212 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
213 const_iterator begin() const { return Slices.begin(); }
214 const_iterator end() const { return Slices.end(); }
217 /// \brief Allow iterating the dead users for this alloca.
219 /// These are instructions which will never actually use the alloca as they
220 /// are outside the allocated range. They are safe to replace with undef and
223 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
224 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
225 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
228 /// \brief Allow iterating the dead expressions referring to this alloca.
230 /// These are operands which have cannot actually be used to refer to the
231 /// alloca as they are outside its range and the user doesn't correct for
232 /// that. These mostly consist of PHI node inputs and the like which we just
233 /// need to replace with undef.
235 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
236 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
237 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
240 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
241 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
242 void printSlice(raw_ostream &OS, const_iterator I,
243 StringRef Indent = " ") const;
244 void printUse(raw_ostream &OS, const_iterator I,
245 StringRef Indent = " ") const;
246 void print(raw_ostream &OS) const;
247 void dump(const_iterator I) const;
252 template <typename DerivedT, typename RetT = void> class BuilderBase;
254 friend class AllocaSlices::SliceBuilder;
256 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
257 /// \brief Handle to alloca instruction to simplify method interfaces.
261 /// \brief The instruction responsible for this alloca not having a known set
264 /// When an instruction (potentially) escapes the pointer to the alloca, we
265 /// store a pointer to that here and abort trying to form slices of the
266 /// alloca. This will be null if the alloca slices are analyzed successfully.
267 Instruction *PointerEscapingInstr;
269 /// \brief The slices of the alloca.
271 /// We store a vector of the slices formed by uses of the alloca here. This
272 /// vector is sorted by increasing begin offset, and then the unsplittable
273 /// slices before the splittable ones. See the Slice inner class for more
275 SmallVector<Slice, 8> Slices;
277 /// \brief Instructions which will become dead if we rewrite the alloca.
279 /// Note that these are not separated by slice. This is because we expect an
280 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
281 /// all these instructions can simply be removed and replaced with undef as
282 /// they come from outside of the allocated space.
283 SmallVector<Instruction *, 8> DeadUsers;
285 /// \brief Operands which will become dead if we rewrite the alloca.
287 /// These are operands that in their particular use can be replaced with
288 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
289 /// to PHI nodes and the like. They aren't entirely dead (there might be
290 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
291 /// want to swap this particular input for undef to simplify the use lists of
293 SmallVector<Use *, 8> DeadOperands;
297 static Value *foldSelectInst(SelectInst &SI) {
298 // If the condition being selected on is a constant or the same value is
299 // being selected between, fold the select. Yes this does (rarely) happen
301 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
302 return SI.getOperand(1+CI->isZero());
303 if (SI.getOperand(1) == SI.getOperand(2))
304 return SI.getOperand(1);
309 /// \brief Builder for the alloca slices.
311 /// This class builds a set of alloca slices by recursively visiting the uses
312 /// of an alloca and making a slice for each load and store at each offset.
313 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
314 friend class PtrUseVisitor<SliceBuilder>;
315 friend class InstVisitor<SliceBuilder>;
316 typedef PtrUseVisitor<SliceBuilder> Base;
318 const uint64_t AllocSize;
321 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
322 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
324 /// \brief Set to de-duplicate dead instructions found in the use walk.
325 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
328 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
329 : PtrUseVisitor<SliceBuilder>(DL),
330 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
333 void markAsDead(Instruction &I) {
334 if (VisitedDeadInsts.insert(&I))
335 S.DeadUsers.push_back(&I);
338 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
339 bool IsSplittable = false) {
340 // Completely skip uses which have a zero size or start either before or
341 // past the end of the allocation.
342 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
343 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
344 << " which has zero size or starts outside of the "
345 << AllocSize << " byte alloca:\n"
346 << " alloca: " << S.AI << "\n"
347 << " use: " << I << "\n");
348 return markAsDead(I);
351 uint64_t BeginOffset = Offset.getZExtValue();
352 uint64_t EndOffset = BeginOffset + Size;
354 // Clamp the end offset to the end of the allocation. Note that this is
355 // formulated to handle even the case where "BeginOffset + Size" overflows.
356 // This may appear superficially to be something we could ignore entirely,
357 // but that is not so! There may be widened loads or PHI-node uses where
358 // some instructions are dead but not others. We can't completely ignore
359 // them, and so have to record at least the information here.
360 assert(AllocSize >= BeginOffset); // Established above.
361 if (Size > AllocSize - BeginOffset) {
362 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
363 << " to remain within the " << AllocSize << " byte alloca:\n"
364 << " alloca: " << S.AI << "\n"
365 << " use: " << I << "\n");
366 EndOffset = AllocSize;
369 S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
372 void visitBitCastInst(BitCastInst &BC) {
374 return markAsDead(BC);
376 return Base::visitBitCastInst(BC);
379 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
380 if (GEPI.use_empty())
381 return markAsDead(GEPI);
383 return Base::visitGetElementPtrInst(GEPI);
386 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
387 uint64_t Size, bool IsVolatile) {
388 // We allow splitting of loads and stores where the type is an integer type
389 // and cover the entire alloca. This prevents us from splitting over
391 // FIXME: In the great blue eventually, we should eagerly split all integer
392 // loads and stores, and then have a separate step that merges adjacent
393 // alloca partitions into a single partition suitable for integer widening.
394 // Or we should skip the merge step and rely on GVN and other passes to
395 // merge adjacent loads and stores that survive mem2reg.
397 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
399 insertUse(I, Offset, Size, IsSplittable);
402 void visitLoadInst(LoadInst &LI) {
403 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
404 "All simple FCA loads should have been pre-split");
407 return PI.setAborted(&LI);
409 uint64_t Size = DL.getTypeStoreSize(LI.getType());
410 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
413 void visitStoreInst(StoreInst &SI) {
414 Value *ValOp = SI.getValueOperand();
416 return PI.setEscapedAndAborted(&SI);
418 return PI.setAborted(&SI);
420 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
422 // If this memory access can be shown to *statically* extend outside the
423 // bounds of of the allocation, it's behavior is undefined, so simply
424 // ignore it. Note that this is more strict than the generic clamping
425 // behavior of insertUse. We also try to handle cases which might run the
427 // FIXME: We should instead consider the pointer to have escaped if this
428 // function is being instrumented for addressing bugs or race conditions.
429 if (Offset.isNegative() || Size > AllocSize ||
430 Offset.ugt(AllocSize - Size)) {
431 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
432 << " which extends past the end of the " << AllocSize
434 << " alloca: " << S.AI << "\n"
435 << " use: " << SI << "\n");
436 return markAsDead(SI);
439 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
440 "All simple FCA stores should have been pre-split");
441 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
445 void visitMemSetInst(MemSetInst &II) {
446 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
447 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
448 if ((Length && Length->getValue() == 0) ||
449 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
450 // Zero-length mem transfer intrinsics can be ignored entirely.
451 return markAsDead(II);
454 return PI.setAborted(&II);
456 insertUse(II, Offset,
457 Length ? Length->getLimitedValue()
458 : AllocSize - Offset.getLimitedValue(),
462 void visitMemTransferInst(MemTransferInst &II) {
463 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
464 if (Length && Length->getValue() == 0)
465 // Zero-length mem transfer intrinsics can be ignored entirely.
466 return markAsDead(II);
468 // Because we can visit these intrinsics twice, also check to see if the
469 // first time marked this instruction as dead. If so, skip it.
470 if (VisitedDeadInsts.count(&II))
474 return PI.setAborted(&II);
476 // This side of the transfer is completely out-of-bounds, and so we can
477 // nuke the entire transfer. However, we also need to nuke the other side
478 // if already added to our partitions.
479 // FIXME: Yet another place we really should bypass this when
480 // instrumenting for ASan.
481 if (!Offset.isNegative() && Offset.uge(AllocSize)) {
482 SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II);
483 if (MTPI != MemTransferSliceMap.end())
484 S.Slices[MTPI->second].kill();
485 return markAsDead(II);
488 uint64_t RawOffset = Offset.getLimitedValue();
489 uint64_t Size = Length ? Length->getLimitedValue()
490 : AllocSize - RawOffset;
492 // Check for the special case where the same exact value is used for both
494 if (*U == II.getRawDest() && *U == II.getRawSource()) {
495 // For non-volatile transfers this is a no-op.
496 if (!II.isVolatile())
497 return markAsDead(II);
499 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
502 // If we have seen both source and destination for a mem transfer, then
503 // they both point to the same alloca.
505 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
506 llvm::tie(MTPI, Inserted) =
507 MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
508 unsigned PrevIdx = MTPI->second;
510 Slice &PrevP = S.Slices[PrevIdx];
512 // Check if the begin offsets match and this is a non-volatile transfer.
513 // In that case, we can completely elide the transfer.
514 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
516 return markAsDead(II);
519 // Otherwise we have an offset transfer within the same alloca. We can't
521 PrevP.makeUnsplittable();
524 // Insert the use now that we've fixed up the splittable nature.
525 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
527 // Check that we ended up with a valid index in the map.
528 assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
529 "Map index doesn't point back to a slice with this user.");
532 // Disable SRoA for any intrinsics except for lifetime invariants.
533 // FIXME: What about debug intrinsics? This matches old behavior, but
534 // doesn't make sense.
535 void visitIntrinsicInst(IntrinsicInst &II) {
537 return PI.setAborted(&II);
539 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
540 II.getIntrinsicID() == Intrinsic::lifetime_end) {
541 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
542 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
543 Length->getLimitedValue());
544 insertUse(II, Offset, Size, true);
548 Base::visitIntrinsicInst(II);
551 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
552 // We consider any PHI or select that results in a direct load or store of
553 // the same offset to be a viable use for slicing purposes. These uses
554 // are considered unsplittable and the size is the maximum loaded or stored
556 SmallPtrSet<Instruction *, 4> Visited;
557 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
558 Visited.insert(Root);
559 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
560 // If there are no loads or stores, the access is dead. We mark that as
561 // a size zero access.
564 Instruction *I, *UsedI;
565 llvm::tie(UsedI, I) = Uses.pop_back_val();
567 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
568 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
571 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
572 Value *Op = SI->getOperand(0);
575 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
579 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
580 if (!GEP->hasAllZeroIndices())
582 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
583 !isa<SelectInst>(I)) {
587 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
589 if (Visited.insert(cast<Instruction>(*UI)))
590 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
591 } while (!Uses.empty());
596 void visitPHINode(PHINode &PN) {
598 return markAsDead(PN);
600 return PI.setAborted(&PN);
602 // See if we already have computed info on this node.
603 uint64_t &PHISize = PHIOrSelectSizes[&PN];
605 // This is a new PHI node, check for an unsafe use of the PHI node.
606 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
607 return PI.setAborted(UnsafeI);
610 // For PHI and select operands outside the alloca, we can't nuke the entire
611 // phi or select -- the other side might still be relevant, so we special
612 // case them here and use a separate structure to track the operands
613 // themselves which should be replaced with undef.
614 // FIXME: This should instead be escaped in the event we're instrumenting
615 // for address sanitization.
616 if ((Offset.isNegative() && (-Offset).uge(PHISize)) ||
617 (!Offset.isNegative() && Offset.uge(AllocSize))) {
618 S.DeadOperands.push_back(U);
622 insertUse(PN, Offset, PHISize);
625 void visitSelectInst(SelectInst &SI) {
627 return markAsDead(SI);
628 if (Value *Result = foldSelectInst(SI)) {
630 // If the result of the constant fold will be the pointer, recurse
631 // through the select as if we had RAUW'ed it.
634 // Otherwise the operand to the select is dead, and we can replace it
636 S.DeadOperands.push_back(U);
641 return PI.setAborted(&SI);
643 // See if we already have computed info on this node.
644 uint64_t &SelectSize = PHIOrSelectSizes[&SI];
646 // This is a new Select, check for an unsafe use of it.
647 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
648 return PI.setAborted(UnsafeI);
651 // For PHI and select operands outside the alloca, we can't nuke the entire
652 // phi or select -- the other side might still be relevant, so we special
653 // case them here and use a separate structure to track the operands
654 // themselves which should be replaced with undef.
655 // FIXME: This should instead be escaped in the event we're instrumenting
656 // for address sanitization.
657 if ((Offset.isNegative() && Offset.uge(SelectSize)) ||
658 (!Offset.isNegative() && Offset.uge(AllocSize))) {
659 S.DeadOperands.push_back(U);
663 insertUse(SI, Offset, SelectSize);
666 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
667 void visitInstruction(Instruction &I) {
672 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
674 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
677 PointerEscapingInstr(0) {
678 SliceBuilder PB(DL, AI, *this);
679 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
680 if (PtrI.isEscaped() || PtrI.isAborted()) {
681 // FIXME: We should sink the escape vs. abort info into the caller nicely,
682 // possibly by just storing the PtrInfo in the AllocaSlices.
683 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
684 : PtrI.getAbortingInst();
685 assert(PointerEscapingInstr && "Did not track a bad instruction");
689 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
690 std::mem_fun_ref(&Slice::isDead)),
693 // Sort the uses. This arranges for the offsets to be in ascending order,
694 // and the sizes to be in descending order.
695 std::sort(Slices.begin(), Slices.end());
698 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
700 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
701 StringRef Indent) const {
702 printSlice(OS, I, Indent);
703 printUse(OS, I, Indent);
706 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
707 StringRef Indent) const {
708 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
709 << " slice #" << (I - begin())
710 << (I->isSplittable() ? " (splittable)" : "") << "\n";
713 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
714 StringRef Indent) const {
715 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
718 void AllocaSlices::print(raw_ostream &OS) const {
719 if (PointerEscapingInstr) {
720 OS << "Can't analyze slices for alloca: " << AI << "\n"
721 << " A pointer to this alloca escaped by:\n"
722 << " " << *PointerEscapingInstr << "\n";
726 OS << "Slices of alloca: " << AI << "\n";
727 for (const_iterator I = begin(), E = end(); I != E; ++I)
731 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
734 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
736 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
739 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
741 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
742 /// the loads and stores of an alloca instruction, as well as updating its
743 /// debug information. This is used when a domtree is unavailable and thus
744 /// mem2reg in its full form can't be used to handle promotion of allocas to
746 class AllocaPromoter : public LoadAndStorePromoter {
750 SmallVector<DbgDeclareInst *, 4> DDIs;
751 SmallVector<DbgValueInst *, 4> DVIs;
754 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
755 AllocaInst &AI, DIBuilder &DIB)
756 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
758 void run(const SmallVectorImpl<Instruction*> &Insts) {
759 // Retain the debug information attached to the alloca for use when
760 // rewriting loads and stores.
761 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
762 for (Value::use_iterator UI = DebugNode->use_begin(),
763 UE = DebugNode->use_end();
765 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
767 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
771 LoadAndStorePromoter::run(Insts);
773 // While we have the debug information, clear it off of the alloca. The
774 // caller takes care of deleting the alloca.
775 while (!DDIs.empty())
776 DDIs.pop_back_val()->eraseFromParent();
777 while (!DVIs.empty())
778 DVIs.pop_back_val()->eraseFromParent();
781 virtual bool isInstInList(Instruction *I,
782 const SmallVectorImpl<Instruction*> &Insts) const {
784 if (LoadInst *LI = dyn_cast<LoadInst>(I))
785 Ptr = LI->getOperand(0);
787 Ptr = cast<StoreInst>(I)->getPointerOperand();
789 // Only used to detect cycles, which will be rare and quickly found as
790 // we're walking up a chain of defs rather than down through uses.
791 SmallPtrSet<Value *, 4> Visited;
797 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
798 Ptr = BCI->getOperand(0);
799 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
800 Ptr = GEPI->getPointerOperand();
804 } while (Visited.insert(Ptr));
809 virtual void updateDebugInfo(Instruction *Inst) const {
810 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
811 E = DDIs.end(); I != E; ++I) {
812 DbgDeclareInst *DDI = *I;
813 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
814 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
815 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
816 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
818 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
819 E = DVIs.end(); I != E; ++I) {
820 DbgValueInst *DVI = *I;
822 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
823 // If an argument is zero extended then use argument directly. The ZExt
824 // may be zapped by an optimization pass in future.
825 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
826 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
827 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
828 Arg = dyn_cast<Argument>(SExt->getOperand(0));
830 Arg = SI->getValueOperand();
831 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
832 Arg = LI->getPointerOperand();
836 Instruction *DbgVal =
837 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
839 DbgVal->setDebugLoc(DVI->getDebugLoc());
843 } // end anon namespace
847 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
849 /// This pass takes allocations which can be completely analyzed (that is, they
850 /// don't escape) and tries to turn them into scalar SSA values. There are
851 /// a few steps to this process.
853 /// 1) It takes allocations of aggregates and analyzes the ways in which they
854 /// are used to try to split them into smaller allocations, ideally of
855 /// a single scalar data type. It will split up memcpy and memset accesses
856 /// as necessary and try to isolate individual scalar accesses.
857 /// 2) It will transform accesses into forms which are suitable for SSA value
858 /// promotion. This can be replacing a memset with a scalar store of an
859 /// integer value, or it can involve speculating operations on a PHI or
860 /// select to be a PHI or select of the results.
861 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
862 /// onto insert and extract operations on a vector value, and convert them to
863 /// this form. By doing so, it will enable promotion of vector aggregates to
864 /// SSA vector values.
865 class SROA : public FunctionPass {
866 const bool RequiresDomTree;
869 const DataLayout *DL;
872 /// \brief Worklist of alloca instructions to simplify.
874 /// Each alloca in the function is added to this. Each new alloca formed gets
875 /// added to it as well to recursively simplify unless that alloca can be
876 /// directly promoted. Finally, each time we rewrite a use of an alloca other
877 /// the one being actively rewritten, we add it back onto the list if not
878 /// already present to ensure it is re-visited.
879 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
881 /// \brief A collection of instructions to delete.
882 /// We try to batch deletions to simplify code and make things a bit more
884 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
886 /// \brief Post-promotion worklist.
888 /// Sometimes we discover an alloca which has a high probability of becoming
889 /// viable for SROA after a round of promotion takes place. In those cases,
890 /// the alloca is enqueued here for re-processing.
892 /// Note that we have to be very careful to clear allocas out of this list in
893 /// the event they are deleted.
894 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
896 /// \brief A collection of alloca instructions we can directly promote.
897 std::vector<AllocaInst *> PromotableAllocas;
899 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
901 /// All of these PHIs have been checked for the safety of speculation and by
902 /// being speculated will allow promoting allocas currently in the promotable
904 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
906 /// \brief A worklist of select instructions to speculate prior to promoting
909 /// All of these select instructions have been checked for the safety of
910 /// speculation and by being speculated will allow promoting allocas
911 /// currently in the promotable queue.
912 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
915 SROA(bool RequiresDomTree = true)
916 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
918 initializeSROAPass(*PassRegistry::getPassRegistry());
920 bool runOnFunction(Function &F);
921 void getAnalysisUsage(AnalysisUsage &AU) const;
923 const char *getPassName() const { return "SROA"; }
927 friend class PHIOrSelectSpeculator;
928 friend class AllocaSliceRewriter;
930 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
931 AllocaSlices::iterator B, AllocaSlices::iterator E,
932 int64_t BeginOffset, int64_t EndOffset,
933 ArrayRef<AllocaSlices::iterator> SplitUses);
934 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
935 bool runOnAlloca(AllocaInst &AI);
936 void clobberUse(Use &U);
937 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
938 bool promoteAllocas(Function &F);
944 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
945 return new SROA(RequiresDomTree);
948 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
950 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
951 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
954 /// Walk the range of a partitioning looking for a common type to cover this
955 /// sequence of slices.
956 static Type *findCommonType(AllocaSlices::const_iterator B,
957 AllocaSlices::const_iterator E,
958 uint64_t EndOffset) {
960 bool TyIsCommon = true;
961 IntegerType *ITy = 0;
963 // Note that we need to look at *every* alloca slice's Use to ensure we
964 // always get consistent results regardless of the order of slices.
965 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
966 Use *U = I->getUse();
967 if (isa<IntrinsicInst>(*U->getUser()))
969 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
973 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
974 UserTy = LI->getType();
975 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
976 UserTy = SI->getValueOperand()->getType();
979 if (!UserTy || (Ty && Ty != UserTy))
980 TyIsCommon = false; // Give up on anything but an iN type.
984 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
985 // If the type is larger than the partition, skip it. We only encounter
986 // this for split integer operations where we want to use the type of the
987 // entity causing the split. Also skip if the type is not a byte width
989 if (UserITy->getBitWidth() % 8 != 0 ||
990 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
993 // Track the largest bitwidth integer type used in this way in case there
994 // is no common type.
995 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1000 return TyIsCommon ? Ty : ITy;
1003 /// PHI instructions that use an alloca and are subsequently loaded can be
1004 /// rewritten to load both input pointers in the pred blocks and then PHI the
1005 /// results, allowing the load of the alloca to be promoted.
1007 /// %P2 = phi [i32* %Alloca, i32* %Other]
1008 /// %V = load i32* %P2
1010 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1012 /// %V2 = load i32* %Other
1014 /// %V = phi [i32 %V1, i32 %V2]
1016 /// We can do this to a select if its only uses are loads and if the operands
1017 /// to the select can be loaded unconditionally.
1019 /// FIXME: This should be hoisted into a generic utility, likely in
1020 /// Transforms/Util/Local.h
1021 static bool isSafePHIToSpeculate(PHINode &PN,
1022 const DataLayout *DL = 0) {
1023 // For now, we can only do this promotion if the load is in the same block
1024 // as the PHI, and if there are no stores between the phi and load.
1025 // TODO: Allow recursive phi users.
1026 // TODO: Allow stores.
1027 BasicBlock *BB = PN.getParent();
1028 unsigned MaxAlign = 0;
1029 bool HaveLoad = false;
1030 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
1032 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1033 if (LI == 0 || !LI->isSimple())
1036 // For now we only allow loads in the same block as the PHI. This is
1037 // a common case that happens when instcombine merges two loads through
1039 if (LI->getParent() != BB)
1042 // Ensure that there are no instructions between the PHI and the load that
1044 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1045 if (BBI->mayWriteToMemory())
1048 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1055 // We can only transform this if it is safe to push the loads into the
1056 // predecessor blocks. The only thing to watch out for is that we can't put
1057 // a possibly trapping load in the predecessor if it is a critical edge.
1058 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1059 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1060 Value *InVal = PN.getIncomingValue(Idx);
1062 // If the value is produced by the terminator of the predecessor (an
1063 // invoke) or it has side-effects, there is no valid place to put a load
1064 // in the predecessor.
1065 if (TI == InVal || TI->mayHaveSideEffects())
1068 // If the predecessor has a single successor, then the edge isn't
1070 if (TI->getNumSuccessors() == 1)
1073 // If this pointer is always safe to load, or if we can prove that there
1074 // is already a load in the block, then we can move the load to the pred
1076 if (InVal->isDereferenceablePointer() ||
1077 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
1086 static void speculatePHINodeLoads(PHINode &PN) {
1087 DEBUG(dbgs() << " original: " << PN << "\n");
1089 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1090 IRBuilderTy PHIBuilder(&PN);
1091 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1092 PN.getName() + ".sroa.speculated");
1094 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1095 // matter which one we get and if any differ.
1096 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1097 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1098 unsigned Align = SomeLoad->getAlignment();
1100 // Rewrite all loads of the PN to use the new PHI.
1101 while (!PN.use_empty()) {
1102 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1103 LI->replaceAllUsesWith(NewPN);
1104 LI->eraseFromParent();
1107 // Inject loads into all of the pred blocks.
1108 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1109 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1110 TerminatorInst *TI = Pred->getTerminator();
1111 Value *InVal = PN.getIncomingValue(Idx);
1112 IRBuilderTy PredBuilder(TI);
1114 LoadInst *Load = PredBuilder.CreateLoad(
1115 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1116 ++NumLoadsSpeculated;
1117 Load->setAlignment(Align);
1119 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1120 NewPN->addIncoming(Load, Pred);
1123 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1124 PN.eraseFromParent();
1127 /// Select instructions that use an alloca and are subsequently loaded can be
1128 /// rewritten to load both input pointers and then select between the result,
1129 /// allowing the load of the alloca to be promoted.
1131 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1132 /// %V = load i32* %P2
1134 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1135 /// %V2 = load i32* %Other
1136 /// %V = select i1 %cond, i32 %V1, i32 %V2
1138 /// We can do this to a select if its only uses are loads and if the operand
1139 /// to the select can be loaded unconditionally.
1140 static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
1141 Value *TValue = SI.getTrueValue();
1142 Value *FValue = SI.getFalseValue();
1143 bool TDerefable = TValue->isDereferenceablePointer();
1144 bool FDerefable = FValue->isDereferenceablePointer();
1146 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1148 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1149 if (LI == 0 || !LI->isSimple())
1152 // Both operands to the select need to be dereferencable, either
1153 // absolutely (e.g. allocas) or at this point because we can see other
1156 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
1159 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
1166 static void speculateSelectInstLoads(SelectInst &SI) {
1167 DEBUG(dbgs() << " original: " << SI << "\n");
1169 IRBuilderTy IRB(&SI);
1170 Value *TV = SI.getTrueValue();
1171 Value *FV = SI.getFalseValue();
1172 // Replace the loads of the select with a select of two loads.
1173 while (!SI.use_empty()) {
1174 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1175 assert(LI->isSimple() && "We only speculate simple loads");
1177 IRB.SetInsertPoint(LI);
1179 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1181 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1182 NumLoadsSpeculated += 2;
1184 // Transfer alignment and TBAA info if present.
1185 TL->setAlignment(LI->getAlignment());
1186 FL->setAlignment(LI->getAlignment());
1187 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1188 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1189 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1192 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1193 LI->getName() + ".sroa.speculated");
1195 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1196 LI->replaceAllUsesWith(V);
1197 LI->eraseFromParent();
1199 SI.eraseFromParent();
1202 /// \brief Build a GEP out of a base pointer and indices.
1204 /// This will return the BasePtr if that is valid, or build a new GEP
1205 /// instruction using the IRBuilder if GEP-ing is needed.
1206 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1207 SmallVectorImpl<Value *> &Indices) {
1208 if (Indices.empty())
1211 // A single zero index is a no-op, so check for this and avoid building a GEP
1213 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1216 return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
1219 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1220 /// TargetTy without changing the offset of the pointer.
1222 /// This routine assumes we've already established a properly offset GEP with
1223 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1224 /// zero-indices down through type layers until we find one the same as
1225 /// TargetTy. If we can't find one with the same type, we at least try to use
1226 /// one with the same size. If none of that works, we just produce the GEP as
1227 /// indicated by Indices to have the correct offset.
1228 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1229 Value *BasePtr, Type *Ty, Type *TargetTy,
1230 SmallVectorImpl<Value *> &Indices) {
1232 return buildGEP(IRB, BasePtr, Indices);
1234 // See if we can descend into a struct and locate a field with the correct
1236 unsigned NumLayers = 0;
1237 Type *ElementTy = Ty;
1239 if (ElementTy->isPointerTy())
1241 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1242 ElementTy = SeqTy->getElementType();
1243 // Note that we use the default address space as this index is over an
1244 // array or a vector, not a pointer.
1245 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
1246 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1247 if (STy->element_begin() == STy->element_end())
1248 break; // Nothing left to descend into.
1249 ElementTy = *STy->element_begin();
1250 Indices.push_back(IRB.getInt32(0));
1255 } while (ElementTy != TargetTy);
1256 if (ElementTy != TargetTy)
1257 Indices.erase(Indices.end() - NumLayers, Indices.end());
1259 return buildGEP(IRB, BasePtr, Indices);
1262 /// \brief Recursively compute indices for a natural GEP.
1264 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1265 /// element types adding appropriate indices for the GEP.
1266 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1267 Value *Ptr, Type *Ty, APInt &Offset,
1269 SmallVectorImpl<Value *> &Indices) {
1271 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices);
1273 // We can't recurse through pointer types.
1274 if (Ty->isPointerTy())
1277 // We try to analyze GEPs over vectors here, but note that these GEPs are
1278 // extremely poorly defined currently. The long-term goal is to remove GEPing
1279 // over a vector from the IR completely.
1280 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1281 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1282 if (ElementSizeInBits % 8)
1283 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1284 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1285 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1286 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1288 Offset -= NumSkippedElements * ElementSize;
1289 Indices.push_back(IRB.getInt(NumSkippedElements));
1290 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1291 Offset, TargetTy, Indices);
1294 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1295 Type *ElementTy = ArrTy->getElementType();
1296 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1297 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1298 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1301 Offset -= NumSkippedElements * ElementSize;
1302 Indices.push_back(IRB.getInt(NumSkippedElements));
1303 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1307 StructType *STy = dyn_cast<StructType>(Ty);
1311 const StructLayout *SL = DL.getStructLayout(STy);
1312 uint64_t StructOffset = Offset.getZExtValue();
1313 if (StructOffset >= SL->getSizeInBytes())
1315 unsigned Index = SL->getElementContainingOffset(StructOffset);
1316 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1317 Type *ElementTy = STy->getElementType(Index);
1318 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1319 return 0; // The offset points into alignment padding.
1321 Indices.push_back(IRB.getInt32(Index));
1322 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1326 /// \brief Get a natural GEP from a base pointer to a particular offset and
1327 /// resulting in a particular type.
1329 /// The goal is to produce a "natural" looking GEP that works with the existing
1330 /// composite types to arrive at the appropriate offset and element type for
1331 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1332 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1333 /// Indices, and setting Ty to the result subtype.
1335 /// If no natural GEP can be constructed, this function returns null.
1336 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1337 Value *Ptr, APInt Offset, Type *TargetTy,
1338 SmallVectorImpl<Value *> &Indices) {
1339 PointerType *Ty = cast<PointerType>(Ptr->getType());
1341 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1343 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1346 Type *ElementTy = Ty->getElementType();
1347 if (!ElementTy->isSized())
1348 return 0; // We can't GEP through an unsized element.
1349 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1350 if (ElementSize == 0)
1351 return 0; // Zero-length arrays can't help us build a natural GEP.
1352 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1354 Offset -= NumSkippedElements * ElementSize;
1355 Indices.push_back(IRB.getInt(NumSkippedElements));
1356 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1360 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1361 /// resulting pointer has PointerTy.
1363 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1364 /// and produces the pointer type desired. Where it cannot, it will try to use
1365 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1366 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1367 /// bitcast to the type.
1369 /// The strategy for finding the more natural GEPs is to peel off layers of the
1370 /// pointer, walking back through bit casts and GEPs, searching for a base
1371 /// pointer from which we can compute a natural GEP with the desired
1372 /// properties. The algorithm tries to fold as many constant indices into
1373 /// a single GEP as possible, thus making each GEP more independent of the
1374 /// surrounding code.
1375 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL,
1376 Value *Ptr, APInt Offset, Type *PointerTy) {
1377 // Even though we don't look through PHI nodes, we could be called on an
1378 // instruction in an unreachable block, which may be on a cycle.
1379 SmallPtrSet<Value *, 4> Visited;
1380 Visited.insert(Ptr);
1381 SmallVector<Value *, 4> Indices;
1383 // We may end up computing an offset pointer that has the wrong type. If we
1384 // never are able to compute one directly that has the correct type, we'll
1385 // fall back to it, so keep it around here.
1386 Value *OffsetPtr = 0;
1388 // Remember any i8 pointer we come across to re-use if we need to do a raw
1391 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1393 Type *TargetTy = PointerTy->getPointerElementType();
1396 // First fold any existing GEPs into the offset.
1397 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1398 APInt GEPOffset(Offset.getBitWidth(), 0);
1399 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1401 Offset += GEPOffset;
1402 Ptr = GEP->getPointerOperand();
1403 if (!Visited.insert(Ptr))
1407 // See if we can perform a natural GEP here.
1409 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1411 if (P->getType() == PointerTy) {
1412 // Zap any offset pointer that we ended up computing in previous rounds.
1413 if (OffsetPtr && OffsetPtr->use_empty())
1414 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1415 I->eraseFromParent();
1423 // Stash this pointer if we've found an i8*.
1424 if (Ptr->getType()->isIntegerTy(8)) {
1426 Int8PtrOffset = Offset;
1429 // Peel off a layer of the pointer and update the offset appropriately.
1430 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1431 Ptr = cast<Operator>(Ptr)->getOperand(0);
1432 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1433 if (GA->mayBeOverridden())
1435 Ptr = GA->getAliasee();
1439 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1440 } while (Visited.insert(Ptr));
1444 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1446 Int8PtrOffset = Offset;
1449 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1450 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1455 // On the off chance we were targeting i8*, guard the bitcast here.
1456 if (Ptr->getType() != PointerTy)
1457 Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
1462 /// \brief Test whether we can convert a value from the old to the new type.
1464 /// This predicate should be used to guard calls to convertValue in order to
1465 /// ensure that we only try to convert viable values. The strategy is that we
1466 /// will peel off single element struct and array wrappings to get to an
1467 /// underlying value, and convert that value.
1468 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1471 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1472 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1473 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1475 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1477 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1480 // We can convert pointers to integers and vice-versa. Same for vectors
1481 // of pointers and integers.
1482 OldTy = OldTy->getScalarType();
1483 NewTy = NewTy->getScalarType();
1484 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1485 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1487 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1495 /// \brief Generic routine to convert an SSA value to a value of a different
1498 /// This will try various different casting techniques, such as bitcasts,
1499 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1500 /// two types for viability with this routine.
1501 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1503 Type *OldTy = V->getType();
1504 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1509 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1510 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1511 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1512 return IRB.CreateZExt(V, NewITy);
1514 // See if we need inttoptr for this type pair. A cast involving both scalars
1515 // and vectors requires and additional bitcast.
1516 if (OldTy->getScalarType()->isIntegerTy() &&
1517 NewTy->getScalarType()->isPointerTy()) {
1518 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1519 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1520 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1523 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1524 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1525 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1528 return IRB.CreateIntToPtr(V, NewTy);
1531 // See if we need ptrtoint for this type pair. A cast involving both scalars
1532 // and vectors requires and additional bitcast.
1533 if (OldTy->getScalarType()->isPointerTy() &&
1534 NewTy->getScalarType()->isIntegerTy()) {
1535 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1536 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1537 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1540 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1541 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1542 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1545 return IRB.CreatePtrToInt(V, NewTy);
1548 return IRB.CreateBitCast(V, NewTy);
1551 /// \brief Test whether the given slice use can be promoted to a vector.
1553 /// This function is called to test each entry in a partioning which is slated
1554 /// for a single slice.
1555 static bool isVectorPromotionViableForSlice(
1556 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1557 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1558 AllocaSlices::const_iterator I) {
1559 // First validate the slice offsets.
1560 uint64_t BeginOffset =
1561 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
1562 uint64_t BeginIndex = BeginOffset / ElementSize;
1563 if (BeginIndex * ElementSize != BeginOffset ||
1564 BeginIndex >= Ty->getNumElements())
1566 uint64_t EndOffset =
1567 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
1568 uint64_t EndIndex = EndOffset / ElementSize;
1569 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1572 assert(EndIndex > BeginIndex && "Empty vector!");
1573 uint64_t NumElements = EndIndex - BeginIndex;
1575 (NumElements == 1) ? Ty->getElementType()
1576 : VectorType::get(Ty->getElementType(), NumElements);
1579 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1581 Use *U = I->getUse();
1583 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1584 if (MI->isVolatile())
1586 if (!I->isSplittable())
1587 return false; // Skip any unsplittable intrinsics.
1588 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1589 // Disable vector promotion when there are loads or stores of an FCA.
1591 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1592 if (LI->isVolatile())
1594 Type *LTy = LI->getType();
1595 if (SliceBeginOffset > I->beginOffset() ||
1596 SliceEndOffset < I->endOffset()) {
1597 assert(LTy->isIntegerTy());
1600 if (!canConvertValue(DL, SliceTy, LTy))
1602 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1603 if (SI->isVolatile())
1605 Type *STy = SI->getValueOperand()->getType();
1606 if (SliceBeginOffset > I->beginOffset() ||
1607 SliceEndOffset < I->endOffset()) {
1608 assert(STy->isIntegerTy());
1611 if (!canConvertValue(DL, STy, SliceTy))
1620 /// \brief Test whether the given alloca partitioning and range of slices can be
1621 /// promoted to a vector.
1623 /// This is a quick test to check whether we can rewrite a particular alloca
1624 /// partition (and its newly formed alloca) into a vector alloca with only
1625 /// whole-vector loads and stores such that it could be promoted to a vector
1626 /// SSA value. We only can ensure this for a limited set of operations, and we
1627 /// don't want to do the rewrites unless we are confident that the result will
1628 /// be promotable, so we have an early test here.
1630 isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1631 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1632 AllocaSlices::const_iterator I,
1633 AllocaSlices::const_iterator E,
1634 ArrayRef<AllocaSlices::iterator> SplitUses) {
1635 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1639 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
1641 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1642 // that aren't byte sized.
1643 if (ElementSize % 8)
1645 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
1646 "vector size not a multiple of element size?");
1650 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1651 SliceEndOffset, Ty, ElementSize, I))
1654 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1655 SUE = SplitUses.end();
1657 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1658 SliceEndOffset, Ty, ElementSize, *SUI))
1664 /// \brief Test whether a slice of an alloca is valid for integer widening.
1666 /// This implements the necessary checking for the \c isIntegerWideningViable
1667 /// test below on a single slice of the alloca.
1668 static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1670 uint64_t AllocBeginOffset,
1671 uint64_t Size, AllocaSlices &S,
1672 AllocaSlices::const_iterator I,
1673 bool &WholeAllocaOp) {
1674 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1675 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1677 // We can't reasonably handle cases where the load or store extends past
1678 // the end of the aloca's type and into its padding.
1682 Use *U = I->getUse();
1684 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1685 if (LI->isVolatile())
1687 if (RelBegin == 0 && RelEnd == Size)
1688 WholeAllocaOp = true;
1689 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1690 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1692 } else if (RelBegin != 0 || RelEnd != Size ||
1693 !canConvertValue(DL, AllocaTy, LI->getType())) {
1694 // Non-integer loads need to be convertible from the alloca type so that
1695 // they are promotable.
1698 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1699 Type *ValueTy = SI->getValueOperand()->getType();
1700 if (SI->isVolatile())
1702 if (RelBegin == 0 && RelEnd == Size)
1703 WholeAllocaOp = true;
1704 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
1705 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1707 } else if (RelBegin != 0 || RelEnd != Size ||
1708 !canConvertValue(DL, ValueTy, AllocaTy)) {
1709 // Non-integer stores need to be convertible to the alloca type so that
1710 // they are promotable.
1713 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1714 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1716 if (!I->isSplittable())
1717 return false; // Skip any unsplittable intrinsics.
1718 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1719 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1720 II->getIntrinsicID() != Intrinsic::lifetime_end)
1729 /// \brief Test whether the given alloca partition's integer operations can be
1730 /// widened to promotable ones.
1732 /// This is a quick test to check whether we can rewrite the integer loads and
1733 /// stores to a particular alloca into wider loads and stores and be able to
1734 /// promote the resulting alloca.
1736 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
1737 uint64_t AllocBeginOffset, AllocaSlices &S,
1738 AllocaSlices::const_iterator I,
1739 AllocaSlices::const_iterator E,
1740 ArrayRef<AllocaSlices::iterator> SplitUses) {
1741 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
1742 // Don't create integer types larger than the maximum bitwidth.
1743 if (SizeInBits > IntegerType::MAX_INT_BITS)
1746 // Don't try to handle allocas with bit-padding.
1747 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
1750 // We need to ensure that an integer type with the appropriate bitwidth can
1751 // be converted to the alloca type, whatever that is. We don't want to force
1752 // the alloca itself to have an integer type if there is a more suitable one.
1753 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
1754 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1755 !canConvertValue(DL, IntTy, AllocaTy))
1758 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1760 // While examining uses, we ensure that the alloca has a covering load or
1761 // store. We don't want to widen the integer operations only to fail to
1762 // promote due to some other unsplittable entry (which we may make splittable
1763 // later). However, if there are only splittable uses, go ahead and assume
1764 // that we cover the alloca.
1765 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
1768 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1769 S, I, WholeAllocaOp))
1772 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1773 SUE = SplitUses.end();
1775 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1776 S, *SUI, WholeAllocaOp))
1779 return WholeAllocaOp;
1782 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1783 IntegerType *Ty, uint64_t Offset,
1784 const Twine &Name) {
1785 DEBUG(dbgs() << " start: " << *V << "\n");
1786 IntegerType *IntTy = cast<IntegerType>(V->getType());
1787 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1788 "Element extends past full value");
1789 uint64_t ShAmt = 8*Offset;
1790 if (DL.isBigEndian())
1791 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1793 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
1794 DEBUG(dbgs() << " shifted: " << *V << "\n");
1796 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1797 "Cannot extract to a larger integer!");
1799 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
1800 DEBUG(dbgs() << " trunced: " << *V << "\n");
1805 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
1806 Value *V, uint64_t Offset, const Twine &Name) {
1807 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1808 IntegerType *Ty = cast<IntegerType>(V->getType());
1809 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1810 "Cannot insert a larger integer!");
1811 DEBUG(dbgs() << " start: " << *V << "\n");
1813 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
1814 DEBUG(dbgs() << " extended: " << *V << "\n");
1816 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1817 "Element store outside of alloca store");
1818 uint64_t ShAmt = 8*Offset;
1819 if (DL.isBigEndian())
1820 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1822 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
1823 DEBUG(dbgs() << " shifted: " << *V << "\n");
1826 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1827 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1828 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
1829 DEBUG(dbgs() << " masked: " << *Old << "\n");
1830 V = IRB.CreateOr(Old, V, Name + ".insert");
1831 DEBUG(dbgs() << " inserted: " << *V << "\n");
1836 static Value *extractVector(IRBuilderTy &IRB, Value *V,
1837 unsigned BeginIndex, unsigned EndIndex,
1838 const Twine &Name) {
1839 VectorType *VecTy = cast<VectorType>(V->getType());
1840 unsigned NumElements = EndIndex - BeginIndex;
1841 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1843 if (NumElements == VecTy->getNumElements())
1846 if (NumElements == 1) {
1847 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1849 DEBUG(dbgs() << " extract: " << *V << "\n");
1853 SmallVector<Constant*, 8> Mask;
1854 Mask.reserve(NumElements);
1855 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1856 Mask.push_back(IRB.getInt32(i));
1857 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1858 ConstantVector::get(Mask),
1860 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1864 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
1865 unsigned BeginIndex, const Twine &Name) {
1866 VectorType *VecTy = cast<VectorType>(Old->getType());
1867 assert(VecTy && "Can only insert a vector into a vector");
1869 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1871 // Single element to insert.
1872 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1874 DEBUG(dbgs() << " insert: " << *V << "\n");
1878 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1879 "Too many elements!");
1880 if (Ty->getNumElements() == VecTy->getNumElements()) {
1881 assert(V->getType() == VecTy && "Vector type mismatch");
1884 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1886 // When inserting a smaller vector into the larger to store, we first
1887 // use a shuffle vector to widen it with undef elements, and then
1888 // a second shuffle vector to select between the loaded vector and the
1890 SmallVector<Constant*, 8> Mask;
1891 Mask.reserve(VecTy->getNumElements());
1892 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1893 if (i >= BeginIndex && i < EndIndex)
1894 Mask.push_back(IRB.getInt32(i - BeginIndex));
1896 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1897 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1898 ConstantVector::get(Mask),
1900 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1903 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1904 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1906 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1908 DEBUG(dbgs() << " blend: " << *V << "\n");
1913 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
1914 /// to use a new alloca.
1916 /// Also implements the rewriting to vector-based accesses when the partition
1917 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1919 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
1920 // Befriend the base class so it can delegate to private visit methods.
1921 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1922 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
1924 const DataLayout &DL;
1927 AllocaInst &OldAI, &NewAI;
1928 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1931 // If we are rewriting an alloca partition which can be written as pure
1932 // vector operations, we stash extra information here. When VecTy is
1933 // non-null, we have some strict guarantees about the rewritten alloca:
1934 // - The new alloca is exactly the size of the vector type here.
1935 // - The accesses all either map to the entire vector or to a single
1937 // - The set of accessing instructions is only one of those handled above
1938 // in isVectorPromotionViable. Generally these are the same access kinds
1939 // which are promotable via mem2reg.
1942 uint64_t ElementSize;
1944 // This is a convenience and flag variable that will be null unless the new
1945 // alloca's integer operations should be widened to this integer type due to
1946 // passing isIntegerWideningViable above. If it is non-null, the desired
1947 // integer type will be stored here for easy access during rewriting.
1950 // The offset of the slice currently being rewritten.
1951 uint64_t BeginOffset, EndOffset;
1955 Instruction *OldPtr;
1957 // Track post-rewrite users which are PHI nodes and Selects.
1958 SmallPtrSetImpl<PHINode *> &PHIUsers;
1959 SmallPtrSetImpl<SelectInst *> &SelectUsers;
1961 // Utility IR builder, whose name prefix is setup for each visited use, and
1962 // the insertion point is set to point to the user.
1966 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
1967 AllocaInst &OldAI, AllocaInst &NewAI,
1968 uint64_t NewBeginOffset, uint64_t NewEndOffset,
1969 bool IsVectorPromotable, bool IsIntegerPromotable,
1970 SmallPtrSetImpl<PHINode *> &PHIUsers,
1971 SmallPtrSetImpl<SelectInst *> &SelectUsers)
1972 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
1973 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1974 NewAllocaTy(NewAI.getAllocatedType()),
1975 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1976 ElementTy(VecTy ? VecTy->getElementType() : 0),
1977 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
1978 IntTy(IsIntegerPromotable
1981 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
1983 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
1984 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
1985 IRB(NewAI.getContext(), ConstantFolder()) {
1987 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
1988 "Only multiple-of-8 sized vector elements are viable");
1991 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
1992 IsVectorPromotable != IsIntegerPromotable);
1995 bool visit(AllocaSlices::const_iterator I) {
1996 bool CanSROA = true;
1997 BeginOffset = I->beginOffset();
1998 EndOffset = I->endOffset();
1999 IsSplittable = I->isSplittable();
2001 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2003 OldUse = I->getUse();
2004 OldPtr = cast<Instruction>(OldUse->get());
2006 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2007 IRB.SetInsertPoint(OldUserI);
2008 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2009 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2011 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2018 // Make sure the other visit overloads are visible.
2021 // Every instruction which can end up as a user must have a rewrite rule.
2022 bool visitInstruction(Instruction &I) {
2023 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2024 llvm_unreachable("No rewrite rule for this instruction!");
2027 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
2029 assert(Offset >= NewAllocaBeginOffset);
2030 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
2031 Offset - NewAllocaBeginOffset),
2035 /// \brief Compute suitable alignment to access an offset into the new alloca.
2036 unsigned getOffsetAlign(uint64_t Offset) {
2037 unsigned NewAIAlign = NewAI.getAlignment();
2039 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2040 return MinAlign(NewAIAlign, Offset);
2043 /// \brief Compute suitable alignment to access a type at an offset of the
2046 /// \returns zero if the type's ABI alignment is a suitable alignment,
2047 /// otherwise returns the maximal suitable alignment.
2048 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2049 unsigned Align = getOffsetAlign(Offset);
2050 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
2053 unsigned getIndex(uint64_t Offset) {
2054 assert(VecTy && "Can only call getIndex when rewriting a vector");
2055 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2056 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2057 uint32_t Index = RelOffset / ElementSize;
2058 assert(Index * ElementSize == RelOffset);
2062 void deleteIfTriviallyDead(Value *V) {
2063 Instruction *I = cast<Instruction>(V);
2064 if (isInstructionTriviallyDead(I))
2065 Pass.DeadInsts.insert(I);
2068 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
2069 uint64_t NewEndOffset) {
2070 unsigned BeginIndex = getIndex(NewBeginOffset);
2071 unsigned EndIndex = getIndex(NewEndOffset);
2072 assert(EndIndex > BeginIndex && "Empty vector!");
2074 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2076 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2079 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2080 uint64_t NewEndOffset) {
2081 assert(IntTy && "We cannot insert an integer to the alloca");
2082 assert(!LI.isVolatile());
2083 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2085 V = convertValue(DL, IRB, V, IntTy);
2086 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2087 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2088 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
2089 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2094 bool visitLoadInst(LoadInst &LI) {
2095 DEBUG(dbgs() << " original: " << LI << "\n");
2096 Value *OldOp = LI.getOperand(0);
2097 assert(OldOp == OldPtr);
2099 // Compute the intersecting offset range.
2100 assert(BeginOffset < NewAllocaEndOffset);
2101 assert(EndOffset > NewAllocaBeginOffset);
2102 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2103 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2105 uint64_t Size = NewEndOffset - NewBeginOffset;
2107 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2109 bool IsPtrAdjusted = false;
2112 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
2113 } else if (IntTy && LI.getType()->isIntegerTy()) {
2114 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2115 } else if (NewBeginOffset == NewAllocaBeginOffset &&
2116 canConvertValue(DL, NewAllocaTy, LI.getType())) {
2117 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2118 LI.isVolatile(), "load");
2120 Type *LTy = TargetTy->getPointerTo();
2121 V = IRB.CreateAlignedLoad(
2122 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2123 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2124 LI.isVolatile(), "load");
2125 IsPtrAdjusted = true;
2127 V = convertValue(DL, IRB, V, TargetTy);
2130 assert(!LI.isVolatile());
2131 assert(LI.getType()->isIntegerTy() &&
2132 "Only integer type loads and stores are split");
2133 assert(Size < DL.getTypeStoreSize(LI.getType()) &&
2134 "Split load isn't smaller than original load");
2135 assert(LI.getType()->getIntegerBitWidth() ==
2136 DL.getTypeStoreSizeInBits(LI.getType()) &&
2137 "Non-byte-multiple bit width");
2138 // Move the insertion point just past the load so that we can refer to it.
2139 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
2140 // Create a placeholder value with the same type as LI to use as the
2141 // basis for the new value. This allows us to replace the uses of LI with
2142 // the computed value, and then replace the placeholder with LI, leaving
2143 // LI only used for this computation.
2145 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2146 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
2148 LI.replaceAllUsesWith(V);
2149 Placeholder->replaceAllUsesWith(&LI);
2152 LI.replaceAllUsesWith(V);
2155 Pass.DeadInsts.insert(&LI);
2156 deleteIfTriviallyDead(OldOp);
2157 DEBUG(dbgs() << " to: " << *V << "\n");
2158 return !LI.isVolatile() && !IsPtrAdjusted;
2161 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2162 uint64_t NewBeginOffset,
2163 uint64_t NewEndOffset) {
2164 if (V->getType() != VecTy) {
2165 unsigned BeginIndex = getIndex(NewBeginOffset);
2166 unsigned EndIndex = getIndex(NewEndOffset);
2167 assert(EndIndex > BeginIndex && "Empty vector!");
2168 unsigned NumElements = EndIndex - BeginIndex;
2169 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2171 (NumElements == 1) ? ElementTy
2172 : VectorType::get(ElementTy, NumElements);
2173 if (V->getType() != SliceTy)
2174 V = convertValue(DL, IRB, V, SliceTy);
2176 // Mix in the existing elements.
2177 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2179 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2181 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2182 Pass.DeadInsts.insert(&SI);
2185 DEBUG(dbgs() << " to: " << *Store << "\n");
2189 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2190 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
2191 assert(IntTy && "We cannot extract an integer from the alloca");
2192 assert(!SI.isVolatile());
2193 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2194 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2196 Old = convertValue(DL, IRB, Old, IntTy);
2197 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2198 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2199 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
2202 V = convertValue(DL, IRB, V, NewAllocaTy);
2203 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2204 Pass.DeadInsts.insert(&SI);
2206 DEBUG(dbgs() << " to: " << *Store << "\n");
2210 bool visitStoreInst(StoreInst &SI) {
2211 DEBUG(dbgs() << " original: " << SI << "\n");
2212 Value *OldOp = SI.getOperand(1);
2213 assert(OldOp == OldPtr);
2215 Value *V = SI.getValueOperand();
2217 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2218 // alloca that should be re-examined after promoting this alloca.
2219 if (V->getType()->isPointerTy())
2220 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2221 Pass.PostPromotionWorklist.insert(AI);
2223 // Compute the intersecting offset range.
2224 assert(BeginOffset < NewAllocaEndOffset);
2225 assert(EndOffset > NewAllocaBeginOffset);
2226 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2227 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2229 uint64_t Size = NewEndOffset - NewBeginOffset;
2230 if (Size < DL.getTypeStoreSize(V->getType())) {
2231 assert(!SI.isVolatile());
2232 assert(V->getType()->isIntegerTy() &&
2233 "Only integer type loads and stores are split");
2234 assert(V->getType()->getIntegerBitWidth() ==
2235 DL.getTypeStoreSizeInBits(V->getType()) &&
2236 "Non-byte-multiple bit width");
2237 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2238 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
2243 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2245 if (IntTy && V->getType()->isIntegerTy())
2246 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
2249 if (NewBeginOffset == NewAllocaBeginOffset &&
2250 NewEndOffset == NewAllocaEndOffset &&
2251 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2252 V = convertValue(DL, IRB, V, NewAllocaTy);
2253 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2256 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2257 V->getType()->getPointerTo());
2258 NewSI = IRB.CreateAlignedStore(
2259 V, NewPtr, getOffsetTypeAlign(
2260 V->getType(), NewBeginOffset - NewAllocaBeginOffset),
2264 Pass.DeadInsts.insert(&SI);
2265 deleteIfTriviallyDead(OldOp);
2267 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2268 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2271 /// \brief Compute an integer value from splatting an i8 across the given
2272 /// number of bytes.
2274 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2275 /// call this routine.
2276 /// FIXME: Heed the advice above.
2278 /// \param V The i8 value to splat.
2279 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2280 Value *getIntegerSplat(Value *V, unsigned Size) {
2281 assert(Size > 0 && "Expected a positive number of bytes.");
2282 IntegerType *VTy = cast<IntegerType>(V->getType());
2283 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2287 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2288 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
2289 ConstantExpr::getUDiv(
2290 Constant::getAllOnesValue(SplatIntTy),
2291 ConstantExpr::getZExt(
2292 Constant::getAllOnesValue(V->getType()),
2298 /// \brief Compute a vector splat for a given element value.
2299 Value *getVectorSplat(Value *V, unsigned NumElements) {
2300 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2301 DEBUG(dbgs() << " splat: " << *V << "\n");
2305 bool visitMemSetInst(MemSetInst &II) {
2306 DEBUG(dbgs() << " original: " << II << "\n");
2307 assert(II.getRawDest() == OldPtr);
2309 // If the memset has a variable size, it cannot be split, just adjust the
2310 // pointer to the new alloca.
2311 if (!isa<Constant>(II.getLength())) {
2313 assert(BeginOffset >= NewAllocaBeginOffset);
2315 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
2316 Type *CstTy = II.getAlignmentCst()->getType();
2317 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
2319 deleteIfTriviallyDead(OldPtr);
2323 // Record this instruction for deletion.
2324 Pass.DeadInsts.insert(&II);
2326 Type *AllocaTy = NewAI.getAllocatedType();
2327 Type *ScalarTy = AllocaTy->getScalarType();
2329 // Compute the intersecting offset range.
2330 assert(BeginOffset < NewAllocaEndOffset);
2331 assert(EndOffset > NewAllocaBeginOffset);
2332 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2333 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2334 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
2336 // If this doesn't map cleanly onto the alloca type, and that type isn't
2337 // a single value type, just emit a memset.
2338 if (!VecTy && !IntTy &&
2339 (BeginOffset > NewAllocaBeginOffset ||
2340 EndOffset < NewAllocaEndOffset ||
2341 !AllocaTy->isSingleValueType() ||
2342 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2343 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
2344 Type *SizeTy = II.getLength()->getType();
2345 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2346 CallInst *New = IRB.CreateMemSet(
2347 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getRawDest()->getType()),
2348 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
2350 DEBUG(dbgs() << " to: " << *New << "\n");
2354 // If we can represent this as a simple value, we have to build the actual
2355 // value to store, which requires expanding the byte present in memset to
2356 // a sensible representation for the alloca type. This is essentially
2357 // splatting the byte to a sufficiently wide integer, splatting it across
2358 // any desired vector width, and bitcasting to the final type.
2362 // If this is a memset of a vectorized alloca, insert it.
2363 assert(ElementTy == ScalarTy);
2365 unsigned BeginIndex = getIndex(NewBeginOffset);
2366 unsigned EndIndex = getIndex(NewEndOffset);
2367 assert(EndIndex > BeginIndex && "Empty vector!");
2368 unsigned NumElements = EndIndex - BeginIndex;
2369 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2372 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2373 Splat = convertValue(DL, IRB, Splat, ElementTy);
2374 if (NumElements > 1)
2375 Splat = getVectorSplat(Splat, NumElements);
2377 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2379 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2381 // If this is a memset on an alloca where we can widen stores, insert the
2383 assert(!II.isVolatile());
2385 uint64_t Size = NewEndOffset - NewBeginOffset;
2386 V = getIntegerSplat(II.getValue(), Size);
2388 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2389 EndOffset != NewAllocaBeginOffset)) {
2390 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2392 Old = convertValue(DL, IRB, Old, IntTy);
2393 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2394 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2396 assert(V->getType() == IntTy &&
2397 "Wrong type for an alloca wide integer!");
2399 V = convertValue(DL, IRB, V, AllocaTy);
2401 // Established these invariants above.
2402 assert(NewBeginOffset == NewAllocaBeginOffset);
2403 assert(NewEndOffset == NewAllocaEndOffset);
2405 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2406 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2407 V = getVectorSplat(V, AllocaVecTy->getNumElements());
2409 V = convertValue(DL, IRB, V, AllocaTy);
2412 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2415 DEBUG(dbgs() << " to: " << *New << "\n");
2416 return !II.isVolatile();
2419 bool visitMemTransferInst(MemTransferInst &II) {
2420 // Rewriting of memory transfer instructions can be a bit tricky. We break
2421 // them into two categories: split intrinsics and unsplit intrinsics.
2423 DEBUG(dbgs() << " original: " << II << "\n");
2425 // Compute the intersecting offset range.
2426 assert(BeginOffset < NewAllocaEndOffset);
2427 assert(EndOffset > NewAllocaBeginOffset);
2428 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2429 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2431 bool IsDest = &II.getRawDestUse() == OldUse;
2432 assert(IsDest && II.getRawDest() == OldPtr ||
2433 (!IsDest && II.getRawSource() == OldPtr));
2435 // Compute the relative offset within the transfer.
2436 unsigned IntPtrWidth = DL.getPointerSizeInBits();
2437 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2439 unsigned Align = II.getAlignment();
2440 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
2443 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2444 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
2446 // For unsplit intrinsics, we simply modify the source and destination
2447 // pointers in place. This isn't just an optimization, it is a matter of
2448 // correctness. With unsplit intrinsics we may be dealing with transfers
2449 // within a single alloca before SROA ran, or with transfers that have
2450 // a variable length. We may also be dealing with memmove instead of
2451 // memcpy, and so simply updating the pointers is the necessary for us to
2452 // update both source and dest of a single call.
2453 if (!IsSplittable) {
2454 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2457 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
2459 II.setSource(getAdjustedAllocaPtr(IRB, BeginOffset,
2460 II.getRawSource()->getType()));
2462 Type *CstTy = II.getAlignmentCst()->getType();
2463 II.setAlignment(ConstantInt::get(CstTy, Align));
2465 DEBUG(dbgs() << " to: " << II << "\n");
2466 deleteIfTriviallyDead(OldOp);
2469 // For split transfer intrinsics we have an incredibly useful assurance:
2470 // the source and destination do not reside within the same alloca, and at
2471 // least one of them does not escape. This means that we can replace
2472 // memmove with memcpy, and we don't need to worry about all manner of
2473 // downsides to splitting and transforming the operations.
2475 // If this doesn't map cleanly onto the alloca type, and that type isn't
2476 // a single value type, just emit a memcpy.
2478 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2479 EndOffset < NewAllocaEndOffset ||
2480 !NewAI.getAllocatedType()->isSingleValueType());
2482 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2483 // size hasn't been shrunk based on analysis of the viable range, this is
2485 if (EmitMemCpy && &OldAI == &NewAI) {
2486 // Ensure the start lines up.
2487 assert(NewBeginOffset == BeginOffset);
2489 // Rewrite the size as needed.
2490 if (NewEndOffset != EndOffset)
2491 II.setLength(ConstantInt::get(II.getLength()->getType(),
2492 NewEndOffset - NewBeginOffset));
2495 // Record this instruction for deletion.
2496 Pass.DeadInsts.insert(&II);
2498 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2499 // alloca that should be re-examined after rewriting this instruction.
2500 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2502 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2503 assert(AI != &OldAI && AI != &NewAI &&
2504 "Splittable transfers cannot reach the same alloca on both ends.");
2505 Pass.Worklist.insert(AI);
2509 Type *OtherPtrTy = OtherPtr->getType();
2511 // Compute the other pointer, folding as much as possible to produce
2512 // a single, simple GEP in most cases.
2513 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
2515 Value *OurPtr = getAdjustedAllocaPtr(
2516 IRB, NewBeginOffset,
2517 IsDest ? II.getRawDest()->getType() : II.getRawSource()->getType());
2518 Type *SizeTy = II.getLength()->getType();
2519 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2521 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2522 IsDest ? OtherPtr : OurPtr,
2523 Size, Align, II.isVolatile());
2525 DEBUG(dbgs() << " to: " << *New << "\n");
2529 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2530 // is equivalent to 1, but that isn't true if we end up rewriting this as
2535 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2536 NewEndOffset == NewAllocaEndOffset;
2537 uint64_t Size = NewEndOffset - NewBeginOffset;
2538 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2539 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2540 unsigned NumElements = EndIndex - BeginIndex;
2541 IntegerType *SubIntTy
2542 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2544 Type *OtherPtrTy = NewAI.getType();
2545 if (VecTy && !IsWholeAlloca) {
2546 if (NumElements == 1)
2547 OtherPtrTy = VecTy->getElementType();
2549 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2551 OtherPtrTy = OtherPtrTy->getPointerTo();
2552 } else if (IntTy && !IsWholeAlloca) {
2553 OtherPtrTy = SubIntTy->getPointerTo();
2556 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
2557 Value *DstPtr = &NewAI;
2559 std::swap(SrcPtr, DstPtr);
2562 if (VecTy && !IsWholeAlloca && !IsDest) {
2563 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2565 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
2566 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2567 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2569 Src = convertValue(DL, IRB, Src, IntTy);
2570 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2571 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
2573 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2577 if (VecTy && !IsWholeAlloca && IsDest) {
2578 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2580 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
2581 } else if (IntTy && !IsWholeAlloca && IsDest) {
2582 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2584 Old = convertValue(DL, IRB, Old, IntTy);
2585 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2586 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2587 Src = convertValue(DL, IRB, Src, NewAllocaTy);
2590 StoreInst *Store = cast<StoreInst>(
2591 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2593 DEBUG(dbgs() << " to: " << *Store << "\n");
2594 return !II.isVolatile();
2597 bool visitIntrinsicInst(IntrinsicInst &II) {
2598 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2599 II.getIntrinsicID() == Intrinsic::lifetime_end);
2600 DEBUG(dbgs() << " original: " << II << "\n");
2601 assert(II.getArgOperand(1) == OldPtr);
2603 // Compute the intersecting offset range.
2604 assert(BeginOffset < NewAllocaEndOffset);
2605 assert(EndOffset > NewAllocaBeginOffset);
2606 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2607 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2609 // Record this instruction for deletion.
2610 Pass.DeadInsts.insert(&II);
2613 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2614 NewEndOffset - NewBeginOffset);
2616 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getArgOperand(1)->getType());
2618 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2619 New = IRB.CreateLifetimeStart(Ptr, Size);
2621 New = IRB.CreateLifetimeEnd(Ptr, Size);
2624 DEBUG(dbgs() << " to: " << *New << "\n");
2628 bool visitPHINode(PHINode &PN) {
2629 DEBUG(dbgs() << " original: " << PN << "\n");
2630 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2631 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
2633 // We would like to compute a new pointer in only one place, but have it be
2634 // as local as possible to the PHI. To do that, we re-use the location of
2635 // the old pointer, which necessarily must be in the right position to
2636 // dominate the PHI.
2637 IRBuilderTy PtrBuilder(OldPtr);
2638 PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2642 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
2643 // Replace the operands which were using the old pointer.
2644 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
2646 DEBUG(dbgs() << " to: " << PN << "\n");
2647 deleteIfTriviallyDead(OldPtr);
2649 // PHIs can't be promoted on their own, but often can be speculated. We
2650 // check the speculation outside of the rewriter so that we see the
2651 // fully-rewritten alloca.
2652 PHIUsers.insert(&PN);
2656 bool visitSelectInst(SelectInst &SI) {
2657 DEBUG(dbgs() << " original: " << SI << "\n");
2658 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2659 "Pointer isn't an operand!");
2660 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2661 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
2663 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
2664 // Replace the operands which were using the old pointer.
2665 if (SI.getOperand(1) == OldPtr)
2666 SI.setOperand(1, NewPtr);
2667 if (SI.getOperand(2) == OldPtr)
2668 SI.setOperand(2, NewPtr);
2670 DEBUG(dbgs() << " to: " << SI << "\n");
2671 deleteIfTriviallyDead(OldPtr);
2673 // Selects can't be promoted on their own, but often can be speculated. We
2674 // check the speculation outside of the rewriter so that we see the
2675 // fully-rewritten alloca.
2676 SelectUsers.insert(&SI);
2684 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2686 /// This pass aggressively rewrites all aggregate loads and stores on
2687 /// a particular pointer (or any pointer derived from it which we can identify)
2688 /// with scalar loads and stores.
2689 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2690 // Befriend the base class so it can delegate to private visit methods.
2691 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2693 const DataLayout &DL;
2695 /// Queue of pointer uses to analyze and potentially rewrite.
2696 SmallVector<Use *, 8> Queue;
2698 /// Set to prevent us from cycling with phi nodes and loops.
2699 SmallPtrSet<User *, 8> Visited;
2701 /// The current pointer use being rewritten. This is used to dig up the used
2702 /// value (as opposed to the user).
2706 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
2708 /// Rewrite loads and stores through a pointer and all pointers derived from
2710 bool rewrite(Instruction &I) {
2711 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2713 bool Changed = false;
2714 while (!Queue.empty()) {
2715 U = Queue.pop_back_val();
2716 Changed |= visit(cast<Instruction>(U->getUser()));
2722 /// Enqueue all the users of the given instruction for further processing.
2723 /// This uses a set to de-duplicate users.
2724 void enqueueUsers(Instruction &I) {
2725 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2727 if (Visited.insert(*UI))
2728 Queue.push_back(&UI.getUse());
2731 // Conservative default is to not rewrite anything.
2732 bool visitInstruction(Instruction &I) { return false; }
2734 /// \brief Generic recursive split emission class.
2735 template <typename Derived>
2738 /// The builder used to form new instructions.
2740 /// The indices which to be used with insert- or extractvalue to select the
2741 /// appropriate value within the aggregate.
2742 SmallVector<unsigned, 4> Indices;
2743 /// The indices to a GEP instruction which will move Ptr to the correct slot
2744 /// within the aggregate.
2745 SmallVector<Value *, 4> GEPIndices;
2746 /// The base pointer of the original op, used as a base for GEPing the
2747 /// split operations.
2750 /// Initialize the splitter with an insertion point, Ptr and start with a
2751 /// single zero GEP index.
2752 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
2753 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
2756 /// \brief Generic recursive split emission routine.
2758 /// This method recursively splits an aggregate op (load or store) into
2759 /// scalar or vector ops. It splits recursively until it hits a single value
2760 /// and emits that single value operation via the template argument.
2762 /// The logic of this routine relies on GEPs and insertvalue and
2763 /// extractvalue all operating with the same fundamental index list, merely
2764 /// formatted differently (GEPs need actual values).
2766 /// \param Ty The type being split recursively into smaller ops.
2767 /// \param Agg The aggregate value being built up or stored, depending on
2768 /// whether this is splitting a load or a store respectively.
2769 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2770 if (Ty->isSingleValueType())
2771 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
2773 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2774 unsigned OldSize = Indices.size();
2776 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2778 assert(Indices.size() == OldSize && "Did not return to the old size");
2779 Indices.push_back(Idx);
2780 GEPIndices.push_back(IRB.getInt32(Idx));
2781 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2782 GEPIndices.pop_back();
2788 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2789 unsigned OldSize = Indices.size();
2791 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2793 assert(Indices.size() == OldSize && "Did not return to the old size");
2794 Indices.push_back(Idx);
2795 GEPIndices.push_back(IRB.getInt32(Idx));
2796 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2797 GEPIndices.pop_back();
2803 llvm_unreachable("Only arrays and structs are aggregate loadable types");
2807 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
2808 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2809 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
2811 /// Emit a leaf load of a single value. This is called at the leaves of the
2812 /// recursive emission to actually load values.
2813 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2814 assert(Ty->isSingleValueType());
2815 // Load the single value and insert it using the indices.
2816 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2817 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
2818 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2819 DEBUG(dbgs() << " to: " << *Load << "\n");
2823 bool visitLoadInst(LoadInst &LI) {
2824 assert(LI.getPointerOperand() == *U);
2825 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2828 // We have an aggregate being loaded, split it apart.
2829 DEBUG(dbgs() << " original: " << LI << "\n");
2830 LoadOpSplitter Splitter(&LI, *U);
2831 Value *V = UndefValue::get(LI.getType());
2832 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
2833 LI.replaceAllUsesWith(V);
2834 LI.eraseFromParent();
2838 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
2839 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2840 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
2842 /// Emit a leaf store of a single value. This is called at the leaves of the
2843 /// recursive emission to actually produce stores.
2844 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2845 assert(Ty->isSingleValueType());
2846 // Extract the single value and store it using the indices.
2847 Value *Store = IRB.CreateStore(
2848 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2849 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2851 DEBUG(dbgs() << " to: " << *Store << "\n");
2855 bool visitStoreInst(StoreInst &SI) {
2856 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2858 Value *V = SI.getValueOperand();
2859 if (V->getType()->isSingleValueType())
2862 // We have an aggregate being stored, split it apart.
2863 DEBUG(dbgs() << " original: " << SI << "\n");
2864 StoreOpSplitter Splitter(&SI, *U);
2865 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
2866 SI.eraseFromParent();
2870 bool visitBitCastInst(BitCastInst &BC) {
2875 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2880 bool visitPHINode(PHINode &PN) {
2885 bool visitSelectInst(SelectInst &SI) {
2892 /// \brief Strip aggregate type wrapping.
2894 /// This removes no-op aggregate types wrapping an underlying type. It will
2895 /// strip as many layers of types as it can without changing either the type
2896 /// size or the allocated size.
2897 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2898 if (Ty->isSingleValueType())
2901 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2902 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2905 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2906 InnerTy = ArrTy->getElementType();
2907 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2908 const StructLayout *SL = DL.getStructLayout(STy);
2909 unsigned Index = SL->getElementContainingOffset(0);
2910 InnerTy = STy->getElementType(Index);
2915 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2916 TypeSize > DL.getTypeSizeInBits(InnerTy))
2919 return stripAggregateTypeWrapping(DL, InnerTy);
2922 /// \brief Try to find a partition of the aggregate type passed in for a given
2923 /// offset and size.
2925 /// This recurses through the aggregate type and tries to compute a subtype
2926 /// based on the offset and size. When the offset and size span a sub-section
2927 /// of an array, it will even compute a new array type for that sub-section,
2928 /// and the same for structs.
2930 /// Note that this routine is very strict and tries to find a partition of the
2931 /// type which produces the *exact* right offset and size. It is not forgiving
2932 /// when the size or offset cause either end of type-based partition to be off.
2933 /// Also, this is a best-effort routine. It is reasonable to give up and not
2934 /// return a type if necessary.
2935 static Type *getTypePartition(const DataLayout &DL, Type *Ty,
2936 uint64_t Offset, uint64_t Size) {
2937 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2938 return stripAggregateTypeWrapping(DL, Ty);
2939 if (Offset > DL.getTypeAllocSize(Ty) ||
2940 (DL.getTypeAllocSize(Ty) - Offset) < Size)
2943 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2944 // We can't partition pointers...
2945 if (SeqTy->isPointerTy())
2948 Type *ElementTy = SeqTy->getElementType();
2949 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
2950 uint64_t NumSkippedElements = Offset / ElementSize;
2951 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
2952 if (NumSkippedElements >= ArrTy->getNumElements())
2954 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
2955 if (NumSkippedElements >= VecTy->getNumElements())
2958 Offset -= NumSkippedElements * ElementSize;
2960 // First check if we need to recurse.
2961 if (Offset > 0 || Size < ElementSize) {
2962 // Bail if the partition ends in a different array element.
2963 if ((Offset + Size) > ElementSize)
2965 // Recurse through the element type trying to peel off offset bytes.
2966 return getTypePartition(DL, ElementTy, Offset, Size);
2968 assert(Offset == 0);
2970 if (Size == ElementSize)
2971 return stripAggregateTypeWrapping(DL, ElementTy);
2972 assert(Size > ElementSize);
2973 uint64_t NumElements = Size / ElementSize;
2974 if (NumElements * ElementSize != Size)
2976 return ArrayType::get(ElementTy, NumElements);
2979 StructType *STy = dyn_cast<StructType>(Ty);
2983 const StructLayout *SL = DL.getStructLayout(STy);
2984 if (Offset >= SL->getSizeInBytes())
2986 uint64_t EndOffset = Offset + Size;
2987 if (EndOffset > SL->getSizeInBytes())
2990 unsigned Index = SL->getElementContainingOffset(Offset);
2991 Offset -= SL->getElementOffset(Index);
2993 Type *ElementTy = STy->getElementType(Index);
2994 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
2995 if (Offset >= ElementSize)
2996 return 0; // The offset points into alignment padding.
2998 // See if any partition must be contained by the element.
2999 if (Offset > 0 || Size < ElementSize) {
3000 if ((Offset + Size) > ElementSize)
3002 return getTypePartition(DL, ElementTy, Offset, Size);
3004 assert(Offset == 0);
3006 if (Size == ElementSize)
3007 return stripAggregateTypeWrapping(DL, ElementTy);
3009 StructType::element_iterator EI = STy->element_begin() + Index,
3010 EE = STy->element_end();
3011 if (EndOffset < SL->getSizeInBytes()) {
3012 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3013 if (Index == EndIndex)
3014 return 0; // Within a single element and its padding.
3016 // Don't try to form "natural" types if the elements don't line up with the
3018 // FIXME: We could potentially recurse down through the last element in the
3019 // sub-struct to find a natural end point.
3020 if (SL->getElementOffset(EndIndex) != EndOffset)
3023 assert(Index < EndIndex);
3024 EE = STy->element_begin() + EndIndex;
3027 // Try to build up a sub-structure.
3028 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
3030 const StructLayout *SubSL = DL.getStructLayout(SubTy);
3031 if (Size != SubSL->getSizeInBytes())
3032 return 0; // The sub-struct doesn't have quite the size needed.
3037 /// \brief Rewrite an alloca partition's users.
3039 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3040 /// to rewrite uses of an alloca partition to be conducive for SSA value
3041 /// promotion. If the partition needs a new, more refined alloca, this will
3042 /// build that new alloca, preserving as much type information as possible, and
3043 /// rewrite the uses of the old alloca to point at the new one and have the
3044 /// appropriate new offsets. It also evaluates how successful the rewrite was
3045 /// at enabling promotion and if it was successful queues the alloca to be
3047 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3048 AllocaSlices::iterator B, AllocaSlices::iterator E,
3049 int64_t BeginOffset, int64_t EndOffset,
3050 ArrayRef<AllocaSlices::iterator> SplitUses) {
3051 assert(BeginOffset < EndOffset);
3052 uint64_t SliceSize = EndOffset - BeginOffset;
3054 // Try to compute a friendly type for this partition of the alloca. This
3055 // won't always succeed, in which case we fall back to a legal integer type
3056 // or an i8 array of an appropriate size.
3058 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
3059 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3060 SliceTy = CommonUseTy;
3062 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
3063 BeginOffset, SliceSize))
3064 SliceTy = TypePartitionTy;
3065 if ((!SliceTy || (SliceTy->isArrayTy() &&
3066 SliceTy->getArrayElementType()->isIntegerTy())) &&
3067 DL->isLegalInteger(SliceSize * 8))
3068 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3070 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3071 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
3073 bool IsVectorPromotable = isVectorPromotionViable(
3074 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
3076 bool IsIntegerPromotable =
3077 !IsVectorPromotable &&
3078 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
3080 // Check for the case where we're going to rewrite to a new alloca of the
3081 // exact same type as the original, and with the same access offsets. In that
3082 // case, re-use the existing alloca, but still run through the rewriter to
3083 // perform phi and select speculation.
3085 if (SliceTy == AI.getAllocatedType()) {
3086 assert(BeginOffset == 0 &&
3087 "Non-zero begin offset but same alloca type");
3089 // FIXME: We should be able to bail at this point with "nothing changed".
3090 // FIXME: We might want to defer PHI speculation until after here.
3092 unsigned Alignment = AI.getAlignment();
3094 // The minimum alignment which users can rely on when the explicit
3095 // alignment is omitted or zero is that required by the ABI for this
3097 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
3099 Alignment = MinAlign(Alignment, BeginOffset);
3100 // If we will get at least this much alignment from the type alone, leave
3101 // the alloca's alignment unconstrained.
3102 if (Alignment <= DL->getABITypeAlignment(SliceTy))
3104 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3105 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
3109 DEBUG(dbgs() << "Rewriting alloca partition "
3110 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3113 // Track the high watermark on the worklist as it is only relevant for
3114 // promoted allocas. We will reset it to this point if the alloca is not in
3115 // fact scheduled for promotion.
3116 unsigned PPWOldSize = PostPromotionWorklist.size();
3117 unsigned NumUses = 0;
3118 SmallPtrSet<PHINode *, 8> PHIUsers;
3119 SmallPtrSet<SelectInst *, 8> SelectUsers;
3121 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3122 EndOffset, IsVectorPromotable,
3123 IsIntegerPromotable, PHIUsers, SelectUsers);
3124 bool Promotable = true;
3125 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3126 SUE = SplitUses.end();
3127 SUI != SUE; ++SUI) {
3128 DEBUG(dbgs() << " rewriting split ");
3129 DEBUG(S.printSlice(dbgs(), *SUI, ""));
3130 Promotable &= Rewriter.visit(*SUI);
3133 for (AllocaSlices::iterator I = B; I != E; ++I) {
3134 DEBUG(dbgs() << " rewriting ");
3135 DEBUG(S.printSlice(dbgs(), I, ""));
3136 Promotable &= Rewriter.visit(I);
3140 NumAllocaPartitionUses += NumUses;
3141 MaxUsesPerAllocaPartition =
3142 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
3144 // Now that we've processed all the slices in the new partition, check if any
3145 // PHIs or Selects would block promotion.
3146 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3149 if (!isSafePHIToSpeculate(**I, DL)) {
3152 SelectUsers.clear();
3154 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3155 E = SelectUsers.end();
3157 if (!isSafeSelectToSpeculate(**I, DL)) {
3160 SelectUsers.clear();
3164 if (PHIUsers.empty() && SelectUsers.empty()) {
3165 // Promote the alloca.
3166 PromotableAllocas.push_back(NewAI);
3168 // If we have either PHIs or Selects to speculate, add them to those
3169 // worklists and re-queue the new alloca so that we promote in on the
3171 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3174 SpeculatablePHIs.insert(*I);
3175 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3176 E = SelectUsers.end();
3178 SpeculatableSelects.insert(*I);
3179 Worklist.insert(NewAI);
3182 // If we can't promote the alloca, iterate on it to check for new
3183 // refinements exposed by splitting the current alloca. Don't iterate on an
3184 // alloca which didn't actually change and didn't get promoted.
3186 Worklist.insert(NewAI);
3188 // Drop any post-promotion work items if promotion didn't happen.
3189 while (PostPromotionWorklist.size() > PPWOldSize)
3190 PostPromotionWorklist.pop_back();
3197 struct IsSliceEndLessOrEqualTo {
3198 uint64_t UpperBound;
3200 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
3202 bool operator()(const AllocaSlices::iterator &I) {
3203 return I->endOffset() <= UpperBound;
3209 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3210 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
3211 if (Offset >= MaxSplitUseEndOffset) {
3213 MaxSplitUseEndOffset = 0;
3217 size_t SplitUsesOldSize = SplitUses.size();
3218 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
3219 IsSliceEndLessOrEqualTo(Offset)),
3221 if (SplitUsesOldSize == SplitUses.size())
3224 // Recompute the max. While this is linear, so is remove_if.
3225 MaxSplitUseEndOffset = 0;
3226 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
3227 SUI = SplitUses.begin(),
3228 SUE = SplitUses.end();
3230 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3233 /// \brief Walks the slices of an alloca and form partitions based on them,
3234 /// rewriting each of their uses.
3235 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3236 if (S.begin() == S.end())
3239 unsigned NumPartitions = 0;
3240 bool Changed = false;
3241 SmallVector<AllocaSlices::iterator, 4> SplitUses;
3242 uint64_t MaxSplitUseEndOffset = 0;
3244 uint64_t BeginOffset = S.begin()->beginOffset();
3246 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3247 SI != SE; SI = SJ) {
3248 uint64_t MaxEndOffset = SI->endOffset();
3250 if (!SI->isSplittable()) {
3251 // When we're forming an unsplittable region, it must always start at the
3252 // first slice and will extend through its end.
3253 assert(BeginOffset == SI->beginOffset());
3255 // Form a partition including all of the overlapping slices with this
3256 // unsplittable slice.
3257 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3258 if (!SJ->isSplittable())
3259 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3263 assert(SI->isSplittable()); // Established above.
3265 // Collect all of the overlapping splittable slices.
3266 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3267 SJ->isSplittable()) {
3268 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3272 // Back up MaxEndOffset and SJ if we ended the span early when
3273 // encountering an unsplittable slice.
3274 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3275 assert(!SJ->isSplittable());
3276 MaxEndOffset = SJ->beginOffset();
3280 // Check if we have managed to move the end offset forward yet. If so,
3281 // we'll have to rewrite uses and erase old split uses.
3282 if (BeginOffset < MaxEndOffset) {
3283 // Rewrite a sequence of overlapping slices.
3285 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
3288 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3291 // Accumulate all the splittable slices from the [SI,SJ) region which
3292 // overlap going forward.
3293 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3294 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3295 SplitUses.push_back(SK);
3296 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
3299 // If we're already at the end and we have no split uses, we're done.
3300 if (SJ == SE && SplitUses.empty())
3303 // If we have no split uses or no gap in offsets, we're ready to move to
3305 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3306 BeginOffset = SJ->beginOffset();
3310 // Even if we have split slices, if the next slice is splittable and the
3311 // split slices reach it, we can simply set up the beginning offset of the
3312 // next iteration to bridge between them.
3313 if (SJ != SE && SJ->isSplittable() &&
3314 MaxSplitUseEndOffset > SJ->beginOffset()) {
3315 BeginOffset = MaxEndOffset;
3319 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3321 uint64_t PostSplitEndOffset =
3322 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
3324 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3329 break; // Skip the rest, we don't need to do any cleanup.
3331 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3332 PostSplitEndOffset);
3334 // Now just reset the begin offset for the next iteration.
3335 BeginOffset = SJ->beginOffset();
3338 NumAllocaPartitions += NumPartitions;
3339 MaxPartitionsPerAlloca =
3340 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
3345 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3346 void SROA::clobberUse(Use &U) {
3348 // Replace the use with an undef value.
3349 U = UndefValue::get(OldV->getType());
3351 // Check for this making an instruction dead. We have to garbage collect
3352 // all the dead instructions to ensure the uses of any alloca end up being
3354 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3355 if (isInstructionTriviallyDead(OldI)) {
3356 DeadInsts.insert(OldI);
3360 /// \brief Analyze an alloca for SROA.
3362 /// This analyzes the alloca to ensure we can reason about it, builds
3363 /// the slices of the alloca, and then hands it off to be split and
3364 /// rewritten as needed.
3365 bool SROA::runOnAlloca(AllocaInst &AI) {
3366 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3367 ++NumAllocasAnalyzed;
3369 // Special case dead allocas, as they're trivial.
3370 if (AI.use_empty()) {
3371 AI.eraseFromParent();
3375 // Skip alloca forms that this analysis can't handle.
3376 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3377 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
3380 bool Changed = false;
3382 // First, split any FCA loads and stores touching this alloca to promote
3383 // better splitting and promotion opportunities.
3384 AggLoadStoreRewriter AggRewriter(*DL);
3385 Changed |= AggRewriter.rewrite(AI);
3387 // Build the slices using a recursive instruction-visiting builder.
3388 AllocaSlices S(*DL, AI);
3389 DEBUG(S.print(dbgs()));
3393 // Delete all the dead users of this alloca before splitting and rewriting it.
3394 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3395 DE = S.dead_user_end();
3397 // Free up everything used by this instruction.
3398 for (User::op_iterator DOI = (*DI)->op_begin(), DOE = (*DI)->op_end();
3402 // Now replace the uses of this instruction.
3403 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3405 // And mark it for deletion.
3406 DeadInsts.insert(*DI);
3409 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3410 DE = S.dead_op_end();
3416 // No slices to split. Leave the dead alloca for a later pass to clean up.
3417 if (S.begin() == S.end())
3420 Changed |= splitAlloca(AI, S);
3422 DEBUG(dbgs() << " Speculating PHIs\n");
3423 while (!SpeculatablePHIs.empty())
3424 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3426 DEBUG(dbgs() << " Speculating Selects\n");
3427 while (!SpeculatableSelects.empty())
3428 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3433 /// \brief Delete the dead instructions accumulated in this run.
3435 /// Recursively deletes the dead instructions we've accumulated. This is done
3436 /// at the very end to maximize locality of the recursive delete and to
3437 /// minimize the problems of invalidated instruction pointers as such pointers
3438 /// are used heavily in the intermediate stages of the algorithm.
3440 /// We also record the alloca instructions deleted here so that they aren't
3441 /// subsequently handed to mem2reg to promote.
3442 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3443 while (!DeadInsts.empty()) {
3444 Instruction *I = DeadInsts.pop_back_val();
3445 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3447 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3449 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3450 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3451 // Zero out the operand and see if it becomes trivially dead.
3453 if (isInstructionTriviallyDead(U))
3454 DeadInsts.insert(U);
3457 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3458 DeletedAllocas.insert(AI);
3461 I->eraseFromParent();
3465 static void enqueueUsersInWorklist(Instruction &I,
3466 SmallVectorImpl<Instruction *> &Worklist,
3467 SmallPtrSet<Instruction *, 8> &Visited) {
3468 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3470 if (Visited.insert(cast<Instruction>(*UI)))
3471 Worklist.push_back(cast<Instruction>(*UI));
3474 /// \brief Promote the allocas, using the best available technique.
3476 /// This attempts to promote whatever allocas have been identified as viable in
3477 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3478 /// If there is a domtree available, we attempt to promote using the full power
3479 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3480 /// based on the SSAUpdater utilities. This function returns whether any
3481 /// promotion occurred.
3482 bool SROA::promoteAllocas(Function &F) {
3483 if (PromotableAllocas.empty())
3486 NumPromoted += PromotableAllocas.size();
3488 if (DT && !ForceSSAUpdater) {
3489 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3490 PromoteMemToReg(PromotableAllocas, *DT);
3491 PromotableAllocas.clear();
3495 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3497 DIBuilder DIB(*F.getParent());
3498 SmallVector<Instruction *, 64> Insts;
3500 // We need a worklist to walk the uses of each alloca.
3501 SmallVector<Instruction *, 8> Worklist;
3502 SmallPtrSet<Instruction *, 8> Visited;
3503 SmallVector<Instruction *, 32> DeadInsts;
3505 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3506 AllocaInst *AI = PromotableAllocas[Idx];
3511 enqueueUsersInWorklist(*AI, Worklist, Visited);
3513 while (!Worklist.empty()) {
3514 Instruction *I = Worklist.pop_back_val();
3516 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3517 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3518 // leading to them) here. Eventually it should use them to optimize the
3519 // scalar values produced.
3520 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3521 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3522 II->getIntrinsicID() == Intrinsic::lifetime_end);
3523 II->eraseFromParent();
3527 // Push the loads and stores we find onto the list. SROA will already
3528 // have validated that all loads and stores are viable candidates for
3530 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3531 assert(LI->getType() == AI->getAllocatedType());
3532 Insts.push_back(LI);
3535 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3536 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3537 Insts.push_back(SI);
3541 // For everything else, we know that only no-op bitcasts and GEPs will
3542 // make it this far, just recurse through them and recall them for later
3544 DeadInsts.push_back(I);
3545 enqueueUsersInWorklist(*I, Worklist, Visited);
3547 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3548 while (!DeadInsts.empty())
3549 DeadInsts.pop_back_val()->eraseFromParent();
3550 AI->eraseFromParent();
3553 PromotableAllocas.clear();
3558 /// \brief A predicate to test whether an alloca belongs to a set.
3559 class IsAllocaInSet {
3560 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3564 typedef AllocaInst *argument_type;
3566 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3567 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
3571 bool SROA::runOnFunction(Function &F) {
3572 if (skipOptnoneFunction(F))
3575 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3576 C = &F.getContext();
3577 DL = getAnalysisIfAvailable<DataLayout>();
3579 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3582 DominatorTreeWrapperPass *DTWP =
3583 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
3584 DT = DTWP ? &DTWP->getDomTree() : 0;
3586 BasicBlock &EntryBB = F.getEntryBlock();
3587 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3589 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3590 Worklist.insert(AI);
3592 bool Changed = false;
3593 // A set of deleted alloca instruction pointers which should be removed from
3594 // the list of promotable allocas.
3595 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3598 while (!Worklist.empty()) {
3599 Changed |= runOnAlloca(*Worklist.pop_back_val());
3600 deleteDeadInstructions(DeletedAllocas);
3602 // Remove the deleted allocas from various lists so that we don't try to
3603 // continue processing them.
3604 if (!DeletedAllocas.empty()) {
3605 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3606 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3607 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3608 PromotableAllocas.end(),
3609 IsAllocaInSet(DeletedAllocas)),
3610 PromotableAllocas.end());
3611 DeletedAllocas.clear();
3615 Changed |= promoteAllocas(F);
3617 Worklist = PostPromotionWorklist;
3618 PostPromotionWorklist.clear();
3619 } while (!Worklist.empty());
3624 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3625 if (RequiresDomTree)
3626 AU.addRequired<DominatorTreeWrapperPass>();
3627 AU.setPreservesCFG();