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