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/IRBuilder.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/IntrinsicInst.h"
36 #include "llvm/LLVMContext.h"
37 #include "llvm/Module.h"
38 #include "llvm/Operator.h"
39 #include "llvm/Pass.h"
40 #include "llvm/ADT/SetVector.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/Analysis/Dominators.h"
45 #include "llvm/Analysis/Loads.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/DataLayout.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
57 #include "llvm/Transforms/Utils/SSAUpdater.h"
60 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
61 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
62 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
63 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
64 STATISTIC(NumDeleted, "Number of instructions deleted");
65 STATISTIC(NumVectorized, "Number of vectorized aggregates");
67 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
68 /// forming SSA values through the SSAUpdater infrastructure.
70 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
73 /// \brief Alloca partitioning representation.
75 /// This class represents a partitioning of an alloca into slices, and
76 /// information about the nature of uses of each slice of the alloca. The goal
77 /// is that this information is sufficient to decide if and how to split the
78 /// alloca apart and replace slices with scalars. It is also intended that this
79 /// structure can capture the relevant information needed both to decide about
80 /// and to enact these transformations.
81 class AllocaPartitioning {
83 /// \brief A common base class for representing a half-open byte range.
85 /// \brief The beginning offset of the range.
88 /// \brief The ending offset, not included in the range.
91 ByteRange() : BeginOffset(), EndOffset() {}
92 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
93 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
95 /// \brief Support for ordering ranges.
97 /// This provides an ordering over ranges such that start offsets are
98 /// always increasing, and within equal start offsets, the end offsets are
99 /// decreasing. Thus the spanning range comes first in a cluster with the
100 /// same start position.
101 bool operator<(const ByteRange &RHS) const {
102 if (BeginOffset < RHS.BeginOffset) return true;
103 if (BeginOffset > RHS.BeginOffset) return false;
104 if (EndOffset > RHS.EndOffset) return true;
108 /// \brief Support comparison with a single offset to allow binary searches.
109 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
110 return LHS.BeginOffset < RHSOffset;
113 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
114 const ByteRange &RHS) {
115 return LHSOffset < RHS.BeginOffset;
118 bool operator==(const ByteRange &RHS) const {
119 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
121 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
124 /// \brief A partition of an alloca.
126 /// This structure represents a contiguous partition of the alloca. These are
127 /// formed by examining the uses of the alloca. During formation, they may
128 /// overlap but once an AllocaPartitioning is built, the Partitions within it
129 /// are all disjoint.
130 struct Partition : public ByteRange {
131 /// \brief Whether this partition is splittable into smaller partitions.
133 /// We flag partitions as splittable when they are formed entirely due to
134 /// accesses by trivially splittable operations such as memset and memcpy.
137 /// \brief Test whether a partition has been marked as dead.
138 bool isDead() const {
139 if (BeginOffset == UINT64_MAX) {
140 assert(EndOffset == UINT64_MAX);
146 /// \brief Kill a partition.
147 /// This is accomplished by setting both its beginning and end offset to
148 /// the maximum possible value.
150 assert(!isDead() && "He's Dead, Jim!");
151 BeginOffset = EndOffset = UINT64_MAX;
154 Partition() : ByteRange(), IsSplittable() {}
155 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
156 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
159 /// \brief A particular use of a partition of the alloca.
161 /// This structure is used to associate uses of a partition with it. They
162 /// mark the range of bytes which are referenced by a particular instruction,
163 /// and includes a handle to the user itself and the pointer value in use.
164 /// The bounds of these uses are determined by intersecting the bounds of the
165 /// memory use itself with a particular partition. As a consequence there is
166 /// intentionally overlap between various uses of the same partition.
167 struct PartitionUse : public ByteRange {
168 /// \brief The use in question. Provides access to both user and used value.
170 /// Note that this may be null if the partition use is *dead*, that is, it
171 /// should be ignored.
174 PartitionUse() : ByteRange(), U() {}
175 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
176 : ByteRange(BeginOffset, EndOffset), U(U) {}
179 /// \brief Construct a partitioning of a particular alloca.
181 /// Construction does most of the work for partitioning the alloca. This
182 /// performs the necessary walks of users and builds a partitioning from it.
183 AllocaPartitioning(const DataLayout &TD, AllocaInst &AI);
185 /// \brief Test whether a pointer to the allocation escapes our analysis.
187 /// If this is true, the partitioning is never fully built and should be
189 bool isEscaped() const { return PointerEscapingInstr; }
191 /// \brief Support for iterating over the partitions.
193 typedef SmallVectorImpl<Partition>::iterator iterator;
194 iterator begin() { return Partitions.begin(); }
195 iterator end() { return Partitions.end(); }
197 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
198 const_iterator begin() const { return Partitions.begin(); }
199 const_iterator end() const { return Partitions.end(); }
202 /// \brief Support for iterating over and manipulating a particular
203 /// partition's uses.
205 /// The iteration support provided for uses is more limited, but also
206 /// includes some manipulation routines to support rewriting the uses of
207 /// partitions during SROA.
209 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
210 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
211 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
212 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
213 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
215 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
216 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
217 const_use_iterator use_begin(const_iterator I) const {
218 return Uses[I - begin()].begin();
220 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
221 const_use_iterator use_end(const_iterator I) const {
222 return Uses[I - begin()].end();
225 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
226 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
227 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
228 return Uses[PIdx][UIdx];
230 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
231 return Uses[I - begin()][UIdx];
234 void use_push_back(unsigned Idx, const PartitionUse &PU) {
235 Uses[Idx].push_back(PU);
237 void use_push_back(const_iterator I, const PartitionUse &PU) {
238 Uses[I - begin()].push_back(PU);
242 /// \brief Allow iterating the dead users for this alloca.
244 /// These are instructions which will never actually use the alloca as they
245 /// are outside the allocated range. They are safe to replace with undef and
248 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
249 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
250 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
253 /// \brief Allow iterating the dead expressions referring to this alloca.
255 /// These are operands which have cannot actually be used to refer to the
256 /// alloca as they are outside its range and the user doesn't correct for
257 /// that. These mostly consist of PHI node inputs and the like which we just
258 /// need to replace with undef.
260 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
261 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
262 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
265 /// \brief MemTransferInst auxiliary data.
266 /// This struct provides some auxiliary data about memory transfer
267 /// intrinsics such as memcpy and memmove. These intrinsics can use two
268 /// different ranges within the same alloca, and provide other challenges to
269 /// correctly represent. We stash extra data to help us untangle this
270 /// after the partitioning is complete.
271 struct MemTransferOffsets {
272 /// The destination begin and end offsets when the destination is within
273 /// this alloca. If the end offset is zero the destination is not within
275 uint64_t DestBegin, DestEnd;
277 /// The source begin and end offsets when the source is within this alloca.
278 /// If the end offset is zero, the source is not within this alloca.
279 uint64_t SourceBegin, SourceEnd;
281 /// Flag for whether an alloca is splittable.
284 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
285 return MemTransferInstData.lookup(&II);
288 /// \brief Map from a PHI or select operand back to a partition.
290 /// When manipulating PHI nodes or selects, they can use more than one
291 /// partition of an alloca. We store a special mapping to allow finding the
292 /// partition referenced by each of these operands, if any.
293 iterator findPartitionForPHIOrSelectOperand(Use *U) {
294 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
295 = PHIOrSelectOpMap.find(U);
296 if (MapIt == PHIOrSelectOpMap.end())
299 return begin() + MapIt->second.first;
302 /// \brief Map from a PHI or select operand back to the specific use of
305 /// Similar to mapping these operands back to the partitions, this maps
306 /// directly to the use structure of that partition.
307 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
308 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
309 = PHIOrSelectOpMap.find(U);
310 assert(MapIt != PHIOrSelectOpMap.end());
311 return Uses[MapIt->second.first].begin() + MapIt->second.second;
314 /// \brief Compute a common type among the uses of a particular partition.
316 /// This routines walks all of the uses of a particular partition and tries
317 /// to find a common type between them. Untyped operations such as memset and
318 /// memcpy are ignored.
319 Type *getCommonType(iterator I) const;
321 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
322 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
323 void printUsers(raw_ostream &OS, const_iterator I,
324 StringRef Indent = " ") const;
325 void print(raw_ostream &OS) const;
326 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
327 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
331 template <typename DerivedT, typename RetT = void> class BuilderBase;
332 class PartitionBuilder;
333 friend class AllocaPartitioning::PartitionBuilder;
335 friend class AllocaPartitioning::UseBuilder;
337 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
338 /// \brief Handle to alloca instruction to simplify method interfaces.
342 /// \brief The instruction responsible for this alloca having no partitioning.
344 /// When an instruction (potentially) escapes the pointer to the alloca, we
345 /// store a pointer to that here and abort trying to partition the alloca.
346 /// This will be null if the alloca is partitioned successfully.
347 Instruction *PointerEscapingInstr;
349 /// \brief The partitions of the alloca.
351 /// We store a vector of the partitions over the alloca here. This vector is
352 /// sorted by increasing begin offset, and then by decreasing end offset. See
353 /// the Partition inner class for more details. Initially (during
354 /// construction) there are overlaps, but we form a disjoint sequence of
355 /// partitions while finishing construction and a fully constructed object is
356 /// expected to always have this as a disjoint space.
357 SmallVector<Partition, 8> Partitions;
359 /// \brief The uses of the partitions.
361 /// This is essentially a mapping from each partition to a list of uses of
362 /// that partition. The mapping is done with a Uses vector that has the exact
363 /// same number of entries as the partition vector. Each entry is itself
364 /// a vector of the uses.
365 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
367 /// \brief Instructions which will become dead if we rewrite the alloca.
369 /// Note that these are not separated by partition. This is because we expect
370 /// a partitioned alloca to be completely rewritten or not rewritten at all.
371 /// If rewritten, all these instructions can simply be removed and replaced
372 /// with undef as they come from outside of the allocated space.
373 SmallVector<Instruction *, 8> DeadUsers;
375 /// \brief Operands which will become dead if we rewrite the alloca.
377 /// These are operands that in their particular use can be replaced with
378 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
379 /// to PHI nodes and the like. They aren't entirely dead (there might be
380 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
381 /// want to swap this particular input for undef to simplify the use lists of
383 SmallVector<Use *, 8> DeadOperands;
385 /// \brief The underlying storage for auxiliary memcpy and memset info.
386 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
388 /// \brief A side datastructure used when building up the partitions and uses.
390 /// This mapping is only really used during the initial building of the
391 /// partitioning so that we can retain information about PHI and select nodes
393 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
395 /// \brief Auxiliary information for particular PHI or select operands.
396 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
398 /// \brief A utility routine called from the constructor.
400 /// This does what it says on the tin. It is the key of the alloca partition
401 /// splitting and merging. After it is called we have the desired disjoint
402 /// collection of partitions.
403 void splitAndMergePartitions();
407 template <typename DerivedT, typename RetT>
408 class AllocaPartitioning::BuilderBase
409 : public InstVisitor<DerivedT, RetT> {
411 BuilderBase(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
413 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
419 const DataLayout &TD;
420 const uint64_t AllocSize;
421 AllocaPartitioning &P;
423 SmallPtrSet<Use *, 8> VisitedUses;
429 SmallVector<OffsetUse, 8> Queue;
431 // The active offset and use while visiting.
435 void enqueueUsers(Instruction &I, int64_t UserOffset) {
436 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
438 if (VisitedUses.insert(&UI.getUse())) {
439 OffsetUse OU = { &UI.getUse(), UserOffset };
445 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
447 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
449 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
455 // Handle a struct index, which adds its field offset to the pointer.
456 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
457 unsigned ElementIdx = OpC->getZExtValue();
458 const StructLayout *SL = TD.getStructLayout(STy);
459 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
460 // Check that we can continue to model this GEP in a signed 64-bit offset.
461 if (ElementOffset > INT64_MAX ||
463 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
464 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
465 << "what can be represented in an int64_t!\n"
466 << " alloca: " << P.AI << "\n");
470 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
472 GEPOffset += ElementOffset;
476 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
477 Index *= APInt(Index.getBitWidth(),
478 TD.getTypeAllocSize(GTI.getIndexedType()));
479 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
481 // Check if the result can be stored in our int64_t offset.
482 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
483 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
484 << "what can be represented in an int64_t!\n"
485 << " alloca: " << P.AI << "\n");
489 GEPOffset = Index.getSExtValue();
494 Value *foldSelectInst(SelectInst &SI) {
495 // If the condition being selected on is a constant or the same value is
496 // being selected between, fold the select. Yes this does (rarely) happen
498 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
499 return SI.getOperand(1+CI->isZero());
500 if (SI.getOperand(1) == SI.getOperand(2)) {
501 assert(*U == SI.getOperand(1));
502 return SI.getOperand(1);
508 /// \brief Builder for the alloca partitioning.
510 /// This class builds an alloca partitioning by recursively visiting the uses
511 /// of an alloca and splitting the partitions for each load and store at each
513 class AllocaPartitioning::PartitionBuilder
514 : public BuilderBase<PartitionBuilder, bool> {
515 friend class InstVisitor<PartitionBuilder, bool>;
517 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
520 PartitionBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
521 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
523 /// \brief Run the builder over the allocation.
525 // Note that we have to re-evaluate size on each trip through the loop as
526 // the queue grows at the tail.
527 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
529 Offset = Queue[Idx].Offset;
530 if (!visit(cast<Instruction>(U->getUser())))
537 bool markAsEscaping(Instruction &I) {
538 P.PointerEscapingInstr = &I;
542 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
543 bool IsSplittable = false) {
544 // Completely skip uses which have a zero size or don't overlap the
547 (Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
548 (Offset < 0 && (uint64_t)-Offset >= Size)) {
549 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
550 << " which starts past the end of the " << AllocSize
552 << " alloca: " << P.AI << "\n"
553 << " use: " << I << "\n");
557 // Clamp the start to the beginning of the allocation.
559 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
560 << " to start at the beginning of the alloca:\n"
561 << " alloca: " << P.AI << "\n"
562 << " use: " << I << "\n");
563 Size -= (uint64_t)-Offset;
567 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
569 // Clamp the end offset to the end of the allocation. Note that this is
570 // formulated to handle even the case where "BeginOffset + Size" overflows.
571 // NOTE! This may appear superficially to be something we could ignore
572 // entirely, but that is not so! There may be PHI-node uses where some
573 // instructions are dead but not others. We can't completely ignore the
574 // PHI node, and so have to record at least the information here.
575 assert(AllocSize >= BeginOffset); // Established above.
576 if (Size > AllocSize - BeginOffset) {
577 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
578 << " to remain within the " << AllocSize << " byte alloca:\n"
579 << " alloca: " << P.AI << "\n"
580 << " use: " << I << "\n");
581 EndOffset = AllocSize;
584 Partition New(BeginOffset, EndOffset, IsSplittable);
585 P.Partitions.push_back(New);
588 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset,
590 uint64_t Size = TD.getTypeStoreSize(Ty);
592 // If this memory access can be shown to *statically* extend outside the
593 // bounds of of the allocation, it's behavior is undefined, so simply
594 // ignore it. Note that this is more strict than the generic clamping
595 // behavior of insertUse. We also try to handle cases which might run the
597 // FIXME: We should instead consider the pointer to have escaped if this
598 // function is being instrumented for addressing bugs or race conditions.
599 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
600 Size > (AllocSize - (uint64_t)Offset)) {
601 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
602 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
603 << " which extends past the end of the " << AllocSize
605 << " alloca: " << P.AI << "\n"
606 << " use: " << I << "\n");
610 // We allow splitting of loads and stores where the type is an integer type
611 // and which cover the entire alloca. Such integer loads and stores
612 // often require decomposition into fine grained loads and stores.
613 bool IsSplittable = false;
614 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
615 IsSplittable = !IsVolatile && ITy->getBitWidth() == AllocSize*8;
617 insertUse(I, Offset, Size, IsSplittable);
621 bool visitBitCastInst(BitCastInst &BC) {
622 enqueueUsers(BC, Offset);
626 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
628 if (!computeConstantGEPOffset(GEPI, GEPOffset))
629 return markAsEscaping(GEPI);
631 enqueueUsers(GEPI, GEPOffset);
635 bool visitLoadInst(LoadInst &LI) {
636 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
637 "All simple FCA loads should have been pre-split");
638 return handleLoadOrStore(LI.getType(), LI, Offset, LI.isVolatile());
641 bool visitStoreInst(StoreInst &SI) {
642 Value *ValOp = SI.getValueOperand();
644 return markAsEscaping(SI);
646 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
647 "All simple FCA stores should have been pre-split");
648 return handleLoadOrStore(ValOp->getType(), SI, Offset, SI.isVolatile());
652 bool visitMemSetInst(MemSetInst &II) {
653 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
654 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
655 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
656 insertUse(II, Offset, Size, Length);
660 bool visitMemTransferInst(MemTransferInst &II) {
661 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
662 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
664 // Zero-length mem transfer intrinsics can be ignored entirely.
667 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
669 // Only intrinsics with a constant length can be split.
670 Offsets.IsSplittable = Length;
672 if (*U == II.getRawDest()) {
673 Offsets.DestBegin = Offset;
674 Offsets.DestEnd = Offset + Size;
676 if (*U == II.getRawSource()) {
677 Offsets.SourceBegin = Offset;
678 Offsets.SourceEnd = Offset + Size;
681 // If we have set up end offsets for both the source and the destination,
682 // we have found both sides of this transfer pointing at the same alloca.
683 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
684 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
685 unsigned PrevIdx = MemTransferPartitionMap[&II];
687 // Check if the begin offsets match and this is a non-volatile transfer.
688 // In that case, we can completely elide the transfer.
689 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
690 P.Partitions[PrevIdx].kill();
694 // Otherwise we have an offset transfer within the same alloca. We can't
696 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
697 } else if (SeenBothEnds) {
698 // Handle the case where this exact use provides both ends of the
700 assert(II.getRawDest() == II.getRawSource());
702 // For non-volatile transfers this is a no-op.
703 if (!II.isVolatile())
706 // Otherwise just suppress splitting.
707 Offsets.IsSplittable = false;
711 // Insert the use now that we've fixed up the splittable nature.
712 insertUse(II, Offset, Size, Offsets.IsSplittable);
714 // Setup the mapping from intrinsic to partition of we've not seen both
715 // ends of this transfer.
717 unsigned NewIdx = P.Partitions.size() - 1;
719 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
721 "Already have intrinsic in map but haven't seen both ends");
728 // Disable SRoA for any intrinsics except for lifetime invariants.
729 // FIXME: What about debug instrinsics? This matches old behavior, but
730 // doesn't make sense.
731 bool visitIntrinsicInst(IntrinsicInst &II) {
732 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
733 II.getIntrinsicID() == Intrinsic::lifetime_end) {
734 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
735 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
736 insertUse(II, Offset, Size, true);
740 return markAsEscaping(II);
743 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
744 // We consider any PHI or select that results in a direct load or store of
745 // the same offset to be a viable use for partitioning purposes. These uses
746 // are considered unsplittable and the size is the maximum loaded or stored
748 SmallPtrSet<Instruction *, 4> Visited;
749 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
750 Visited.insert(Root);
751 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
752 // If there are no loads or stores, the access is dead. We mark that as
753 // a size zero access.
756 Instruction *I, *UsedI;
757 llvm::tie(UsedI, I) = Uses.pop_back_val();
759 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
760 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
763 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
764 Value *Op = SI->getOperand(0);
767 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
771 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
772 if (!GEP->hasAllZeroIndices())
774 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
775 !isa<SelectInst>(I)) {
779 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
781 if (Visited.insert(cast<Instruction>(*UI)))
782 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
783 } while (!Uses.empty());
788 bool visitPHINode(PHINode &PN) {
789 // See if we already have computed info on this node.
790 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
792 PHIInfo.second = true;
793 insertUse(PN, Offset, PHIInfo.first);
797 // Check for an unsafe use of the PHI node.
798 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
799 return markAsEscaping(*EscapingI);
801 insertUse(PN, Offset, PHIInfo.first);
805 bool visitSelectInst(SelectInst &SI) {
806 if (Value *Result = foldSelectInst(SI)) {
808 // If the result of the constant fold will be the pointer, recurse
809 // through the select as if we had RAUW'ed it.
810 enqueueUsers(SI, Offset);
815 // See if we already have computed info on this node.
816 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
817 if (SelectInfo.first) {
818 SelectInfo.second = true;
819 insertUse(SI, Offset, SelectInfo.first);
823 // Check for an unsafe use of the PHI node.
824 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
825 return markAsEscaping(*EscapingI);
827 insertUse(SI, Offset, SelectInfo.first);
831 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
832 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
836 /// \brief Use adder for the alloca partitioning.
838 /// This class adds the uses of an alloca to all of the partitions which they
839 /// use. For splittable partitions, this can end up doing essentially a linear
840 /// walk of the partitions, but the number of steps remains bounded by the
841 /// total result instruction size:
842 /// - The number of partitions is a result of the number unsplittable
843 /// instructions using the alloca.
844 /// - The number of users of each partition is at worst the total number of
845 /// splittable instructions using the alloca.
846 /// Thus we will produce N * M instructions in the end, where N are the number
847 /// of unsplittable uses and M are the number of splittable. This visitor does
848 /// the exact same number of updates to the partitioning.
850 /// In the more common case, this visitor will leverage the fact that the
851 /// partition space is pre-sorted, and do a logarithmic search for the
852 /// partition needed, making the total visit a classical ((N + M) * log(N))
853 /// complexity operation.
854 class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
855 friend class InstVisitor<UseBuilder>;
857 /// \brief Set to de-duplicate dead instructions found in the use walk.
858 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
861 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
862 : BuilderBase<UseBuilder>(TD, AI, P) {}
864 /// \brief Run the builder over the allocation.
866 // Note that we have to re-evaluate size on each trip through the loop as
867 // the queue grows at the tail.
868 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
870 Offset = Queue[Idx].Offset;
871 this->visit(cast<Instruction>(U->getUser()));
876 void markAsDead(Instruction &I) {
877 if (VisitedDeadInsts.insert(&I))
878 P.DeadUsers.push_back(&I);
881 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
882 // If the use has a zero size or extends outside of the allocation, record
883 // it as a dead use for elimination later.
884 if (Size == 0 || (uint64_t)Offset >= AllocSize ||
885 (Offset < 0 && (uint64_t)-Offset >= Size))
886 return markAsDead(User);
888 // Clamp the start to the beginning of the allocation.
890 Size -= (uint64_t)-Offset;
894 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
896 // Clamp the end offset to the end of the allocation. Note that this is
897 // formulated to handle even the case where "BeginOffset + Size" overflows.
898 assert(AllocSize >= BeginOffset); // Established above.
899 if (Size > AllocSize - BeginOffset)
900 EndOffset = AllocSize;
902 // NB: This only works if we have zero overlapping partitions.
903 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
904 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
906 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
908 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
909 std::min(I->EndOffset, EndOffset), U);
910 P.use_push_back(I, NewPU);
911 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
912 P.PHIOrSelectOpMap[U]
913 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
917 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
918 uint64_t Size = TD.getTypeStoreSize(Ty);
920 // If this memory access can be shown to *statically* extend outside the
921 // bounds of of the allocation, it's behavior is undefined, so simply
922 // ignore it. Note that this is more strict than the generic clamping
923 // behavior of insertUse.
924 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
925 Size > (AllocSize - (uint64_t)Offset))
926 return markAsDead(I);
928 insertUse(I, Offset, Size);
931 void visitBitCastInst(BitCastInst &BC) {
933 return markAsDead(BC);
935 enqueueUsers(BC, Offset);
938 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
939 if (GEPI.use_empty())
940 return markAsDead(GEPI);
943 if (!computeConstantGEPOffset(GEPI, GEPOffset))
944 llvm_unreachable("Unable to compute constant offset for use");
946 enqueueUsers(GEPI, GEPOffset);
949 void visitLoadInst(LoadInst &LI) {
950 handleLoadOrStore(LI.getType(), LI, Offset);
953 void visitStoreInst(StoreInst &SI) {
954 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
957 void visitMemSetInst(MemSetInst &II) {
958 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
959 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
960 insertUse(II, Offset, Size);
963 void visitMemTransferInst(MemTransferInst &II) {
964 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
965 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
967 return markAsDead(II);
969 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
970 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
971 Offsets.DestBegin == Offsets.SourceBegin)
972 return markAsDead(II); // Skip identity transfers without side-effects.
974 insertUse(II, Offset, Size);
977 void visitIntrinsicInst(IntrinsicInst &II) {
978 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
979 II.getIntrinsicID() == Intrinsic::lifetime_end);
981 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
982 insertUse(II, Offset,
983 std::min(AllocSize - Offset, Length->getLimitedValue()));
986 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
987 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
989 // For PHI and select operands outside the alloca, we can't nuke the entire
990 // phi or select -- the other side might still be relevant, so we special
991 // case them here and use a separate structure to track the operands
992 // themselves which should be replaced with undef.
993 if (Offset >= AllocSize) {
994 P.DeadOperands.push_back(U);
998 insertUse(User, Offset, Size);
1000 void visitPHINode(PHINode &PN) {
1002 return markAsDead(PN);
1004 insertPHIOrSelect(PN, Offset);
1006 void visitSelectInst(SelectInst &SI) {
1008 return markAsDead(SI);
1010 if (Value *Result = foldSelectInst(SI)) {
1012 // If the result of the constant fold will be the pointer, recurse
1013 // through the select as if we had RAUW'ed it.
1014 enqueueUsers(SI, Offset);
1016 // Otherwise the operand to the select is dead, and we can replace it
1018 P.DeadOperands.push_back(U);
1023 insertPHIOrSelect(SI, Offset);
1026 /// \brief Unreachable, we've already visited the alloca once.
1027 void visitInstruction(Instruction &I) {
1028 llvm_unreachable("Unhandled instruction in use builder.");
1032 void AllocaPartitioning::splitAndMergePartitions() {
1033 size_t NumDeadPartitions = 0;
1035 // Track the range of splittable partitions that we pass when accumulating
1036 // overlapping unsplittable partitions.
1037 uint64_t SplitEndOffset = 0ull;
1039 Partition New(0ull, 0ull, false);
1041 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
1044 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
1045 assert(New.BeginOffset == New.EndOffset);
1046 New = Partitions[i];
1048 assert(New.IsSplittable);
1049 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
1051 assert(New.BeginOffset != New.EndOffset);
1053 // Scan the overlapping partitions.
1054 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
1055 // If the new partition we are forming is splittable, stop at the first
1056 // unsplittable partition.
1057 if (New.IsSplittable && !Partitions[j].IsSplittable)
1060 // Grow the new partition to include any equally splittable range. 'j' is
1061 // always equally splittable when New is splittable, but when New is not
1062 // splittable, we may subsume some (or part of some) splitable partition
1063 // without growing the new one.
1064 if (New.IsSplittable == Partitions[j].IsSplittable) {
1065 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1067 assert(!New.IsSplittable);
1068 assert(Partitions[j].IsSplittable);
1069 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1072 Partitions[j].kill();
1073 ++NumDeadPartitions;
1077 // If the new partition is splittable, chop off the end as soon as the
1078 // unsplittable subsequent partition starts and ensure we eventually cover
1079 // the splittable area.
1080 if (j != e && New.IsSplittable) {
1081 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1082 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1085 // Add the new partition if it differs from the original one and is
1086 // non-empty. We can end up with an empty partition here if it was
1087 // splittable but there is an unsplittable one that starts at the same
1089 if (New != Partitions[i]) {
1090 if (New.BeginOffset != New.EndOffset)
1091 Partitions.push_back(New);
1092 // Mark the old one for removal.
1093 Partitions[i].kill();
1094 ++NumDeadPartitions;
1097 New.BeginOffset = New.EndOffset;
1098 if (!New.IsSplittable) {
1099 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1100 if (j != e && !Partitions[j].IsSplittable)
1101 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1102 New.IsSplittable = true;
1103 // If there is a trailing splittable partition which won't be fused into
1104 // the next splittable partition go ahead and add it onto the partitions
1106 if (New.BeginOffset < New.EndOffset &&
1107 (j == e || !Partitions[j].IsSplittable ||
1108 New.EndOffset < Partitions[j].BeginOffset)) {
1109 Partitions.push_back(New);
1110 New.BeginOffset = New.EndOffset = 0ull;
1115 // Re-sort the partitions now that they have been split and merged into
1116 // disjoint set of partitions. Also remove any of the dead partitions we've
1117 // replaced in the process.
1118 std::sort(Partitions.begin(), Partitions.end());
1119 if (NumDeadPartitions) {
1120 assert(Partitions.back().isDead());
1121 assert((ptrdiff_t)NumDeadPartitions ==
1122 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1124 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1127 AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
1129 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1132 PointerEscapingInstr(0) {
1133 PartitionBuilder PB(TD, AI, *this);
1137 // Sort the uses. This arranges for the offsets to be in ascending order,
1138 // and the sizes to be in descending order.
1139 std::sort(Partitions.begin(), Partitions.end());
1141 // Remove any partitions from the back which are marked as dead.
1142 while (!Partitions.empty() && Partitions.back().isDead())
1143 Partitions.pop_back();
1145 if (Partitions.size() > 1) {
1146 // Intersect splittability for all partitions with equal offsets and sizes.
1147 // Then remove all but the first so that we have a sequence of non-equal but
1148 // potentially overlapping partitions.
1149 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1152 while (J != E && *I == *J) {
1153 I->IsSplittable &= J->IsSplittable;
1157 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1160 // Split splittable and merge unsplittable partitions into a disjoint set
1161 // of partitions over the used space of the allocation.
1162 splitAndMergePartitions();
1165 // Now build up the user lists for each of these disjoint partitions by
1166 // re-walking the recursive users of the alloca.
1167 Uses.resize(Partitions.size());
1168 UseBuilder UB(TD, AI, *this);
1172 Type *AllocaPartitioning::getCommonType(iterator I) const {
1174 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1176 continue; // Skip dead uses.
1177 if (isa<IntrinsicInst>(*UI->U->getUser()))
1179 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1183 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
1184 UserTy = LI->getType();
1185 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
1186 UserTy = SI->getValueOperand()->getType();
1188 return 0; // Bail if we have weird uses.
1191 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1192 // If the type is larger than the partition, skip it. We only encounter
1193 // this for split integer operations where we want to use the type of the
1194 // entity causing the split.
1195 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1198 // If we have found an integer type use covering the alloca, use that
1199 // regardless of the other types, as integers are often used for a "bucket
1204 if (Ty && Ty != UserTy)
1212 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1214 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1215 StringRef Indent) const {
1216 OS << Indent << "partition #" << (I - begin())
1217 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1218 << (I->IsSplittable ? " (splittable)" : "")
1219 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1223 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1224 StringRef Indent) const {
1225 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1228 continue; // Skip dead uses.
1229 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1230 << "used by: " << *UI->U->getUser() << "\n";
1231 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
1232 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1234 if (!MTO.IsSplittable)
1235 IsDest = UI->BeginOffset == MTO.DestBegin;
1237 IsDest = MTO.DestBegin != 0u;
1238 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1239 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1240 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1245 void AllocaPartitioning::print(raw_ostream &OS) const {
1246 if (PointerEscapingInstr) {
1247 OS << "No partitioning for alloca: " << AI << "\n"
1248 << " A pointer to this alloca escaped by:\n"
1249 << " " << *PointerEscapingInstr << "\n";
1253 OS << "Partitioning of alloca: " << AI << "\n";
1255 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1261 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1262 void AllocaPartitioning::dump() const { print(dbgs()); }
1264 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1268 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1270 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1271 /// the loads and stores of an alloca instruction, as well as updating its
1272 /// debug information. This is used when a domtree is unavailable and thus
1273 /// mem2reg in its full form can't be used to handle promotion of allocas to
1275 class AllocaPromoter : public LoadAndStorePromoter {
1279 SmallVector<DbgDeclareInst *, 4> DDIs;
1280 SmallVector<DbgValueInst *, 4> DVIs;
1283 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1284 AllocaInst &AI, DIBuilder &DIB)
1285 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1287 void run(const SmallVectorImpl<Instruction*> &Insts) {
1288 // Remember which alloca we're promoting (for isInstInList).
1289 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1290 for (Value::use_iterator UI = DebugNode->use_begin(),
1291 UE = DebugNode->use_end();
1293 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1294 DDIs.push_back(DDI);
1295 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1296 DVIs.push_back(DVI);
1299 LoadAndStorePromoter::run(Insts);
1300 AI.eraseFromParent();
1301 while (!DDIs.empty())
1302 DDIs.pop_back_val()->eraseFromParent();
1303 while (!DVIs.empty())
1304 DVIs.pop_back_val()->eraseFromParent();
1307 virtual bool isInstInList(Instruction *I,
1308 const SmallVectorImpl<Instruction*> &Insts) const {
1309 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1310 return LI->getOperand(0) == &AI;
1311 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1314 virtual void updateDebugInfo(Instruction *Inst) const {
1315 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1316 E = DDIs.end(); I != E; ++I) {
1317 DbgDeclareInst *DDI = *I;
1318 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1319 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1320 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1321 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1323 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1324 E = DVIs.end(); I != E; ++I) {
1325 DbgValueInst *DVI = *I;
1327 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1328 // If an argument is zero extended then use argument directly. The ZExt
1329 // may be zapped by an optimization pass in future.
1330 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1331 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1332 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1333 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1335 Arg = SI->getOperand(0);
1336 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1337 Arg = LI->getOperand(0);
1341 Instruction *DbgVal =
1342 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1344 DbgVal->setDebugLoc(DVI->getDebugLoc());
1348 } // end anon namespace
1352 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1354 /// This pass takes allocations which can be completely analyzed (that is, they
1355 /// don't escape) and tries to turn them into scalar SSA values. There are
1356 /// a few steps to this process.
1358 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1359 /// are used to try to split them into smaller allocations, ideally of
1360 /// a single scalar data type. It will split up memcpy and memset accesses
1361 /// as necessary and try to isolate invidual scalar accesses.
1362 /// 2) It will transform accesses into forms which are suitable for SSA value
1363 /// promotion. This can be replacing a memset with a scalar store of an
1364 /// integer value, or it can involve speculating operations on a PHI or
1365 /// select to be a PHI or select of the results.
1366 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1367 /// onto insert and extract operations on a vector value, and convert them to
1368 /// this form. By doing so, it will enable promotion of vector aggregates to
1369 /// SSA vector values.
1370 class SROA : public FunctionPass {
1371 const bool RequiresDomTree;
1374 const DataLayout *TD;
1377 /// \brief Worklist of alloca instructions to simplify.
1379 /// Each alloca in the function is added to this. Each new alloca formed gets
1380 /// added to it as well to recursively simplify unless that alloca can be
1381 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1382 /// the one being actively rewritten, we add it back onto the list if not
1383 /// already present to ensure it is re-visited.
1384 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1386 /// \brief A collection of instructions to delete.
1387 /// We try to batch deletions to simplify code and make things a bit more
1389 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
1391 /// \brief Post-promotion worklist.
1393 /// Sometimes we discover an alloca which has a high probability of becoming
1394 /// viable for SROA after a round of promotion takes place. In those cases,
1395 /// the alloca is enqueued here for re-processing.
1397 /// Note that we have to be very careful to clear allocas out of this list in
1398 /// the event they are deleted.
1399 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1401 /// \brief A collection of alloca instructions we can directly promote.
1402 std::vector<AllocaInst *> PromotableAllocas;
1405 SROA(bool RequiresDomTree = true)
1406 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1407 C(0), TD(0), DT(0) {
1408 initializeSROAPass(*PassRegistry::getPassRegistry());
1410 bool runOnFunction(Function &F);
1411 void getAnalysisUsage(AnalysisUsage &AU) const;
1413 const char *getPassName() const { return "SROA"; }
1417 friend class PHIOrSelectSpeculator;
1418 friend class AllocaPartitionRewriter;
1419 friend class AllocaPartitionVectorRewriter;
1421 bool rewriteAllocaPartition(AllocaInst &AI,
1422 AllocaPartitioning &P,
1423 AllocaPartitioning::iterator PI);
1424 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1425 bool runOnAlloca(AllocaInst &AI);
1426 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
1427 bool promoteAllocas(Function &F);
1433 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1434 return new SROA(RequiresDomTree);
1437 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1439 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1440 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1444 /// \brief Visitor to speculate PHIs and Selects where possible.
1445 class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1446 // Befriend the base class so it can delegate to private visit methods.
1447 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1449 const DataLayout &TD;
1450 AllocaPartitioning &P;
1454 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
1455 : TD(TD), P(P), Pass(Pass) {}
1457 /// \brief Visit the users of an alloca partition and rewrite them.
1458 void visitUsers(AllocaPartitioning::const_iterator PI) {
1459 // Note that we need to use an index here as the underlying vector of uses
1460 // may be grown during speculation. However, we never need to re-visit the
1461 // new uses, and so we can use the initial size bound.
1462 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1463 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1465 continue; // Skip dead use.
1467 visit(cast<Instruction>(PU.U->getUser()));
1472 // By default, skip this instruction.
1473 void visitInstruction(Instruction &I) {}
1475 /// PHI instructions that use an alloca and are subsequently loaded can be
1476 /// rewritten to load both input pointers in the pred blocks and then PHI the
1477 /// results, allowing the load of the alloca to be promoted.
1479 /// %P2 = phi [i32* %Alloca, i32* %Other]
1480 /// %V = load i32* %P2
1482 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1484 /// %V2 = load i32* %Other
1486 /// %V = phi [i32 %V1, i32 %V2]
1488 /// We can do this to a select if its only uses are loads and if the operands
1489 /// to the select can be loaded unconditionally.
1491 /// FIXME: This should be hoisted into a generic utility, likely in
1492 /// Transforms/Util/Local.h
1493 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1494 // For now, we can only do this promotion if the load is in the same block
1495 // as the PHI, and if there are no stores between the phi and load.
1496 // TODO: Allow recursive phi users.
1497 // TODO: Allow stores.
1498 BasicBlock *BB = PN.getParent();
1499 unsigned MaxAlign = 0;
1500 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1502 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1503 if (LI == 0 || !LI->isSimple()) return false;
1505 // For now we only allow loads in the same block as the PHI. This is
1506 // a common case that happens when instcombine merges two loads through
1508 if (LI->getParent() != BB) return false;
1510 // Ensure that there are no instructions between the PHI and the load that
1512 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1513 if (BBI->mayWriteToMemory())
1516 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1517 Loads.push_back(LI);
1520 // We can only transform this if it is safe to push the loads into the
1521 // predecessor blocks. The only thing to watch out for is that we can't put
1522 // a possibly trapping load in the predecessor if it is a critical edge.
1523 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1525 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1526 Value *InVal = PN.getIncomingValue(Idx);
1528 // If the value is produced by the terminator of the predecessor (an
1529 // invoke) or it has side-effects, there is no valid place to put a load
1530 // in the predecessor.
1531 if (TI == InVal || TI->mayHaveSideEffects())
1534 // If the predecessor has a single successor, then the edge isn't
1536 if (TI->getNumSuccessors() == 1)
1539 // If this pointer is always safe to load, or if we can prove that there
1540 // is already a load in the block, then we can move the load to the pred
1542 if (InVal->isDereferenceablePointer() ||
1543 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1552 void visitPHINode(PHINode &PN) {
1553 DEBUG(dbgs() << " original: " << PN << "\n");
1555 SmallVector<LoadInst *, 4> Loads;
1556 if (!isSafePHIToSpeculate(PN, Loads))
1559 assert(!Loads.empty());
1561 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1562 IRBuilder<> PHIBuilder(&PN);
1563 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1564 PN.getName() + ".sroa.speculated");
1566 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1567 // matter which one we get and if any differ, it doesn't matter.
1568 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1569 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1570 unsigned Align = SomeLoad->getAlignment();
1572 // Rewrite all loads of the PN to use the new PHI.
1574 LoadInst *LI = Loads.pop_back_val();
1575 LI->replaceAllUsesWith(NewPN);
1576 Pass.DeadInsts.insert(LI);
1577 } while (!Loads.empty());
1579 // Inject loads into all of the pred blocks.
1580 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1581 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1582 TerminatorInst *TI = Pred->getTerminator();
1583 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1584 Value *InVal = PN.getIncomingValue(Idx);
1585 IRBuilder<> PredBuilder(TI);
1588 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1590 ++NumLoadsSpeculated;
1591 Load->setAlignment(Align);
1593 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1594 NewPN->addIncoming(Load, Pred);
1596 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1598 // No uses to rewrite.
1601 // Try to lookup and rewrite any partition uses corresponding to this phi
1603 AllocaPartitioning::iterator PI
1604 = P.findPartitionForPHIOrSelectOperand(InUse);
1608 // Replace the Use in the PartitionUse for this operand with the Use
1610 AllocaPartitioning::use_iterator UI
1611 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1612 assert(isa<PHINode>(*UI->U->getUser()));
1613 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1615 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1618 /// Select instructions that use an alloca and are subsequently loaded can be
1619 /// rewritten to load both input pointers and then select between the result,
1620 /// allowing the load of the alloca to be promoted.
1622 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1623 /// %V = load i32* %P2
1625 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1626 /// %V2 = load i32* %Other
1627 /// %V = select i1 %cond, i32 %V1, i32 %V2
1629 /// We can do this to a select if its only uses are loads and if the operand
1630 /// to the select can be loaded unconditionally.
1631 bool isSafeSelectToSpeculate(SelectInst &SI,
1632 SmallVectorImpl<LoadInst *> &Loads) {
1633 Value *TValue = SI.getTrueValue();
1634 Value *FValue = SI.getFalseValue();
1635 bool TDerefable = TValue->isDereferenceablePointer();
1636 bool FDerefable = FValue->isDereferenceablePointer();
1638 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1640 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1641 if (LI == 0 || !LI->isSimple()) return false;
1643 // Both operands to the select need to be dereferencable, either
1644 // absolutely (e.g. allocas) or at this point because we can see other
1646 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1647 LI->getAlignment(), &TD))
1649 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1650 LI->getAlignment(), &TD))
1652 Loads.push_back(LI);
1658 void visitSelectInst(SelectInst &SI) {
1659 DEBUG(dbgs() << " original: " << SI << "\n");
1660 IRBuilder<> IRB(&SI);
1662 // If the select isn't safe to speculate, just use simple logic to emit it.
1663 SmallVector<LoadInst *, 4> Loads;
1664 if (!isSafeSelectToSpeculate(SI, Loads))
1667 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1668 AllocaPartitioning::iterator PIs[2];
1669 AllocaPartitioning::PartitionUse PUs[2];
1670 for (unsigned i = 0, e = 2; i != e; ++i) {
1671 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1672 if (PIs[i] != P.end()) {
1673 // If the pointer is within the partitioning, remove the select from
1674 // its uses. We'll add in the new loads below.
1675 AllocaPartitioning::use_iterator UI
1676 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1678 // Clear out the use here so that the offsets into the use list remain
1679 // stable but this use is ignored when rewriting.
1684 Value *TV = SI.getTrueValue();
1685 Value *FV = SI.getFalseValue();
1686 // Replace the loads of the select with a select of two loads.
1687 while (!Loads.empty()) {
1688 LoadInst *LI = Loads.pop_back_val();
1690 IRB.SetInsertPoint(LI);
1692 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1694 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1695 NumLoadsSpeculated += 2;
1697 // Transfer alignment and TBAA info if present.
1698 TL->setAlignment(LI->getAlignment());
1699 FL->setAlignment(LI->getAlignment());
1700 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1701 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1702 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1705 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1706 LI->getName() + ".sroa.speculated");
1708 LoadInst *Loads[2] = { TL, FL };
1709 for (unsigned i = 0, e = 2; i != e; ++i) {
1710 if (PIs[i] != P.end()) {
1711 Use *LoadUse = &Loads[i]->getOperandUse(0);
1712 assert(PUs[i].U->get() == LoadUse->get());
1714 P.use_push_back(PIs[i], PUs[i]);
1718 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1719 LI->replaceAllUsesWith(V);
1720 Pass.DeadInsts.insert(LI);
1726 /// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1728 /// If the provided GEP is all-constant, the total byte offset formed by the
1729 /// GEP is computed and Offset is set to it. If the GEP has any non-constant
1730 /// operands, the function returns false and the value of Offset is unmodified.
1731 static bool accumulateGEPOffsets(const DataLayout &TD, GEPOperator &GEP,
1733 APInt GEPOffset(Offset.getBitWidth(), 0);
1734 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1735 GTI != GTE; ++GTI) {
1736 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1739 if (OpC->isZero()) continue;
1741 // Handle a struct index, which adds its field offset to the pointer.
1742 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1743 unsigned ElementIdx = OpC->getZExtValue();
1744 const StructLayout *SL = TD.getStructLayout(STy);
1745 GEPOffset += APInt(Offset.getBitWidth(),
1746 SL->getElementOffset(ElementIdx));
1750 APInt TypeSize(Offset.getBitWidth(),
1751 TD.getTypeAllocSize(GTI.getIndexedType()));
1752 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1753 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1754 "vector element size is not a multiple of 8, cannot GEP over it");
1755 TypeSize = VTy->getScalarSizeInBits() / 8;
1758 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1764 /// \brief Build a GEP out of a base pointer and indices.
1766 /// This will return the BasePtr if that is valid, or build a new GEP
1767 /// instruction using the IRBuilder if GEP-ing is needed.
1768 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1769 SmallVectorImpl<Value *> &Indices,
1770 const Twine &Prefix) {
1771 if (Indices.empty())
1774 // A single zero index is a no-op, so check for this and avoid building a GEP
1776 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1779 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1782 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1783 /// TargetTy without changing the offset of the pointer.
1785 /// This routine assumes we've already established a properly offset GEP with
1786 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1787 /// zero-indices down through type layers until we find one the same as
1788 /// TargetTy. If we can't find one with the same type, we at least try to use
1789 /// one with the same size. If none of that works, we just produce the GEP as
1790 /// indicated by Indices to have the correct offset.
1791 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
1792 Value *BasePtr, Type *Ty, Type *TargetTy,
1793 SmallVectorImpl<Value *> &Indices,
1794 const Twine &Prefix) {
1796 return buildGEP(IRB, BasePtr, Indices, Prefix);
1798 // See if we can descend into a struct and locate a field with the correct
1800 unsigned NumLayers = 0;
1801 Type *ElementTy = Ty;
1803 if (ElementTy->isPointerTy())
1805 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1806 ElementTy = SeqTy->getElementType();
1807 // Note that we use the default address space as this index is over an
1808 // array or a vector, not a pointer.
1809 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
1810 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1811 if (STy->element_begin() == STy->element_end())
1812 break; // Nothing left to descend into.
1813 ElementTy = *STy->element_begin();
1814 Indices.push_back(IRB.getInt32(0));
1819 } while (ElementTy != TargetTy);
1820 if (ElementTy != TargetTy)
1821 Indices.erase(Indices.end() - NumLayers, Indices.end());
1823 return buildGEP(IRB, BasePtr, Indices, Prefix);
1826 /// \brief Recursively compute indices for a natural GEP.
1828 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1829 /// element types adding appropriate indices for the GEP.
1830 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
1831 Value *Ptr, Type *Ty, APInt &Offset,
1833 SmallVectorImpl<Value *> &Indices,
1834 const Twine &Prefix) {
1836 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1838 // We can't recurse through pointer types.
1839 if (Ty->isPointerTy())
1842 // We try to analyze GEPs over vectors here, but note that these GEPs are
1843 // extremely poorly defined currently. The long-term goal is to remove GEPing
1844 // over a vector from the IR completely.
1845 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1846 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1847 if (ElementSizeInBits % 8)
1848 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1849 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1850 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1851 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1853 Offset -= NumSkippedElements * ElementSize;
1854 Indices.push_back(IRB.getInt(NumSkippedElements));
1855 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1856 Offset, TargetTy, Indices, Prefix);
1859 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1860 Type *ElementTy = ArrTy->getElementType();
1861 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1862 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1863 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1866 Offset -= NumSkippedElements * ElementSize;
1867 Indices.push_back(IRB.getInt(NumSkippedElements));
1868 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1872 StructType *STy = dyn_cast<StructType>(Ty);
1876 const StructLayout *SL = TD.getStructLayout(STy);
1877 uint64_t StructOffset = Offset.getZExtValue();
1878 if (StructOffset >= SL->getSizeInBytes())
1880 unsigned Index = SL->getElementContainingOffset(StructOffset);
1881 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1882 Type *ElementTy = STy->getElementType(Index);
1883 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1884 return 0; // The offset points into alignment padding.
1886 Indices.push_back(IRB.getInt32(Index));
1887 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1891 /// \brief Get a natural GEP from a base pointer to a particular offset and
1892 /// resulting in a particular type.
1894 /// The goal is to produce a "natural" looking GEP that works with the existing
1895 /// composite types to arrive at the appropriate offset and element type for
1896 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1897 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1898 /// Indices, and setting Ty to the result subtype.
1900 /// If no natural GEP can be constructed, this function returns null.
1901 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
1902 Value *Ptr, APInt Offset, Type *TargetTy,
1903 SmallVectorImpl<Value *> &Indices,
1904 const Twine &Prefix) {
1905 PointerType *Ty = cast<PointerType>(Ptr->getType());
1907 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1909 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1912 Type *ElementTy = Ty->getElementType();
1913 if (!ElementTy->isSized())
1914 return 0; // We can't GEP through an unsized element.
1915 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1916 if (ElementSize == 0)
1917 return 0; // Zero-length arrays can't help us build a natural GEP.
1918 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1920 Offset -= NumSkippedElements * ElementSize;
1921 Indices.push_back(IRB.getInt(NumSkippedElements));
1922 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1926 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1927 /// resulting pointer has PointerTy.
1929 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1930 /// and produces the pointer type desired. Where it cannot, it will try to use
1931 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1932 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1933 /// bitcast to the type.
1935 /// The strategy for finding the more natural GEPs is to peel off layers of the
1936 /// pointer, walking back through bit casts and GEPs, searching for a base
1937 /// pointer from which we can compute a natural GEP with the desired
1938 /// properities. The algorithm tries to fold as many constant indices into
1939 /// a single GEP as possible, thus making each GEP more independent of the
1940 /// surrounding code.
1941 static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
1942 Value *Ptr, APInt Offset, Type *PointerTy,
1943 const Twine &Prefix) {
1944 // Even though we don't look through PHI nodes, we could be called on an
1945 // instruction in an unreachable block, which may be on a cycle.
1946 SmallPtrSet<Value *, 4> Visited;
1947 Visited.insert(Ptr);
1948 SmallVector<Value *, 4> Indices;
1950 // We may end up computing an offset pointer that has the wrong type. If we
1951 // never are able to compute one directly that has the correct type, we'll
1952 // fall back to it, so keep it around here.
1953 Value *OffsetPtr = 0;
1955 // Remember any i8 pointer we come across to re-use if we need to do a raw
1958 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1960 Type *TargetTy = PointerTy->getPointerElementType();
1963 // First fold any existing GEPs into the offset.
1964 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1965 APInt GEPOffset(Offset.getBitWidth(), 0);
1966 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1968 Offset += GEPOffset;
1969 Ptr = GEP->getPointerOperand();
1970 if (!Visited.insert(Ptr))
1974 // See if we can perform a natural GEP here.
1976 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1978 if (P->getType() == PointerTy) {
1979 // Zap any offset pointer that we ended up computing in previous rounds.
1980 if (OffsetPtr && OffsetPtr->use_empty())
1981 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1982 I->eraseFromParent();
1990 // Stash this pointer if we've found an i8*.
1991 if (Ptr->getType()->isIntegerTy(8)) {
1993 Int8PtrOffset = Offset;
1996 // Peel off a layer of the pointer and update the offset appropriately.
1997 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1998 Ptr = cast<Operator>(Ptr)->getOperand(0);
1999 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2000 if (GA->mayBeOverridden())
2002 Ptr = GA->getAliasee();
2006 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
2007 } while (Visited.insert(Ptr));
2011 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
2012 Prefix + ".raw_cast");
2013 Int8PtrOffset = Offset;
2016 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
2017 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
2018 Prefix + ".raw_idx");
2022 // On the off chance we were targeting i8*, guard the bitcast here.
2023 if (Ptr->getType() != PointerTy)
2024 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
2029 /// \brief Test whether we can convert a value from the old to the new type.
2031 /// This predicate should be used to guard calls to convertValue in order to
2032 /// ensure that we only try to convert viable values. The strategy is that we
2033 /// will peel off single element struct and array wrappings to get to an
2034 /// underlying value, and convert that value.
2035 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
2038 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
2040 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
2043 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
2044 if (NewTy->isPointerTy() && OldTy->isPointerTy())
2046 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
2054 /// \brief Generic routine to convert an SSA value to a value of a different
2057 /// This will try various different casting techniques, such as bitcasts,
2058 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
2059 /// two types for viability with this routine.
2060 static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2062 assert(canConvertValue(DL, V->getType(), Ty) &&
2063 "Value not convertable to type");
2064 if (V->getType() == Ty)
2066 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2067 return IRB.CreateIntToPtr(V, Ty);
2068 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2069 return IRB.CreatePtrToInt(V, Ty);
2071 return IRB.CreateBitCast(V, Ty);
2074 /// \brief Test whether the given alloca partition can be promoted to a vector.
2076 /// This is a quick test to check whether we can rewrite a particular alloca
2077 /// partition (and its newly formed alloca) into a vector alloca with only
2078 /// whole-vector loads and stores such that it could be promoted to a vector
2079 /// SSA value. We only can ensure this for a limited set of operations, and we
2080 /// don't want to do the rewrites unless we are confident that the result will
2081 /// be promotable, so we have an early test here.
2082 static bool isVectorPromotionViable(const DataLayout &TD,
2084 AllocaPartitioning &P,
2085 uint64_t PartitionBeginOffset,
2086 uint64_t PartitionEndOffset,
2087 AllocaPartitioning::const_use_iterator I,
2088 AllocaPartitioning::const_use_iterator E) {
2089 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2093 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
2094 uint64_t ElementSize = Ty->getScalarSizeInBits();
2096 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2097 // that aren't byte sized.
2098 if (ElementSize % 8)
2100 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
2104 for (; I != E; ++I) {
2106 continue; // Skip dead use.
2108 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2109 uint64_t BeginIndex = BeginOffset / ElementSize;
2110 if (BeginIndex * ElementSize != BeginOffset ||
2111 BeginIndex >= Ty->getNumElements())
2113 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2114 uint64_t EndIndex = EndOffset / ElementSize;
2115 if (EndIndex * ElementSize != EndOffset ||
2116 EndIndex > Ty->getNumElements())
2119 // FIXME: We should build shuffle vector instructions to handle
2120 // non-element-sized accesses. See PR14055 for an example of where this
2122 if ((EndOffset - BeginOffset) != ElementSize &&
2123 (EndOffset - BeginOffset) != VecSize)
2126 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
2127 if (MI->isVolatile())
2129 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
2130 const AllocaPartitioning::MemTransferOffsets &MTO
2131 = P.getMemTransferOffsets(*MTI);
2132 if (!MTO.IsSplittable)
2135 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
2136 // Disable vector promotion when there are loads or stores of an FCA.
2138 } else if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
2139 if (LI->isVolatile())
2141 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
2142 if (SI->isVolatile())
2151 /// \brief Test whether the given alloca partition's integer operations can be
2152 /// widened to promotable ones.
2154 /// This is a quick test to check whether we can rewrite the integer loads and
2155 /// stores to a particular alloca into wider loads and stores and be able to
2156 /// promote the resulting alloca.
2157 static bool isIntegerWideningViable(const DataLayout &TD,
2159 uint64_t AllocBeginOffset,
2160 AllocaPartitioning &P,
2161 AllocaPartitioning::const_use_iterator I,
2162 AllocaPartitioning::const_use_iterator E) {
2163 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
2165 // Don't try to handle allocas with bit-padding.
2166 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
2169 // We need to ensure that an integer type with the appropriate bitwidth can
2170 // be converted to the alloca type, whatever that is. We don't want to force
2171 // the alloca itself to have an integer type if there is a more suitable one.
2172 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2173 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2174 !canConvertValue(TD, IntTy, AllocaTy))
2177 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2179 // Check the uses to ensure the uses are (likely) promoteable integer uses.
2180 // Also ensure that the alloca has a covering load or store. We don't want
2181 // to widen the integer operotains only to fail to promote due to some other
2182 // unsplittable entry (which we may make splittable later).
2183 bool WholeAllocaOp = false;
2184 for (; I != E; ++I) {
2186 continue; // Skip dead use.
2188 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2189 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2191 // We can't reasonably handle cases where the load or store extends past
2192 // the end of the aloca's type and into its padding.
2196 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
2197 if (LI->isVolatile())
2199 if (RelBegin == 0 && RelEnd == Size)
2200 WholeAllocaOp = true;
2201 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2202 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2206 // Non-integer loads need to be convertible from the alloca type so that
2207 // they are promotable.
2208 if (RelBegin != 0 || RelEnd != Size ||
2209 !canConvertValue(TD, AllocaTy, LI->getType()))
2211 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
2212 Type *ValueTy = SI->getValueOperand()->getType();
2213 if (SI->isVolatile())
2215 if (RelBegin == 0 && RelEnd == Size)
2216 WholeAllocaOp = true;
2217 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2218 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2222 // Non-integer stores need to be convertible to the alloca type so that
2223 // they are promotable.
2224 if (RelBegin != 0 || RelEnd != Size ||
2225 !canConvertValue(TD, ValueTy, AllocaTy))
2227 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
2228 if (MI->isVolatile())
2230 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
2231 const AllocaPartitioning::MemTransferOffsets &MTO
2232 = P.getMemTransferOffsets(*MTI);
2233 if (!MTO.IsSplittable)
2236 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->U->getUser())) {
2237 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2238 II->getIntrinsicID() != Intrinsic::lifetime_end)
2244 return WholeAllocaOp;
2247 static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2248 IntegerType *Ty, uint64_t Offset,
2249 const Twine &Name) {
2250 DEBUG(dbgs() << " start: " << *V << "\n");
2251 IntegerType *IntTy = cast<IntegerType>(V->getType());
2252 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2253 "Element extends past full value");
2254 uint64_t ShAmt = 8*Offset;
2255 if (DL.isBigEndian())
2256 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2258 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2259 DEBUG(dbgs() << " shifted: " << *V << "\n");
2261 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2262 "Cannot extract to a larger integer!");
2264 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2265 DEBUG(dbgs() << " trunced: " << *V << "\n");
2270 static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2271 Value *V, uint64_t Offset, const Twine &Name) {
2272 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2273 IntegerType *Ty = cast<IntegerType>(V->getType());
2274 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2275 "Cannot insert a larger integer!");
2276 DEBUG(dbgs() << " start: " << *V << "\n");
2278 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2279 DEBUG(dbgs() << " extended: " << *V << "\n");
2281 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2282 "Element store outside of alloca store");
2283 uint64_t ShAmt = 8*Offset;
2284 if (DL.isBigEndian())
2285 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2287 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2288 DEBUG(dbgs() << " shifted: " << *V << "\n");
2291 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2292 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2293 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2294 DEBUG(dbgs() << " masked: " << *Old << "\n");
2295 V = IRB.CreateOr(Old, V, Name + ".insert");
2296 DEBUG(dbgs() << " inserted: " << *V << "\n");
2302 /// \brief Visitor to rewrite instructions using a partition of an alloca to
2303 /// use a new alloca.
2305 /// Also implements the rewriting to vector-based accesses when the partition
2306 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2308 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2310 // Befriend the base class so it can delegate to private visit methods.
2311 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2313 const DataLayout &TD;
2314 AllocaPartitioning &P;
2316 AllocaInst &OldAI, &NewAI;
2317 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2320 // If we are rewriting an alloca partition which can be written as pure
2321 // vector operations, we stash extra information here. When VecTy is
2322 // non-null, we have some strict guarantees about the rewriten alloca:
2323 // - The new alloca is exactly the size of the vector type here.
2324 // - The accesses all either map to the entire vector or to a single
2326 // - The set of accessing instructions is only one of those handled above
2327 // in isVectorPromotionViable. Generally these are the same access kinds
2328 // which are promotable via mem2reg.
2331 uint64_t ElementSize;
2333 // This is a convenience and flag variable that will be null unless the new
2334 // alloca's integer operations should be widened to this integer type due to
2335 // passing isIntegerWideningViable above. If it is non-null, the desired
2336 // integer type will be stored here for easy access during rewriting.
2339 // The offset of the partition user currently being rewritten.
2340 uint64_t BeginOffset, EndOffset;
2342 Instruction *OldPtr;
2344 // The name prefix to use when rewriting instructions for this alloca.
2345 std::string NamePrefix;
2348 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
2349 AllocaPartitioning::iterator PI,
2350 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2351 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2352 : TD(TD), P(P), Pass(Pass),
2353 OldAI(OldAI), NewAI(NewAI),
2354 NewAllocaBeginOffset(NewBeginOffset),
2355 NewAllocaEndOffset(NewEndOffset),
2356 NewAllocaTy(NewAI.getAllocatedType()),
2357 VecTy(), ElementTy(), ElementSize(), IntTy(),
2358 BeginOffset(), EndOffset() {
2361 /// \brief Visit the users of the alloca partition and rewrite them.
2362 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2363 AllocaPartitioning::const_use_iterator E) {
2364 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2365 NewAllocaBeginOffset, NewAllocaEndOffset,
2368 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2369 ElementTy = VecTy->getElementType();
2370 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2371 "Only multiple-of-8 sized vector elements are viable");
2372 ElementSize = VecTy->getScalarSizeInBits() / 8;
2373 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2374 NewAllocaBeginOffset, P, I, E)) {
2375 IntTy = Type::getIntNTy(NewAI.getContext(),
2376 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
2378 bool CanSROA = true;
2379 for (; I != E; ++I) {
2381 continue; // Skip dead uses.
2382 BeginOffset = I->BeginOffset;
2383 EndOffset = I->EndOffset;
2385 OldPtr = cast<Instruction>(I->U->get());
2386 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
2387 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
2403 // Every instruction which can end up as a user must have a rewrite rule.
2404 bool visitInstruction(Instruction &I) {
2405 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2406 llvm_unreachable("No rewrite rule for this instruction!");
2409 Twine getName(const Twine &Suffix) {
2410 return NamePrefix + Suffix;
2413 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2414 assert(BeginOffset >= NewAllocaBeginOffset);
2415 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
2416 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2419 /// \brief Compute suitable alignment to access an offset into the new alloca.
2420 unsigned getOffsetAlign(uint64_t Offset) {
2421 unsigned NewAIAlign = NewAI.getAlignment();
2423 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2424 return MinAlign(NewAIAlign, Offset);
2427 /// \brief Compute suitable alignment to access this partition of the new
2429 unsigned getPartitionAlign() {
2430 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
2433 /// \brief Compute suitable alignment to access a type at an offset of the
2436 /// \returns zero if the type's ABI alignment is a suitable alignment,
2437 /// otherwise returns the maximal suitable alignment.
2438 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2439 unsigned Align = getOffsetAlign(Offset);
2440 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2443 /// \brief Compute suitable alignment to access a type at the beginning of
2444 /// this partition of the new alloca.
2446 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2447 unsigned getPartitionTypeAlign(Type *Ty) {
2448 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
2451 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
2452 assert(VecTy && "Can only call getIndex when rewriting a vector");
2453 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2454 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2455 uint32_t Index = RelOffset / ElementSize;
2456 assert(Index * ElementSize == RelOffset);
2457 return IRB.getInt32(Index);
2460 void deleteIfTriviallyDead(Value *V) {
2461 Instruction *I = cast<Instruction>(V);
2462 if (isInstructionTriviallyDead(I))
2463 Pass.DeadInsts.insert(I);
2466 Value *rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2467 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2469 if (LI.getType() == VecTy->getElementType() ||
2470 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2471 V = IRB.CreateExtractElement(V, getIndex(IRB, BeginOffset),
2472 getName(".extract"));
2477 Value *rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
2478 assert(IntTy && "We cannot insert an integer to the alloca");
2479 assert(!LI.isVolatile());
2480 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2482 V = convertValue(TD, IRB, V, IntTy);
2483 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2484 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2485 if (Offset > 0 || EndOffset < NewAllocaEndOffset)
2486 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2487 getName(".extract"));
2491 bool visitLoadInst(LoadInst &LI) {
2492 DEBUG(dbgs() << " original: " << LI << "\n");
2493 Value *OldOp = LI.getOperand(0);
2494 assert(OldOp == OldPtr);
2495 IRBuilder<> IRB(&LI);
2497 uint64_t Size = EndOffset - BeginOffset;
2498 bool IsSplitIntLoad = Size < TD.getTypeStoreSize(LI.getType());
2500 // If this memory access can be shown to *statically* extend outside the
2501 // bounds of the original allocation it's behavior is undefined. Rather
2502 // than trying to transform it, just replace it with undef.
2503 // FIXME: We should do something more clever for functions being
2504 // instrumented by asan.
2505 // FIXME: Eventually, once ASan and friends can flush out bugs here, this
2506 // should be transformed to a load of null making it unreachable.
2507 uint64_t OldAllocSize = TD.getTypeAllocSize(OldAI.getAllocatedType());
2508 if (TD.getTypeStoreSize(LI.getType()) > OldAllocSize) {
2509 LI.replaceAllUsesWith(UndefValue::get(LI.getType()));
2510 Pass.DeadInsts.insert(&LI);
2511 deleteIfTriviallyDead(OldOp);
2512 DEBUG(dbgs() << " to: undef!!\n");
2516 Type *TargetTy = IsSplitIntLoad ? Type::getIntNTy(LI.getContext(), Size * 8)
2518 bool IsPtrAdjusted = false;
2521 V = rewriteVectorizedLoadInst(IRB, LI, OldOp);
2522 } else if (IntTy && LI.getType()->isIntegerTy()) {
2523 V = rewriteIntegerLoad(IRB, LI);
2524 } else if (BeginOffset == NewAllocaBeginOffset &&
2525 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2526 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2527 LI.isVolatile(), getName(".load"));
2529 Type *LTy = TargetTy->getPointerTo();
2530 V = IRB.CreateAlignedLoad(getAdjustedAllocaPtr(IRB, LTy),
2531 getPartitionTypeAlign(TargetTy),
2532 LI.isVolatile(), getName(".load"));
2533 IsPtrAdjusted = true;
2535 V = convertValue(TD, IRB, V, TargetTy);
2537 if (IsSplitIntLoad) {
2538 assert(!LI.isVolatile());
2539 assert(LI.getType()->isIntegerTy() &&
2540 "Only integer type loads and stores are split");
2541 assert(LI.getType()->getIntegerBitWidth() ==
2542 TD.getTypeStoreSizeInBits(LI.getType()) &&
2543 "Non-byte-multiple bit width");
2544 assert(LI.getType()->getIntegerBitWidth() ==
2545 TD.getTypeAllocSizeInBits(OldAI.getAllocatedType()) &&
2546 "Only alloca-wide loads can be split and recomposed");
2547 // Move the insertion point just past the load so that we can refer to it.
2548 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
2549 // Create a placeholder value with the same type as LI to use as the
2550 // basis for the new value. This allows us to replace the uses of LI with
2551 // the computed value, and then replace the placeholder with LI, leaving
2552 // LI only used for this computation.
2554 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2555 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2556 getName(".insert"));
2557 LI.replaceAllUsesWith(V);
2558 Placeholder->replaceAllUsesWith(&LI);
2561 LI.replaceAllUsesWith(V);
2564 Pass.DeadInsts.insert(&LI);
2565 deleteIfTriviallyDead(OldOp);
2566 DEBUG(dbgs() << " to: " << *V << "\n");
2567 return !LI.isVolatile() && !IsPtrAdjusted;
2570 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, Value *V,
2571 StoreInst &SI, Value *OldOp) {
2572 if (V->getType() == ElementTy ||
2573 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2574 if (V->getType() != ElementTy)
2575 V = convertValue(TD, IRB, V, ElementTy);
2576 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2578 V = IRB.CreateInsertElement(LI, V, getIndex(IRB, BeginOffset),
2579 getName(".insert"));
2580 } else if (V->getType() != VecTy) {
2581 V = convertValue(TD, IRB, V, VecTy);
2583 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2584 Pass.DeadInsts.insert(&SI);
2587 DEBUG(dbgs() << " to: " << *Store << "\n");
2591 bool rewriteIntegerStore(IRBuilder<> &IRB, Value *V, StoreInst &SI) {
2592 assert(IntTy && "We cannot extract an integer from the alloca");
2593 assert(!SI.isVolatile());
2594 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2595 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2596 getName(".oldload"));
2597 Old = convertValue(TD, IRB, Old, IntTy);
2598 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2599 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2600 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2601 getName(".insert"));
2603 V = convertValue(TD, IRB, V, NewAllocaTy);
2604 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2605 Pass.DeadInsts.insert(&SI);
2607 DEBUG(dbgs() << " to: " << *Store << "\n");
2611 bool visitStoreInst(StoreInst &SI) {
2612 DEBUG(dbgs() << " original: " << SI << "\n");
2613 Value *OldOp = SI.getOperand(1);
2614 assert(OldOp == OldPtr);
2615 IRBuilder<> IRB(&SI);
2617 Value *V = SI.getValueOperand();
2619 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2620 // alloca that should be re-examined after promoting this alloca.
2621 if (V->getType()->isPointerTy())
2622 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2623 Pass.PostPromotionWorklist.insert(AI);
2625 uint64_t Size = EndOffset - BeginOffset;
2626 if (Size < TD.getTypeStoreSize(V->getType())) {
2627 assert(!SI.isVolatile());
2628 assert(V->getType()->isIntegerTy() &&
2629 "Only integer type loads and stores are split");
2630 assert(V->getType()->getIntegerBitWidth() ==
2631 TD.getTypeStoreSizeInBits(V->getType()) &&
2632 "Non-byte-multiple bit width");
2633 assert(V->getType()->getIntegerBitWidth() ==
2634 TD.getTypeSizeInBits(OldAI.getAllocatedType()) &&
2635 "Only alloca-wide stores can be split and recomposed");
2636 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2637 V = extractInteger(TD, IRB, V, NarrowTy, BeginOffset,
2638 getName(".extract"));
2642 return rewriteVectorizedStoreInst(IRB, V, SI, OldOp);
2643 if (IntTy && V->getType()->isIntegerTy())
2644 return rewriteIntegerStore(IRB, V, SI);
2647 if (BeginOffset == NewAllocaBeginOffset &&
2648 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2649 V = convertValue(TD, IRB, V, NewAllocaTy);
2650 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2653 Value *NewPtr = getAdjustedAllocaPtr(IRB, V->getType()->getPointerTo());
2654 NewSI = IRB.CreateAlignedStore(V, NewPtr,
2655 getPartitionTypeAlign(V->getType()),
2659 Pass.DeadInsts.insert(&SI);
2660 deleteIfTriviallyDead(OldOp);
2662 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2663 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2666 bool visitMemSetInst(MemSetInst &II) {
2667 DEBUG(dbgs() << " original: " << II << "\n");
2668 IRBuilder<> IRB(&II);
2669 assert(II.getRawDest() == OldPtr);
2671 // If the memset has a variable size, it cannot be split, just adjust the
2672 // pointer to the new alloca.
2673 if (!isa<Constant>(II.getLength())) {
2674 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2675 Type *CstTy = II.getAlignmentCst()->getType();
2676 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
2678 deleteIfTriviallyDead(OldPtr);
2682 // Record this instruction for deletion.
2683 Pass.DeadInsts.insert(&II);
2685 Type *AllocaTy = NewAI.getAllocatedType();
2686 Type *ScalarTy = AllocaTy->getScalarType();
2688 // If this doesn't map cleanly onto the alloca type, and that type isn't
2689 // a single value type, just emit a memset.
2690 if (!VecTy && !IntTy &&
2691 (BeginOffset != NewAllocaBeginOffset ||
2692 EndOffset != NewAllocaEndOffset ||
2693 !AllocaTy->isSingleValueType() ||
2694 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
2695 Type *SizeTy = II.getLength()->getType();
2696 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2698 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2699 II.getRawDest()->getType()),
2700 II.getValue(), Size, getPartitionAlign(),
2703 DEBUG(dbgs() << " to: " << *New << "\n");
2707 // If we can represent this as a simple value, we have to build the actual
2708 // value to store, which requires expanding the byte present in memset to
2709 // a sensible representation for the alloca type. This is essentially
2710 // splatting the byte to a sufficiently wide integer, bitcasting to the
2711 // desired scalar type, and splatting it across any desired vector type.
2712 uint64_t Size = EndOffset - BeginOffset;
2713 Value *V = II.getValue();
2714 IntegerType *VTy = cast<IntegerType>(V->getType());
2715 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2716 if (Size*8 > VTy->getBitWidth())
2717 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
2718 ConstantExpr::getUDiv(
2719 Constant::getAllOnesValue(SplatIntTy),
2720 ConstantExpr::getZExt(
2721 Constant::getAllOnesValue(V->getType()),
2723 getName(".isplat"));
2725 // If this is an element-wide memset of a vectorizable alloca, insert it.
2726 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2727 EndOffset < NewAllocaEndOffset)) {
2728 if (V->getType() != ScalarTy)
2729 V = convertValue(TD, IRB, V, ScalarTy);
2730 StoreInst *Store = IRB.CreateAlignedStore(
2731 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2732 NewAI.getAlignment(),
2734 V, getIndex(IRB, BeginOffset),
2735 getName(".insert")),
2736 &NewAI, NewAI.getAlignment());
2738 DEBUG(dbgs() << " to: " << *Store << "\n");
2742 // If this is a memset on an alloca where we can widen stores, insert the
2744 if (IntTy && (BeginOffset > NewAllocaBeginOffset ||
2745 EndOffset < NewAllocaEndOffset)) {
2746 assert(!II.isVolatile());
2747 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2748 getName(".oldload"));
2749 Old = convertValue(TD, IRB, Old, IntTy);
2750 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2751 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2752 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
2755 if (V->getType() != AllocaTy)
2756 V = convertValue(TD, IRB, V, AllocaTy);
2758 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2761 DEBUG(dbgs() << " to: " << *New << "\n");
2762 return !II.isVolatile();
2765 bool visitMemTransferInst(MemTransferInst &II) {
2766 // Rewriting of memory transfer instructions can be a bit tricky. We break
2767 // them into two categories: split intrinsics and unsplit intrinsics.
2769 DEBUG(dbgs() << " original: " << II << "\n");
2770 IRBuilder<> IRB(&II);
2772 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2773 bool IsDest = II.getRawDest() == OldPtr;
2775 const AllocaPartitioning::MemTransferOffsets &MTO
2776 = P.getMemTransferOffsets(II);
2778 // Compute the relative offset within the transfer.
2779 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2780 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2781 : MTO.SourceBegin));
2783 unsigned Align = II.getAlignment();
2785 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2786 MinAlign(II.getAlignment(), getPartitionAlign()));
2788 // For unsplit intrinsics, we simply modify the source and destination
2789 // pointers in place. This isn't just an optimization, it is a matter of
2790 // correctness. With unsplit intrinsics we may be dealing with transfers
2791 // within a single alloca before SROA ran, or with transfers that have
2792 // a variable length. We may also be dealing with memmove instead of
2793 // memcpy, and so simply updating the pointers is the necessary for us to
2794 // update both source and dest of a single call.
2795 if (!MTO.IsSplittable) {
2796 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2798 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2800 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2802 Type *CstTy = II.getAlignmentCst()->getType();
2803 II.setAlignment(ConstantInt::get(CstTy, Align));
2805 DEBUG(dbgs() << " to: " << II << "\n");
2806 deleteIfTriviallyDead(OldOp);
2809 // For split transfer intrinsics we have an incredibly useful assurance:
2810 // the source and destination do not reside within the same alloca, and at
2811 // least one of them does not escape. This means that we can replace
2812 // memmove with memcpy, and we don't need to worry about all manner of
2813 // downsides to splitting and transforming the operations.
2815 // If this doesn't map cleanly onto the alloca type, and that type isn't
2816 // a single value type, just emit a memcpy.
2818 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2819 EndOffset != NewAllocaEndOffset ||
2820 !NewAI.getAllocatedType()->isSingleValueType());
2822 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2823 // size hasn't been shrunk based on analysis of the viable range, this is
2825 if (EmitMemCpy && &OldAI == &NewAI) {
2826 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2827 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2828 // Ensure the start lines up.
2829 assert(BeginOffset == OrigBegin);
2832 // Rewrite the size as needed.
2833 if (EndOffset != OrigEnd)
2834 II.setLength(ConstantInt::get(II.getLength()->getType(),
2835 EndOffset - BeginOffset));
2838 // Record this instruction for deletion.
2839 Pass.DeadInsts.insert(&II);
2841 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2842 EndOffset == NewAllocaEndOffset;
2843 bool IsVectorElement = VecTy && !IsWholeAlloca;
2844 uint64_t Size = EndOffset - BeginOffset;
2845 IntegerType *SubIntTy
2846 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2848 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2849 : II.getRawDest()->getType();
2851 if (IsVectorElement)
2852 OtherPtrTy = VecTy->getElementType()->getPointerTo();
2853 else if (IntTy && !IsWholeAlloca)
2854 OtherPtrTy = SubIntTy->getPointerTo();
2856 OtherPtrTy = NewAI.getType();
2859 // Compute the other pointer, folding as much as possible to produce
2860 // a single, simple GEP in most cases.
2861 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2862 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2863 getName("." + OtherPtr->getName()));
2865 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2866 // alloca that should be re-examined after rewriting this instruction.
2868 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2869 Pass.Worklist.insert(AI);
2873 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2874 : II.getRawSource()->getType());
2875 Type *SizeTy = II.getLength()->getType();
2876 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2878 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2879 IsDest ? OtherPtr : OurPtr,
2880 Size, Align, II.isVolatile());
2882 DEBUG(dbgs() << " to: " << *New << "\n");
2886 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2887 // is equivalent to 1, but that isn't true if we end up rewriting this as
2892 Value *SrcPtr = OtherPtr;
2893 Value *DstPtr = &NewAI;
2895 std::swap(SrcPtr, DstPtr);
2898 if (IsVectorElement && !IsDest) {
2899 // We have to extract rather than load.
2900 Src = IRB.CreateExtractElement(
2901 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
2902 getIndex(IRB, BeginOffset),
2903 getName(".copyextract"));
2904 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2905 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2907 Src = convertValue(TD, IRB, Src, IntTy);
2908 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2909 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2910 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
2912 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2913 getName(".copyload"));
2916 if (IntTy && !IsWholeAlloca && IsDest) {
2917 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2918 getName(".oldload"));
2919 Old = convertValue(TD, IRB, Old, IntTy);
2920 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2921 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2922 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2923 Src = convertValue(TD, IRB, Src, NewAllocaTy);
2926 if (IsVectorElement && IsDest) {
2927 // We have to insert into a loaded copy before storing.
2928 Src = IRB.CreateInsertElement(
2929 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2930 Src, getIndex(IRB, BeginOffset),
2931 getName(".insert"));
2934 StoreInst *Store = cast<StoreInst>(
2935 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2937 DEBUG(dbgs() << " to: " << *Store << "\n");
2938 return !II.isVolatile();
2941 bool visitIntrinsicInst(IntrinsicInst &II) {
2942 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2943 II.getIntrinsicID() == Intrinsic::lifetime_end);
2944 DEBUG(dbgs() << " original: " << II << "\n");
2945 IRBuilder<> IRB(&II);
2946 assert(II.getArgOperand(1) == OldPtr);
2948 // Record this instruction for deletion.
2949 Pass.DeadInsts.insert(&II);
2952 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2953 EndOffset - BeginOffset);
2954 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2956 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2957 New = IRB.CreateLifetimeStart(Ptr, Size);
2959 New = IRB.CreateLifetimeEnd(Ptr, Size);
2961 DEBUG(dbgs() << " to: " << *New << "\n");
2965 bool visitPHINode(PHINode &PN) {
2966 DEBUG(dbgs() << " original: " << PN << "\n");
2968 // We would like to compute a new pointer in only one place, but have it be
2969 // as local as possible to the PHI. To do that, we re-use the location of
2970 // the old pointer, which necessarily must be in the right position to
2971 // dominate the PHI.
2972 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2974 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2975 // Replace the operands which were using the old pointer.
2976 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
2978 DEBUG(dbgs() << " to: " << PN << "\n");
2979 deleteIfTriviallyDead(OldPtr);
2983 bool visitSelectInst(SelectInst &SI) {
2984 DEBUG(dbgs() << " original: " << SI << "\n");
2985 IRBuilder<> IRB(&SI);
2987 // Find the operand we need to rewrite here.
2988 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2990 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2992 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2994 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2995 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2996 DEBUG(dbgs() << " to: " << SI << "\n");
2997 deleteIfTriviallyDead(OldPtr);
3005 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
3007 /// This pass aggressively rewrites all aggregate loads and stores on
3008 /// a particular pointer (or any pointer derived from it which we can identify)
3009 /// with scalar loads and stores.
3010 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3011 // Befriend the base class so it can delegate to private visit methods.
3012 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3014 const DataLayout &TD;
3016 /// Queue of pointer uses to analyze and potentially rewrite.
3017 SmallVector<Use *, 8> Queue;
3019 /// Set to prevent us from cycling with phi nodes and loops.
3020 SmallPtrSet<User *, 8> Visited;
3022 /// The current pointer use being rewritten. This is used to dig up the used
3023 /// value (as opposed to the user).
3027 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
3029 /// Rewrite loads and stores through a pointer and all pointers derived from
3031 bool rewrite(Instruction &I) {
3032 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3034 bool Changed = false;
3035 while (!Queue.empty()) {
3036 U = Queue.pop_back_val();
3037 Changed |= visit(cast<Instruction>(U->getUser()));
3043 /// Enqueue all the users of the given instruction for further processing.
3044 /// This uses a set to de-duplicate users.
3045 void enqueueUsers(Instruction &I) {
3046 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3048 if (Visited.insert(*UI))
3049 Queue.push_back(&UI.getUse());
3052 // Conservative default is to not rewrite anything.
3053 bool visitInstruction(Instruction &I) { return false; }
3055 /// \brief Generic recursive split emission class.
3056 template <typename Derived>
3059 /// The builder used to form new instructions.
3061 /// The indices which to be used with insert- or extractvalue to select the
3062 /// appropriate value within the aggregate.
3063 SmallVector<unsigned, 4> Indices;
3064 /// The indices to a GEP instruction which will move Ptr to the correct slot
3065 /// within the aggregate.
3066 SmallVector<Value *, 4> GEPIndices;
3067 /// The base pointer of the original op, used as a base for GEPing the
3068 /// split operations.
3071 /// Initialize the splitter with an insertion point, Ptr and start with a
3072 /// single zero GEP index.
3073 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
3074 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3077 /// \brief Generic recursive split emission routine.
3079 /// This method recursively splits an aggregate op (load or store) into
3080 /// scalar or vector ops. It splits recursively until it hits a single value
3081 /// and emits that single value operation via the template argument.
3083 /// The logic of this routine relies on GEPs and insertvalue and
3084 /// extractvalue all operating with the same fundamental index list, merely
3085 /// formatted differently (GEPs need actual values).
3087 /// \param Ty The type being split recursively into smaller ops.
3088 /// \param Agg The aggregate value being built up or stored, depending on
3089 /// whether this is splitting a load or a store respectively.
3090 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3091 if (Ty->isSingleValueType())
3092 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
3094 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3095 unsigned OldSize = Indices.size();
3097 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3099 assert(Indices.size() == OldSize && "Did not return to the old size");
3100 Indices.push_back(Idx);
3101 GEPIndices.push_back(IRB.getInt32(Idx));
3102 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3103 GEPIndices.pop_back();
3109 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3110 unsigned OldSize = Indices.size();
3112 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3114 assert(Indices.size() == OldSize && "Did not return to the old size");
3115 Indices.push_back(Idx);
3116 GEPIndices.push_back(IRB.getInt32(Idx));
3117 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3118 GEPIndices.pop_back();
3124 llvm_unreachable("Only arrays and structs are aggregate loadable types");
3128 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3129 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3130 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
3132 /// Emit a leaf load of a single value. This is called at the leaves of the
3133 /// recursive emission to actually load values.
3134 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3135 assert(Ty->isSingleValueType());
3136 // Load the single value and insert it using the indices.
3137 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
3140 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3141 DEBUG(dbgs() << " to: " << *Load << "\n");
3145 bool visitLoadInst(LoadInst &LI) {
3146 assert(LI.getPointerOperand() == *U);
3147 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3150 // We have an aggregate being loaded, split it apart.
3151 DEBUG(dbgs() << " original: " << LI << "\n");
3152 LoadOpSplitter Splitter(&LI, *U);
3153 Value *V = UndefValue::get(LI.getType());
3154 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3155 LI.replaceAllUsesWith(V);
3156 LI.eraseFromParent();
3160 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
3161 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3162 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
3164 /// Emit a leaf store of a single value. This is called at the leaves of the
3165 /// recursive emission to actually produce stores.
3166 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3167 assert(Ty->isSingleValueType());
3168 // Extract the single value and store it using the indices.
3169 Value *Store = IRB.CreateStore(
3170 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3171 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3173 DEBUG(dbgs() << " to: " << *Store << "\n");
3177 bool visitStoreInst(StoreInst &SI) {
3178 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3180 Value *V = SI.getValueOperand();
3181 if (V->getType()->isSingleValueType())
3184 // We have an aggregate being stored, split it apart.
3185 DEBUG(dbgs() << " original: " << SI << "\n");
3186 StoreOpSplitter Splitter(&SI, *U);
3187 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3188 SI.eraseFromParent();
3192 bool visitBitCastInst(BitCastInst &BC) {
3197 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3202 bool visitPHINode(PHINode &PN) {
3207 bool visitSelectInst(SelectInst &SI) {
3214 /// \brief Strip aggregate type wrapping.
3216 /// This removes no-op aggregate types wrapping an underlying type. It will
3217 /// strip as many layers of types as it can without changing either the type
3218 /// size or the allocated size.
3219 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3220 if (Ty->isSingleValueType())
3223 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3224 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3227 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3228 InnerTy = ArrTy->getElementType();
3229 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3230 const StructLayout *SL = DL.getStructLayout(STy);
3231 unsigned Index = SL->getElementContainingOffset(0);
3232 InnerTy = STy->getElementType(Index);
3237 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3238 TypeSize > DL.getTypeSizeInBits(InnerTy))
3241 return stripAggregateTypeWrapping(DL, InnerTy);
3244 /// \brief Try to find a partition of the aggregate type passed in for a given
3245 /// offset and size.
3247 /// This recurses through the aggregate type and tries to compute a subtype
3248 /// based on the offset and size. When the offset and size span a sub-section
3249 /// of an array, it will even compute a new array type for that sub-section,
3250 /// and the same for structs.
3252 /// Note that this routine is very strict and tries to find a partition of the
3253 /// type which produces the *exact* right offset and size. It is not forgiving
3254 /// when the size or offset cause either end of type-based partition to be off.
3255 /// Also, this is a best-effort routine. It is reasonable to give up and not
3256 /// return a type if necessary.
3257 static Type *getTypePartition(const DataLayout &TD, Type *Ty,
3258 uint64_t Offset, uint64_t Size) {
3259 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
3260 return stripAggregateTypeWrapping(TD, Ty);
3261 if (Offset > TD.getTypeAllocSize(Ty) ||
3262 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3265 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3266 // We can't partition pointers...
3267 if (SeqTy->isPointerTy())
3270 Type *ElementTy = SeqTy->getElementType();
3271 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3272 uint64_t NumSkippedElements = Offset / ElementSize;
3273 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3274 if (NumSkippedElements >= ArrTy->getNumElements())
3276 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3277 if (NumSkippedElements >= VecTy->getNumElements())
3279 Offset -= NumSkippedElements * ElementSize;
3281 // First check if we need to recurse.
3282 if (Offset > 0 || Size < ElementSize) {
3283 // Bail if the partition ends in a different array element.
3284 if ((Offset + Size) > ElementSize)
3286 // Recurse through the element type trying to peel off offset bytes.
3287 return getTypePartition(TD, ElementTy, Offset, Size);
3289 assert(Offset == 0);
3291 if (Size == ElementSize)
3292 return stripAggregateTypeWrapping(TD, ElementTy);
3293 assert(Size > ElementSize);
3294 uint64_t NumElements = Size / ElementSize;
3295 if (NumElements * ElementSize != Size)
3297 return ArrayType::get(ElementTy, NumElements);
3300 StructType *STy = dyn_cast<StructType>(Ty);
3304 const StructLayout *SL = TD.getStructLayout(STy);
3305 if (Offset >= SL->getSizeInBytes())
3307 uint64_t EndOffset = Offset + Size;
3308 if (EndOffset > SL->getSizeInBytes())
3311 unsigned Index = SL->getElementContainingOffset(Offset);
3312 Offset -= SL->getElementOffset(Index);
3314 Type *ElementTy = STy->getElementType(Index);
3315 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3316 if (Offset >= ElementSize)
3317 return 0; // The offset points into alignment padding.
3319 // See if any partition must be contained by the element.
3320 if (Offset > 0 || Size < ElementSize) {
3321 if ((Offset + Size) > ElementSize)
3323 return getTypePartition(TD, ElementTy, Offset, Size);
3325 assert(Offset == 0);
3327 if (Size == ElementSize)
3328 return stripAggregateTypeWrapping(TD, ElementTy);
3330 StructType::element_iterator EI = STy->element_begin() + Index,
3331 EE = STy->element_end();
3332 if (EndOffset < SL->getSizeInBytes()) {
3333 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3334 if (Index == EndIndex)
3335 return 0; // Within a single element and its padding.
3337 // Don't try to form "natural" types if the elements don't line up with the
3339 // FIXME: We could potentially recurse down through the last element in the
3340 // sub-struct to find a natural end point.
3341 if (SL->getElementOffset(EndIndex) != EndOffset)
3344 assert(Index < EndIndex);
3345 EE = STy->element_begin() + EndIndex;
3348 // Try to build up a sub-structure.
3349 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
3351 const StructLayout *SubSL = TD.getStructLayout(SubTy);
3352 if (Size != SubSL->getSizeInBytes())
3353 return 0; // The sub-struct doesn't have quite the size needed.
3358 /// \brief Rewrite an alloca partition's users.
3360 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3361 /// to rewrite uses of an alloca partition to be conducive for SSA value
3362 /// promotion. If the partition needs a new, more refined alloca, this will
3363 /// build that new alloca, preserving as much type information as possible, and
3364 /// rewrite the uses of the old alloca to point at the new one and have the
3365 /// appropriate new offsets. It also evaluates how successful the rewrite was
3366 /// at enabling promotion and if it was successful queues the alloca to be
3368 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3369 AllocaPartitioning &P,
3370 AllocaPartitioning::iterator PI) {
3371 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
3372 bool IsLive = false;
3373 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3375 UI != UE && !IsLive; ++UI)
3379 return false; // No live uses left of this partition.
3381 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3382 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3384 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3385 DEBUG(dbgs() << " speculating ");
3386 DEBUG(P.print(dbgs(), PI, ""));
3387 Speculator.visitUsers(PI);
3389 // Try to compute a friendly type for this partition of the alloca. This
3390 // won't always succeed, in which case we fall back to a legal integer type
3391 // or an i8 array of an appropriate size.
3393 if (Type *PartitionTy = P.getCommonType(PI))
3394 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3395 AllocaTy = PartitionTy;
3397 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3398 PI->BeginOffset, AllocaSize))
3399 AllocaTy = PartitionTy;
3401 (AllocaTy->isArrayTy() &&
3402 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3403 TD->isLegalInteger(AllocaSize * 8))
3404 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3406 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
3407 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
3409 // Check for the case where we're going to rewrite to a new alloca of the
3410 // exact same type as the original, and with the same access offsets. In that
3411 // case, re-use the existing alloca, but still run through the rewriter to
3412 // performe phi and select speculation.
3414 if (AllocaTy == AI.getAllocatedType()) {
3415 assert(PI->BeginOffset == 0 &&
3416 "Non-zero begin offset but same alloca type");
3417 assert(PI == P.begin() && "Begin offset is zero on later partition");
3420 unsigned Alignment = AI.getAlignment();
3422 // The minimum alignment which users can rely on when the explicit
3423 // alignment is omitted or zero is that required by the ABI for this
3425 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3427 Alignment = MinAlign(Alignment, PI->BeginOffset);
3428 // If we will get at least this much alignment from the type alone, leave
3429 // the alloca's alignment unconstrained.
3430 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3432 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
3433 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3438 DEBUG(dbgs() << "Rewriting alloca partition "
3439 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3442 // Track the high watermark of the post-promotion worklist. We will reset it
3443 // to this point if the alloca is not in fact scheduled for promotion.
3444 unsigned PPWOldSize = PostPromotionWorklist.size();
3446 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3447 PI->BeginOffset, PI->EndOffset);
3448 DEBUG(dbgs() << " rewriting ");
3449 DEBUG(P.print(dbgs(), PI, ""));
3450 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3452 DEBUG(dbgs() << " and queuing for promotion\n");
3453 PromotableAllocas.push_back(NewAI);
3454 } else if (NewAI != &AI) {
3455 // If we can't promote the alloca, iterate on it to check for new
3456 // refinements exposed by splitting the current alloca. Don't iterate on an
3457 // alloca which didn't actually change and didn't get promoted.
3458 Worklist.insert(NewAI);
3461 // Drop any post-promotion work items if promotion didn't happen.
3463 while (PostPromotionWorklist.size() > PPWOldSize)
3464 PostPromotionWorklist.pop_back();
3469 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3470 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3471 bool Changed = false;
3472 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3474 Changed |= rewriteAllocaPartition(AI, P, PI);
3479 /// \brief Analyze an alloca for SROA.
3481 /// This analyzes the alloca to ensure we can reason about it, builds
3482 /// a partitioning of the alloca, and then hands it off to be split and
3483 /// rewritten as needed.
3484 bool SROA::runOnAlloca(AllocaInst &AI) {
3485 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3486 ++NumAllocasAnalyzed;
3488 // Special case dead allocas, as they're trivial.
3489 if (AI.use_empty()) {
3490 AI.eraseFromParent();
3494 // Skip alloca forms that this analysis can't handle.
3495 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3496 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3499 bool Changed = false;
3501 // First, split any FCA loads and stores touching this alloca to promote
3502 // better splitting and promotion opportunities.
3503 AggLoadStoreRewriter AggRewriter(*TD);
3504 Changed |= AggRewriter.rewrite(AI);
3506 // Build the partition set using a recursive instruction-visiting builder.
3507 AllocaPartitioning P(*TD, AI);
3508 DEBUG(P.print(dbgs()));
3512 // Delete all the dead users of this alloca before splitting and rewriting it.
3513 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3514 DE = P.dead_user_end();
3517 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3518 DeadInsts.insert(*DI);
3520 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3521 DE = P.dead_op_end();
3524 // Clobber the use with an undef value.
3525 **DO = UndefValue::get(OldV->getType());
3526 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3527 if (isInstructionTriviallyDead(OldI)) {
3529 DeadInsts.insert(OldI);
3533 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3534 if (P.begin() == P.end())
3537 return splitAlloca(AI, P) || Changed;
3540 /// \brief Delete the dead instructions accumulated in this run.
3542 /// Recursively deletes the dead instructions we've accumulated. This is done
3543 /// at the very end to maximize locality of the recursive delete and to
3544 /// minimize the problems of invalidated instruction pointers as such pointers
3545 /// are used heavily in the intermediate stages of the algorithm.
3547 /// We also record the alloca instructions deleted here so that they aren't
3548 /// subsequently handed to mem2reg to promote.
3549 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3550 while (!DeadInsts.empty()) {
3551 Instruction *I = DeadInsts.pop_back_val();
3552 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3554 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3556 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3557 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3558 // Zero out the operand and see if it becomes trivially dead.
3560 if (isInstructionTriviallyDead(U))
3561 DeadInsts.insert(U);
3564 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3565 DeletedAllocas.insert(AI);
3568 I->eraseFromParent();
3572 /// \brief Promote the allocas, using the best available technique.
3574 /// This attempts to promote whatever allocas have been identified as viable in
3575 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3576 /// If there is a domtree available, we attempt to promote using the full power
3577 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3578 /// based on the SSAUpdater utilities. This function returns whether any
3579 /// promotion occured.
3580 bool SROA::promoteAllocas(Function &F) {
3581 if (PromotableAllocas.empty())
3584 NumPromoted += PromotableAllocas.size();
3586 if (DT && !ForceSSAUpdater) {
3587 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3588 PromoteMemToReg(PromotableAllocas, *DT);
3589 PromotableAllocas.clear();
3593 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3595 DIBuilder DIB(*F.getParent());
3596 SmallVector<Instruction*, 64> Insts;
3598 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3599 AllocaInst *AI = PromotableAllocas[Idx];
3600 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3602 Instruction *I = cast<Instruction>(*UI++);
3603 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3604 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3605 // leading to them) here. Eventually it should use them to optimize the
3606 // scalar values produced.
3607 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3608 assert(onlyUsedByLifetimeMarkers(I) &&
3609 "Found a bitcast used outside of a lifetime marker.");
3610 while (!I->use_empty())
3611 cast<Instruction>(*I->use_begin())->eraseFromParent();
3612 I->eraseFromParent();
3615 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3616 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3617 II->getIntrinsicID() == Intrinsic::lifetime_end);
3618 II->eraseFromParent();
3624 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3628 PromotableAllocas.clear();
3633 /// \brief A predicate to test whether an alloca belongs to a set.
3634 class IsAllocaInSet {
3635 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3639 typedef AllocaInst *argument_type;
3641 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3642 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
3646 bool SROA::runOnFunction(Function &F) {
3647 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3648 C = &F.getContext();
3649 TD = getAnalysisIfAvailable<DataLayout>();
3651 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3654 DT = getAnalysisIfAvailable<DominatorTree>();
3656 BasicBlock &EntryBB = F.getEntryBlock();
3657 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3659 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3660 Worklist.insert(AI);
3662 bool Changed = false;
3663 // A set of deleted alloca instruction pointers which should be removed from
3664 // the list of promotable allocas.
3665 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3668 while (!Worklist.empty()) {
3669 Changed |= runOnAlloca(*Worklist.pop_back_val());
3670 deleteDeadInstructions(DeletedAllocas);
3672 // Remove the deleted allocas from various lists so that we don't try to
3673 // continue processing them.
3674 if (!DeletedAllocas.empty()) {
3675 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3676 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3677 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3678 PromotableAllocas.end(),
3679 IsAllocaInSet(DeletedAllocas)),
3680 PromotableAllocas.end());
3681 DeletedAllocas.clear();
3685 Changed |= promoteAllocas(F);
3687 Worklist = PostPromotionWorklist;
3688 PostPromotionWorklist.clear();
3689 } while (!Worklist.empty());
3694 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3695 if (RequiresDomTree)
3696 AU.addRequired<DominatorTree>();
3697 AU.setPreservesCFG();