1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This transformation implements the well known scalar replacement of
11 /// aggregates transformation. It tries to identify promotable elements of an
12 /// aggregate alloca, and promote them to registers. It will also try to
13 /// convert uses of an element (or set of elements) of an alloca into a vector
14 /// or bitfield-style integer scalar if appropriate.
16 /// It works to do this with minimal slicing of the alloca so that regions
17 /// which are merely transferred in and out of external memory remain unchanged
18 /// and are not decomposed to scalar code.
20 /// Because this also performs alloca promotion, it can be thought of as also
21 /// serving the purpose of SSA formation. The algorithm iterates on the
22 /// function until all opportunities for promotion have been realized.
24 //===----------------------------------------------------------------------===//
26 #define DEBUG_TYPE "sroa"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/Dominators.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/PtrUseVisitor.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/DIBuilder.h"
37 #include "llvm/DebugInfo.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/LLVMContext.h"
46 #include "llvm/IR/Operator.h"
47 #include "llvm/InstVisitor.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/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");
63 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses found");
64 STATISTIC(MaxPartitionUsesPerAlloca, "Maximum number of partition uses");
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 partition of an alloca.
116 /// This structure represents a contiguous partition of the alloca. These are
117 /// formed by examining the uses of the alloca. During formation, they may
118 /// overlap but once an AllocaPartitioning is built, the Partitions within it
119 /// are all disjoint. The partition also contains a chain of uses of that
122 /// \brief The beginning offset of the range.
123 uint64_t BeginOffset;
125 /// \brief The ending offset, not included in the range.
128 /// \brief Storage for both the use of this partition and whether it can be
130 PointerIntPair<Use *, 1, bool> PartitionUseAndIsSplittable;
133 Partition() : BeginOffset(), EndOffset() {}
134 Partition(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
135 : BeginOffset(BeginOffset), EndOffset(EndOffset),
136 PartitionUseAndIsSplittable(U, IsSplittable) {}
138 uint64_t beginOffset() const { return BeginOffset; }
139 uint64_t endOffset() const { return EndOffset; }
141 bool isSplittable() const { return PartitionUseAndIsSplittable.getInt(); }
142 void makeUnsplittable() { PartitionUseAndIsSplittable.setInt(false); }
144 Use *getUse() const { return PartitionUseAndIsSplittable.getPointer(); }
146 bool isDead() const { return getUse() == 0; }
147 void kill() { PartitionUseAndIsSplittable.setPointer(0); }
149 /// \brief Support for ordering ranges.
151 /// This provides an ordering over ranges such that start offsets are
152 /// always increasing, and within equal start offsets, the end offsets are
153 /// decreasing. Thus the spanning range comes first in a cluster with the
154 /// same start position.
155 bool operator<(const Partition &RHS) const {
156 if (beginOffset() < RHS.beginOffset()) return true;
157 if (beginOffset() > RHS.beginOffset()) return false;
158 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
159 if (endOffset() > RHS.endOffset()) return true;
163 /// \brief Support comparison with a single offset to allow binary searches.
164 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Partition &LHS,
165 uint64_t RHSOffset) {
166 return LHS.beginOffset() < RHSOffset;
168 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
169 const Partition &RHS) {
170 return LHSOffset < RHS.beginOffset();
173 bool operator==(const Partition &RHS) const {
174 return isSplittable() == RHS.isSplittable() &&
175 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
177 bool operator!=(const Partition &RHS) const { return !operator==(RHS); }
179 } // end anonymous namespace
182 template <typename T> struct isPodLike;
183 template <> struct isPodLike<Partition> {
184 static const bool value = true;
189 /// \brief Alloca partitioning representation.
191 /// This class represents a partitioning of an alloca into slices, and
192 /// information about the nature of uses of each slice of the alloca. The goal
193 /// is that this information is sufficient to decide if and how to split the
194 /// alloca apart and replace slices with scalars. It is also intended that this
195 /// structure can capture the relevant information needed both to decide about
196 /// and to enact these transformations.
197 class AllocaPartitioning {
199 /// \brief Construct a partitioning of a particular alloca.
201 /// Construction does most of the work for partitioning the alloca. This
202 /// performs the necessary walks of users and builds a partitioning from it.
203 AllocaPartitioning(const DataLayout &TD, AllocaInst &AI);
205 /// \brief Test whether a pointer to the allocation escapes our analysis.
207 /// If this is true, the partitioning is never fully built and should be
209 bool isEscaped() const { return PointerEscapingInstr; }
211 /// \brief Support for iterating over the partitions.
213 typedef SmallVectorImpl<Partition>::iterator iterator;
214 iterator begin() { return Partitions.begin(); }
215 iterator end() { return Partitions.end(); }
217 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
218 const_iterator begin() const { return Partitions.begin(); }
219 const_iterator end() const { return Partitions.end(); }
222 /// \brief Allow iterating the dead users for this alloca.
224 /// These are instructions which will never actually use the alloca as they
225 /// are outside the allocated range. They are safe to replace with undef and
228 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
229 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
230 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
233 /// \brief Allow iterating the dead expressions referring to this alloca.
235 /// These are operands which have cannot actually be used to refer to the
236 /// alloca as they are outside its range and the user doesn't correct for
237 /// that. These mostly consist of PHI node inputs and the like which we just
238 /// need to replace with undef.
240 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
241 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
242 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
245 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
246 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
247 void printPartition(raw_ostream &OS, const_iterator I,
248 StringRef Indent = " ") const;
249 void printUse(raw_ostream &OS, const_iterator I,
250 StringRef Indent = " ") const;
251 void print(raw_ostream &OS) const;
252 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
253 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
257 template <typename DerivedT, typename RetT = void> class BuilderBase;
258 class PartitionBuilder;
259 friend class AllocaPartitioning::PartitionBuilder;
261 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
262 /// \brief Handle to alloca instruction to simplify method interfaces.
266 /// \brief The instruction responsible for this alloca having no partitioning.
268 /// When an instruction (potentially) escapes the pointer to the alloca, we
269 /// store a pointer to that here and abort trying to partition the alloca.
270 /// This will be null if the alloca is partitioned successfully.
271 Instruction *PointerEscapingInstr;
273 /// \brief The partitions of the alloca.
275 /// We store a vector of the partitions over the alloca here. This vector is
276 /// sorted by increasing begin offset, and then by decreasing end offset. See
277 /// the Partition inner class for more details. Initially (during
278 /// construction) there are overlaps, but we form a disjoint sequence of
279 /// partitions while finishing construction and a fully constructed object is
280 /// expected to always have this as a disjoint space.
281 SmallVector<Partition, 8> Partitions;
283 /// \brief Instructions which will become dead if we rewrite the alloca.
285 /// Note that these are not separated by partition. This is because we expect
286 /// a partitioned alloca to be completely rewritten or not rewritten at all.
287 /// If rewritten, all these instructions can simply be removed and replaced
288 /// with undef as they come from outside of the allocated space.
289 SmallVector<Instruction *, 8> DeadUsers;
291 /// \brief Operands which will become dead if we rewrite the alloca.
293 /// These are operands that in their particular use can be replaced with
294 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
295 /// to PHI nodes and the like. They aren't entirely dead (there might be
296 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
297 /// want to swap this particular input for undef to simplify the use lists of
299 SmallVector<Use *, 8> DeadOperands;
303 static Value *foldSelectInst(SelectInst &SI) {
304 // If the condition being selected on is a constant or the same value is
305 // being selected between, fold the select. Yes this does (rarely) happen
307 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
308 return SI.getOperand(1+CI->isZero());
309 if (SI.getOperand(1) == SI.getOperand(2))
310 return SI.getOperand(1);
315 /// \brief Builder for the alloca partitioning.
317 /// This class builds an alloca partitioning by recursively visiting the uses
318 /// of an alloca and splitting the partitions for each load and store at each
320 class AllocaPartitioning::PartitionBuilder
321 : public PtrUseVisitor<PartitionBuilder> {
322 friend class PtrUseVisitor<PartitionBuilder>;
323 friend class InstVisitor<PartitionBuilder>;
324 typedef PtrUseVisitor<PartitionBuilder> Base;
326 const uint64_t AllocSize;
327 AllocaPartitioning &P;
329 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
330 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
332 /// \brief Set to de-duplicate dead instructions found in the use walk.
333 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
336 PartitionBuilder(const DataLayout &DL, AllocaInst &AI, AllocaPartitioning &P)
337 : PtrUseVisitor<PartitionBuilder>(DL),
338 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())),
342 void markAsDead(Instruction &I) {
343 if (VisitedDeadInsts.insert(&I))
344 P.DeadUsers.push_back(&I);
347 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
348 bool IsSplittable = false) {
349 // Completely skip uses which have a zero size or start either before or
350 // past the end of the allocation.
351 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
352 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
353 << " which has zero size or starts outside of the "
354 << AllocSize << " byte alloca:\n"
355 << " alloca: " << P.AI << "\n"
356 << " use: " << I << "\n");
357 return markAsDead(I);
360 uint64_t BeginOffset = Offset.getZExtValue();
361 uint64_t EndOffset = BeginOffset + Size;
363 // Clamp the end offset to the end of the allocation. Note that this is
364 // formulated to handle even the case where "BeginOffset + Size" overflows.
365 // This may appear superficially to be something we could ignore entirely,
366 // but that is not so! There may be widened loads or PHI-node uses where
367 // some instructions are dead but not others. We can't completely ignore
368 // them, and so have to record at least the information here.
369 assert(AllocSize >= BeginOffset); // Established above.
370 if (Size > AllocSize - BeginOffset) {
371 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
372 << " to remain within the " << AllocSize << " byte alloca:\n"
373 << " alloca: " << P.AI << "\n"
374 << " use: " << I << "\n");
375 EndOffset = AllocSize;
378 P.Partitions.push_back(Partition(BeginOffset, EndOffset, U, IsSplittable));
381 void visitBitCastInst(BitCastInst &BC) {
383 return markAsDead(BC);
385 return Base::visitBitCastInst(BC);
388 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
389 if (GEPI.use_empty())
390 return markAsDead(GEPI);
392 return Base::visitGetElementPtrInst(GEPI);
395 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
396 uint64_t Size, bool IsVolatile) {
397 // We allow splitting of loads and stores where the type is an integer type
398 // and cover the entire alloca. This prevents us from splitting over
400 // FIXME: In the great blue eventually, we should eagerly split all integer
401 // loads and stores, and then have a separate step that merges adjacent
402 // alloca partitions into a single partition suitable for integer widening.
403 // Or we should skip the merge step and rely on GVN and other passes to
404 // merge adjacent loads and stores that survive mem2reg.
406 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
408 insertUse(I, Offset, Size, IsSplittable);
411 void visitLoadInst(LoadInst &LI) {
412 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
413 "All simple FCA loads should have been pre-split");
416 return PI.setAborted(&LI);
418 uint64_t Size = DL.getTypeStoreSize(LI.getType());
419 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
422 void visitStoreInst(StoreInst &SI) {
423 Value *ValOp = SI.getValueOperand();
425 return PI.setEscapedAndAborted(&SI);
427 return PI.setAborted(&SI);
429 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
431 // If this memory access can be shown to *statically* extend outside the
432 // bounds of of the allocation, it's behavior is undefined, so simply
433 // ignore it. Note that this is more strict than the generic clamping
434 // behavior of insertUse. We also try to handle cases which might run the
436 // FIXME: We should instead consider the pointer to have escaped if this
437 // function is being instrumented for addressing bugs or race conditions.
438 if (Offset.isNegative() || Size > AllocSize ||
439 Offset.ugt(AllocSize - Size)) {
440 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
441 << " which extends past the end of the " << AllocSize
443 << " alloca: " << P.AI << "\n"
444 << " use: " << SI << "\n");
445 return markAsDead(SI);
448 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
449 "All simple FCA stores should have been pre-split");
450 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
454 void visitMemSetInst(MemSetInst &II) {
455 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
456 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
457 if ((Length && Length->getValue() == 0) ||
458 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
459 // Zero-length mem transfer intrinsics can be ignored entirely.
460 return markAsDead(II);
463 return PI.setAborted(&II);
465 insertUse(II, Offset,
466 Length ? Length->getLimitedValue()
467 : AllocSize - Offset.getLimitedValue(),
471 void visitMemTransferInst(MemTransferInst &II) {
472 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
473 if ((Length && Length->getValue() == 0) ||
474 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
475 // Zero-length mem transfer intrinsics can be ignored entirely.
476 return markAsDead(II);
479 return PI.setAborted(&II);
481 uint64_t RawOffset = Offset.getLimitedValue();
482 uint64_t Size = Length ? Length->getLimitedValue()
483 : AllocSize - RawOffset;
485 // Check for the special case where the same exact value is used for both
487 if (*U == II.getRawDest() && *U == II.getRawSource()) {
488 // For non-volatile transfers this is a no-op.
489 if (!II.isVolatile())
490 return markAsDead(II);
492 return insertUse(II, Offset, Size, /*IsSplittable=*/false);;
495 // If we have seen both source and destination for a mem transfer, then
496 // they both point to the same alloca.
498 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
499 llvm::tie(MTPI, Inserted) =
500 MemTransferPartitionMap.insert(std::make_pair(&II, P.Partitions.size()));
501 unsigned PrevIdx = MTPI->second;
503 Partition &PrevP = P.Partitions[PrevIdx];
505 // Check if the begin offsets match and this is a non-volatile transfer.
506 // In that case, we can completely elide the transfer.
507 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
509 return markAsDead(II);
512 // Otherwise we have an offset transfer within the same alloca. We can't
514 PrevP.makeUnsplittable();
517 // Insert the use now that we've fixed up the splittable nature.
518 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
520 // Check that we ended up with a valid index in the map.
521 assert(P.Partitions[PrevIdx].getUse()->getUser() == &II &&
522 "Map index doesn't point back to a partition with this user.");
525 // Disable SRoA for any intrinsics except for lifetime invariants.
526 // FIXME: What about debug intrinsics? This matches old behavior, but
527 // doesn't make sense.
528 void visitIntrinsicInst(IntrinsicInst &II) {
530 return PI.setAborted(&II);
532 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
533 II.getIntrinsicID() == Intrinsic::lifetime_end) {
534 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
535 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
536 Length->getLimitedValue());
537 insertUse(II, Offset, Size, true);
541 Base::visitIntrinsicInst(II);
544 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
545 // We consider any PHI or select that results in a direct load or store of
546 // the same offset to be a viable use for partitioning purposes. These uses
547 // are considered unsplittable and the size is the maximum loaded or stored
549 SmallPtrSet<Instruction *, 4> Visited;
550 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
551 Visited.insert(Root);
552 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
553 // If there are no loads or stores, the access is dead. We mark that as
554 // a size zero access.
557 Instruction *I, *UsedI;
558 llvm::tie(UsedI, I) = Uses.pop_back_val();
560 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
561 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
564 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
565 Value *Op = SI->getOperand(0);
568 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
572 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
573 if (!GEP->hasAllZeroIndices())
575 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
576 !isa<SelectInst>(I)) {
580 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
582 if (Visited.insert(cast<Instruction>(*UI)))
583 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
584 } while (!Uses.empty());
589 void visitPHINode(PHINode &PN) {
591 return markAsDead(PN);
593 return PI.setAborted(&PN);
595 // See if we already have computed info on this node.
596 uint64_t &PHISize = PHIOrSelectSizes[&PN];
598 // This is a new PHI node, check for an unsafe use of the PHI node.
599 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
600 return PI.setAborted(UnsafeI);
603 // For PHI and select operands outside the alloca, we can't nuke the entire
604 // phi or select -- the other side might still be relevant, so we special
605 // case them here and use a separate structure to track the operands
606 // themselves which should be replaced with undef.
607 // FIXME: This should instead be escaped in the event we're instrumenting
608 // for address sanitization.
609 if ((Offset.isNegative() && (-Offset).uge(PHISize)) ||
610 (!Offset.isNegative() && Offset.uge(AllocSize))) {
611 P.DeadOperands.push_back(U);
615 insertUse(PN, Offset, PHISize);
618 void visitSelectInst(SelectInst &SI) {
620 return markAsDead(SI);
621 if (Value *Result = foldSelectInst(SI)) {
623 // If the result of the constant fold will be the pointer, recurse
624 // through the select as if we had RAUW'ed it.
627 // Otherwise the operand to the select is dead, and we can replace it
629 P.DeadOperands.push_back(U);
634 return PI.setAborted(&SI);
636 // See if we already have computed info on this node.
637 uint64_t &SelectSize = PHIOrSelectSizes[&SI];
639 // This is a new Select, check for an unsafe use of it.
640 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
641 return PI.setAborted(UnsafeI);
644 // For PHI and select operands outside the alloca, we can't nuke the entire
645 // phi or select -- the other side might still be relevant, so we special
646 // case them here and use a separate structure to track the operands
647 // themselves which should be replaced with undef.
648 // FIXME: This should instead be escaped in the event we're instrumenting
649 // for address sanitization.
650 if ((Offset.isNegative() && Offset.uge(SelectSize)) ||
651 (!Offset.isNegative() && Offset.uge(AllocSize))) {
652 P.DeadOperands.push_back(U);
656 insertUse(SI, Offset, SelectSize);
659 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
660 void visitInstruction(Instruction &I) {
666 struct IsPartitionDead {
667 bool operator()(const Partition &P) { return P.isDead(); }
671 AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
673 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
676 PointerEscapingInstr(0) {
677 PartitionBuilder PB(TD, AI, *this);
678 PartitionBuilder::PtrInfo PtrI = PB.visitPtr(AI);
679 if (PtrI.isEscaped() || PtrI.isAborted()) {
680 // FIXME: We should sink the escape vs. abort info into the caller nicely,
681 // possibly by just storing the PtrInfo in the AllocaPartitioning.
682 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
683 : PtrI.getAbortingInst();
684 assert(PointerEscapingInstr && "Did not track a bad instruction");
688 // Sort the uses. This arranges for the offsets to be in ascending order,
689 // and the sizes to be in descending order.
690 std::sort(Partitions.begin(), Partitions.end());
693 std::remove_if(Partitions.begin(), Partitions.end(), IsPartitionDead()),
696 // Record how many partitions we end up with.
697 NumAllocaPartitions += Partitions.size();
698 MaxPartitionsPerAlloca = std::max<unsigned>(Partitions.size(), MaxPartitionsPerAlloca);
700 NumAllocaPartitionUses += Partitions.size();
701 MaxPartitionUsesPerAlloca =
702 std::max<unsigned>(Partitions.size(), MaxPartitionUsesPerAlloca);
705 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
707 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
708 StringRef Indent) const {
709 printPartition(OS, I, Indent);
710 printUse(OS, I, Indent);
713 void AllocaPartitioning::printPartition(raw_ostream &OS, const_iterator I,
714 StringRef Indent) const {
715 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
716 << " partition #" << (I - begin())
717 << (I->isSplittable() ? " (splittable)" : "") << "\n";
720 void AllocaPartitioning::printUse(raw_ostream &OS, const_iterator I,
721 StringRef Indent) const {
722 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
725 void AllocaPartitioning::print(raw_ostream &OS) const {
726 if (PointerEscapingInstr) {
727 OS << "No partitioning for alloca: " << AI << "\n"
728 << " A pointer to this alloca escaped by:\n"
729 << " " << *PointerEscapingInstr << "\n";
733 OS << "Partitioning of alloca: " << AI << "\n";
734 for (const_iterator I = begin(), E = end(); I != E; ++I)
738 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
739 void AllocaPartitioning::dump() const { print(dbgs()); }
741 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
744 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
746 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
747 /// the loads and stores of an alloca instruction, as well as updating its
748 /// debug information. This is used when a domtree is unavailable and thus
749 /// mem2reg in its full form can't be used to handle promotion of allocas to
751 class AllocaPromoter : public LoadAndStorePromoter {
755 SmallVector<DbgDeclareInst *, 4> DDIs;
756 SmallVector<DbgValueInst *, 4> DVIs;
759 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
760 AllocaInst &AI, DIBuilder &DIB)
761 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
763 void run(const SmallVectorImpl<Instruction*> &Insts) {
764 // Remember which alloca we're promoting (for isInstInList).
765 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
766 for (Value::use_iterator UI = DebugNode->use_begin(),
767 UE = DebugNode->use_end();
769 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
771 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
775 LoadAndStorePromoter::run(Insts);
776 AI.eraseFromParent();
777 while (!DDIs.empty())
778 DDIs.pop_back_val()->eraseFromParent();
779 while (!DVIs.empty())
780 DVIs.pop_back_val()->eraseFromParent();
783 virtual bool isInstInList(Instruction *I,
784 const SmallVectorImpl<Instruction*> &Insts) const {
785 if (LoadInst *LI = dyn_cast<LoadInst>(I))
786 return LI->getOperand(0) == &AI;
787 return cast<StoreInst>(I)->getPointerOperand() == &AI;
790 virtual void updateDebugInfo(Instruction *Inst) const {
791 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
792 E = DDIs.end(); I != E; ++I) {
793 DbgDeclareInst *DDI = *I;
794 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
795 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
796 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
797 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
799 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
800 E = DVIs.end(); I != E; ++I) {
801 DbgValueInst *DVI = *I;
803 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
804 // If an argument is zero extended then use argument directly. The ZExt
805 // may be zapped by an optimization pass in future.
806 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
807 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
808 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
809 Arg = dyn_cast<Argument>(SExt->getOperand(0));
811 Arg = SI->getValueOperand();
812 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
813 Arg = LI->getPointerOperand();
817 Instruction *DbgVal =
818 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
820 DbgVal->setDebugLoc(DVI->getDebugLoc());
824 } // end anon namespace
828 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
830 /// This pass takes allocations which can be completely analyzed (that is, they
831 /// don't escape) and tries to turn them into scalar SSA values. There are
832 /// a few steps to this process.
834 /// 1) It takes allocations of aggregates and analyzes the ways in which they
835 /// are used to try to split them into smaller allocations, ideally of
836 /// a single scalar data type. It will split up memcpy and memset accesses
837 /// as necessary and try to isolate individual scalar accesses.
838 /// 2) It will transform accesses into forms which are suitable for SSA value
839 /// promotion. This can be replacing a memset with a scalar store of an
840 /// integer value, or it can involve speculating operations on a PHI or
841 /// select to be a PHI or select of the results.
842 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
843 /// onto insert and extract operations on a vector value, and convert them to
844 /// this form. By doing so, it will enable promotion of vector aggregates to
845 /// SSA vector values.
846 class SROA : public FunctionPass {
847 const bool RequiresDomTree;
850 const DataLayout *TD;
853 /// \brief Worklist of alloca instructions to simplify.
855 /// Each alloca in the function is added to this. Each new alloca formed gets
856 /// added to it as well to recursively simplify unless that alloca can be
857 /// directly promoted. Finally, each time we rewrite a use of an alloca other
858 /// the one being actively rewritten, we add it back onto the list if not
859 /// already present to ensure it is re-visited.
860 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
862 /// \brief A collection of instructions to delete.
863 /// We try to batch deletions to simplify code and make things a bit more
865 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
867 /// \brief Post-promotion worklist.
869 /// Sometimes we discover an alloca which has a high probability of becoming
870 /// viable for SROA after a round of promotion takes place. In those cases,
871 /// the alloca is enqueued here for re-processing.
873 /// Note that we have to be very careful to clear allocas out of this list in
874 /// the event they are deleted.
875 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
877 /// \brief A collection of alloca instructions we can directly promote.
878 std::vector<AllocaInst *> PromotableAllocas;
880 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
882 /// All of these PHIs have been checked for the safety of speculation and by
883 /// being speculated will allow promoting allocas currently in the promotable
885 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
887 /// \brief A worklist of select instructions to speculate prior to promoting
890 /// All of these select instructions have been checked for the safety of
891 /// speculation and by being speculated will allow promoting allocas
892 /// currently in the promotable queue.
893 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
896 SROA(bool RequiresDomTree = true)
897 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
899 initializeSROAPass(*PassRegistry::getPassRegistry());
901 bool runOnFunction(Function &F);
902 void getAnalysisUsage(AnalysisUsage &AU) const;
904 const char *getPassName() const { return "SROA"; }
908 friend class PHIOrSelectSpeculator;
909 friend class AllocaPartitionRewriter;
910 friend class AllocaPartitionVectorRewriter;
912 bool rewritePartitions(AllocaInst &AI, AllocaPartitioning &P,
913 AllocaPartitioning::iterator B,
914 AllocaPartitioning::iterator E,
915 int64_t BeginOffset, int64_t EndOffset,
916 ArrayRef<AllocaPartitioning::iterator> SplitUses);
917 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
918 bool runOnAlloca(AllocaInst &AI);
919 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
920 bool promoteAllocas(Function &F);
926 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
927 return new SROA(RequiresDomTree);
930 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
932 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
933 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
936 /// Walk a range of a partitioning looking for a common type to cover this
937 /// sequence of partition uses.
938 static Type *findCommonType(AllocaPartitioning::const_iterator B,
939 AllocaPartitioning::const_iterator E,
940 uint64_t EndOffset) {
942 for (AllocaPartitioning::const_iterator I = B; I != E; ++I) {
943 Use *U = I->getUse();
944 if (isa<IntrinsicInst>(*U->getUser()))
946 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
950 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
951 UserTy = LI->getType();
952 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
953 UserTy = SI->getValueOperand()->getType();
955 return 0; // Bail if we have weird uses.
957 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
958 // If the type is larger than the partition, skip it. We only encounter
959 // this for split integer operations where we want to use the type of
961 // entity causing the split.
962 if (ITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
965 // If we have found an integer type use covering the alloca, use that
966 // regardless of the other types, as integers are often used for a
972 if (Ty && Ty != UserTy)
980 /// PHI instructions that use an alloca and are subsequently loaded can be
981 /// rewritten to load both input pointers in the pred blocks and then PHI the
982 /// results, allowing the load of the alloca to be promoted.
984 /// %P2 = phi [i32* %Alloca, i32* %Other]
985 /// %V = load i32* %P2
987 /// %V1 = load i32* %Alloca -> will be mem2reg'd
989 /// %V2 = load i32* %Other
991 /// %V = phi [i32 %V1, i32 %V2]
993 /// We can do this to a select if its only uses are loads and if the operands
994 /// to the select can be loaded unconditionally.
996 /// FIXME: This should be hoisted into a generic utility, likely in
997 /// Transforms/Util/Local.h
998 static bool isSafePHIToSpeculate(PHINode &PN,
999 const DataLayout *TD = 0) {
1000 // For now, we can only do this promotion if the load is in the same block
1001 // as the PHI, and if there are no stores between the phi and load.
1002 // TODO: Allow recursive phi users.
1003 // TODO: Allow stores.
1004 BasicBlock *BB = PN.getParent();
1005 unsigned MaxAlign = 0;
1006 bool HaveLoad = false;
1007 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
1009 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1010 if (LI == 0 || !LI->isSimple())
1013 // For now we only allow loads in the same block as the PHI. This is
1014 // a common case that happens when instcombine merges two loads through
1016 if (LI->getParent() != BB)
1019 // Ensure that there are no instructions between the PHI and the load that
1021 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1022 if (BBI->mayWriteToMemory())
1025 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1032 // We can only transform this if it is safe to push the loads into the
1033 // predecessor blocks. The only thing to watch out for is that we can't put
1034 // a possibly trapping load in the predecessor if it is a critical edge.
1035 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1036 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1037 Value *InVal = PN.getIncomingValue(Idx);
1039 // If the value is produced by the terminator of the predecessor (an
1040 // invoke) or it has side-effects, there is no valid place to put a load
1041 // in the predecessor.
1042 if (TI == InVal || TI->mayHaveSideEffects())
1045 // If the predecessor has a single successor, then the edge isn't
1047 if (TI->getNumSuccessors() == 1)
1050 // If this pointer is always safe to load, or if we can prove that there
1051 // is already a load in the block, then we can move the load to the pred
1053 if (InVal->isDereferenceablePointer() ||
1054 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, TD))
1063 static void speculatePHINodeLoads(PHINode &PN) {
1064 DEBUG(dbgs() << " original: " << PN << "\n");
1066 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1067 IRBuilderTy PHIBuilder(&PN);
1068 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1069 PN.getName() + ".sroa.speculated");
1071 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1072 // matter which one we get and if any differ.
1073 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1074 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1075 unsigned Align = SomeLoad->getAlignment();
1077 // Rewrite all loads of the PN to use the new PHI.
1078 while (!PN.use_empty()) {
1079 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1080 LI->replaceAllUsesWith(NewPN);
1081 LI->eraseFromParent();
1084 // Inject loads into all of the pred blocks.
1085 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1086 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1087 TerminatorInst *TI = Pred->getTerminator();
1088 Value *InVal = PN.getIncomingValue(Idx);
1089 IRBuilderTy PredBuilder(TI);
1091 LoadInst *Load = PredBuilder.CreateLoad(
1092 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1093 ++NumLoadsSpeculated;
1094 Load->setAlignment(Align);
1096 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1097 NewPN->addIncoming(Load, Pred);
1100 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1101 PN.eraseFromParent();
1104 /// Select instructions that use an alloca and are subsequently loaded can be
1105 /// rewritten to load both input pointers and then select between the result,
1106 /// allowing the load of the alloca to be promoted.
1108 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1109 /// %V = load i32* %P2
1111 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1112 /// %V2 = load i32* %Other
1113 /// %V = select i1 %cond, i32 %V1, i32 %V2
1115 /// We can do this to a select if its only uses are loads and if the operand
1116 /// to the select can be loaded unconditionally.
1117 static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *TD = 0) {
1118 Value *TValue = SI.getTrueValue();
1119 Value *FValue = SI.getFalseValue();
1120 bool TDerefable = TValue->isDereferenceablePointer();
1121 bool FDerefable = FValue->isDereferenceablePointer();
1123 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1125 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1126 if (LI == 0 || !LI->isSimple())
1129 // Both operands to the select need to be dereferencable, either
1130 // absolutely (e.g. allocas) or at this point because we can see other
1133 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), TD))
1136 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), TD))
1143 static void speculateSelectInstLoads(SelectInst &SI) {
1144 DEBUG(dbgs() << " original: " << SI << "\n");
1146 IRBuilderTy IRB(&SI);
1147 Value *TV = SI.getTrueValue();
1148 Value *FV = SI.getFalseValue();
1149 // Replace the loads of the select with a select of two loads.
1150 while (!SI.use_empty()) {
1151 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1152 assert(LI->isSimple() && "We only speculate simple loads");
1154 IRB.SetInsertPoint(LI);
1156 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1158 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1159 NumLoadsSpeculated += 2;
1161 // Transfer alignment and TBAA info if present.
1162 TL->setAlignment(LI->getAlignment());
1163 FL->setAlignment(LI->getAlignment());
1164 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1165 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1166 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1169 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1170 LI->getName() + ".sroa.speculated");
1172 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1173 LI->replaceAllUsesWith(V);
1174 LI->eraseFromParent();
1176 SI.eraseFromParent();
1179 /// \brief Build a GEP out of a base pointer and indices.
1181 /// This will return the BasePtr if that is valid, or build a new GEP
1182 /// instruction using the IRBuilder if GEP-ing is needed.
1183 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1184 SmallVectorImpl<Value *> &Indices) {
1185 if (Indices.empty())
1188 // A single zero index is a no-op, so check for this and avoid building a GEP
1190 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1193 return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
1196 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1197 /// TargetTy without changing the offset of the pointer.
1199 /// This routine assumes we've already established a properly offset GEP with
1200 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1201 /// zero-indices down through type layers until we find one the same as
1202 /// TargetTy. If we can't find one with the same type, we at least try to use
1203 /// one with the same size. If none of that works, we just produce the GEP as
1204 /// indicated by Indices to have the correct offset.
1205 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &TD,
1206 Value *BasePtr, Type *Ty, Type *TargetTy,
1207 SmallVectorImpl<Value *> &Indices) {
1209 return buildGEP(IRB, BasePtr, Indices);
1211 // See if we can descend into a struct and locate a field with the correct
1213 unsigned NumLayers = 0;
1214 Type *ElementTy = Ty;
1216 if (ElementTy->isPointerTy())
1218 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1219 ElementTy = SeqTy->getElementType();
1220 // Note that we use the default address space as this index is over an
1221 // array or a vector, not a pointer.
1222 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
1223 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1224 if (STy->element_begin() == STy->element_end())
1225 break; // Nothing left to descend into.
1226 ElementTy = *STy->element_begin();
1227 Indices.push_back(IRB.getInt32(0));
1232 } while (ElementTy != TargetTy);
1233 if (ElementTy != TargetTy)
1234 Indices.erase(Indices.end() - NumLayers, Indices.end());
1236 return buildGEP(IRB, BasePtr, Indices);
1239 /// \brief Recursively compute indices for a natural GEP.
1241 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1242 /// element types adding appropriate indices for the GEP.
1243 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &TD,
1244 Value *Ptr, Type *Ty, APInt &Offset,
1246 SmallVectorImpl<Value *> &Indices) {
1248 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices);
1250 // We can't recurse through pointer types.
1251 if (Ty->isPointerTy())
1254 // We try to analyze GEPs over vectors here, but note that these GEPs are
1255 // extremely poorly defined currently. The long-term goal is to remove GEPing
1256 // over a vector from the IR completely.
1257 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1258 unsigned ElementSizeInBits = TD.getTypeSizeInBits(VecTy->getScalarType());
1259 if (ElementSizeInBits % 8)
1260 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1261 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1262 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1263 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1265 Offset -= NumSkippedElements * ElementSize;
1266 Indices.push_back(IRB.getInt(NumSkippedElements));
1267 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1268 Offset, TargetTy, Indices);
1271 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1272 Type *ElementTy = ArrTy->getElementType();
1273 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1274 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1275 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1278 Offset -= NumSkippedElements * ElementSize;
1279 Indices.push_back(IRB.getInt(NumSkippedElements));
1280 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1284 StructType *STy = dyn_cast<StructType>(Ty);
1288 const StructLayout *SL = TD.getStructLayout(STy);
1289 uint64_t StructOffset = Offset.getZExtValue();
1290 if (StructOffset >= SL->getSizeInBytes())
1292 unsigned Index = SL->getElementContainingOffset(StructOffset);
1293 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1294 Type *ElementTy = STy->getElementType(Index);
1295 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1296 return 0; // The offset points into alignment padding.
1298 Indices.push_back(IRB.getInt32(Index));
1299 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1303 /// \brief Get a natural GEP from a base pointer to a particular offset and
1304 /// resulting in a particular type.
1306 /// The goal is to produce a "natural" looking GEP that works with the existing
1307 /// composite types to arrive at the appropriate offset and element type for
1308 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1309 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1310 /// Indices, and setting Ty to the result subtype.
1312 /// If no natural GEP can be constructed, this function returns null.
1313 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &TD,
1314 Value *Ptr, APInt Offset, Type *TargetTy,
1315 SmallVectorImpl<Value *> &Indices) {
1316 PointerType *Ty = cast<PointerType>(Ptr->getType());
1318 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1320 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1323 Type *ElementTy = Ty->getElementType();
1324 if (!ElementTy->isSized())
1325 return 0; // We can't GEP through an unsized element.
1326 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1327 if (ElementSize == 0)
1328 return 0; // Zero-length arrays can't help us build a natural GEP.
1329 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1331 Offset -= NumSkippedElements * ElementSize;
1332 Indices.push_back(IRB.getInt(NumSkippedElements));
1333 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1337 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1338 /// resulting pointer has PointerTy.
1340 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1341 /// and produces the pointer type desired. Where it cannot, it will try to use
1342 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1343 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1344 /// bitcast to the type.
1346 /// The strategy for finding the more natural GEPs is to peel off layers of the
1347 /// pointer, walking back through bit casts and GEPs, searching for a base
1348 /// pointer from which we can compute a natural GEP with the desired
1349 /// properties. The algorithm tries to fold as many constant indices into
1350 /// a single GEP as possible, thus making each GEP more independent of the
1351 /// surrounding code.
1352 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &TD,
1353 Value *Ptr, APInt Offset, Type *PointerTy) {
1354 // Even though we don't look through PHI nodes, we could be called on an
1355 // instruction in an unreachable block, which may be on a cycle.
1356 SmallPtrSet<Value *, 4> Visited;
1357 Visited.insert(Ptr);
1358 SmallVector<Value *, 4> Indices;
1360 // We may end up computing an offset pointer that has the wrong type. If we
1361 // never are able to compute one directly that has the correct type, we'll
1362 // fall back to it, so keep it around here.
1363 Value *OffsetPtr = 0;
1365 // Remember any i8 pointer we come across to re-use if we need to do a raw
1368 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1370 Type *TargetTy = PointerTy->getPointerElementType();
1373 // First fold any existing GEPs into the offset.
1374 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1375 APInt GEPOffset(Offset.getBitWidth(), 0);
1376 if (!GEP->accumulateConstantOffset(TD, GEPOffset))
1378 Offset += GEPOffset;
1379 Ptr = GEP->getPointerOperand();
1380 if (!Visited.insert(Ptr))
1384 // See if we can perform a natural GEP here.
1386 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1388 if (P->getType() == PointerTy) {
1389 // Zap any offset pointer that we ended up computing in previous rounds.
1390 if (OffsetPtr && OffsetPtr->use_empty())
1391 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1392 I->eraseFromParent();
1400 // Stash this pointer if we've found an i8*.
1401 if (Ptr->getType()->isIntegerTy(8)) {
1403 Int8PtrOffset = Offset;
1406 // Peel off a layer of the pointer and update the offset appropriately.
1407 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1408 Ptr = cast<Operator>(Ptr)->getOperand(0);
1409 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1410 if (GA->mayBeOverridden())
1412 Ptr = GA->getAliasee();
1416 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1417 } while (Visited.insert(Ptr));
1421 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1423 Int8PtrOffset = Offset;
1426 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1427 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1432 // On the off chance we were targeting i8*, guard the bitcast here.
1433 if (Ptr->getType() != PointerTy)
1434 Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
1439 /// \brief Test whether we can convert a value from the old to the new type.
1441 /// This predicate should be used to guard calls to convertValue in order to
1442 /// ensure that we only try to convert viable values. The strategy is that we
1443 /// will peel off single element struct and array wrappings to get to an
1444 /// underlying value, and convert that value.
1445 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1448 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1449 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1450 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1452 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1454 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1457 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1458 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1460 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1468 /// \brief Generic routine to convert an SSA value to a value of a different
1471 /// This will try various different casting techniques, such as bitcasts,
1472 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1473 /// two types for viability with this routine.
1474 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1476 assert(canConvertValue(DL, V->getType(), Ty) &&
1477 "Value not convertable to type");
1478 if (V->getType() == Ty)
1480 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
1481 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
1482 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1483 return IRB.CreateZExt(V, NewITy);
1484 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1485 return IRB.CreateIntToPtr(V, Ty);
1486 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1487 return IRB.CreatePtrToInt(V, Ty);
1489 return IRB.CreateBitCast(V, Ty);
1492 /// \brief Test whether the given partition use can be promoted to a vector.
1494 /// This function is called to test each entry in a partioning which is slated
1495 /// for a single partition.
1496 static bool isVectorPromotionViableForPartitioning(
1497 const DataLayout &TD, AllocaPartitioning &P,
1498 uint64_t PartitionBeginOffset, uint64_t PartitionEndOffset, VectorType *Ty,
1499 uint64_t ElementSize, AllocaPartitioning::const_iterator I) {
1500 // First validate the partitioning offsets.
1501 uint64_t BeginOffset =
1502 std::max(I->beginOffset(), PartitionBeginOffset) - PartitionBeginOffset;
1503 uint64_t BeginIndex = BeginOffset / ElementSize;
1504 if (BeginIndex * ElementSize != BeginOffset ||
1505 BeginIndex >= Ty->getNumElements())
1507 uint64_t EndOffset =
1508 std::min(I->endOffset(), PartitionEndOffset) - PartitionBeginOffset;
1509 uint64_t EndIndex = EndOffset / ElementSize;
1510 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1513 assert(EndIndex > BeginIndex && "Empty vector!");
1514 uint64_t NumElements = EndIndex - BeginIndex;
1516 (NumElements == 1) ? Ty->getElementType()
1517 : VectorType::get(Ty->getElementType(), NumElements);
1520 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1522 Use *U = I->getUse();
1524 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1525 if (MI->isVolatile())
1527 if (!I->isSplittable())
1528 return false; // Skip any unsplittable intrinsics.
1529 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1530 // Disable vector promotion when there are loads or stores of an FCA.
1532 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1533 if (LI->isVolatile())
1535 Type *LTy = LI->getType();
1536 if (PartitionBeginOffset > I->beginOffset() ||
1537 PartitionEndOffset < I->endOffset()) {
1538 assert(LTy->isIntegerTy());
1541 if (!canConvertValue(TD, PartitionTy, LTy))
1543 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1544 if (SI->isVolatile())
1546 Type *STy = SI->getValueOperand()->getType();
1547 if (PartitionBeginOffset > I->beginOffset() ||
1548 PartitionEndOffset < I->endOffset()) {
1549 assert(STy->isIntegerTy());
1552 if (!canConvertValue(TD, STy, PartitionTy))
1559 /// \brief Test whether the given alloca partition can be promoted to a vector.
1561 /// This is a quick test to check whether we can rewrite a particular alloca
1562 /// partition (and its newly formed alloca) into a vector alloca with only
1563 /// whole-vector loads and stores such that it could be promoted to a vector
1564 /// SSA value. We only can ensure this for a limited set of operations, and we
1565 /// don't want to do the rewrites unless we are confident that the result will
1566 /// be promotable, so we have an early test here.
1567 static bool isVectorPromotionViable(
1568 const DataLayout &TD, Type *AllocaTy, AllocaPartitioning &P,
1569 uint64_t PartitionBeginOffset, uint64_t PartitionEndOffset,
1570 AllocaPartitioning::const_iterator I, AllocaPartitioning::const_iterator E,
1571 ArrayRef<AllocaPartitioning::iterator> SplitUses) {
1572 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1576 uint64_t ElementSize = TD.getTypeSizeInBits(Ty->getScalarType());
1578 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1579 // that aren't byte sized.
1580 if (ElementSize % 8)
1582 assert((TD.getTypeSizeInBits(Ty) % 8) == 0 &&
1583 "vector size not a multiple of element size?");
1587 if (!isVectorPromotionViableForPartitioning(
1588 TD, P, PartitionBeginOffset, PartitionEndOffset, Ty, ElementSize,
1592 for (ArrayRef<AllocaPartitioning::iterator>::const_iterator
1593 SUI = SplitUses.begin(),
1594 SUE = SplitUses.end();
1596 if (!isVectorPromotionViableForPartitioning(
1597 TD, P, PartitionBeginOffset, PartitionEndOffset, Ty, ElementSize,
1604 /// \brief Test whether a partitioning slice of an alloca is a valid set of
1605 /// operations for integer widening.
1607 /// This implements the necessary checking for the \c isIntegerWideningViable
1608 /// test below on a single partitioning slice of the alloca.
1609 static bool isIntegerWideningViableForPartitioning(
1610 const DataLayout &TD, Type *AllocaTy, uint64_t AllocBeginOffset,
1611 uint64_t Size, AllocaPartitioning &P, AllocaPartitioning::const_iterator I,
1612 bool &WholeAllocaOp) {
1613 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1614 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1616 // We can't reasonably handle cases where the load or store extends past
1617 // the end of the aloca's type and into its padding.
1621 Use *U = I->getUse();
1623 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1624 if (LI->isVolatile())
1626 if (RelBegin == 0 && RelEnd == Size)
1627 WholeAllocaOp = true;
1628 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1629 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
1631 } else if (RelBegin != 0 || RelEnd != Size ||
1632 !canConvertValue(TD, AllocaTy, LI->getType())) {
1633 // Non-integer loads need to be convertible from the alloca type so that
1634 // they are promotable.
1637 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1638 Type *ValueTy = SI->getValueOperand()->getType();
1639 if (SI->isVolatile())
1641 if (RelBegin == 0 && RelEnd == Size)
1642 WholeAllocaOp = true;
1643 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
1644 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
1646 } else if (RelBegin != 0 || RelEnd != Size ||
1647 !canConvertValue(TD, ValueTy, AllocaTy)) {
1648 // Non-integer stores need to be convertible to the alloca type so that
1649 // they are promotable.
1652 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1653 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1655 if (!I->isSplittable())
1656 return false; // Skip any unsplittable intrinsics.
1657 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1658 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1659 II->getIntrinsicID() != Intrinsic::lifetime_end)
1668 /// \brief Test whether the given alloca partition's integer operations can be
1669 /// widened to promotable ones.
1671 /// This is a quick test to check whether we can rewrite the integer loads and
1672 /// stores to a particular alloca into wider loads and stores and be able to
1673 /// promote the resulting alloca.
1675 isIntegerWideningViable(const DataLayout &TD, Type *AllocaTy,
1676 uint64_t AllocBeginOffset, AllocaPartitioning &P,
1677 AllocaPartitioning::const_iterator I,
1678 AllocaPartitioning::const_iterator E,
1679 ArrayRef<AllocaPartitioning::iterator> SplitUses) {
1680 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
1681 // Don't create integer types larger than the maximum bitwidth.
1682 if (SizeInBits > IntegerType::MAX_INT_BITS)
1685 // Don't try to handle allocas with bit-padding.
1686 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
1689 // We need to ensure that an integer type with the appropriate bitwidth can
1690 // be converted to the alloca type, whatever that is. We don't want to force
1691 // the alloca itself to have an integer type if there is a more suitable one.
1692 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
1693 if (!canConvertValue(TD, AllocaTy, IntTy) ||
1694 !canConvertValue(TD, IntTy, AllocaTy))
1697 // If we have no actual uses of this partition, we're forming a fully
1698 // splittable partition. Assume all the operations are easy to widen (they
1699 // are if they're splittable), and just check that it's a good idea to form
1700 // a single integer.
1702 return TD.isLegalInteger(SizeInBits);
1704 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
1706 // While examining uses, we ensure that the alloca has a covering load or
1707 // store. We don't want to widen the integer operations only to fail to
1708 // promote due to some other unsplittable entry (which we may make splittable
1710 bool WholeAllocaOp = false;
1713 if (!isIntegerWideningViableForPartitioning(TD, AllocaTy, AllocBeginOffset,
1714 Size, P, I, WholeAllocaOp))
1717 for (ArrayRef<AllocaPartitioning::iterator>::const_iterator
1718 SUI = SplitUses.begin(),
1719 SUE = SplitUses.end();
1721 if (!isIntegerWideningViableForPartitioning(TD, AllocaTy, AllocBeginOffset,
1722 Size, P, *SUI, WholeAllocaOp))
1725 return WholeAllocaOp;
1728 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1729 IntegerType *Ty, uint64_t Offset,
1730 const Twine &Name) {
1731 DEBUG(dbgs() << " start: " << *V << "\n");
1732 IntegerType *IntTy = cast<IntegerType>(V->getType());
1733 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1734 "Element extends past full value");
1735 uint64_t ShAmt = 8*Offset;
1736 if (DL.isBigEndian())
1737 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1739 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
1740 DEBUG(dbgs() << " shifted: " << *V << "\n");
1742 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1743 "Cannot extract to a larger integer!");
1745 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
1746 DEBUG(dbgs() << " trunced: " << *V << "\n");
1751 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
1752 Value *V, uint64_t Offset, const Twine &Name) {
1753 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1754 IntegerType *Ty = cast<IntegerType>(V->getType());
1755 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1756 "Cannot insert a larger integer!");
1757 DEBUG(dbgs() << " start: " << *V << "\n");
1759 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
1760 DEBUG(dbgs() << " extended: " << *V << "\n");
1762 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1763 "Element store outside of alloca store");
1764 uint64_t ShAmt = 8*Offset;
1765 if (DL.isBigEndian())
1766 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1768 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
1769 DEBUG(dbgs() << " shifted: " << *V << "\n");
1772 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1773 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1774 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
1775 DEBUG(dbgs() << " masked: " << *Old << "\n");
1776 V = IRB.CreateOr(Old, V, Name + ".insert");
1777 DEBUG(dbgs() << " inserted: " << *V << "\n");
1782 static Value *extractVector(IRBuilderTy &IRB, Value *V,
1783 unsigned BeginIndex, unsigned EndIndex,
1784 const Twine &Name) {
1785 VectorType *VecTy = cast<VectorType>(V->getType());
1786 unsigned NumElements = EndIndex - BeginIndex;
1787 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1789 if (NumElements == VecTy->getNumElements())
1792 if (NumElements == 1) {
1793 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1795 DEBUG(dbgs() << " extract: " << *V << "\n");
1799 SmallVector<Constant*, 8> Mask;
1800 Mask.reserve(NumElements);
1801 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1802 Mask.push_back(IRB.getInt32(i));
1803 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1804 ConstantVector::get(Mask),
1806 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1810 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
1811 unsigned BeginIndex, const Twine &Name) {
1812 VectorType *VecTy = cast<VectorType>(Old->getType());
1813 assert(VecTy && "Can only insert a vector into a vector");
1815 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1817 // Single element to insert.
1818 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1820 DEBUG(dbgs() << " insert: " << *V << "\n");
1824 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1825 "Too many elements!");
1826 if (Ty->getNumElements() == VecTy->getNumElements()) {
1827 assert(V->getType() == VecTy && "Vector type mismatch");
1830 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1832 // When inserting a smaller vector into the larger to store, we first
1833 // use a shuffle vector to widen it with undef elements, and then
1834 // a second shuffle vector to select between the loaded vector and the
1836 SmallVector<Constant*, 8> Mask;
1837 Mask.reserve(VecTy->getNumElements());
1838 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1839 if (i >= BeginIndex && i < EndIndex)
1840 Mask.push_back(IRB.getInt32(i - BeginIndex));
1842 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1843 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1844 ConstantVector::get(Mask),
1846 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1849 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1850 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1852 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1854 DEBUG(dbgs() << " blend: " << *V << "\n");
1859 /// \brief Visitor to rewrite instructions using a partition of an alloca to
1860 /// use a new alloca.
1862 /// Also implements the rewriting to vector-based accesses when the partition
1863 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1865 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
1867 // Befriend the base class so it can delegate to private visit methods.
1868 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
1869 typedef llvm::InstVisitor<AllocaPartitionRewriter, bool> Base;
1871 const DataLayout &TD;
1872 AllocaPartitioning &P;
1874 AllocaInst &OldAI, &NewAI;
1875 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1878 // If we are rewriting an alloca partition which can be written as pure
1879 // vector operations, we stash extra information here. When VecTy is
1880 // non-null, we have some strict guarantees about the rewritten alloca:
1881 // - The new alloca is exactly the size of the vector type here.
1882 // - The accesses all either map to the entire vector or to a single
1884 // - The set of accessing instructions is only one of those handled above
1885 // in isVectorPromotionViable. Generally these are the same access kinds
1886 // which are promotable via mem2reg.
1889 uint64_t ElementSize;
1891 // This is a convenience and flag variable that will be null unless the new
1892 // alloca's integer operations should be widened to this integer type due to
1893 // passing isIntegerWideningViable above. If it is non-null, the desired
1894 // integer type will be stored here for easy access during rewriting.
1897 // The offset of the partition user currently being rewritten.
1898 uint64_t BeginOffset, EndOffset;
1902 Instruction *OldPtr;
1904 // Utility IR builder, whose name prefix is setup for each visited use, and
1905 // the insertion point is set to point to the user.
1909 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
1910 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
1911 uint64_t NewBeginOffset, uint64_t NewEndOffset,
1912 bool IsVectorPromotable = false,
1913 bool IsIntegerPromotable = false)
1914 : TD(TD), P(P), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
1915 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1916 NewAllocaTy(NewAI.getAllocatedType()),
1917 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1918 ElementTy(VecTy ? VecTy->getElementType() : 0),
1919 ElementSize(VecTy ? TD.getTypeSizeInBits(ElementTy) / 8 : 0),
1920 IntTy(IsIntegerPromotable
1923 TD.getTypeSizeInBits(NewAI.getAllocatedType()))
1925 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
1926 OldPtr(), IRB(NewAI.getContext(), ConstantFolder()) {
1928 assert((TD.getTypeSizeInBits(ElementTy) % 8) == 0 &&
1929 "Only multiple-of-8 sized vector elements are viable");
1932 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
1933 IsVectorPromotable != IsIntegerPromotable);
1936 bool visit(AllocaPartitioning::const_iterator I) {
1937 bool CanSROA = true;
1938 BeginOffset = I->beginOffset();
1939 EndOffset = I->endOffset();
1940 IsSplittable = I->isSplittable();
1942 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
1944 OldUse = I->getUse();
1945 OldPtr = cast<Instruction>(OldUse->get());
1947 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
1948 IRB.SetInsertPoint(OldUserI);
1949 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
1950 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
1952 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
1959 // Make sure the other visit overloads are visible.
1962 // Every instruction which can end up as a user must have a rewrite rule.
1963 bool visitInstruction(Instruction &I) {
1964 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1965 llvm_unreachable("No rewrite rule for this instruction!");
1968 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
1970 assert(Offset >= NewAllocaBeginOffset);
1971 return getAdjustedPtr(IRB, TD, &NewAI, APInt(TD.getPointerSizeInBits(),
1972 Offset - NewAllocaBeginOffset),
1976 /// \brief Compute suitable alignment to access an offset into the new alloca.
1977 unsigned getOffsetAlign(uint64_t Offset) {
1978 unsigned NewAIAlign = NewAI.getAlignment();
1980 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
1981 return MinAlign(NewAIAlign, Offset);
1984 /// \brief Compute suitable alignment to access a type at an offset of the
1987 /// \returns zero if the type's ABI alignment is a suitable alignment,
1988 /// otherwise returns the maximal suitable alignment.
1989 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
1990 unsigned Align = getOffsetAlign(Offset);
1991 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
1994 unsigned getIndex(uint64_t Offset) {
1995 assert(VecTy && "Can only call getIndex when rewriting a vector");
1996 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1997 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1998 uint32_t Index = RelOffset / ElementSize;
1999 assert(Index * ElementSize == RelOffset);
2003 void deleteIfTriviallyDead(Value *V) {
2004 Instruction *I = cast<Instruction>(V);
2005 if (isInstructionTriviallyDead(I))
2006 Pass.DeadInsts.insert(I);
2009 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
2010 uint64_t NewEndOffset) {
2011 unsigned BeginIndex = getIndex(NewBeginOffset);
2012 unsigned EndIndex = getIndex(NewEndOffset);
2013 assert(EndIndex > BeginIndex && "Empty vector!");
2015 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2017 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2020 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2021 uint64_t NewEndOffset) {
2022 assert(IntTy && "We cannot insert an integer to the alloca");
2023 assert(!LI.isVolatile());
2024 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2026 V = convertValue(TD, IRB, V, IntTy);
2027 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2028 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2029 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
2030 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2035 bool visitLoadInst(LoadInst &LI) {
2036 DEBUG(dbgs() << " original: " << LI << "\n");
2037 Value *OldOp = LI.getOperand(0);
2038 assert(OldOp == OldPtr);
2040 // Compute the intersecting offset range.
2041 assert(BeginOffset < NewAllocaEndOffset);
2042 assert(EndOffset > NewAllocaBeginOffset);
2043 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2044 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2046 uint64_t Size = NewEndOffset - NewBeginOffset;
2048 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2050 bool IsPtrAdjusted = false;
2053 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
2054 } else if (IntTy && LI.getType()->isIntegerTy()) {
2055 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2056 } else if (NewBeginOffset == NewAllocaBeginOffset &&
2057 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2058 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2059 LI.isVolatile(), "load");
2061 Type *LTy = TargetTy->getPointerTo();
2062 V = IRB.CreateAlignedLoad(
2063 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2064 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2065 LI.isVolatile(), "load");
2066 IsPtrAdjusted = true;
2068 V = convertValue(TD, IRB, V, TargetTy);
2071 assert(!LI.isVolatile());
2072 assert(LI.getType()->isIntegerTy() &&
2073 "Only integer type loads and stores are split");
2074 assert(Size < TD.getTypeStoreSize(LI.getType()) &&
2075 "Split load isn't smaller than original load");
2076 assert(LI.getType()->getIntegerBitWidth() ==
2077 TD.getTypeStoreSizeInBits(LI.getType()) &&
2078 "Non-byte-multiple bit width");
2079 // Move the insertion point just past the load so that we can refer to it.
2080 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
2081 // Create a placeholder value with the same type as LI to use as the
2082 // basis for the new value. This allows us to replace the uses of LI with
2083 // the computed value, and then replace the placeholder with LI, leaving
2084 // LI only used for this computation.
2086 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2087 V = insertInteger(TD, IRB, Placeholder, V, NewBeginOffset,
2089 LI.replaceAllUsesWith(V);
2090 Placeholder->replaceAllUsesWith(&LI);
2093 LI.replaceAllUsesWith(V);
2096 Pass.DeadInsts.insert(&LI);
2097 deleteIfTriviallyDead(OldOp);
2098 DEBUG(dbgs() << " to: " << *V << "\n");
2099 return !LI.isVolatile() && !IsPtrAdjusted;
2102 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2103 uint64_t NewBeginOffset,
2104 uint64_t NewEndOffset) {
2105 if (V->getType() != VecTy) {
2106 unsigned BeginIndex = getIndex(NewBeginOffset);
2107 unsigned EndIndex = getIndex(NewEndOffset);
2108 assert(EndIndex > BeginIndex && "Empty vector!");
2109 unsigned NumElements = EndIndex - BeginIndex;
2110 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2112 = (NumElements == 1) ? ElementTy
2113 : VectorType::get(ElementTy, NumElements);
2114 if (V->getType() != PartitionTy)
2115 V = convertValue(TD, IRB, V, PartitionTy);
2117 // Mix in the existing elements.
2118 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2120 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2122 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2123 Pass.DeadInsts.insert(&SI);
2126 DEBUG(dbgs() << " to: " << *Store << "\n");
2130 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2131 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
2132 assert(IntTy && "We cannot extract an integer from the alloca");
2133 assert(!SI.isVolatile());
2134 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2135 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2137 Old = convertValue(TD, IRB, Old, IntTy);
2138 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2139 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2140 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2143 V = convertValue(TD, IRB, V, NewAllocaTy);
2144 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2145 Pass.DeadInsts.insert(&SI);
2147 DEBUG(dbgs() << " to: " << *Store << "\n");
2151 bool visitStoreInst(StoreInst &SI) {
2152 DEBUG(dbgs() << " original: " << SI << "\n");
2153 Value *OldOp = SI.getOperand(1);
2154 assert(OldOp == OldPtr);
2156 Value *V = SI.getValueOperand();
2158 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2159 // alloca that should be re-examined after promoting this alloca.
2160 if (V->getType()->isPointerTy())
2161 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2162 Pass.PostPromotionWorklist.insert(AI);
2164 // Compute the intersecting offset range.
2165 assert(BeginOffset < NewAllocaEndOffset);
2166 assert(EndOffset > NewAllocaBeginOffset);
2167 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2168 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2170 uint64_t Size = NewEndOffset - NewBeginOffset;
2171 if (Size < TD.getTypeStoreSize(V->getType())) {
2172 assert(!SI.isVolatile());
2173 assert(V->getType()->isIntegerTy() &&
2174 "Only integer type loads and stores are split");
2175 assert(V->getType()->getIntegerBitWidth() ==
2176 TD.getTypeStoreSizeInBits(V->getType()) &&
2177 "Non-byte-multiple bit width");
2178 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2179 V = extractInteger(TD, IRB, V, NarrowTy, NewBeginOffset,
2184 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2186 if (IntTy && V->getType()->isIntegerTy())
2187 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
2190 if (NewBeginOffset == NewAllocaBeginOffset &&
2191 NewEndOffset == NewAllocaEndOffset &&
2192 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2193 V = convertValue(TD, IRB, V, NewAllocaTy);
2194 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2197 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2198 V->getType()->getPointerTo());
2199 NewSI = IRB.CreateAlignedStore(
2200 V, NewPtr, getOffsetTypeAlign(
2201 V->getType(), NewBeginOffset - NewAllocaBeginOffset),
2205 Pass.DeadInsts.insert(&SI);
2206 deleteIfTriviallyDead(OldOp);
2208 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2209 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2212 /// \brief Compute an integer value from splatting an i8 across the given
2213 /// number of bytes.
2215 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2216 /// call this routine.
2217 /// FIXME: Heed the advice above.
2219 /// \param V The i8 value to splat.
2220 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2221 Value *getIntegerSplat(Value *V, unsigned Size) {
2222 assert(Size > 0 && "Expected a positive number of bytes.");
2223 IntegerType *VTy = cast<IntegerType>(V->getType());
2224 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2228 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2229 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
2230 ConstantExpr::getUDiv(
2231 Constant::getAllOnesValue(SplatIntTy),
2232 ConstantExpr::getZExt(
2233 Constant::getAllOnesValue(V->getType()),
2239 /// \brief Compute a vector splat for a given element value.
2240 Value *getVectorSplat(Value *V, unsigned NumElements) {
2241 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2242 DEBUG(dbgs() << " splat: " << *V << "\n");
2246 bool visitMemSetInst(MemSetInst &II) {
2247 DEBUG(dbgs() << " original: " << II << "\n");
2248 assert(II.getRawDest() == OldPtr);
2250 // If the memset has a variable size, it cannot be split, just adjust the
2251 // pointer to the new alloca.
2252 if (!isa<Constant>(II.getLength())) {
2254 assert(BeginOffset >= NewAllocaBeginOffset);
2256 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
2257 Type *CstTy = II.getAlignmentCst()->getType();
2258 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
2260 deleteIfTriviallyDead(OldPtr);
2264 // Record this instruction for deletion.
2265 Pass.DeadInsts.insert(&II);
2267 Type *AllocaTy = NewAI.getAllocatedType();
2268 Type *ScalarTy = AllocaTy->getScalarType();
2270 // Compute the intersecting offset range.
2271 assert(BeginOffset < NewAllocaEndOffset);
2272 assert(EndOffset > NewAllocaBeginOffset);
2273 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2274 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2275 uint64_t PartitionOffset = NewBeginOffset - NewAllocaBeginOffset;
2277 // If this doesn't map cleanly onto the alloca type, and that type isn't
2278 // a single value type, just emit a memset.
2279 if (!VecTy && !IntTy &&
2280 (BeginOffset > NewAllocaBeginOffset ||
2281 EndOffset < NewAllocaEndOffset ||
2282 !AllocaTy->isSingleValueType() ||
2283 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)) ||
2284 TD.getTypeSizeInBits(ScalarTy)%8 != 0)) {
2285 Type *SizeTy = II.getLength()->getType();
2286 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2287 CallInst *New = IRB.CreateMemSet(
2288 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getRawDest()->getType()),
2289 II.getValue(), Size, getOffsetAlign(PartitionOffset),
2292 DEBUG(dbgs() << " to: " << *New << "\n");
2296 // If we can represent this as a simple value, we have to build the actual
2297 // value to store, which requires expanding the byte present in memset to
2298 // a sensible representation for the alloca type. This is essentially
2299 // splatting the byte to a sufficiently wide integer, splatting it across
2300 // any desired vector width, and bitcasting to the final type.
2304 // If this is a memset of a vectorized alloca, insert it.
2305 assert(ElementTy == ScalarTy);
2307 unsigned BeginIndex = getIndex(NewBeginOffset);
2308 unsigned EndIndex = getIndex(NewEndOffset);
2309 assert(EndIndex > BeginIndex && "Empty vector!");
2310 unsigned NumElements = EndIndex - BeginIndex;
2311 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2314 getIntegerSplat(II.getValue(), TD.getTypeSizeInBits(ElementTy) / 8);
2315 Splat = convertValue(TD, IRB, Splat, ElementTy);
2316 if (NumElements > 1)
2317 Splat = getVectorSplat(Splat, NumElements);
2319 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2321 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2323 // If this is a memset on an alloca where we can widen stores, insert the
2325 assert(!II.isVolatile());
2327 uint64_t Size = NewEndOffset - NewBeginOffset;
2328 V = getIntegerSplat(II.getValue(), Size);
2330 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2331 EndOffset != NewAllocaBeginOffset)) {
2332 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2334 Old = convertValue(TD, IRB, Old, IntTy);
2335 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2336 V = insertInteger(TD, IRB, Old, V, Offset, "insert");
2338 assert(V->getType() == IntTy &&
2339 "Wrong type for an alloca wide integer!");
2341 V = convertValue(TD, IRB, V, AllocaTy);
2343 // Established these invariants above.
2344 assert(NewBeginOffset == NewAllocaBeginOffset);
2345 assert(NewEndOffset == NewAllocaEndOffset);
2347 V = getIntegerSplat(II.getValue(), TD.getTypeSizeInBits(ScalarTy) / 8);
2348 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2349 V = getVectorSplat(V, AllocaVecTy->getNumElements());
2351 V = convertValue(TD, IRB, V, AllocaTy);
2354 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2357 DEBUG(dbgs() << " to: " << *New << "\n");
2358 return !II.isVolatile();
2361 bool visitMemTransferInst(MemTransferInst &II) {
2362 // Rewriting of memory transfer instructions can be a bit tricky. We break
2363 // them into two categories: split intrinsics and unsplit intrinsics.
2365 DEBUG(dbgs() << " original: " << II << "\n");
2367 // Compute the intersecting offset range.
2368 assert(BeginOffset < NewAllocaEndOffset);
2369 assert(EndOffset > NewAllocaBeginOffset);
2370 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2371 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2373 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2374 bool IsDest = II.getRawDest() == OldPtr;
2376 // Compute the relative offset within the transfer.
2377 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2378 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2380 unsigned Align = II.getAlignment();
2381 uint64_t PartitionOffset = NewBeginOffset - NewAllocaBeginOffset;
2384 RelOffset.zextOrTrunc(64).getZExtValue(),
2385 MinAlign(II.getAlignment(), getOffsetAlign(PartitionOffset)));
2387 // For unsplit intrinsics, we simply modify the source and destination
2388 // pointers in place. This isn't just an optimization, it is a matter of
2389 // correctness. With unsplit intrinsics we may be dealing with transfers
2390 // within a single alloca before SROA ran, or with transfers that have
2391 // a variable length. We may also be dealing with memmove instead of
2392 // memcpy, and so simply updating the pointers is the necessary for us to
2393 // update both source and dest of a single call.
2394 if (!IsSplittable) {
2395 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2398 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
2400 II.setSource(getAdjustedAllocaPtr(IRB, BeginOffset,
2401 II.getRawSource()->getType()));
2403 Type *CstTy = II.getAlignmentCst()->getType();
2404 II.setAlignment(ConstantInt::get(CstTy, Align));
2406 DEBUG(dbgs() << " to: " << II << "\n");
2407 deleteIfTriviallyDead(OldOp);
2410 // For split transfer intrinsics we have an incredibly useful assurance:
2411 // the source and destination do not reside within the same alloca, and at
2412 // least one of them does not escape. This means that we can replace
2413 // memmove with memcpy, and we don't need to worry about all manner of
2414 // downsides to splitting and transforming the operations.
2416 // If this doesn't map cleanly onto the alloca type, and that type isn't
2417 // a single value type, just emit a memcpy.
2419 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2420 EndOffset < NewAllocaEndOffset ||
2421 !NewAI.getAllocatedType()->isSingleValueType());
2423 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2424 // size hasn't been shrunk based on analysis of the viable range, this is
2426 if (EmitMemCpy && &OldAI == &NewAI) {
2427 // Ensure the start lines up.
2428 assert(NewBeginOffset == BeginOffset);
2430 // Rewrite the size as needed.
2431 if (NewEndOffset != EndOffset)
2432 II.setLength(ConstantInt::get(II.getLength()->getType(),
2433 NewEndOffset - NewBeginOffset));
2436 // Record this instruction for deletion.
2437 Pass.DeadInsts.insert(&II);
2439 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2440 // alloca that should be re-examined after rewriting this instruction.
2441 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2443 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2444 Pass.Worklist.insert(AI);
2447 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2448 : II.getRawDest()->getType();
2450 // Compute the other pointer, folding as much as possible to produce
2451 // a single, simple GEP in most cases.
2452 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy);
2454 Value *OurPtr = getAdjustedAllocaPtr(
2455 IRB, NewBeginOffset,
2456 IsDest ? II.getRawDest()->getType() : II.getRawSource()->getType());
2457 Type *SizeTy = II.getLength()->getType();
2458 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2460 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2461 IsDest ? OtherPtr : OurPtr,
2462 Size, Align, II.isVolatile());
2464 DEBUG(dbgs() << " to: " << *New << "\n");
2468 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2469 // is equivalent to 1, but that isn't true if we end up rewriting this as
2474 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2475 NewEndOffset == NewAllocaEndOffset;
2476 uint64_t Size = NewEndOffset - NewBeginOffset;
2477 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2478 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2479 unsigned NumElements = EndIndex - BeginIndex;
2480 IntegerType *SubIntTy
2481 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2483 Type *OtherPtrTy = NewAI.getType();
2484 if (VecTy && !IsWholeAlloca) {
2485 if (NumElements == 1)
2486 OtherPtrTy = VecTy->getElementType();
2488 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2490 OtherPtrTy = OtherPtrTy->getPointerTo();
2491 } else if (IntTy && !IsWholeAlloca) {
2492 OtherPtrTy = SubIntTy->getPointerTo();
2495 Value *SrcPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy);
2496 Value *DstPtr = &NewAI;
2498 std::swap(SrcPtr, DstPtr);
2501 if (VecTy && !IsWholeAlloca && !IsDest) {
2502 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2504 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
2505 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2506 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2508 Src = convertValue(TD, IRB, Src, IntTy);
2509 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2510 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, "extract");
2512 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2516 if (VecTy && !IsWholeAlloca && IsDest) {
2517 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2519 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
2520 } else if (IntTy && !IsWholeAlloca && IsDest) {
2521 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2523 Old = convertValue(TD, IRB, Old, IntTy);
2524 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2525 Src = insertInteger(TD, IRB, Old, Src, Offset, "insert");
2526 Src = convertValue(TD, IRB, Src, NewAllocaTy);
2529 StoreInst *Store = cast<StoreInst>(
2530 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2532 DEBUG(dbgs() << " to: " << *Store << "\n");
2533 return !II.isVolatile();
2536 bool visitIntrinsicInst(IntrinsicInst &II) {
2537 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2538 II.getIntrinsicID() == Intrinsic::lifetime_end);
2539 DEBUG(dbgs() << " original: " << II << "\n");
2540 assert(II.getArgOperand(1) == OldPtr);
2542 // Compute the intersecting offset range.
2543 assert(BeginOffset < NewAllocaEndOffset);
2544 assert(EndOffset > NewAllocaBeginOffset);
2545 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2546 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2548 // Record this instruction for deletion.
2549 Pass.DeadInsts.insert(&II);
2552 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2553 NewEndOffset - NewBeginOffset);
2555 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getArgOperand(1)->getType());
2557 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2558 New = IRB.CreateLifetimeStart(Ptr, Size);
2560 New = IRB.CreateLifetimeEnd(Ptr, Size);
2563 DEBUG(dbgs() << " to: " << *New << "\n");
2567 bool visitPHINode(PHINode &PN) {
2568 DEBUG(dbgs() << " original: " << PN << "\n");
2569 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2570 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
2572 // We would like to compute a new pointer in only one place, but have it be
2573 // as local as possible to the PHI. To do that, we re-use the location of
2574 // the old pointer, which necessarily must be in the right position to
2575 // dominate the PHI.
2576 IRBuilderTy PtrBuilder(cast<Instruction>(OldPtr));
2577 PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2581 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
2582 // Replace the operands which were using the old pointer.
2583 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
2585 DEBUG(dbgs() << " to: " << PN << "\n");
2586 deleteIfTriviallyDead(OldPtr);
2588 // Check whether we can speculate this PHI node, and if so remember that
2589 // fact and return that this alloca remains viable for promotion to an SSA
2591 if (isSafePHIToSpeculate(PN, &TD)) {
2592 Pass.SpeculatablePHIs.insert(&PN);
2596 return false; // PHIs can't be promoted on their own.
2599 bool visitSelectInst(SelectInst &SI) {
2600 DEBUG(dbgs() << " original: " << SI << "\n");
2601 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2602 "Pointer isn't an operand!");
2603 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2604 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
2606 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
2607 // Replace the operands which were using the old pointer.
2608 if (SI.getOperand(1) == OldPtr)
2609 SI.setOperand(1, NewPtr);
2610 if (SI.getOperand(2) == OldPtr)
2611 SI.setOperand(2, NewPtr);
2613 DEBUG(dbgs() << " to: " << SI << "\n");
2614 deleteIfTriviallyDead(OldPtr);
2616 // Check whether we can speculate this select instruction, and if so
2617 // remember that fact and return that this alloca remains viable for
2618 // promotion to an SSA value.
2619 if (isSafeSelectToSpeculate(SI, &TD)) {
2620 Pass.SpeculatableSelects.insert(&SI);
2624 return false; // Selects can't be promoted on their own.
2631 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2633 /// This pass aggressively rewrites all aggregate loads and stores on
2634 /// a particular pointer (or any pointer derived from it which we can identify)
2635 /// with scalar loads and stores.
2636 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2637 // Befriend the base class so it can delegate to private visit methods.
2638 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2640 const DataLayout &TD;
2642 /// Queue of pointer uses to analyze and potentially rewrite.
2643 SmallVector<Use *, 8> Queue;
2645 /// Set to prevent us from cycling with phi nodes and loops.
2646 SmallPtrSet<User *, 8> Visited;
2648 /// The current pointer use being rewritten. This is used to dig up the used
2649 /// value (as opposed to the user).
2653 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
2655 /// Rewrite loads and stores through a pointer and all pointers derived from
2657 bool rewrite(Instruction &I) {
2658 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2660 bool Changed = false;
2661 while (!Queue.empty()) {
2662 U = Queue.pop_back_val();
2663 Changed |= visit(cast<Instruction>(U->getUser()));
2669 /// Enqueue all the users of the given instruction for further processing.
2670 /// This uses a set to de-duplicate users.
2671 void enqueueUsers(Instruction &I) {
2672 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2674 if (Visited.insert(*UI))
2675 Queue.push_back(&UI.getUse());
2678 // Conservative default is to not rewrite anything.
2679 bool visitInstruction(Instruction &I) { return false; }
2681 /// \brief Generic recursive split emission class.
2682 template <typename Derived>
2685 /// The builder used to form new instructions.
2687 /// The indices which to be used with insert- or extractvalue to select the
2688 /// appropriate value within the aggregate.
2689 SmallVector<unsigned, 4> Indices;
2690 /// The indices to a GEP instruction which will move Ptr to the correct slot
2691 /// within the aggregate.
2692 SmallVector<Value *, 4> GEPIndices;
2693 /// The base pointer of the original op, used as a base for GEPing the
2694 /// split operations.
2697 /// Initialize the splitter with an insertion point, Ptr and start with a
2698 /// single zero GEP index.
2699 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
2700 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
2703 /// \brief Generic recursive split emission routine.
2705 /// This method recursively splits an aggregate op (load or store) into
2706 /// scalar or vector ops. It splits recursively until it hits a single value
2707 /// and emits that single value operation via the template argument.
2709 /// The logic of this routine relies on GEPs and insertvalue and
2710 /// extractvalue all operating with the same fundamental index list, merely
2711 /// formatted differently (GEPs need actual values).
2713 /// \param Ty The type being split recursively into smaller ops.
2714 /// \param Agg The aggregate value being built up or stored, depending on
2715 /// whether this is splitting a load or a store respectively.
2716 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2717 if (Ty->isSingleValueType())
2718 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
2720 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2721 unsigned OldSize = Indices.size();
2723 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2725 assert(Indices.size() == OldSize && "Did not return to the old size");
2726 Indices.push_back(Idx);
2727 GEPIndices.push_back(IRB.getInt32(Idx));
2728 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2729 GEPIndices.pop_back();
2735 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2736 unsigned OldSize = Indices.size();
2738 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2740 assert(Indices.size() == OldSize && "Did not return to the old size");
2741 Indices.push_back(Idx);
2742 GEPIndices.push_back(IRB.getInt32(Idx));
2743 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2744 GEPIndices.pop_back();
2750 llvm_unreachable("Only arrays and structs are aggregate loadable types");
2754 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
2755 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2756 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
2758 /// Emit a leaf load of a single value. This is called at the leaves of the
2759 /// recursive emission to actually load values.
2760 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2761 assert(Ty->isSingleValueType());
2762 // Load the single value and insert it using the indices.
2763 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2764 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
2765 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2766 DEBUG(dbgs() << " to: " << *Load << "\n");
2770 bool visitLoadInst(LoadInst &LI) {
2771 assert(LI.getPointerOperand() == *U);
2772 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2775 // We have an aggregate being loaded, split it apart.
2776 DEBUG(dbgs() << " original: " << LI << "\n");
2777 LoadOpSplitter Splitter(&LI, *U);
2778 Value *V = UndefValue::get(LI.getType());
2779 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
2780 LI.replaceAllUsesWith(V);
2781 LI.eraseFromParent();
2785 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
2786 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2787 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
2789 /// Emit a leaf store of a single value. This is called at the leaves of the
2790 /// recursive emission to actually produce stores.
2791 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2792 assert(Ty->isSingleValueType());
2793 // Extract the single value and store it using the indices.
2794 Value *Store = IRB.CreateStore(
2795 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2796 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2798 DEBUG(dbgs() << " to: " << *Store << "\n");
2802 bool visitStoreInst(StoreInst &SI) {
2803 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2805 Value *V = SI.getValueOperand();
2806 if (V->getType()->isSingleValueType())
2809 // We have an aggregate being stored, split it apart.
2810 DEBUG(dbgs() << " original: " << SI << "\n");
2811 StoreOpSplitter Splitter(&SI, *U);
2812 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
2813 SI.eraseFromParent();
2817 bool visitBitCastInst(BitCastInst &BC) {
2822 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2827 bool visitPHINode(PHINode &PN) {
2832 bool visitSelectInst(SelectInst &SI) {
2839 /// \brief Strip aggregate type wrapping.
2841 /// This removes no-op aggregate types wrapping an underlying type. It will
2842 /// strip as many layers of types as it can without changing either the type
2843 /// size or the allocated size.
2844 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2845 if (Ty->isSingleValueType())
2848 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2849 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2852 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2853 InnerTy = ArrTy->getElementType();
2854 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2855 const StructLayout *SL = DL.getStructLayout(STy);
2856 unsigned Index = SL->getElementContainingOffset(0);
2857 InnerTy = STy->getElementType(Index);
2862 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2863 TypeSize > DL.getTypeSizeInBits(InnerTy))
2866 return stripAggregateTypeWrapping(DL, InnerTy);
2869 /// \brief Try to find a partition of the aggregate type passed in for a given
2870 /// offset and size.
2872 /// This recurses through the aggregate type and tries to compute a subtype
2873 /// based on the offset and size. When the offset and size span a sub-section
2874 /// of an array, it will even compute a new array type for that sub-section,
2875 /// and the same for structs.
2877 /// Note that this routine is very strict and tries to find a partition of the
2878 /// type which produces the *exact* right offset and size. It is not forgiving
2879 /// when the size or offset cause either end of type-based partition to be off.
2880 /// Also, this is a best-effort routine. It is reasonable to give up and not
2881 /// return a type if necessary.
2882 static Type *getTypePartition(const DataLayout &TD, Type *Ty,
2883 uint64_t Offset, uint64_t Size) {
2884 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2885 return stripAggregateTypeWrapping(TD, Ty);
2886 if (Offset > TD.getTypeAllocSize(Ty) ||
2887 (TD.getTypeAllocSize(Ty) - Offset) < Size)
2890 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2891 // We can't partition pointers...
2892 if (SeqTy->isPointerTy())
2895 Type *ElementTy = SeqTy->getElementType();
2896 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2897 uint64_t NumSkippedElements = Offset / ElementSize;
2898 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
2899 if (NumSkippedElements >= ArrTy->getNumElements())
2901 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
2902 if (NumSkippedElements >= VecTy->getNumElements())
2905 Offset -= NumSkippedElements * ElementSize;
2907 // First check if we need to recurse.
2908 if (Offset > 0 || Size < ElementSize) {
2909 // Bail if the partition ends in a different array element.
2910 if ((Offset + Size) > ElementSize)
2912 // Recurse through the element type trying to peel off offset bytes.
2913 return getTypePartition(TD, ElementTy, Offset, Size);
2915 assert(Offset == 0);
2917 if (Size == ElementSize)
2918 return stripAggregateTypeWrapping(TD, ElementTy);
2919 assert(Size > ElementSize);
2920 uint64_t NumElements = Size / ElementSize;
2921 if (NumElements * ElementSize != Size)
2923 return ArrayType::get(ElementTy, NumElements);
2926 StructType *STy = dyn_cast<StructType>(Ty);
2930 const StructLayout *SL = TD.getStructLayout(STy);
2931 if (Offset >= SL->getSizeInBytes())
2933 uint64_t EndOffset = Offset + Size;
2934 if (EndOffset > SL->getSizeInBytes())
2937 unsigned Index = SL->getElementContainingOffset(Offset);
2938 Offset -= SL->getElementOffset(Index);
2940 Type *ElementTy = STy->getElementType(Index);
2941 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2942 if (Offset >= ElementSize)
2943 return 0; // The offset points into alignment padding.
2945 // See if any partition must be contained by the element.
2946 if (Offset > 0 || Size < ElementSize) {
2947 if ((Offset + Size) > ElementSize)
2949 return getTypePartition(TD, ElementTy, Offset, Size);
2951 assert(Offset == 0);
2953 if (Size == ElementSize)
2954 return stripAggregateTypeWrapping(TD, ElementTy);
2956 StructType::element_iterator EI = STy->element_begin() + Index,
2957 EE = STy->element_end();
2958 if (EndOffset < SL->getSizeInBytes()) {
2959 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2960 if (Index == EndIndex)
2961 return 0; // Within a single element and its padding.
2963 // Don't try to form "natural" types if the elements don't line up with the
2965 // FIXME: We could potentially recurse down through the last element in the
2966 // sub-struct to find a natural end point.
2967 if (SL->getElementOffset(EndIndex) != EndOffset)
2970 assert(Index < EndIndex);
2971 EE = STy->element_begin() + EndIndex;
2974 // Try to build up a sub-structure.
2975 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
2977 const StructLayout *SubSL = TD.getStructLayout(SubTy);
2978 if (Size != SubSL->getSizeInBytes())
2979 return 0; // The sub-struct doesn't have quite the size needed.
2984 /// \brief Rewrite an alloca partition's users.
2986 /// This routine drives both of the rewriting goals of the SROA pass. It tries
2987 /// to rewrite uses of an alloca partition to be conducive for SSA value
2988 /// promotion. If the partition needs a new, more refined alloca, this will
2989 /// build that new alloca, preserving as much type information as possible, and
2990 /// rewrite the uses of the old alloca to point at the new one and have the
2991 /// appropriate new offsets. It also evaluates how successful the rewrite was
2992 /// at enabling promotion and if it was successful queues the alloca to be
2994 bool SROA::rewritePartitions(AllocaInst &AI, AllocaPartitioning &P,
2995 AllocaPartitioning::iterator B,
2996 AllocaPartitioning::iterator E,
2997 int64_t BeginOffset, int64_t EndOffset,
2998 ArrayRef<AllocaPartitioning::iterator> SplitUses) {
2999 assert(BeginOffset < EndOffset);
3000 uint64_t PartitionSize = EndOffset - BeginOffset;
3002 // Try to compute a friendly type for this partition of the alloca. This
3003 // won't always succeed, in which case we fall back to a legal integer type
3004 // or an i8 array of an appropriate size.
3005 Type *PartitionTy = 0;
3006 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
3007 if (TD->getTypeAllocSize(CommonUseTy) >= PartitionSize)
3008 PartitionTy = CommonUseTy;
3010 if (Type *TypePartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3011 BeginOffset, PartitionSize))
3012 PartitionTy = TypePartitionTy;
3013 if ((!PartitionTy || (PartitionTy->isArrayTy() &&
3014 PartitionTy->getArrayElementType()->isIntegerTy())) &&
3015 TD->isLegalInteger(PartitionSize * 8))
3016 PartitionTy = Type::getIntNTy(*C, PartitionSize * 8);
3018 PartitionTy = ArrayType::get(Type::getInt8Ty(*C), PartitionSize);
3019 assert(TD->getTypeAllocSize(PartitionTy) >= PartitionSize);
3021 bool IsVectorPromotable = isVectorPromotionViable(
3022 *TD, PartitionTy, P, BeginOffset, EndOffset, B, E, SplitUses);
3024 bool IsIntegerPromotable =
3025 !IsVectorPromotable &&
3026 isIntegerWideningViable(*TD, PartitionTy, BeginOffset, P, B, E,
3029 // Check for the case where we're going to rewrite to a new alloca of the
3030 // exact same type as the original, and with the same access offsets. In that
3031 // case, re-use the existing alloca, but still run through the rewriter to
3032 // perform phi and select speculation.
3034 if (PartitionTy == AI.getAllocatedType()) {
3035 assert(BeginOffset == 0 &&
3036 "Non-zero begin offset but same alloca type");
3038 // FIXME: We should be able to bail at this point with "nothing changed".
3039 // FIXME: We might want to defer PHI speculation until after here.
3041 unsigned Alignment = AI.getAlignment();
3043 // The minimum alignment which users can rely on when the explicit
3044 // alignment is omitted or zero is that required by the ABI for this
3046 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3048 Alignment = MinAlign(Alignment, BeginOffset);
3049 // If we will get at least this much alignment from the type alone, leave
3050 // the alloca's alignment unconstrained.
3051 if (Alignment <= TD->getABITypeAlignment(PartitionTy))
3053 NewAI = new AllocaInst(PartitionTy, 0, Alignment,
3054 AI.getName() + ".sroa." + Twine(B - P.begin()), &AI);
3058 DEBUG(dbgs() << "Rewriting alloca partition "
3059 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3062 // Track the high watermark on several worklists that are only relevant for
3063 // promoted allocas. We will reset it to this point if the alloca is not in
3064 // fact scheduled for promotion.
3065 unsigned PPWOldSize = PostPromotionWorklist.size();
3066 unsigned SPOldSize = SpeculatablePHIs.size();
3067 unsigned SSOldSize = SpeculatableSelects.size();
3069 AllocaPartitionRewriter Rewriter(*TD, P, *this, AI, *NewAI, BeginOffset,
3070 EndOffset, IsVectorPromotable,
3071 IsIntegerPromotable);
3072 bool Promotable = true;
3073 for (ArrayRef<AllocaPartitioning::iterator>::const_iterator
3074 SUI = SplitUses.begin(),
3075 SUE = SplitUses.end();
3076 SUI != SUE; ++SUI) {
3077 DEBUG(dbgs() << " rewriting split ");
3078 DEBUG(P.printPartition(dbgs(), *SUI, ""));
3079 Promotable &= Rewriter.visit(*SUI);
3081 for (AllocaPartitioning::iterator I = B; I != E; ++I) {
3082 DEBUG(dbgs() << " rewriting ");
3083 DEBUG(P.printPartition(dbgs(), I, ""));
3084 Promotable &= Rewriter.visit(I);
3087 if (Promotable && (SpeculatablePHIs.size() > SPOldSize ||
3088 SpeculatableSelects.size() > SSOldSize)) {
3089 // If we have a promotable alloca except for some unspeculated loads below
3090 // PHIs or Selects, iterate once. We will speculate the loads and on the
3091 // next iteration rewrite them into a promotable form.
3092 Worklist.insert(NewAI);
3093 } else if (Promotable) {
3094 DEBUG(dbgs() << " and queuing for promotion\n");
3095 PromotableAllocas.push_back(NewAI);
3096 } else if (NewAI != &AI) {
3097 // If we can't promote the alloca, iterate on it to check for new
3098 // refinements exposed by splitting the current alloca. Don't iterate on an
3099 // alloca which didn't actually change and didn't get promoted.
3100 // FIXME: We should actually track whether the rewriter changed anything.
3101 Worklist.insert(NewAI);
3104 // Drop any post-promotion work items if promotion didn't happen.
3106 while (PostPromotionWorklist.size() > PPWOldSize)
3107 PostPromotionWorklist.pop_back();
3108 while (SpeculatablePHIs.size() > SPOldSize)
3109 SpeculatablePHIs.pop_back();
3110 while (SpeculatableSelects.size() > SSOldSize)
3111 SpeculatableSelects.pop_back();
3118 struct IsPartitionEndLessOrEqualTo {
3119 uint64_t UpperBound;
3121 IsPartitionEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
3123 bool operator()(const AllocaPartitioning::iterator &I) {
3124 return I->endOffset() <= UpperBound;
3129 static void removeFinishedSplitUses(
3130 SmallVectorImpl<AllocaPartitioning::iterator> &SplitUses,
3131 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
3132 if (Offset >= MaxSplitUseEndOffset) {
3134 MaxSplitUseEndOffset = 0;
3138 size_t SplitUsesOldSize = SplitUses.size();
3139 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
3140 IsPartitionEndLessOrEqualTo(Offset)),
3142 if (SplitUsesOldSize == SplitUses.size())
3145 // Recompute the max. While this is linear, so is remove_if.
3146 MaxSplitUseEndOffset = 0;
3147 for (SmallVectorImpl<AllocaPartitioning::iterator>::iterator
3148 SUI = SplitUses.begin(),
3149 SUE = SplitUses.end();
3151 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3154 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3155 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3156 if (P.begin() == P.end())
3159 bool Changed = false;
3160 SmallVector<AllocaPartitioning::iterator, 4> SplitUses;
3161 uint64_t MaxSplitUseEndOffset = 0;
3163 uint64_t BeginOffset = P.begin()->beginOffset();
3165 for (AllocaPartitioning::iterator PI = P.begin(), PJ = llvm::next(PI),
3167 PI != PE; PI = PJ) {
3168 uint64_t MaxEndOffset = PI->endOffset();
3170 if (!PI->isSplittable()) {
3171 // When we're forming an unsplittable region, it must always start at he
3172 // first partitioning use and will extend through its end.
3173 assert(BeginOffset == PI->beginOffset());
3175 // Rewrite a partition including all of the overlapping uses with this
3176 // unsplittable partition.
3177 while (PJ != PE && PJ->beginOffset() < MaxEndOffset) {
3178 if (!PJ->isSplittable())
3179 MaxEndOffset = std::max(MaxEndOffset, PJ->endOffset());
3183 assert(PI->isSplittable()); // Established above.
3185 // Collect all of the overlapping splittable partitions.
3186 while (PJ != PE && PJ->beginOffset() < MaxEndOffset &&
3187 PJ->isSplittable()) {
3188 MaxEndOffset = std::max(MaxEndOffset, PJ->endOffset());
3192 // Back up MaxEndOffset and PJ if we ended the span early when
3193 // encountering an unsplittable partition.
3194 if (PJ != PE && PJ->beginOffset() < MaxEndOffset) {
3195 assert(!PJ->isSplittable());
3196 MaxEndOffset = PJ->beginOffset();
3200 // Check if we have managed to move the end offset forward yet. If so,
3201 // we'll have to rewrite uses and erase old split uses.
3202 if (BeginOffset < MaxEndOffset) {
3203 // Rewrite a sequence of overlapping partition uses.
3204 Changed |= rewritePartitions(AI, P, PI, PJ, BeginOffset,
3205 MaxEndOffset, SplitUses);
3207 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3210 // Accumulate all the splittable partitions from the [PI,PJ) region which
3211 // overlap going forward.
3212 for (AllocaPartitioning::iterator PII = PI, PIE = PJ; PII != PIE; ++PII)
3213 if (PII->isSplittable() && PII->endOffset() > MaxEndOffset) {
3214 SplitUses.push_back(PII);
3215 MaxSplitUseEndOffset = std::max(PII->endOffset(), MaxSplitUseEndOffset);
3218 // If we're already at the end and we have no split uses, we're done.
3219 if (PJ == PE && SplitUses.empty())
3222 // If we have no split uses or no gap in offsets, we're ready to move to
3223 // the next partitioning use.
3224 if (SplitUses.empty() || (PJ != PE && MaxEndOffset == PJ->beginOffset())) {
3225 BeginOffset = PJ->beginOffset();
3229 // Even if we have split uses, if the next partitioning use is splittable
3230 // and the split uses reach it, we can simply set up the beginning offset
3231 // to bridge between them.
3232 if (PJ != PE && PJ->isSplittable() && MaxSplitUseEndOffset > PJ->beginOffset()) {
3233 BeginOffset = MaxEndOffset;
3237 // Otherwise, we have a tail of split uses. Rewrite them with an empty
3238 // range of partitioning uses.
3239 uint64_t PostSplitEndOffset =
3240 PJ == PE ? MaxSplitUseEndOffset : PJ->beginOffset();
3242 Changed |= rewritePartitions(AI, P, PJ, PJ, MaxEndOffset,
3243 PostSplitEndOffset, SplitUses);
3245 break; // Skip the rest, we don't need to do any cleanup.
3247 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3248 PostSplitEndOffset);
3250 // Now just reset the begin offset for the next iteration.
3251 BeginOffset = PJ->beginOffset();
3257 /// \brief Analyze an alloca for SROA.
3259 /// This analyzes the alloca to ensure we can reason about it, builds
3260 /// a partitioning of the alloca, and then hands it off to be split and
3261 /// rewritten as needed.
3262 bool SROA::runOnAlloca(AllocaInst &AI) {
3263 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3264 ++NumAllocasAnalyzed;
3266 // Special case dead allocas, as they're trivial.
3267 if (AI.use_empty()) {
3268 AI.eraseFromParent();
3272 // Skip alloca forms that this analysis can't handle.
3273 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3274 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3277 bool Changed = false;
3279 // First, split any FCA loads and stores touching this alloca to promote
3280 // better splitting and promotion opportunities.
3281 AggLoadStoreRewriter AggRewriter(*TD);
3282 Changed |= AggRewriter.rewrite(AI);
3284 // Build the partition set using a recursive instruction-visiting builder.
3285 AllocaPartitioning P(*TD, AI);
3286 DEBUG(P.print(dbgs()));
3290 // Delete all the dead users of this alloca before splitting and rewriting it.
3291 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3292 DE = P.dead_user_end();
3295 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3296 DeadInsts.insert(*DI);
3298 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3299 DE = P.dead_op_end();
3302 // Clobber the use with an undef value.
3303 **DO = UndefValue::get(OldV->getType());
3304 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3305 if (isInstructionTriviallyDead(OldI)) {
3307 DeadInsts.insert(OldI);
3311 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3312 if (P.begin() == P.end())
3315 Changed |= splitAlloca(AI, P);
3317 DEBUG(dbgs() << " Speculating PHIs\n");
3318 while (!SpeculatablePHIs.empty())
3319 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3321 DEBUG(dbgs() << " Speculating Selects\n");
3322 while (!SpeculatableSelects.empty())
3323 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3328 /// \brief Delete the dead instructions accumulated in this run.
3330 /// Recursively deletes the dead instructions we've accumulated. This is done
3331 /// at the very end to maximize locality of the recursive delete and to
3332 /// minimize the problems of invalidated instruction pointers as such pointers
3333 /// are used heavily in the intermediate stages of the algorithm.
3335 /// We also record the alloca instructions deleted here so that they aren't
3336 /// subsequently handed to mem2reg to promote.
3337 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3338 while (!DeadInsts.empty()) {
3339 Instruction *I = DeadInsts.pop_back_val();
3340 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3342 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3344 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3345 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3346 // Zero out the operand and see if it becomes trivially dead.
3348 if (isInstructionTriviallyDead(U))
3349 DeadInsts.insert(U);
3352 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3353 DeletedAllocas.insert(AI);
3356 I->eraseFromParent();
3360 /// \brief Promote the allocas, using the best available technique.
3362 /// This attempts to promote whatever allocas have been identified as viable in
3363 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3364 /// If there is a domtree available, we attempt to promote using the full power
3365 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3366 /// based on the SSAUpdater utilities. This function returns whether any
3367 /// promotion occurred.
3368 bool SROA::promoteAllocas(Function &F) {
3369 if (PromotableAllocas.empty())
3372 NumPromoted += PromotableAllocas.size();
3374 if (DT && !ForceSSAUpdater) {
3375 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3376 PromoteMemToReg(PromotableAllocas, *DT);
3377 PromotableAllocas.clear();
3381 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3383 DIBuilder DIB(*F.getParent());
3384 SmallVector<Instruction*, 64> Insts;
3386 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3387 AllocaInst *AI = PromotableAllocas[Idx];
3388 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3390 Instruction *I = cast<Instruction>(*UI++);
3391 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3392 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3393 // leading to them) here. Eventually it should use them to optimize the
3394 // scalar values produced.
3395 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3396 assert(onlyUsedByLifetimeMarkers(I) &&
3397 "Found a bitcast used outside of a lifetime marker.");
3398 while (!I->use_empty())
3399 cast<Instruction>(*I->use_begin())->eraseFromParent();
3400 I->eraseFromParent();
3403 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3404 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3405 II->getIntrinsicID() == Intrinsic::lifetime_end);
3406 II->eraseFromParent();
3412 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3416 PromotableAllocas.clear();
3421 /// \brief A predicate to test whether an alloca belongs to a set.
3422 class IsAllocaInSet {
3423 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3427 typedef AllocaInst *argument_type;
3429 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3430 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
3434 bool SROA::runOnFunction(Function &F) {
3435 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3436 C = &F.getContext();
3437 TD = getAnalysisIfAvailable<DataLayout>();
3439 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3442 DT = getAnalysisIfAvailable<DominatorTree>();
3444 BasicBlock &EntryBB = F.getEntryBlock();
3445 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3447 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3448 Worklist.insert(AI);
3450 bool Changed = false;
3451 // A set of deleted alloca instruction pointers which should be removed from
3452 // the list of promotable allocas.
3453 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3456 while (!Worklist.empty()) {
3457 Changed |= runOnAlloca(*Worklist.pop_back_val());
3458 deleteDeadInstructions(DeletedAllocas);
3460 // Remove the deleted allocas from various lists so that we don't try to
3461 // continue processing them.
3462 if (!DeletedAllocas.empty()) {
3463 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3464 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3465 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3466 PromotableAllocas.end(),
3467 IsAllocaInSet(DeletedAllocas)),
3468 PromotableAllocas.end());
3469 DeletedAllocas.clear();
3473 Changed |= promoteAllocas(F);
3475 Worklist = PostPromotionWorklist;
3476 PostPromotionWorklist.clear();
3477 } while (!Worklist.empty());
3482 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3483 if (RequiresDomTree)
3484 AU.addRequired<DominatorTree>();
3485 AU.setPreservesCFG();