1 //===- 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 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/AssumptionCache.h"
32 #include "llvm/Analysis/Loads.h"
33 #include "llvm/Analysis/PtrUseVisitor.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DIBuilder.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DebugInfo.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Dominators.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/InstVisitor.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/IntrinsicInst.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Operator.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/TimeValue.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
58 #include "llvm/Transforms/Utils/SSAUpdater.h"
59
60 #if __cplusplus >= 201103L && !defined(NDEBUG)
61 // We only use this for a debug check in C++11
62 #include <random>
63 #endif
64
65 using namespace llvm;
66
67 #define DEBUG_TYPE "sroa"
68
69 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
70 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
71 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
72 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
73 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
74 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
75 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
76 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
77 STATISTIC(NumDeleted, "Number of instructions deleted");
78 STATISTIC(NumVectorized, "Number of vectorized aggregates");
79
80 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
81 /// forming SSA values through the SSAUpdater infrastructure.
82 static cl::opt<bool> ForceSSAUpdater("force-ssa-updater", cl::init(false),
83 cl::Hidden);
84
85 /// Hidden option to enable randomly shuffling the slices to help uncover
86 /// instability in their order.
87 static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
88 cl::init(false), cl::Hidden);
89
90 /// Hidden option to experiment with completely strict handling of inbounds
91 /// GEPs.
92 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
93 cl::Hidden);
94
95 namespace {
96 /// \brief A custom IRBuilder inserter which prefixes all names if they are
97 /// preserved.
98 template <bool preserveNames = true>
99 class IRBuilderPrefixedInserter
100 : public IRBuilderDefaultInserter<preserveNames> {
101 std::string Prefix;
102
103 public:
SetNamePrefix(const Twine & P)104 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
105
106 protected:
InsertHelper(Instruction * I,const Twine & Name,BasicBlock * BB,BasicBlock::iterator InsertPt) const107 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
108 BasicBlock::iterator InsertPt) const {
109 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
110 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
111 }
112 };
113
114 // Specialization for not preserving the name is trivial.
115 template <>
116 class IRBuilderPrefixedInserter<false>
117 : public IRBuilderDefaultInserter<false> {
118 public:
SetNamePrefix(const Twine & P)119 void SetNamePrefix(const Twine &P) {}
120 };
121
122 /// \brief Provide a typedef for IRBuilder that drops names in release builds.
123 #ifndef NDEBUG
124 typedef llvm::IRBuilder<true, ConstantFolder, IRBuilderPrefixedInserter<true>>
125 IRBuilderTy;
126 #else
127 typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
128 IRBuilderTy;
129 #endif
130 }
131
132 namespace {
133 /// \brief A used slice of an alloca.
134 ///
135 /// This structure represents a slice of an alloca used by some instruction. It
136 /// stores both the begin and end offsets of this use, a pointer to the use
137 /// itself, and a flag indicating whether we can classify the use as splittable
138 /// or not when forming partitions of the alloca.
139 class Slice {
140 /// \brief The beginning offset of the range.
141 uint64_t BeginOffset;
142
143 /// \brief The ending offset, not included in the range.
144 uint64_t EndOffset;
145
146 /// \brief Storage for both the use of this slice and whether it can be
147 /// split.
148 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
149
150 public:
Slice()151 Slice() : BeginOffset(), EndOffset() {}
Slice(uint64_t BeginOffset,uint64_t EndOffset,Use * U,bool IsSplittable)152 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
153 : BeginOffset(BeginOffset), EndOffset(EndOffset),
154 UseAndIsSplittable(U, IsSplittable) {}
155
beginOffset() const156 uint64_t beginOffset() const { return BeginOffset; }
endOffset() const157 uint64_t endOffset() const { return EndOffset; }
158
isSplittable() const159 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
makeUnsplittable()160 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
161
getUse() const162 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
163
isDead() const164 bool isDead() const { return getUse() == nullptr; }
kill()165 void kill() { UseAndIsSplittable.setPointer(nullptr); }
166
167 /// \brief Support for ordering ranges.
168 ///
169 /// This provides an ordering over ranges such that start offsets are
170 /// always increasing, and within equal start offsets, the end offsets are
171 /// decreasing. Thus the spanning range comes first in a cluster with the
172 /// same start position.
operator <(const Slice & RHS) const173 bool operator<(const Slice &RHS) const {
174 if (beginOffset() < RHS.beginOffset())
175 return true;
176 if (beginOffset() > RHS.beginOffset())
177 return false;
178 if (isSplittable() != RHS.isSplittable())
179 return !isSplittable();
180 if (endOffset() > RHS.endOffset())
181 return true;
182 return false;
183 }
184
185 /// \brief Support comparison with a single offset to allow binary searches.
operator <(const Slice & LHS,uint64_t RHSOffset)186 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
187 uint64_t RHSOffset) {
188 return LHS.beginOffset() < RHSOffset;
189 }
operator <(uint64_t LHSOffset,const Slice & RHS)190 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
191 const Slice &RHS) {
192 return LHSOffset < RHS.beginOffset();
193 }
194
operator ==(const Slice & RHS) const195 bool operator==(const Slice &RHS) const {
196 return isSplittable() == RHS.isSplittable() &&
197 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
198 }
operator !=(const Slice & RHS) const199 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
200 };
201 } // end anonymous namespace
202
203 namespace llvm {
204 template <typename T> struct isPodLike;
205 template <> struct isPodLike<Slice> { static const bool value = true; };
206 }
207
208 namespace {
209 /// \brief Representation of the alloca slices.
210 ///
211 /// This class represents the slices of an alloca which are formed by its
212 /// various uses. If a pointer escapes, we can't fully build a representation
213 /// for the slices used and we reflect that in this structure. The uses are
214 /// stored, sorted by increasing beginning offset and with unsplittable slices
215 /// starting at a particular offset before splittable slices.
216 class AllocaSlices {
217 public:
218 /// \brief Construct the slices of a particular alloca.
219 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
220
221 /// \brief Test whether a pointer to the allocation escapes our analysis.
222 ///
223 /// If this is true, the slices are never fully built and should be
224 /// ignored.
isEscaped() const225 bool isEscaped() const { return PointerEscapingInstr; }
226
227 /// \brief Support for iterating over the slices.
228 /// @{
229 typedef SmallVectorImpl<Slice>::iterator iterator;
230 typedef iterator_range<iterator> range;
begin()231 iterator begin() { return Slices.begin(); }
end()232 iterator end() { return Slices.end(); }
233
234 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
235 typedef iterator_range<const_iterator> const_range;
begin() const236 const_iterator begin() const { return Slices.begin(); }
end() const237 const_iterator end() const { return Slices.end(); }
238 /// @}
239
240 /// \brief Erase a range of slices.
erase(iterator Start,iterator Stop)241 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
242
243 /// \brief Insert new slices for this alloca.
244 ///
245 /// This moves the slices into the alloca's slices collection, and re-sorts
246 /// everything so that the usual ordering properties of the alloca's slices
247 /// hold.
insert(ArrayRef<Slice> NewSlices)248 void insert(ArrayRef<Slice> NewSlices) {
249 int OldSize = Slices.size();
250 Slices.append(NewSlices.begin(), NewSlices.end());
251 auto SliceI = Slices.begin() + OldSize;
252 std::sort(SliceI, Slices.end());
253 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
254 }
255
256 // Forward declare an iterator to befriend it.
257 class partition_iterator;
258
259 /// \brief A partition of the slices.
260 ///
261 /// An ephemeral representation for a range of slices which can be viewed as
262 /// a partition of the alloca. This range represents a span of the alloca's
263 /// memory which cannot be split, and provides access to all of the slices
264 /// overlapping some part of the partition.
265 ///
266 /// Objects of this type are produced by traversing the alloca's slices, but
267 /// are only ephemeral and not persistent.
268 class Partition {
269 private:
270 friend class AllocaSlices;
271 friend class AllocaSlices::partition_iterator;
272
273 /// \brief The begining and ending offsets of the alloca for this partition.
274 uint64_t BeginOffset, EndOffset;
275
276 /// \brief The start end end iterators of this partition.
277 iterator SI, SJ;
278
279 /// \brief A collection of split slice tails overlapping the partition.
280 SmallVector<Slice *, 4> SplitTails;
281
282 /// \brief Raw constructor builds an empty partition starting and ending at
283 /// the given iterator.
Partition(iterator SI)284 Partition(iterator SI) : SI(SI), SJ(SI) {}
285
286 public:
287 /// \brief The start offset of this partition.
288 ///
289 /// All of the contained slices start at or after this offset.
beginOffset() const290 uint64_t beginOffset() const { return BeginOffset; }
291
292 /// \brief The end offset of this partition.
293 ///
294 /// All of the contained slices end at or before this offset.
endOffset() const295 uint64_t endOffset() const { return EndOffset; }
296
297 /// \brief The size of the partition.
298 ///
299 /// Note that this can never be zero.
size() const300 uint64_t size() const {
301 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
302 return EndOffset - BeginOffset;
303 }
304
305 /// \brief Test whether this partition contains no slices, and merely spans
306 /// a region occupied by split slices.
empty() const307 bool empty() const { return SI == SJ; }
308
309 /// \name Iterate slices that start within the partition.
310 /// These may be splittable or unsplittable. They have a begin offset >= the
311 /// partition begin offset.
312 /// @{
313 // FIXME: We should probably define a "concat_iterator" helper and use that
314 // to stitch together pointee_iterators over the split tails and the
315 // contiguous iterators of the partition. That would give a much nicer
316 // interface here. We could then additionally expose filtered iterators for
317 // split, unsplit, and unsplittable splices based on the usage patterns.
begin() const318 iterator begin() const { return SI; }
end() const319 iterator end() const { return SJ; }
320 /// @}
321
322 /// \brief Get the sequence of split slice tails.
323 ///
324 /// These tails are of slices which start before this partition but are
325 /// split and overlap into the partition. We accumulate these while forming
326 /// partitions.
splitSliceTails() const327 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
328 };
329
330 /// \brief An iterator over partitions of the alloca's slices.
331 ///
332 /// This iterator implements the core algorithm for partitioning the alloca's
333 /// slices. It is a forward iterator as we don't support backtracking for
334 /// efficiency reasons, and re-use a single storage area to maintain the
335 /// current set of split slices.
336 ///
337 /// It is templated on the slice iterator type to use so that it can operate
338 /// with either const or non-const slice iterators.
339 class partition_iterator
340 : public iterator_facade_base<partition_iterator,
341 std::forward_iterator_tag, Partition> {
342 friend class AllocaSlices;
343
344 /// \brief Most of the state for walking the partitions is held in a class
345 /// with a nice interface for examining them.
346 Partition P;
347
348 /// \brief We need to keep the end of the slices to know when to stop.
349 AllocaSlices::iterator SE;
350
351 /// \brief We also need to keep track of the maximum split end offset seen.
352 /// FIXME: Do we really?
353 uint64_t MaxSplitSliceEndOffset;
354
355 /// \brief Sets the partition to be empty at given iterator, and sets the
356 /// end iterator.
partition_iterator(AllocaSlices::iterator SI,AllocaSlices::iterator SE)357 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
358 : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
359 // If not already at the end, advance our state to form the initial
360 // partition.
361 if (SI != SE)
362 advance();
363 }
364
365 /// \brief Advance the iterator to the next partition.
366 ///
367 /// Requires that the iterator not be at the end of the slices.
advance()368 void advance() {
369 assert((P.SI != SE || !P.SplitTails.empty()) &&
370 "Cannot advance past the end of the slices!");
371
372 // Clear out any split uses which have ended.
373 if (!P.SplitTails.empty()) {
374 if (P.EndOffset >= MaxSplitSliceEndOffset) {
375 // If we've finished all splits, this is easy.
376 P.SplitTails.clear();
377 MaxSplitSliceEndOffset = 0;
378 } else {
379 // Remove the uses which have ended in the prior partition. This
380 // cannot change the max split slice end because we just checked that
381 // the prior partition ended prior to that max.
382 P.SplitTails.erase(
383 std::remove_if(
384 P.SplitTails.begin(), P.SplitTails.end(),
385 [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
386 P.SplitTails.end());
387 assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
388 [&](Slice *S) {
389 return S->endOffset() == MaxSplitSliceEndOffset;
390 }) &&
391 "Could not find the current max split slice offset!");
392 assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
393 [&](Slice *S) {
394 return S->endOffset() <= MaxSplitSliceEndOffset;
395 }) &&
396 "Max split slice end offset is not actually the max!");
397 }
398 }
399
400 // If P.SI is already at the end, then we've cleared the split tail and
401 // now have an end iterator.
402 if (P.SI == SE) {
403 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
404 return;
405 }
406
407 // If we had a non-empty partition previously, set up the state for
408 // subsequent partitions.
409 if (P.SI != P.SJ) {
410 // Accumulate all the splittable slices which started in the old
411 // partition into the split list.
412 for (Slice &S : P)
413 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
414 P.SplitTails.push_back(&S);
415 MaxSplitSliceEndOffset =
416 std::max(S.endOffset(), MaxSplitSliceEndOffset);
417 }
418
419 // Start from the end of the previous partition.
420 P.SI = P.SJ;
421
422 // If P.SI is now at the end, we at most have a tail of split slices.
423 if (P.SI == SE) {
424 P.BeginOffset = P.EndOffset;
425 P.EndOffset = MaxSplitSliceEndOffset;
426 return;
427 }
428
429 // If the we have split slices and the next slice is after a gap and is
430 // not splittable immediately form an empty partition for the split
431 // slices up until the next slice begins.
432 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
433 !P.SI->isSplittable()) {
434 P.BeginOffset = P.EndOffset;
435 P.EndOffset = P.SI->beginOffset();
436 return;
437 }
438 }
439
440 // OK, we need to consume new slices. Set the end offset based on the
441 // current slice, and step SJ past it. The beginning offset of the
442 // parttion is the beginning offset of the next slice unless we have
443 // pre-existing split slices that are continuing, in which case we begin
444 // at the prior end offset.
445 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
446 P.EndOffset = P.SI->endOffset();
447 ++P.SJ;
448
449 // There are two strategies to form a partition based on whether the
450 // partition starts with an unsplittable slice or a splittable slice.
451 if (!P.SI->isSplittable()) {
452 // When we're forming an unsplittable region, it must always start at
453 // the first slice and will extend through its end.
454 assert(P.BeginOffset == P.SI->beginOffset());
455
456 // Form a partition including all of the overlapping slices with this
457 // unsplittable slice.
458 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
459 if (!P.SJ->isSplittable())
460 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
461 ++P.SJ;
462 }
463
464 // We have a partition across a set of overlapping unsplittable
465 // partitions.
466 return;
467 }
468
469 // If we're starting with a splittable slice, then we need to form
470 // a synthetic partition spanning it and any other overlapping splittable
471 // splices.
472 assert(P.SI->isSplittable() && "Forming a splittable partition!");
473
474 // Collect all of the overlapping splittable slices.
475 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
476 P.SJ->isSplittable()) {
477 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
478 ++P.SJ;
479 }
480
481 // Back upiP.EndOffset if we ended the span early when encountering an
482 // unsplittable slice. This synthesizes the early end offset of
483 // a partition spanning only splittable slices.
484 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
485 assert(!P.SJ->isSplittable());
486 P.EndOffset = P.SJ->beginOffset();
487 }
488 }
489
490 public:
operator ==(const partition_iterator & RHS) const491 bool operator==(const partition_iterator &RHS) const {
492 assert(SE == RHS.SE &&
493 "End iterators don't match between compared partition iterators!");
494
495 // The observed positions of partitions is marked by the P.SI iterator and
496 // the emptyness of the split slices. The latter is only relevant when
497 // P.SI == SE, as the end iterator will additionally have an empty split
498 // slices list, but the prior may have the same P.SI and a tail of split
499 // slices.
500 if (P.SI == RHS.P.SI &&
501 P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
502 assert(P.SJ == RHS.P.SJ &&
503 "Same set of slices formed two different sized partitions!");
504 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
505 "Same slice position with differently sized non-empty split "
506 "slice tails!");
507 return true;
508 }
509 return false;
510 }
511
operator ++()512 partition_iterator &operator++() {
513 advance();
514 return *this;
515 }
516
operator *()517 Partition &operator*() { return P; }
518 };
519
520 /// \brief A forward range over the partitions of the alloca's slices.
521 ///
522 /// This accesses an iterator range over the partitions of the alloca's
523 /// slices. It computes these partitions on the fly based on the overlapping
524 /// offsets of the slices and the ability to split them. It will visit "empty"
525 /// partitions to cover regions of the alloca only accessed via split
526 /// slices.
partitions()527 iterator_range<partition_iterator> partitions() {
528 return make_range(partition_iterator(begin(), end()),
529 partition_iterator(end(), end()));
530 }
531
532 /// \brief Access the dead users for this alloca.
getDeadUsers() const533 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
534
535 /// \brief Access the dead operands referring to this alloca.
536 ///
537 /// These are operands which have cannot actually be used to refer to the
538 /// alloca as they are outside its range and the user doesn't correct for
539 /// that. These mostly consist of PHI node inputs and the like which we just
540 /// need to replace with undef.
getDeadOperands() const541 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
542
543 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
544 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
545 void printSlice(raw_ostream &OS, const_iterator I,
546 StringRef Indent = " ") const;
547 void printUse(raw_ostream &OS, const_iterator I,
548 StringRef Indent = " ") const;
549 void print(raw_ostream &OS) const;
550 void dump(const_iterator I) const;
551 void dump() const;
552 #endif
553
554 private:
555 template <typename DerivedT, typename RetT = void> class BuilderBase;
556 class SliceBuilder;
557 friend class AllocaSlices::SliceBuilder;
558
559 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
560 /// \brief Handle to alloca instruction to simplify method interfaces.
561 AllocaInst &AI;
562 #endif
563
564 /// \brief The instruction responsible for this alloca not having a known set
565 /// of slices.
566 ///
567 /// When an instruction (potentially) escapes the pointer to the alloca, we
568 /// store a pointer to that here and abort trying to form slices of the
569 /// alloca. This will be null if the alloca slices are analyzed successfully.
570 Instruction *PointerEscapingInstr;
571
572 /// \brief The slices of the alloca.
573 ///
574 /// We store a vector of the slices formed by uses of the alloca here. This
575 /// vector is sorted by increasing begin offset, and then the unsplittable
576 /// slices before the splittable ones. See the Slice inner class for more
577 /// details.
578 SmallVector<Slice, 8> Slices;
579
580 /// \brief Instructions which will become dead if we rewrite the alloca.
581 ///
582 /// Note that these are not separated by slice. This is because we expect an
583 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
584 /// all these instructions can simply be removed and replaced with undef as
585 /// they come from outside of the allocated space.
586 SmallVector<Instruction *, 8> DeadUsers;
587
588 /// \brief Operands which will become dead if we rewrite the alloca.
589 ///
590 /// These are operands that in their particular use can be replaced with
591 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
592 /// to PHI nodes and the like. They aren't entirely dead (there might be
593 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
594 /// want to swap this particular input for undef to simplify the use lists of
595 /// the alloca.
596 SmallVector<Use *, 8> DeadOperands;
597 };
598 }
599
foldSelectInst(SelectInst & SI)600 static Value *foldSelectInst(SelectInst &SI) {
601 // If the condition being selected on is a constant or the same value is
602 // being selected between, fold the select. Yes this does (rarely) happen
603 // early on.
604 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
605 return SI.getOperand(1 + CI->isZero());
606 if (SI.getOperand(1) == SI.getOperand(2))
607 return SI.getOperand(1);
608
609 return nullptr;
610 }
611
612 /// \brief A helper that folds a PHI node or a select.
foldPHINodeOrSelectInst(Instruction & I)613 static Value *foldPHINodeOrSelectInst(Instruction &I) {
614 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
615 // If PN merges together the same value, return that value.
616 return PN->hasConstantValue();
617 }
618 return foldSelectInst(cast<SelectInst>(I));
619 }
620
621 /// \brief Builder for the alloca slices.
622 ///
623 /// This class builds a set of alloca slices by recursively visiting the uses
624 /// of an alloca and making a slice for each load and store at each offset.
625 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
626 friend class PtrUseVisitor<SliceBuilder>;
627 friend class InstVisitor<SliceBuilder>;
628 typedef PtrUseVisitor<SliceBuilder> Base;
629
630 const uint64_t AllocSize;
631 AllocaSlices &AS;
632
633 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
634 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
635
636 /// \brief Set to de-duplicate dead instructions found in the use walk.
637 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
638
639 public:
SliceBuilder(const DataLayout & DL,AllocaInst & AI,AllocaSlices & AS)640 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
641 : PtrUseVisitor<SliceBuilder>(DL),
642 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
643
644 private:
markAsDead(Instruction & I)645 void markAsDead(Instruction &I) {
646 if (VisitedDeadInsts.insert(&I).second)
647 AS.DeadUsers.push_back(&I);
648 }
649
insertUse(Instruction & I,const APInt & Offset,uint64_t Size,bool IsSplittable=false)650 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
651 bool IsSplittable = false) {
652 // Completely skip uses which have a zero size or start either before or
653 // past the end of the allocation.
654 if (Size == 0 || Offset.uge(AllocSize)) {
655 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
656 << " which has zero size or starts outside of the "
657 << AllocSize << " byte alloca:\n"
658 << " alloca: " << AS.AI << "\n"
659 << " use: " << I << "\n");
660 return markAsDead(I);
661 }
662
663 uint64_t BeginOffset = Offset.getZExtValue();
664 uint64_t EndOffset = BeginOffset + Size;
665
666 // Clamp the end offset to the end of the allocation. Note that this is
667 // formulated to handle even the case where "BeginOffset + Size" overflows.
668 // This may appear superficially to be something we could ignore entirely,
669 // but that is not so! There may be widened loads or PHI-node uses where
670 // some instructions are dead but not others. We can't completely ignore
671 // them, and so have to record at least the information here.
672 assert(AllocSize >= BeginOffset); // Established above.
673 if (Size > AllocSize - BeginOffset) {
674 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
675 << " to remain within the " << AllocSize << " byte alloca:\n"
676 << " alloca: " << AS.AI << "\n"
677 << " use: " << I << "\n");
678 EndOffset = AllocSize;
679 }
680
681 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
682 }
683
visitBitCastInst(BitCastInst & BC)684 void visitBitCastInst(BitCastInst &BC) {
685 if (BC.use_empty())
686 return markAsDead(BC);
687
688 return Base::visitBitCastInst(BC);
689 }
690
visitGetElementPtrInst(GetElementPtrInst & GEPI)691 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
692 if (GEPI.use_empty())
693 return markAsDead(GEPI);
694
695 if (SROAStrictInbounds && GEPI.isInBounds()) {
696 // FIXME: This is a manually un-factored variant of the basic code inside
697 // of GEPs with checking of the inbounds invariant specified in the
698 // langref in a very strict sense. If we ever want to enable
699 // SROAStrictInbounds, this code should be factored cleanly into
700 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
701 // by writing out the code here where we have tho underlying allocation
702 // size readily available.
703 APInt GEPOffset = Offset;
704 const DataLayout &DL = GEPI.getModule()->getDataLayout();
705 for (gep_type_iterator GTI = gep_type_begin(GEPI),
706 GTE = gep_type_end(GEPI);
707 GTI != GTE; ++GTI) {
708 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
709 if (!OpC)
710 break;
711
712 // Handle a struct index, which adds its field offset to the pointer.
713 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
714 unsigned ElementIdx = OpC->getZExtValue();
715 const StructLayout *SL = DL.getStructLayout(STy);
716 GEPOffset +=
717 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
718 } else {
719 // For array or vector indices, scale the index by the size of the
720 // type.
721 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
722 GEPOffset += Index * APInt(Offset.getBitWidth(),
723 DL.getTypeAllocSize(GTI.getIndexedType()));
724 }
725
726 // If this index has computed an intermediate pointer which is not
727 // inbounds, then the result of the GEP is a poison value and we can
728 // delete it and all uses.
729 if (GEPOffset.ugt(AllocSize))
730 return markAsDead(GEPI);
731 }
732 }
733
734 return Base::visitGetElementPtrInst(GEPI);
735 }
736
handleLoadOrStore(Type * Ty,Instruction & I,const APInt & Offset,uint64_t Size,bool IsVolatile)737 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
738 uint64_t Size, bool IsVolatile) {
739 // We allow splitting of non-volatile loads and stores where the type is an
740 // integer type. These may be used to implement 'memcpy' or other "transfer
741 // of bits" patterns.
742 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
743
744 insertUse(I, Offset, Size, IsSplittable);
745 }
746
visitLoadInst(LoadInst & LI)747 void visitLoadInst(LoadInst &LI) {
748 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
749 "All simple FCA loads should have been pre-split");
750
751 if (!IsOffsetKnown)
752 return PI.setAborted(&LI);
753
754 const DataLayout &DL = LI.getModule()->getDataLayout();
755 uint64_t Size = DL.getTypeStoreSize(LI.getType());
756 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
757 }
758
visitStoreInst(StoreInst & SI)759 void visitStoreInst(StoreInst &SI) {
760 Value *ValOp = SI.getValueOperand();
761 if (ValOp == *U)
762 return PI.setEscapedAndAborted(&SI);
763 if (!IsOffsetKnown)
764 return PI.setAborted(&SI);
765
766 const DataLayout &DL = SI.getModule()->getDataLayout();
767 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
768
769 // If this memory access can be shown to *statically* extend outside the
770 // bounds of of the allocation, it's behavior is undefined, so simply
771 // ignore it. Note that this is more strict than the generic clamping
772 // behavior of insertUse. We also try to handle cases which might run the
773 // risk of overflow.
774 // FIXME: We should instead consider the pointer to have escaped if this
775 // function is being instrumented for addressing bugs or race conditions.
776 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
777 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
778 << " which extends past the end of the " << AllocSize
779 << " byte alloca:\n"
780 << " alloca: " << AS.AI << "\n"
781 << " use: " << SI << "\n");
782 return markAsDead(SI);
783 }
784
785 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
786 "All simple FCA stores should have been pre-split");
787 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
788 }
789
visitMemSetInst(MemSetInst & II)790 void visitMemSetInst(MemSetInst &II) {
791 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
792 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
793 if ((Length && Length->getValue() == 0) ||
794 (IsOffsetKnown && Offset.uge(AllocSize)))
795 // Zero-length mem transfer intrinsics can be ignored entirely.
796 return markAsDead(II);
797
798 if (!IsOffsetKnown)
799 return PI.setAborted(&II);
800
801 insertUse(II, Offset, Length ? Length->getLimitedValue()
802 : AllocSize - Offset.getLimitedValue(),
803 (bool)Length);
804 }
805
visitMemTransferInst(MemTransferInst & II)806 void visitMemTransferInst(MemTransferInst &II) {
807 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
808 if (Length && Length->getValue() == 0)
809 // Zero-length mem transfer intrinsics can be ignored entirely.
810 return markAsDead(II);
811
812 // Because we can visit these intrinsics twice, also check to see if the
813 // first time marked this instruction as dead. If so, skip it.
814 if (VisitedDeadInsts.count(&II))
815 return;
816
817 if (!IsOffsetKnown)
818 return PI.setAborted(&II);
819
820 // This side of the transfer is completely out-of-bounds, and so we can
821 // nuke the entire transfer. However, we also need to nuke the other side
822 // if already added to our partitions.
823 // FIXME: Yet another place we really should bypass this when
824 // instrumenting for ASan.
825 if (Offset.uge(AllocSize)) {
826 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
827 MemTransferSliceMap.find(&II);
828 if (MTPI != MemTransferSliceMap.end())
829 AS.Slices[MTPI->second].kill();
830 return markAsDead(II);
831 }
832
833 uint64_t RawOffset = Offset.getLimitedValue();
834 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
835
836 // Check for the special case where the same exact value is used for both
837 // source and dest.
838 if (*U == II.getRawDest() && *U == II.getRawSource()) {
839 // For non-volatile transfers this is a no-op.
840 if (!II.isVolatile())
841 return markAsDead(II);
842
843 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
844 }
845
846 // If we have seen both source and destination for a mem transfer, then
847 // they both point to the same alloca.
848 bool Inserted;
849 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
850 std::tie(MTPI, Inserted) =
851 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
852 unsigned PrevIdx = MTPI->second;
853 if (!Inserted) {
854 Slice &PrevP = AS.Slices[PrevIdx];
855
856 // Check if the begin offsets match and this is a non-volatile transfer.
857 // In that case, we can completely elide the transfer.
858 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
859 PrevP.kill();
860 return markAsDead(II);
861 }
862
863 // Otherwise we have an offset transfer within the same alloca. We can't
864 // split those.
865 PrevP.makeUnsplittable();
866 }
867
868 // Insert the use now that we've fixed up the splittable nature.
869 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
870
871 // Check that we ended up with a valid index in the map.
872 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
873 "Map index doesn't point back to a slice with this user.");
874 }
875
876 // Disable SRoA for any intrinsics except for lifetime invariants.
877 // FIXME: What about debug intrinsics? This matches old behavior, but
878 // doesn't make sense.
visitIntrinsicInst(IntrinsicInst & II)879 void visitIntrinsicInst(IntrinsicInst &II) {
880 if (!IsOffsetKnown)
881 return PI.setAborted(&II);
882
883 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
884 II.getIntrinsicID() == Intrinsic::lifetime_end) {
885 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
886 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
887 Length->getLimitedValue());
888 insertUse(II, Offset, Size, true);
889 return;
890 }
891
892 Base::visitIntrinsicInst(II);
893 }
894
hasUnsafePHIOrSelectUse(Instruction * Root,uint64_t & Size)895 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
896 // We consider any PHI or select that results in a direct load or store of
897 // the same offset to be a viable use for slicing purposes. These uses
898 // are considered unsplittable and the size is the maximum loaded or stored
899 // size.
900 SmallPtrSet<Instruction *, 4> Visited;
901 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
902 Visited.insert(Root);
903 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
904 const DataLayout &DL = Root->getModule()->getDataLayout();
905 // If there are no loads or stores, the access is dead. We mark that as
906 // a size zero access.
907 Size = 0;
908 do {
909 Instruction *I, *UsedI;
910 std::tie(UsedI, I) = Uses.pop_back_val();
911
912 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
913 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
914 continue;
915 }
916 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
917 Value *Op = SI->getOperand(0);
918 if (Op == UsedI)
919 return SI;
920 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
921 continue;
922 }
923
924 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
925 if (!GEP->hasAllZeroIndices())
926 return GEP;
927 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
928 !isa<SelectInst>(I)) {
929 return I;
930 }
931
932 for (User *U : I->users())
933 if (Visited.insert(cast<Instruction>(U)).second)
934 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
935 } while (!Uses.empty());
936
937 return nullptr;
938 }
939
visitPHINodeOrSelectInst(Instruction & I)940 void visitPHINodeOrSelectInst(Instruction &I) {
941 assert(isa<PHINode>(I) || isa<SelectInst>(I));
942 if (I.use_empty())
943 return markAsDead(I);
944
945 // TODO: We could use SimplifyInstruction here to fold PHINodes and
946 // SelectInsts. However, doing so requires to change the current
947 // dead-operand-tracking mechanism. For instance, suppose neither loading
948 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
949 // trap either. However, if we simply replace %U with undef using the
950 // current dead-operand-tracking mechanism, "load (select undef, undef,
951 // %other)" may trap because the select may return the first operand
952 // "undef".
953 if (Value *Result = foldPHINodeOrSelectInst(I)) {
954 if (Result == *U)
955 // If the result of the constant fold will be the pointer, recurse
956 // through the PHI/select as if we had RAUW'ed it.
957 enqueueUsers(I);
958 else
959 // Otherwise the operand to the PHI/select is dead, and we can replace
960 // it with undef.
961 AS.DeadOperands.push_back(U);
962
963 return;
964 }
965
966 if (!IsOffsetKnown)
967 return PI.setAborted(&I);
968
969 // See if we already have computed info on this node.
970 uint64_t &Size = PHIOrSelectSizes[&I];
971 if (!Size) {
972 // This is a new PHI/Select, check for an unsafe use of it.
973 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
974 return PI.setAborted(UnsafeI);
975 }
976
977 // For PHI and select operands outside the alloca, we can't nuke the entire
978 // phi or select -- the other side might still be relevant, so we special
979 // case them here and use a separate structure to track the operands
980 // themselves which should be replaced with undef.
981 // FIXME: This should instead be escaped in the event we're instrumenting
982 // for address sanitization.
983 if (Offset.uge(AllocSize)) {
984 AS.DeadOperands.push_back(U);
985 return;
986 }
987
988 insertUse(I, Offset, Size);
989 }
990
visitPHINode(PHINode & PN)991 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
992
visitSelectInst(SelectInst & SI)993 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
994
995 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
visitInstruction(Instruction & I)996 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
997 };
998
AllocaSlices(const DataLayout & DL,AllocaInst & AI)999 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
1000 :
1001 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1002 AI(AI),
1003 #endif
1004 PointerEscapingInstr(nullptr) {
1005 SliceBuilder PB(DL, AI, *this);
1006 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1007 if (PtrI.isEscaped() || PtrI.isAborted()) {
1008 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1009 // possibly by just storing the PtrInfo in the AllocaSlices.
1010 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1011 : PtrI.getAbortingInst();
1012 assert(PointerEscapingInstr && "Did not track a bad instruction");
1013 return;
1014 }
1015
1016 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
1017 [](const Slice &S) {
1018 return S.isDead();
1019 }),
1020 Slices.end());
1021
1022 #if __cplusplus >= 201103L && !defined(NDEBUG)
1023 if (SROARandomShuffleSlices) {
1024 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
1025 std::shuffle(Slices.begin(), Slices.end(), MT);
1026 }
1027 #endif
1028
1029 // Sort the uses. This arranges for the offsets to be in ascending order,
1030 // and the sizes to be in descending order.
1031 std::sort(Slices.begin(), Slices.end());
1032 }
1033
1034 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1035
print(raw_ostream & OS,const_iterator I,StringRef Indent) const1036 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1037 StringRef Indent) const {
1038 printSlice(OS, I, Indent);
1039 OS << "\n";
1040 printUse(OS, I, Indent);
1041 }
1042
printSlice(raw_ostream & OS,const_iterator I,StringRef Indent) const1043 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1044 StringRef Indent) const {
1045 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
1046 << " slice #" << (I - begin())
1047 << (I->isSplittable() ? " (splittable)" : "");
1048 }
1049
printUse(raw_ostream & OS,const_iterator I,StringRef Indent) const1050 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1051 StringRef Indent) const {
1052 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
1053 }
1054
print(raw_ostream & OS) const1055 void AllocaSlices::print(raw_ostream &OS) const {
1056 if (PointerEscapingInstr) {
1057 OS << "Can't analyze slices for alloca: " << AI << "\n"
1058 << " A pointer to this alloca escaped by:\n"
1059 << " " << *PointerEscapingInstr << "\n";
1060 return;
1061 }
1062
1063 OS << "Slices of alloca: " << AI << "\n";
1064 for (const_iterator I = begin(), E = end(); I != E; ++I)
1065 print(OS, I);
1066 }
1067
dump(const_iterator I) const1068 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1069 print(dbgs(), I);
1070 }
dump() const1071 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
1072
1073 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1074
1075 namespace {
1076 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1077 ///
1078 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1079 /// the loads and stores of an alloca instruction, as well as updating its
1080 /// debug information. This is used when a domtree is unavailable and thus
1081 /// mem2reg in its full form can't be used to handle promotion of allocas to
1082 /// scalar values.
1083 class AllocaPromoter : public LoadAndStorePromoter {
1084 AllocaInst &AI;
1085 DIBuilder &DIB;
1086
1087 SmallVector<DbgDeclareInst *, 4> DDIs;
1088 SmallVector<DbgValueInst *, 4> DVIs;
1089
1090 public:
AllocaPromoter(const SmallVectorImpl<Instruction * > & Insts,SSAUpdater & S,AllocaInst & AI,DIBuilder & DIB)1091 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
1092 AllocaInst &AI, DIBuilder &DIB)
1093 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1094
run(const SmallVectorImpl<Instruction * > & Insts)1095 void run(const SmallVectorImpl<Instruction *> &Insts) {
1096 // Retain the debug information attached to the alloca for use when
1097 // rewriting loads and stores.
1098 if (auto *L = LocalAsMetadata::getIfExists(&AI)) {
1099 if (auto *DebugNode = MetadataAsValue::getIfExists(AI.getContext(), L)) {
1100 for (User *U : DebugNode->users())
1101 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1102 DDIs.push_back(DDI);
1103 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1104 DVIs.push_back(DVI);
1105 }
1106 }
1107
1108 LoadAndStorePromoter::run(Insts);
1109
1110 // While we have the debug information, clear it off of the alloca. The
1111 // caller takes care of deleting the alloca.
1112 while (!DDIs.empty())
1113 DDIs.pop_back_val()->eraseFromParent();
1114 while (!DVIs.empty())
1115 DVIs.pop_back_val()->eraseFromParent();
1116 }
1117
1118 bool
isInstInList(Instruction * I,const SmallVectorImpl<Instruction * > & Insts) const1119 isInstInList(Instruction *I,
1120 const SmallVectorImpl<Instruction *> &Insts) const override {
1121 Value *Ptr;
1122 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1123 Ptr = LI->getOperand(0);
1124 else
1125 Ptr = cast<StoreInst>(I)->getPointerOperand();
1126
1127 // Only used to detect cycles, which will be rare and quickly found as
1128 // we're walking up a chain of defs rather than down through uses.
1129 SmallPtrSet<Value *, 4> Visited;
1130
1131 do {
1132 if (Ptr == &AI)
1133 return true;
1134
1135 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
1136 Ptr = BCI->getOperand(0);
1137 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
1138 Ptr = GEPI->getPointerOperand();
1139 else
1140 return false;
1141
1142 } while (Visited.insert(Ptr).second);
1143
1144 return false;
1145 }
1146
updateDebugInfo(Instruction * Inst) const1147 void updateDebugInfo(Instruction *Inst) const override {
1148 for (DbgDeclareInst *DDI : DDIs)
1149 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1150 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1151 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1152 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1153 for (DbgValueInst *DVI : DVIs) {
1154 Value *Arg = nullptr;
1155 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1156 // If an argument is zero extended then use argument directly. The ZExt
1157 // may be zapped by an optimization pass in future.
1158 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1159 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1160 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1161 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1162 if (!Arg)
1163 Arg = SI->getValueOperand();
1164 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1165 Arg = LI->getPointerOperand();
1166 } else {
1167 continue;
1168 }
1169 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1170 DIExpression(DVI->getExpression()),
1171 DVI->getDebugLoc(), Inst);
1172 }
1173 }
1174 };
1175 } // end anon namespace
1176
1177 namespace {
1178 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1179 ///
1180 /// This pass takes allocations which can be completely analyzed (that is, they
1181 /// don't escape) and tries to turn them into scalar SSA values. There are
1182 /// a few steps to this process.
1183 ///
1184 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1185 /// are used to try to split them into smaller allocations, ideally of
1186 /// a single scalar data type. It will split up memcpy and memset accesses
1187 /// as necessary and try to isolate individual scalar accesses.
1188 /// 2) It will transform accesses into forms which are suitable for SSA value
1189 /// promotion. This can be replacing a memset with a scalar store of an
1190 /// integer value, or it can involve speculating operations on a PHI or
1191 /// select to be a PHI or select of the results.
1192 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1193 /// onto insert and extract operations on a vector value, and convert them to
1194 /// this form. By doing so, it will enable promotion of vector aggregates to
1195 /// SSA vector values.
1196 class SROA : public FunctionPass {
1197 const bool RequiresDomTree;
1198
1199 LLVMContext *C;
1200 DominatorTree *DT;
1201 AssumptionCache *AC;
1202
1203 /// \brief Worklist of alloca instructions to simplify.
1204 ///
1205 /// Each alloca in the function is added to this. Each new alloca formed gets
1206 /// added to it as well to recursively simplify unless that alloca can be
1207 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1208 /// the one being actively rewritten, we add it back onto the list if not
1209 /// already present to ensure it is re-visited.
1210 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> Worklist;
1211
1212 /// \brief A collection of instructions to delete.
1213 /// We try to batch deletions to simplify code and make things a bit more
1214 /// efficient.
1215 SetVector<Instruction *, SmallVector<Instruction *, 8>> DeadInsts;
1216
1217 /// \brief Post-promotion worklist.
1218 ///
1219 /// Sometimes we discover an alloca which has a high probability of becoming
1220 /// viable for SROA after a round of promotion takes place. In those cases,
1221 /// the alloca is enqueued here for re-processing.
1222 ///
1223 /// Note that we have to be very careful to clear allocas out of this list in
1224 /// the event they are deleted.
1225 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> PostPromotionWorklist;
1226
1227 /// \brief A collection of alloca instructions we can directly promote.
1228 std::vector<AllocaInst *> PromotableAllocas;
1229
1230 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
1231 ///
1232 /// All of these PHIs have been checked for the safety of speculation and by
1233 /// being speculated will allow promoting allocas currently in the promotable
1234 /// queue.
1235 SetVector<PHINode *, SmallVector<PHINode *, 2>> SpeculatablePHIs;
1236
1237 /// \brief A worklist of select instructions to speculate prior to promoting
1238 /// allocas.
1239 ///
1240 /// All of these select instructions have been checked for the safety of
1241 /// speculation and by being speculated will allow promoting allocas
1242 /// currently in the promotable queue.
1243 SetVector<SelectInst *, SmallVector<SelectInst *, 2>> SpeculatableSelects;
1244
1245 public:
SROA(bool RequiresDomTree=true)1246 SROA(bool RequiresDomTree = true)
1247 : FunctionPass(ID), RequiresDomTree(RequiresDomTree), C(nullptr),
1248 DT(nullptr) {
1249 initializeSROAPass(*PassRegistry::getPassRegistry());
1250 }
1251 bool runOnFunction(Function &F) override;
1252 void getAnalysisUsage(AnalysisUsage &AU) const override;
1253
getPassName() const1254 const char *getPassName() const override { return "SROA"; }
1255 static char ID;
1256
1257 private:
1258 friend class PHIOrSelectSpeculator;
1259 friend class AllocaSliceRewriter;
1260
1261 bool presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS);
1262 AllocaInst *rewritePartition(AllocaInst &AI, AllocaSlices &AS,
1263 AllocaSlices::Partition &P);
1264 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
1265 bool runOnAlloca(AllocaInst &AI);
1266 void clobberUse(Use &U);
1267 void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
1268 bool promoteAllocas(Function &F);
1269 };
1270 }
1271
1272 char SROA::ID = 0;
1273
createSROAPass(bool RequiresDomTree)1274 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1275 return new SROA(RequiresDomTree);
1276 }
1277
1278 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1279 false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)1280 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1281 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1282 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1283 false)
1284
1285 /// Walk the range of a partitioning looking for a common type to cover this
1286 /// sequence of slices.
1287 static Type *findCommonType(AllocaSlices::const_iterator B,
1288 AllocaSlices::const_iterator E,
1289 uint64_t EndOffset) {
1290 Type *Ty = nullptr;
1291 bool TyIsCommon = true;
1292 IntegerType *ITy = nullptr;
1293
1294 // Note that we need to look at *every* alloca slice's Use to ensure we
1295 // always get consistent results regardless of the order of slices.
1296 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1297 Use *U = I->getUse();
1298 if (isa<IntrinsicInst>(*U->getUser()))
1299 continue;
1300 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1301 continue;
1302
1303 Type *UserTy = nullptr;
1304 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1305 UserTy = LI->getType();
1306 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1307 UserTy = SI->getValueOperand()->getType();
1308 }
1309
1310 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1311 // If the type is larger than the partition, skip it. We only encounter
1312 // this for split integer operations where we want to use the type of the
1313 // entity causing the split. Also skip if the type is not a byte width
1314 // multiple.
1315 if (UserITy->getBitWidth() % 8 != 0 ||
1316 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1317 continue;
1318
1319 // Track the largest bitwidth integer type used in this way in case there
1320 // is no common type.
1321 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1322 ITy = UserITy;
1323 }
1324
1325 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1326 // depend on types skipped above.
1327 if (!UserTy || (Ty && Ty != UserTy))
1328 TyIsCommon = false; // Give up on anything but an iN type.
1329 else
1330 Ty = UserTy;
1331 }
1332
1333 return TyIsCommon ? Ty : ITy;
1334 }
1335
1336 /// PHI instructions that use an alloca and are subsequently loaded can be
1337 /// rewritten to load both input pointers in the pred blocks and then PHI the
1338 /// results, allowing the load of the alloca to be promoted.
1339 /// From this:
1340 /// %P2 = phi [i32* %Alloca, i32* %Other]
1341 /// %V = load i32* %P2
1342 /// to:
1343 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1344 /// ...
1345 /// %V2 = load i32* %Other
1346 /// ...
1347 /// %V = phi [i32 %V1, i32 %V2]
1348 ///
1349 /// We can do this to a select if its only uses are loads and if the operands
1350 /// to the select can be loaded unconditionally.
1351 ///
1352 /// FIXME: This should be hoisted into a generic utility, likely in
1353 /// Transforms/Util/Local.h
isSafePHIToSpeculate(PHINode & PN)1354 static bool isSafePHIToSpeculate(PHINode &PN) {
1355 // For now, we can only do this promotion if the load is in the same block
1356 // as the PHI, and if there are no stores between the phi and load.
1357 // TODO: Allow recursive phi users.
1358 // TODO: Allow stores.
1359 BasicBlock *BB = PN.getParent();
1360 unsigned MaxAlign = 0;
1361 bool HaveLoad = false;
1362 for (User *U : PN.users()) {
1363 LoadInst *LI = dyn_cast<LoadInst>(U);
1364 if (!LI || !LI->isSimple())
1365 return false;
1366
1367 // For now we only allow loads in the same block as the PHI. This is
1368 // a common case that happens when instcombine merges two loads through
1369 // a PHI.
1370 if (LI->getParent() != BB)
1371 return false;
1372
1373 // Ensure that there are no instructions between the PHI and the load that
1374 // could store.
1375 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1376 if (BBI->mayWriteToMemory())
1377 return false;
1378
1379 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1380 HaveLoad = true;
1381 }
1382
1383 if (!HaveLoad)
1384 return false;
1385
1386 const DataLayout &DL = PN.getModule()->getDataLayout();
1387
1388 // We can only transform this if it is safe to push the loads into the
1389 // predecessor blocks. The only thing to watch out for is that we can't put
1390 // a possibly trapping load in the predecessor if it is a critical edge.
1391 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1392 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1393 Value *InVal = PN.getIncomingValue(Idx);
1394
1395 // If the value is produced by the terminator of the predecessor (an
1396 // invoke) or it has side-effects, there is no valid place to put a load
1397 // in the predecessor.
1398 if (TI == InVal || TI->mayHaveSideEffects())
1399 return false;
1400
1401 // If the predecessor has a single successor, then the edge isn't
1402 // critical.
1403 if (TI->getNumSuccessors() == 1)
1404 continue;
1405
1406 // If this pointer is always safe to load, or if we can prove that there
1407 // is already a load in the block, then we can move the load to the pred
1408 // block.
1409 if (InVal->isDereferenceablePointer(DL) ||
1410 isSafeToLoadUnconditionally(InVal, TI, MaxAlign))
1411 continue;
1412
1413 return false;
1414 }
1415
1416 return true;
1417 }
1418
speculatePHINodeLoads(PHINode & PN)1419 static void speculatePHINodeLoads(PHINode &PN) {
1420 DEBUG(dbgs() << " original: " << PN << "\n");
1421
1422 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1423 IRBuilderTy PHIBuilder(&PN);
1424 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1425 PN.getName() + ".sroa.speculated");
1426
1427 // Get the AA tags and alignment to use from one of the loads. It doesn't
1428 // matter which one we get and if any differ.
1429 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1430
1431 AAMDNodes AATags;
1432 SomeLoad->getAAMetadata(AATags);
1433 unsigned Align = SomeLoad->getAlignment();
1434
1435 // Rewrite all loads of the PN to use the new PHI.
1436 while (!PN.use_empty()) {
1437 LoadInst *LI = cast<LoadInst>(PN.user_back());
1438 LI->replaceAllUsesWith(NewPN);
1439 LI->eraseFromParent();
1440 }
1441
1442 // Inject loads into all of the pred blocks.
1443 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1444 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1445 TerminatorInst *TI = Pred->getTerminator();
1446 Value *InVal = PN.getIncomingValue(Idx);
1447 IRBuilderTy PredBuilder(TI);
1448
1449 LoadInst *Load = PredBuilder.CreateLoad(
1450 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1451 ++NumLoadsSpeculated;
1452 Load->setAlignment(Align);
1453 if (AATags)
1454 Load->setAAMetadata(AATags);
1455 NewPN->addIncoming(Load, Pred);
1456 }
1457
1458 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1459 PN.eraseFromParent();
1460 }
1461
1462 /// Select instructions that use an alloca and are subsequently loaded can be
1463 /// rewritten to load both input pointers and then select between the result,
1464 /// allowing the load of the alloca to be promoted.
1465 /// From this:
1466 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1467 /// %V = load i32* %P2
1468 /// to:
1469 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1470 /// %V2 = load i32* %Other
1471 /// %V = select i1 %cond, i32 %V1, i32 %V2
1472 ///
1473 /// We can do this to a select if its only uses are loads and if the operand
1474 /// to the select can be loaded unconditionally.
isSafeSelectToSpeculate(SelectInst & SI)1475 static bool isSafeSelectToSpeculate(SelectInst &SI) {
1476 Value *TValue = SI.getTrueValue();
1477 Value *FValue = SI.getFalseValue();
1478 const DataLayout &DL = SI.getModule()->getDataLayout();
1479 bool TDerefable = TValue->isDereferenceablePointer(DL);
1480 bool FDerefable = FValue->isDereferenceablePointer(DL);
1481
1482 for (User *U : SI.users()) {
1483 LoadInst *LI = dyn_cast<LoadInst>(U);
1484 if (!LI || !LI->isSimple())
1485 return false;
1486
1487 // Both operands to the select need to be dereferencable, either
1488 // absolutely (e.g. allocas) or at this point because we can see other
1489 // accesses to it.
1490 if (!TDerefable &&
1491 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment()))
1492 return false;
1493 if (!FDerefable &&
1494 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment()))
1495 return false;
1496 }
1497
1498 return true;
1499 }
1500
speculateSelectInstLoads(SelectInst & SI)1501 static void speculateSelectInstLoads(SelectInst &SI) {
1502 DEBUG(dbgs() << " original: " << SI << "\n");
1503
1504 IRBuilderTy IRB(&SI);
1505 Value *TV = SI.getTrueValue();
1506 Value *FV = SI.getFalseValue();
1507 // Replace the loads of the select with a select of two loads.
1508 while (!SI.use_empty()) {
1509 LoadInst *LI = cast<LoadInst>(SI.user_back());
1510 assert(LI->isSimple() && "We only speculate simple loads");
1511
1512 IRB.SetInsertPoint(LI);
1513 LoadInst *TL =
1514 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1515 LoadInst *FL =
1516 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1517 NumLoadsSpeculated += 2;
1518
1519 // Transfer alignment and AA info if present.
1520 TL->setAlignment(LI->getAlignment());
1521 FL->setAlignment(LI->getAlignment());
1522
1523 AAMDNodes Tags;
1524 LI->getAAMetadata(Tags);
1525 if (Tags) {
1526 TL->setAAMetadata(Tags);
1527 FL->setAAMetadata(Tags);
1528 }
1529
1530 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1531 LI->getName() + ".sroa.speculated");
1532
1533 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1534 LI->replaceAllUsesWith(V);
1535 LI->eraseFromParent();
1536 }
1537 SI.eraseFromParent();
1538 }
1539
1540 /// \brief Build a GEP out of a base pointer and indices.
1541 ///
1542 /// This will return the BasePtr if that is valid, or build a new GEP
1543 /// instruction using the IRBuilder if GEP-ing is needed.
buildGEP(IRBuilderTy & IRB,Value * BasePtr,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)1544 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1545 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
1546 if (Indices.empty())
1547 return BasePtr;
1548
1549 // A single zero index is a no-op, so check for this and avoid building a GEP
1550 // in that case.
1551 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1552 return BasePtr;
1553
1554 return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1555 NamePrefix + "sroa_idx");
1556 }
1557
1558 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1559 /// TargetTy without changing the offset of the pointer.
1560 ///
1561 /// This routine assumes we've already established a properly offset GEP with
1562 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1563 /// zero-indices down through type layers until we find one the same as
1564 /// TargetTy. If we can't find one with the same type, we at least try to use
1565 /// one with the same size. If none of that works, we just produce the GEP as
1566 /// indicated by Indices to have the correct offset.
getNaturalGEPWithType(IRBuilderTy & IRB,const DataLayout & DL,Value * BasePtr,Type * Ty,Type * TargetTy,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)1567 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1568 Value *BasePtr, Type *Ty, Type *TargetTy,
1569 SmallVectorImpl<Value *> &Indices,
1570 Twine NamePrefix) {
1571 if (Ty == TargetTy)
1572 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1573
1574 // Pointer size to use for the indices.
1575 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1576
1577 // See if we can descend into a struct and locate a field with the correct
1578 // type.
1579 unsigned NumLayers = 0;
1580 Type *ElementTy = Ty;
1581 do {
1582 if (ElementTy->isPointerTy())
1583 break;
1584
1585 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1586 ElementTy = ArrayTy->getElementType();
1587 Indices.push_back(IRB.getIntN(PtrSize, 0));
1588 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1589 ElementTy = VectorTy->getElementType();
1590 Indices.push_back(IRB.getInt32(0));
1591 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1592 if (STy->element_begin() == STy->element_end())
1593 break; // Nothing left to descend into.
1594 ElementTy = *STy->element_begin();
1595 Indices.push_back(IRB.getInt32(0));
1596 } else {
1597 break;
1598 }
1599 ++NumLayers;
1600 } while (ElementTy != TargetTy);
1601 if (ElementTy != TargetTy)
1602 Indices.erase(Indices.end() - NumLayers, Indices.end());
1603
1604 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1605 }
1606
1607 /// \brief Recursively compute indices for a natural GEP.
1608 ///
1609 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1610 /// element types adding appropriate indices for the GEP.
getNaturalGEPRecursively(IRBuilderTy & IRB,const DataLayout & DL,Value * Ptr,Type * Ty,APInt & Offset,Type * TargetTy,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)1611 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1612 Value *Ptr, Type *Ty, APInt &Offset,
1613 Type *TargetTy,
1614 SmallVectorImpl<Value *> &Indices,
1615 Twine NamePrefix) {
1616 if (Offset == 0)
1617 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1618 NamePrefix);
1619
1620 // We can't recurse through pointer types.
1621 if (Ty->isPointerTy())
1622 return nullptr;
1623
1624 // We try to analyze GEPs over vectors here, but note that these GEPs are
1625 // extremely poorly defined currently. The long-term goal is to remove GEPing
1626 // over a vector from the IR completely.
1627 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1628 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1629 if (ElementSizeInBits % 8 != 0) {
1630 // GEPs over non-multiple of 8 size vector elements are invalid.
1631 return nullptr;
1632 }
1633 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1634 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1635 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1636 return nullptr;
1637 Offset -= NumSkippedElements * ElementSize;
1638 Indices.push_back(IRB.getInt(NumSkippedElements));
1639 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1640 Offset, TargetTy, Indices, NamePrefix);
1641 }
1642
1643 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1644 Type *ElementTy = ArrTy->getElementType();
1645 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1646 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1647 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1648 return nullptr;
1649
1650 Offset -= NumSkippedElements * ElementSize;
1651 Indices.push_back(IRB.getInt(NumSkippedElements));
1652 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1653 Indices, NamePrefix);
1654 }
1655
1656 StructType *STy = dyn_cast<StructType>(Ty);
1657 if (!STy)
1658 return nullptr;
1659
1660 const StructLayout *SL = DL.getStructLayout(STy);
1661 uint64_t StructOffset = Offset.getZExtValue();
1662 if (StructOffset >= SL->getSizeInBytes())
1663 return nullptr;
1664 unsigned Index = SL->getElementContainingOffset(StructOffset);
1665 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1666 Type *ElementTy = STy->getElementType(Index);
1667 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1668 return nullptr; // The offset points into alignment padding.
1669
1670 Indices.push_back(IRB.getInt32(Index));
1671 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1672 Indices, NamePrefix);
1673 }
1674
1675 /// \brief Get a natural GEP from a base pointer to a particular offset and
1676 /// resulting in a particular type.
1677 ///
1678 /// The goal is to produce a "natural" looking GEP that works with the existing
1679 /// composite types to arrive at the appropriate offset and element type for
1680 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1681 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1682 /// Indices, and setting Ty to the result subtype.
1683 ///
1684 /// If no natural GEP can be constructed, this function returns null.
getNaturalGEPWithOffset(IRBuilderTy & IRB,const DataLayout & DL,Value * Ptr,APInt Offset,Type * TargetTy,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)1685 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1686 Value *Ptr, APInt Offset, Type *TargetTy,
1687 SmallVectorImpl<Value *> &Indices,
1688 Twine NamePrefix) {
1689 PointerType *Ty = cast<PointerType>(Ptr->getType());
1690
1691 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1692 // an i8.
1693 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
1694 return nullptr;
1695
1696 Type *ElementTy = Ty->getElementType();
1697 if (!ElementTy->isSized())
1698 return nullptr; // We can't GEP through an unsized element.
1699 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1700 if (ElementSize == 0)
1701 return nullptr; // Zero-length arrays can't help us build a natural GEP.
1702 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1703
1704 Offset -= NumSkippedElements * ElementSize;
1705 Indices.push_back(IRB.getInt(NumSkippedElements));
1706 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1707 Indices, NamePrefix);
1708 }
1709
1710 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1711 /// resulting pointer has PointerTy.
1712 ///
1713 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1714 /// and produces the pointer type desired. Where it cannot, it will try to use
1715 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1716 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1717 /// bitcast to the type.
1718 ///
1719 /// The strategy for finding the more natural GEPs is to peel off layers of the
1720 /// pointer, walking back through bit casts and GEPs, searching for a base
1721 /// pointer from which we can compute a natural GEP with the desired
1722 /// properties. The algorithm tries to fold as many constant indices into
1723 /// a single GEP as possible, thus making each GEP more independent of the
1724 /// surrounding code.
getAdjustedPtr(IRBuilderTy & IRB,const DataLayout & DL,Value * Ptr,APInt Offset,Type * PointerTy,Twine NamePrefix)1725 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1726 APInt Offset, Type *PointerTy, Twine NamePrefix) {
1727 // Even though we don't look through PHI nodes, we could be called on an
1728 // instruction in an unreachable block, which may be on a cycle.
1729 SmallPtrSet<Value *, 4> Visited;
1730 Visited.insert(Ptr);
1731 SmallVector<Value *, 4> Indices;
1732
1733 // We may end up computing an offset pointer that has the wrong type. If we
1734 // never are able to compute one directly that has the correct type, we'll
1735 // fall back to it, so keep it and the base it was computed from around here.
1736 Value *OffsetPtr = nullptr;
1737 Value *OffsetBasePtr;
1738
1739 // Remember any i8 pointer we come across to re-use if we need to do a raw
1740 // byte offset.
1741 Value *Int8Ptr = nullptr;
1742 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1743
1744 Type *TargetTy = PointerTy->getPointerElementType();
1745
1746 do {
1747 // First fold any existing GEPs into the offset.
1748 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1749 APInt GEPOffset(Offset.getBitWidth(), 0);
1750 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1751 break;
1752 Offset += GEPOffset;
1753 Ptr = GEP->getPointerOperand();
1754 if (!Visited.insert(Ptr).second)
1755 break;
1756 }
1757
1758 // See if we can perform a natural GEP here.
1759 Indices.clear();
1760 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1761 Indices, NamePrefix)) {
1762 // If we have a new natural pointer at the offset, clear out any old
1763 // offset pointer we computed. Unless it is the base pointer or
1764 // a non-instruction, we built a GEP we don't need. Zap it.
1765 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1766 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1767 assert(I->use_empty() && "Built a GEP with uses some how!");
1768 I->eraseFromParent();
1769 }
1770 OffsetPtr = P;
1771 OffsetBasePtr = Ptr;
1772 // If we also found a pointer of the right type, we're done.
1773 if (P->getType() == PointerTy)
1774 return P;
1775 }
1776
1777 // Stash this pointer if we've found an i8*.
1778 if (Ptr->getType()->isIntegerTy(8)) {
1779 Int8Ptr = Ptr;
1780 Int8PtrOffset = Offset;
1781 }
1782
1783 // Peel off a layer of the pointer and update the offset appropriately.
1784 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1785 Ptr = cast<Operator>(Ptr)->getOperand(0);
1786 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1787 if (GA->mayBeOverridden())
1788 break;
1789 Ptr = GA->getAliasee();
1790 } else {
1791 break;
1792 }
1793 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1794 } while (Visited.insert(Ptr).second);
1795
1796 if (!OffsetPtr) {
1797 if (!Int8Ptr) {
1798 Int8Ptr = IRB.CreateBitCast(
1799 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1800 NamePrefix + "sroa_raw_cast");
1801 Int8PtrOffset = Offset;
1802 }
1803
1804 OffsetPtr = Int8PtrOffset == 0
1805 ? Int8Ptr
1806 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1807 IRB.getInt(Int8PtrOffset),
1808 NamePrefix + "sroa_raw_idx");
1809 }
1810 Ptr = OffsetPtr;
1811
1812 // On the off chance we were targeting i8*, guard the bitcast here.
1813 if (Ptr->getType() != PointerTy)
1814 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
1815
1816 return Ptr;
1817 }
1818
1819 /// \brief Compute the adjusted alignment for a load or store from an offset.
getAdjustedAlignment(Instruction * I,uint64_t Offset,const DataLayout & DL)1820 static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1821 const DataLayout &DL) {
1822 unsigned Alignment;
1823 Type *Ty;
1824 if (auto *LI = dyn_cast<LoadInst>(I)) {
1825 Alignment = LI->getAlignment();
1826 Ty = LI->getType();
1827 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1828 Alignment = SI->getAlignment();
1829 Ty = SI->getValueOperand()->getType();
1830 } else {
1831 llvm_unreachable("Only loads and stores are allowed!");
1832 }
1833
1834 if (!Alignment)
1835 Alignment = DL.getABITypeAlignment(Ty);
1836
1837 return MinAlign(Alignment, Offset);
1838 }
1839
1840 /// \brief Test whether we can convert a value from the old to the new type.
1841 ///
1842 /// This predicate should be used to guard calls to convertValue in order to
1843 /// ensure that we only try to convert viable values. The strategy is that we
1844 /// will peel off single element struct and array wrappings to get to an
1845 /// underlying value, and convert that value.
canConvertValue(const DataLayout & DL,Type * OldTy,Type * NewTy)1846 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1847 if (OldTy == NewTy)
1848 return true;
1849 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1850 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1851 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1852 return true;
1853 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1854 return false;
1855 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1856 return false;
1857
1858 // We can convert pointers to integers and vice-versa. Same for vectors
1859 // of pointers and integers.
1860 OldTy = OldTy->getScalarType();
1861 NewTy = NewTy->getScalarType();
1862 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1863 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1864 return true;
1865 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1866 return true;
1867 return false;
1868 }
1869
1870 return true;
1871 }
1872
1873 /// \brief Generic routine to convert an SSA value to a value of a different
1874 /// type.
1875 ///
1876 /// This will try various different casting techniques, such as bitcasts,
1877 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1878 /// two types for viability with this routine.
convertValue(const DataLayout & DL,IRBuilderTy & IRB,Value * V,Type * NewTy)1879 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1880 Type *NewTy) {
1881 Type *OldTy = V->getType();
1882 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1883
1884 if (OldTy == NewTy)
1885 return V;
1886
1887 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1888 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1889 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1890 return IRB.CreateZExt(V, NewITy);
1891
1892 // See if we need inttoptr for this type pair. A cast involving both scalars
1893 // and vectors requires and additional bitcast.
1894 if (OldTy->getScalarType()->isIntegerTy() &&
1895 NewTy->getScalarType()->isPointerTy()) {
1896 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1897 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1898 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1899 NewTy);
1900
1901 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1902 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1903 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1904 NewTy);
1905
1906 return IRB.CreateIntToPtr(V, NewTy);
1907 }
1908
1909 // See if we need ptrtoint for this type pair. A cast involving both scalars
1910 // and vectors requires and additional bitcast.
1911 if (OldTy->getScalarType()->isPointerTy() &&
1912 NewTy->getScalarType()->isIntegerTy()) {
1913 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1914 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1915 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1916 NewTy);
1917
1918 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1919 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1920 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1921 NewTy);
1922
1923 return IRB.CreatePtrToInt(V, NewTy);
1924 }
1925
1926 return IRB.CreateBitCast(V, NewTy);
1927 }
1928
1929 /// \brief Test whether the given slice use can be promoted to a vector.
1930 ///
1931 /// This function is called to test each entry in a partioning which is slated
1932 /// for a single slice.
isVectorPromotionViableForSlice(AllocaSlices::Partition & P,const Slice & S,VectorType * Ty,uint64_t ElementSize,const DataLayout & DL)1933 static bool isVectorPromotionViableForSlice(AllocaSlices::Partition &P,
1934 const Slice &S, VectorType *Ty,
1935 uint64_t ElementSize,
1936 const DataLayout &DL) {
1937 // First validate the slice offsets.
1938 uint64_t BeginOffset =
1939 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
1940 uint64_t BeginIndex = BeginOffset / ElementSize;
1941 if (BeginIndex * ElementSize != BeginOffset ||
1942 BeginIndex >= Ty->getNumElements())
1943 return false;
1944 uint64_t EndOffset =
1945 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
1946 uint64_t EndIndex = EndOffset / ElementSize;
1947 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1948 return false;
1949
1950 assert(EndIndex > BeginIndex && "Empty vector!");
1951 uint64_t NumElements = EndIndex - BeginIndex;
1952 Type *SliceTy = (NumElements == 1)
1953 ? Ty->getElementType()
1954 : VectorType::get(Ty->getElementType(), NumElements);
1955
1956 Type *SplitIntTy =
1957 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1958
1959 Use *U = S.getUse();
1960
1961 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1962 if (MI->isVolatile())
1963 return false;
1964 if (!S.isSplittable())
1965 return false; // Skip any unsplittable intrinsics.
1966 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1967 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1968 II->getIntrinsicID() != Intrinsic::lifetime_end)
1969 return false;
1970 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1971 // Disable vector promotion when there are loads or stores of an FCA.
1972 return false;
1973 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1974 if (LI->isVolatile())
1975 return false;
1976 Type *LTy = LI->getType();
1977 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1978 assert(LTy->isIntegerTy());
1979 LTy = SplitIntTy;
1980 }
1981 if (!canConvertValue(DL, SliceTy, LTy))
1982 return false;
1983 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1984 if (SI->isVolatile())
1985 return false;
1986 Type *STy = SI->getValueOperand()->getType();
1987 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1988 assert(STy->isIntegerTy());
1989 STy = SplitIntTy;
1990 }
1991 if (!canConvertValue(DL, STy, SliceTy))
1992 return false;
1993 } else {
1994 return false;
1995 }
1996
1997 return true;
1998 }
1999
2000 /// \brief Test whether the given alloca partitioning and range of slices can be
2001 /// promoted to a vector.
2002 ///
2003 /// This is a quick test to check whether we can rewrite a particular alloca
2004 /// partition (and its newly formed alloca) into a vector alloca with only
2005 /// whole-vector loads and stores such that it could be promoted to a vector
2006 /// SSA value. We only can ensure this for a limited set of operations, and we
2007 /// don't want to do the rewrites unless we are confident that the result will
2008 /// be promotable, so we have an early test here.
isVectorPromotionViable(AllocaSlices::Partition & P,const DataLayout & DL)2009 static VectorType *isVectorPromotionViable(AllocaSlices::Partition &P,
2010 const DataLayout &DL) {
2011 // Collect the candidate types for vector-based promotion. Also track whether
2012 // we have different element types.
2013 SmallVector<VectorType *, 4> CandidateTys;
2014 Type *CommonEltTy = nullptr;
2015 bool HaveCommonEltTy = true;
2016 auto CheckCandidateType = [&](Type *Ty) {
2017 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
2018 CandidateTys.push_back(VTy);
2019 if (!CommonEltTy)
2020 CommonEltTy = VTy->getElementType();
2021 else if (CommonEltTy != VTy->getElementType())
2022 HaveCommonEltTy = false;
2023 }
2024 };
2025 // Consider any loads or stores that are the exact size of the slice.
2026 for (const Slice &S : P)
2027 if (S.beginOffset() == P.beginOffset() &&
2028 S.endOffset() == P.endOffset()) {
2029 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
2030 CheckCandidateType(LI->getType());
2031 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
2032 CheckCandidateType(SI->getValueOperand()->getType());
2033 }
2034
2035 // If we didn't find a vector type, nothing to do here.
2036 if (CandidateTys.empty())
2037 return nullptr;
2038
2039 // Remove non-integer vector types if we had multiple common element types.
2040 // FIXME: It'd be nice to replace them with integer vector types, but we can't
2041 // do that until all the backends are known to produce good code for all
2042 // integer vector types.
2043 if (!HaveCommonEltTy) {
2044 CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
2045 [](VectorType *VTy) {
2046 return !VTy->getElementType()->isIntegerTy();
2047 }),
2048 CandidateTys.end());
2049
2050 // If there were no integer vector types, give up.
2051 if (CandidateTys.empty())
2052 return nullptr;
2053
2054 // Rank the remaining candidate vector types. This is easy because we know
2055 // they're all integer vectors. We sort by ascending number of elements.
2056 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
2057 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
2058 "Cannot have vector types of different sizes!");
2059 assert(RHSTy->getElementType()->isIntegerTy() &&
2060 "All non-integer types eliminated!");
2061 assert(LHSTy->getElementType()->isIntegerTy() &&
2062 "All non-integer types eliminated!");
2063 return RHSTy->getNumElements() < LHSTy->getNumElements();
2064 };
2065 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
2066 CandidateTys.erase(
2067 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
2068 CandidateTys.end());
2069 } else {
2070 // The only way to have the same element type in every vector type is to
2071 // have the same vector type. Check that and remove all but one.
2072 #ifndef NDEBUG
2073 for (VectorType *VTy : CandidateTys) {
2074 assert(VTy->getElementType() == CommonEltTy &&
2075 "Unaccounted for element type!");
2076 assert(VTy == CandidateTys[0] &&
2077 "Different vector types with the same element type!");
2078 }
2079 #endif
2080 CandidateTys.resize(1);
2081 }
2082
2083 // Try each vector type, and return the one which works.
2084 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
2085 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
2086
2087 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2088 // that aren't byte sized.
2089 if (ElementSize % 8)
2090 return false;
2091 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
2092 "vector size not a multiple of element size?");
2093 ElementSize /= 8;
2094
2095 for (const Slice &S : P)
2096 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
2097 return false;
2098
2099 for (const Slice *S : P.splitSliceTails())
2100 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
2101 return false;
2102
2103 return true;
2104 };
2105 for (VectorType *VTy : CandidateTys)
2106 if (CheckVectorTypeForPromotion(VTy))
2107 return VTy;
2108
2109 return nullptr;
2110 }
2111
2112 /// \brief Test whether a slice of an alloca is valid for integer widening.
2113 ///
2114 /// This implements the necessary checking for the \c isIntegerWideningViable
2115 /// test below on a single slice of the alloca.
isIntegerWideningViableForSlice(const Slice & S,uint64_t AllocBeginOffset,Type * AllocaTy,const DataLayout & DL,bool & WholeAllocaOp)2116 static bool isIntegerWideningViableForSlice(const Slice &S,
2117 uint64_t AllocBeginOffset,
2118 Type *AllocaTy,
2119 const DataLayout &DL,
2120 bool &WholeAllocaOp) {
2121 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
2122
2123 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2124 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
2125
2126 // We can't reasonably handle cases where the load or store extends past
2127 // the end of the aloca's type and into its padding.
2128 if (RelEnd > Size)
2129 return false;
2130
2131 Use *U = S.getUse();
2132
2133 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2134 if (LI->isVolatile())
2135 return false;
2136 // Note that we don't count vector loads or stores as whole-alloca
2137 // operations which enable integer widening because we would prefer to use
2138 // vector widening instead.
2139 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
2140 WholeAllocaOp = true;
2141 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2142 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
2143 return false;
2144 } else if (RelBegin != 0 || RelEnd != Size ||
2145 !canConvertValue(DL, AllocaTy, LI->getType())) {
2146 // Non-integer loads need to be convertible from the alloca type so that
2147 // they are promotable.
2148 return false;
2149 }
2150 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2151 Type *ValueTy = SI->getValueOperand()->getType();
2152 if (SI->isVolatile())
2153 return false;
2154 // Note that we don't count vector loads or stores as whole-alloca
2155 // operations which enable integer widening because we would prefer to use
2156 // vector widening instead.
2157 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
2158 WholeAllocaOp = true;
2159 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2160 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
2161 return false;
2162 } else if (RelBegin != 0 || RelEnd != Size ||
2163 !canConvertValue(DL, ValueTy, AllocaTy)) {
2164 // Non-integer stores need to be convertible to the alloca type so that
2165 // they are promotable.
2166 return false;
2167 }
2168 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2169 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2170 return false;
2171 if (!S.isSplittable())
2172 return false; // Skip any unsplittable intrinsics.
2173 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2174 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2175 II->getIntrinsicID() != Intrinsic::lifetime_end)
2176 return false;
2177 } else {
2178 return false;
2179 }
2180
2181 return true;
2182 }
2183
2184 /// \brief Test whether the given alloca partition's integer operations can be
2185 /// widened to promotable ones.
2186 ///
2187 /// This is a quick test to check whether we can rewrite the integer loads and
2188 /// stores to a particular alloca into wider loads and stores and be able to
2189 /// promote the resulting alloca.
isIntegerWideningViable(AllocaSlices::Partition & P,Type * AllocaTy,const DataLayout & DL)2190 static bool isIntegerWideningViable(AllocaSlices::Partition &P, Type *AllocaTy,
2191 const DataLayout &DL) {
2192 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
2193 // Don't create integer types larger than the maximum bitwidth.
2194 if (SizeInBits > IntegerType::MAX_INT_BITS)
2195 return false;
2196
2197 // Don't try to handle allocas with bit-padding.
2198 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
2199 return false;
2200
2201 // We need to ensure that an integer type with the appropriate bitwidth can
2202 // be converted to the alloca type, whatever that is. We don't want to force
2203 // the alloca itself to have an integer type if there is a more suitable one.
2204 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2205 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2206 !canConvertValue(DL, IntTy, AllocaTy))
2207 return false;
2208
2209 // While examining uses, we ensure that the alloca has a covering load or
2210 // store. We don't want to widen the integer operations only to fail to
2211 // promote due to some other unsplittable entry (which we may make splittable
2212 // later). However, if there are only splittable uses, go ahead and assume
2213 // that we cover the alloca.
2214 // FIXME: We shouldn't consider split slices that happen to start in the
2215 // partition here...
2216 bool WholeAllocaOp =
2217 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
2218
2219 for (const Slice &S : P)
2220 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2221 WholeAllocaOp))
2222 return false;
2223
2224 for (const Slice *S : P.splitSliceTails())
2225 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2226 WholeAllocaOp))
2227 return false;
2228
2229 return WholeAllocaOp;
2230 }
2231
extractInteger(const DataLayout & DL,IRBuilderTy & IRB,Value * V,IntegerType * Ty,uint64_t Offset,const Twine & Name)2232 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2233 IntegerType *Ty, uint64_t Offset,
2234 const Twine &Name) {
2235 DEBUG(dbgs() << " start: " << *V << "\n");
2236 IntegerType *IntTy = cast<IntegerType>(V->getType());
2237 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2238 "Element extends past full value");
2239 uint64_t ShAmt = 8 * Offset;
2240 if (DL.isBigEndian())
2241 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2242 if (ShAmt) {
2243 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2244 DEBUG(dbgs() << " shifted: " << *V << "\n");
2245 }
2246 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2247 "Cannot extract to a larger integer!");
2248 if (Ty != IntTy) {
2249 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2250 DEBUG(dbgs() << " trunced: " << *V << "\n");
2251 }
2252 return V;
2253 }
2254
insertInteger(const DataLayout & DL,IRBuilderTy & IRB,Value * Old,Value * V,uint64_t Offset,const Twine & Name)2255 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2256 Value *V, uint64_t Offset, const Twine &Name) {
2257 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2258 IntegerType *Ty = cast<IntegerType>(V->getType());
2259 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2260 "Cannot insert a larger integer!");
2261 DEBUG(dbgs() << " start: " << *V << "\n");
2262 if (Ty != IntTy) {
2263 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2264 DEBUG(dbgs() << " extended: " << *V << "\n");
2265 }
2266 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2267 "Element store outside of alloca store");
2268 uint64_t ShAmt = 8 * Offset;
2269 if (DL.isBigEndian())
2270 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2271 if (ShAmt) {
2272 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2273 DEBUG(dbgs() << " shifted: " << *V << "\n");
2274 }
2275
2276 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2277 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2278 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2279 DEBUG(dbgs() << " masked: " << *Old << "\n");
2280 V = IRB.CreateOr(Old, V, Name + ".insert");
2281 DEBUG(dbgs() << " inserted: " << *V << "\n");
2282 }
2283 return V;
2284 }
2285
extractVector(IRBuilderTy & IRB,Value * V,unsigned BeginIndex,unsigned EndIndex,const Twine & Name)2286 static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2287 unsigned EndIndex, const Twine &Name) {
2288 VectorType *VecTy = cast<VectorType>(V->getType());
2289 unsigned NumElements = EndIndex - BeginIndex;
2290 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2291
2292 if (NumElements == VecTy->getNumElements())
2293 return V;
2294
2295 if (NumElements == 1) {
2296 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2297 Name + ".extract");
2298 DEBUG(dbgs() << " extract: " << *V << "\n");
2299 return V;
2300 }
2301
2302 SmallVector<Constant *, 8> Mask;
2303 Mask.reserve(NumElements);
2304 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2305 Mask.push_back(IRB.getInt32(i));
2306 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2307 ConstantVector::get(Mask), Name + ".extract");
2308 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2309 return V;
2310 }
2311
insertVector(IRBuilderTy & IRB,Value * Old,Value * V,unsigned BeginIndex,const Twine & Name)2312 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2313 unsigned BeginIndex, const Twine &Name) {
2314 VectorType *VecTy = cast<VectorType>(Old->getType());
2315 assert(VecTy && "Can only insert a vector into a vector");
2316
2317 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2318 if (!Ty) {
2319 // Single element to insert.
2320 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2321 Name + ".insert");
2322 DEBUG(dbgs() << " insert: " << *V << "\n");
2323 return V;
2324 }
2325
2326 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2327 "Too many elements!");
2328 if (Ty->getNumElements() == VecTy->getNumElements()) {
2329 assert(V->getType() == VecTy && "Vector type mismatch");
2330 return V;
2331 }
2332 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2333
2334 // When inserting a smaller vector into the larger to store, we first
2335 // use a shuffle vector to widen it with undef elements, and then
2336 // a second shuffle vector to select between the loaded vector and the
2337 // incoming vector.
2338 SmallVector<Constant *, 8> Mask;
2339 Mask.reserve(VecTy->getNumElements());
2340 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2341 if (i >= BeginIndex && i < EndIndex)
2342 Mask.push_back(IRB.getInt32(i - BeginIndex));
2343 else
2344 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2345 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2346 ConstantVector::get(Mask), Name + ".expand");
2347 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2348
2349 Mask.clear();
2350 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2351 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2352
2353 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2354
2355 DEBUG(dbgs() << " blend: " << *V << "\n");
2356 return V;
2357 }
2358
2359 namespace {
2360 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
2361 /// to use a new alloca.
2362 ///
2363 /// Also implements the rewriting to vector-based accesses when the partition
2364 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2365 /// lives here.
2366 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
2367 // Befriend the base class so it can delegate to private visit methods.
2368 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2369 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
2370
2371 const DataLayout &DL;
2372 AllocaSlices &AS;
2373 SROA &Pass;
2374 AllocaInst &OldAI, &NewAI;
2375 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2376 Type *NewAllocaTy;
2377
2378 // This is a convenience and flag variable that will be null unless the new
2379 // alloca's integer operations should be widened to this integer type due to
2380 // passing isIntegerWideningViable above. If it is non-null, the desired
2381 // integer type will be stored here for easy access during rewriting.
2382 IntegerType *IntTy;
2383
2384 // If we are rewriting an alloca partition which can be written as pure
2385 // vector operations, we stash extra information here. When VecTy is
2386 // non-null, we have some strict guarantees about the rewritten alloca:
2387 // - The new alloca is exactly the size of the vector type here.
2388 // - The accesses all either map to the entire vector or to a single
2389 // element.
2390 // - The set of accessing instructions is only one of those handled above
2391 // in isVectorPromotionViable. Generally these are the same access kinds
2392 // which are promotable via mem2reg.
2393 VectorType *VecTy;
2394 Type *ElementTy;
2395 uint64_t ElementSize;
2396
2397 // The original offset of the slice currently being rewritten relative to
2398 // the original alloca.
2399 uint64_t BeginOffset, EndOffset;
2400 // The new offsets of the slice currently being rewritten relative to the
2401 // original alloca.
2402 uint64_t NewBeginOffset, NewEndOffset;
2403
2404 uint64_t SliceSize;
2405 bool IsSplittable;
2406 bool IsSplit;
2407 Use *OldUse;
2408 Instruction *OldPtr;
2409
2410 // Track post-rewrite users which are PHI nodes and Selects.
2411 SmallPtrSetImpl<PHINode *> &PHIUsers;
2412 SmallPtrSetImpl<SelectInst *> &SelectUsers;
2413
2414 // Utility IR builder, whose name prefix is setup for each visited use, and
2415 // the insertion point is set to point to the user.
2416 IRBuilderTy IRB;
2417
2418 public:
AllocaSliceRewriter(const DataLayout & DL,AllocaSlices & AS,SROA & Pass,AllocaInst & OldAI,AllocaInst & NewAI,uint64_t NewAllocaBeginOffset,uint64_t NewAllocaEndOffset,bool IsIntegerPromotable,VectorType * PromotableVecTy,SmallPtrSetImpl<PHINode * > & PHIUsers,SmallPtrSetImpl<SelectInst * > & SelectUsers)2419 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2420 AllocaInst &OldAI, AllocaInst &NewAI,
2421 uint64_t NewAllocaBeginOffset,
2422 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2423 VectorType *PromotableVecTy,
2424 SmallPtrSetImpl<PHINode *> &PHIUsers,
2425 SmallPtrSetImpl<SelectInst *> &SelectUsers)
2426 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2427 NewAllocaBeginOffset(NewAllocaBeginOffset),
2428 NewAllocaEndOffset(NewAllocaEndOffset),
2429 NewAllocaTy(NewAI.getAllocatedType()),
2430 IntTy(IsIntegerPromotable
2431 ? Type::getIntNTy(
2432 NewAI.getContext(),
2433 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2434 : nullptr),
2435 VecTy(PromotableVecTy),
2436 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2437 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2438 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
2439 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2440 IRB(NewAI.getContext(), ConstantFolder()) {
2441 if (VecTy) {
2442 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
2443 "Only multiple-of-8 sized vector elements are viable");
2444 ++NumVectorized;
2445 }
2446 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2447 }
2448
visit(AllocaSlices::const_iterator I)2449 bool visit(AllocaSlices::const_iterator I) {
2450 bool CanSROA = true;
2451 BeginOffset = I->beginOffset();
2452 EndOffset = I->endOffset();
2453 IsSplittable = I->isSplittable();
2454 IsSplit =
2455 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2456 DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2457 DEBUG(AS.printSlice(dbgs(), I, ""));
2458 DEBUG(dbgs() << "\n");
2459
2460 // Compute the intersecting offset range.
2461 assert(BeginOffset < NewAllocaEndOffset);
2462 assert(EndOffset > NewAllocaBeginOffset);
2463 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2464 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2465
2466 SliceSize = NewEndOffset - NewBeginOffset;
2467
2468 OldUse = I->getUse();
2469 OldPtr = cast<Instruction>(OldUse->get());
2470
2471 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2472 IRB.SetInsertPoint(OldUserI);
2473 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2474 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2475
2476 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2477 if (VecTy || IntTy)
2478 assert(CanSROA);
2479 return CanSROA;
2480 }
2481
2482 private:
2483 // Make sure the other visit overloads are visible.
2484 using Base::visit;
2485
2486 // Every instruction which can end up as a user must have a rewrite rule.
visitInstruction(Instruction & I)2487 bool visitInstruction(Instruction &I) {
2488 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2489 llvm_unreachable("No rewrite rule for this instruction!");
2490 }
2491
getNewAllocaSlicePtr(IRBuilderTy & IRB,Type * PointerTy)2492 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2493 // Note that the offset computation can use BeginOffset or NewBeginOffset
2494 // interchangeably for unsplit slices.
2495 assert(IsSplit || BeginOffset == NewBeginOffset);
2496 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2497
2498 #ifndef NDEBUG
2499 StringRef OldName = OldPtr->getName();
2500 // Skip through the last '.sroa.' component of the name.
2501 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2502 if (LastSROAPrefix != StringRef::npos) {
2503 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2504 // Look for an SROA slice index.
2505 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2506 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2507 // Strip the index and look for the offset.
2508 OldName = OldName.substr(IndexEnd + 1);
2509 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2510 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2511 // Strip the offset.
2512 OldName = OldName.substr(OffsetEnd + 1);
2513 }
2514 }
2515 // Strip any SROA suffixes as well.
2516 OldName = OldName.substr(0, OldName.find(".sroa_"));
2517 #endif
2518
2519 return getAdjustedPtr(IRB, DL, &NewAI,
2520 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
2521 #ifndef NDEBUG
2522 Twine(OldName) + "."
2523 #else
2524 Twine()
2525 #endif
2526 );
2527 }
2528
2529 /// \brief Compute suitable alignment to access this slice of the *new*
2530 /// alloca.
2531 ///
2532 /// You can optionally pass a type to this routine and if that type's ABI
2533 /// alignment is itself suitable, this will return zero.
getSliceAlign(Type * Ty=nullptr)2534 unsigned getSliceAlign(Type *Ty = nullptr) {
2535 unsigned NewAIAlign = NewAI.getAlignment();
2536 if (!NewAIAlign)
2537 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2538 unsigned Align =
2539 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2540 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
2541 }
2542
getIndex(uint64_t Offset)2543 unsigned getIndex(uint64_t Offset) {
2544 assert(VecTy && "Can only call getIndex when rewriting a vector");
2545 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2546 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2547 uint32_t Index = RelOffset / ElementSize;
2548 assert(Index * ElementSize == RelOffset);
2549 return Index;
2550 }
2551
deleteIfTriviallyDead(Value * V)2552 void deleteIfTriviallyDead(Value *V) {
2553 Instruction *I = cast<Instruction>(V);
2554 if (isInstructionTriviallyDead(I))
2555 Pass.DeadInsts.insert(I);
2556 }
2557
rewriteVectorizedLoadInst()2558 Value *rewriteVectorizedLoadInst() {
2559 unsigned BeginIndex = getIndex(NewBeginOffset);
2560 unsigned EndIndex = getIndex(NewEndOffset);
2561 assert(EndIndex > BeginIndex && "Empty vector!");
2562
2563 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2564 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2565 }
2566
rewriteIntegerLoad(LoadInst & LI)2567 Value *rewriteIntegerLoad(LoadInst &LI) {
2568 assert(IntTy && "We cannot insert an integer to the alloca");
2569 assert(!LI.isVolatile());
2570 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2571 V = convertValue(DL, IRB, V, IntTy);
2572 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2573 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2574 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
2575 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2576 "extract");
2577 return V;
2578 }
2579
visitLoadInst(LoadInst & LI)2580 bool visitLoadInst(LoadInst &LI) {
2581 DEBUG(dbgs() << " original: " << LI << "\n");
2582 Value *OldOp = LI.getOperand(0);
2583 assert(OldOp == OldPtr);
2584
2585 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2586 : LI.getType();
2587 bool IsPtrAdjusted = false;
2588 Value *V;
2589 if (VecTy) {
2590 V = rewriteVectorizedLoadInst();
2591 } else if (IntTy && LI.getType()->isIntegerTy()) {
2592 V = rewriteIntegerLoad(LI);
2593 } else if (NewBeginOffset == NewAllocaBeginOffset &&
2594 canConvertValue(DL, NewAllocaTy, LI.getType())) {
2595 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), LI.isVolatile(),
2596 LI.getName());
2597 } else {
2598 Type *LTy = TargetTy->getPointerTo();
2599 V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2600 getSliceAlign(TargetTy), LI.isVolatile(),
2601 LI.getName());
2602 IsPtrAdjusted = true;
2603 }
2604 V = convertValue(DL, IRB, V, TargetTy);
2605
2606 if (IsSplit) {
2607 assert(!LI.isVolatile());
2608 assert(LI.getType()->isIntegerTy() &&
2609 "Only integer type loads and stores are split");
2610 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
2611 "Split load isn't smaller than original load");
2612 assert(LI.getType()->getIntegerBitWidth() ==
2613 DL.getTypeStoreSizeInBits(LI.getType()) &&
2614 "Non-byte-multiple bit width");
2615 // Move the insertion point just past the load so that we can refer to it.
2616 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
2617 // Create a placeholder value with the same type as LI to use as the
2618 // basis for the new value. This allows us to replace the uses of LI with
2619 // the computed value, and then replace the placeholder with LI, leaving
2620 // LI only used for this computation.
2621 Value *Placeholder =
2622 new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2623 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2624 "insert");
2625 LI.replaceAllUsesWith(V);
2626 Placeholder->replaceAllUsesWith(&LI);
2627 delete Placeholder;
2628 } else {
2629 LI.replaceAllUsesWith(V);
2630 }
2631
2632 Pass.DeadInsts.insert(&LI);
2633 deleteIfTriviallyDead(OldOp);
2634 DEBUG(dbgs() << " to: " << *V << "\n");
2635 return !LI.isVolatile() && !IsPtrAdjusted;
2636 }
2637
rewriteVectorizedStoreInst(Value * V,StoreInst & SI,Value * OldOp)2638 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
2639 if (V->getType() != VecTy) {
2640 unsigned BeginIndex = getIndex(NewBeginOffset);
2641 unsigned EndIndex = getIndex(NewEndOffset);
2642 assert(EndIndex > BeginIndex && "Empty vector!");
2643 unsigned NumElements = EndIndex - BeginIndex;
2644 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2645 Type *SliceTy = (NumElements == 1)
2646 ? ElementTy
2647 : VectorType::get(ElementTy, NumElements);
2648 if (V->getType() != SliceTy)
2649 V = convertValue(DL, IRB, V, SliceTy);
2650
2651 // Mix in the existing elements.
2652 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2653 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2654 }
2655 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2656 Pass.DeadInsts.insert(&SI);
2657
2658 (void)Store;
2659 DEBUG(dbgs() << " to: " << *Store << "\n");
2660 return true;
2661 }
2662
rewriteIntegerStore(Value * V,StoreInst & SI)2663 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
2664 assert(IntTy && "We cannot extract an integer from the alloca");
2665 assert(!SI.isVolatile());
2666 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2667 Value *Old =
2668 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2669 Old = convertValue(DL, IRB, Old, IntTy);
2670 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2671 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2672 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
2673 }
2674 V = convertValue(DL, IRB, V, NewAllocaTy);
2675 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2676 Pass.DeadInsts.insert(&SI);
2677 (void)Store;
2678 DEBUG(dbgs() << " to: " << *Store << "\n");
2679 return true;
2680 }
2681
visitStoreInst(StoreInst & SI)2682 bool visitStoreInst(StoreInst &SI) {
2683 DEBUG(dbgs() << " original: " << SI << "\n");
2684 Value *OldOp = SI.getOperand(1);
2685 assert(OldOp == OldPtr);
2686
2687 Value *V = SI.getValueOperand();
2688
2689 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2690 // alloca that should be re-examined after promoting this alloca.
2691 if (V->getType()->isPointerTy())
2692 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2693 Pass.PostPromotionWorklist.insert(AI);
2694
2695 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
2696 assert(!SI.isVolatile());
2697 assert(V->getType()->isIntegerTy() &&
2698 "Only integer type loads and stores are split");
2699 assert(V->getType()->getIntegerBitWidth() ==
2700 DL.getTypeStoreSizeInBits(V->getType()) &&
2701 "Non-byte-multiple bit width");
2702 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2703 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2704 "extract");
2705 }
2706
2707 if (VecTy)
2708 return rewriteVectorizedStoreInst(V, SI, OldOp);
2709 if (IntTy && V->getType()->isIntegerTy())
2710 return rewriteIntegerStore(V, SI);
2711
2712 StoreInst *NewSI;
2713 if (NewBeginOffset == NewAllocaBeginOffset &&
2714 NewEndOffset == NewAllocaEndOffset &&
2715 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2716 V = convertValue(DL, IRB, V, NewAllocaTy);
2717 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2718 SI.isVolatile());
2719 } else {
2720 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
2721 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2722 SI.isVolatile());
2723 }
2724 (void)NewSI;
2725 Pass.DeadInsts.insert(&SI);
2726 deleteIfTriviallyDead(OldOp);
2727
2728 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2729 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2730 }
2731
2732 /// \brief Compute an integer value from splatting an i8 across the given
2733 /// number of bytes.
2734 ///
2735 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2736 /// call this routine.
2737 /// FIXME: Heed the advice above.
2738 ///
2739 /// \param V The i8 value to splat.
2740 /// \param Size The number of bytes in the output (assuming i8 is one byte)
getIntegerSplat(Value * V,unsigned Size)2741 Value *getIntegerSplat(Value *V, unsigned Size) {
2742 assert(Size > 0 && "Expected a positive number of bytes.");
2743 IntegerType *VTy = cast<IntegerType>(V->getType());
2744 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2745 if (Size == 1)
2746 return V;
2747
2748 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2749 V = IRB.CreateMul(
2750 IRB.CreateZExt(V, SplatIntTy, "zext"),
2751 ConstantExpr::getUDiv(
2752 Constant::getAllOnesValue(SplatIntTy),
2753 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2754 SplatIntTy)),
2755 "isplat");
2756 return V;
2757 }
2758
2759 /// \brief Compute a vector splat for a given element value.
getVectorSplat(Value * V,unsigned NumElements)2760 Value *getVectorSplat(Value *V, unsigned NumElements) {
2761 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2762 DEBUG(dbgs() << " splat: " << *V << "\n");
2763 return V;
2764 }
2765
visitMemSetInst(MemSetInst & II)2766 bool visitMemSetInst(MemSetInst &II) {
2767 DEBUG(dbgs() << " original: " << II << "\n");
2768 assert(II.getRawDest() == OldPtr);
2769
2770 // If the memset has a variable size, it cannot be split, just adjust the
2771 // pointer to the new alloca.
2772 if (!isa<Constant>(II.getLength())) {
2773 assert(!IsSplit);
2774 assert(NewBeginOffset == BeginOffset);
2775 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2776 Type *CstTy = II.getAlignmentCst()->getType();
2777 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
2778
2779 deleteIfTriviallyDead(OldPtr);
2780 return false;
2781 }
2782
2783 // Record this instruction for deletion.
2784 Pass.DeadInsts.insert(&II);
2785
2786 Type *AllocaTy = NewAI.getAllocatedType();
2787 Type *ScalarTy = AllocaTy->getScalarType();
2788
2789 // If this doesn't map cleanly onto the alloca type, and that type isn't
2790 // a single value type, just emit a memset.
2791 if (!VecTy && !IntTy &&
2792 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2793 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
2794 !AllocaTy->isSingleValueType() ||
2795 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2796 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
2797 Type *SizeTy = II.getLength()->getType();
2798 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2799 CallInst *New = IRB.CreateMemSet(
2800 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2801 getSliceAlign(), II.isVolatile());
2802 (void)New;
2803 DEBUG(dbgs() << " to: " << *New << "\n");
2804 return false;
2805 }
2806
2807 // If we can represent this as a simple value, we have to build the actual
2808 // value to store, which requires expanding the byte present in memset to
2809 // a sensible representation for the alloca type. This is essentially
2810 // splatting the byte to a sufficiently wide integer, splatting it across
2811 // any desired vector width, and bitcasting to the final type.
2812 Value *V;
2813
2814 if (VecTy) {
2815 // If this is a memset of a vectorized alloca, insert it.
2816 assert(ElementTy == ScalarTy);
2817
2818 unsigned BeginIndex = getIndex(NewBeginOffset);
2819 unsigned EndIndex = getIndex(NewEndOffset);
2820 assert(EndIndex > BeginIndex && "Empty vector!");
2821 unsigned NumElements = EndIndex - BeginIndex;
2822 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2823
2824 Value *Splat =
2825 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2826 Splat = convertValue(DL, IRB, Splat, ElementTy);
2827 if (NumElements > 1)
2828 Splat = getVectorSplat(Splat, NumElements);
2829
2830 Value *Old =
2831 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2832 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2833 } else if (IntTy) {
2834 // If this is a memset on an alloca where we can widen stores, insert the
2835 // set integer.
2836 assert(!II.isVolatile());
2837
2838 uint64_t Size = NewEndOffset - NewBeginOffset;
2839 V = getIntegerSplat(II.getValue(), Size);
2840
2841 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2842 EndOffset != NewAllocaBeginOffset)) {
2843 Value *Old =
2844 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2845 Old = convertValue(DL, IRB, Old, IntTy);
2846 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2847 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2848 } else {
2849 assert(V->getType() == IntTy &&
2850 "Wrong type for an alloca wide integer!");
2851 }
2852 V = convertValue(DL, IRB, V, AllocaTy);
2853 } else {
2854 // Established these invariants above.
2855 assert(NewBeginOffset == NewAllocaBeginOffset);
2856 assert(NewEndOffset == NewAllocaEndOffset);
2857
2858 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2859 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2860 V = getVectorSplat(V, AllocaVecTy->getNumElements());
2861
2862 V = convertValue(DL, IRB, V, AllocaTy);
2863 }
2864
2865 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2866 II.isVolatile());
2867 (void)New;
2868 DEBUG(dbgs() << " to: " << *New << "\n");
2869 return !II.isVolatile();
2870 }
2871
visitMemTransferInst(MemTransferInst & II)2872 bool visitMemTransferInst(MemTransferInst &II) {
2873 // Rewriting of memory transfer instructions can be a bit tricky. We break
2874 // them into two categories: split intrinsics and unsplit intrinsics.
2875
2876 DEBUG(dbgs() << " original: " << II << "\n");
2877
2878 bool IsDest = &II.getRawDestUse() == OldUse;
2879 assert((IsDest && II.getRawDest() == OldPtr) ||
2880 (!IsDest && II.getRawSource() == OldPtr));
2881
2882 unsigned SliceAlign = getSliceAlign();
2883
2884 // For unsplit intrinsics, we simply modify the source and destination
2885 // pointers in place. This isn't just an optimization, it is a matter of
2886 // correctness. With unsplit intrinsics we may be dealing with transfers
2887 // within a single alloca before SROA ran, or with transfers that have
2888 // a variable length. We may also be dealing with memmove instead of
2889 // memcpy, and so simply updating the pointers is the necessary for us to
2890 // update both source and dest of a single call.
2891 if (!IsSplittable) {
2892 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2893 if (IsDest)
2894 II.setDest(AdjustedPtr);
2895 else
2896 II.setSource(AdjustedPtr);
2897
2898 if (II.getAlignment() > SliceAlign) {
2899 Type *CstTy = II.getAlignmentCst()->getType();
2900 II.setAlignment(
2901 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
2902 }
2903
2904 DEBUG(dbgs() << " to: " << II << "\n");
2905 deleteIfTriviallyDead(OldPtr);
2906 return false;
2907 }
2908 // For split transfer intrinsics we have an incredibly useful assurance:
2909 // the source and destination do not reside within the same alloca, and at
2910 // least one of them does not escape. This means that we can replace
2911 // memmove with memcpy, and we don't need to worry about all manner of
2912 // downsides to splitting and transforming the operations.
2913
2914 // If this doesn't map cleanly onto the alloca type, and that type isn't
2915 // a single value type, just emit a memcpy.
2916 bool EmitMemCpy =
2917 !VecTy && !IntTy &&
2918 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2919 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2920 !NewAI.getAllocatedType()->isSingleValueType());
2921
2922 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2923 // size hasn't been shrunk based on analysis of the viable range, this is
2924 // a no-op.
2925 if (EmitMemCpy && &OldAI == &NewAI) {
2926 // Ensure the start lines up.
2927 assert(NewBeginOffset == BeginOffset);
2928
2929 // Rewrite the size as needed.
2930 if (NewEndOffset != EndOffset)
2931 II.setLength(ConstantInt::get(II.getLength()->getType(),
2932 NewEndOffset - NewBeginOffset));
2933 return false;
2934 }
2935 // Record this instruction for deletion.
2936 Pass.DeadInsts.insert(&II);
2937
2938 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2939 // alloca that should be re-examined after rewriting this instruction.
2940 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2941 if (AllocaInst *AI =
2942 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2943 assert(AI != &OldAI && AI != &NewAI &&
2944 "Splittable transfers cannot reach the same alloca on both ends.");
2945 Pass.Worklist.insert(AI);
2946 }
2947
2948 Type *OtherPtrTy = OtherPtr->getType();
2949 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2950
2951 // Compute the relative offset for the other pointer within the transfer.
2952 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
2953 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2954 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2955 OtherOffset.zextOrTrunc(64).getZExtValue());
2956
2957 if (EmitMemCpy) {
2958 // Compute the other pointer, folding as much as possible to produce
2959 // a single, simple GEP in most cases.
2960 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2961 OtherPtr->getName() + ".");
2962
2963 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2964 Type *SizeTy = II.getLength()->getType();
2965 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2966
2967 CallInst *New = IRB.CreateMemCpy(
2968 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2969 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
2970 (void)New;
2971 DEBUG(dbgs() << " to: " << *New << "\n");
2972 return false;
2973 }
2974
2975 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2976 NewEndOffset == NewAllocaEndOffset;
2977 uint64_t Size = NewEndOffset - NewBeginOffset;
2978 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2979 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2980 unsigned NumElements = EndIndex - BeginIndex;
2981 IntegerType *SubIntTy =
2982 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
2983
2984 // Reset the other pointer type to match the register type we're going to
2985 // use, but using the address space of the original other pointer.
2986 if (VecTy && !IsWholeAlloca) {
2987 if (NumElements == 1)
2988 OtherPtrTy = VecTy->getElementType();
2989 else
2990 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2991
2992 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
2993 } else if (IntTy && !IsWholeAlloca) {
2994 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2995 } else {
2996 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
2997 }
2998
2999 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
3000 OtherPtr->getName() + ".");
3001 unsigned SrcAlign = OtherAlign;
3002 Value *DstPtr = &NewAI;
3003 unsigned DstAlign = SliceAlign;
3004 if (!IsDest) {
3005 std::swap(SrcPtr, DstPtr);
3006 std::swap(SrcAlign, DstAlign);
3007 }
3008
3009 Value *Src;
3010 if (VecTy && !IsWholeAlloca && !IsDest) {
3011 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
3012 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
3013 } else if (IntTy && !IsWholeAlloca && !IsDest) {
3014 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
3015 Src = convertValue(DL, IRB, Src, IntTy);
3016 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3017 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
3018 } else {
3019 Src =
3020 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
3021 }
3022
3023 if (VecTy && !IsWholeAlloca && IsDest) {
3024 Value *Old =
3025 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
3026 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
3027 } else if (IntTy && !IsWholeAlloca && IsDest) {
3028 Value *Old =
3029 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
3030 Old = convertValue(DL, IRB, Old, IntTy);
3031 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3032 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3033 Src = convertValue(DL, IRB, Src, NewAllocaTy);
3034 }
3035
3036 StoreInst *Store = cast<StoreInst>(
3037 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
3038 (void)Store;
3039 DEBUG(dbgs() << " to: " << *Store << "\n");
3040 return !II.isVolatile();
3041 }
3042
visitIntrinsicInst(IntrinsicInst & II)3043 bool visitIntrinsicInst(IntrinsicInst &II) {
3044 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
3045 II.getIntrinsicID() == Intrinsic::lifetime_end);
3046 DEBUG(dbgs() << " original: " << II << "\n");
3047 assert(II.getArgOperand(1) == OldPtr);
3048
3049 // Record this instruction for deletion.
3050 Pass.DeadInsts.insert(&II);
3051
3052 ConstantInt *Size =
3053 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
3054 NewEndOffset - NewBeginOffset);
3055 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3056 Value *New;
3057 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3058 New = IRB.CreateLifetimeStart(Ptr, Size);
3059 else
3060 New = IRB.CreateLifetimeEnd(Ptr, Size);
3061
3062 (void)New;
3063 DEBUG(dbgs() << " to: " << *New << "\n");
3064 return true;
3065 }
3066
visitPHINode(PHINode & PN)3067 bool visitPHINode(PHINode &PN) {
3068 DEBUG(dbgs() << " original: " << PN << "\n");
3069 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3070 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
3071
3072 // We would like to compute a new pointer in only one place, but have it be
3073 // as local as possible to the PHI. To do that, we re-use the location of
3074 // the old pointer, which necessarily must be in the right position to
3075 // dominate the PHI.
3076 IRBuilderTy PtrBuilder(IRB);
3077 if (isa<PHINode>(OldPtr))
3078 PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
3079 else
3080 PtrBuilder.SetInsertPoint(OldPtr);
3081 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
3082
3083 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
3084 // Replace the operands which were using the old pointer.
3085 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3086
3087 DEBUG(dbgs() << " to: " << PN << "\n");
3088 deleteIfTriviallyDead(OldPtr);
3089
3090 // PHIs can't be promoted on their own, but often can be speculated. We
3091 // check the speculation outside of the rewriter so that we see the
3092 // fully-rewritten alloca.
3093 PHIUsers.insert(&PN);
3094 return true;
3095 }
3096
visitSelectInst(SelectInst & SI)3097 bool visitSelectInst(SelectInst &SI) {
3098 DEBUG(dbgs() << " original: " << SI << "\n");
3099 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3100 "Pointer isn't an operand!");
3101 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3102 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
3103
3104 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3105 // Replace the operands which were using the old pointer.
3106 if (SI.getOperand(1) == OldPtr)
3107 SI.setOperand(1, NewPtr);
3108 if (SI.getOperand(2) == OldPtr)
3109 SI.setOperand(2, NewPtr);
3110
3111 DEBUG(dbgs() << " to: " << SI << "\n");
3112 deleteIfTriviallyDead(OldPtr);
3113
3114 // Selects can't be promoted on their own, but often can be speculated. We
3115 // check the speculation outside of the rewriter so that we see the
3116 // fully-rewritten alloca.
3117 SelectUsers.insert(&SI);
3118 return true;
3119 }
3120 };
3121 }
3122
3123 namespace {
3124 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
3125 ///
3126 /// This pass aggressively rewrites all aggregate loads and stores on
3127 /// a particular pointer (or any pointer derived from it which we can identify)
3128 /// with scalar loads and stores.
3129 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3130 // Befriend the base class so it can delegate to private visit methods.
3131 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3132
3133 const DataLayout &DL;
3134
3135 /// Queue of pointer uses to analyze and potentially rewrite.
3136 SmallVector<Use *, 8> Queue;
3137
3138 /// Set to prevent us from cycling with phi nodes and loops.
3139 SmallPtrSet<User *, 8> Visited;
3140
3141 /// The current pointer use being rewritten. This is used to dig up the used
3142 /// value (as opposed to the user).
3143 Use *U;
3144
3145 public:
AggLoadStoreRewriter(const DataLayout & DL)3146 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
3147
3148 /// Rewrite loads and stores through a pointer and all pointers derived from
3149 /// it.
rewrite(Instruction & I)3150 bool rewrite(Instruction &I) {
3151 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3152 enqueueUsers(I);
3153 bool Changed = false;
3154 while (!Queue.empty()) {
3155 U = Queue.pop_back_val();
3156 Changed |= visit(cast<Instruction>(U->getUser()));
3157 }
3158 return Changed;
3159 }
3160
3161 private:
3162 /// Enqueue all the users of the given instruction for further processing.
3163 /// This uses a set to de-duplicate users.
enqueueUsers(Instruction & I)3164 void enqueueUsers(Instruction &I) {
3165 for (Use &U : I.uses())
3166 if (Visited.insert(U.getUser()).second)
3167 Queue.push_back(&U);
3168 }
3169
3170 // Conservative default is to not rewrite anything.
visitInstruction(Instruction & I)3171 bool visitInstruction(Instruction &I) { return false; }
3172
3173 /// \brief Generic recursive split emission class.
3174 template <typename Derived> class OpSplitter {
3175 protected:
3176 /// The builder used to form new instructions.
3177 IRBuilderTy IRB;
3178 /// The indices which to be used with insert- or extractvalue to select the
3179 /// appropriate value within the aggregate.
3180 SmallVector<unsigned, 4> Indices;
3181 /// The indices to a GEP instruction which will move Ptr to the correct slot
3182 /// within the aggregate.
3183 SmallVector<Value *, 4> GEPIndices;
3184 /// The base pointer of the original op, used as a base for GEPing the
3185 /// split operations.
3186 Value *Ptr;
3187
3188 /// Initialize the splitter with an insertion point, Ptr and start with a
3189 /// single zero GEP index.
OpSplitter(Instruction * InsertionPoint,Value * Ptr)3190 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
3191 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3192
3193 public:
3194 /// \brief Generic recursive split emission routine.
3195 ///
3196 /// This method recursively splits an aggregate op (load or store) into
3197 /// scalar or vector ops. It splits recursively until it hits a single value
3198 /// and emits that single value operation via the template argument.
3199 ///
3200 /// The logic of this routine relies on GEPs and insertvalue and
3201 /// extractvalue all operating with the same fundamental index list, merely
3202 /// formatted differently (GEPs need actual values).
3203 ///
3204 /// \param Ty The type being split recursively into smaller ops.
3205 /// \param Agg The aggregate value being built up or stored, depending on
3206 /// whether this is splitting a load or a store respectively.
emitSplitOps(Type * Ty,Value * & Agg,const Twine & Name)3207 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3208 if (Ty->isSingleValueType())
3209 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
3210
3211 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3212 unsigned OldSize = Indices.size();
3213 (void)OldSize;
3214 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3215 ++Idx) {
3216 assert(Indices.size() == OldSize && "Did not return to the old size");
3217 Indices.push_back(Idx);
3218 GEPIndices.push_back(IRB.getInt32(Idx));
3219 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3220 GEPIndices.pop_back();
3221 Indices.pop_back();
3222 }
3223 return;
3224 }
3225
3226 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3227 unsigned OldSize = Indices.size();
3228 (void)OldSize;
3229 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3230 ++Idx) {
3231 assert(Indices.size() == OldSize && "Did not return to the old size");
3232 Indices.push_back(Idx);
3233 GEPIndices.push_back(IRB.getInt32(Idx));
3234 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3235 GEPIndices.pop_back();
3236 Indices.pop_back();
3237 }
3238 return;
3239 }
3240
3241 llvm_unreachable("Only arrays and structs are aggregate loadable types");
3242 }
3243 };
3244
3245 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
LoadOpSplitter__anonadce12ea0f11::AggLoadStoreRewriter::LoadOpSplitter3246 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3247 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
3248
3249 /// Emit a leaf load of a single value. This is called at the leaves of the
3250 /// recursive emission to actually load values.
emitFunc__anonadce12ea0f11::AggLoadStoreRewriter::LoadOpSplitter3251 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3252 assert(Ty->isSingleValueType());
3253 // Load the single value and insert it using the indices.
3254 Value *GEP =
3255 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
3256 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
3257 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3258 DEBUG(dbgs() << " to: " << *Load << "\n");
3259 }
3260 };
3261
visitLoadInst(LoadInst & LI)3262 bool visitLoadInst(LoadInst &LI) {
3263 assert(LI.getPointerOperand() == *U);
3264 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3265 return false;
3266
3267 // We have an aggregate being loaded, split it apart.
3268 DEBUG(dbgs() << " original: " << LI << "\n");
3269 LoadOpSplitter Splitter(&LI, *U);
3270 Value *V = UndefValue::get(LI.getType());
3271 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3272 LI.replaceAllUsesWith(V);
3273 LI.eraseFromParent();
3274 return true;
3275 }
3276
3277 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
StoreOpSplitter__anonadce12ea0f11::AggLoadStoreRewriter::StoreOpSplitter3278 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3279 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
3280
3281 /// Emit a leaf store of a single value. This is called at the leaves of the
3282 /// recursive emission to actually produce stores.
emitFunc__anonadce12ea0f11::AggLoadStoreRewriter::StoreOpSplitter3283 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3284 assert(Ty->isSingleValueType());
3285 // Extract the single value and store it using the indices.
3286 Value *Store = IRB.CreateStore(
3287 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3288 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep"));
3289 (void)Store;
3290 DEBUG(dbgs() << " to: " << *Store << "\n");
3291 }
3292 };
3293
visitStoreInst(StoreInst & SI)3294 bool visitStoreInst(StoreInst &SI) {
3295 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3296 return false;
3297 Value *V = SI.getValueOperand();
3298 if (V->getType()->isSingleValueType())
3299 return false;
3300
3301 // We have an aggregate being stored, split it apart.
3302 DEBUG(dbgs() << " original: " << SI << "\n");
3303 StoreOpSplitter Splitter(&SI, *U);
3304 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3305 SI.eraseFromParent();
3306 return true;
3307 }
3308
visitBitCastInst(BitCastInst & BC)3309 bool visitBitCastInst(BitCastInst &BC) {
3310 enqueueUsers(BC);
3311 return false;
3312 }
3313
visitGetElementPtrInst(GetElementPtrInst & GEPI)3314 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3315 enqueueUsers(GEPI);
3316 return false;
3317 }
3318
visitPHINode(PHINode & PN)3319 bool visitPHINode(PHINode &PN) {
3320 enqueueUsers(PN);
3321 return false;
3322 }
3323
visitSelectInst(SelectInst & SI)3324 bool visitSelectInst(SelectInst &SI) {
3325 enqueueUsers(SI);
3326 return false;
3327 }
3328 };
3329 }
3330
3331 /// \brief Strip aggregate type wrapping.
3332 ///
3333 /// This removes no-op aggregate types wrapping an underlying type. It will
3334 /// strip as many layers of types as it can without changing either the type
3335 /// size or the allocated size.
stripAggregateTypeWrapping(const DataLayout & DL,Type * Ty)3336 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3337 if (Ty->isSingleValueType())
3338 return Ty;
3339
3340 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3341 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3342
3343 Type *InnerTy;
3344 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3345 InnerTy = ArrTy->getElementType();
3346 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3347 const StructLayout *SL = DL.getStructLayout(STy);
3348 unsigned Index = SL->getElementContainingOffset(0);
3349 InnerTy = STy->getElementType(Index);
3350 } else {
3351 return Ty;
3352 }
3353
3354 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3355 TypeSize > DL.getTypeSizeInBits(InnerTy))
3356 return Ty;
3357
3358 return stripAggregateTypeWrapping(DL, InnerTy);
3359 }
3360
3361 /// \brief Try to find a partition of the aggregate type passed in for a given
3362 /// offset and size.
3363 ///
3364 /// This recurses through the aggregate type and tries to compute a subtype
3365 /// based on the offset and size. When the offset and size span a sub-section
3366 /// of an array, it will even compute a new array type for that sub-section,
3367 /// and the same for structs.
3368 ///
3369 /// Note that this routine is very strict and tries to find a partition of the
3370 /// type which produces the *exact* right offset and size. It is not forgiving
3371 /// when the size or offset cause either end of type-based partition to be off.
3372 /// Also, this is a best-effort routine. It is reasonable to give up and not
3373 /// return a type if necessary.
getTypePartition(const DataLayout & DL,Type * Ty,uint64_t Offset,uint64_t Size)3374 static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3375 uint64_t Size) {
3376 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3377 return stripAggregateTypeWrapping(DL, Ty);
3378 if (Offset > DL.getTypeAllocSize(Ty) ||
3379 (DL.getTypeAllocSize(Ty) - Offset) < Size)
3380 return nullptr;
3381
3382 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3383 // We can't partition pointers...
3384 if (SeqTy->isPointerTy())
3385 return nullptr;
3386
3387 Type *ElementTy = SeqTy->getElementType();
3388 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3389 uint64_t NumSkippedElements = Offset / ElementSize;
3390 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
3391 if (NumSkippedElements >= ArrTy->getNumElements())
3392 return nullptr;
3393 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
3394 if (NumSkippedElements >= VecTy->getNumElements())
3395 return nullptr;
3396 }
3397 Offset -= NumSkippedElements * ElementSize;
3398
3399 // First check if we need to recurse.
3400 if (Offset > 0 || Size < ElementSize) {
3401 // Bail if the partition ends in a different array element.
3402 if ((Offset + Size) > ElementSize)
3403 return nullptr;
3404 // Recurse through the element type trying to peel off offset bytes.
3405 return getTypePartition(DL, ElementTy, Offset, Size);
3406 }
3407 assert(Offset == 0);
3408
3409 if (Size == ElementSize)
3410 return stripAggregateTypeWrapping(DL, ElementTy);
3411 assert(Size > ElementSize);
3412 uint64_t NumElements = Size / ElementSize;
3413 if (NumElements * ElementSize != Size)
3414 return nullptr;
3415 return ArrayType::get(ElementTy, NumElements);
3416 }
3417
3418 StructType *STy = dyn_cast<StructType>(Ty);
3419 if (!STy)
3420 return nullptr;
3421
3422 const StructLayout *SL = DL.getStructLayout(STy);
3423 if (Offset >= SL->getSizeInBytes())
3424 return nullptr;
3425 uint64_t EndOffset = Offset + Size;
3426 if (EndOffset > SL->getSizeInBytes())
3427 return nullptr;
3428
3429 unsigned Index = SL->getElementContainingOffset(Offset);
3430 Offset -= SL->getElementOffset(Index);
3431
3432 Type *ElementTy = STy->getElementType(Index);
3433 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3434 if (Offset >= ElementSize)
3435 return nullptr; // The offset points into alignment padding.
3436
3437 // See if any partition must be contained by the element.
3438 if (Offset > 0 || Size < ElementSize) {
3439 if ((Offset + Size) > ElementSize)
3440 return nullptr;
3441 return getTypePartition(DL, ElementTy, Offset, Size);
3442 }
3443 assert(Offset == 0);
3444
3445 if (Size == ElementSize)
3446 return stripAggregateTypeWrapping(DL, ElementTy);
3447
3448 StructType::element_iterator EI = STy->element_begin() + Index,
3449 EE = STy->element_end();
3450 if (EndOffset < SL->getSizeInBytes()) {
3451 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3452 if (Index == EndIndex)
3453 return nullptr; // Within a single element and its padding.
3454
3455 // Don't try to form "natural" types if the elements don't line up with the
3456 // expected size.
3457 // FIXME: We could potentially recurse down through the last element in the
3458 // sub-struct to find a natural end point.
3459 if (SL->getElementOffset(EndIndex) != EndOffset)
3460 return nullptr;
3461
3462 assert(Index < EndIndex);
3463 EE = STy->element_begin() + EndIndex;
3464 }
3465
3466 // Try to build up a sub-structure.
3467 StructType *SubTy =
3468 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
3469 const StructLayout *SubSL = DL.getStructLayout(SubTy);
3470 if (Size != SubSL->getSizeInBytes())
3471 return nullptr; // The sub-struct doesn't have quite the size needed.
3472
3473 return SubTy;
3474 }
3475
3476 /// \brief Pre-split loads and stores to simplify rewriting.
3477 ///
3478 /// We want to break up the splittable load+store pairs as much as
3479 /// possible. This is important to do as a preprocessing step, as once we
3480 /// start rewriting the accesses to partitions of the alloca we lose the
3481 /// necessary information to correctly split apart paired loads and stores
3482 /// which both point into this alloca. The case to consider is something like
3483 /// the following:
3484 ///
3485 /// %a = alloca [12 x i8]
3486 /// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3487 /// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3488 /// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3489 /// %iptr1 = bitcast i8* %gep1 to i64*
3490 /// %iptr2 = bitcast i8* %gep2 to i64*
3491 /// %fptr1 = bitcast i8* %gep1 to float*
3492 /// %fptr2 = bitcast i8* %gep2 to float*
3493 /// %fptr3 = bitcast i8* %gep3 to float*
3494 /// store float 0.0, float* %fptr1
3495 /// store float 1.0, float* %fptr2
3496 /// %v = load i64* %iptr1
3497 /// store i64 %v, i64* %iptr2
3498 /// %f1 = load float* %fptr2
3499 /// %f2 = load float* %fptr3
3500 ///
3501 /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3502 /// promote everything so we recover the 2 SSA values that should have been
3503 /// there all along.
3504 ///
3505 /// \returns true if any changes are made.
presplitLoadsAndStores(AllocaInst & AI,AllocaSlices & AS)3506 bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3507 DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3508
3509 // Track the loads and stores which are candidates for pre-splitting here, in
3510 // the order they first appear during the partition scan. These give stable
3511 // iteration order and a basis for tracking which loads and stores we
3512 // actually split.
3513 SmallVector<LoadInst *, 4> Loads;
3514 SmallVector<StoreInst *, 4> Stores;
3515
3516 // We need to accumulate the splits required of each load or store where we
3517 // can find them via a direct lookup. This is important to cross-check loads
3518 // and stores against each other. We also track the slice so that we can kill
3519 // all the slices that end up split.
3520 struct SplitOffsets {
3521 Slice *S;
3522 std::vector<uint64_t> Splits;
3523 };
3524 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3525
3526 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3527 // This is important as we also cannot pre-split stores of those loads!
3528 // FIXME: This is all pretty gross. It means that we can be more aggressive
3529 // in pre-splitting when the load feeding the store happens to come from
3530 // a separate alloca. Put another way, the effectiveness of SROA would be
3531 // decreased by a frontend which just concatenated all of its local allocas
3532 // into one big flat alloca. But defeating such patterns is exactly the job
3533 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3534 // change store pre-splitting to actually force pre-splitting of the load
3535 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3536 // maybe it would make it more principled?
3537 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3538
3539 DEBUG(dbgs() << " Searching for candidate loads and stores\n");
3540 for (auto &P : AS.partitions()) {
3541 for (Slice &S : P) {
3542 Instruction *I = cast<Instruction>(S.getUse()->getUser());
3543 if (!S.isSplittable() ||S.endOffset() <= P.endOffset()) {
3544 // If this was a load we have to track that it can't participate in any
3545 // pre-splitting!
3546 if (auto *LI = dyn_cast<LoadInst>(I))
3547 UnsplittableLoads.insert(LI);
3548 continue;
3549 }
3550 assert(P.endOffset() > S.beginOffset() &&
3551 "Empty or backwards partition!");
3552
3553 // Determine if this is a pre-splittable slice.
3554 if (auto *LI = dyn_cast<LoadInst>(I)) {
3555 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3556
3557 // The load must be used exclusively to store into other pointers for
3558 // us to be able to arbitrarily pre-split it. The stores must also be
3559 // simple to avoid changing semantics.
3560 auto IsLoadSimplyStored = [](LoadInst *LI) {
3561 for (User *LU : LI->users()) {
3562 auto *SI = dyn_cast<StoreInst>(LU);
3563 if (!SI || !SI->isSimple())
3564 return false;
3565 }
3566 return true;
3567 };
3568 if (!IsLoadSimplyStored(LI)) {
3569 UnsplittableLoads.insert(LI);
3570 continue;
3571 }
3572
3573 Loads.push_back(LI);
3574 } else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) {
3575 if (!SI ||
3576 S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3577 continue;
3578 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3579 if (!StoredLoad || !StoredLoad->isSimple())
3580 continue;
3581 assert(!SI->isVolatile() && "Cannot split volatile stores!");
3582
3583 Stores.push_back(SI);
3584 } else {
3585 // Other uses cannot be pre-split.
3586 continue;
3587 }
3588
3589 // Record the initial split.
3590 DEBUG(dbgs() << " Candidate: " << *I << "\n");
3591 auto &Offsets = SplitOffsetsMap[I];
3592 assert(Offsets.Splits.empty() &&
3593 "Should not have splits the first time we see an instruction!");
3594 Offsets.S = &S;
3595 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
3596 }
3597
3598 // Now scan the already split slices, and add a split for any of them which
3599 // we're going to pre-split.
3600 for (Slice *S : P.splitSliceTails()) {
3601 auto SplitOffsetsMapI =
3602 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3603 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3604 continue;
3605 auto &Offsets = SplitOffsetsMapI->second;
3606
3607 assert(Offsets.S == S && "Found a mismatched slice!");
3608 assert(!Offsets.Splits.empty() &&
3609 "Cannot have an empty set of splits on the second partition!");
3610 assert(Offsets.Splits.back() ==
3611 P.beginOffset() - Offsets.S->beginOffset() &&
3612 "Previous split does not end where this one begins!");
3613
3614 // Record each split. The last partition's end isn't needed as the size
3615 // of the slice dictates that.
3616 if (S->endOffset() > P.endOffset())
3617 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
3618 }
3619 }
3620
3621 // We may have split loads where some of their stores are split stores. For
3622 // such loads and stores, we can only pre-split them if their splits exactly
3623 // match relative to their starting offset. We have to verify this prior to
3624 // any rewriting.
3625 Stores.erase(
3626 std::remove_if(Stores.begin(), Stores.end(),
3627 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3628 // Lookup the load we are storing in our map of split
3629 // offsets.
3630 auto *LI = cast<LoadInst>(SI->getValueOperand());
3631 // If it was completely unsplittable, then we're done,
3632 // and this store can't be pre-split.
3633 if (UnsplittableLoads.count(LI))
3634 return true;
3635
3636 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3637 if (LoadOffsetsI == SplitOffsetsMap.end())
3638 return false; // Unrelated loads are definitely safe.
3639 auto &LoadOffsets = LoadOffsetsI->second;
3640
3641 // Now lookup the store's offsets.
3642 auto &StoreOffsets = SplitOffsetsMap[SI];
3643
3644 // If the relative offsets of each split in the load and
3645 // store match exactly, then we can split them and we
3646 // don't need to remove them here.
3647 if (LoadOffsets.Splits == StoreOffsets.Splits)
3648 return false;
3649
3650 DEBUG(dbgs()
3651 << " Mismatched splits for load and store:\n"
3652 << " " << *LI << "\n"
3653 << " " << *SI << "\n");
3654
3655 // We've found a store and load that we need to split
3656 // with mismatched relative splits. Just give up on them
3657 // and remove both instructions from our list of
3658 // candidates.
3659 UnsplittableLoads.insert(LI);
3660 return true;
3661 }),
3662 Stores.end());
3663 // Now we have to go *back* through all te stores, because a later store may
3664 // have caused an earlier store's load to become unsplittable and if it is
3665 // unsplittable for the later store, then we can't rely on it being split in
3666 // the earlier store either.
3667 Stores.erase(std::remove_if(Stores.begin(), Stores.end(),
3668 [&UnsplittableLoads](StoreInst *SI) {
3669 auto *LI =
3670 cast<LoadInst>(SI->getValueOperand());
3671 return UnsplittableLoads.count(LI);
3672 }),
3673 Stores.end());
3674 // Once we've established all the loads that can't be split for some reason,
3675 // filter any that made it into our list out.
3676 Loads.erase(std::remove_if(Loads.begin(), Loads.end(),
3677 [&UnsplittableLoads](LoadInst *LI) {
3678 return UnsplittableLoads.count(LI);
3679 }),
3680 Loads.end());
3681
3682
3683 // If no loads or stores are left, there is no pre-splitting to be done for
3684 // this alloca.
3685 if (Loads.empty() && Stores.empty())
3686 return false;
3687
3688 // From here on, we can't fail and will be building new accesses, so rig up
3689 // an IR builder.
3690 IRBuilderTy IRB(&AI);
3691
3692 // Collect the new slices which we will merge into the alloca slices.
3693 SmallVector<Slice, 4> NewSlices;
3694
3695 // Track any allocas we end up splitting loads and stores for so we iterate
3696 // on them.
3697 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3698
3699 // At this point, we have collected all of the loads and stores we can
3700 // pre-split, and the specific splits needed for them. We actually do the
3701 // splitting in a specific order in order to handle when one of the loads in
3702 // the value operand to one of the stores.
3703 //
3704 // First, we rewrite all of the split loads, and just accumulate each split
3705 // load in a parallel structure. We also build the slices for them and append
3706 // them to the alloca slices.
3707 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3708 std::vector<LoadInst *> SplitLoads;
3709 const DataLayout &DL = AI.getModule()->getDataLayout();
3710 for (LoadInst *LI : Loads) {
3711 SplitLoads.clear();
3712
3713 IntegerType *Ty = cast<IntegerType>(LI->getType());
3714 uint64_t LoadSize = Ty->getBitWidth() / 8;
3715 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3716
3717 auto &Offsets = SplitOffsetsMap[LI];
3718 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3719 "Slice size should always match load size exactly!");
3720 uint64_t BaseOffset = Offsets.S->beginOffset();
3721 assert(BaseOffset + LoadSize > BaseOffset &&
3722 "Cannot represent alloca access size using 64-bit integers!");
3723
3724 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
3725 IRB.SetInsertPoint(BasicBlock::iterator(LI));
3726
3727 DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
3728
3729 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3730 int Idx = 0, Size = Offsets.Splits.size();
3731 for (;;) {
3732 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3733 auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3734 LoadInst *PLoad = IRB.CreateAlignedLoad(
3735 getAdjustedPtr(IRB, DL, BasePtr,
3736 APInt(DL.getPointerSizeInBits(), PartOffset),
3737 PartPtrTy, BasePtr->getName() + "."),
3738 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
3739 LI->getName());
3740
3741 // Append this load onto the list of split loads so we can find it later
3742 // to rewrite the stores.
3743 SplitLoads.push_back(PLoad);
3744
3745 // Now build a new slice for the alloca.
3746 NewSlices.push_back(
3747 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3748 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
3749 /*IsSplittable*/ false));
3750 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3751 << ", " << NewSlices.back().endOffset() << "): " << *PLoad
3752 << "\n");
3753
3754 // See if we've handled all the splits.
3755 if (Idx >= Size)
3756 break;
3757
3758 // Setup the next partition.
3759 PartOffset = Offsets.Splits[Idx];
3760 ++Idx;
3761 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3762 }
3763
3764 // Now that we have the split loads, do the slow walk over all uses of the
3765 // load and rewrite them as split stores, or save the split loads to use
3766 // below if the store is going to be split there anyways.
3767 bool DeferredStores = false;
3768 for (User *LU : LI->users()) {
3769 StoreInst *SI = cast<StoreInst>(LU);
3770 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3771 DeferredStores = true;
3772 DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
3773 continue;
3774 }
3775
3776 Value *StoreBasePtr = SI->getPointerOperand();
3777 IRB.SetInsertPoint(BasicBlock::iterator(SI));
3778
3779 DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
3780
3781 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3782 LoadInst *PLoad = SplitLoads[Idx];
3783 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
3784 auto *PartPtrTy =
3785 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
3786
3787 StoreInst *PStore = IRB.CreateAlignedStore(
3788 PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3789 APInt(DL.getPointerSizeInBits(), PartOffset),
3790 PartPtrTy, StoreBasePtr->getName() + "."),
3791 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
3792 (void)PStore;
3793 DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
3794 }
3795
3796 // We want to immediately iterate on any allocas impacted by splitting
3797 // this store, and we have to track any promotable alloca (indicated by
3798 // a direct store) as needing to be resplit because it is no longer
3799 // promotable.
3800 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3801 ResplitPromotableAllocas.insert(OtherAI);
3802 Worklist.insert(OtherAI);
3803 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3804 StoreBasePtr->stripInBoundsOffsets())) {
3805 Worklist.insert(OtherAI);
3806 }
3807
3808 // Mark the original store as dead.
3809 DeadInsts.insert(SI);
3810 }
3811
3812 // Save the split loads if there are deferred stores among the users.
3813 if (DeferredStores)
3814 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3815
3816 // Mark the original load as dead and kill the original slice.
3817 DeadInsts.insert(LI);
3818 Offsets.S->kill();
3819 }
3820
3821 // Second, we rewrite all of the split stores. At this point, we know that
3822 // all loads from this alloca have been split already. For stores of such
3823 // loads, we can simply look up the pre-existing split loads. For stores of
3824 // other loads, we split those loads first and then write split stores of
3825 // them.
3826 for (StoreInst *SI : Stores) {
3827 auto *LI = cast<LoadInst>(SI->getValueOperand());
3828 IntegerType *Ty = cast<IntegerType>(LI->getType());
3829 uint64_t StoreSize = Ty->getBitWidth() / 8;
3830 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3831
3832 auto &Offsets = SplitOffsetsMap[SI];
3833 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3834 "Slice size should always match load size exactly!");
3835 uint64_t BaseOffset = Offsets.S->beginOffset();
3836 assert(BaseOffset + StoreSize > BaseOffset &&
3837 "Cannot represent alloca access size using 64-bit integers!");
3838
3839 Value *LoadBasePtr = LI->getPointerOperand();
3840 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3841
3842 DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
3843
3844 // Check whether we have an already split load.
3845 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3846 std::vector<LoadInst *> *SplitLoads = nullptr;
3847 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3848 SplitLoads = &SplitLoadsMapI->second;
3849 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3850 "Too few split loads for the number of splits in the store!");
3851 } else {
3852 DEBUG(dbgs() << " of load: " << *LI << "\n");
3853 }
3854
3855 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3856 int Idx = 0, Size = Offsets.Splits.size();
3857 for (;;) {
3858 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3859 auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
3860
3861 // Either lookup a split load or create one.
3862 LoadInst *PLoad;
3863 if (SplitLoads) {
3864 PLoad = (*SplitLoads)[Idx];
3865 } else {
3866 IRB.SetInsertPoint(BasicBlock::iterator(LI));
3867 PLoad = IRB.CreateAlignedLoad(
3868 getAdjustedPtr(IRB, DL, LoadBasePtr,
3869 APInt(DL.getPointerSizeInBits(), PartOffset),
3870 PartPtrTy, LoadBasePtr->getName() + "."),
3871 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
3872 LI->getName());
3873 }
3874
3875 // And store this partition.
3876 IRB.SetInsertPoint(BasicBlock::iterator(SI));
3877 StoreInst *PStore = IRB.CreateAlignedStore(
3878 PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3879 APInt(DL.getPointerSizeInBits(), PartOffset),
3880 PartPtrTy, StoreBasePtr->getName() + "."),
3881 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
3882
3883 // Now build a new slice for the alloca.
3884 NewSlices.push_back(
3885 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3886 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
3887 /*IsSplittable*/ false));
3888 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3889 << ", " << NewSlices.back().endOffset() << "): " << *PStore
3890 << "\n");
3891 if (!SplitLoads) {
3892 DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
3893 }
3894
3895 // See if we've finished all the splits.
3896 if (Idx >= Size)
3897 break;
3898
3899 // Setup the next partition.
3900 PartOffset = Offsets.Splits[Idx];
3901 ++Idx;
3902 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3903 }
3904
3905 // We want to immediately iterate on any allocas impacted by splitting
3906 // this load, which is only relevant if it isn't a load of this alloca and
3907 // thus we didn't already split the loads above. We also have to keep track
3908 // of any promotable allocas we split loads on as they can no longer be
3909 // promoted.
3910 if (!SplitLoads) {
3911 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3912 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3913 ResplitPromotableAllocas.insert(OtherAI);
3914 Worklist.insert(OtherAI);
3915 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3916 LoadBasePtr->stripInBoundsOffsets())) {
3917 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3918 Worklist.insert(OtherAI);
3919 }
3920 }
3921
3922 // Mark the original store as dead now that we've split it up and kill its
3923 // slice. Note that we leave the original load in place unless this store
3924 // was its ownly use. It may in turn be split up if it is an alloca load
3925 // for some other alloca, but it may be a normal load. This may introduce
3926 // redundant loads, but where those can be merged the rest of the optimizer
3927 // should handle the merging, and this uncovers SSA splits which is more
3928 // important. In practice, the original loads will almost always be fully
3929 // split and removed eventually, and the splits will be merged by any
3930 // trivial CSE, including instcombine.
3931 if (LI->hasOneUse()) {
3932 assert(*LI->user_begin() == SI && "Single use isn't this store!");
3933 DeadInsts.insert(LI);
3934 }
3935 DeadInsts.insert(SI);
3936 Offsets.S->kill();
3937 }
3938
3939 // Remove the killed slices that have ben pre-split.
3940 AS.erase(std::remove_if(AS.begin(), AS.end(), [](const Slice &S) {
3941 return S.isDead();
3942 }), AS.end());
3943
3944 // Insert our new slices. This will sort and merge them into the sorted
3945 // sequence.
3946 AS.insert(NewSlices);
3947
3948 DEBUG(dbgs() << " Pre-split slices:\n");
3949 #ifndef NDEBUG
3950 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3951 DEBUG(AS.print(dbgs(), I, " "));
3952 #endif
3953
3954 // Finally, don't try to promote any allocas that new require re-splitting.
3955 // They have already been added to the worklist above.
3956 PromotableAllocas.erase(
3957 std::remove_if(
3958 PromotableAllocas.begin(), PromotableAllocas.end(),
3959 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3960 PromotableAllocas.end());
3961
3962 return true;
3963 }
3964
3965 /// \brief Rewrite an alloca partition's users.
3966 ///
3967 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3968 /// to rewrite uses of an alloca partition to be conducive for SSA value
3969 /// promotion. If the partition needs a new, more refined alloca, this will
3970 /// build that new alloca, preserving as much type information as possible, and
3971 /// rewrite the uses of the old alloca to point at the new one and have the
3972 /// appropriate new offsets. It also evaluates how successful the rewrite was
3973 /// at enabling promotion and if it was successful queues the alloca to be
3974 /// promoted.
rewritePartition(AllocaInst & AI,AllocaSlices & AS,AllocaSlices::Partition & P)3975 AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
3976 AllocaSlices::Partition &P) {
3977 // Try to compute a friendly type for this partition of the alloca. This
3978 // won't always succeed, in which case we fall back to a legal integer type
3979 // or an i8 array of an appropriate size.
3980 Type *SliceTy = nullptr;
3981 const DataLayout &DL = AI.getModule()->getDataLayout();
3982 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
3983 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
3984 SliceTy = CommonUseTy;
3985 if (!SliceTy)
3986 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
3987 P.beginOffset(), P.size()))
3988 SliceTy = TypePartitionTy;
3989 if ((!SliceTy || (SliceTy->isArrayTy() &&
3990 SliceTy->getArrayElementType()->isIntegerTy())) &&
3991 DL.isLegalInteger(P.size() * 8))
3992 SliceTy = Type::getIntNTy(*C, P.size() * 8);
3993 if (!SliceTy)
3994 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
3995 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
3996
3997 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
3998
3999 VectorType *VecTy =
4000 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
4001 if (VecTy)
4002 SliceTy = VecTy;
4003
4004 // Check for the case where we're going to rewrite to a new alloca of the
4005 // exact same type as the original, and with the same access offsets. In that
4006 // case, re-use the existing alloca, but still run through the rewriter to
4007 // perform phi and select speculation.
4008 AllocaInst *NewAI;
4009 if (SliceTy == AI.getAllocatedType()) {
4010 assert(P.beginOffset() == 0 &&
4011 "Non-zero begin offset but same alloca type");
4012 NewAI = &AI;
4013 // FIXME: We should be able to bail at this point with "nothing changed".
4014 // FIXME: We might want to defer PHI speculation until after here.
4015 // FIXME: return nullptr;
4016 } else {
4017 unsigned Alignment = AI.getAlignment();
4018 if (!Alignment) {
4019 // The minimum alignment which users can rely on when the explicit
4020 // alignment is omitted or zero is that required by the ABI for this
4021 // type.
4022 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
4023 }
4024 Alignment = MinAlign(Alignment, P.beginOffset());
4025 // If we will get at least this much alignment from the type alone, leave
4026 // the alloca's alignment unconstrained.
4027 if (Alignment <= DL.getABITypeAlignment(SliceTy))
4028 Alignment = 0;
4029 NewAI = new AllocaInst(
4030 SliceTy, nullptr, Alignment,
4031 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
4032 ++NumNewAllocas;
4033 }
4034
4035 DEBUG(dbgs() << "Rewriting alloca partition "
4036 << "[" << P.beginOffset() << "," << P.endOffset()
4037 << ") to: " << *NewAI << "\n");
4038
4039 // Track the high watermark on the worklist as it is only relevant for
4040 // promoted allocas. We will reset it to this point if the alloca is not in
4041 // fact scheduled for promotion.
4042 unsigned PPWOldSize = PostPromotionWorklist.size();
4043 unsigned NumUses = 0;
4044 SmallPtrSet<PHINode *, 8> PHIUsers;
4045 SmallPtrSet<SelectInst *, 8> SelectUsers;
4046
4047 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
4048 P.endOffset(), IsIntegerPromotable, VecTy,
4049 PHIUsers, SelectUsers);
4050 bool Promotable = true;
4051 for (Slice *S : P.splitSliceTails()) {
4052 Promotable &= Rewriter.visit(S);
4053 ++NumUses;
4054 }
4055 for (Slice &S : P) {
4056 Promotable &= Rewriter.visit(&S);
4057 ++NumUses;
4058 }
4059
4060 NumAllocaPartitionUses += NumUses;
4061 MaxUsesPerAllocaPartition =
4062 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
4063
4064 // Now that we've processed all the slices in the new partition, check if any
4065 // PHIs or Selects would block promotion.
4066 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
4067 E = PHIUsers.end();
4068 I != E; ++I)
4069 if (!isSafePHIToSpeculate(**I)) {
4070 Promotable = false;
4071 PHIUsers.clear();
4072 SelectUsers.clear();
4073 break;
4074 }
4075 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
4076 E = SelectUsers.end();
4077 I != E; ++I)
4078 if (!isSafeSelectToSpeculate(**I)) {
4079 Promotable = false;
4080 PHIUsers.clear();
4081 SelectUsers.clear();
4082 break;
4083 }
4084
4085 if (Promotable) {
4086 if (PHIUsers.empty() && SelectUsers.empty()) {
4087 // Promote the alloca.
4088 PromotableAllocas.push_back(NewAI);
4089 } else {
4090 // If we have either PHIs or Selects to speculate, add them to those
4091 // worklists and re-queue the new alloca so that we promote in on the
4092 // next iteration.
4093 for (PHINode *PHIUser : PHIUsers)
4094 SpeculatablePHIs.insert(PHIUser);
4095 for (SelectInst *SelectUser : SelectUsers)
4096 SpeculatableSelects.insert(SelectUser);
4097 Worklist.insert(NewAI);
4098 }
4099 } else {
4100 // If we can't promote the alloca, iterate on it to check for new
4101 // refinements exposed by splitting the current alloca. Don't iterate on an
4102 // alloca which didn't actually change and didn't get promoted.
4103 if (NewAI != &AI)
4104 Worklist.insert(NewAI);
4105
4106 // Drop any post-promotion work items if promotion didn't happen.
4107 while (PostPromotionWorklist.size() > PPWOldSize)
4108 PostPromotionWorklist.pop_back();
4109 }
4110
4111 return NewAI;
4112 }
4113
4114 /// \brief Walks the slices of an alloca and form partitions based on them,
4115 /// rewriting each of their uses.
splitAlloca(AllocaInst & AI,AllocaSlices & AS)4116 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4117 if (AS.begin() == AS.end())
4118 return false;
4119
4120 unsigned NumPartitions = 0;
4121 bool Changed = false;
4122 const DataLayout &DL = AI.getModule()->getDataLayout();
4123
4124 // First try to pre-split loads and stores.
4125 Changed |= presplitLoadsAndStores(AI, AS);
4126
4127 // Now that we have identified any pre-splitting opportunities, mark any
4128 // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
4129 // to split these during pre-splitting, we want to force them to be
4130 // rewritten into a partition.
4131 bool IsSorted = true;
4132 for (Slice &S : AS) {
4133 if (!S.isSplittable())
4134 continue;
4135 // FIXME: We currently leave whole-alloca splittable loads and stores. This
4136 // used to be the only splittable loads and stores and we need to be
4137 // confident that the above handling of splittable loads and stores is
4138 // completely sufficient before we forcibly disable the remaining handling.
4139 if (S.beginOffset() == 0 &&
4140 S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
4141 continue;
4142 if (isa<LoadInst>(S.getUse()->getUser()) ||
4143 isa<StoreInst>(S.getUse()->getUser())) {
4144 S.makeUnsplittable();
4145 IsSorted = false;
4146 }
4147 }
4148 if (!IsSorted)
4149 std::sort(AS.begin(), AS.end());
4150
4151 /// \brief Describes the allocas introduced by rewritePartition
4152 /// in order to migrate the debug info.
4153 struct Piece {
4154 AllocaInst *Alloca;
4155 uint64_t Offset;
4156 uint64_t Size;
4157 Piece(AllocaInst *AI, uint64_t O, uint64_t S)
4158 : Alloca(AI), Offset(O), Size(S) {}
4159 };
4160 SmallVector<Piece, 4> Pieces;
4161
4162 // Rewrite each partition.
4163 for (auto &P : AS.partitions()) {
4164 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4165 Changed = true;
4166 if (NewAI != &AI) {
4167 uint64_t SizeOfByte = 8;
4168 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
4169 // Don't include any padding.
4170 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
4171 Pieces.push_back(Piece(NewAI, P.beginOffset() * SizeOfByte, Size));
4172 }
4173 }
4174 ++NumPartitions;
4175 }
4176
4177 NumAllocaPartitions += NumPartitions;
4178 MaxPartitionsPerAlloca =
4179 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
4180
4181 // Migrate debug information from the old alloca to the new alloca(s)
4182 // and the individial partitions.
4183 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(&AI)) {
4184 DIVariable Var(DbgDecl->getVariable());
4185 DIExpression Expr(DbgDecl->getExpression());
4186 DIBuilder DIB(*AI.getParent()->getParent()->getParent(),
4187 /*AllowUnresolved*/ false);
4188 bool IsSplit = Pieces.size() > 1;
4189 for (auto Piece : Pieces) {
4190 // Create a piece expression describing the new partition or reuse AI's
4191 // expression if there is only one partition.
4192 DIExpression PieceExpr = Expr;
4193 if (IsSplit || Expr->isBitPiece()) {
4194 // If this alloca is already a scalar replacement of a larger aggregate,
4195 // Piece.Offset describes the offset inside the scalar.
4196 uint64_t Offset = Expr->isBitPiece() ? Expr->getBitPieceOffset() : 0;
4197 uint64_t Start = Offset + Piece.Offset;
4198 uint64_t Size = Piece.Size;
4199 if (Expr->isBitPiece()) {
4200 uint64_t AbsEnd = Expr->getBitPieceOffset() + Expr->getBitPieceSize();
4201 if (Start >= AbsEnd)
4202 // No need to describe a SROAed padding.
4203 continue;
4204 Size = std::min(Size, AbsEnd - Start);
4205 }
4206 PieceExpr = DIB.createBitPieceExpression(Start, Size);
4207 }
4208
4209 // Remove any existing dbg.declare intrinsic describing the same alloca.
4210 if (DbgDeclareInst *OldDDI = FindAllocaDbgDeclare(Piece.Alloca))
4211 OldDDI->eraseFromParent();
4212
4213 DIB.insertDeclare(Piece.Alloca, Var, PieceExpr, DbgDecl->getDebugLoc(),
4214 &AI);
4215 }
4216 }
4217 return Changed;
4218 }
4219
4220 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
clobberUse(Use & U)4221 void SROA::clobberUse(Use &U) {
4222 Value *OldV = U;
4223 // Replace the use with an undef value.
4224 U = UndefValue::get(OldV->getType());
4225
4226 // Check for this making an instruction dead. We have to garbage collect
4227 // all the dead instructions to ensure the uses of any alloca end up being
4228 // minimal.
4229 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4230 if (isInstructionTriviallyDead(OldI)) {
4231 DeadInsts.insert(OldI);
4232 }
4233 }
4234
4235 /// \brief Analyze an alloca for SROA.
4236 ///
4237 /// This analyzes the alloca to ensure we can reason about it, builds
4238 /// the slices of the alloca, and then hands it off to be split and
4239 /// rewritten as needed.
runOnAlloca(AllocaInst & AI)4240 bool SROA::runOnAlloca(AllocaInst &AI) {
4241 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4242 ++NumAllocasAnalyzed;
4243
4244 // Special case dead allocas, as they're trivial.
4245 if (AI.use_empty()) {
4246 AI.eraseFromParent();
4247 return true;
4248 }
4249 const DataLayout &DL = AI.getModule()->getDataLayout();
4250
4251 // Skip alloca forms that this analysis can't handle.
4252 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
4253 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
4254 return false;
4255
4256 bool Changed = false;
4257
4258 // First, split any FCA loads and stores touching this alloca to promote
4259 // better splitting and promotion opportunities.
4260 AggLoadStoreRewriter AggRewriter(DL);
4261 Changed |= AggRewriter.rewrite(AI);
4262
4263 // Build the slices using a recursive instruction-visiting builder.
4264 AllocaSlices AS(DL, AI);
4265 DEBUG(AS.print(dbgs()));
4266 if (AS.isEscaped())
4267 return Changed;
4268
4269 // Delete all the dead users of this alloca before splitting and rewriting it.
4270 for (Instruction *DeadUser : AS.getDeadUsers()) {
4271 // Free up everything used by this instruction.
4272 for (Use &DeadOp : DeadUser->operands())
4273 clobberUse(DeadOp);
4274
4275 // Now replace the uses of this instruction.
4276 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
4277
4278 // And mark it for deletion.
4279 DeadInsts.insert(DeadUser);
4280 Changed = true;
4281 }
4282 for (Use *DeadOp : AS.getDeadOperands()) {
4283 clobberUse(*DeadOp);
4284 Changed = true;
4285 }
4286
4287 // No slices to split. Leave the dead alloca for a later pass to clean up.
4288 if (AS.begin() == AS.end())
4289 return Changed;
4290
4291 Changed |= splitAlloca(AI, AS);
4292
4293 DEBUG(dbgs() << " Speculating PHIs\n");
4294 while (!SpeculatablePHIs.empty())
4295 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4296
4297 DEBUG(dbgs() << " Speculating Selects\n");
4298 while (!SpeculatableSelects.empty())
4299 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4300
4301 return Changed;
4302 }
4303
4304 /// \brief Delete the dead instructions accumulated in this run.
4305 ///
4306 /// Recursively deletes the dead instructions we've accumulated. This is done
4307 /// at the very end to maximize locality of the recursive delete and to
4308 /// minimize the problems of invalidated instruction pointers as such pointers
4309 /// are used heavily in the intermediate stages of the algorithm.
4310 ///
4311 /// We also record the alloca instructions deleted here so that they aren't
4312 /// subsequently handed to mem2reg to promote.
deleteDeadInstructions(SmallPtrSetImpl<AllocaInst * > & DeletedAllocas)4313 void SROA::deleteDeadInstructions(
4314 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
4315 while (!DeadInsts.empty()) {
4316 Instruction *I = DeadInsts.pop_back_val();
4317 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4318
4319 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4320
4321 for (Use &Operand : I->operands())
4322 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
4323 // Zero out the operand and see if it becomes trivially dead.
4324 Operand = nullptr;
4325 if (isInstructionTriviallyDead(U))
4326 DeadInsts.insert(U);
4327 }
4328
4329 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4330 DeletedAllocas.insert(AI);
4331 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
4332 DbgDecl->eraseFromParent();
4333 }
4334
4335 ++NumDeleted;
4336 I->eraseFromParent();
4337 }
4338 }
4339
enqueueUsersInWorklist(Instruction & I,SmallVectorImpl<Instruction * > & Worklist,SmallPtrSetImpl<Instruction * > & Visited)4340 static void enqueueUsersInWorklist(Instruction &I,
4341 SmallVectorImpl<Instruction *> &Worklist,
4342 SmallPtrSetImpl<Instruction *> &Visited) {
4343 for (User *U : I.users())
4344 if (Visited.insert(cast<Instruction>(U)).second)
4345 Worklist.push_back(cast<Instruction>(U));
4346 }
4347
4348 /// \brief Promote the allocas, using the best available technique.
4349 ///
4350 /// This attempts to promote whatever allocas have been identified as viable in
4351 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
4352 /// If there is a domtree available, we attempt to promote using the full power
4353 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
4354 /// based on the SSAUpdater utilities. This function returns whether any
4355 /// promotion occurred.
promoteAllocas(Function & F)4356 bool SROA::promoteAllocas(Function &F) {
4357 if (PromotableAllocas.empty())
4358 return false;
4359
4360 NumPromoted += PromotableAllocas.size();
4361
4362 if (DT && !ForceSSAUpdater) {
4363 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
4364 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AC);
4365 PromotableAllocas.clear();
4366 return true;
4367 }
4368
4369 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
4370 SSAUpdater SSA;
4371 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
4372 SmallVector<Instruction *, 64> Insts;
4373
4374 // We need a worklist to walk the uses of each alloca.
4375 SmallVector<Instruction *, 8> Worklist;
4376 SmallPtrSet<Instruction *, 8> Visited;
4377 SmallVector<Instruction *, 32> DeadInsts;
4378
4379 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
4380 AllocaInst *AI = PromotableAllocas[Idx];
4381 Insts.clear();
4382 Worklist.clear();
4383 Visited.clear();
4384
4385 enqueueUsersInWorklist(*AI, Worklist, Visited);
4386
4387 while (!Worklist.empty()) {
4388 Instruction *I = Worklist.pop_back_val();
4389
4390 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
4391 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
4392 // leading to them) here. Eventually it should use them to optimize the
4393 // scalar values produced.
4394 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
4395 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
4396 II->getIntrinsicID() == Intrinsic::lifetime_end);
4397 II->eraseFromParent();
4398 continue;
4399 }
4400
4401 // Push the loads and stores we find onto the list. SROA will already
4402 // have validated that all loads and stores are viable candidates for
4403 // promotion.
4404 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4405 assert(LI->getType() == AI->getAllocatedType());
4406 Insts.push_back(LI);
4407 continue;
4408 }
4409 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
4410 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
4411 Insts.push_back(SI);
4412 continue;
4413 }
4414
4415 // For everything else, we know that only no-op bitcasts and GEPs will
4416 // make it this far, just recurse through them and recall them for later
4417 // removal.
4418 DeadInsts.push_back(I);
4419 enqueueUsersInWorklist(*I, Worklist, Visited);
4420 }
4421 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
4422 while (!DeadInsts.empty())
4423 DeadInsts.pop_back_val()->eraseFromParent();
4424 AI->eraseFromParent();
4425 }
4426
4427 PromotableAllocas.clear();
4428 return true;
4429 }
4430
runOnFunction(Function & F)4431 bool SROA::runOnFunction(Function &F) {
4432 if (skipOptnoneFunction(F))
4433 return false;
4434
4435 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4436 C = &F.getContext();
4437 DominatorTreeWrapperPass *DTWP =
4438 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
4439 DT = DTWP ? &DTWP->getDomTree() : nullptr;
4440 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4441
4442 BasicBlock &EntryBB = F.getEntryBlock();
4443 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
4444 I != E; ++I) {
4445 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4446 Worklist.insert(AI);
4447 }
4448
4449 bool Changed = false;
4450 // A set of deleted alloca instruction pointers which should be removed from
4451 // the list of promotable allocas.
4452 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4453
4454 do {
4455 while (!Worklist.empty()) {
4456 Changed |= runOnAlloca(*Worklist.pop_back_val());
4457 deleteDeadInstructions(DeletedAllocas);
4458
4459 // Remove the deleted allocas from various lists so that we don't try to
4460 // continue processing them.
4461 if (!DeletedAllocas.empty()) {
4462 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
4463 Worklist.remove_if(IsInSet);
4464 PostPromotionWorklist.remove_if(IsInSet);
4465 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
4466 PromotableAllocas.end(),
4467 IsInSet),
4468 PromotableAllocas.end());
4469 DeletedAllocas.clear();
4470 }
4471 }
4472
4473 Changed |= promoteAllocas(F);
4474
4475 Worklist = PostPromotionWorklist;
4476 PostPromotionWorklist.clear();
4477 } while (!Worklist.empty());
4478
4479 return Changed;
4480 }
4481
getAnalysisUsage(AnalysisUsage & AU) const4482 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
4483 AU.addRequired<AssumptionCacheTracker>();
4484 if (RequiresDomTree)
4485 AU.addRequired<DominatorTreeWrapperPass>();
4486 AU.setPreservesCFG();
4487 }
4488