blob: 9ecefa6199c51b5526a921adfae89d3ddae67c25 [file] [log] [blame]
Chandler Carruth713aa942012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
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.
15///
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.
19///
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.
23///
24//===----------------------------------------------------------------------===//
25
26#define DEBUG_TYPE "sroa"
27#include "llvm/Transforms/Scalar.h"
28#include "llvm/Constants.h"
29#include "llvm/DIBuilder.h"
30#include "llvm/DebugInfo.h"
31#include "llvm/DerivedTypes.h"
32#include "llvm/Function.h"
33#include "llvm/GlobalVariable.h"
34#include "llvm/IRBuilder.h"
35#include "llvm/Instructions.h"
36#include "llvm/IntrinsicInst.h"
37#include "llvm/LLVMContext.h"
38#include "llvm/Module.h"
39#include "llvm/Operator.h"
40#include "llvm/Pass.h"
41#include "llvm/ADT/SetVector.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/TinyPtrVector.h"
46#include "llvm/Analysis/Dominators.h"
47#include "llvm/Analysis/Loads.h"
48#include "llvm/Analysis/ValueTracking.h"
49#include "llvm/Support/CallSite.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/GetElementPtrTypeIterator.h"
53#include "llvm/Support/InstVisitor.h"
54#include "llvm/Support/MathExtras.h"
55#include "llvm/Support/ValueHandle.h"
56#include "llvm/Support/raw_ostream.h"
57#include "llvm/Target/TargetData.h"
58#include "llvm/Transforms/Utils/Local.h"
59#include "llvm/Transforms/Utils/PromoteMemToReg.h"
60#include "llvm/Transforms/Utils/SSAUpdater.h"
61using namespace llvm;
62
63STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
64STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
65STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
66STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
67STATISTIC(NumDeleted, "Number of instructions deleted");
68STATISTIC(NumVectorized, "Number of vectorized aggregates");
69
70namespace {
71/// \brief Alloca partitioning representation.
72///
73/// This class represents a partitioning of an alloca into slices, and
74/// information about the nature of uses of each slice of the alloca. The goal
75/// is that this information is sufficient to decide if and how to split the
76/// alloca apart and replace slices with scalars. It is also intended that this
77/// structure can capture the relevant information needed both due decide about
78/// and to enact these transformations.
79class AllocaPartitioning {
80public:
81 /// \brief A common base class for representing a half-open byte range.
82 struct ByteRange {
83 /// \brief The beginning offset of the range.
84 uint64_t BeginOffset;
85
86 /// \brief The ending offset, not included in the range.
87 uint64_t EndOffset;
88
89 ByteRange() : BeginOffset(), EndOffset() {}
90 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
91 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
92
93 /// \brief Support for ordering ranges.
94 ///
95 /// This provides an ordering over ranges such that start offsets are
96 /// always increasing, and within equal start offsets, the end offsets are
97 /// decreasing. Thus the spanning range comes first in in cluster with the
98 /// same start position.
99 bool operator<(const ByteRange &RHS) const {
100 if (BeginOffset < RHS.BeginOffset) return true;
101 if (BeginOffset > RHS.BeginOffset) return false;
102 if (EndOffset > RHS.EndOffset) return true;
103 return false;
104 }
105
106 /// \brief Support comparison with a single offset to allow binary searches.
107 bool operator<(uint64_t RHSOffset) const {
108 return BeginOffset < RHSOffset;
109 }
110
111 bool operator==(const ByteRange &RHS) const {
112 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
113 }
114 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
115 };
116
117 /// \brief A partition of an alloca.
118 ///
119 /// This structure represents a contiguous partition of the alloca. These are
120 /// formed by examining the uses of the alloca. During formation, they may
121 /// overlap but once an AllocaPartitioning is built, the Partitions within it
122 /// are all disjoint.
123 struct Partition : public ByteRange {
124 /// \brief Whether this partition is splittable into smaller partitions.
125 ///
126 /// We flag partitions as splittable when they are formed entirely due to
127 /// accesses by trivially split operations such as memset and memcpy.
128 ///
129 /// FIXME: At some point we should consider loads and stores of FCAs to be
130 /// splittable and eagerly split them into scalar values.
131 bool IsSplittable;
132
133 Partition() : ByteRange(), IsSplittable() {}
134 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
135 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
136 };
137
138 /// \brief A particular use of a partition of the alloca.
139 ///
140 /// This structure is used to associate uses of a partition with it. They
141 /// mark the range of bytes which are referenced by a particular instruction,
142 /// and includes a handle to the user itself and the pointer value in use.
143 /// The bounds of these uses are determined by intersecting the bounds of the
144 /// memory use itself with a particular partition. As a consequence there is
145 /// intentionally overlap between various usues of the same partition.
146 struct PartitionUse : public ByteRange {
147 /// \brief The user of this range of the alloca.
148 AssertingVH<Instruction> User;
149
150 /// \brief The particular pointer value derived from this alloca in use.
151 AssertingVH<Instruction> Ptr;
152
153 PartitionUse() : ByteRange(), User(), Ptr() {}
154 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset,
155 Instruction *User, Instruction *Ptr)
156 : ByteRange(BeginOffset, EndOffset), User(User), Ptr(Ptr) {}
157 };
158
159 /// \brief Construct a partitioning of a particular alloca.
160 ///
161 /// Construction does most of the work for partitioning the alloca. This
162 /// performs the necessary walks of users and builds a partitioning from it.
163 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
164
165 /// \brief Test whether a pointer to the allocation escapes our analysis.
166 ///
167 /// If this is true, the partitioning is never fully built and should be
168 /// ignored.
169 bool isEscaped() const { return PointerEscapingInstr; }
170
171 /// \brief Support for iterating over the partitions.
172 /// @{
173 typedef SmallVectorImpl<Partition>::iterator iterator;
174 iterator begin() { return Partitions.begin(); }
175 iterator end() { return Partitions.end(); }
176
177 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
178 const_iterator begin() const { return Partitions.begin(); }
179 const_iterator end() const { return Partitions.end(); }
180 /// @}
181
182 /// \brief Support for iterating over and manipulating a particular
183 /// partition's uses.
184 ///
185 /// The iteration support provided for uses is more limited, but also
186 /// includes some manipulation routines to support rewriting the uses of
187 /// partitions during SROA.
188 /// @{
189 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
190 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
191 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
192 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
193 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
194 void use_insert(unsigned Idx, use_iterator UI, const PartitionUse &U) {
195 Uses[Idx].insert(UI, U);
196 }
197 void use_insert(const_iterator I, use_iterator UI, const PartitionUse &U) {
198 Uses[I - begin()].insert(UI, U);
199 }
200 void use_erase(unsigned Idx, use_iterator UI) { Uses[Idx].erase(UI); }
201 void use_erase(const_iterator I, use_iterator UI) {
202 Uses[I - begin()].erase(UI);
203 }
204
205 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
206 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
207 const_use_iterator use_begin(const_iterator I) const {
208 return Uses[I - begin()].begin();
209 }
210 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
211 const_use_iterator use_end(const_iterator I) const {
212 return Uses[I - begin()].end();
213 }
214 /// @}
215
216 /// \brief Allow iterating the dead users for this alloca.
217 ///
218 /// These are instructions which will never actually use the alloca as they
219 /// are outside the allocated range. They are safe to replace with undef and
220 /// delete.
221 /// @{
222 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
223 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
224 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
225 /// @}
226
227 /// \brief Allow iterating the dead operands referring to this alloca.
228 ///
229 /// These are operands which have cannot actually be used to refer to the
230 /// alloca as they are outside its range and the user doesn't correct for
231 /// that. These mostly consist of PHI node inputs and the like which we just
232 /// need to replace with undef.
233 /// @{
234 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
235 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
236 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
237 /// @}
238
239 /// \brief MemTransferInst auxiliary data.
240 /// This struct provides some auxiliary data about memory transfer
241 /// intrinsics such as memcpy and memmove. These intrinsics can use two
242 /// different ranges within the same alloca, and provide other challenges to
243 /// correctly represent. We stash extra data to help us untangle this
244 /// after the partitioning is complete.
245 struct MemTransferOffsets {
246 uint64_t DestBegin, DestEnd;
247 uint64_t SourceBegin, SourceEnd;
248 bool IsSplittable;
249 };
250 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
251 return MemTransferInstData.lookup(&II);
252 }
253
254 /// \brief Map from a PHI or select operand back to a partition.
255 ///
256 /// When manipulating PHI nodes or selects, they can use more than one
257 /// partition of an alloca. We store a special mapping to allow finding the
258 /// partition referenced by each of these operands, if any.
259 iterator findPartitionForPHIOrSelectOperand(Instruction &I, Value *Op) {
260 SmallDenseMap<std::pair<Instruction *, Value *>,
261 std::pair<unsigned, unsigned> >::const_iterator MapIt
262 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
263 if (MapIt == PHIOrSelectOpMap.end())
264 return end();
265
266 return begin() + MapIt->second.first;
267 }
268
269 /// \brief Map from a PHI or select operand back to the specific use of
270 /// a partition.
271 ///
272 /// Similar to mapping these operands back to the partitions, this maps
273 /// directly to the use structure of that partition.
274 use_iterator findPartitionUseForPHIOrSelectOperand(Instruction &I,
275 Value *Op) {
276 SmallDenseMap<std::pair<Instruction *, Value *>,
277 std::pair<unsigned, unsigned> >::const_iterator MapIt
278 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
279 assert(MapIt != PHIOrSelectOpMap.end());
280 return Uses[MapIt->second.first].begin() + MapIt->second.second;
281 }
282
283 /// \brief Compute a common type among the uses of a particular partition.
284 ///
285 /// This routines walks all of the uses of a particular partition and tries
286 /// to find a common type between them. Untyped operations such as memset and
287 /// memcpy are ignored.
288 Type *getCommonType(iterator I) const;
289
290 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
291 void printUsers(raw_ostream &OS, const_iterator I,
292 StringRef Indent = " ") const;
293 void print(raw_ostream &OS) const;
294 void dump(const_iterator I) const LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED;
295 void dump() const LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED;
296
297private:
298 template <typename DerivedT, typename RetT = void> class BuilderBase;
299 class PartitionBuilder;
300 friend class AllocaPartitioning::PartitionBuilder;
301 class UseBuilder;
302 friend class AllocaPartitioning::UseBuilder;
303
304 /// \brief Handle to alloca instruction to simplify method interfaces.
305 AllocaInst &AI;
306
307 /// \brief The instruction responsible for this alloca having no partitioning.
308 ///
309 /// When an instruction (potentially) escapes the pointer to the alloca, we
310 /// store a pointer to that here and abort trying to partition the alloca.
311 /// This will be null if the alloca is partitioned successfully.
312 Instruction *PointerEscapingInstr;
313
314 /// \brief The partitions of the alloca.
315 ///
316 /// We store a vector of the partitions over the alloca here. This vector is
317 /// sorted by increasing begin offset, and then by decreasing end offset. See
318 /// the Partition inner class for more details. Initially there are overlaps,
319 /// be during construction we form a disjoint sequence toward the end.
320 SmallVector<Partition, 8> Partitions;
321
322 /// \brief The uses of the partitions.
323 ///
324 /// This is essentially a mapping from each partition to a list of uses of
325 /// that partition. The mapping is done with a Uses vector that has the exact
326 /// same number of entries as the partition vector. Each entry is itself
327 /// a vector of the uses.
328 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
329
330 /// \brief Instructions which will become dead if we rewrite the alloca.
331 ///
332 /// Note that these are not separated by partition. This is because we expect
333 /// a partitioned alloca to be completely rewritten or not rewritten at all.
334 /// If rewritten, all these instructions can simply be removed and replaced
335 /// with undef as they come from outside of the allocated space.
336 SmallVector<Instruction *, 8> DeadUsers;
337
338 /// \brief Operands which will become dead if we rewrite the alloca.
339 ///
340 /// These are operands that in their particular use can be replaced with
341 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
342 /// to PHI nodes and the like. They aren't entirely dead (there might be
343 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
344 /// want to swap this particular input for undef to simplify the use lists of
345 /// the alloca.
346 SmallVector<Use *, 8> DeadOperands;
347
348 /// \brief The underlying storage for auxiliary memcpy and memset info.
349 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
350
351 /// \brief A side datastructure used when building up the partitions and uses.
352 ///
353 /// This mapping is only really used during the initial building of the
354 /// partitioning so that we can retain information about PHI and select nodes
355 /// processed.
356 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
357
358 /// \brief Auxiliary information for particular PHI or select operands.
359 SmallDenseMap<std::pair<Instruction *, Value *>,
360 std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
361
362 /// \brief A utility routine called from the constructor.
363 ///
364 /// This does what it says on the tin. It is the key of the alloca partition
365 /// splitting and merging. After it is called we have the desired disjoint
366 /// collection of partitions.
367 void splitAndMergePartitions();
368};
369}
370
371template <typename DerivedT, typename RetT>
372class AllocaPartitioning::BuilderBase
373 : public InstVisitor<DerivedT, RetT> {
374public:
375 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
376 : TD(TD),
377 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
378 P(P) {
379 enqueueUsers(AI, 0);
380 }
381
382protected:
383 const TargetData &TD;
384 const uint64_t AllocSize;
385 AllocaPartitioning &P;
386
387 struct OffsetUse {
388 Use *U;
389 uint64_t Offset;
390 };
391 SmallVector<OffsetUse, 8> Queue;
392
393 // The active offset and use while visiting.
394 Use *U;
395 uint64_t Offset;
396
397 void enqueueUsers(Instruction &I, uint64_t UserOffset) {
398 SmallPtrSet<User *, 8> UserSet;
399 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
400 UI != UE; ++UI) {
401 if (!UserSet.insert(*UI))
402 continue;
403
404 OffsetUse OU = { &UI.getUse(), UserOffset };
405 Queue.push_back(OU);
406 }
407 }
408
409 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, uint64_t &GEPOffset) {
410 GEPOffset = Offset;
411 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
412 GTI != GTE; ++GTI) {
413 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
414 if (!OpC)
415 return false;
416 if (OpC->isZero())
417 continue;
418
419 // Handle a struct index, which adds its field offset to the pointer.
420 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
421 unsigned ElementIdx = OpC->getZExtValue();
422 const StructLayout *SL = TD.getStructLayout(STy);
423 GEPOffset += SL->getElementOffset(ElementIdx);
424 continue;
425 }
426
427 GEPOffset
428 += OpC->getZExtValue() * TD.getTypeAllocSize(GTI.getIndexedType());
429 }
430 return true;
431 }
432
433 Value *foldSelectInst(SelectInst &SI) {
434 // If the condition being selected on is a constant or the same value is
435 // being selected between, fold the select. Yes this does (rarely) happen
436 // early on.
437 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
438 return SI.getOperand(1+CI->isZero());
439 if (SI.getOperand(1) == SI.getOperand(2)) {
440 assert(*U == SI.getOperand(1));
441 return SI.getOperand(1);
442 }
443 return 0;
444 }
445};
446
447/// \brief Builder for the alloca partitioning.
448///
449/// This class builds an alloca partitioning by recursively visiting the uses
450/// of an alloca and splitting the partitions for each load and store at each
451/// offset.
452class AllocaPartitioning::PartitionBuilder
453 : public BuilderBase<PartitionBuilder, bool> {
454 friend class InstVisitor<PartitionBuilder, bool>;
455
456 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
457
458public:
459 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
460 : BuilderBase(TD, AI, P) {}
461
462 /// \brief Run the builder over the allocation.
463 bool operator()() {
464 // Note that we have to re-evaluate size on each trip through the loop as
465 // the queue grows at the tail.
466 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
467 U = Queue[Idx].U;
468 Offset = Queue[Idx].Offset;
469 if (!visit(cast<Instruction>(U->getUser())))
470 return false;
471 }
472 return true;
473 }
474
475private:
476 bool markAsEscaping(Instruction &I) {
477 P.PointerEscapingInstr = &I;
478 return false;
479 }
480
481 void insertUse(Instruction &I, uint64_t Size, bool IsSplittable = false) {
482 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
483
484 // Completely skip uses which start outside of the allocation.
485 if (BeginOffset >= AllocSize) {
486 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
487 << " which starts past the end of the " << AllocSize
488 << " byte alloca:\n"
489 << " alloca: " << P.AI << "\n"
490 << " use: " << I << "\n");
491 return;
492 }
493
494 // Clamp the size to the allocation.
495 if (EndOffset > AllocSize) {
496 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
497 << " to remain within the " << AllocSize << " byte alloca:\n"
498 << " alloca: " << P.AI << "\n"
499 << " use: " << I << "\n");
500 EndOffset = AllocSize;
501 }
502
503 // See if we can just add a user onto the last slot currently occupied.
504 if (!P.Partitions.empty() &&
505 P.Partitions.back().BeginOffset == BeginOffset &&
506 P.Partitions.back().EndOffset == EndOffset) {
507 P.Partitions.back().IsSplittable &= IsSplittable;
508 return;
509 }
510
511 Partition New(BeginOffset, EndOffset, IsSplittable);
512 P.Partitions.push_back(New);
513 }
514
515 bool handleLoadOrStore(Type *Ty, Instruction &I) {
516 uint64_t Size = TD.getTypeStoreSize(Ty);
517
518 // If this memory access can be shown to *statically* extend outside the
519 // bounds of of the allocation, it's behavior is undefined, so simply
520 // ignore it. Note that this is more strict than the generic clamping
521 // behavior of insertUse. We also try to handle cases which might run the
522 // risk of overflow.
523 // FIXME: We should instead consider the pointer to have escaped if this
524 // function is being instrumented for addressing bugs or race conditions.
525 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize) {
526 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
527 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
528 << " which extends past the end of the " << AllocSize
529 << " byte alloca:\n"
530 << " alloca: " << P.AI << "\n"
531 << " use: " << I << "\n");
532 return true;
533 }
534
535 insertUse(I, Size);
536 return true;
537 }
538
539 bool visitBitCastInst(BitCastInst &BC) {
540 enqueueUsers(BC, Offset);
541 return true;
542 }
543
544 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
545 //unsigned IntPtrWidth = TD->getPointerSizeInBits();
546 //assert(IntPtrWidth == Offset.getBitWidth());
547 uint64_t GEPOffset;
548 if (!computeConstantGEPOffset(GEPI, GEPOffset))
549 return markAsEscaping(GEPI);
550
551 enqueueUsers(GEPI, GEPOffset);
552 return true;
553 }
554
555 bool visitLoadInst(LoadInst &LI) {
556 return handleLoadOrStore(LI.getType(), LI);
557 }
558
559 bool visitStoreInst(StoreInst &SI) {
560 if (SI.getOperand(0) == *U)
561 return markAsEscaping(SI);
562
563 return handleLoadOrStore(SI.getOperand(0)->getType(), SI);
564 }
565
566
567 bool visitMemSetInst(MemSetInst &II) {
568 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
569 insertUse(II, Length ? Length->getZExtValue() : AllocSize - Offset, Length);
570 return true;
571 }
572
573 bool visitMemTransferInst(MemTransferInst &II) {
574 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
575 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
576 if (!Size)
577 // Zero-length mem transfer intrinsics can be ignored entirely.
578 return true;
579
580 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
581
582 // Only intrinsics with a constant length can be split.
583 Offsets.IsSplittable = Length;
584
585 if (*U != II.getRawDest()) {
586 assert(*U == II.getRawSource());
587 Offsets.SourceBegin = Offset;
588 Offsets.SourceEnd = Offset + Size;
589 } else {
590 Offsets.DestBegin = Offset;
591 Offsets.DestEnd = Offset + Size;
592 }
593
594 insertUse(II, Size, Offsets.IsSplittable);
595 unsigned NewIdx = P.Partitions.size() - 1;
596
597 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
598 bool Inserted = false;
599 llvm::tie(PMI, Inserted)
600 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
601 if (!Inserted && Offsets.IsSplittable) {
602 // We've found a memory transfer intrinsic which refers to the alloca as
603 // both a source and dest. We refuse to split these to simplify splitting
604 // logic. If possible, SROA will still split them into separate allocas
605 // and then re-analyze.
606 Offsets.IsSplittable = false;
607 P.Partitions[PMI->second].IsSplittable = false;
608 P.Partitions[NewIdx].IsSplittable = false;
609 }
610
611 return true;
612 }
613
614 // Disable SRoA for any intrinsics except for lifetime invariants.
615 bool visitIntrinsicInst(IntrinsicInst &II) {
616 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
617 II.getIntrinsicID() == Intrinsic::lifetime_end) {
618 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
619 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
620 insertUse(II, Size, true);
621 return true;
622 }
623
624 return markAsEscaping(II);
625 }
626
627 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
628 // We consider any PHI or select that results in a direct load or store of
629 // the same offset to be a viable use for partitioning purposes. These uses
630 // are considered unsplittable and the size is the maximum loaded or stored
631 // size.
632 SmallPtrSet<Instruction *, 4> Visited;
633 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
634 Visited.insert(Root);
635 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
636 do {
637 Instruction *I, *UsedI;
638 llvm::tie(UsedI, I) = Uses.pop_back_val();
639
640 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
641 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
642 continue;
643 }
644 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
645 Value *Op = SI->getOperand(0);
646 if (Op == UsedI)
647 return SI;
648 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
649 continue;
650 }
651
652 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
653 if (!GEP->hasAllZeroIndices())
654 return GEP;
655 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
656 !isa<SelectInst>(I)) {
657 return I;
658 }
659
660 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
661 ++UI)
662 if (Visited.insert(cast<Instruction>(*UI)))
663 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
664 } while (!Uses.empty());
665
666 return 0;
667 }
668
669 bool visitPHINode(PHINode &PN) {
670 // See if we already have computed info on this node.
671 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
672 if (PHIInfo.first) {
673 PHIInfo.second = true;
674 insertUse(PN, PHIInfo.first);
675 return true;
676 }
677
678 // Check for an unsafe use of the PHI node.
679 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
680 return markAsEscaping(*EscapingI);
681
682 insertUse(PN, PHIInfo.first);
683 return true;
684 }
685
686 bool visitSelectInst(SelectInst &SI) {
687 if (Value *Result = foldSelectInst(SI)) {
688 if (Result == *U)
689 // If the result of the constant fold will be the pointer, recurse
690 // through the select as if we had RAUW'ed it.
691 enqueueUsers(SI, Offset);
692
693 return true;
694 }
695
696 // See if we already have computed info on this node.
697 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
698 if (SelectInfo.first) {
699 SelectInfo.second = true;
700 insertUse(SI, SelectInfo.first);
701 return true;
702 }
703
704 // Check for an unsafe use of the PHI node.
705 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
706 return markAsEscaping(*EscapingI);
707
708 insertUse(SI, SelectInfo.first);
709 return true;
710 }
711
712 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
713 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
714};
715
716
717/// \brief Use adder for the alloca partitioning.
718///
719/// This class adds the uses of an alloca to all of the partitions which it
720/// uses. For splittable partitions, this can end up doing essentially a linear
721/// walk of the partitions, but the number of steps remains bounded by the
722/// total result instruction size:
723/// - The number of partitions is a result of the number unsplittable
724/// instructions using the alloca.
725/// - The number of users of each partition is at worst the total number of
726/// splittable instructions using the alloca.
727/// Thus we will produce N * M instructions in the end, where N are the number
728/// of unsplittable uses and M are the number of splittable. This visitor does
729/// the exact same number of updates to the partitioning.
730///
731/// In the more common case, this visitor will leverage the fact that the
732/// partition space is pre-sorted, and do a logarithmic search for the
733/// partition needed, making the total visit a classical ((N + M) * log(N))
734/// complexity operation.
735class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
736 friend class InstVisitor<UseBuilder>;
737
738 /// \brief Set to de-duplicate dead instructions found in the use walk.
739 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
740
741public:
742 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
743 : BuilderBase(TD, AI, P) {}
744
745 /// \brief Run the builder over the allocation.
746 void operator()() {
747 // Note that we have to re-evaluate size on each trip through the loop as
748 // the queue grows at the tail.
749 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
750 U = Queue[Idx].U;
751 Offset = Queue[Idx].Offset;
752 this->visit(cast<Instruction>(U->getUser()));
753 }
754 }
755
756private:
757 void markAsDead(Instruction &I) {
758 if (VisitedDeadInsts.insert(&I))
759 P.DeadUsers.push_back(&I);
760 }
761
762 void insertUse(uint64_t Size, Instruction &User) {
763 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
764
765 // If the use extends outside of the allocation, record it as a dead use
766 // for elimination later.
767 if (BeginOffset >= AllocSize || Size == 0)
768 return markAsDead(User);
769
770 // Bound the use by the size of the allocation.
771 if (EndOffset > AllocSize)
772 EndOffset = AllocSize;
773
774 // NB: This only works if we have zero overlapping partitions.
775 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
776 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
777 B = llvm::prior(B);
778 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
779 ++I) {
780 PartitionUse NewUse(std::max(I->BeginOffset, BeginOffset),
781 std::min(I->EndOffset, EndOffset),
782 &User, cast<Instruction>(*U));
783 P.Uses[I - P.begin()].push_back(NewUse);
784 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
785 P.PHIOrSelectOpMap[std::make_pair(&User, U->get())]
786 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
787 }
788 }
789
790 void handleLoadOrStore(Type *Ty, Instruction &I) {
791 uint64_t Size = TD.getTypeStoreSize(Ty);
792
793 // If this memory access can be shown to *statically* extend outside the
794 // bounds of of the allocation, it's behavior is undefined, so simply
795 // ignore it. Note that this is more strict than the generic clamping
796 // behavior of insertUse.
797 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize)
798 return markAsDead(I);
799
800 insertUse(Size, I);
801 }
802
803 void visitBitCastInst(BitCastInst &BC) {
804 if (BC.use_empty())
805 return markAsDead(BC);
806
807 enqueueUsers(BC, Offset);
808 }
809
810 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
811 if (GEPI.use_empty())
812 return markAsDead(GEPI);
813
814 //unsigned IntPtrWidth = TD->getPointerSizeInBits();
815 //assert(IntPtrWidth == Offset.getBitWidth());
816 uint64_t GEPOffset;
817 if (!computeConstantGEPOffset(GEPI, GEPOffset))
818 llvm_unreachable("Unable to compute constant offset for use");
819
820 enqueueUsers(GEPI, GEPOffset);
821 }
822
823 void visitLoadInst(LoadInst &LI) {
824 handleLoadOrStore(LI.getType(), LI);
825 }
826
827 void visitStoreInst(StoreInst &SI) {
828 handleLoadOrStore(SI.getOperand(0)->getType(), SI);
829 }
830
831 void visitMemSetInst(MemSetInst &II) {
832 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
833 insertUse(Length ? Length->getZExtValue() : AllocSize - Offset, II);
834 }
835
836 void visitMemTransferInst(MemTransferInst &II) {
837 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
838 insertUse(Length ? Length->getZExtValue() : AllocSize - Offset, II);
839 }
840
841 void visitIntrinsicInst(IntrinsicInst &II) {
842 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
843 II.getIntrinsicID() == Intrinsic::lifetime_end);
844
845 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
846 insertUse(std::min(AllocSize - Offset, Length->getLimitedValue()), II);
847 }
848
849 void insertPHIOrSelect(Instruction &User) {
850 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
851
852 // For PHI and select operands outside the alloca, we can't nuke the entire
853 // phi or select -- the other side might still be relevant, so we special
854 // case them here and use a separate structure to track the operands
855 // themselves which should be replaced with undef.
856 if (Offset >= AllocSize) {
857 P.DeadOperands.push_back(U);
858 return;
859 }
860
861 insertUse(Size, User);
862 }
863 void visitPHINode(PHINode &PN) {
864 if (PN.use_empty())
865 return markAsDead(PN);
866
867 insertPHIOrSelect(PN);
868 }
869 void visitSelectInst(SelectInst &SI) {
870 if (SI.use_empty())
871 return markAsDead(SI);
872
873 if (Value *Result = foldSelectInst(SI)) {
874 if (Result == *U)
875 // If the result of the constant fold will be the pointer, recurse
876 // through the select as if we had RAUW'ed it.
877 enqueueUsers(SI, Offset);
878
879 return;
880 }
881
882 insertPHIOrSelect(SI);
883 }
884
885 /// \brief Unreachable, we've already visited the alloca once.
886 void visitInstruction(Instruction &I) {
887 llvm_unreachable("Unhandled instruction in use builder.");
888 }
889};
890
891void AllocaPartitioning::splitAndMergePartitions() {
892 size_t NumDeadPartitions = 0;
893
894 // Track the range of splittable partitions that we pass when accumulating
895 // overlapping unsplittable partitions.
896 uint64_t SplitEndOffset = 0ull;
897
898 Partition New(0ull, 0ull, false);
899
900 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
901 ++j;
902
903 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
904 assert(New.BeginOffset == New.EndOffset);
905 New = Partitions[i];
906 } else {
907 assert(New.IsSplittable);
908 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
909 }
910 assert(New.BeginOffset != New.EndOffset);
911
912 // Scan the overlapping partitions.
913 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
914 // If the new partition we are forming is splittable, stop at the first
915 // unsplittable partition.
916 if (New.IsSplittable && !Partitions[j].IsSplittable)
917 break;
918
919 // Grow the new partition to include any equally splittable range. 'j' is
920 // always equally splittable when New is splittable, but when New is not
921 // splittable, we may subsume some (or part of some) splitable partition
922 // without growing the new one.
923 if (New.IsSplittable == Partitions[j].IsSplittable) {
924 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
925 } else {
926 assert(!New.IsSplittable);
927 assert(Partitions[j].IsSplittable);
928 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
929 }
930
931 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
932 ++NumDeadPartitions;
933 ++j;
934 }
935
936 // If the new partition is splittable, chop off the end as soon as the
937 // unsplittable subsequent partition starts and ensure we eventually cover
938 // the splittable area.
939 if (j != e && New.IsSplittable) {
940 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
941 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
942 }
943
944 // Add the new partition if it differs from the original one and is
945 // non-empty. We can end up with an empty partition here if it was
946 // splittable but there is an unsplittable one that starts at the same
947 // offset.
948 if (New != Partitions[i]) {
949 if (New.BeginOffset != New.EndOffset)
950 Partitions.push_back(New);
951 // Mark the old one for removal.
952 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
953 ++NumDeadPartitions;
954 }
955
956 New.BeginOffset = New.EndOffset;
957 if (!New.IsSplittable) {
958 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
959 if (j != e && !Partitions[j].IsSplittable)
960 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
961 New.IsSplittable = true;
962 // If there is a trailing splittable partition which won't be fused into
963 // the next splittable partition go ahead and add it onto the partitions
964 // list.
965 if (New.BeginOffset < New.EndOffset &&
966 (j == e || !Partitions[j].IsSplittable ||
967 New.EndOffset < Partitions[j].BeginOffset)) {
968 Partitions.push_back(New);
969 New.BeginOffset = New.EndOffset = 0ull;
970 }
971 }
972 }
973
974 // Re-sort the partitions now that they have been split and merged into
975 // disjoint set of partitions. Also remove any of the dead partitions we've
976 // replaced in the process.
977 std::sort(Partitions.begin(), Partitions.end());
978 if (NumDeadPartitions) {
979 assert(Partitions.back().BeginOffset == UINT64_MAX);
980 assert(Partitions.back().EndOffset == UINT64_MAX);
981 assert((ptrdiff_t)NumDeadPartitions ==
982 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
983 }
984 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
985}
986
987AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
988 : AI(AI), PointerEscapingInstr(0) {
989 PartitionBuilder PB(TD, AI, *this);
990 if (!PB())
991 return;
992
993 if (Partitions.size() > 1) {
994 // Sort the uses. This arranges for the offsets to be in ascending order,
995 // and the sizes to be in descending order.
996 std::sort(Partitions.begin(), Partitions.end());
997
998 // Intersect splittability for all partitions with equal offsets and sizes.
999 // Then remove all but the first so that we have a sequence of non-equal but
1000 // potentially overlapping partitions.
1001 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1002 I = J) {
1003 ++J;
1004 while (J != E && *I == *J) {
1005 I->IsSplittable &= J->IsSplittable;
1006 ++J;
1007 }
1008 }
1009 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1010 Partitions.end());
1011
1012 // Split splittable and merge unsplittable partitions into a disjoint set
1013 // of partitions over the used space of the allocation.
1014 splitAndMergePartitions();
1015 }
1016
1017 // Now build up the user lists for each of these disjoint partitions by
1018 // re-walking the recursive users of the alloca.
1019 Uses.resize(Partitions.size());
1020 UseBuilder UB(TD, AI, *this);
1021 UB();
1022 for (iterator I = Partitions.begin(), E = Partitions.end(); I != E; ++I)
1023 std::stable_sort(use_begin(I), use_end(I));
1024}
1025
1026Type *AllocaPartitioning::getCommonType(iterator I) const {
1027 Type *Ty = 0;
1028 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1029 if (isa<MemIntrinsic>(*UI->User))
1030 continue;
1031 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1032 break;
1033
1034 Type *UserTy = 0;
1035 if (LoadInst *LI = dyn_cast<LoadInst>(&*UI->User)) {
1036 UserTy = LI->getType();
1037 } else if (StoreInst *SI = dyn_cast<StoreInst>(&*UI->User)) {
1038 UserTy = SI->getValueOperand()->getType();
1039 } else if (SelectInst *SI = dyn_cast<SelectInst>(&*UI->User)) {
1040 if (PointerType *PtrTy = dyn_cast<PointerType>(SI->getType()))
1041 UserTy = PtrTy->getElementType();
1042 } else if (PHINode *PN = dyn_cast<PHINode>(&*UI->User)) {
1043 if (PointerType *PtrTy = dyn_cast<PointerType>(PN->getType()))
1044 UserTy = PtrTy->getElementType();
1045 }
1046
1047 if (Ty && Ty != UserTy)
1048 return 0;
1049
1050 Ty = UserTy;
1051 }
1052 return Ty;
1053}
1054
1055void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1056 StringRef Indent) const {
1057 OS << Indent << "partition #" << (I - begin())
1058 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1059 << (I->IsSplittable ? " (splittable)" : "")
1060 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1061 << "\n";
1062}
1063
1064void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1065 StringRef Indent) const {
1066 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1067 UI != UE; ++UI) {
1068 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1069 << "used by: " << *UI->User << "\n";
1070 if (MemTransferInst *II = dyn_cast<MemTransferInst>(&*UI->User)) {
1071 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1072 bool IsDest;
1073 if (!MTO.IsSplittable)
1074 IsDest = UI->BeginOffset == MTO.DestBegin;
1075 else
1076 IsDest = MTO.DestBegin != 0u;
1077 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1078 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1079 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1080 }
1081 }
1082}
1083
1084void AllocaPartitioning::print(raw_ostream &OS) const {
1085 if (PointerEscapingInstr) {
1086 OS << "No partitioning for alloca: " << AI << "\n"
1087 << " A pointer to this alloca escaped by:\n"
1088 << " " << *PointerEscapingInstr << "\n";
1089 return;
1090 }
1091
1092 OS << "Partitioning of alloca: " << AI << "\n";
1093 unsigned Num = 0;
1094 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1095 print(OS, I);
1096 printUsers(OS, I);
1097 }
1098}
1099
1100void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1101void AllocaPartitioning::dump() const { print(dbgs()); }
1102
1103
1104namespace {
1105/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1106///
1107/// This pass takes allocations which can be completely analyzed (that is, they
1108/// don't escape) and tries to turn them into scalar SSA values. There are
1109/// a few steps to this process.
1110///
1111/// 1) It takes allocations of aggregates and analyzes the ways in which they
1112/// are used to try to split them into smaller allocations, ideally of
1113/// a single scalar data type. It will split up memcpy and memset accesses
1114/// as necessary and try to isolate invidual scalar accesses.
1115/// 2) It will transform accesses into forms which are suitable for SSA value
1116/// promotion. This can be replacing a memset with a scalar store of an
1117/// integer value, or it can involve speculating operations on a PHI or
1118/// select to be a PHI or select of the results.
1119/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1120/// onto insert and extract operations on a vector value, and convert them to
1121/// this form. By doing so, it will enable promotion of vector aggregates to
1122/// SSA vector values.
1123class SROA : public FunctionPass {
1124 LLVMContext *C;
1125 const TargetData *TD;
1126 DominatorTree *DT;
1127
1128 /// \brief Worklist of alloca instructions to simplify.
1129 ///
1130 /// Each alloca in the function is added to this. Each new alloca formed gets
1131 /// added to it as well to recursively simplify unless that alloca can be
1132 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1133 /// the one being actively rewritten, we add it back onto the list if not
1134 /// already present to ensure it is re-visited.
1135 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1136
1137 /// \brief A collection of instructions to delete.
1138 /// We try to batch deletions to simplify code and make things a bit more
1139 /// efficient.
1140 SmallVector<Instruction *, 8> DeadInsts;
1141
1142 /// \brief A set to prevent repeatedly marking an instruction split into many
1143 /// uses as dead. Only used to guard insertion into DeadInsts.
1144 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1145
1146 /// \brief A set of deleted alloca instructions.
1147 ///
1148 /// These pointers are *no longer valid* as they have been deleted. They are
1149 /// used to remove deleted allocas from the list of promotable allocas.
1150 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
1151
1152 /// \brief A collection of alloca instructions we can directly promote.
1153 std::vector<AllocaInst *> PromotableAllocas;
1154
1155public:
1156 SROA() : FunctionPass(ID), C(0), TD(0), DT(0) {
1157 initializeSROAPass(*PassRegistry::getPassRegistry());
1158 }
1159 bool runOnFunction(Function &F);
1160 void getAnalysisUsage(AnalysisUsage &AU) const;
1161
1162 const char *getPassName() const { return "SROA"; }
1163 static char ID;
1164
1165private:
1166 friend class AllocaPartitionRewriter;
1167 friend class AllocaPartitionVectorRewriter;
1168
1169 bool rewriteAllocaPartition(AllocaInst &AI,
1170 AllocaPartitioning &P,
1171 AllocaPartitioning::iterator PI);
1172 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1173 bool runOnAlloca(AllocaInst &AI);
1174 void deleteDeadInstructions();
1175};
1176}
1177
1178char SROA::ID = 0;
1179
1180FunctionPass *llvm::createSROAPass() {
1181 return new SROA();
1182}
1183
1184INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1185 false, false)
1186INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1187INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1188 false, false)
1189
1190/// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1191///
1192/// If the provided GEP is all-constant, the total byte offset formed by the
1193/// GEP is computed and Offset is set to it. If the GEP has any non-constant
1194/// operands, the function returns false and the value of Offset is unmodified.
1195static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1196 APInt &Offset) {
1197 APInt GEPOffset(Offset.getBitWidth(), 0);
1198 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1199 GTI != GTE; ++GTI) {
1200 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1201 if (!OpC)
1202 return false;
1203 if (OpC->isZero()) continue;
1204
1205 // Handle a struct index, which adds its field offset to the pointer.
1206 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1207 unsigned ElementIdx = OpC->getZExtValue();
1208 const StructLayout *SL = TD.getStructLayout(STy);
1209 GEPOffset += APInt(Offset.getBitWidth(),
1210 SL->getElementOffset(ElementIdx));
1211 continue;
1212 }
1213
1214 APInt TypeSize(Offset.getBitWidth(),
1215 TD.getTypeAllocSize(GTI.getIndexedType()));
1216 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1217 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1218 "vector element size is not a multiple of 8, cannot GEP over it");
1219 TypeSize = VTy->getScalarSizeInBits() / 8;
1220 }
1221
1222 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1223 }
1224 Offset = GEPOffset;
1225 return true;
1226}
1227
1228/// \brief Build a GEP out of a base pointer and indices.
1229///
1230/// This will return the BasePtr if that is valid, or build a new GEP
1231/// instruction using the IRBuilder if GEP-ing is needed.
1232static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1233 SmallVectorImpl<Value *> &Indices,
1234 const Twine &Prefix) {
1235 if (Indices.empty())
1236 return BasePtr;
1237
1238 // A single zero index is a no-op, so check for this and avoid building a GEP
1239 // in that case.
1240 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1241 return BasePtr;
1242
1243 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1244}
1245
1246/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1247/// TargetTy without changing the offset of the pointer.
1248///
1249/// This routine assumes we've already established a properly offset GEP with
1250/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1251/// zero-indices down through type layers until we find one the same as
1252/// TargetTy. If we can't find one with the same type, we at least try to use
1253/// one with the same size. If none of that works, we just produce the GEP as
1254/// indicated by Indices to have the correct offset.
1255static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1256 Value *BasePtr, Type *Ty, Type *TargetTy,
1257 SmallVectorImpl<Value *> &Indices,
1258 const Twine &Prefix) {
1259 if (Ty == TargetTy)
1260 return buildGEP(IRB, BasePtr, Indices, Prefix);
1261
1262 // See if we can descend into a struct and locate a field with the correct
1263 // type.
1264 unsigned NumLayers = 0;
1265 Type *ElementTy = Ty;
1266 do {
1267 if (ElementTy->isPointerTy())
1268 break;
1269 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1270 ElementTy = SeqTy->getElementType();
1271 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1272 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1273 ElementTy = *STy->element_begin();
1274 Indices.push_back(IRB.getInt32(0));
1275 } else {
1276 break;
1277 }
1278 ++NumLayers;
1279 } while (ElementTy != TargetTy);
1280 if (ElementTy != TargetTy)
1281 Indices.erase(Indices.end() - NumLayers, Indices.end());
1282
1283 return buildGEP(IRB, BasePtr, Indices, Prefix);
1284}
1285
1286/// \brief Recursively compute indices for a natural GEP.
1287///
1288/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1289/// element types adding appropriate indices for the GEP.
1290static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1291 Value *Ptr, Type *Ty, APInt &Offset,
1292 Type *TargetTy,
1293 SmallVectorImpl<Value *> &Indices,
1294 const Twine &Prefix) {
1295 if (Offset == 0)
1296 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1297
1298 // We can't recurse through pointer types.
1299 if (Ty->isPointerTy())
1300 return 0;
1301
1302 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1303 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1304 if (ElementSizeInBits % 8)
1305 return 0; // GEPs over multiple of 8 size vector elements are invalid.
1306 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1307 APInt NumSkippedElements = Offset.udiv(ElementSize);
1308 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1309 return 0;
1310 Offset -= NumSkippedElements * ElementSize;
1311 Indices.push_back(IRB.getInt(NumSkippedElements));
1312 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1313 Offset, TargetTy, Indices, Prefix);
1314 }
1315
1316 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1317 Type *ElementTy = ArrTy->getElementType();
1318 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1319 APInt NumSkippedElements = Offset.udiv(ElementSize);
1320 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1321 return 0;
1322
1323 Offset -= NumSkippedElements * ElementSize;
1324 Indices.push_back(IRB.getInt(NumSkippedElements));
1325 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1326 Indices, Prefix);
1327 }
1328
1329 StructType *STy = dyn_cast<StructType>(Ty);
1330 if (!STy)
1331 return 0;
1332
1333 const StructLayout *SL = TD.getStructLayout(STy);
1334 uint64_t StructOffset = Offset.getZExtValue();
1335 if (StructOffset > SL->getSizeInBytes())
1336 return 0;
1337 unsigned Index = SL->getElementContainingOffset(StructOffset);
1338 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1339 Type *ElementTy = STy->getElementType(Index);
1340 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1341 return 0; // The offset points into alignment padding.
1342
1343 Indices.push_back(IRB.getInt32(Index));
1344 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1345 Indices, Prefix);
1346}
1347
1348/// \brief Get a natural GEP from a base pointer to a particular offset and
1349/// resulting in a particular type.
1350///
1351/// The goal is to produce a "natural" looking GEP that works with the existing
1352/// composite types to arrive at the appropriate offset and element type for
1353/// a pointer. TargetTy is the element type the returned GEP should point-to if
1354/// possible. We recurse by decreasing Offset, adding the appropriate index to
1355/// Indices, and setting Ty to the result subtype.
1356///
1357/// If no natural GEP can be constructed, this function returns a null Value*.
1358static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1359 Value *Ptr, APInt Offset, Type *TargetTy,
1360 SmallVectorImpl<Value *> &Indices,
1361 const Twine &Prefix) {
1362 PointerType *Ty = cast<PointerType>(Ptr->getType());
1363
1364 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1365 // an i8.
1366 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1367 return 0;
1368
1369 Type *ElementTy = Ty->getElementType();
1370 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1371 if (ElementSize == 0)
1372 return 0; // Zero-length arrays can't help us build a natural GEP.
1373 APInt NumSkippedElements = Offset.udiv(ElementSize);
1374
1375 Offset -= NumSkippedElements * ElementSize;
1376 Indices.push_back(IRB.getInt(NumSkippedElements));
1377 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1378 Indices, Prefix);
1379}
1380
1381/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1382/// resulting pointer has PointerTy.
1383///
1384/// This tries very hard to compute a "natural" GEP which arrives at the offset
1385/// and produces the pointer type desired. Where it cannot, it will try to use
1386/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1387/// fails, it will try to use an existing i8* and GEP to the byte offset and
1388/// bitcast to the type.
1389///
1390/// The strategy for finding the more natural GEPs is to peel off layers of the
1391/// pointer, walking back through bit casts and GEPs, searching for a base
1392/// pointer from which we can compute a natural GEP with the desired
1393/// properities. The algorithm tries to fold as many constant indices into
1394/// a single GEP as possible, thus making each GEP more independent of the
1395/// surrounding code.
1396static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1397 Value *Ptr, APInt Offset, Type *PointerTy,
1398 const Twine &Prefix) {
1399 // Even though we don't look through PHI nodes, we could be called on an
1400 // instruction in an unreachable block, which may be on a cycle.
1401 SmallPtrSet<Value *, 4> Visited;
1402 Visited.insert(Ptr);
1403 SmallVector<Value *, 4> Indices;
1404
1405 // We may end up computing an offset pointer that has the wrong type. If we
1406 // never are able to compute one directly that has the correct type, we'll
1407 // fall back to it, so keep it around here.
1408 Value *OffsetPtr = 0;
1409
1410 // Remember any i8 pointer we come across to re-use if we need to do a raw
1411 // byte offset.
1412 Value *Int8Ptr = 0;
1413 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1414
1415 Type *TargetTy = PointerTy->getPointerElementType();
1416
1417 do {
1418 // First fold any existing GEPs into the offset.
1419 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1420 APInt GEPOffset(Offset.getBitWidth(), 0);
1421 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1422 break;
1423 Offset += GEPOffset;
1424 Ptr = GEP->getPointerOperand();
1425 if (!Visited.insert(Ptr))
1426 break;
1427 }
1428
1429 // See if we can perform a natural GEP here.
1430 Indices.clear();
1431 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1432 Indices, Prefix)) {
1433 if (P->getType() == PointerTy) {
1434 // Zap any offset pointer that we ended up computing in previous rounds.
1435 if (OffsetPtr && OffsetPtr->use_empty())
1436 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1437 I->eraseFromParent();
1438 return P;
1439 }
1440 if (!OffsetPtr) {
1441 OffsetPtr = P;
1442 }
1443 }
1444
1445 // Stash this pointer if we've found an i8*.
1446 if (Ptr->getType()->isIntegerTy(8)) {
1447 Int8Ptr = Ptr;
1448 Int8PtrOffset = Offset;
1449 }
1450
1451 // Peel off a layer of the pointer and update the offset appropriately.
1452 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1453 Ptr = cast<Operator>(Ptr)->getOperand(0);
1454 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1455 if (GA->mayBeOverridden())
1456 break;
1457 Ptr = GA->getAliasee();
1458 } else {
1459 break;
1460 }
1461 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1462 } while (Visited.insert(Ptr));
1463
1464 if (!OffsetPtr) {
1465 if (!Int8Ptr) {
1466 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1467 Prefix + ".raw_cast");
1468 Int8PtrOffset = Offset;
1469 }
1470
1471 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1472 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1473 Prefix + ".raw_idx");
1474 }
1475 Ptr = OffsetPtr;
1476
1477 // On the off chance we were targeting i8*, guard the bitcast here.
1478 if (Ptr->getType() != PointerTy)
1479 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1480
1481 return Ptr;
1482}
1483
1484/// \brief Test whether the given alloca partition can be promoted to a vector.
1485///
1486/// This is a quick test to check whether we can rewrite a particular alloca
1487/// partition (and its newly formed alloca) into a vector alloca with only
1488/// whole-vector loads and stores such that it could be promoted to a vector
1489/// SSA value. We only can ensure this for a limited set of operations, and we
1490/// don't want to do the rewrites unless we are confident that the result will
1491/// be promotable, so we have an early test here.
1492static bool isVectorPromotionViable(const TargetData &TD,
1493 Type *AllocaTy,
1494 AllocaPartitioning &P,
1495 uint64_t PartitionBeginOffset,
1496 uint64_t PartitionEndOffset,
1497 AllocaPartitioning::const_use_iterator I,
1498 AllocaPartitioning::const_use_iterator E) {
1499 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1500 if (!Ty)
1501 return false;
1502
1503 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1504 uint64_t ElementSize = Ty->getScalarSizeInBits();
1505
1506 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1507 // that aren't byte sized.
1508 if (ElementSize % 8)
1509 return false;
1510 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1511 VecSize /= 8;
1512 ElementSize /= 8;
1513
1514 for (; I != E; ++I) {
1515 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1516 uint64_t BeginIndex = BeginOffset / ElementSize;
1517 if (BeginIndex * ElementSize != BeginOffset ||
1518 BeginIndex >= Ty->getNumElements())
1519 return false;
1520 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1521 uint64_t EndIndex = EndOffset / ElementSize;
1522 if (EndIndex * ElementSize != EndOffset ||
1523 EndIndex > Ty->getNumElements())
1524 return false;
1525
1526 // FIXME: We should build shuffle vector instructions to handle
1527 // non-element-sized accesses.
1528 if ((EndOffset - BeginOffset) != ElementSize &&
1529 (EndOffset - BeginOffset) != VecSize)
1530 return false;
1531
1532 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&*I->User)) {
1533 if (MI->isVolatile())
1534 return false;
1535 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(&*I->User)) {
1536 const AllocaPartitioning::MemTransferOffsets &MTO
1537 = P.getMemTransferOffsets(*MTI);
1538 if (!MTO.IsSplittable)
1539 return false;
1540 }
1541 } else if (I->Ptr->getType()->getPointerElementType()->isStructTy()) {
1542 // Disable vector promotion when there are loads or stores of an FCA.
1543 return false;
1544 } else if (!isa<LoadInst>(*I->User) && !isa<StoreInst>(*I->User)) {
1545 return false;
1546 }
1547 }
1548 return true;
1549}
1550
1551namespace {
1552/// \brief Visitor to rewrite instructions using a partition of an alloca to
1553/// use a new alloca.
1554///
1555/// Also implements the rewriting to vector-based accesses when the partition
1556/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1557/// lives here.
1558class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
1559 bool> {
1560 // Befriend the base class so it can delegate to private visit methods.
1561 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
1562
1563 const TargetData &TD;
1564 AllocaPartitioning &P;
1565 SROA &Pass;
1566 AllocaInst &OldAI, &NewAI;
1567 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1568
1569 // If we are rewriting an alloca partition which can be written as pure
1570 // vector operations, we stash extra information here. When VecTy is
1571 // non-null, we have some strict guarantees about the rewriten alloca:
1572 // - The new alloca is exactly the size of the vector type here.
1573 // - The accesses all either map to the entire vector or to a single
1574 // element.
1575 // - The set of accessing instructions is only one of those handled above
1576 // in isVectorPromotionViable. Generally these are the same access kinds
1577 // which are promotable via mem2reg.
1578 VectorType *VecTy;
1579 Type *ElementTy;
1580 uint64_t ElementSize;
1581
1582 // The offset of the partition user currently being rewritten.
1583 uint64_t BeginOffset, EndOffset;
1584 Instruction *OldPtr;
1585
1586 // The name prefix to use when rewriting instructions for this alloca.
1587 std::string NamePrefix;
1588
1589public:
1590 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
1591 AllocaPartitioning::iterator PI,
1592 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
1593 uint64_t NewBeginOffset, uint64_t NewEndOffset)
1594 : TD(TD), P(P), Pass(Pass),
1595 OldAI(OldAI), NewAI(NewAI),
1596 NewAllocaBeginOffset(NewBeginOffset),
1597 NewAllocaEndOffset(NewEndOffset),
1598 VecTy(), ElementTy(), ElementSize(),
1599 BeginOffset(), EndOffset() {
1600 }
1601
1602 /// \brief Visit the users of the alloca partition and rewrite them.
1603 bool visitUsers(AllocaPartitioning::const_use_iterator I,
1604 AllocaPartitioning::const_use_iterator E) {
1605 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
1606 NewAllocaBeginOffset, NewAllocaEndOffset,
1607 I, E)) {
1608 ++NumVectorized;
1609 VecTy = cast<VectorType>(NewAI.getAllocatedType());
1610 ElementTy = VecTy->getElementType();
1611 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
1612 "Only multiple-of-8 sized vector elements are viable");
1613 ElementSize = VecTy->getScalarSizeInBits() / 8;
1614 }
1615 bool CanSROA = true;
1616 for (; I != E; ++I) {
1617 BeginOffset = I->BeginOffset;
1618 EndOffset = I->EndOffset;
1619 OldPtr = I->Ptr;
1620 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
1621 CanSROA &= visit(I->User);
1622 }
1623 if (VecTy) {
1624 assert(CanSROA);
1625 VecTy = 0;
1626 ElementTy = 0;
1627 ElementSize = 0;
1628 }
1629 return CanSROA;
1630 }
1631
1632private:
1633 // Every instruction which can end up as a user must have a rewrite rule.
1634 bool visitInstruction(Instruction &I) {
1635 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1636 llvm_unreachable("No rewrite rule for this instruction!");
1637 }
1638
1639 Twine getName(const Twine &Suffix) {
1640 return NamePrefix + Suffix;
1641 }
1642
1643 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
1644 assert(BeginOffset >= NewAllocaBeginOffset);
1645 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
1646 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
1647 }
1648
1649 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
1650 assert(VecTy && "Can only call getIndex when rewriting a vector");
1651 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1652 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1653 uint32_t Index = RelOffset / ElementSize;
1654 assert(Index * ElementSize == RelOffset);
1655 return IRB.getInt32(Index);
1656 }
1657
1658 void deleteIfTriviallyDead(Value *V) {
1659 Instruction *I = cast<Instruction>(V);
1660 if (isInstructionTriviallyDead(I))
1661 Pass.DeadInsts.push_back(I);
1662 }
1663
1664 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
1665 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1666 return IRB.CreateIntToPtr(V, Ty);
1667 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1668 return IRB.CreatePtrToInt(V, Ty);
1669
1670 return IRB.CreateBitCast(V, Ty);
1671 }
1672
1673 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
1674 Value *Result;
1675 if (LI.getType() == VecTy->getElementType() ||
1676 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1677 Result
1678 = IRB.CreateExtractElement(IRB.CreateLoad(&NewAI, getName(".load")),
1679 getIndex(IRB, BeginOffset),
1680 getName(".extract"));
1681 } else {
1682 Result = IRB.CreateLoad(&NewAI, getName(".load"));
1683 }
1684 if (Result->getType() != LI.getType())
1685 Result = getValueCast(IRB, Result, LI.getType());
1686 LI.replaceAllUsesWith(Result);
1687 Pass.DeadInsts.push_back(&LI);
1688
1689 DEBUG(dbgs() << " to: " << *Result << "\n");
1690 return true;
1691 }
1692
1693 bool visitLoadInst(LoadInst &LI) {
1694 DEBUG(dbgs() << " original: " << LI << "\n");
1695 Value *OldOp = LI.getOperand(0);
1696 assert(OldOp == OldPtr);
1697 IRBuilder<> IRB(&LI);
1698
1699 if (VecTy)
1700 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
1701
1702 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1703 LI.getPointerOperand()->getType());
1704 LI.setOperand(0, NewPtr);
1705 DEBUG(dbgs() << " to: " << LI << "\n");
1706
1707 deleteIfTriviallyDead(OldOp);
1708 return NewPtr == &NewAI && !LI.isVolatile();
1709 }
1710
1711 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
1712 Value *OldOp) {
1713 Value *V = SI.getValueOperand();
1714 if (V->getType() == ElementTy ||
1715 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1716 if (V->getType() != ElementTy)
1717 V = getValueCast(IRB, V, ElementTy);
1718 V = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1719 getIndex(IRB, BeginOffset),
1720 getName(".insert"));
1721 } else if (V->getType() != VecTy) {
1722 V = getValueCast(IRB, V, VecTy);
1723 }
1724 StoreInst *Store = IRB.CreateStore(V, &NewAI);
1725 Pass.DeadInsts.push_back(&SI);
1726
1727 (void)Store;
1728 DEBUG(dbgs() << " to: " << *Store << "\n");
1729 return true;
1730 }
1731
1732 bool visitStoreInst(StoreInst &SI) {
1733 DEBUG(dbgs() << " original: " << SI << "\n");
1734 Value *OldOp = SI.getOperand(1);
1735 assert(OldOp == OldPtr);
1736 IRBuilder<> IRB(&SI);
1737
1738 if (VecTy)
1739 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
1740
1741 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1742 SI.getPointerOperand()->getType());
1743 SI.setOperand(1, NewPtr);
1744 DEBUG(dbgs() << " to: " << SI << "\n");
1745
1746 deleteIfTriviallyDead(OldOp);
1747 return NewPtr == &NewAI && !SI.isVolatile();
1748 }
1749
1750 bool visitMemSetInst(MemSetInst &II) {
1751 DEBUG(dbgs() << " original: " << II << "\n");
1752 IRBuilder<> IRB(&II);
1753 assert(II.getRawDest() == OldPtr);
1754
1755 // If the memset has a variable size, it cannot be split, just adjust the
1756 // pointer to the new alloca.
1757 if (!isa<Constant>(II.getLength())) {
1758 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1759 deleteIfTriviallyDead(OldPtr);
1760 return false;
1761 }
1762
1763 // Record this instruction for deletion.
1764 if (Pass.DeadSplitInsts.insert(&II))
1765 Pass.DeadInsts.push_back(&II);
1766
1767 Type *AllocaTy = NewAI.getAllocatedType();
1768 Type *ScalarTy = AllocaTy->getScalarType();
1769
1770 // If this doesn't map cleanly onto the alloca type, and that type isn't
1771 // a single value type, just emit a memset.
1772 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
1773 EndOffset != NewAllocaEndOffset ||
1774 !AllocaTy->isSingleValueType() ||
1775 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
1776 Type *SizeTy = II.getLength()->getType();
1777 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
1778
1779 CallInst *New
1780 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
1781 II.getRawDest()->getType()),
1782 II.getValue(), Size, II.getAlignment(),
1783 II.isVolatile());
1784 (void)New;
1785 DEBUG(dbgs() << " to: " << *New << "\n");
1786 return false;
1787 }
1788
1789 // If we can represent this as a simple value, we have to build the actual
1790 // value to store, which requires expanding the byte present in memset to
1791 // a sensible representation for the alloca type. This is essentially
1792 // splatting the byte to a sufficiently wide integer, bitcasting to the
1793 // desired scalar type, and splatting it across any desired vector type.
1794 Value *V = II.getValue();
1795 IntegerType *VTy = cast<IntegerType>(V->getType());
1796 Type *IntTy = Type::getIntNTy(VTy->getContext(),
1797 TD.getTypeSizeInBits(ScalarTy));
1798 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
1799 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
1800 ConstantExpr::getUDiv(
1801 Constant::getAllOnesValue(IntTy),
1802 ConstantExpr::getZExt(
1803 Constant::getAllOnesValue(V->getType()),
1804 IntTy)),
1805 getName(".isplat"));
1806 if (V->getType() != ScalarTy) {
1807 if (ScalarTy->isPointerTy())
1808 V = IRB.CreateIntToPtr(V, ScalarTy);
1809 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
1810 V = IRB.CreateBitCast(V, ScalarTy);
1811 else if (ScalarTy->isIntegerTy())
1812 llvm_unreachable("Computed different integer types with equal widths");
1813 else
1814 llvm_unreachable("Invalid scalar type");
1815 }
1816
1817 // If this is an element-wide memset of a vectorizable alloca, insert it.
1818 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
1819 EndOffset < NewAllocaEndOffset)) {
1820 StoreInst *Store = IRB.CreateStore(
1821 IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1822 getIndex(IRB, BeginOffset),
1823 getName(".insert")),
1824 &NewAI);
1825 (void)Store;
1826 DEBUG(dbgs() << " to: " << *Store << "\n");
1827 return true;
1828 }
1829
1830 // Splat to a vector if needed.
1831 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
1832 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
1833 V = IRB.CreateShuffleVector(
1834 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
1835 IRB.getInt32(0), getName(".vsplat.insert")),
1836 UndefValue::get(SplatSourceTy),
1837 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
1838 getName(".vsplat.shuffle"));
1839 assert(V->getType() == VecTy);
1840 }
1841
1842 Value *New = IRB.CreateStore(V, &NewAI, II.isVolatile());
1843 (void)New;
1844 DEBUG(dbgs() << " to: " << *New << "\n");
1845 return !II.isVolatile();
1846 }
1847
1848 bool visitMemTransferInst(MemTransferInst &II) {
1849 // Rewriting of memory transfer instructions can be a bit tricky. We break
1850 // them into two categories: split intrinsics and unsplit intrinsics.
1851
1852 DEBUG(dbgs() << " original: " << II << "\n");
1853 IRBuilder<> IRB(&II);
1854
1855 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
1856 bool IsDest = II.getRawDest() == OldPtr;
1857
1858 const AllocaPartitioning::MemTransferOffsets &MTO
1859 = P.getMemTransferOffsets(II);
1860
1861 // For unsplit intrinsics, we simply modify the source and destination
1862 // pointers in place. This isn't just an optimization, it is a matter of
1863 // correctness. With unsplit intrinsics we may be dealing with transfers
1864 // within a single alloca before SROA ran, or with transfers that have
1865 // a variable length. We may also be dealing with memmove instead of
1866 // memcpy, and so simply updating the pointers is the necessary for us to
1867 // update both source and dest of a single call.
1868 if (!MTO.IsSplittable) {
1869 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
1870 if (IsDest)
1871 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1872 else
1873 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
1874
1875 DEBUG(dbgs() << " to: " << II << "\n");
1876 deleteIfTriviallyDead(OldOp);
1877 return false;
1878 }
1879 // For split transfer intrinsics we have an incredibly useful assurance:
1880 // the source and destination do not reside within the same alloca, and at
1881 // least one of them does not escape. This means that we can replace
1882 // memmove with memcpy, and we don't need to worry about all manner of
1883 // downsides to splitting and transforming the operations.
1884
1885 // Compute the relative offset within the transfer.
1886 unsigned IntPtrWidth = TD.getPointerSizeInBits();
1887 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
1888 : MTO.SourceBegin));
1889
1890 // If this doesn't map cleanly onto the alloca type, and that type isn't
1891 // a single value type, just emit a memcpy.
1892 bool EmitMemCpy
1893 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
1894 EndOffset != NewAllocaEndOffset ||
1895 !NewAI.getAllocatedType()->isSingleValueType());
1896
1897 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
1898 // size hasn't been shrunk based on analysis of the viable range, this is
1899 // a no-op.
1900 if (EmitMemCpy && &OldAI == &NewAI) {
1901 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
1902 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
1903 // Ensure the start lines up.
1904 assert(BeginOffset == OrigBegin);
1905
1906 // Rewrite the size as needed.
1907 if (EndOffset != OrigEnd)
1908 II.setLength(ConstantInt::get(II.getLength()->getType(),
1909 EndOffset - BeginOffset));
1910 return false;
1911 }
1912 // Record this instruction for deletion.
1913 if (Pass.DeadSplitInsts.insert(&II))
1914 Pass.DeadInsts.push_back(&II);
1915
1916 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
1917 EndOffset < NewAllocaEndOffset);
1918
1919 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
1920 : II.getRawDest()->getType();
1921 if (!EmitMemCpy)
1922 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
1923 : NewAI.getType();
1924
1925 // Compute the other pointer, folding as much as possible to produce
1926 // a single, simple GEP in most cases.
1927 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
1928 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
1929 getName("." + OtherPtr->getName()));
1930
1931 // Strip all inbounds GEPs and pointer casts to try to dig out any root
1932 // alloca that should be re-examined after rewriting this instruction.
1933 if (AllocaInst *AI
1934 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
1935 Pass.Worklist.insert(AI);
1936
1937 if (EmitMemCpy) {
1938 Value *OurPtr
1939 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
1940 : II.getRawSource()->getType());
1941 Type *SizeTy = II.getLength()->getType();
1942 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
1943
1944 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
1945 IsDest ? OtherPtr : OurPtr,
1946 Size, II.getAlignment(),
1947 II.isVolatile());
1948 (void)New;
1949 DEBUG(dbgs() << " to: " << *New << "\n");
1950 return false;
1951 }
1952
1953 Value *SrcPtr = OtherPtr;
1954 Value *DstPtr = &NewAI;
1955 if (!IsDest)
1956 std::swap(SrcPtr, DstPtr);
1957
1958 Value *Src;
1959 if (IsVectorElement && !IsDest) {
1960 // We have to extract rather than load.
1961 Src = IRB.CreateExtractElement(IRB.CreateLoad(SrcPtr,
1962 getName(".copyload")),
1963 getIndex(IRB, BeginOffset),
1964 getName(".copyextract"));
1965 } else {
1966 Src = IRB.CreateLoad(SrcPtr, II.isVolatile(), getName(".copyload"));
1967 }
1968
1969 if (IsVectorElement && IsDest) {
1970 // We have to insert into a loaded copy before storing.
1971 Src = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")),
1972 Src, getIndex(IRB, BeginOffset),
1973 getName(".insert"));
1974 }
1975
1976 Value *Store = IRB.CreateStore(Src, DstPtr, II.isVolatile());
1977 (void)Store;
1978 DEBUG(dbgs() << " to: " << *Store << "\n");
1979 return !II.isVolatile();
1980 }
1981
1982 bool visitIntrinsicInst(IntrinsicInst &II) {
1983 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
1984 II.getIntrinsicID() == Intrinsic::lifetime_end);
1985 DEBUG(dbgs() << " original: " << II << "\n");
1986 IRBuilder<> IRB(&II);
1987 assert(II.getArgOperand(1) == OldPtr);
1988
1989 // Record this instruction for deletion.
1990 if (Pass.DeadSplitInsts.insert(&II))
1991 Pass.DeadInsts.push_back(&II);
1992
1993 ConstantInt *Size
1994 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
1995 EndOffset - BeginOffset);
1996 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
1997 Value *New;
1998 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
1999 New = IRB.CreateLifetimeStart(Ptr, Size);
2000 else
2001 New = IRB.CreateLifetimeEnd(Ptr, Size);
2002
2003 DEBUG(dbgs() << " to: " << *New << "\n");
2004 return true;
2005 }
2006
2007 /// PHI instructions that use an alloca and are subsequently loaded can be
2008 /// rewritten to load both input pointers in the pred blocks and then PHI the
2009 /// results, allowing the load of the alloca to be promoted.
2010 /// From this:
2011 /// %P2 = phi [i32* %Alloca, i32* %Other]
2012 /// %V = load i32* %P2
2013 /// to:
2014 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2015 /// ...
2016 /// %V2 = load i32* %Other
2017 /// ...
2018 /// %V = phi [i32 %V1, i32 %V2]
2019 ///
2020 /// We can do this to a select if its only uses are loads and if the operand
2021 /// to the select can be loaded unconditionally.
2022 ///
2023 /// FIXME: This should be hoisted into a generic utility, likely in
2024 /// Transforms/Util/Local.h
2025 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
2026 // For now, we can only do this promotion if the load is in the same block
2027 // as the PHI, and if there are no stores between the phi and load.
2028 // TODO: Allow recursive phi users.
2029 // TODO: Allow stores.
2030 BasicBlock *BB = PN.getParent();
2031 unsigned MaxAlign = 0;
2032 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
2033 UI != UE; ++UI) {
2034 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2035 if (LI == 0 || !LI->isSimple()) return false;
2036
2037 // For now we only allow loads in the same block as the PHI. This is
2038 // a common case that happens when instcombine merges two loads through
2039 // a PHI.
2040 if (LI->getParent() != BB) return false;
2041
2042 // Ensure that there are no instructions between the PHI and the load that
2043 // could store.
2044 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
2045 if (BBI->mayWriteToMemory())
2046 return false;
2047
2048 MaxAlign = std::max(MaxAlign, LI->getAlignment());
2049 Loads.push_back(LI);
2050 }
2051
2052 // We can only transform this if it is safe to push the loads into the
2053 // predecessor blocks. The only thing to watch out for is that we can't put
2054 // a possibly trapping load in the predecessor if it is a critical edge.
2055 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
2056 ++Idx) {
2057 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
2058 Value *InVal = PN.getIncomingValue(Idx);
2059
2060 // If the value is produced by the terminator of the predecessor (an
2061 // invoke) or it has side-effects, there is no valid place to put a load
2062 // in the predecessor.
2063 if (TI == InVal || TI->mayHaveSideEffects())
2064 return false;
2065
2066 // If the predecessor has a single successor, then the edge isn't
2067 // critical.
2068 if (TI->getNumSuccessors() == 1)
2069 continue;
2070
2071 // If this pointer is always safe to load, or if we can prove that there
2072 // is already a load in the block, then we can move the load to the pred
2073 // block.
2074 if (InVal->isDereferenceablePointer() ||
2075 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
2076 continue;
2077
2078 return false;
2079 }
2080
2081 return true;
2082 }
2083
2084 bool visitPHINode(PHINode &PN) {
2085 DEBUG(dbgs() << " original: " << PN << "\n");
2086 // We would like to compute a new pointer in only one place, but have it be
2087 // as local as possible to the PHI. To do that, we re-use the location of
2088 // the old pointer, which necessarily must be in the right position to
2089 // dominate the PHI.
2090 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2091
2092 SmallVector<LoadInst *, 4> Loads;
2093 if (!isSafePHIToSpeculate(PN, Loads)) {
2094 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2095 // Replace the operands which were using the old pointer.
2096 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2097 for (; OI != OE; ++OI)
2098 if (*OI == OldPtr)
2099 *OI = NewPtr;
2100
2101 DEBUG(dbgs() << " to: " << PN << "\n");
2102 deleteIfTriviallyDead(OldPtr);
2103 return false;
2104 }
2105 assert(!Loads.empty());
2106
2107 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
2108 IRBuilder<> PHIBuilder(&PN);
2109 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues());
2110 NewPN->takeName(&PN);
2111
2112 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
2113 // matter which one we get and if any differ, it doesn't matter.
2114 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
2115 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
2116 unsigned Align = SomeLoad->getAlignment();
2117 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2118
2119 // Rewrite all loads of the PN to use the new PHI.
2120 do {
2121 LoadInst *LI = Loads.pop_back_val();
2122 LI->replaceAllUsesWith(NewPN);
2123 Pass.DeadInsts.push_back(LI);
2124 } while (!Loads.empty());
2125
2126 // Inject loads into all of the pred blocks.
2127 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
2128 BasicBlock *Pred = PN.getIncomingBlock(Idx);
2129 TerminatorInst *TI = Pred->getTerminator();
2130 Value *InVal = PN.getIncomingValue(Idx);
2131 IRBuilder<> PredBuilder(TI);
2132
2133 // Map the value to the new alloca pointer if this was the old alloca
2134 // pointer.
2135 bool ThisOperand = InVal == OldPtr;
2136 if (ThisOperand)
2137 InVal = NewPtr;
2138
2139 LoadInst *Load
2140 = PredBuilder.CreateLoad(InVal, getName(".sroa.speculate." +
2141 Pred->getName()));
2142 ++NumLoadsSpeculated;
2143 Load->setAlignment(Align);
2144 if (TBAATag)
2145 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
2146 NewPN->addIncoming(Load, Pred);
2147
2148 if (ThisOperand)
2149 continue;
2150 Instruction *OtherPtr = dyn_cast<Instruction>(InVal);
2151 if (!OtherPtr)
2152 // No uses to rewrite.
2153 continue;
2154
2155 // Try to lookup and rewrite any partition uses corresponding to this phi
2156 // input.
2157 AllocaPartitioning::iterator PI
2158 = P.findPartitionForPHIOrSelectOperand(PN, OtherPtr);
2159 if (PI != P.end()) {
2160 // If the other pointer is within the partitioning, replace the PHI in
2161 // its uses with the load we just speculated, or add another load for
2162 // it to rewrite if we've already replaced the PHI.
2163 AllocaPartitioning::use_iterator UI
2164 = P.findPartitionUseForPHIOrSelectOperand(PN, OtherPtr);
2165 if (isa<PHINode>(*UI->User))
2166 UI->User = Load;
2167 else {
2168 AllocaPartitioning::PartitionUse OtherUse = *UI;
2169 OtherUse.User = Load;
2170 P.use_insert(PI, std::upper_bound(UI, P.use_end(PI), OtherUse),
2171 OtherUse);
2172 }
2173 }
2174 }
2175 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
2176 return NewPtr == &NewAI;
2177 }
2178
2179 /// Select instructions that use an alloca and are subsequently loaded can be
2180 /// rewritten to load both input pointers and then select between the result,
2181 /// allowing the load of the alloca to be promoted.
2182 /// From this:
2183 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
2184 /// %V = load i32* %P2
2185 /// to:
2186 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2187 /// %V2 = load i32* %Other
2188 /// %V = select i1 %cond, i32 %V1, i32 %V2
2189 ///
2190 /// We can do this to a select if its only uses are loads and if the operand
2191 /// to the select can be loaded unconditionally.
2192 bool isSafeSelectToSpeculate(SelectInst &SI,
2193 SmallVectorImpl<LoadInst *> &Loads) {
2194 Value *TValue = SI.getTrueValue();
2195 Value *FValue = SI.getFalseValue();
2196 bool TDerefable = TValue->isDereferenceablePointer();
2197 bool FDerefable = FValue->isDereferenceablePointer();
2198
2199 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
2200 UI != UE; ++UI) {
2201 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2202 if (LI == 0 || !LI->isSimple()) return false;
2203
2204 // Both operands to the select need to be dereferencable, either
2205 // absolutely (e.g. allocas) or at this point because we can see other
2206 // accesses to it.
2207 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
2208 LI->getAlignment(), &TD))
2209 return false;
2210 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
2211 LI->getAlignment(), &TD))
2212 return false;
2213 Loads.push_back(LI);
2214 }
2215
2216 return true;
2217 }
2218
2219 bool visitSelectInst(SelectInst &SI) {
2220 DEBUG(dbgs() << " original: " << SI << "\n");
2221 IRBuilder<> IRB(&SI);
2222
2223 // Find the operand we need to rewrite here.
2224 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2225 if (IsTrueVal)
2226 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2227 else
2228 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2229 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2230
2231 // If the select isn't safe to speculate, just use simple logic to emit it.
2232 SmallVector<LoadInst *, 4> Loads;
2233 if (!isSafeSelectToSpeculate(SI, Loads)) {
2234 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2235 DEBUG(dbgs() << " to: " << SI << "\n");
2236 deleteIfTriviallyDead(OldPtr);
2237 return false;
2238 }
2239
2240 Value *OtherPtr = IsTrueVal ? SI.getFalseValue() : SI.getTrueValue();
2241 AllocaPartitioning::iterator PI
2242 = P.findPartitionForPHIOrSelectOperand(SI, OtherPtr);
2243 AllocaPartitioning::PartitionUse OtherUse;
2244 if (PI != P.end()) {
2245 // If the other pointer is within the partitioning, remove the select
2246 // from its uses. We'll add in the new loads below.
2247 AllocaPartitioning::use_iterator UI
2248 = P.findPartitionUseForPHIOrSelectOperand(SI, OtherPtr);
2249 OtherUse = *UI;
2250 P.use_erase(PI, UI);
2251 }
2252
2253 Value *TV = IsTrueVal ? NewPtr : SI.getTrueValue();
2254 Value *FV = IsTrueVal ? SI.getFalseValue() : NewPtr;
2255 // Replace the loads of the select with a select of two loads.
2256 while (!Loads.empty()) {
2257 LoadInst *LI = Loads.pop_back_val();
2258
2259 IRB.SetInsertPoint(LI);
2260 LoadInst *TL =
2261 IRB.CreateLoad(TV, getName("." + LI->getName() + ".true"));
2262 LoadInst *FL =
2263 IRB.CreateLoad(FV, getName("." + LI->getName() + ".false"));
2264 NumLoadsSpeculated += 2;
2265 if (PI != P.end()) {
2266 LoadInst *OtherLoad = IsTrueVal ? FL : TL;
2267 assert(OtherUse.Ptr == OtherLoad->getOperand(0));
2268 OtherUse.User = OtherLoad;
2269 P.use_insert(PI, P.use_end(PI), OtherUse);
2270 }
2271
2272 // Transfer alignment and TBAA info if present.
2273 TL->setAlignment(LI->getAlignment());
2274 FL->setAlignment(LI->getAlignment());
2275 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2276 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2277 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2278 }
2279
2280 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL);
2281 V->takeName(LI);
2282 DEBUG(dbgs() << " speculated to: " << *V << "\n");
2283 LI->replaceAllUsesWith(V);
2284 Pass.DeadInsts.push_back(LI);
2285 }
2286 if (PI != P.end())
2287 std::stable_sort(P.use_begin(PI), P.use_end(PI));
2288
2289 deleteIfTriviallyDead(OldPtr);
2290 return NewPtr == &NewAI;
2291 }
2292
2293};
2294}
2295
2296/// \brief Try to find a partition of the aggregate type passed in for a given
2297/// offset and size.
2298///
2299/// This recurses through the aggregate type and tries to compute a subtype
2300/// based on the offset and size. When the offset and size span a sub-section
2301/// of an array, it will even compute a new array type for that sub-section.
2302static Type *getTypePartition(const TargetData &TD, Type *Ty,
2303 uint64_t Offset, uint64_t Size) {
2304 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2305 return Ty;
2306
2307 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2308 // We can't partition pointers...
2309 if (SeqTy->isPointerTy())
2310 return 0;
2311
2312 Type *ElementTy = SeqTy->getElementType();
2313 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2314 uint64_t NumSkippedElements = Offset / ElementSize;
2315 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2316 if (NumSkippedElements >= ArrTy->getNumElements())
2317 return 0;
2318 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2319 if (NumSkippedElements >= VecTy->getNumElements())
2320 return 0;
2321 Offset -= NumSkippedElements * ElementSize;
2322
2323 // First check if we need to recurse.
2324 if (Offset > 0 || Size < ElementSize) {
2325 // Bail if the partition ends in a different array element.
2326 if ((Offset + Size) > ElementSize)
2327 return 0;
2328 // Recurse through the element type trying to peel off offset bytes.
2329 return getTypePartition(TD, ElementTy, Offset, Size);
2330 }
2331 assert(Offset == 0);
2332
2333 if (Size == ElementSize)
2334 return ElementTy;
2335 assert(Size > ElementSize);
2336 uint64_t NumElements = Size / ElementSize;
2337 if (NumElements * ElementSize != Size)
2338 return 0;
2339 return ArrayType::get(ElementTy, NumElements);
2340 }
2341
2342 StructType *STy = dyn_cast<StructType>(Ty);
2343 if (!STy)
2344 return 0;
2345
2346 const StructLayout *SL = TD.getStructLayout(STy);
2347 if (Offset > SL->getSizeInBytes())
2348 return 0;
2349 uint64_t EndOffset = Offset + Size;
2350 if (EndOffset > SL->getSizeInBytes())
2351 return 0;
2352
2353 unsigned Index = SL->getElementContainingOffset(Offset);
2354 if (SL->getElementOffset(Index) != Offset)
2355 return 0; // Inside of padding.
2356 Offset -= SL->getElementOffset(Index);
2357
2358 Type *ElementTy = STy->getElementType(Index);
2359 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2360 if (Offset >= ElementSize)
2361 return 0; // The offset points into alignment padding.
2362
2363 // See if any partition must be contained by the element.
2364 if (Offset > 0 || Size < ElementSize) {
2365 if ((Offset + Size) > ElementSize)
2366 return 0;
2367 // Bail if this is a poniter element, we can't recurse through them.
2368 if (ElementTy->isPointerTy())
2369 return 0;
2370 return getTypePartition(TD, ElementTy, Offset, Size);
2371 }
2372 assert(Offset == 0);
2373
2374 if (Size == ElementSize)
2375 return ElementTy;
2376
2377 StructType::element_iterator EI = STy->element_begin() + Index,
2378 EE = STy->element_end();
2379 if (EndOffset < SL->getSizeInBytes()) {
2380 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2381 if (Index == EndIndex)
2382 return 0; // Within a single element and its padding.
2383 assert(Index < EndIndex);
2384 assert(Index + EndIndex <= STy->getNumElements());
2385 EE = STy->element_begin() + EndIndex;
2386 }
2387
2388 // Try to build up a sub-structure.
2389 SmallVector<Type *, 4> ElementTys;
2390 do {
2391 ElementTys.push_back(*EI++);
2392 } while (EI != EE);
2393 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
2394 STy->isPacked());
2395 const StructLayout *SubSL = TD.getStructLayout(SubTy);
2396 if (Size == SubSL->getSizeInBytes())
2397 return SubTy;
2398
2399 // FIXME: We could potentially recurse down through the last element in the
2400 // sub-struct to find a natural end point.
2401 return 0;
2402}
2403
2404/// \brief Rewrite an alloca partition's users.
2405///
2406/// This routine drives both of the rewriting goals of the SROA pass. It tries
2407/// to rewrite uses of an alloca partition to be conducive for SSA value
2408/// promotion. If the partition needs a new, more refined alloca, this will
2409/// build that new alloca, preserving as much type information as possible, and
2410/// rewrite the uses of the old alloca to point at the new one and have the
2411/// appropriate new offsets. It also evaluates how successful the rewrite was
2412/// at enabling promotion and if it was successful queues the alloca to be
2413/// promoted.
2414bool SROA::rewriteAllocaPartition(AllocaInst &AI,
2415 AllocaPartitioning &P,
2416 AllocaPartitioning::iterator PI) {
2417 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
2418 if (P.use_begin(PI) == P.use_end(PI))
2419 return false; // No live uses left of this partition.
2420
2421 // Try to compute a friendly type for this partition of the alloca. This
2422 // won't always succeed, in which case we fall back to a legal integer type
2423 // or an i8 array of an appropriate size.
2424 Type *AllocaTy = 0;
2425 if (Type *PartitionTy = P.getCommonType(PI))
2426 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
2427 AllocaTy = PartitionTy;
2428 if (!AllocaTy)
2429 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
2430 PI->BeginOffset, AllocaSize))
2431 AllocaTy = PartitionTy;
2432 if ((!AllocaTy ||
2433 (AllocaTy->isArrayTy() &&
2434 AllocaTy->getArrayElementType()->isIntegerTy())) &&
2435 TD->isLegalInteger(AllocaSize * 8))
2436 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
2437 if (!AllocaTy)
2438 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
2439
2440 // Check for the case where we're going to rewrite to a new alloca of the
2441 // exact same type as the original, and with the same access offsets. In that
2442 // case, re-use the existing alloca, but still run through the rewriter to
2443 // performe phi and select speculation.
2444 AllocaInst *NewAI;
2445 if (AllocaTy == AI.getAllocatedType()) {
2446 assert(PI->BeginOffset == 0 &&
2447 "Non-zero begin offset but same alloca type");
2448 assert(PI == P.begin() && "Begin offset is zero on later partition");
2449 NewAI = &AI;
2450 } else {
2451 // FIXME: The alignment here is overly conservative -- we could in many
2452 // cases get away with much weaker alignment constraints.
2453 NewAI = new AllocaInst(AllocaTy, 0, AI.getAlignment(),
2454 AI.getName() + ".sroa." + Twine(PI - P.begin()),
2455 &AI);
2456 ++NumNewAllocas;
2457 }
2458
2459 DEBUG(dbgs() << "Rewriting alloca partition "
2460 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
2461 << *NewAI << "\n");
2462
2463 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
2464 PI->BeginOffset, PI->EndOffset);
2465 DEBUG(dbgs() << " rewriting ");
2466 DEBUG(P.print(dbgs(), PI, ""));
2467 if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
2468 DEBUG(dbgs() << " and queuing for promotion\n");
2469 PromotableAllocas.push_back(NewAI);
2470 } else if (NewAI != &AI) {
2471 // If we can't promote the alloca, iterate on it to check for new
2472 // refinements exposed by splitting the current alloca. Don't iterate on an
2473 // alloca which didn't actually change and didn't get promoted.
2474 Worklist.insert(NewAI);
2475 }
2476 return true;
2477}
2478
2479/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
2480bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
2481 bool Changed = false;
2482 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
2483 ++PI)
2484 Changed |= rewriteAllocaPartition(AI, P, PI);
2485
2486 return Changed;
2487}
2488
2489/// \brief Analyze an alloca for SROA.
2490///
2491/// This analyzes the alloca to ensure we can reason about it, builds
2492/// a partitioning of the alloca, and then hands it off to be split and
2493/// rewritten as needed.
2494bool SROA::runOnAlloca(AllocaInst &AI) {
2495 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
2496 ++NumAllocasAnalyzed;
2497
2498 // Special case dead allocas, as they're trivial.
2499 if (AI.use_empty()) {
2500 AI.eraseFromParent();
2501 return true;
2502 }
2503
2504 // Skip alloca forms that this analysis can't handle.
2505 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
2506 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
2507 return false;
2508
2509 // First check if this is a non-aggregate type that we should simply promote.
2510 if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
2511 DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
2512 PromotableAllocas.push_back(&AI);
2513 return false;
2514 }
2515
2516 // Build the partition set using a recursive instruction-visiting builder.
2517 AllocaPartitioning P(*TD, AI);
2518 DEBUG(P.print(dbgs()));
2519 if (P.isEscaped())
2520 return false;
2521
2522 // No partitions to split. Leave the dead alloca for a later pass to clean up.
2523 if (P.begin() == P.end())
2524 return false;
2525
2526 // Delete all the dead users of this alloca before splitting and rewriting it.
2527 bool Changed = false;
2528 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
2529 DE = P.dead_user_end();
2530 DI != DE; ++DI) {
2531 Changed = true;
2532 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
2533 DeadInsts.push_back(*DI);
2534 }
2535 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
2536 DE = P.dead_op_end();
2537 DO != DE; ++DO) {
2538 Value *OldV = **DO;
2539 // Clobber the use with an undef value.
2540 **DO = UndefValue::get(OldV->getType());
2541 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
2542 if (isInstructionTriviallyDead(OldI)) {
2543 Changed = true;
2544 DeadInsts.push_back(OldI);
2545 }
2546 }
2547
2548 return splitAlloca(AI, P) || Changed;
2549}
2550
2551void SROA::deleteDeadInstructions() {
2552 DeadSplitInsts.clear();
2553 while (!DeadInsts.empty()) {
2554 Instruction *I = DeadInsts.pop_back_val();
2555 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
2556
2557 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
2558 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
2559 // Zero out the operand and see if it becomes trivially dead.
2560 *OI = 0;
2561 if (isInstructionTriviallyDead(U))
2562 DeadInsts.push_back(U);
2563 }
2564
2565 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2566 DeletedAllocas.insert(AI);
2567
2568 ++NumDeleted;
2569 I->eraseFromParent();
2570 }
2571}
2572
2573namespace {
2574 /// \brief A predicate to test whether an alloca belongs to a set.
2575 class IsAllocaInSet {
2576 typedef SmallPtrSet<AllocaInst *, 4> SetType;
2577 const SetType &Set;
2578
2579 public:
2580 IsAllocaInSet(const SetType &Set) : Set(Set) {}
2581 bool operator()(AllocaInst *AI) { return Set.count(AI); }
2582 };
2583}
2584
2585bool SROA::runOnFunction(Function &F) {
2586 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
2587 C = &F.getContext();
2588 TD = getAnalysisIfAvailable<TargetData>();
2589 if (!TD) {
2590 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
2591 return false;
2592 }
2593 DT = &getAnalysis<DominatorTree>();
2594
2595 BasicBlock &EntryBB = F.getEntryBlock();
2596 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
2597 I != E; ++I)
2598 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2599 Worklist.insert(AI);
2600
2601 bool Changed = false;
2602 while (!Worklist.empty()) {
2603 Changed |= runOnAlloca(*Worklist.pop_back_val());
2604 deleteDeadInstructions();
2605 if (!DeletedAllocas.empty()) {
2606 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
2607 PromotableAllocas.end(),
2608 IsAllocaInSet(DeletedAllocas)),
2609 PromotableAllocas.end());
2610 DeletedAllocas.clear();
2611 }
2612 }
2613
2614 if (!PromotableAllocas.empty()) {
2615 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
2616 PromoteMemToReg(PromotableAllocas, *DT);
2617 Changed = true;
2618 NumPromoted += PromotableAllocas.size();
2619 PromotableAllocas.clear();
2620 }
2621
2622 return Changed;
2623}
2624
2625void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
2626 AU.addRequired<DominatorTree>();
2627 AU.setPreservesCFG();
2628}