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/Constants.h"
29 #include "llvm/DIBuilder.h"
30 #include "llvm/DebugInfo.h"
31 #include "llvm/DerivedTypes.h"
32 #include "llvm/Function.h"
33 #include "llvm/GlobalVariable.h"
34 #include "llvm/IRBuilder.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/IntrinsicInst.h"
37 #include "llvm/LLVMContext.h"
38 #include "llvm/Module.h"
39 #include "llvm/Operator.h"
40 #include "llvm/Pass.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/TinyPtrVector.h"
46 #include "llvm/Analysis/Dominators.h"
47 #include "llvm/Analysis/Loads.h"
48 #include "llvm/Analysis/ValueTracking.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/ValueHandle.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetData.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
61 #include "llvm/Transforms/Utils/SSAUpdater.h"
64 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
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 Alloca partitioning representation.
79 /// This class represents a partitioning of an alloca into slices, and
80 /// information about the nature of uses of each slice of the alloca. The goal
81 /// is that this information is sufficient to decide if and how to split the
82 /// alloca apart and replace slices with scalars. It is also intended that this
83 /// structure can capture the relevant information needed both to decide about
84 /// and to enact these transformations.
85 class AllocaPartitioning {
87 /// \brief A common base class for representing a half-open byte range.
89 /// \brief The beginning offset of the range.
92 /// \brief The ending offset, not included in the range.
95 ByteRange() : BeginOffset(), EndOffset() {}
96 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
97 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
99 /// \brief Support for ordering ranges.
101 /// This provides an ordering over ranges such that start offsets are
102 /// always increasing, and within equal start offsets, the end offsets are
103 /// decreasing. Thus the spanning range comes first in a cluster with the
104 /// same start position.
105 bool operator<(const ByteRange &RHS) const {
106 if (BeginOffset < RHS.BeginOffset) return true;
107 if (BeginOffset > RHS.BeginOffset) return false;
108 if (EndOffset > RHS.EndOffset) return true;
112 /// \brief Support comparison with a single offset to allow binary searches.
113 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
114 return LHS.BeginOffset < RHSOffset;
117 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
118 const ByteRange &RHS) {
119 return LHSOffset < RHS.BeginOffset;
122 bool operator==(const ByteRange &RHS) const {
123 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
125 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
128 /// \brief A partition of an alloca.
130 /// This structure represents a contiguous partition of the alloca. These are
131 /// formed by examining the uses of the alloca. During formation, they may
132 /// overlap but once an AllocaPartitioning is built, the Partitions within it
133 /// are all disjoint.
134 struct Partition : public ByteRange {
135 /// \brief Whether this partition is splittable into smaller partitions.
137 /// We flag partitions as splittable when they are formed entirely due to
138 /// accesses by trivially splittable operations such as memset and memcpy.
140 /// FIXME: At some point we should consider loads and stores of FCAs to be
141 /// splittable and eagerly split them into scalar values.
144 Partition() : ByteRange(), IsSplittable() {}
145 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
146 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
149 /// \brief A particular use of a partition of the alloca.
151 /// This structure is used to associate uses of a partition with it. They
152 /// mark the range of bytes which are referenced by a particular instruction,
153 /// and includes a handle to the user itself and the pointer value in use.
154 /// The bounds of these uses are determined by intersecting the bounds of the
155 /// memory use itself with a particular partition. As a consequence there is
156 /// intentionally overlap between various uses of the same partition.
157 struct PartitionUse : public ByteRange {
158 /// \brief The user of this range of the alloca.
159 AssertingVH<Instruction> User;
161 /// \brief The particular pointer value derived from this alloca in use.
162 AssertingVH<Instruction> Ptr;
164 PartitionUse() : ByteRange(), User(), Ptr() {}
165 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset,
166 Instruction *User, Instruction *Ptr)
167 : ByteRange(BeginOffset, EndOffset), User(User), Ptr(Ptr) {}
170 /// \brief Construct a partitioning of a particular alloca.
172 /// Construction does most of the work for partitioning the alloca. This
173 /// performs the necessary walks of users and builds a partitioning from it.
174 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
176 /// \brief Test whether a pointer to the allocation escapes our analysis.
178 /// If this is true, the partitioning is never fully built and should be
180 bool isEscaped() const { return PointerEscapingInstr; }
182 /// \brief Support for iterating over the partitions.
184 typedef SmallVectorImpl<Partition>::iterator iterator;
185 iterator begin() { return Partitions.begin(); }
186 iterator end() { return Partitions.end(); }
188 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
189 const_iterator begin() const { return Partitions.begin(); }
190 const_iterator end() const { return Partitions.end(); }
193 /// \brief Support for iterating over and manipulating a particular
194 /// partition's uses.
196 /// The iteration support provided for uses is more limited, but also
197 /// includes some manipulation routines to support rewriting the uses of
198 /// partitions during SROA.
200 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
201 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
202 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
203 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
204 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
205 void use_insert(unsigned Idx, use_iterator UI, const PartitionUse &U) {
206 Uses[Idx].insert(UI, U);
208 void use_insert(const_iterator I, use_iterator UI, const PartitionUse &U) {
209 Uses[I - begin()].insert(UI, U);
211 void use_erase(unsigned Idx, use_iterator UI) { Uses[Idx].erase(UI); }
212 void use_erase(const_iterator I, use_iterator UI) {
213 Uses[I - begin()].erase(UI);
216 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
217 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
218 const_use_iterator use_begin(const_iterator I) const {
219 return Uses[I - begin()].begin();
221 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
222 const_use_iterator use_end(const_iterator I) const {
223 return Uses[I - begin()].end();
227 /// \brief Allow iterating the dead users for this alloca.
229 /// These are instructions which will never actually use the alloca as they
230 /// are outside the allocated range. They are safe to replace with undef and
233 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
234 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
235 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
238 /// \brief Allow iterating the dead expressions referring to this alloca.
240 /// These are operands which have cannot actually be used to refer to the
241 /// alloca as they are outside its range and the user doesn't correct for
242 /// that. These mostly consist of PHI node inputs and the like which we just
243 /// need to replace with undef.
245 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
246 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
247 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
250 /// \brief MemTransferInst auxiliary data.
251 /// This struct provides some auxiliary data about memory transfer
252 /// intrinsics such as memcpy and memmove. These intrinsics can use two
253 /// different ranges within the same alloca, and provide other challenges to
254 /// correctly represent. We stash extra data to help us untangle this
255 /// after the partitioning is complete.
256 struct MemTransferOffsets {
257 uint64_t DestBegin, DestEnd;
258 uint64_t SourceBegin, SourceEnd;
261 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
262 return MemTransferInstData.lookup(&II);
265 /// \brief Map from a PHI or select operand back to a partition.
267 /// When manipulating PHI nodes or selects, they can use more than one
268 /// partition of an alloca. We store a special mapping to allow finding the
269 /// partition referenced by each of these operands, if any.
270 iterator findPartitionForPHIOrSelectOperand(Instruction &I, Value *Op) {
271 SmallDenseMap<std::pair<Instruction *, Value *>,
272 std::pair<unsigned, unsigned> >::const_iterator MapIt
273 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
274 if (MapIt == PHIOrSelectOpMap.end())
277 return begin() + MapIt->second.first;
280 /// \brief Map from a PHI or select operand back to the specific use of
283 /// Similar to mapping these operands back to the partitions, this maps
284 /// directly to the use structure of that partition.
285 use_iterator findPartitionUseForPHIOrSelectOperand(Instruction &I,
287 SmallDenseMap<std::pair<Instruction *, Value *>,
288 std::pair<unsigned, unsigned> >::const_iterator MapIt
289 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
290 assert(MapIt != PHIOrSelectOpMap.end());
291 return Uses[MapIt->second.first].begin() + MapIt->second.second;
294 /// \brief Compute a common type among the uses of a particular partition.
296 /// This routines walks all of the uses of a particular partition and tries
297 /// to find a common type between them. Untyped operations such as memset and
298 /// memcpy are ignored.
299 Type *getCommonType(iterator I) const;
301 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
302 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
303 void printUsers(raw_ostream &OS, const_iterator I,
304 StringRef Indent = " ") const;
305 void print(raw_ostream &OS) const;
306 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
307 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
311 template <typename DerivedT, typename RetT = void> class BuilderBase;
312 class PartitionBuilder;
313 friend class AllocaPartitioning::PartitionBuilder;
315 friend class AllocaPartitioning::UseBuilder;
318 /// \brief Handle to alloca instruction to simplify method interfaces.
322 /// \brief The instruction responsible for this alloca having no partitioning.
324 /// When an instruction (potentially) escapes the pointer to the alloca, we
325 /// store a pointer to that here and abort trying to partition the alloca.
326 /// This will be null if the alloca is partitioned successfully.
327 Instruction *PointerEscapingInstr;
329 /// \brief The partitions of the alloca.
331 /// We store a vector of the partitions over the alloca here. This vector is
332 /// sorted by increasing begin offset, and then by decreasing end offset. See
333 /// the Partition inner class for more details. Initially (during
334 /// construction) there are overlaps, but we form a disjoint sequence of
335 /// partitions while finishing construction and a fully constructed object is
336 /// expected to always have this as a disjoint space.
337 SmallVector<Partition, 8> Partitions;
339 /// \brief The uses of the partitions.
341 /// This is essentially a mapping from each partition to a list of uses of
342 /// that partition. The mapping is done with a Uses vector that has the exact
343 /// same number of entries as the partition vector. Each entry is itself
344 /// a vector of the uses.
345 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
347 /// \brief Instructions which will become dead if we rewrite the alloca.
349 /// Note that these are not separated by partition. This is because we expect
350 /// a partitioned alloca to be completely rewritten or not rewritten at all.
351 /// If rewritten, all these instructions can simply be removed and replaced
352 /// with undef as they come from outside of the allocated space.
353 SmallVector<Instruction *, 8> DeadUsers;
355 /// \brief Operands which will become dead if we rewrite the alloca.
357 /// These are operands that in their particular use can be replaced with
358 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
359 /// to PHI nodes and the like. They aren't entirely dead (there might be
360 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
361 /// want to swap this particular input for undef to simplify the use lists of
363 SmallVector<Use *, 8> DeadOperands;
365 /// \brief The underlying storage for auxiliary memcpy and memset info.
366 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
368 /// \brief A side datastructure used when building up the partitions and uses.
370 /// This mapping is only really used during the initial building of the
371 /// partitioning so that we can retain information about PHI and select nodes
373 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
375 /// \brief Auxiliary information for particular PHI or select operands.
376 SmallDenseMap<std::pair<Instruction *, Value *>,
377 std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
379 /// \brief A utility routine called from the constructor.
381 /// This does what it says on the tin. It is the key of the alloca partition
382 /// splitting and merging. After it is called we have the desired disjoint
383 /// collection of partitions.
384 void splitAndMergePartitions();
388 template <typename DerivedT, typename RetT>
389 class AllocaPartitioning::BuilderBase
390 : public InstVisitor<DerivedT, RetT> {
392 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
394 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
400 const TargetData &TD;
401 const uint64_t AllocSize;
402 AllocaPartitioning &P;
408 SmallVector<OffsetUse, 8> Queue;
410 // The active offset and use while visiting.
414 void enqueueUsers(Instruction &I, uint64_t UserOffset) {
415 SmallPtrSet<User *, 8> UserSet;
416 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
418 if (!UserSet.insert(*UI))
421 OffsetUse OU = { &UI.getUse(), UserOffset };
426 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, uint64_t &GEPOffset) {
428 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
430 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
436 // Handle a struct index, which adds its field offset to the pointer.
437 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
438 unsigned ElementIdx = OpC->getZExtValue();
439 const StructLayout *SL = TD.getStructLayout(STy);
440 GEPOffset += SL->getElementOffset(ElementIdx);
445 += OpC->getZExtValue() * TD.getTypeAllocSize(GTI.getIndexedType());
450 Value *foldSelectInst(SelectInst &SI) {
451 // If the condition being selected on is a constant or the same value is
452 // being selected between, fold the select. Yes this does (rarely) happen
454 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
455 return SI.getOperand(1+CI->isZero());
456 if (SI.getOperand(1) == SI.getOperand(2)) {
457 assert(*U == SI.getOperand(1));
458 return SI.getOperand(1);
464 /// \brief Builder for the alloca partitioning.
466 /// This class builds an alloca partitioning by recursively visiting the uses
467 /// of an alloca and splitting the partitions for each load and store at each
469 class AllocaPartitioning::PartitionBuilder
470 : public BuilderBase<PartitionBuilder, bool> {
471 friend class InstVisitor<PartitionBuilder, bool>;
473 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
476 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
477 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
479 /// \brief Run the builder over the allocation.
481 // Note that we have to re-evaluate size on each trip through the loop as
482 // the queue grows at the tail.
483 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
485 Offset = Queue[Idx].Offset;
486 if (!visit(cast<Instruction>(U->getUser())))
493 bool markAsEscaping(Instruction &I) {
494 P.PointerEscapingInstr = &I;
498 void insertUse(Instruction &I, uint64_t Offset, uint64_t Size,
499 bool IsSplittable = false) {
500 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
502 // Completely skip uses which start outside of the allocation.
503 if (BeginOffset >= AllocSize) {
504 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
505 << " which starts past the end of the " << AllocSize
507 << " alloca: " << P.AI << "\n"
508 << " use: " << I << "\n");
512 // Clamp the size to the allocation.
513 if (EndOffset > AllocSize) {
514 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
515 << " to remain within the " << AllocSize << " byte alloca:\n"
516 << " alloca: " << P.AI << "\n"
517 << " use: " << I << "\n");
518 EndOffset = AllocSize;
521 // See if we can just add a user onto the last slot currently occupied.
522 if (!P.Partitions.empty() &&
523 P.Partitions.back().BeginOffset == BeginOffset &&
524 P.Partitions.back().EndOffset == EndOffset) {
525 P.Partitions.back().IsSplittable &= IsSplittable;
529 Partition New(BeginOffset, EndOffset, IsSplittable);
530 P.Partitions.push_back(New);
533 bool handleLoadOrStore(Type *Ty, Instruction &I, uint64_t Offset) {
534 uint64_t Size = TD.getTypeStoreSize(Ty);
536 // If this memory access can be shown to *statically* extend outside the
537 // bounds of of the allocation, it's behavior is undefined, so simply
538 // ignore it. Note that this is more strict than the generic clamping
539 // behavior of insertUse. We also try to handle cases which might run the
541 // FIXME: We should instead consider the pointer to have escaped if this
542 // function is being instrumented for addressing bugs or race conditions.
543 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize) {
544 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
545 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
546 << " which extends past the end of the " << AllocSize
548 << " alloca: " << P.AI << "\n"
549 << " use: " << I << "\n");
553 insertUse(I, Offset, Size);
557 bool visitBitCastInst(BitCastInst &BC) {
558 enqueueUsers(BC, Offset);
562 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
564 if (!computeConstantGEPOffset(GEPI, GEPOffset))
565 return markAsEscaping(GEPI);
567 enqueueUsers(GEPI, GEPOffset);
571 bool visitLoadInst(LoadInst &LI) {
572 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
573 "All simple FCA loads should have been pre-split");
574 return handleLoadOrStore(LI.getType(), LI, Offset);
577 bool visitStoreInst(StoreInst &SI) {
578 Value *ValOp = SI.getValueOperand();
580 return markAsEscaping(SI);
582 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
583 "All simple FCA stores should have been pre-split");
584 return handleLoadOrStore(ValOp->getType(), SI, Offset);
588 bool visitMemSetInst(MemSetInst &II) {
589 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
590 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
591 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
592 insertUse(II, Offset, Size, Length);
596 bool visitMemTransferInst(MemTransferInst &II) {
597 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
598 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
600 // Zero-length mem transfer intrinsics can be ignored entirely.
603 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
605 // Only intrinsics with a constant length can be split.
606 Offsets.IsSplittable = Length;
608 if (*U != II.getRawDest()) {
609 assert(*U == II.getRawSource());
610 Offsets.SourceBegin = Offset;
611 Offsets.SourceEnd = Offset + Size;
613 Offsets.DestBegin = Offset;
614 Offsets.DestEnd = Offset + Size;
617 insertUse(II, Offset, Size, Offsets.IsSplittable);
618 unsigned NewIdx = P.Partitions.size() - 1;
620 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
621 bool Inserted = false;
622 llvm::tie(PMI, Inserted)
623 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
624 if (!Inserted && Offsets.IsSplittable) {
625 // We've found a memory transfer intrinsic which refers to the alloca as
626 // both a source and dest. We refuse to split these to simplify splitting
627 // logic. If possible, SROA will still split them into separate allocas
628 // and then re-analyze.
629 Offsets.IsSplittable = false;
630 P.Partitions[PMI->second].IsSplittable = false;
631 P.Partitions[NewIdx].IsSplittable = false;
637 // Disable SRoA for any intrinsics except for lifetime invariants.
638 // FIXME: What about debug instrinsics? This matches old behavior, but
639 // doesn't make sense.
640 bool visitIntrinsicInst(IntrinsicInst &II) {
641 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
642 II.getIntrinsicID() == Intrinsic::lifetime_end) {
643 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
644 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
645 insertUse(II, Offset, Size, true);
649 return markAsEscaping(II);
652 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
653 // We consider any PHI or select that results in a direct load or store of
654 // the same offset to be a viable use for partitioning purposes. These uses
655 // are considered unsplittable and the size is the maximum loaded or stored
657 SmallPtrSet<Instruction *, 4> Visited;
658 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
659 Visited.insert(Root);
660 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
662 Instruction *I, *UsedI;
663 llvm::tie(UsedI, I) = Uses.pop_back_val();
665 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
666 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
669 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
670 Value *Op = SI->getOperand(0);
673 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
677 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
678 if (!GEP->hasAllZeroIndices())
680 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
681 !isa<SelectInst>(I)) {
685 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
687 if (Visited.insert(cast<Instruction>(*UI)))
688 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
689 } while (!Uses.empty());
694 bool visitPHINode(PHINode &PN) {
695 // See if we already have computed info on this node.
696 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
698 PHIInfo.second = true;
699 insertUse(PN, Offset, PHIInfo.first);
703 // Check for an unsafe use of the PHI node.
704 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
705 return markAsEscaping(*EscapingI);
707 insertUse(PN, Offset, PHIInfo.first);
711 bool visitSelectInst(SelectInst &SI) {
712 if (Value *Result = foldSelectInst(SI)) {
714 // If the result of the constant fold will be the pointer, recurse
715 // through the select as if we had RAUW'ed it.
716 enqueueUsers(SI, Offset);
721 // See if we already have computed info on this node.
722 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
723 if (SelectInfo.first) {
724 SelectInfo.second = true;
725 insertUse(SI, Offset, SelectInfo.first);
729 // Check for an unsafe use of the PHI node.
730 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
731 return markAsEscaping(*EscapingI);
733 insertUse(SI, Offset, SelectInfo.first);
737 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
738 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
742 /// \brief Use adder for the alloca partitioning.
744 /// This class adds the uses of an alloca to all of the partitions which they
745 /// use. For splittable partitions, this can end up doing essentially a linear
746 /// walk of the partitions, but the number of steps remains bounded by the
747 /// total result instruction size:
748 /// - The number of partitions is a result of the number unsplittable
749 /// instructions using the alloca.
750 /// - The number of users of each partition is at worst the total number of
751 /// splittable instructions using the alloca.
752 /// Thus we will produce N * M instructions in the end, where N are the number
753 /// of unsplittable uses and M are the number of splittable. This visitor does
754 /// the exact same number of updates to the partitioning.
756 /// In the more common case, this visitor will leverage the fact that the
757 /// partition space is pre-sorted, and do a logarithmic search for the
758 /// partition needed, making the total visit a classical ((N + M) * log(N))
759 /// complexity operation.
760 class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
761 friend class InstVisitor<UseBuilder>;
763 /// \brief Set to de-duplicate dead instructions found in the use walk.
764 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
767 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
768 : BuilderBase<UseBuilder>(TD, AI, P) {}
770 /// \brief Run the builder over the allocation.
772 // Note that we have to re-evaluate size on each trip through the loop as
773 // the queue grows at the tail.
774 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
776 Offset = Queue[Idx].Offset;
777 this->visit(cast<Instruction>(U->getUser()));
782 void markAsDead(Instruction &I) {
783 if (VisitedDeadInsts.insert(&I))
784 P.DeadUsers.push_back(&I);
787 void insertUse(Instruction &User, uint64_t Offset, uint64_t Size) {
788 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
790 // If the use extends outside of the allocation, record it as a dead use
791 // for elimination later.
792 if (BeginOffset >= AllocSize || Size == 0)
793 return markAsDead(User);
795 // Bound the use by the size of the allocation.
796 if (EndOffset > AllocSize)
797 EndOffset = AllocSize;
799 // NB: This only works if we have zero overlapping partitions.
800 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
801 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
803 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
805 PartitionUse NewUse(std::max(I->BeginOffset, BeginOffset),
806 std::min(I->EndOffset, EndOffset),
807 &User, cast<Instruction>(*U));
808 P.Uses[I - P.begin()].push_back(NewUse);
809 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
810 P.PHIOrSelectOpMap[std::make_pair(&User, U->get())]
811 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
815 void handleLoadOrStore(Type *Ty, Instruction &I, uint64_t Offset) {
816 uint64_t Size = TD.getTypeStoreSize(Ty);
818 // If this memory access can be shown to *statically* extend outside the
819 // bounds of of the allocation, it's behavior is undefined, so simply
820 // ignore it. Note that this is more strict than the generic clamping
821 // behavior of insertUse.
822 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize)
823 return markAsDead(I);
825 insertUse(I, Offset, Size);
828 void visitBitCastInst(BitCastInst &BC) {
830 return markAsDead(BC);
832 enqueueUsers(BC, Offset);
835 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
836 if (GEPI.use_empty())
837 return markAsDead(GEPI);
840 if (!computeConstantGEPOffset(GEPI, GEPOffset))
841 llvm_unreachable("Unable to compute constant offset for use");
843 enqueueUsers(GEPI, GEPOffset);
846 void visitLoadInst(LoadInst &LI) {
847 handleLoadOrStore(LI.getType(), LI, Offset);
850 void visitStoreInst(StoreInst &SI) {
851 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
854 void visitMemSetInst(MemSetInst &II) {
855 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
856 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
857 insertUse(II, Offset, Size);
860 void visitMemTransferInst(MemTransferInst &II) {
861 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
862 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
863 insertUse(II, Offset, Size);
866 void visitIntrinsicInst(IntrinsicInst &II) {
867 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
868 II.getIntrinsicID() == Intrinsic::lifetime_end);
870 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
871 insertUse(II, Offset,
872 std::min(AllocSize - Offset, Length->getLimitedValue()));
875 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
876 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
878 // For PHI and select operands outside the alloca, we can't nuke the entire
879 // phi or select -- the other side might still be relevant, so we special
880 // case them here and use a separate structure to track the operands
881 // themselves which should be replaced with undef.
882 if (Offset >= AllocSize) {
883 P.DeadOperands.push_back(U);
887 insertUse(User, Offset, Size);
889 void visitPHINode(PHINode &PN) {
891 return markAsDead(PN);
893 insertPHIOrSelect(PN, Offset);
895 void visitSelectInst(SelectInst &SI) {
897 return markAsDead(SI);
899 if (Value *Result = foldSelectInst(SI)) {
901 // If the result of the constant fold will be the pointer, recurse
902 // through the select as if we had RAUW'ed it.
903 enqueueUsers(SI, Offset);
908 insertPHIOrSelect(SI, Offset);
911 /// \brief Unreachable, we've already visited the alloca once.
912 void visitInstruction(Instruction &I) {
913 llvm_unreachable("Unhandled instruction in use builder.");
917 void AllocaPartitioning::splitAndMergePartitions() {
918 size_t NumDeadPartitions = 0;
920 // Track the range of splittable partitions that we pass when accumulating
921 // overlapping unsplittable partitions.
922 uint64_t SplitEndOffset = 0ull;
924 Partition New(0ull, 0ull, false);
926 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
929 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
930 assert(New.BeginOffset == New.EndOffset);
933 assert(New.IsSplittable);
934 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
936 assert(New.BeginOffset != New.EndOffset);
938 // Scan the overlapping partitions.
939 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
940 // If the new partition we are forming is splittable, stop at the first
941 // unsplittable partition.
942 if (New.IsSplittable && !Partitions[j].IsSplittable)
945 // Grow the new partition to include any equally splittable range. 'j' is
946 // always equally splittable when New is splittable, but when New is not
947 // splittable, we may subsume some (or part of some) splitable partition
948 // without growing the new one.
949 if (New.IsSplittable == Partitions[j].IsSplittable) {
950 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
952 assert(!New.IsSplittable);
953 assert(Partitions[j].IsSplittable);
954 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
957 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
962 // If the new partition is splittable, chop off the end as soon as the
963 // unsplittable subsequent partition starts and ensure we eventually cover
964 // the splittable area.
965 if (j != e && New.IsSplittable) {
966 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
967 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
970 // Add the new partition if it differs from the original one and is
971 // non-empty. We can end up with an empty partition here if it was
972 // splittable but there is an unsplittable one that starts at the same
974 if (New != Partitions[i]) {
975 if (New.BeginOffset != New.EndOffset)
976 Partitions.push_back(New);
977 // Mark the old one for removal.
978 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
982 New.BeginOffset = New.EndOffset;
983 if (!New.IsSplittable) {
984 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
985 if (j != e && !Partitions[j].IsSplittable)
986 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
987 New.IsSplittable = true;
988 // If there is a trailing splittable partition which won't be fused into
989 // the next splittable partition go ahead and add it onto the partitions
991 if (New.BeginOffset < New.EndOffset &&
992 (j == e || !Partitions[j].IsSplittable ||
993 New.EndOffset < Partitions[j].BeginOffset)) {
994 Partitions.push_back(New);
995 New.BeginOffset = New.EndOffset = 0ull;
1000 // Re-sort the partitions now that they have been split and merged into
1001 // disjoint set of partitions. Also remove any of the dead partitions we've
1002 // replaced in the process.
1003 std::sort(Partitions.begin(), Partitions.end());
1004 if (NumDeadPartitions) {
1005 assert(Partitions.back().BeginOffset == UINT64_MAX);
1006 assert(Partitions.back().EndOffset == UINT64_MAX);
1007 assert((ptrdiff_t)NumDeadPartitions ==
1008 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1010 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1013 AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
1018 PointerEscapingInstr(0) {
1019 PartitionBuilder PB(TD, AI, *this);
1023 if (Partitions.size() > 1) {
1024 // Sort the uses. This arranges for the offsets to be in ascending order,
1025 // and the sizes to be in descending order.
1026 std::sort(Partitions.begin(), Partitions.end());
1028 // Intersect splittability for all partitions with equal offsets and sizes.
1029 // Then remove all but the first so that we have a sequence of non-equal but
1030 // potentially overlapping partitions.
1031 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1034 while (J != E && *I == *J) {
1035 I->IsSplittable &= J->IsSplittable;
1039 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1042 // Split splittable and merge unsplittable partitions into a disjoint set
1043 // of partitions over the used space of the allocation.
1044 splitAndMergePartitions();
1047 // Now build up the user lists for each of these disjoint partitions by
1048 // re-walking the recursive users of the alloca.
1049 Uses.resize(Partitions.size());
1050 UseBuilder UB(TD, AI, *this);
1052 for (iterator I = Partitions.begin(), E = Partitions.end(); I != E; ++I)
1053 std::stable_sort(use_begin(I), use_end(I));
1056 Type *AllocaPartitioning::getCommonType(iterator I) const {
1058 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1059 if (isa<IntrinsicInst>(*UI->User))
1061 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1065 if (LoadInst *LI = dyn_cast<LoadInst>(&*UI->User)) {
1066 UserTy = LI->getType();
1067 } else if (StoreInst *SI = dyn_cast<StoreInst>(&*UI->User)) {
1068 UserTy = SI->getValueOperand()->getType();
1069 } else if (SelectInst *SI = dyn_cast<SelectInst>(&*UI->User)) {
1070 if (PointerType *PtrTy = dyn_cast<PointerType>(SI->getType()))
1071 UserTy = PtrTy->getElementType();
1072 } else if (PHINode *PN = dyn_cast<PHINode>(&*UI->User)) {
1073 if (PointerType *PtrTy = dyn_cast<PointerType>(PN->getType()))
1074 UserTy = PtrTy->getElementType();
1077 if (Ty && Ty != UserTy)
1085 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1087 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1088 StringRef Indent) const {
1089 OS << Indent << "partition #" << (I - begin())
1090 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1091 << (I->IsSplittable ? " (splittable)" : "")
1092 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1096 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1097 StringRef Indent) const {
1098 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1100 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1101 << "used by: " << *UI->User << "\n";
1102 if (MemTransferInst *II = dyn_cast<MemTransferInst>(&*UI->User)) {
1103 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1105 if (!MTO.IsSplittable)
1106 IsDest = UI->BeginOffset == MTO.DestBegin;
1108 IsDest = MTO.DestBegin != 0u;
1109 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1110 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1111 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1116 void AllocaPartitioning::print(raw_ostream &OS) const {
1117 if (PointerEscapingInstr) {
1118 OS << "No partitioning for alloca: " << AI << "\n"
1119 << " A pointer to this alloca escaped by:\n"
1120 << " " << *PointerEscapingInstr << "\n";
1124 OS << "Partitioning of alloca: " << AI << "\n";
1126 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1132 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1133 void AllocaPartitioning::dump() const { print(dbgs()); }
1135 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1139 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1141 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1142 /// the loads and stores of an alloca instruction, as well as updating its
1143 /// debug information. This is used when a domtree is unavailable and thus
1144 /// mem2reg in its full form can't be used to handle promotion of allocas to
1146 class AllocaPromoter : public LoadAndStorePromoter {
1150 SmallVector<DbgDeclareInst *, 4> DDIs;
1151 SmallVector<DbgValueInst *, 4> DVIs;
1154 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1155 AllocaInst &AI, DIBuilder &DIB)
1156 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1158 void run(const SmallVectorImpl<Instruction*> &Insts) {
1159 // Remember which alloca we're promoting (for isInstInList).
1160 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1161 for (Value::use_iterator UI = DebugNode->use_begin(),
1162 UE = DebugNode->use_end();
1164 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1165 DDIs.push_back(DDI);
1166 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1167 DVIs.push_back(DVI);
1170 LoadAndStorePromoter::run(Insts);
1171 AI.eraseFromParent();
1172 while (!DDIs.empty())
1173 DDIs.pop_back_val()->eraseFromParent();
1174 while (!DVIs.empty())
1175 DVIs.pop_back_val()->eraseFromParent();
1178 virtual bool isInstInList(Instruction *I,
1179 const SmallVectorImpl<Instruction*> &Insts) const {
1180 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1181 return LI->getOperand(0) == &AI;
1182 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1185 virtual void updateDebugInfo(Instruction *Inst) const {
1186 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1187 E = DDIs.end(); I != E; ++I) {
1188 DbgDeclareInst *DDI = *I;
1189 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1190 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1191 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1192 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1194 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1195 E = DVIs.end(); I != E; ++I) {
1196 DbgValueInst *DVI = *I;
1198 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1199 // If an argument is zero extended then use argument directly. The ZExt
1200 // may be zapped by an optimization pass in future.
1201 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1202 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1203 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1204 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1206 Arg = SI->getOperand(0);
1207 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1208 Arg = LI->getOperand(0);
1212 Instruction *DbgVal =
1213 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1215 DbgVal->setDebugLoc(DVI->getDebugLoc());
1219 } // end anon namespace
1223 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1225 /// This pass takes allocations which can be completely analyzed (that is, they
1226 /// don't escape) and tries to turn them into scalar SSA values. There are
1227 /// a few steps to this process.
1229 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1230 /// are used to try to split them into smaller allocations, ideally of
1231 /// a single scalar data type. It will split up memcpy and memset accesses
1232 /// as necessary and try to isolate invidual scalar accesses.
1233 /// 2) It will transform accesses into forms which are suitable for SSA value
1234 /// promotion. This can be replacing a memset with a scalar store of an
1235 /// integer value, or it can involve speculating operations on a PHI or
1236 /// select to be a PHI or select of the results.
1237 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1238 /// onto insert and extract operations on a vector value, and convert them to
1239 /// this form. By doing so, it will enable promotion of vector aggregates to
1240 /// SSA vector values.
1241 class SROA : public FunctionPass {
1242 const bool RequiresDomTree;
1245 const TargetData *TD;
1248 /// \brief Worklist of alloca instructions to simplify.
1250 /// Each alloca in the function is added to this. Each new alloca formed gets
1251 /// added to it as well to recursively simplify unless that alloca can be
1252 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1253 /// the one being actively rewritten, we add it back onto the list if not
1254 /// already present to ensure it is re-visited.
1255 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1257 /// \brief A collection of instructions to delete.
1258 /// We try to batch deletions to simplify code and make things a bit more
1260 SmallVector<Instruction *, 8> DeadInsts;
1262 /// \brief A set to prevent repeatedly marking an instruction split into many
1263 /// uses as dead. Only used to guard insertion into DeadInsts.
1264 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1266 /// \brief A collection of alloca instructions we can directly promote.
1267 std::vector<AllocaInst *> PromotableAllocas;
1270 SROA(bool RequiresDomTree = true)
1271 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1272 C(0), TD(0), DT(0) {
1273 initializeSROAPass(*PassRegistry::getPassRegistry());
1275 bool runOnFunction(Function &F);
1276 void getAnalysisUsage(AnalysisUsage &AU) const;
1278 const char *getPassName() const { return "SROA"; }
1282 friend class AllocaPartitionRewriter;
1283 friend class AllocaPartitionVectorRewriter;
1285 bool rewriteAllocaPartition(AllocaInst &AI,
1286 AllocaPartitioning &P,
1287 AllocaPartitioning::iterator PI);
1288 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1289 bool runOnAlloca(AllocaInst &AI);
1290 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
1291 bool promoteAllocas(Function &F);
1297 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1298 return new SROA(RequiresDomTree);
1301 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1303 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1304 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1307 /// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1309 /// If the provided GEP is all-constant, the total byte offset formed by the
1310 /// GEP is computed and Offset is set to it. If the GEP has any non-constant
1311 /// operands, the function returns false and the value of Offset is unmodified.
1312 static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1314 APInt GEPOffset(Offset.getBitWidth(), 0);
1315 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1316 GTI != GTE; ++GTI) {
1317 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1320 if (OpC->isZero()) continue;
1322 // Handle a struct index, which adds its field offset to the pointer.
1323 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1324 unsigned ElementIdx = OpC->getZExtValue();
1325 const StructLayout *SL = TD.getStructLayout(STy);
1326 GEPOffset += APInt(Offset.getBitWidth(),
1327 SL->getElementOffset(ElementIdx));
1331 APInt TypeSize(Offset.getBitWidth(),
1332 TD.getTypeAllocSize(GTI.getIndexedType()));
1333 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1334 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1335 "vector element size is not a multiple of 8, cannot GEP over it");
1336 TypeSize = VTy->getScalarSizeInBits() / 8;
1339 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1345 /// \brief Build a GEP out of a base pointer and indices.
1347 /// This will return the BasePtr if that is valid, or build a new GEP
1348 /// instruction using the IRBuilder if GEP-ing is needed.
1349 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1350 SmallVectorImpl<Value *> &Indices,
1351 const Twine &Prefix) {
1352 if (Indices.empty())
1355 // A single zero index is a no-op, so check for this and avoid building a GEP
1357 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1360 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1363 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1364 /// TargetTy without changing the offset of the pointer.
1366 /// This routine assumes we've already established a properly offset GEP with
1367 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1368 /// zero-indices down through type layers until we find one the same as
1369 /// TargetTy. If we can't find one with the same type, we at least try to use
1370 /// one with the same size. If none of that works, we just produce the GEP as
1371 /// indicated by Indices to have the correct offset.
1372 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1373 Value *BasePtr, Type *Ty, Type *TargetTy,
1374 SmallVectorImpl<Value *> &Indices,
1375 const Twine &Prefix) {
1377 return buildGEP(IRB, BasePtr, Indices, Prefix);
1379 // See if we can descend into a struct and locate a field with the correct
1381 unsigned NumLayers = 0;
1382 Type *ElementTy = Ty;
1384 if (ElementTy->isPointerTy())
1386 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1387 ElementTy = SeqTy->getElementType();
1388 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1389 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1390 ElementTy = *STy->element_begin();
1391 Indices.push_back(IRB.getInt32(0));
1396 } while (ElementTy != TargetTy);
1397 if (ElementTy != TargetTy)
1398 Indices.erase(Indices.end() - NumLayers, Indices.end());
1400 return buildGEP(IRB, BasePtr, Indices, Prefix);
1403 /// \brief Recursively compute indices for a natural GEP.
1405 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1406 /// element types adding appropriate indices for the GEP.
1407 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1408 Value *Ptr, Type *Ty, APInt &Offset,
1410 SmallVectorImpl<Value *> &Indices,
1411 const Twine &Prefix) {
1413 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1415 // We can't recurse through pointer types.
1416 if (Ty->isPointerTy())
1419 // We try to analyze GEPs over vectors here, but note that these GEPs are
1420 // extremely poorly defined currently. The long-term goal is to remove GEPing
1421 // over a vector from the IR completely.
1422 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1423 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1424 if (ElementSizeInBits % 8)
1425 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1426 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1427 APInt NumSkippedElements = Offset.udiv(ElementSize);
1428 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1430 Offset -= NumSkippedElements * ElementSize;
1431 Indices.push_back(IRB.getInt(NumSkippedElements));
1432 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1433 Offset, TargetTy, Indices, Prefix);
1436 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1437 Type *ElementTy = ArrTy->getElementType();
1438 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1439 APInt NumSkippedElements = Offset.udiv(ElementSize);
1440 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1443 Offset -= NumSkippedElements * ElementSize;
1444 Indices.push_back(IRB.getInt(NumSkippedElements));
1445 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1449 StructType *STy = dyn_cast<StructType>(Ty);
1453 const StructLayout *SL = TD.getStructLayout(STy);
1454 uint64_t StructOffset = Offset.getZExtValue();
1455 if (StructOffset >= SL->getSizeInBytes())
1457 unsigned Index = SL->getElementContainingOffset(StructOffset);
1458 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1459 Type *ElementTy = STy->getElementType(Index);
1460 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1461 return 0; // The offset points into alignment padding.
1463 Indices.push_back(IRB.getInt32(Index));
1464 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1468 /// \brief Get a natural GEP from a base pointer to a particular offset and
1469 /// resulting in a particular type.
1471 /// The goal is to produce a "natural" looking GEP that works with the existing
1472 /// composite types to arrive at the appropriate offset and element type for
1473 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1474 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1475 /// Indices, and setting Ty to the result subtype.
1477 /// If no natural GEP can be constructed, this function returns null.
1478 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1479 Value *Ptr, APInt Offset, Type *TargetTy,
1480 SmallVectorImpl<Value *> &Indices,
1481 const Twine &Prefix) {
1482 PointerType *Ty = cast<PointerType>(Ptr->getType());
1484 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1486 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1489 Type *ElementTy = Ty->getElementType();
1490 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1491 if (ElementSize == 0)
1492 return 0; // Zero-length arrays can't help us build a natural GEP.
1493 APInt NumSkippedElements = Offset.udiv(ElementSize);
1495 Offset -= NumSkippedElements * ElementSize;
1496 Indices.push_back(IRB.getInt(NumSkippedElements));
1497 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1501 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1502 /// resulting pointer has PointerTy.
1504 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1505 /// and produces the pointer type desired. Where it cannot, it will try to use
1506 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1507 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1508 /// bitcast to the type.
1510 /// The strategy for finding the more natural GEPs is to peel off layers of the
1511 /// pointer, walking back through bit casts and GEPs, searching for a base
1512 /// pointer from which we can compute a natural GEP with the desired
1513 /// properities. The algorithm tries to fold as many constant indices into
1514 /// a single GEP as possible, thus making each GEP more independent of the
1515 /// surrounding code.
1516 static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1517 Value *Ptr, APInt Offset, Type *PointerTy,
1518 const Twine &Prefix) {
1519 // Even though we don't look through PHI nodes, we could be called on an
1520 // instruction in an unreachable block, which may be on a cycle.
1521 SmallPtrSet<Value *, 4> Visited;
1522 Visited.insert(Ptr);
1523 SmallVector<Value *, 4> Indices;
1525 // We may end up computing an offset pointer that has the wrong type. If we
1526 // never are able to compute one directly that has the correct type, we'll
1527 // fall back to it, so keep it around here.
1528 Value *OffsetPtr = 0;
1530 // Remember any i8 pointer we come across to re-use if we need to do a raw
1533 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1535 Type *TargetTy = PointerTy->getPointerElementType();
1538 // First fold any existing GEPs into the offset.
1539 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1540 APInt GEPOffset(Offset.getBitWidth(), 0);
1541 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1543 Offset += GEPOffset;
1544 Ptr = GEP->getPointerOperand();
1545 if (!Visited.insert(Ptr))
1549 // See if we can perform a natural GEP here.
1551 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1553 if (P->getType() == PointerTy) {
1554 // Zap any offset pointer that we ended up computing in previous rounds.
1555 if (OffsetPtr && OffsetPtr->use_empty())
1556 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1557 I->eraseFromParent();
1565 // Stash this pointer if we've found an i8*.
1566 if (Ptr->getType()->isIntegerTy(8)) {
1568 Int8PtrOffset = Offset;
1571 // Peel off a layer of the pointer and update the offset appropriately.
1572 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1573 Ptr = cast<Operator>(Ptr)->getOperand(0);
1574 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1575 if (GA->mayBeOverridden())
1577 Ptr = GA->getAliasee();
1581 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1582 } while (Visited.insert(Ptr));
1586 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1587 Prefix + ".raw_cast");
1588 Int8PtrOffset = Offset;
1591 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1592 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1593 Prefix + ".raw_idx");
1597 // On the off chance we were targeting i8*, guard the bitcast here.
1598 if (Ptr->getType() != PointerTy)
1599 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1604 /// \brief Test whether the given alloca partition can be promoted to a vector.
1606 /// This is a quick test to check whether we can rewrite a particular alloca
1607 /// partition (and its newly formed alloca) into a vector alloca with only
1608 /// whole-vector loads and stores such that it could be promoted to a vector
1609 /// SSA value. We only can ensure this for a limited set of operations, and we
1610 /// don't want to do the rewrites unless we are confident that the result will
1611 /// be promotable, so we have an early test here.
1612 static bool isVectorPromotionViable(const TargetData &TD,
1614 AllocaPartitioning &P,
1615 uint64_t PartitionBeginOffset,
1616 uint64_t PartitionEndOffset,
1617 AllocaPartitioning::const_use_iterator I,
1618 AllocaPartitioning::const_use_iterator E) {
1619 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1623 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1624 uint64_t ElementSize = Ty->getScalarSizeInBits();
1626 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1627 // that aren't byte sized.
1628 if (ElementSize % 8)
1630 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1634 for (; I != E; ++I) {
1635 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1636 uint64_t BeginIndex = BeginOffset / ElementSize;
1637 if (BeginIndex * ElementSize != BeginOffset ||
1638 BeginIndex >= Ty->getNumElements())
1640 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1641 uint64_t EndIndex = EndOffset / ElementSize;
1642 if (EndIndex * ElementSize != EndOffset ||
1643 EndIndex > Ty->getNumElements())
1646 // FIXME: We should build shuffle vector instructions to handle
1647 // non-element-sized accesses.
1648 if ((EndOffset - BeginOffset) != ElementSize &&
1649 (EndOffset - BeginOffset) != VecSize)
1652 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&*I->User)) {
1653 if (MI->isVolatile())
1655 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(&*I->User)) {
1656 const AllocaPartitioning::MemTransferOffsets &MTO
1657 = P.getMemTransferOffsets(*MTI);
1658 if (!MTO.IsSplittable)
1661 } else if (I->Ptr->getType()->getPointerElementType()->isStructTy()) {
1662 // Disable vector promotion when there are loads or stores of an FCA.
1664 } else if (!isa<LoadInst>(*I->User) && !isa<StoreInst>(*I->User)) {
1672 /// \brief Visitor to rewrite instructions using a partition of an alloca to
1673 /// use a new alloca.
1675 /// Also implements the rewriting to vector-based accesses when the partition
1676 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1678 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
1680 // Befriend the base class so it can delegate to private visit methods.
1681 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
1683 const TargetData &TD;
1684 AllocaPartitioning &P;
1686 AllocaInst &OldAI, &NewAI;
1687 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1689 // If we are rewriting an alloca partition which can be written as pure
1690 // vector operations, we stash extra information here. When VecTy is
1691 // non-null, we have some strict guarantees about the rewriten alloca:
1692 // - The new alloca is exactly the size of the vector type here.
1693 // - The accesses all either map to the entire vector or to a single
1695 // - The set of accessing instructions is only one of those handled above
1696 // in isVectorPromotionViable. Generally these are the same access kinds
1697 // which are promotable via mem2reg.
1700 uint64_t ElementSize;
1702 // The offset of the partition user currently being rewritten.
1703 uint64_t BeginOffset, EndOffset;
1704 Instruction *OldPtr;
1706 // The name prefix to use when rewriting instructions for this alloca.
1707 std::string NamePrefix;
1710 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
1711 AllocaPartitioning::iterator PI,
1712 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
1713 uint64_t NewBeginOffset, uint64_t NewEndOffset)
1714 : TD(TD), P(P), Pass(Pass),
1715 OldAI(OldAI), NewAI(NewAI),
1716 NewAllocaBeginOffset(NewBeginOffset),
1717 NewAllocaEndOffset(NewEndOffset),
1718 VecTy(), ElementTy(), ElementSize(),
1719 BeginOffset(), EndOffset() {
1722 /// \brief Visit the users of the alloca partition and rewrite them.
1723 bool visitUsers(AllocaPartitioning::const_use_iterator I,
1724 AllocaPartitioning::const_use_iterator E) {
1725 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
1726 NewAllocaBeginOffset, NewAllocaEndOffset,
1729 VecTy = cast<VectorType>(NewAI.getAllocatedType());
1730 ElementTy = VecTy->getElementType();
1731 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
1732 "Only multiple-of-8 sized vector elements are viable");
1733 ElementSize = VecTy->getScalarSizeInBits() / 8;
1735 bool CanSROA = true;
1736 for (; I != E; ++I) {
1737 BeginOffset = I->BeginOffset;
1738 EndOffset = I->EndOffset;
1740 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
1741 CanSROA &= visit(I->User);
1753 // Every instruction which can end up as a user must have a rewrite rule.
1754 bool visitInstruction(Instruction &I) {
1755 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1756 llvm_unreachable("No rewrite rule for this instruction!");
1759 Twine getName(const Twine &Suffix) {
1760 return NamePrefix + Suffix;
1763 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
1764 assert(BeginOffset >= NewAllocaBeginOffset);
1765 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
1766 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
1769 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
1770 assert(VecTy && "Can only call getIndex when rewriting a vector");
1771 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1772 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1773 uint32_t Index = RelOffset / ElementSize;
1774 assert(Index * ElementSize == RelOffset);
1775 return IRB.getInt32(Index);
1778 void deleteIfTriviallyDead(Value *V) {
1779 Instruction *I = cast<Instruction>(V);
1780 if (isInstructionTriviallyDead(I))
1781 Pass.DeadInsts.push_back(I);
1784 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
1785 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1786 return IRB.CreateIntToPtr(V, Ty);
1787 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1788 return IRB.CreatePtrToInt(V, Ty);
1790 return IRB.CreateBitCast(V, Ty);
1793 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
1795 if (LI.getType() == VecTy->getElementType() ||
1796 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1798 = IRB.CreateExtractElement(IRB.CreateLoad(&NewAI, getName(".load")),
1799 getIndex(IRB, BeginOffset),
1800 getName(".extract"));
1802 Result = IRB.CreateLoad(&NewAI, getName(".load"));
1804 if (Result->getType() != LI.getType())
1805 Result = getValueCast(IRB, Result, LI.getType());
1806 LI.replaceAllUsesWith(Result);
1807 Pass.DeadInsts.push_back(&LI);
1809 DEBUG(dbgs() << " to: " << *Result << "\n");
1813 bool visitLoadInst(LoadInst &LI) {
1814 DEBUG(dbgs() << " original: " << LI << "\n");
1815 Value *OldOp = LI.getOperand(0);
1816 assert(OldOp == OldPtr);
1817 IRBuilder<> IRB(&LI);
1820 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
1822 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1823 LI.getPointerOperand()->getType());
1824 LI.setOperand(0, NewPtr);
1825 DEBUG(dbgs() << " to: " << LI << "\n");
1827 deleteIfTriviallyDead(OldOp);
1828 return NewPtr == &NewAI && !LI.isVolatile();
1831 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
1833 Value *V = SI.getValueOperand();
1834 if (V->getType() == ElementTy ||
1835 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1836 if (V->getType() != ElementTy)
1837 V = getValueCast(IRB, V, ElementTy);
1838 V = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1839 getIndex(IRB, BeginOffset),
1840 getName(".insert"));
1841 } else if (V->getType() != VecTy) {
1842 V = getValueCast(IRB, V, VecTy);
1844 StoreInst *Store = IRB.CreateStore(V, &NewAI);
1845 Pass.DeadInsts.push_back(&SI);
1848 DEBUG(dbgs() << " to: " << *Store << "\n");
1852 bool visitStoreInst(StoreInst &SI) {
1853 DEBUG(dbgs() << " original: " << SI << "\n");
1854 Value *OldOp = SI.getOperand(1);
1855 assert(OldOp == OldPtr);
1856 IRBuilder<> IRB(&SI);
1859 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
1861 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1862 SI.getPointerOperand()->getType());
1863 SI.setOperand(1, NewPtr);
1864 DEBUG(dbgs() << " to: " << SI << "\n");
1866 deleteIfTriviallyDead(OldOp);
1867 return NewPtr == &NewAI && !SI.isVolatile();
1870 bool visitMemSetInst(MemSetInst &II) {
1871 DEBUG(dbgs() << " original: " << II << "\n");
1872 IRBuilder<> IRB(&II);
1873 assert(II.getRawDest() == OldPtr);
1875 // If the memset has a variable size, it cannot be split, just adjust the
1876 // pointer to the new alloca.
1877 if (!isa<Constant>(II.getLength())) {
1878 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1879 deleteIfTriviallyDead(OldPtr);
1883 // Record this instruction for deletion.
1884 if (Pass.DeadSplitInsts.insert(&II))
1885 Pass.DeadInsts.push_back(&II);
1887 Type *AllocaTy = NewAI.getAllocatedType();
1888 Type *ScalarTy = AllocaTy->getScalarType();
1890 // If this doesn't map cleanly onto the alloca type, and that type isn't
1891 // a single value type, just emit a memset.
1892 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
1893 EndOffset != NewAllocaEndOffset ||
1894 !AllocaTy->isSingleValueType() ||
1895 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
1896 Type *SizeTy = II.getLength()->getType();
1897 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
1900 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
1901 II.getRawDest()->getType()),
1902 II.getValue(), Size, II.getAlignment(),
1905 DEBUG(dbgs() << " to: " << *New << "\n");
1909 // If we can represent this as a simple value, we have to build the actual
1910 // value to store, which requires expanding the byte present in memset to
1911 // a sensible representation for the alloca type. This is essentially
1912 // splatting the byte to a sufficiently wide integer, bitcasting to the
1913 // desired scalar type, and splatting it across any desired vector type.
1914 Value *V = II.getValue();
1915 IntegerType *VTy = cast<IntegerType>(V->getType());
1916 Type *IntTy = Type::getIntNTy(VTy->getContext(),
1917 TD.getTypeSizeInBits(ScalarTy));
1918 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
1919 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
1920 ConstantExpr::getUDiv(
1921 Constant::getAllOnesValue(IntTy),
1922 ConstantExpr::getZExt(
1923 Constant::getAllOnesValue(V->getType()),
1925 getName(".isplat"));
1926 if (V->getType() != ScalarTy) {
1927 if (ScalarTy->isPointerTy())
1928 V = IRB.CreateIntToPtr(V, ScalarTy);
1929 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
1930 V = IRB.CreateBitCast(V, ScalarTy);
1931 else if (ScalarTy->isIntegerTy())
1932 llvm_unreachable("Computed different integer types with equal widths");
1934 llvm_unreachable("Invalid scalar type");
1937 // If this is an element-wide memset of a vectorizable alloca, insert it.
1938 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
1939 EndOffset < NewAllocaEndOffset)) {
1940 StoreInst *Store = IRB.CreateStore(
1941 IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1942 getIndex(IRB, BeginOffset),
1943 getName(".insert")),
1946 DEBUG(dbgs() << " to: " << *Store << "\n");
1950 // Splat to a vector if needed.
1951 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
1952 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
1953 V = IRB.CreateShuffleVector(
1954 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
1955 IRB.getInt32(0), getName(".vsplat.insert")),
1956 UndefValue::get(SplatSourceTy),
1957 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
1958 getName(".vsplat.shuffle"));
1959 assert(V->getType() == VecTy);
1962 Value *New = IRB.CreateStore(V, &NewAI, II.isVolatile());
1964 DEBUG(dbgs() << " to: " << *New << "\n");
1965 return !II.isVolatile();
1968 bool visitMemTransferInst(MemTransferInst &II) {
1969 // Rewriting of memory transfer instructions can be a bit tricky. We break
1970 // them into two categories: split intrinsics and unsplit intrinsics.
1972 DEBUG(dbgs() << " original: " << II << "\n");
1973 IRBuilder<> IRB(&II);
1975 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
1976 bool IsDest = II.getRawDest() == OldPtr;
1978 const AllocaPartitioning::MemTransferOffsets &MTO
1979 = P.getMemTransferOffsets(II);
1981 // For unsplit intrinsics, we simply modify the source and destination
1982 // pointers in place. This isn't just an optimization, it is a matter of
1983 // correctness. With unsplit intrinsics we may be dealing with transfers
1984 // within a single alloca before SROA ran, or with transfers that have
1985 // a variable length. We may also be dealing with memmove instead of
1986 // memcpy, and so simply updating the pointers is the necessary for us to
1987 // update both source and dest of a single call.
1988 if (!MTO.IsSplittable) {
1989 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
1991 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1993 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
1995 DEBUG(dbgs() << " to: " << II << "\n");
1996 deleteIfTriviallyDead(OldOp);
1999 // For split transfer intrinsics we have an incredibly useful assurance:
2000 // the source and destination do not reside within the same alloca, and at
2001 // least one of them does not escape. This means that we can replace
2002 // memmove with memcpy, and we don't need to worry about all manner of
2003 // downsides to splitting and transforming the operations.
2005 // Compute the relative offset within the transfer.
2006 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2007 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2008 : MTO.SourceBegin));
2010 // If this doesn't map cleanly onto the alloca type, and that type isn't
2011 // a single value type, just emit a memcpy.
2013 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
2014 EndOffset != NewAllocaEndOffset ||
2015 !NewAI.getAllocatedType()->isSingleValueType());
2017 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2018 // size hasn't been shrunk based on analysis of the viable range, this is
2020 if (EmitMemCpy && &OldAI == &NewAI) {
2021 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2022 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2023 // Ensure the start lines up.
2024 assert(BeginOffset == OrigBegin);
2027 // Rewrite the size as needed.
2028 if (EndOffset != OrigEnd)
2029 II.setLength(ConstantInt::get(II.getLength()->getType(),
2030 EndOffset - BeginOffset));
2033 // Record this instruction for deletion.
2034 if (Pass.DeadSplitInsts.insert(&II))
2035 Pass.DeadInsts.push_back(&II);
2037 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
2038 EndOffset < NewAllocaEndOffset);
2040 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2041 : II.getRawDest()->getType();
2043 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
2046 // Compute the other pointer, folding as much as possible to produce
2047 // a single, simple GEP in most cases.
2048 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2049 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2050 getName("." + OtherPtr->getName()));
2052 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2053 // alloca that should be re-examined after rewriting this instruction.
2055 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2056 Pass.Worklist.insert(AI);
2060 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2061 : II.getRawSource()->getType());
2062 Type *SizeTy = II.getLength()->getType();
2063 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2065 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2066 IsDest ? OtherPtr : OurPtr,
2067 Size, II.getAlignment(),
2070 DEBUG(dbgs() << " to: " << *New << "\n");
2074 Value *SrcPtr = OtherPtr;
2075 Value *DstPtr = &NewAI;
2077 std::swap(SrcPtr, DstPtr);
2080 if (IsVectorElement && !IsDest) {
2081 // We have to extract rather than load.
2082 Src = IRB.CreateExtractElement(IRB.CreateLoad(SrcPtr,
2083 getName(".copyload")),
2084 getIndex(IRB, BeginOffset),
2085 getName(".copyextract"));
2087 Src = IRB.CreateLoad(SrcPtr, II.isVolatile(), getName(".copyload"));
2090 if (IsVectorElement && IsDest) {
2091 // We have to insert into a loaded copy before storing.
2092 Src = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")),
2093 Src, getIndex(IRB, BeginOffset),
2094 getName(".insert"));
2097 Value *Store = IRB.CreateStore(Src, DstPtr, II.isVolatile());
2099 DEBUG(dbgs() << " to: " << *Store << "\n");
2100 return !II.isVolatile();
2103 bool visitIntrinsicInst(IntrinsicInst &II) {
2104 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2105 II.getIntrinsicID() == Intrinsic::lifetime_end);
2106 DEBUG(dbgs() << " original: " << II << "\n");
2107 IRBuilder<> IRB(&II);
2108 assert(II.getArgOperand(1) == OldPtr);
2110 // Record this instruction for deletion.
2111 if (Pass.DeadSplitInsts.insert(&II))
2112 Pass.DeadInsts.push_back(&II);
2115 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2116 EndOffset - BeginOffset);
2117 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2119 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2120 New = IRB.CreateLifetimeStart(Ptr, Size);
2122 New = IRB.CreateLifetimeEnd(Ptr, Size);
2124 DEBUG(dbgs() << " to: " << *New << "\n");
2128 /// PHI instructions that use an alloca and are subsequently loaded can be
2129 /// rewritten to load both input pointers in the pred blocks and then PHI the
2130 /// results, allowing the load of the alloca to be promoted.
2132 /// %P2 = phi [i32* %Alloca, i32* %Other]
2133 /// %V = load i32* %P2
2135 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2137 /// %V2 = load i32* %Other
2139 /// %V = phi [i32 %V1, i32 %V2]
2141 /// We can do this to a select if its only uses are loads and if the operand
2142 /// to the select can be loaded unconditionally.
2144 /// FIXME: This should be hoisted into a generic utility, likely in
2145 /// Transforms/Util/Local.h
2146 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
2147 // For now, we can only do this promotion if the load is in the same block
2148 // as the PHI, and if there are no stores between the phi and load.
2149 // TODO: Allow recursive phi users.
2150 // TODO: Allow stores.
2151 BasicBlock *BB = PN.getParent();
2152 unsigned MaxAlign = 0;
2153 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
2155 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2156 if (LI == 0 || !LI->isSimple()) return false;
2158 // For now we only allow loads in the same block as the PHI. This is
2159 // a common case that happens when instcombine merges two loads through
2161 if (LI->getParent() != BB) return false;
2163 // Ensure that there are no instructions between the PHI and the load that
2165 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
2166 if (BBI->mayWriteToMemory())
2169 MaxAlign = std::max(MaxAlign, LI->getAlignment());
2170 Loads.push_back(LI);
2173 // We can only transform this if it is safe to push the loads into the
2174 // predecessor blocks. The only thing to watch out for is that we can't put
2175 // a possibly trapping load in the predecessor if it is a critical edge.
2176 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
2178 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
2179 Value *InVal = PN.getIncomingValue(Idx);
2181 // If the value is produced by the terminator of the predecessor (an
2182 // invoke) or it has side-effects, there is no valid place to put a load
2183 // in the predecessor.
2184 if (TI == InVal || TI->mayHaveSideEffects())
2187 // If the predecessor has a single successor, then the edge isn't
2189 if (TI->getNumSuccessors() == 1)
2192 // If this pointer is always safe to load, or if we can prove that there
2193 // is already a load in the block, then we can move the load to the pred
2195 if (InVal->isDereferenceablePointer() ||
2196 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
2205 bool visitPHINode(PHINode &PN) {
2206 DEBUG(dbgs() << " original: " << PN << "\n");
2207 // We would like to compute a new pointer in only one place, but have it be
2208 // as local as possible to the PHI. To do that, we re-use the location of
2209 // the old pointer, which necessarily must be in the right position to
2210 // dominate the PHI.
2211 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2213 SmallVector<LoadInst *, 4> Loads;
2214 if (!isSafePHIToSpeculate(PN, Loads)) {
2215 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2216 // Replace the operands which were using the old pointer.
2217 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2218 for (; OI != OE; ++OI)
2222 DEBUG(dbgs() << " to: " << PN << "\n");
2223 deleteIfTriviallyDead(OldPtr);
2226 assert(!Loads.empty());
2228 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
2229 IRBuilder<> PHIBuilder(&PN);
2230 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues());
2231 NewPN->takeName(&PN);
2233 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
2234 // matter which one we get and if any differ, it doesn't matter.
2235 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
2236 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
2237 unsigned Align = SomeLoad->getAlignment();
2238 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2240 // Rewrite all loads of the PN to use the new PHI.
2242 LoadInst *LI = Loads.pop_back_val();
2243 LI->replaceAllUsesWith(NewPN);
2244 Pass.DeadInsts.push_back(LI);
2245 } while (!Loads.empty());
2247 // Inject loads into all of the pred blocks.
2248 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
2249 BasicBlock *Pred = PN.getIncomingBlock(Idx);
2250 TerminatorInst *TI = Pred->getTerminator();
2251 Value *InVal = PN.getIncomingValue(Idx);
2252 IRBuilder<> PredBuilder(TI);
2254 // Map the value to the new alloca pointer if this was the old alloca
2256 bool ThisOperand = InVal == OldPtr;
2261 = PredBuilder.CreateLoad(InVal, getName(".sroa.speculate." +
2263 ++NumLoadsSpeculated;
2264 Load->setAlignment(Align);
2266 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
2267 NewPN->addIncoming(Load, Pred);
2271 Instruction *OtherPtr = dyn_cast<Instruction>(InVal);
2273 // No uses to rewrite.
2276 // Try to lookup and rewrite any partition uses corresponding to this phi
2278 AllocaPartitioning::iterator PI
2279 = P.findPartitionForPHIOrSelectOperand(PN, OtherPtr);
2280 if (PI != P.end()) {
2281 // If the other pointer is within the partitioning, replace the PHI in
2282 // its uses with the load we just speculated, or add another load for
2283 // it to rewrite if we've already replaced the PHI.
2284 AllocaPartitioning::use_iterator UI
2285 = P.findPartitionUseForPHIOrSelectOperand(PN, OtherPtr);
2286 if (isa<PHINode>(*UI->User))
2289 AllocaPartitioning::PartitionUse OtherUse = *UI;
2290 OtherUse.User = Load;
2291 P.use_insert(PI, std::upper_bound(UI, P.use_end(PI), OtherUse),
2296 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
2297 return NewPtr == &NewAI;
2300 /// Select instructions that use an alloca and are subsequently loaded can be
2301 /// rewritten to load both input pointers and then select between the result,
2302 /// allowing the load of the alloca to be promoted.
2304 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
2305 /// %V = load i32* %P2
2307 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2308 /// %V2 = load i32* %Other
2309 /// %V = select i1 %cond, i32 %V1, i32 %V2
2311 /// We can do this to a select if its only uses are loads and if the operand
2312 /// to the select can be loaded unconditionally.
2313 bool isSafeSelectToSpeculate(SelectInst &SI,
2314 SmallVectorImpl<LoadInst *> &Loads) {
2315 Value *TValue = SI.getTrueValue();
2316 Value *FValue = SI.getFalseValue();
2317 bool TDerefable = TValue->isDereferenceablePointer();
2318 bool FDerefable = FValue->isDereferenceablePointer();
2320 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
2322 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2323 if (LI == 0 || !LI->isSimple()) return false;
2325 // Both operands to the select need to be dereferencable, either
2326 // absolutely (e.g. allocas) or at this point because we can see other
2328 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
2329 LI->getAlignment(), &TD))
2331 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
2332 LI->getAlignment(), &TD))
2334 Loads.push_back(LI);
2340 bool visitSelectInst(SelectInst &SI) {
2341 DEBUG(dbgs() << " original: " << SI << "\n");
2342 IRBuilder<> IRB(&SI);
2344 // Find the operand we need to rewrite here.
2345 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2347 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2349 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2350 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2352 // If the select isn't safe to speculate, just use simple logic to emit it.
2353 SmallVector<LoadInst *, 4> Loads;
2354 if (!isSafeSelectToSpeculate(SI, Loads)) {
2355 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2356 DEBUG(dbgs() << " to: " << SI << "\n");
2357 deleteIfTriviallyDead(OldPtr);
2361 Value *OtherPtr = IsTrueVal ? SI.getFalseValue() : SI.getTrueValue();
2362 AllocaPartitioning::iterator PI
2363 = P.findPartitionForPHIOrSelectOperand(SI, OtherPtr);
2364 AllocaPartitioning::PartitionUse OtherUse;
2365 if (PI != P.end()) {
2366 // If the other pointer is within the partitioning, remove the select
2367 // from its uses. We'll add in the new loads below.
2368 AllocaPartitioning::use_iterator UI
2369 = P.findPartitionUseForPHIOrSelectOperand(SI, OtherPtr);
2371 P.use_erase(PI, UI);
2374 Value *TV = IsTrueVal ? NewPtr : SI.getTrueValue();
2375 Value *FV = IsTrueVal ? SI.getFalseValue() : NewPtr;
2376 // Replace the loads of the select with a select of two loads.
2377 while (!Loads.empty()) {
2378 LoadInst *LI = Loads.pop_back_val();
2380 IRB.SetInsertPoint(LI);
2382 IRB.CreateLoad(TV, getName("." + LI->getName() + ".true"));
2384 IRB.CreateLoad(FV, getName("." + LI->getName() + ".false"));
2385 NumLoadsSpeculated += 2;
2386 if (PI != P.end()) {
2387 LoadInst *OtherLoad = IsTrueVal ? FL : TL;
2388 assert(OtherUse.Ptr == OtherLoad->getOperand(0));
2389 OtherUse.User = OtherLoad;
2390 P.use_insert(PI, P.use_end(PI), OtherUse);
2393 // Transfer alignment and TBAA info if present.
2394 TL->setAlignment(LI->getAlignment());
2395 FL->setAlignment(LI->getAlignment());
2396 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2397 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2398 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2401 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL);
2403 DEBUG(dbgs() << " speculated to: " << *V << "\n");
2404 LI->replaceAllUsesWith(V);
2405 Pass.DeadInsts.push_back(LI);
2408 std::stable_sort(P.use_begin(PI), P.use_end(PI));
2410 deleteIfTriviallyDead(OldPtr);
2411 return NewPtr == &NewAI;
2418 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2420 /// This pass aggressively rewrites all aggregate loads and stores on
2421 /// a particular pointer (or any pointer derived from it which we can identify)
2422 /// with scalar loads and stores.
2423 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2424 // Befriend the base class so it can delegate to private visit methods.
2425 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2427 const TargetData &TD;
2429 /// Queue of pointer uses to analyze and potentially rewrite.
2430 SmallVector<Use *, 8> Queue;
2432 /// Set to prevent us from cycling with phi nodes and loops.
2433 SmallPtrSet<User *, 8> Visited;
2435 /// The current pointer use being rewritten. This is used to dig up the used
2436 /// value (as opposed to the user).
2440 AggLoadStoreRewriter(const TargetData &TD) : TD(TD) {}
2442 /// Rewrite loads and stores through a pointer and all pointers derived from
2444 bool rewrite(Instruction &I) {
2445 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2447 bool Changed = false;
2448 while (!Queue.empty()) {
2449 U = Queue.pop_back_val();
2450 Changed |= visit(cast<Instruction>(U->getUser()));
2456 /// Enqueue all the users of the given instruction for further processing.
2457 /// This uses a set to de-duplicate users.
2458 void enqueueUsers(Instruction &I) {
2459 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2461 if (Visited.insert(*UI))
2462 Queue.push_back(&UI.getUse());
2465 // Conservative default is to not rewrite anything.
2466 bool visitInstruction(Instruction &I) { return false; }
2468 /// \brief Generic recursive split emission routine.
2470 /// This method recursively splits an aggregate op (load or store) into
2471 /// scalar or vector ops. It splits recursively until it hits a single value
2472 /// and emits that single value operation via the template argument.
2474 /// The logic of this routine relies on GEPs and insertvalue and extractvalue
2475 /// all operating with the same fundamental index list, merely formatted
2476 /// differently (GEPs need actual values).
2478 /// \param IRB The builder used to form new instructions.
2479 /// \param Ty The type being split recursively into smaller ops.
2480 /// \param Agg The aggregate value being built up or stored, depending on
2481 /// whether this is splitting a load or a store respectively.
2482 /// \param Ptr The base pointer of the original op, used as a base for GEPing
2483 /// the split operations.
2484 /// \param Indices The indices which to be used with insert- or extractvalue
2485 /// to select the appropriate value within the aggregate for \p Ty.
2486 /// \param GEPIndices The indices to a GEP instruction which will move \p Ptr
2487 /// to the correct slot within the aggregate for \p Ty.
2488 template <void (AggLoadStoreRewriter::*emitFunc)(
2489 IRBuilder<> &IRB, Type *Ty, Value *&Agg, Value *Ptr,
2490 ArrayRef<unsigned> Indices, ArrayRef<Value *> GEPIndices,
2492 void emitSplitOps(IRBuilder<> &IRB, Type *Ty, Value *&Agg, Value *Ptr,
2493 SmallVectorImpl<unsigned> &Indices,
2494 SmallVectorImpl<Value *> &GEPIndices,
2495 const Twine &Name) {
2496 if (Ty->isSingleValueType())
2497 return (this->*emitFunc)(IRB, Ty, Agg, Ptr, Indices, GEPIndices, Name);
2499 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2500 unsigned OldSize = Indices.size();
2502 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size; ++Idx) {
2503 assert(Indices.size() == OldSize && "Did not return to the old size");
2504 Indices.push_back(Idx);
2505 GEPIndices.push_back(IRB.getInt32(Idx));
2506 emitSplitOps<emitFunc>(IRB, ATy->getElementType(), Agg, Ptr,
2507 Indices, GEPIndices, Name + "." + Twine(Idx));
2508 GEPIndices.pop_back();
2514 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2515 unsigned OldSize = Indices.size();
2517 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size; ++Idx) {
2518 assert(Indices.size() == OldSize && "Did not return to the old size");
2519 Indices.push_back(Idx);
2520 GEPIndices.push_back(IRB.getInt32(Idx));
2521 emitSplitOps<emitFunc>(IRB, STy->getElementType(Idx), Agg, Ptr,
2522 Indices, GEPIndices, Name + "." + Twine(Idx));
2523 GEPIndices.pop_back();
2529 llvm_unreachable("Only arrays and structs are aggregate loadable types");
2532 /// Emit a leaf load of a single value. This is called at the leaves of the
2533 /// recursive emission to actually load values.
2534 void emitLoad(IRBuilder<> &IRB, Type *Ty, Value *&Agg, Value *Ptr,
2535 ArrayRef<unsigned> Indices, ArrayRef<Value *> GEPIndices,
2536 const Twine &Name) {
2537 assert(Ty->isSingleValueType());
2538 // Load the single value and insert it using the indices.
2539 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
2542 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2543 DEBUG(dbgs() << " to: " << *Load << "\n");
2546 bool visitLoadInst(LoadInst &LI) {
2547 assert(LI.getPointerOperand() == *U);
2548 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2551 // We have an aggregate being loaded, split it apart.
2552 DEBUG(dbgs() << " original: " << LI << "\n");
2553 IRBuilder<> IRB(&LI);
2554 Value *V = UndefValue::get(LI.getType());
2555 SmallVector<unsigned, 4> Indices;
2556 SmallVector<Value *, 4> GEPIndices;
2557 GEPIndices.push_back(IRB.getInt32(0));
2558 emitSplitOps<&AggLoadStoreRewriter::emitLoad>(
2559 IRB, LI.getType(), V, *U, Indices, GEPIndices, LI.getName() + ".fca");
2560 LI.replaceAllUsesWith(V);
2561 LI.eraseFromParent();
2565 /// Emit a leaf store of a single value. This is called at the leaves of the
2566 /// recursive emission to actually produce stores.
2567 void emitStore(IRBuilder<> &IRB, Type *Ty, Value *&Agg, Value *Ptr,
2568 ArrayRef<unsigned> Indices, ArrayRef<Value *> GEPIndices,
2569 const Twine &Name) {
2570 assert(Ty->isSingleValueType());
2571 // Extract the single value and store it using the indices.
2572 Value *Store = IRB.CreateStore(
2573 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2574 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2576 DEBUG(dbgs() << " to: " << *Store << "\n");
2579 bool visitStoreInst(StoreInst &SI) {
2580 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2582 Value *V = SI.getValueOperand();
2583 if (V->getType()->isSingleValueType())
2586 // We have an aggregate being stored, split it apart.
2587 DEBUG(dbgs() << " original: " << SI << "\n");
2588 IRBuilder<> IRB(&SI);
2589 SmallVector<unsigned, 4> Indices;
2590 SmallVector<Value *, 4> GEPIndices;
2591 GEPIndices.push_back(IRB.getInt32(0));
2592 emitSplitOps<&AggLoadStoreRewriter::emitStore>(
2593 IRB, V->getType(), V, *U, Indices, GEPIndices, V->getName() + ".fca");
2594 SI.eraseFromParent();
2598 bool visitBitCastInst(BitCastInst &BC) {
2603 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2608 bool visitPHINode(PHINode &PN) {
2613 bool visitSelectInst(SelectInst &SI) {
2620 /// \brief Try to find a partition of the aggregate type passed in for a given
2621 /// offset and size.
2623 /// This recurses through the aggregate type and tries to compute a subtype
2624 /// based on the offset and size. When the offset and size span a sub-section
2625 /// of an array, it will even compute a new array type for that sub-section,
2626 /// and the same for structs.
2628 /// Note that this routine is very strict and tries to find a partition of the
2629 /// type which produces the *exact* right offset and size. It is not forgiving
2630 /// when the size or offset cause either end of type-based partition to be off.
2631 /// Also, this is a best-effort routine. It is reasonable to give up and not
2632 /// return a type if necessary.
2633 static Type *getTypePartition(const TargetData &TD, Type *Ty,
2634 uint64_t Offset, uint64_t Size) {
2635 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2638 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2639 // We can't partition pointers...
2640 if (SeqTy->isPointerTy())
2643 Type *ElementTy = SeqTy->getElementType();
2644 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2645 uint64_t NumSkippedElements = Offset / ElementSize;
2646 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2647 if (NumSkippedElements >= ArrTy->getNumElements())
2649 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2650 if (NumSkippedElements >= VecTy->getNumElements())
2652 Offset -= NumSkippedElements * ElementSize;
2654 // First check if we need to recurse.
2655 if (Offset > 0 || Size < ElementSize) {
2656 // Bail if the partition ends in a different array element.
2657 if ((Offset + Size) > ElementSize)
2659 // Recurse through the element type trying to peel off offset bytes.
2660 return getTypePartition(TD, ElementTy, Offset, Size);
2662 assert(Offset == 0);
2664 if (Size == ElementSize)
2666 assert(Size > ElementSize);
2667 uint64_t NumElements = Size / ElementSize;
2668 if (NumElements * ElementSize != Size)
2670 return ArrayType::get(ElementTy, NumElements);
2673 StructType *STy = dyn_cast<StructType>(Ty);
2677 const StructLayout *SL = TD.getStructLayout(STy);
2678 if (Offset >= SL->getSizeInBytes())
2680 uint64_t EndOffset = Offset + Size;
2681 if (EndOffset > SL->getSizeInBytes())
2684 unsigned Index = SL->getElementContainingOffset(Offset);
2685 Offset -= SL->getElementOffset(Index);
2687 Type *ElementTy = STy->getElementType(Index);
2688 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2689 if (Offset >= ElementSize)
2690 return 0; // The offset points into alignment padding.
2692 // See if any partition must be contained by the element.
2693 if (Offset > 0 || Size < ElementSize) {
2694 if ((Offset + Size) > ElementSize)
2696 return getTypePartition(TD, ElementTy, Offset, Size);
2698 assert(Offset == 0);
2700 if (Size == ElementSize)
2703 StructType::element_iterator EI = STy->element_begin() + Index,
2704 EE = STy->element_end();
2705 if (EndOffset < SL->getSizeInBytes()) {
2706 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2707 if (Index == EndIndex)
2708 return 0; // Within a single element and its padding.
2710 // Don't try to form "natural" types if the elements don't line up with the
2712 // FIXME: We could potentially recurse down through the last element in the
2713 // sub-struct to find a natural end point.
2714 if (SL->getElementOffset(EndIndex) != EndOffset)
2717 assert(Index < EndIndex);
2718 EE = STy->element_begin() + EndIndex;
2721 // Try to build up a sub-structure.
2722 SmallVector<Type *, 4> ElementTys;
2724 ElementTys.push_back(*EI++);
2726 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
2728 const StructLayout *SubSL = TD.getStructLayout(SubTy);
2729 if (Size != SubSL->getSizeInBytes())
2730 return 0; // The sub-struct doesn't have quite the size needed.
2735 /// \brief Rewrite an alloca partition's users.
2737 /// This routine drives both of the rewriting goals of the SROA pass. It tries
2738 /// to rewrite uses of an alloca partition to be conducive for SSA value
2739 /// promotion. If the partition needs a new, more refined alloca, this will
2740 /// build that new alloca, preserving as much type information as possible, and
2741 /// rewrite the uses of the old alloca to point at the new one and have the
2742 /// appropriate new offsets. It also evaluates how successful the rewrite was
2743 /// at enabling promotion and if it was successful queues the alloca to be
2745 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
2746 AllocaPartitioning &P,
2747 AllocaPartitioning::iterator PI) {
2748 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
2749 if (P.use_begin(PI) == P.use_end(PI))
2750 return false; // No live uses left of this partition.
2752 // Try to compute a friendly type for this partition of the alloca. This
2753 // won't always succeed, in which case we fall back to a legal integer type
2754 // or an i8 array of an appropriate size.
2756 if (Type *PartitionTy = P.getCommonType(PI))
2757 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
2758 AllocaTy = PartitionTy;
2760 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
2761 PI->BeginOffset, AllocaSize))
2762 AllocaTy = PartitionTy;
2764 (AllocaTy->isArrayTy() &&
2765 AllocaTy->getArrayElementType()->isIntegerTy())) &&
2766 TD->isLegalInteger(AllocaSize * 8))
2767 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
2769 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
2770 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
2772 // Check for the case where we're going to rewrite to a new alloca of the
2773 // exact same type as the original, and with the same access offsets. In that
2774 // case, re-use the existing alloca, but still run through the rewriter to
2775 // performe phi and select speculation.
2777 if (AllocaTy == AI.getAllocatedType()) {
2778 assert(PI->BeginOffset == 0 &&
2779 "Non-zero begin offset but same alloca type");
2780 assert(PI == P.begin() && "Begin offset is zero on later partition");
2783 // FIXME: The alignment here is overly conservative -- we could in many
2784 // cases get away with much weaker alignment constraints.
2785 NewAI = new AllocaInst(AllocaTy, 0, AI.getAlignment(),
2786 AI.getName() + ".sroa." + Twine(PI - P.begin()),
2791 DEBUG(dbgs() << "Rewriting alloca partition "
2792 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
2795 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
2796 PI->BeginOffset, PI->EndOffset);
2797 DEBUG(dbgs() << " rewriting ");
2798 DEBUG(P.print(dbgs(), PI, ""));
2799 if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
2800 DEBUG(dbgs() << " and queuing for promotion\n");
2801 PromotableAllocas.push_back(NewAI);
2802 } else if (NewAI != &AI) {
2803 // If we can't promote the alloca, iterate on it to check for new
2804 // refinements exposed by splitting the current alloca. Don't iterate on an
2805 // alloca which didn't actually change and didn't get promoted.
2806 Worklist.insert(NewAI);
2811 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
2812 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
2813 bool Changed = false;
2814 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
2816 Changed |= rewriteAllocaPartition(AI, P, PI);
2821 /// \brief Analyze an alloca for SROA.
2823 /// This analyzes the alloca to ensure we can reason about it, builds
2824 /// a partitioning of the alloca, and then hands it off to be split and
2825 /// rewritten as needed.
2826 bool SROA::runOnAlloca(AllocaInst &AI) {
2827 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
2828 ++NumAllocasAnalyzed;
2830 // Special case dead allocas, as they're trivial.
2831 if (AI.use_empty()) {
2832 AI.eraseFromParent();
2836 // Skip alloca forms that this analysis can't handle.
2837 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
2838 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
2841 // First check if this is a non-aggregate type that we should simply promote.
2842 if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
2843 DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
2844 PromotableAllocas.push_back(&AI);
2848 bool Changed = false;
2850 // First, split any FCA loads and stores touching this alloca to promote
2851 // better splitting and promotion opportunities.
2852 AggLoadStoreRewriter AggRewriter(*TD);
2853 Changed |= AggRewriter.rewrite(AI);
2855 // Build the partition set using a recursive instruction-visiting builder.
2856 AllocaPartitioning P(*TD, AI);
2857 DEBUG(P.print(dbgs()));
2861 // No partitions to split. Leave the dead alloca for a later pass to clean up.
2862 if (P.begin() == P.end())
2865 // Delete all the dead users of this alloca before splitting and rewriting it.
2866 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
2867 DE = P.dead_user_end();
2870 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
2871 DeadInsts.push_back(*DI);
2873 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
2874 DE = P.dead_op_end();
2877 // Clobber the use with an undef value.
2878 **DO = UndefValue::get(OldV->getType());
2879 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
2880 if (isInstructionTriviallyDead(OldI)) {
2882 DeadInsts.push_back(OldI);
2886 return splitAlloca(AI, P) || Changed;
2889 /// \brief Delete the dead instructions accumulated in this run.
2891 /// Recursively deletes the dead instructions we've accumulated. This is done
2892 /// at the very end to maximize locality of the recursive delete and to
2893 /// minimize the problems of invalidated instruction pointers as such pointers
2894 /// are used heavily in the intermediate stages of the algorithm.
2896 /// We also record the alloca instructions deleted here so that they aren't
2897 /// subsequently handed to mem2reg to promote.
2898 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
2899 DeadSplitInsts.clear();
2900 while (!DeadInsts.empty()) {
2901 Instruction *I = DeadInsts.pop_back_val();
2902 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
2904 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
2905 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
2906 // Zero out the operand and see if it becomes trivially dead.
2908 if (isInstructionTriviallyDead(U))
2909 DeadInsts.push_back(U);
2912 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2913 DeletedAllocas.insert(AI);
2916 I->eraseFromParent();
2920 /// \brief Promote the allocas, using the best available technique.
2922 /// This attempts to promote whatever allocas have been identified as viable in
2923 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
2924 /// If there is a domtree available, we attempt to promote using the full power
2925 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
2926 /// based on the SSAUpdater utilities. This function returns whether any
2927 /// promotion occured.
2928 bool SROA::promoteAllocas(Function &F) {
2929 if (PromotableAllocas.empty())
2932 NumPromoted += PromotableAllocas.size();
2934 if (DT && !ForceSSAUpdater) {
2935 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
2936 PromoteMemToReg(PromotableAllocas, *DT);
2937 PromotableAllocas.clear();
2941 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
2943 DIBuilder DIB(*F.getParent());
2944 SmallVector<Instruction*, 64> Insts;
2946 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
2947 AllocaInst *AI = PromotableAllocas[Idx];
2948 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
2950 Instruction *I = cast<Instruction>(*UI++);
2951 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
2952 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
2953 // leading to them) here. Eventually it should use them to optimize the
2954 // scalar values produced.
2955 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
2956 assert(onlyUsedByLifetimeMarkers(I) &&
2957 "Found a bitcast used outside of a lifetime marker.");
2958 while (!I->use_empty())
2959 cast<Instruction>(*I->use_begin())->eraseFromParent();
2960 I->eraseFromParent();
2963 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2964 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
2965 II->getIntrinsicID() == Intrinsic::lifetime_end);
2966 II->eraseFromParent();
2972 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
2976 PromotableAllocas.clear();
2981 /// \brief A predicate to test whether an alloca belongs to a set.
2982 class IsAllocaInSet {
2983 typedef SmallPtrSet<AllocaInst *, 4> SetType;
2987 IsAllocaInSet(const SetType &Set) : Set(Set) {}
2988 bool operator()(AllocaInst *AI) { return Set.count(AI); }
2992 bool SROA::runOnFunction(Function &F) {
2993 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
2994 C = &F.getContext();
2995 TD = getAnalysisIfAvailable<TargetData>();
2997 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3000 DT = getAnalysisIfAvailable<DominatorTree>();
3002 BasicBlock &EntryBB = F.getEntryBlock();
3003 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3005 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3006 Worklist.insert(AI);
3008 bool Changed = false;
3009 // A set of deleted alloca instruction pointers which should be removed from
3010 // the list of promotable allocas.
3011 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3013 while (!Worklist.empty()) {
3014 Changed |= runOnAlloca(*Worklist.pop_back_val());
3015 deleteDeadInstructions(DeletedAllocas);
3016 if (!DeletedAllocas.empty()) {
3017 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3018 PromotableAllocas.end(),
3019 IsAllocaInSet(DeletedAllocas)),
3020 PromotableAllocas.end());
3021 DeletedAllocas.clear();
3025 Changed |= promoteAllocas(F);
3030 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3031 if (RequiresDomTree)
3032 AU.addRequired<DominatorTree>();
3033 AU.setPreservesCFG();