1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This transformation implements the well known scalar replacement of
10 /// aggregates transformation. It tries to identify promotable elements of an
11 /// aggregate alloca, and promote them to registers. It will also try to
12 /// convert uses of an element (or set of elements) of an alloca into a vector
13 /// or bitfield-style integer scalar if appropriate.
14 ///
15 /// It works to do this with minimal slicing of the alloca so that regions
16 /// which are merely transferred in and out of external memory remain unchanged
17 /// and are not decomposed to scalar code.
18 ///
19 /// Because this also performs alloca promotion, it can be thought of as also
20 /// serving the purpose of SSA formation. The algorithm iterates on the
21 /// function until all opportunities for promotion have been realized.
22 ///
23 //===----------------------------------------------------------------------===//
24
25 #include "llvm/Transforms/Scalar/SROA.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/PointerIntPair.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/ADT/SmallBitVector.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/ADT/iterator.h"
39 #include "llvm/ADT/iterator_range.h"
40 #include "llvm/Analysis/AssumptionCache.h"
41 #include "llvm/Analysis/DomTreeUpdater.h"
42 #include "llvm/Analysis/GlobalsModRef.h"
43 #include "llvm/Analysis/Loads.h"
44 #include "llvm/Analysis/PtrUseVisitor.h"
45 #include "llvm/Config/llvm-config.h"
46 #include "llvm/IR/BasicBlock.h"
47 #include "llvm/IR/Constant.h"
48 #include "llvm/IR/ConstantFolder.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DIBuilder.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/DebugInfo.h"
53 #include "llvm/IR/DebugInfoMetadata.h"
54 #include "llvm/IR/DerivedTypes.h"
55 #include "llvm/IR/Dominators.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/GetElementPtrTypeIterator.h"
58 #include "llvm/IR/GlobalAlias.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstVisitor.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/LLVMContext.h"
65 #include "llvm/IR/Metadata.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/Operator.h"
68 #include "llvm/IR/PassManager.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/User.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/InitializePasses.h"
74 #include "llvm/Pass.h"
75 #include "llvm/Support/Casting.h"
76 #include "llvm/Support/CommandLine.h"
77 #include "llvm/Support/Compiler.h"
78 #include "llvm/Support/Debug.h"
79 #include "llvm/Support/ErrorHandling.h"
80 #include "llvm/Support/raw_ostream.h"
81 #include "llvm/Transforms/Scalar.h"
82 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
83 #include "llvm/Transforms/Utils/Local.h"
84 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
85 #include <algorithm>
86 #include <cassert>
87 #include <cstddef>
88 #include <cstdint>
89 #include <cstring>
90 #include <iterator>
91 #include <string>
92 #include <tuple>
93 #include <utility>
94 #include <vector>
95
96 using namespace llvm;
97 using namespace llvm::sroa;
98
99 #define DEBUG_TYPE "sroa"
100
101 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
102 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
103 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
104 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
105 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
106 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
107 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
108 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
109 STATISTIC(NumLoadsPredicated,
110 "Number of loads rewritten into predicated loads to allow promotion");
111 STATISTIC(
112 NumStoresPredicated,
113 "Number of stores rewritten into predicated loads to allow promotion");
114 STATISTIC(NumDeleted, "Number of instructions deleted");
115 STATISTIC(NumVectorized, "Number of vectorized aggregates");
116
117 /// Hidden option to experiment with completely strict handling of inbounds
118 /// GEPs.
119 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
120 cl::Hidden);
121 namespace {
122 /// Find linked dbg.assign and generate a new one with the correct
123 /// FragmentInfo. Link Inst to the new dbg.assign. If Value is nullptr the
124 /// value component is copied from the old dbg.assign to the new.
125 /// \param OldAlloca Alloca for the variable before splitting.
126 /// \param RelativeOffsetInBits Offset into \p OldAlloca relative to the
127 /// offset prior to splitting (change in offset).
128 /// \param SliceSizeInBits New number of bits being written to.
129 /// \param OldInst Instruction that is being split.
130 /// \param Inst New instruction performing this part of the
131 /// split store.
132 /// \param Dest Store destination.
133 /// \param Value Stored value.
134 /// \param DL Datalayout.
migrateDebugInfo(AllocaInst * OldAlloca,uint64_t RelativeOffsetInBits,uint64_t SliceSizeInBits,Instruction * OldInst,Instruction * Inst,Value * Dest,Value * Value,const DataLayout & DL)135 static void migrateDebugInfo(AllocaInst *OldAlloca,
136 uint64_t RelativeOffsetInBits,
137 uint64_t SliceSizeInBits, Instruction *OldInst,
138 Instruction *Inst, Value *Dest, Value *Value,
139 const DataLayout &DL) {
140 auto MarkerRange = at::getAssignmentMarkers(OldInst);
141 // Nothing to do if OldInst has no linked dbg.assign intrinsics.
142 if (MarkerRange.empty())
143 return;
144
145 LLVM_DEBUG(dbgs() << " migrateDebugInfo\n");
146 LLVM_DEBUG(dbgs() << " OldAlloca: " << *OldAlloca << "\n");
147 LLVM_DEBUG(dbgs() << " RelativeOffset: " << RelativeOffsetInBits << "\n");
148 LLVM_DEBUG(dbgs() << " SliceSizeInBits: " << SliceSizeInBits << "\n");
149 LLVM_DEBUG(dbgs() << " OldInst: " << *OldInst << "\n");
150 LLVM_DEBUG(dbgs() << " Inst: " << *Inst << "\n");
151 LLVM_DEBUG(dbgs() << " Dest: " << *Dest << "\n");
152 if (Value)
153 LLVM_DEBUG(dbgs() << " Value: " << *Value << "\n");
154
155 // The new inst needs a DIAssignID unique metadata tag (if OldInst has
156 // one). It shouldn't already have one: assert this assumption.
157 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID));
158 DIAssignID *NewID = nullptr;
159 auto &Ctx = Inst->getContext();
160 DIBuilder DIB(*OldInst->getModule(), /*AllowUnresolved*/ false);
161 uint64_t AllocaSizeInBits = *OldAlloca->getAllocationSizeInBits(DL);
162 assert(OldAlloca->isStaticAlloca());
163
164 for (DbgAssignIntrinsic *DbgAssign : MarkerRange) {
165 LLVM_DEBUG(dbgs() << " existing dbg.assign is: " << *DbgAssign
166 << "\n");
167 auto *Expr = DbgAssign->getExpression();
168
169 // Check if the dbg.assign already describes a fragment.
170 auto GetCurrentFragSize = [AllocaSizeInBits, DbgAssign,
171 Expr]() -> uint64_t {
172 if (auto FI = Expr->getFragmentInfo())
173 return FI->SizeInBits;
174 if (auto VarSize = DbgAssign->getVariable()->getSizeInBits())
175 return *VarSize;
176 // The variable type has an unspecified size. This can happen in the
177 // case of DW_TAG_unspecified_type types, e.g. std::nullptr_t. Because
178 // there is no fragment and we do not know the size of the variable type,
179 // we'll guess by looking at the alloca.
180 return AllocaSizeInBits;
181 };
182 uint64_t CurrentFragSize = GetCurrentFragSize();
183 bool MakeNewFragment = CurrentFragSize != SliceSizeInBits;
184 assert(MakeNewFragment || RelativeOffsetInBits == 0);
185
186 assert(SliceSizeInBits <= AllocaSizeInBits);
187 if (MakeNewFragment) {
188 assert(RelativeOffsetInBits + SliceSizeInBits <= CurrentFragSize);
189 auto E = DIExpression::createFragmentExpression(
190 Expr, RelativeOffsetInBits, SliceSizeInBits);
191 assert(E && "Failed to create fragment expr!");
192 Expr = *E;
193 }
194
195 // If we haven't created a DIAssignID ID do that now and attach it to Inst.
196 if (!NewID) {
197 NewID = DIAssignID::getDistinct(Ctx);
198 Inst->setMetadata(LLVMContext::MD_DIAssignID, NewID);
199 }
200
201 Value = Value ? Value : DbgAssign->getValue();
202 auto *NewAssign = DIB.insertDbgAssign(
203 Inst, Value, DbgAssign->getVariable(), Expr, Dest,
204 DIExpression::get(Ctx, std::nullopt), DbgAssign->getDebugLoc());
205
206 // We could use more precision here at the cost of some additional (code)
207 // complexity - if the original dbg.assign was adjacent to its store, we
208 // could position this new dbg.assign adjacent to its store rather than the
209 // old dbg.assgn. That would result in interleaved dbg.assigns rather than
210 // what we get now:
211 // split store !1
212 // split store !2
213 // dbg.assign !1
214 // dbg.assign !2
215 // This (current behaviour) results results in debug assignments being
216 // noted as slightly offset (in code) from the store. In practice this
217 // should have little effect on the debugging experience due to the fact
218 // that all the split stores should get the same line number.
219 NewAssign->moveBefore(DbgAssign);
220
221 NewAssign->setDebugLoc(DbgAssign->getDebugLoc());
222 LLVM_DEBUG(dbgs() << "Created new assign intrinsic: " << *NewAssign
223 << "\n");
224 }
225 }
226
227 /// A custom IRBuilder inserter which prefixes all names, but only in
228 /// Assert builds.
229 class IRBuilderPrefixedInserter final : public IRBuilderDefaultInserter {
230 std::string Prefix;
231
getNameWithPrefix(const Twine & Name) const232 Twine getNameWithPrefix(const Twine &Name) const {
233 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
234 }
235
236 public:
SetNamePrefix(const Twine & P)237 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
238
InsertHelper(Instruction * I,const Twine & Name,BasicBlock * BB,BasicBlock::iterator InsertPt) const239 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
240 BasicBlock::iterator InsertPt) const override {
241 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
242 InsertPt);
243 }
244 };
245
246 /// Provide a type for IRBuilder that drops names in release builds.
247 using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
248
249 /// A used slice of an alloca.
250 ///
251 /// This structure represents a slice of an alloca used by some instruction. It
252 /// stores both the begin and end offsets of this use, a pointer to the use
253 /// itself, and a flag indicating whether we can classify the use as splittable
254 /// or not when forming partitions of the alloca.
255 class Slice {
256 /// The beginning offset of the range.
257 uint64_t BeginOffset = 0;
258
259 /// The ending offset, not included in the range.
260 uint64_t EndOffset = 0;
261
262 /// Storage for both the use of this slice and whether it can be
263 /// split.
264 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
265
266 public:
267 Slice() = default;
268
Slice(uint64_t BeginOffset,uint64_t EndOffset,Use * U,bool IsSplittable)269 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
270 : BeginOffset(BeginOffset), EndOffset(EndOffset),
271 UseAndIsSplittable(U, IsSplittable) {}
272
beginOffset() const273 uint64_t beginOffset() const { return BeginOffset; }
endOffset() const274 uint64_t endOffset() const { return EndOffset; }
275
isSplittable() const276 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
makeUnsplittable()277 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
278
getUse() const279 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
280
isDead() const281 bool isDead() const { return getUse() == nullptr; }
kill()282 void kill() { UseAndIsSplittable.setPointer(nullptr); }
283
284 /// Support for ordering ranges.
285 ///
286 /// This provides an ordering over ranges such that start offsets are
287 /// always increasing, and within equal start offsets, the end offsets are
288 /// decreasing. Thus the spanning range comes first in a cluster with the
289 /// same start position.
operator <(const Slice & RHS) const290 bool operator<(const Slice &RHS) const {
291 if (beginOffset() < RHS.beginOffset())
292 return true;
293 if (beginOffset() > RHS.beginOffset())
294 return false;
295 if (isSplittable() != RHS.isSplittable())
296 return !isSplittable();
297 if (endOffset() > RHS.endOffset())
298 return true;
299 return false;
300 }
301
302 /// Support comparison with a single offset to allow binary searches.
operator <(const Slice & LHS,uint64_t RHSOffset)303 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
304 uint64_t RHSOffset) {
305 return LHS.beginOffset() < RHSOffset;
306 }
operator <(uint64_t LHSOffset,const Slice & RHS)307 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
308 const Slice &RHS) {
309 return LHSOffset < RHS.beginOffset();
310 }
311
operator ==(const Slice & RHS) const312 bool operator==(const Slice &RHS) const {
313 return isSplittable() == RHS.isSplittable() &&
314 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
315 }
operator !=(const Slice & RHS) const316 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
317 };
318
319 } // end anonymous namespace
320
321 /// Representation of the alloca slices.
322 ///
323 /// This class represents the slices of an alloca which are formed by its
324 /// various uses. If a pointer escapes, we can't fully build a representation
325 /// for the slices used and we reflect that in this structure. The uses are
326 /// stored, sorted by increasing beginning offset and with unsplittable slices
327 /// starting at a particular offset before splittable slices.
328 class llvm::sroa::AllocaSlices {
329 public:
330 /// Construct the slices of a particular alloca.
331 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
332
333 /// Test whether a pointer to the allocation escapes our analysis.
334 ///
335 /// If this is true, the slices are never fully built and should be
336 /// ignored.
isEscaped() const337 bool isEscaped() const { return PointerEscapingInstr; }
338
339 /// Support for iterating over the slices.
340 /// @{
341 using iterator = SmallVectorImpl<Slice>::iterator;
342 using range = iterator_range<iterator>;
343
begin()344 iterator begin() { return Slices.begin(); }
end()345 iterator end() { return Slices.end(); }
346
347 using const_iterator = SmallVectorImpl<Slice>::const_iterator;
348 using const_range = iterator_range<const_iterator>;
349
begin() const350 const_iterator begin() const { return Slices.begin(); }
end() const351 const_iterator end() const { return Slices.end(); }
352 /// @}
353
354 /// Erase a range of slices.
erase(iterator Start,iterator Stop)355 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
356
357 /// Insert new slices for this alloca.
358 ///
359 /// This moves the slices into the alloca's slices collection, and re-sorts
360 /// everything so that the usual ordering properties of the alloca's slices
361 /// hold.
insert(ArrayRef<Slice> NewSlices)362 void insert(ArrayRef<Slice> NewSlices) {
363 int OldSize = Slices.size();
364 Slices.append(NewSlices.begin(), NewSlices.end());
365 auto SliceI = Slices.begin() + OldSize;
366 llvm::sort(SliceI, Slices.end());
367 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
368 }
369
370 // Forward declare the iterator and range accessor for walking the
371 // partitions.
372 class partition_iterator;
373 iterator_range<partition_iterator> partitions();
374
375 /// Access the dead users for this alloca.
getDeadUsers() const376 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
377
378 /// Access Uses that should be dropped if the alloca is promotable.
getDeadUsesIfPromotable() const379 ArrayRef<Use *> getDeadUsesIfPromotable() const {
380 return DeadUseIfPromotable;
381 }
382
383 /// Access the dead operands referring to this alloca.
384 ///
385 /// These are operands which have cannot actually be used to refer to the
386 /// alloca as they are outside its range and the user doesn't correct for
387 /// that. These mostly consist of PHI node inputs and the like which we just
388 /// need to replace with undef.
getDeadOperands() const389 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
390
391 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
392 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
393 void printSlice(raw_ostream &OS, const_iterator I,
394 StringRef Indent = " ") const;
395 void printUse(raw_ostream &OS, const_iterator I,
396 StringRef Indent = " ") const;
397 void print(raw_ostream &OS) const;
398 void dump(const_iterator I) const;
399 void dump() const;
400 #endif
401
402 private:
403 template <typename DerivedT, typename RetT = void> class BuilderBase;
404 class SliceBuilder;
405
406 friend class AllocaSlices::SliceBuilder;
407
408 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
409 /// Handle to alloca instruction to simplify method interfaces.
410 AllocaInst &AI;
411 #endif
412
413 /// The instruction responsible for this alloca not having a known set
414 /// of slices.
415 ///
416 /// When an instruction (potentially) escapes the pointer to the alloca, we
417 /// store a pointer to that here and abort trying to form slices of the
418 /// alloca. This will be null if the alloca slices are analyzed successfully.
419 Instruction *PointerEscapingInstr;
420
421 /// The slices of the alloca.
422 ///
423 /// We store a vector of the slices formed by uses of the alloca here. This
424 /// vector is sorted by increasing begin offset, and then the unsplittable
425 /// slices before the splittable ones. See the Slice inner class for more
426 /// details.
427 SmallVector<Slice, 8> Slices;
428
429 /// Instructions which will become dead if we rewrite the alloca.
430 ///
431 /// Note that these are not separated by slice. This is because we expect an
432 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
433 /// all these instructions can simply be removed and replaced with poison as
434 /// they come from outside of the allocated space.
435 SmallVector<Instruction *, 8> DeadUsers;
436
437 /// Uses which will become dead if can promote the alloca.
438 SmallVector<Use *, 8> DeadUseIfPromotable;
439
440 /// Operands which will become dead if we rewrite the alloca.
441 ///
442 /// These are operands that in their particular use can be replaced with
443 /// poison when we rewrite the alloca. These show up in out-of-bounds inputs
444 /// to PHI nodes and the like. They aren't entirely dead (there might be
445 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
446 /// want to swap this particular input for poison to simplify the use lists of
447 /// the alloca.
448 SmallVector<Use *, 8> DeadOperands;
449 };
450
451 /// A partition of the slices.
452 ///
453 /// An ephemeral representation for a range of slices which can be viewed as
454 /// a partition of the alloca. This range represents a span of the alloca's
455 /// memory which cannot be split, and provides access to all of the slices
456 /// overlapping some part of the partition.
457 ///
458 /// Objects of this type are produced by traversing the alloca's slices, but
459 /// are only ephemeral and not persistent.
460 class llvm::sroa::Partition {
461 private:
462 friend class AllocaSlices;
463 friend class AllocaSlices::partition_iterator;
464
465 using iterator = AllocaSlices::iterator;
466
467 /// The beginning and ending offsets of the alloca for this
468 /// partition.
469 uint64_t BeginOffset = 0, EndOffset = 0;
470
471 /// The start and end iterators of this partition.
472 iterator SI, SJ;
473
474 /// A collection of split slice tails overlapping the partition.
475 SmallVector<Slice *, 4> SplitTails;
476
477 /// Raw constructor builds an empty partition starting and ending at
478 /// the given iterator.
Partition(iterator SI)479 Partition(iterator SI) : SI(SI), SJ(SI) {}
480
481 public:
482 /// The start offset of this partition.
483 ///
484 /// All of the contained slices start at or after this offset.
beginOffset() const485 uint64_t beginOffset() const { return BeginOffset; }
486
487 /// The end offset of this partition.
488 ///
489 /// All of the contained slices end at or before this offset.
endOffset() const490 uint64_t endOffset() const { return EndOffset; }
491
492 /// The size of the partition.
493 ///
494 /// Note that this can never be zero.
size() const495 uint64_t size() const {
496 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
497 return EndOffset - BeginOffset;
498 }
499
500 /// Test whether this partition contains no slices, and merely spans
501 /// a region occupied by split slices.
empty() const502 bool empty() const { return SI == SJ; }
503
504 /// \name Iterate slices that start within the partition.
505 /// These may be splittable or unsplittable. They have a begin offset >= the
506 /// partition begin offset.
507 /// @{
508 // FIXME: We should probably define a "concat_iterator" helper and use that
509 // to stitch together pointee_iterators over the split tails and the
510 // contiguous iterators of the partition. That would give a much nicer
511 // interface here. We could then additionally expose filtered iterators for
512 // split, unsplit, and unsplittable splices based on the usage patterns.
begin() const513 iterator begin() const { return SI; }
end() const514 iterator end() const { return SJ; }
515 /// @}
516
517 /// Get the sequence of split slice tails.
518 ///
519 /// These tails are of slices which start before this partition but are
520 /// split and overlap into the partition. We accumulate these while forming
521 /// partitions.
splitSliceTails() const522 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
523 };
524
525 /// An iterator over partitions of the alloca's slices.
526 ///
527 /// This iterator implements the core algorithm for partitioning the alloca's
528 /// slices. It is a forward iterator as we don't support backtracking for
529 /// efficiency reasons, and re-use a single storage area to maintain the
530 /// current set of split slices.
531 ///
532 /// It is templated on the slice iterator type to use so that it can operate
533 /// with either const or non-const slice iterators.
534 class AllocaSlices::partition_iterator
535 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
536 Partition> {
537 friend class AllocaSlices;
538
539 /// Most of the state for walking the partitions is held in a class
540 /// with a nice interface for examining them.
541 Partition P;
542
543 /// We need to keep the end of the slices to know when to stop.
544 AllocaSlices::iterator SE;
545
546 /// We also need to keep track of the maximum split end offset seen.
547 /// FIXME: Do we really?
548 uint64_t MaxSplitSliceEndOffset = 0;
549
550 /// Sets the partition to be empty at given iterator, and sets the
551 /// end iterator.
partition_iterator(AllocaSlices::iterator SI,AllocaSlices::iterator SE)552 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
553 : P(SI), SE(SE) {
554 // If not already at the end, advance our state to form the initial
555 // partition.
556 if (SI != SE)
557 advance();
558 }
559
560 /// Advance the iterator to the next partition.
561 ///
562 /// Requires that the iterator not be at the end of the slices.
advance()563 void advance() {
564 assert((P.SI != SE || !P.SplitTails.empty()) &&
565 "Cannot advance past the end of the slices!");
566
567 // Clear out any split uses which have ended.
568 if (!P.SplitTails.empty()) {
569 if (P.EndOffset >= MaxSplitSliceEndOffset) {
570 // If we've finished all splits, this is easy.
571 P.SplitTails.clear();
572 MaxSplitSliceEndOffset = 0;
573 } else {
574 // Remove the uses which have ended in the prior partition. This
575 // cannot change the max split slice end because we just checked that
576 // the prior partition ended prior to that max.
577 llvm::erase_if(P.SplitTails,
578 [&](Slice *S) { return S->endOffset() <= P.EndOffset; });
579 assert(llvm::any_of(P.SplitTails,
580 [&](Slice *S) {
581 return S->endOffset() == MaxSplitSliceEndOffset;
582 }) &&
583 "Could not find the current max split slice offset!");
584 assert(llvm::all_of(P.SplitTails,
585 [&](Slice *S) {
586 return S->endOffset() <= MaxSplitSliceEndOffset;
587 }) &&
588 "Max split slice end offset is not actually the max!");
589 }
590 }
591
592 // If P.SI is already at the end, then we've cleared the split tail and
593 // now have an end iterator.
594 if (P.SI == SE) {
595 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
596 return;
597 }
598
599 // If we had a non-empty partition previously, set up the state for
600 // subsequent partitions.
601 if (P.SI != P.SJ) {
602 // Accumulate all the splittable slices which started in the old
603 // partition into the split list.
604 for (Slice &S : P)
605 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
606 P.SplitTails.push_back(&S);
607 MaxSplitSliceEndOffset =
608 std::max(S.endOffset(), MaxSplitSliceEndOffset);
609 }
610
611 // Start from the end of the previous partition.
612 P.SI = P.SJ;
613
614 // If P.SI is now at the end, we at most have a tail of split slices.
615 if (P.SI == SE) {
616 P.BeginOffset = P.EndOffset;
617 P.EndOffset = MaxSplitSliceEndOffset;
618 return;
619 }
620
621 // If the we have split slices and the next slice is after a gap and is
622 // not splittable immediately form an empty partition for the split
623 // slices up until the next slice begins.
624 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
625 !P.SI->isSplittable()) {
626 P.BeginOffset = P.EndOffset;
627 P.EndOffset = P.SI->beginOffset();
628 return;
629 }
630 }
631
632 // OK, we need to consume new slices. Set the end offset based on the
633 // current slice, and step SJ past it. The beginning offset of the
634 // partition is the beginning offset of the next slice unless we have
635 // pre-existing split slices that are continuing, in which case we begin
636 // at the prior end offset.
637 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
638 P.EndOffset = P.SI->endOffset();
639 ++P.SJ;
640
641 // There are two strategies to form a partition based on whether the
642 // partition starts with an unsplittable slice or a splittable slice.
643 if (!P.SI->isSplittable()) {
644 // When we're forming an unsplittable region, it must always start at
645 // the first slice and will extend through its end.
646 assert(P.BeginOffset == P.SI->beginOffset());
647
648 // Form a partition including all of the overlapping slices with this
649 // unsplittable slice.
650 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
651 if (!P.SJ->isSplittable())
652 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
653 ++P.SJ;
654 }
655
656 // We have a partition across a set of overlapping unsplittable
657 // partitions.
658 return;
659 }
660
661 // If we're starting with a splittable slice, then we need to form
662 // a synthetic partition spanning it and any other overlapping splittable
663 // splices.
664 assert(P.SI->isSplittable() && "Forming a splittable partition!");
665
666 // Collect all of the overlapping splittable slices.
667 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
668 P.SJ->isSplittable()) {
669 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
670 ++P.SJ;
671 }
672
673 // Back upiP.EndOffset if we ended the span early when encountering an
674 // unsplittable slice. This synthesizes the early end offset of
675 // a partition spanning only splittable slices.
676 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
677 assert(!P.SJ->isSplittable());
678 P.EndOffset = P.SJ->beginOffset();
679 }
680 }
681
682 public:
operator ==(const partition_iterator & RHS) const683 bool operator==(const partition_iterator &RHS) const {
684 assert(SE == RHS.SE &&
685 "End iterators don't match between compared partition iterators!");
686
687 // The observed positions of partitions is marked by the P.SI iterator and
688 // the emptiness of the split slices. The latter is only relevant when
689 // P.SI == SE, as the end iterator will additionally have an empty split
690 // slices list, but the prior may have the same P.SI and a tail of split
691 // slices.
692 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
693 assert(P.SJ == RHS.P.SJ &&
694 "Same set of slices formed two different sized partitions!");
695 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
696 "Same slice position with differently sized non-empty split "
697 "slice tails!");
698 return true;
699 }
700 return false;
701 }
702
operator ++()703 partition_iterator &operator++() {
704 advance();
705 return *this;
706 }
707
operator *()708 Partition &operator*() { return P; }
709 };
710
711 /// A forward range over the partitions of the alloca's slices.
712 ///
713 /// This accesses an iterator range over the partitions of the alloca's
714 /// slices. It computes these partitions on the fly based on the overlapping
715 /// offsets of the slices and the ability to split them. It will visit "empty"
716 /// partitions to cover regions of the alloca only accessed via split
717 /// slices.
partitions()718 iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
719 return make_range(partition_iterator(begin(), end()),
720 partition_iterator(end(), end()));
721 }
722
foldSelectInst(SelectInst & SI)723 static Value *foldSelectInst(SelectInst &SI) {
724 // If the condition being selected on is a constant or the same value is
725 // being selected between, fold the select. Yes this does (rarely) happen
726 // early on.
727 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
728 return SI.getOperand(1 + CI->isZero());
729 if (SI.getOperand(1) == SI.getOperand(2))
730 return SI.getOperand(1);
731
732 return nullptr;
733 }
734
735 /// A helper that folds a PHI node or a select.
foldPHINodeOrSelectInst(Instruction & I)736 static Value *foldPHINodeOrSelectInst(Instruction &I) {
737 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
738 // If PN merges together the same value, return that value.
739 return PN->hasConstantValue();
740 }
741 return foldSelectInst(cast<SelectInst>(I));
742 }
743
744 /// Builder for the alloca slices.
745 ///
746 /// This class builds a set of alloca slices by recursively visiting the uses
747 /// of an alloca and making a slice for each load and store at each offset.
748 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
749 friend class PtrUseVisitor<SliceBuilder>;
750 friend class InstVisitor<SliceBuilder>;
751
752 using Base = PtrUseVisitor<SliceBuilder>;
753
754 const uint64_t AllocSize;
755 AllocaSlices &AS;
756
757 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
758 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
759
760 /// Set to de-duplicate dead instructions found in the use walk.
761 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
762
763 public:
SliceBuilder(const DataLayout & DL,AllocaInst & AI,AllocaSlices & AS)764 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
765 : PtrUseVisitor<SliceBuilder>(DL),
766 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType()).getFixedValue()),
767 AS(AS) {}
768
769 private:
markAsDead(Instruction & I)770 void markAsDead(Instruction &I) {
771 if (VisitedDeadInsts.insert(&I).second)
772 AS.DeadUsers.push_back(&I);
773 }
774
insertUse(Instruction & I,const APInt & Offset,uint64_t Size,bool IsSplittable=false)775 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
776 bool IsSplittable = false) {
777 // Completely skip uses which have a zero size or start either before or
778 // past the end of the allocation.
779 if (Size == 0 || Offset.uge(AllocSize)) {
780 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"
781 << Offset
782 << " which has zero size or starts outside of the "
783 << AllocSize << " byte alloca:\n"
784 << " alloca: " << AS.AI << "\n"
785 << " use: " << I << "\n");
786 return markAsDead(I);
787 }
788
789 uint64_t BeginOffset = Offset.getZExtValue();
790 uint64_t EndOffset = BeginOffset + Size;
791
792 // Clamp the end offset to the end of the allocation. Note that this is
793 // formulated to handle even the case where "BeginOffset + Size" overflows.
794 // This may appear superficially to be something we could ignore entirely,
795 // but that is not so! There may be widened loads or PHI-node uses where
796 // some instructions are dead but not others. We can't completely ignore
797 // them, and so have to record at least the information here.
798 assert(AllocSize >= BeginOffset); // Established above.
799 if (Size > AllocSize - BeginOffset) {
800 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"
801 << Offset << " to remain within the " << AllocSize
802 << " byte alloca:\n"
803 << " alloca: " << AS.AI << "\n"
804 << " use: " << I << "\n");
805 EndOffset = AllocSize;
806 }
807
808 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
809 }
810
visitBitCastInst(BitCastInst & BC)811 void visitBitCastInst(BitCastInst &BC) {
812 if (BC.use_empty())
813 return markAsDead(BC);
814
815 return Base::visitBitCastInst(BC);
816 }
817
visitAddrSpaceCastInst(AddrSpaceCastInst & ASC)818 void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
819 if (ASC.use_empty())
820 return markAsDead(ASC);
821
822 return Base::visitAddrSpaceCastInst(ASC);
823 }
824
visitGetElementPtrInst(GetElementPtrInst & GEPI)825 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
826 if (GEPI.use_empty())
827 return markAsDead(GEPI);
828
829 if (SROAStrictInbounds && GEPI.isInBounds()) {
830 // FIXME: This is a manually un-factored variant of the basic code inside
831 // of GEPs with checking of the inbounds invariant specified in the
832 // langref in a very strict sense. If we ever want to enable
833 // SROAStrictInbounds, this code should be factored cleanly into
834 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
835 // by writing out the code here where we have the underlying allocation
836 // size readily available.
837 APInt GEPOffset = Offset;
838 const DataLayout &DL = GEPI.getModule()->getDataLayout();
839 for (gep_type_iterator GTI = gep_type_begin(GEPI),
840 GTE = gep_type_end(GEPI);
841 GTI != GTE; ++GTI) {
842 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
843 if (!OpC)
844 break;
845
846 // Handle a struct index, which adds its field offset to the pointer.
847 if (StructType *STy = GTI.getStructTypeOrNull()) {
848 unsigned ElementIdx = OpC->getZExtValue();
849 const StructLayout *SL = DL.getStructLayout(STy);
850 GEPOffset +=
851 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
852 } else {
853 // For array or vector indices, scale the index by the size of the
854 // type.
855 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
856 GEPOffset +=
857 Index *
858 APInt(Offset.getBitWidth(),
859 DL.getTypeAllocSize(GTI.getIndexedType()).getFixedValue());
860 }
861
862 // If this index has computed an intermediate pointer which is not
863 // inbounds, then the result of the GEP is a poison value and we can
864 // delete it and all uses.
865 if (GEPOffset.ugt(AllocSize))
866 return markAsDead(GEPI);
867 }
868 }
869
870 return Base::visitGetElementPtrInst(GEPI);
871 }
872
handleLoadOrStore(Type * Ty,Instruction & I,const APInt & Offset,uint64_t Size,bool IsVolatile)873 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
874 uint64_t Size, bool IsVolatile) {
875 // We allow splitting of non-volatile loads and stores where the type is an
876 // integer type. These may be used to implement 'memcpy' or other "transfer
877 // of bits" patterns.
878 bool IsSplittable =
879 Ty->isIntegerTy() && !IsVolatile && DL.typeSizeEqualsStoreSize(Ty);
880
881 insertUse(I, Offset, Size, IsSplittable);
882 }
883
visitLoadInst(LoadInst & LI)884 void visitLoadInst(LoadInst &LI) {
885 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
886 "All simple FCA loads should have been pre-split");
887
888 if (!IsOffsetKnown)
889 return PI.setAborted(&LI);
890
891 if (isa<ScalableVectorType>(LI.getType()))
892 return PI.setAborted(&LI);
893
894 uint64_t Size = DL.getTypeStoreSize(LI.getType()).getFixedValue();
895 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
896 }
897
visitStoreInst(StoreInst & SI)898 void visitStoreInst(StoreInst &SI) {
899 Value *ValOp = SI.getValueOperand();
900 if (ValOp == *U)
901 return PI.setEscapedAndAborted(&SI);
902 if (!IsOffsetKnown)
903 return PI.setAborted(&SI);
904
905 if (isa<ScalableVectorType>(ValOp->getType()))
906 return PI.setAborted(&SI);
907
908 uint64_t Size = DL.getTypeStoreSize(ValOp->getType()).getFixedValue();
909
910 // If this memory access can be shown to *statically* extend outside the
911 // bounds of the allocation, it's behavior is undefined, so simply
912 // ignore it. Note that this is more strict than the generic clamping
913 // behavior of insertUse. We also try to handle cases which might run the
914 // risk of overflow.
915 // FIXME: We should instead consider the pointer to have escaped if this
916 // function is being instrumented for addressing bugs or race conditions.
917 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
918 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"
919 << Offset << " which extends past the end of the "
920 << AllocSize << " byte alloca:\n"
921 << " alloca: " << AS.AI << "\n"
922 << " use: " << SI << "\n");
923 return markAsDead(SI);
924 }
925
926 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
927 "All simple FCA stores should have been pre-split");
928 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
929 }
930
visitMemSetInst(MemSetInst & II)931 void visitMemSetInst(MemSetInst &II) {
932 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
933 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
934 if ((Length && Length->getValue() == 0) ||
935 (IsOffsetKnown && Offset.uge(AllocSize)))
936 // Zero-length mem transfer intrinsics can be ignored entirely.
937 return markAsDead(II);
938
939 if (!IsOffsetKnown)
940 return PI.setAborted(&II);
941
942 insertUse(II, Offset, Length ? Length->getLimitedValue()
943 : AllocSize - Offset.getLimitedValue(),
944 (bool)Length);
945 }
946
visitMemTransferInst(MemTransferInst & II)947 void visitMemTransferInst(MemTransferInst &II) {
948 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
949 if (Length && Length->getValue() == 0)
950 // Zero-length mem transfer intrinsics can be ignored entirely.
951 return markAsDead(II);
952
953 // Because we can visit these intrinsics twice, also check to see if the
954 // first time marked this instruction as dead. If so, skip it.
955 if (VisitedDeadInsts.count(&II))
956 return;
957
958 if (!IsOffsetKnown)
959 return PI.setAborted(&II);
960
961 // This side of the transfer is completely out-of-bounds, and so we can
962 // nuke the entire transfer. However, we also need to nuke the other side
963 // if already added to our partitions.
964 // FIXME: Yet another place we really should bypass this when
965 // instrumenting for ASan.
966 if (Offset.uge(AllocSize)) {
967 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
968 MemTransferSliceMap.find(&II);
969 if (MTPI != MemTransferSliceMap.end())
970 AS.Slices[MTPI->second].kill();
971 return markAsDead(II);
972 }
973
974 uint64_t RawOffset = Offset.getLimitedValue();
975 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
976
977 // Check for the special case where the same exact value is used for both
978 // source and dest.
979 if (*U == II.getRawDest() && *U == II.getRawSource()) {
980 // For non-volatile transfers this is a no-op.
981 if (!II.isVolatile())
982 return markAsDead(II);
983
984 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
985 }
986
987 // If we have seen both source and destination for a mem transfer, then
988 // they both point to the same alloca.
989 bool Inserted;
990 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
991 std::tie(MTPI, Inserted) =
992 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
993 unsigned PrevIdx = MTPI->second;
994 if (!Inserted) {
995 Slice &PrevP = AS.Slices[PrevIdx];
996
997 // Check if the begin offsets match and this is a non-volatile transfer.
998 // In that case, we can completely elide the transfer.
999 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
1000 PrevP.kill();
1001 return markAsDead(II);
1002 }
1003
1004 // Otherwise we have an offset transfer within the same alloca. We can't
1005 // split those.
1006 PrevP.makeUnsplittable();
1007 }
1008
1009 // Insert the use now that we've fixed up the splittable nature.
1010 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
1011
1012 // Check that we ended up with a valid index in the map.
1013 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
1014 "Map index doesn't point back to a slice with this user.");
1015 }
1016
1017 // Disable SRoA for any intrinsics except for lifetime invariants and
1018 // invariant group.
1019 // FIXME: What about debug intrinsics? This matches old behavior, but
1020 // doesn't make sense.
visitIntrinsicInst(IntrinsicInst & II)1021 void visitIntrinsicInst(IntrinsicInst &II) {
1022 if (II.isDroppable()) {
1023 AS.DeadUseIfPromotable.push_back(U);
1024 return;
1025 }
1026
1027 if (!IsOffsetKnown)
1028 return PI.setAborted(&II);
1029
1030 if (II.isLifetimeStartOrEnd()) {
1031 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
1032 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
1033 Length->getLimitedValue());
1034 insertUse(II, Offset, Size, true);
1035 return;
1036 }
1037
1038 if (II.isLaunderOrStripInvariantGroup()) {
1039 enqueueUsers(II);
1040 return;
1041 }
1042
1043 Base::visitIntrinsicInst(II);
1044 }
1045
hasUnsafePHIOrSelectUse(Instruction * Root,uint64_t & Size)1046 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
1047 // We consider any PHI or select that results in a direct load or store of
1048 // the same offset to be a viable use for slicing purposes. These uses
1049 // are considered unsplittable and the size is the maximum loaded or stored
1050 // size.
1051 SmallPtrSet<Instruction *, 4> Visited;
1052 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
1053 Visited.insert(Root);
1054 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
1055 const DataLayout &DL = Root->getModule()->getDataLayout();
1056 // If there are no loads or stores, the access is dead. We mark that as
1057 // a size zero access.
1058 Size = 0;
1059 do {
1060 Instruction *I, *UsedI;
1061 std::tie(UsedI, I) = Uses.pop_back_val();
1062
1063 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1064 Size =
1065 std::max(Size, DL.getTypeStoreSize(LI->getType()).getFixedValue());
1066 continue;
1067 }
1068 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1069 Value *Op = SI->getOperand(0);
1070 if (Op == UsedI)
1071 return SI;
1072 Size =
1073 std::max(Size, DL.getTypeStoreSize(Op->getType()).getFixedValue());
1074 continue;
1075 }
1076
1077 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
1078 if (!GEP->hasAllZeroIndices())
1079 return GEP;
1080 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
1081 !isa<SelectInst>(I) && !isa<AddrSpaceCastInst>(I)) {
1082 return I;
1083 }
1084
1085 for (User *U : I->users())
1086 if (Visited.insert(cast<Instruction>(U)).second)
1087 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
1088 } while (!Uses.empty());
1089
1090 return nullptr;
1091 }
1092
visitPHINodeOrSelectInst(Instruction & I)1093 void visitPHINodeOrSelectInst(Instruction &I) {
1094 assert(isa<PHINode>(I) || isa<SelectInst>(I));
1095 if (I.use_empty())
1096 return markAsDead(I);
1097
1098 // If this is a PHI node before a catchswitch, we cannot insert any non-PHI
1099 // instructions in this BB, which may be required during rewriting. Bail out
1100 // on these cases.
1101 if (isa<PHINode>(I) &&
1102 I.getParent()->getFirstInsertionPt() == I.getParent()->end())
1103 return PI.setAborted(&I);
1104
1105 // TODO: We could use simplifyInstruction here to fold PHINodes and
1106 // SelectInsts. However, doing so requires to change the current
1107 // dead-operand-tracking mechanism. For instance, suppose neither loading
1108 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
1109 // trap either. However, if we simply replace %U with undef using the
1110 // current dead-operand-tracking mechanism, "load (select undef, undef,
1111 // %other)" may trap because the select may return the first operand
1112 // "undef".
1113 if (Value *Result = foldPHINodeOrSelectInst(I)) {
1114 if (Result == *U)
1115 // If the result of the constant fold will be the pointer, recurse
1116 // through the PHI/select as if we had RAUW'ed it.
1117 enqueueUsers(I);
1118 else
1119 // Otherwise the operand to the PHI/select is dead, and we can replace
1120 // it with poison.
1121 AS.DeadOperands.push_back(U);
1122
1123 return;
1124 }
1125
1126 if (!IsOffsetKnown)
1127 return PI.setAborted(&I);
1128
1129 // See if we already have computed info on this node.
1130 uint64_t &Size = PHIOrSelectSizes[&I];
1131 if (!Size) {
1132 // This is a new PHI/Select, check for an unsafe use of it.
1133 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
1134 return PI.setAborted(UnsafeI);
1135 }
1136
1137 // For PHI and select operands outside the alloca, we can't nuke the entire
1138 // phi or select -- the other side might still be relevant, so we special
1139 // case them here and use a separate structure to track the operands
1140 // themselves which should be replaced with poison.
1141 // FIXME: This should instead be escaped in the event we're instrumenting
1142 // for address sanitization.
1143 if (Offset.uge(AllocSize)) {
1144 AS.DeadOperands.push_back(U);
1145 return;
1146 }
1147
1148 insertUse(I, Offset, Size);
1149 }
1150
visitPHINode(PHINode & PN)1151 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
1152
visitSelectInst(SelectInst & SI)1153 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
1154
1155 /// Disable SROA entirely if there are unhandled users of the alloca.
visitInstruction(Instruction & I)1156 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
1157 };
1158
AllocaSlices(const DataLayout & DL,AllocaInst & AI)1159 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
1160 :
1161 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1162 AI(AI),
1163 #endif
1164 PointerEscapingInstr(nullptr) {
1165 SliceBuilder PB(DL, AI, *this);
1166 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1167 if (PtrI.isEscaped() || PtrI.isAborted()) {
1168 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1169 // possibly by just storing the PtrInfo in the AllocaSlices.
1170 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1171 : PtrI.getAbortingInst();
1172 assert(PointerEscapingInstr && "Did not track a bad instruction");
1173 return;
1174 }
1175
1176 llvm::erase_if(Slices, [](const Slice &S) { return S.isDead(); });
1177
1178 // Sort the uses. This arranges for the offsets to be in ascending order,
1179 // and the sizes to be in descending order.
1180 llvm::stable_sort(Slices);
1181 }
1182
1183 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1184
print(raw_ostream & OS,const_iterator I,StringRef Indent) const1185 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1186 StringRef Indent) const {
1187 printSlice(OS, I, Indent);
1188 OS << "\n";
1189 printUse(OS, I, Indent);
1190 }
1191
printSlice(raw_ostream & OS,const_iterator I,StringRef Indent) const1192 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1193 StringRef Indent) const {
1194 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
1195 << " slice #" << (I - begin())
1196 << (I->isSplittable() ? " (splittable)" : "");
1197 }
1198
printUse(raw_ostream & OS,const_iterator I,StringRef Indent) const1199 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1200 StringRef Indent) const {
1201 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
1202 }
1203
print(raw_ostream & OS) const1204 void AllocaSlices::print(raw_ostream &OS) const {
1205 if (PointerEscapingInstr) {
1206 OS << "Can't analyze slices for alloca: " << AI << "\n"
1207 << " A pointer to this alloca escaped by:\n"
1208 << " " << *PointerEscapingInstr << "\n";
1209 return;
1210 }
1211
1212 OS << "Slices of alloca: " << AI << "\n";
1213 for (const_iterator I = begin(), E = end(); I != E; ++I)
1214 print(OS, I);
1215 }
1216
dump(const_iterator I) const1217 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1218 print(dbgs(), I);
1219 }
dump() const1220 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
1221
1222 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1223
1224 /// Walk the range of a partitioning looking for a common type to cover this
1225 /// sequence of slices.
1226 static std::pair<Type *, IntegerType *>
findCommonType(AllocaSlices::const_iterator B,AllocaSlices::const_iterator E,uint64_t EndOffset)1227 findCommonType(AllocaSlices::const_iterator B, AllocaSlices::const_iterator E,
1228 uint64_t EndOffset) {
1229 Type *Ty = nullptr;
1230 bool TyIsCommon = true;
1231 IntegerType *ITy = nullptr;
1232
1233 // Note that we need to look at *every* alloca slice's Use to ensure we
1234 // always get consistent results regardless of the order of slices.
1235 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1236 Use *U = I->getUse();
1237 if (isa<IntrinsicInst>(*U->getUser()))
1238 continue;
1239 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1240 continue;
1241
1242 Type *UserTy = nullptr;
1243 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1244 UserTy = LI->getType();
1245 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1246 UserTy = SI->getValueOperand()->getType();
1247 }
1248
1249 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1250 // If the type is larger than the partition, skip it. We only encounter
1251 // this for split integer operations where we want to use the type of the
1252 // entity causing the split. Also skip if the type is not a byte width
1253 // multiple.
1254 if (UserITy->getBitWidth() % 8 != 0 ||
1255 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1256 continue;
1257
1258 // Track the largest bitwidth integer type used in this way in case there
1259 // is no common type.
1260 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1261 ITy = UserITy;
1262 }
1263
1264 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1265 // depend on types skipped above.
1266 if (!UserTy || (Ty && Ty != UserTy))
1267 TyIsCommon = false; // Give up on anything but an iN type.
1268 else
1269 Ty = UserTy;
1270 }
1271
1272 return {TyIsCommon ? Ty : nullptr, ITy};
1273 }
1274
1275 /// PHI instructions that use an alloca and are subsequently loaded can be
1276 /// rewritten to load both input pointers in the pred blocks and then PHI the
1277 /// results, allowing the load of the alloca to be promoted.
1278 /// From this:
1279 /// %P2 = phi [i32* %Alloca, i32* %Other]
1280 /// %V = load i32* %P2
1281 /// to:
1282 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1283 /// ...
1284 /// %V2 = load i32* %Other
1285 /// ...
1286 /// %V = phi [i32 %V1, i32 %V2]
1287 ///
1288 /// We can do this to a select if its only uses are loads and if the operands
1289 /// to the select can be loaded unconditionally.
1290 ///
1291 /// FIXME: This should be hoisted into a generic utility, likely in
1292 /// Transforms/Util/Local.h
isSafePHIToSpeculate(PHINode & PN)1293 static bool isSafePHIToSpeculate(PHINode &PN) {
1294 const DataLayout &DL = PN.getModule()->getDataLayout();
1295
1296 // For now, we can only do this promotion if the load is in the same block
1297 // as the PHI, and if there are no stores between the phi and load.
1298 // TODO: Allow recursive phi users.
1299 // TODO: Allow stores.
1300 BasicBlock *BB = PN.getParent();
1301 Align MaxAlign;
1302 uint64_t APWidth = DL.getIndexTypeSizeInBits(PN.getType());
1303 Type *LoadType = nullptr;
1304 for (User *U : PN.users()) {
1305 LoadInst *LI = dyn_cast<LoadInst>(U);
1306 if (!LI || !LI->isSimple())
1307 return false;
1308
1309 // For now we only allow loads in the same block as the PHI. This is
1310 // a common case that happens when instcombine merges two loads through
1311 // a PHI.
1312 if (LI->getParent() != BB)
1313 return false;
1314
1315 if (LoadType) {
1316 if (LoadType != LI->getType())
1317 return false;
1318 } else {
1319 LoadType = LI->getType();
1320 }
1321
1322 // Ensure that there are no instructions between the PHI and the load that
1323 // could store.
1324 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
1325 if (BBI->mayWriteToMemory())
1326 return false;
1327
1328 MaxAlign = std::max(MaxAlign, LI->getAlign());
1329 }
1330
1331 if (!LoadType)
1332 return false;
1333
1334 APInt LoadSize =
1335 APInt(APWidth, DL.getTypeStoreSize(LoadType).getFixedValue());
1336
1337 // We can only transform this if it is safe to push the loads into the
1338 // predecessor blocks. The only thing to watch out for is that we can't put
1339 // a possibly trapping load in the predecessor if it is a critical edge.
1340 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1341 Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator();
1342 Value *InVal = PN.getIncomingValue(Idx);
1343
1344 // If the value is produced by the terminator of the predecessor (an
1345 // invoke) or it has side-effects, there is no valid place to put a load
1346 // in the predecessor.
1347 if (TI == InVal || TI->mayHaveSideEffects())
1348 return false;
1349
1350 // If the predecessor has a single successor, then the edge isn't
1351 // critical.
1352 if (TI->getNumSuccessors() == 1)
1353 continue;
1354
1355 // If this pointer is always safe to load, or if we can prove that there
1356 // is already a load in the block, then we can move the load to the pred
1357 // block.
1358 if (isSafeToLoadUnconditionally(InVal, MaxAlign, LoadSize, DL, TI))
1359 continue;
1360
1361 return false;
1362 }
1363
1364 return true;
1365 }
1366
speculatePHINodeLoads(IRBuilderTy & IRB,PHINode & PN)1367 static void speculatePHINodeLoads(IRBuilderTy &IRB, PHINode &PN) {
1368 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
1369
1370 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1371 Type *LoadTy = SomeLoad->getType();
1372 IRB.SetInsertPoint(&PN);
1373 PHINode *NewPN = IRB.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1374 PN.getName() + ".sroa.speculated");
1375
1376 // Get the AA tags and alignment to use from one of the loads. It does not
1377 // matter which one we get and if any differ.
1378 AAMDNodes AATags = SomeLoad->getAAMetadata();
1379 Align Alignment = SomeLoad->getAlign();
1380
1381 // Rewrite all loads of the PN to use the new PHI.
1382 while (!PN.use_empty()) {
1383 LoadInst *LI = cast<LoadInst>(PN.user_back());
1384 LI->replaceAllUsesWith(NewPN);
1385 LI->eraseFromParent();
1386 }
1387
1388 // Inject loads into all of the pred blocks.
1389 DenseMap<BasicBlock*, Value*> InjectedLoads;
1390 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1391 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1392 Value *InVal = PN.getIncomingValue(Idx);
1393
1394 // A PHI node is allowed to have multiple (duplicated) entries for the same
1395 // basic block, as long as the value is the same. So if we already injected
1396 // a load in the predecessor, then we should reuse the same load for all
1397 // duplicated entries.
1398 if (Value* V = InjectedLoads.lookup(Pred)) {
1399 NewPN->addIncoming(V, Pred);
1400 continue;
1401 }
1402
1403 Instruction *TI = Pred->getTerminator();
1404 IRB.SetInsertPoint(TI);
1405
1406 LoadInst *Load = IRB.CreateAlignedLoad(
1407 LoadTy, InVal, Alignment,
1408 (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1409 ++NumLoadsSpeculated;
1410 if (AATags)
1411 Load->setAAMetadata(AATags);
1412 NewPN->addIncoming(Load, Pred);
1413 InjectedLoads[Pred] = Load;
1414 }
1415
1416 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1417 PN.eraseFromParent();
1418 }
1419
1420 sroa::SelectHandSpeculativity &
setAsSpeculatable(bool isTrueVal)1421 sroa::SelectHandSpeculativity::setAsSpeculatable(bool isTrueVal) {
1422 if (isTrueVal)
1423 Bitfield::set<sroa::SelectHandSpeculativity::TrueVal>(Storage, true);
1424 else
1425 Bitfield::set<sroa::SelectHandSpeculativity::FalseVal>(Storage, true);
1426 return *this;
1427 }
1428
isSpeculatable(bool isTrueVal) const1429 bool sroa::SelectHandSpeculativity::isSpeculatable(bool isTrueVal) const {
1430 return isTrueVal
1431 ? Bitfield::get<sroa::SelectHandSpeculativity::TrueVal>(Storage)
1432 : Bitfield::get<sroa::SelectHandSpeculativity::FalseVal>(Storage);
1433 }
1434
areAllSpeculatable() const1435 bool sroa::SelectHandSpeculativity::areAllSpeculatable() const {
1436 return isSpeculatable(/*isTrueVal=*/true) &&
1437 isSpeculatable(/*isTrueVal=*/false);
1438 }
1439
areAnySpeculatable() const1440 bool sroa::SelectHandSpeculativity::areAnySpeculatable() const {
1441 return isSpeculatable(/*isTrueVal=*/true) ||
1442 isSpeculatable(/*isTrueVal=*/false);
1443 }
areNoneSpeculatable() const1444 bool sroa::SelectHandSpeculativity::areNoneSpeculatable() const {
1445 return !areAnySpeculatable();
1446 }
1447
1448 static sroa::SelectHandSpeculativity
isSafeLoadOfSelectToSpeculate(LoadInst & LI,SelectInst & SI,bool PreserveCFG)1449 isSafeLoadOfSelectToSpeculate(LoadInst &LI, SelectInst &SI, bool PreserveCFG) {
1450 assert(LI.isSimple() && "Only for simple loads");
1451 sroa::SelectHandSpeculativity Spec;
1452
1453 const DataLayout &DL = SI.getModule()->getDataLayout();
1454 for (Value *Value : {SI.getTrueValue(), SI.getFalseValue()})
1455 if (isSafeToLoadUnconditionally(Value, LI.getType(), LI.getAlign(), DL,
1456 &LI))
1457 Spec.setAsSpeculatable(/*isTrueVal=*/Value == SI.getTrueValue());
1458 else if (PreserveCFG)
1459 return Spec;
1460
1461 return Spec;
1462 }
1463
1464 std::optional<sroa::RewriteableMemOps>
isSafeSelectToSpeculate(SelectInst & SI,bool PreserveCFG)1465 SROAPass::isSafeSelectToSpeculate(SelectInst &SI, bool PreserveCFG) {
1466 RewriteableMemOps Ops;
1467
1468 for (User *U : SI.users()) {
1469 if (auto *BC = dyn_cast<BitCastInst>(U); BC && BC->hasOneUse())
1470 U = *BC->user_begin();
1471
1472 if (auto *Store = dyn_cast<StoreInst>(U)) {
1473 // Note that atomic stores can be transformed; atomic semantics do not
1474 // have any meaning for a local alloca. Stores are not speculatable,
1475 // however, so if we can't turn it into a predicated store, we are done.
1476 if (Store->isVolatile() || PreserveCFG)
1477 return {}; // Give up on this `select`.
1478 Ops.emplace_back(Store);
1479 continue;
1480 }
1481
1482 auto *LI = dyn_cast<LoadInst>(U);
1483
1484 // Note that atomic loads can be transformed;
1485 // atomic semantics do not have any meaning for a local alloca.
1486 if (!LI || LI->isVolatile())
1487 return {}; // Give up on this `select`.
1488
1489 PossiblySpeculatableLoad Load(LI);
1490 if (!LI->isSimple()) {
1491 // If the `load` is not simple, we can't speculatively execute it,
1492 // but we could handle this via a CFG modification. But can we?
1493 if (PreserveCFG)
1494 return {}; // Give up on this `select`.
1495 Ops.emplace_back(Load);
1496 continue;
1497 }
1498
1499 sroa::SelectHandSpeculativity Spec =
1500 isSafeLoadOfSelectToSpeculate(*LI, SI, PreserveCFG);
1501 if (PreserveCFG && !Spec.areAllSpeculatable())
1502 return {}; // Give up on this `select`.
1503
1504 Load.setInt(Spec);
1505 Ops.emplace_back(Load);
1506 }
1507
1508 return Ops;
1509 }
1510
speculateSelectInstLoads(SelectInst & SI,LoadInst & LI,IRBuilderTy & IRB)1511 static void speculateSelectInstLoads(SelectInst &SI, LoadInst &LI,
1512 IRBuilderTy &IRB) {
1513 LLVM_DEBUG(dbgs() << " original load: " << SI << "\n");
1514
1515 Value *TV = SI.getTrueValue();
1516 Value *FV = SI.getFalseValue();
1517 // Replace the given load of the select with a select of two loads.
1518
1519 assert(LI.isSimple() && "We only speculate simple loads");
1520
1521 IRB.SetInsertPoint(&LI);
1522
1523 if (auto *TypedPtrTy = LI.getPointerOperandType();
1524 !TypedPtrTy->isOpaquePointerTy() && SI.getType() != TypedPtrTy) {
1525 TV = IRB.CreateBitOrPointerCast(TV, TypedPtrTy, "");
1526 FV = IRB.CreateBitOrPointerCast(FV, TypedPtrTy, "");
1527 }
1528
1529 LoadInst *TL =
1530 IRB.CreateAlignedLoad(LI.getType(), TV, LI.getAlign(),
1531 LI.getName() + ".sroa.speculate.load.true");
1532 LoadInst *FL =
1533 IRB.CreateAlignedLoad(LI.getType(), FV, LI.getAlign(),
1534 LI.getName() + ".sroa.speculate.load.false");
1535 NumLoadsSpeculated += 2;
1536
1537 // Transfer alignment and AA info if present.
1538 TL->setAlignment(LI.getAlign());
1539 FL->setAlignment(LI.getAlign());
1540
1541 AAMDNodes Tags = LI.getAAMetadata();
1542 if (Tags) {
1543 TL->setAAMetadata(Tags);
1544 FL->setAAMetadata(Tags);
1545 }
1546
1547 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1548 LI.getName() + ".sroa.speculated");
1549
1550 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n");
1551 LI.replaceAllUsesWith(V);
1552 }
1553
1554 template <typename T>
rewriteMemOpOfSelect(SelectInst & SI,T & I,sroa::SelectHandSpeculativity Spec,DomTreeUpdater & DTU)1555 static void rewriteMemOpOfSelect(SelectInst &SI, T &I,
1556 sroa::SelectHandSpeculativity Spec,
1557 DomTreeUpdater &DTU) {
1558 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) && "Only for load and store!");
1559 LLVM_DEBUG(dbgs() << " original mem op: " << I << "\n");
1560 BasicBlock *Head = I.getParent();
1561 Instruction *ThenTerm = nullptr;
1562 Instruction *ElseTerm = nullptr;
1563 if (Spec.areNoneSpeculatable())
1564 SplitBlockAndInsertIfThenElse(SI.getCondition(), &I, &ThenTerm, &ElseTerm,
1565 SI.getMetadata(LLVMContext::MD_prof), &DTU);
1566 else {
1567 SplitBlockAndInsertIfThen(SI.getCondition(), &I, /*Unreachable=*/false,
1568 SI.getMetadata(LLVMContext::MD_prof), &DTU,
1569 /*LI=*/nullptr, /*ThenBlock=*/nullptr);
1570 if (Spec.isSpeculatable(/*isTrueVal=*/true))
1571 cast<BranchInst>(Head->getTerminator())->swapSuccessors();
1572 }
1573 auto *HeadBI = cast<BranchInst>(Head->getTerminator());
1574 Spec = {}; // Do not use `Spec` beyond this point.
1575 BasicBlock *Tail = I.getParent();
1576 Tail->setName(Head->getName() + ".cont");
1577 PHINode *PN;
1578 if (isa<LoadInst>(I))
1579 PN = PHINode::Create(I.getType(), 2, "", &I);
1580 for (BasicBlock *SuccBB : successors(Head)) {
1581 bool IsThen = SuccBB == HeadBI->getSuccessor(0);
1582 int SuccIdx = IsThen ? 0 : 1;
1583 auto *NewMemOpBB = SuccBB == Tail ? Head : SuccBB;
1584 if (NewMemOpBB != Head) {
1585 NewMemOpBB->setName(Head->getName() + (IsThen ? ".then" : ".else"));
1586 if (isa<LoadInst>(I))
1587 ++NumLoadsPredicated;
1588 else
1589 ++NumStoresPredicated;
1590 } else
1591 ++NumLoadsSpeculated;
1592 auto &CondMemOp = cast<T>(*I.clone());
1593 CondMemOp.insertBefore(NewMemOpBB->getTerminator());
1594 Value *Ptr = SI.getOperand(1 + SuccIdx);
1595 if (auto *PtrTy = Ptr->getType();
1596 !PtrTy->isOpaquePointerTy() &&
1597 PtrTy != CondMemOp.getPointerOperandType())
1598 Ptr = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
1599 Ptr, CondMemOp.getPointerOperandType(), "", &CondMemOp);
1600 CondMemOp.setOperand(I.getPointerOperandIndex(), Ptr);
1601 if (isa<LoadInst>(I)) {
1602 CondMemOp.setName(I.getName() + (IsThen ? ".then" : ".else") + ".val");
1603 PN->addIncoming(&CondMemOp, NewMemOpBB);
1604 } else
1605 LLVM_DEBUG(dbgs() << " to: " << CondMemOp << "\n");
1606 }
1607 if (isa<LoadInst>(I)) {
1608 PN->takeName(&I);
1609 LLVM_DEBUG(dbgs() << " to: " << *PN << "\n");
1610 I.replaceAllUsesWith(PN);
1611 }
1612 }
1613
rewriteMemOpOfSelect(SelectInst & SelInst,Instruction & I,sroa::SelectHandSpeculativity Spec,DomTreeUpdater & DTU)1614 static void rewriteMemOpOfSelect(SelectInst &SelInst, Instruction &I,
1615 sroa::SelectHandSpeculativity Spec,
1616 DomTreeUpdater &DTU) {
1617 if (auto *LI = dyn_cast<LoadInst>(&I))
1618 rewriteMemOpOfSelect(SelInst, *LI, Spec, DTU);
1619 else if (auto *SI = dyn_cast<StoreInst>(&I))
1620 rewriteMemOpOfSelect(SelInst, *SI, Spec, DTU);
1621 else
1622 llvm_unreachable_internal("Only for load and store.");
1623 }
1624
rewriteSelectInstMemOps(SelectInst & SI,const sroa::RewriteableMemOps & Ops,IRBuilderTy & IRB,DomTreeUpdater * DTU)1625 static bool rewriteSelectInstMemOps(SelectInst &SI,
1626 const sroa::RewriteableMemOps &Ops,
1627 IRBuilderTy &IRB, DomTreeUpdater *DTU) {
1628 bool CFGChanged = false;
1629 LLVM_DEBUG(dbgs() << " original select: " << SI << "\n");
1630
1631 for (const RewriteableMemOp &Op : Ops) {
1632 sroa::SelectHandSpeculativity Spec;
1633 Instruction *I;
1634 if (auto *const *US = std::get_if<UnspeculatableStore>(&Op)) {
1635 I = *US;
1636 } else {
1637 auto PSL = std::get<PossiblySpeculatableLoad>(Op);
1638 I = PSL.getPointer();
1639 Spec = PSL.getInt();
1640 }
1641 if (Spec.areAllSpeculatable()) {
1642 speculateSelectInstLoads(SI, cast<LoadInst>(*I), IRB);
1643 } else {
1644 assert(DTU && "Should not get here when not allowed to modify the CFG!");
1645 rewriteMemOpOfSelect(SI, *I, Spec, *DTU);
1646 CFGChanged = true;
1647 }
1648 I->eraseFromParent();
1649 }
1650
1651 for (User *U : make_early_inc_range(SI.users()))
1652 cast<BitCastInst>(U)->eraseFromParent();
1653 SI.eraseFromParent();
1654 return CFGChanged;
1655 }
1656
1657 /// Build a GEP out of a base pointer and indices.
1658 ///
1659 /// This will return the BasePtr if that is valid, or build a new GEP
1660 /// instruction using the IRBuilder if GEP-ing is needed.
buildGEP(IRBuilderTy & IRB,Value * BasePtr,SmallVectorImpl<Value * > & Indices,const Twine & NamePrefix)1661 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1662 SmallVectorImpl<Value *> &Indices,
1663 const Twine &NamePrefix) {
1664 if (Indices.empty())
1665 return BasePtr;
1666
1667 // A single zero index is a no-op, so check for this and avoid building a GEP
1668 // in that case.
1669 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1670 return BasePtr;
1671
1672 // buildGEP() is only called for non-opaque pointers.
1673 return IRB.CreateInBoundsGEP(
1674 BasePtr->getType()->getNonOpaquePointerElementType(), BasePtr, Indices,
1675 NamePrefix + "sroa_idx");
1676 }
1677
1678 /// Get a natural GEP off of the BasePtr walking through Ty toward
1679 /// TargetTy without changing the offset of the pointer.
1680 ///
1681 /// This routine assumes we've already established a properly offset GEP with
1682 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1683 /// zero-indices down through type layers until we find one the same as
1684 /// TargetTy. If we can't find one with the same type, we at least try to use
1685 /// one with the same size. If none of that works, we just produce the GEP as
1686 /// indicated by Indices to have the correct offset.
getNaturalGEPWithType(IRBuilderTy & IRB,const DataLayout & DL,Value * BasePtr,Type * Ty,Type * TargetTy,SmallVectorImpl<Value * > & Indices,const Twine & NamePrefix)1687 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1688 Value *BasePtr, Type *Ty, Type *TargetTy,
1689 SmallVectorImpl<Value *> &Indices,
1690 const Twine &NamePrefix) {
1691 if (Ty == TargetTy)
1692 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1693
1694 // Offset size to use for the indices.
1695 unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType());
1696
1697 // See if we can descend into a struct and locate a field with the correct
1698 // type.
1699 unsigned NumLayers = 0;
1700 Type *ElementTy = Ty;
1701 do {
1702 if (ElementTy->isPointerTy())
1703 break;
1704
1705 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1706 ElementTy = ArrayTy->getElementType();
1707 Indices.push_back(IRB.getIntN(OffsetSize, 0));
1708 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1709 ElementTy = VectorTy->getElementType();
1710 Indices.push_back(IRB.getInt32(0));
1711 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1712 if (STy->element_begin() == STy->element_end())
1713 break; // Nothing left to descend into.
1714 ElementTy = *STy->element_begin();
1715 Indices.push_back(IRB.getInt32(0));
1716 } else {
1717 break;
1718 }
1719 ++NumLayers;
1720 } while (ElementTy != TargetTy);
1721 if (ElementTy != TargetTy)
1722 Indices.erase(Indices.end() - NumLayers, Indices.end());
1723
1724 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1725 }
1726
1727 /// Get a natural GEP from a base pointer to a particular offset and
1728 /// resulting in a particular type.
1729 ///
1730 /// The goal is to produce a "natural" looking GEP that works with the existing
1731 /// composite types to arrive at the appropriate offset and element type for
1732 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1733 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1734 /// Indices, and setting Ty to the result subtype.
1735 ///
1736 /// 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,const Twine & NamePrefix)1737 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1738 Value *Ptr, APInt Offset, Type *TargetTy,
1739 SmallVectorImpl<Value *> &Indices,
1740 const Twine &NamePrefix) {
1741 PointerType *Ty = cast<PointerType>(Ptr->getType());
1742
1743 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1744 // an i8.
1745 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
1746 return nullptr;
1747
1748 Type *ElementTy = Ty->getNonOpaquePointerElementType();
1749 if (!ElementTy->isSized())
1750 return nullptr; // We can't GEP through an unsized element.
1751
1752 SmallVector<APInt> IntIndices = DL.getGEPIndicesForOffset(ElementTy, Offset);
1753 if (Offset != 0)
1754 return nullptr;
1755
1756 for (const APInt &Index : IntIndices)
1757 Indices.push_back(IRB.getInt(Index));
1758 return getNaturalGEPWithType(IRB, DL, Ptr, ElementTy, TargetTy, Indices,
1759 NamePrefix);
1760 }
1761
1762 /// Compute an adjusted pointer from Ptr by Offset bytes where the
1763 /// resulting pointer has PointerTy.
1764 ///
1765 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1766 /// and produces the pointer type desired. Where it cannot, it will try to use
1767 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1768 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1769 /// bitcast to the type.
1770 ///
1771 /// The strategy for finding the more natural GEPs is to peel off layers of the
1772 /// pointer, walking back through bit casts and GEPs, searching for a base
1773 /// pointer from which we can compute a natural GEP with the desired
1774 /// properties. The algorithm tries to fold as many constant indices into
1775 /// a single GEP as possible, thus making each GEP more independent of the
1776 /// surrounding code.
getAdjustedPtr(IRBuilderTy & IRB,const DataLayout & DL,Value * Ptr,APInt Offset,Type * PointerTy,const Twine & NamePrefix)1777 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1778 APInt Offset, Type *PointerTy,
1779 const Twine &NamePrefix) {
1780 // Create i8 GEP for opaque pointers.
1781 if (Ptr->getType()->isOpaquePointerTy()) {
1782 if (Offset != 0)
1783 Ptr = IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Ptr, IRB.getInt(Offset),
1784 NamePrefix + "sroa_idx");
1785 return IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr, PointerTy,
1786 NamePrefix + "sroa_cast");
1787 }
1788
1789 // Even though we don't look through PHI nodes, we could be called on an
1790 // instruction in an unreachable block, which may be on a cycle.
1791 SmallPtrSet<Value *, 4> Visited;
1792 Visited.insert(Ptr);
1793 SmallVector<Value *, 4> Indices;
1794
1795 // We may end up computing an offset pointer that has the wrong type. If we
1796 // never are able to compute one directly that has the correct type, we'll
1797 // fall back to it, so keep it and the base it was computed from around here.
1798 Value *OffsetPtr = nullptr;
1799 Value *OffsetBasePtr;
1800
1801 // Remember any i8 pointer we come across to re-use if we need to do a raw
1802 // byte offset.
1803 Value *Int8Ptr = nullptr;
1804 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1805
1806 PointerType *TargetPtrTy = cast<PointerType>(PointerTy);
1807 Type *TargetTy = TargetPtrTy->getNonOpaquePointerElementType();
1808
1809 // As `addrspacecast` is , `Ptr` (the storage pointer) may have different
1810 // address space from the expected `PointerTy` (the pointer to be used).
1811 // Adjust the pointer type based the original storage pointer.
1812 auto AS = cast<PointerType>(Ptr->getType())->getAddressSpace();
1813 PointerTy = TargetTy->getPointerTo(AS);
1814
1815 do {
1816 // First fold any existing GEPs into the offset.
1817 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1818 APInt GEPOffset(Offset.getBitWidth(), 0);
1819 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1820 break;
1821 Offset += GEPOffset;
1822 Ptr = GEP->getPointerOperand();
1823 if (!Visited.insert(Ptr).second)
1824 break;
1825 }
1826
1827 // See if we can perform a natural GEP here.
1828 Indices.clear();
1829 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1830 Indices, NamePrefix)) {
1831 // If we have a new natural pointer at the offset, clear out any old
1832 // offset pointer we computed. Unless it is the base pointer or
1833 // a non-instruction, we built a GEP we don't need. Zap it.
1834 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1835 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1836 assert(I->use_empty() && "Built a GEP with uses some how!");
1837 I->eraseFromParent();
1838 }
1839 OffsetPtr = P;
1840 OffsetBasePtr = Ptr;
1841 // If we also found a pointer of the right type, we're done.
1842 if (P->getType() == PointerTy)
1843 break;
1844 }
1845
1846 // Stash this pointer if we've found an i8*.
1847 if (Ptr->getType()->isIntegerTy(8)) {
1848 Int8Ptr = Ptr;
1849 Int8PtrOffset = Offset;
1850 }
1851
1852 // Peel off a layer of the pointer and update the offset appropriately.
1853 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1854 Ptr = cast<Operator>(Ptr)->getOperand(0);
1855 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1856 if (GA->isInterposable())
1857 break;
1858 Ptr = GA->getAliasee();
1859 } else {
1860 break;
1861 }
1862 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1863 } while (Visited.insert(Ptr).second);
1864
1865 if (!OffsetPtr) {
1866 if (!Int8Ptr) {
1867 Int8Ptr = IRB.CreateBitCast(
1868 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1869 NamePrefix + "sroa_raw_cast");
1870 Int8PtrOffset = Offset;
1871 }
1872
1873 OffsetPtr = Int8PtrOffset == 0
1874 ? Int8Ptr
1875 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1876 IRB.getInt(Int8PtrOffset),
1877 NamePrefix + "sroa_raw_idx");
1878 }
1879 Ptr = OffsetPtr;
1880
1881 // On the off chance we were targeting i8*, guard the bitcast here.
1882 if (cast<PointerType>(Ptr->getType()) != TargetPtrTy) {
1883 Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr,
1884 TargetPtrTy,
1885 NamePrefix + "sroa_cast");
1886 }
1887
1888 return Ptr;
1889 }
1890
1891 /// Compute the adjusted alignment for a load or store from an offset.
getAdjustedAlignment(Instruction * I,uint64_t Offset)1892 static Align getAdjustedAlignment(Instruction *I, uint64_t Offset) {
1893 return commonAlignment(getLoadStoreAlignment(I), Offset);
1894 }
1895
1896 /// Test whether we can convert a value from the old to the new type.
1897 ///
1898 /// This predicate should be used to guard calls to convertValue in order to
1899 /// ensure that we only try to convert viable values. The strategy is that we
1900 /// will peel off single element struct and array wrappings to get to an
1901 /// underlying value, and convert that value.
canConvertValue(const DataLayout & DL,Type * OldTy,Type * NewTy)1902 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1903 if (OldTy == NewTy)
1904 return true;
1905
1906 // For integer types, we can't handle any bit-width differences. This would
1907 // break both vector conversions with extension and introduce endianness
1908 // issues when in conjunction with loads and stores.
1909 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1910 assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1911 cast<IntegerType>(NewTy)->getBitWidth() &&
1912 "We can't have the same bitwidth for different int types");
1913 return false;
1914 }
1915
1916 if (DL.getTypeSizeInBits(NewTy).getFixedValue() !=
1917 DL.getTypeSizeInBits(OldTy).getFixedValue())
1918 return false;
1919 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1920 return false;
1921
1922 // We can convert pointers to integers and vice-versa. Same for vectors
1923 // of pointers and integers.
1924 OldTy = OldTy->getScalarType();
1925 NewTy = NewTy->getScalarType();
1926 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1927 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1928 unsigned OldAS = OldTy->getPointerAddressSpace();
1929 unsigned NewAS = NewTy->getPointerAddressSpace();
1930 // Convert pointers if they are pointers from the same address space or
1931 // different integral (not non-integral) address spaces with the same
1932 // pointer size.
1933 return OldAS == NewAS ||
1934 (!DL.isNonIntegralAddressSpace(OldAS) &&
1935 !DL.isNonIntegralAddressSpace(NewAS) &&
1936 DL.getPointerSize(OldAS) == DL.getPointerSize(NewAS));
1937 }
1938
1939 // We can convert integers to integral pointers, but not to non-integral
1940 // pointers.
1941 if (OldTy->isIntegerTy())
1942 return !DL.isNonIntegralPointerType(NewTy);
1943
1944 // We can convert integral pointers to integers, but non-integral pointers
1945 // need to remain pointers.
1946 if (!DL.isNonIntegralPointerType(OldTy))
1947 return NewTy->isIntegerTy();
1948
1949 return false;
1950 }
1951
1952 if (OldTy->isTargetExtTy() || NewTy->isTargetExtTy())
1953 return false;
1954
1955 return true;
1956 }
1957
1958 /// Generic routine to convert an SSA value to a value of a different
1959 /// type.
1960 ///
1961 /// This will try various different casting techniques, such as bitcasts,
1962 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1963 /// two types for viability with this routine.
convertValue(const DataLayout & DL,IRBuilderTy & IRB,Value * V,Type * NewTy)1964 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1965 Type *NewTy) {
1966 Type *OldTy = V->getType();
1967 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1968
1969 if (OldTy == NewTy)
1970 return V;
1971
1972 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1973 "Integer types must be the exact same to convert.");
1974
1975 // See if we need inttoptr for this type pair. May require additional bitcast.
1976 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
1977 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1978 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1979 // Expand <4 x i32> to <2 x i8*> --> <4 x i32> to <2 x i64> to <2 x i8*>
1980 // Directly handle i64 to i8*
1981 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1982 NewTy);
1983 }
1984
1985 // See if we need ptrtoint for this type pair. May require additional bitcast.
1986 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
1987 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1988 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1989 // Expand <2 x i8*> to <4 x i32> --> <2 x i8*> to <2 x i64> to <4 x i32>
1990 // Expand i8* to i64 --> i8* to i64 to i64
1991 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1992 NewTy);
1993 }
1994
1995 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
1996 unsigned OldAS = OldTy->getPointerAddressSpace();
1997 unsigned NewAS = NewTy->getPointerAddressSpace();
1998 // To convert pointers with different address spaces (they are already
1999 // checked convertible, i.e. they have the same pointer size), so far we
2000 // cannot use `bitcast` (which has restrict on the same address space) or
2001 // `addrspacecast` (which is not always no-op casting). Instead, use a pair
2002 // of no-op `ptrtoint`/`inttoptr` casts through an integer with the same bit
2003 // size.
2004 if (OldAS != NewAS) {
2005 assert(DL.getPointerSize(OldAS) == DL.getPointerSize(NewAS));
2006 return IRB.CreateIntToPtr(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
2007 NewTy);
2008 }
2009 }
2010
2011 return IRB.CreateBitCast(V, NewTy);
2012 }
2013
2014 /// Test whether the given slice use can be promoted to a vector.
2015 ///
2016 /// This function is called to test each entry in a partition which is slated
2017 /// for a single slice.
isVectorPromotionViableForSlice(Partition & P,const Slice & S,VectorType * Ty,uint64_t ElementSize,const DataLayout & DL)2018 static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
2019 VectorType *Ty,
2020 uint64_t ElementSize,
2021 const DataLayout &DL) {
2022 // First validate the slice offsets.
2023 uint64_t BeginOffset =
2024 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
2025 uint64_t BeginIndex = BeginOffset / ElementSize;
2026 if (BeginIndex * ElementSize != BeginOffset ||
2027 BeginIndex >= cast<FixedVectorType>(Ty)->getNumElements())
2028 return false;
2029 uint64_t EndOffset =
2030 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
2031 uint64_t EndIndex = EndOffset / ElementSize;
2032 if (EndIndex * ElementSize != EndOffset ||
2033 EndIndex > cast<FixedVectorType>(Ty)->getNumElements())
2034 return false;
2035
2036 assert(EndIndex > BeginIndex && "Empty vector!");
2037 uint64_t NumElements = EndIndex - BeginIndex;
2038 Type *SliceTy = (NumElements == 1)
2039 ? Ty->getElementType()
2040 : FixedVectorType::get(Ty->getElementType(), NumElements);
2041
2042 Type *SplitIntTy =
2043 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
2044
2045 Use *U = S.getUse();
2046
2047 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2048 if (MI->isVolatile())
2049 return false;
2050 if (!S.isSplittable())
2051 return false; // Skip any unsplittable intrinsics.
2052 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2053 if (!II->isLifetimeStartOrEnd() && !II->isDroppable())
2054 return false;
2055 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2056 if (LI->isVolatile())
2057 return false;
2058 Type *LTy = LI->getType();
2059 // Disable vector promotion when there are loads or stores of an FCA.
2060 if (LTy->isStructTy())
2061 return false;
2062 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
2063 assert(LTy->isIntegerTy());
2064 LTy = SplitIntTy;
2065 }
2066 if (!canConvertValue(DL, SliceTy, LTy))
2067 return false;
2068 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2069 if (SI->isVolatile())
2070 return false;
2071 Type *STy = SI->getValueOperand()->getType();
2072 // Disable vector promotion when there are loads or stores of an FCA.
2073 if (STy->isStructTy())
2074 return false;
2075 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
2076 assert(STy->isIntegerTy());
2077 STy = SplitIntTy;
2078 }
2079 if (!canConvertValue(DL, STy, SliceTy))
2080 return false;
2081 } else {
2082 return false;
2083 }
2084
2085 return true;
2086 }
2087
2088 /// Test whether a vector type is viable for promotion.
2089 ///
2090 /// This implements the necessary checking for \c isVectorPromotionViable over
2091 /// all slices of the alloca for the given VectorType.
checkVectorTypeForPromotion(Partition & P,VectorType * VTy,const DataLayout & DL)2092 static bool checkVectorTypeForPromotion(Partition &P, VectorType *VTy,
2093 const DataLayout &DL) {
2094 uint64_t ElementSize =
2095 DL.getTypeSizeInBits(VTy->getElementType()).getFixedValue();
2096
2097 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2098 // that aren't byte sized.
2099 if (ElementSize % 8)
2100 return false;
2101 assert((DL.getTypeSizeInBits(VTy).getFixedValue() % 8) == 0 &&
2102 "vector size not a multiple of element size?");
2103 ElementSize /= 8;
2104
2105 for (const Slice &S : P)
2106 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
2107 return false;
2108
2109 for (const Slice *S : P.splitSliceTails())
2110 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
2111 return false;
2112
2113 return true;
2114 }
2115
2116 /// Test whether the given alloca partitioning and range of slices can be
2117 /// promoted to a vector.
2118 ///
2119 /// This is a quick test to check whether we can rewrite a particular alloca
2120 /// partition (and its newly formed alloca) into a vector alloca with only
2121 /// whole-vector loads and stores such that it could be promoted to a vector
2122 /// SSA value. We only can ensure this for a limited set of operations, and we
2123 /// don't want to do the rewrites unless we are confident that the result will
2124 /// be promotable, so we have an early test here.
isVectorPromotionViable(Partition & P,const DataLayout & DL)2125 static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
2126 // Collect the candidate types for vector-based promotion. Also track whether
2127 // we have different element types.
2128 SmallVector<VectorType *, 4> CandidateTys;
2129 Type *CommonEltTy = nullptr;
2130 VectorType *CommonVecPtrTy = nullptr;
2131 bool HaveVecPtrTy = false;
2132 bool HaveCommonEltTy = true;
2133 bool HaveCommonVecPtrTy = true;
2134 auto CheckCandidateType = [&](Type *Ty) {
2135 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
2136 // Return if bitcast to vectors is different for total size in bits.
2137 if (!CandidateTys.empty()) {
2138 VectorType *V = CandidateTys[0];
2139 if (DL.getTypeSizeInBits(VTy).getFixedValue() !=
2140 DL.getTypeSizeInBits(V).getFixedValue()) {
2141 CandidateTys.clear();
2142 return;
2143 }
2144 }
2145 CandidateTys.push_back(VTy);
2146 Type *EltTy = VTy->getElementType();
2147
2148 if (!CommonEltTy)
2149 CommonEltTy = EltTy;
2150 else if (CommonEltTy != EltTy)
2151 HaveCommonEltTy = false;
2152
2153 if (EltTy->isPointerTy()) {
2154 HaveVecPtrTy = true;
2155 if (!CommonVecPtrTy)
2156 CommonVecPtrTy = VTy;
2157 else if (CommonVecPtrTy != VTy)
2158 HaveCommonVecPtrTy = false;
2159 }
2160 }
2161 };
2162 // Consider any loads or stores that are the exact size of the slice.
2163 for (const Slice &S : P)
2164 if (S.beginOffset() == P.beginOffset() &&
2165 S.endOffset() == P.endOffset()) {
2166 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
2167 CheckCandidateType(LI->getType());
2168 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
2169 CheckCandidateType(SI->getValueOperand()->getType());
2170 }
2171
2172 // If we didn't find a vector type, nothing to do here.
2173 if (CandidateTys.empty())
2174 return nullptr;
2175
2176 // Pointer-ness is sticky, if we had a vector-of-pointers candidate type,
2177 // then we should choose it, not some other alternative.
2178 // But, we can't perform a no-op pointer address space change via bitcast,
2179 // so if we didn't have a common pointer element type, bail.
2180 if (HaveVecPtrTy && !HaveCommonVecPtrTy)
2181 return nullptr;
2182
2183 // Try to pick the "best" element type out of the choices.
2184 if (!HaveCommonEltTy && HaveVecPtrTy) {
2185 // If there was a pointer element type, there's really only one choice.
2186 CandidateTys.clear();
2187 CandidateTys.push_back(CommonVecPtrTy);
2188 } else if (!HaveCommonEltTy && !HaveVecPtrTy) {
2189 // Integer-ify vector types.
2190 for (VectorType *&VTy : CandidateTys) {
2191 if (!VTy->getElementType()->isIntegerTy())
2192 VTy = cast<VectorType>(VTy->getWithNewType(IntegerType::getIntNTy(
2193 VTy->getContext(), VTy->getScalarSizeInBits())));
2194 }
2195
2196 // Rank the remaining candidate vector types. This is easy because we know
2197 // they're all integer vectors. We sort by ascending number of elements.
2198 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
2199 (void)DL;
2200 assert(DL.getTypeSizeInBits(RHSTy).getFixedValue() ==
2201 DL.getTypeSizeInBits(LHSTy).getFixedValue() &&
2202 "Cannot have vector types of different sizes!");
2203 assert(RHSTy->getElementType()->isIntegerTy() &&
2204 "All non-integer types eliminated!");
2205 assert(LHSTy->getElementType()->isIntegerTy() &&
2206 "All non-integer types eliminated!");
2207 return cast<FixedVectorType>(RHSTy)->getNumElements() <
2208 cast<FixedVectorType>(LHSTy)->getNumElements();
2209 };
2210 llvm::sort(CandidateTys, RankVectorTypes);
2211 CandidateTys.erase(
2212 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
2213 CandidateTys.end());
2214 } else {
2215 // The only way to have the same element type in every vector type is to
2216 // have the same vector type. Check that and remove all but one.
2217 #ifndef NDEBUG
2218 for (VectorType *VTy : CandidateTys) {
2219 assert(VTy->getElementType() == CommonEltTy &&
2220 "Unaccounted for element type!");
2221 assert(VTy == CandidateTys[0] &&
2222 "Different vector types with the same element type!");
2223 }
2224 #endif
2225 CandidateTys.resize(1);
2226 }
2227
2228 // FIXME: hack. Do we have a named constant for this?
2229 // SDAG SDNode can't have more than 65535 operands.
2230 llvm::erase_if(CandidateTys, [](VectorType *VTy) {
2231 return cast<FixedVectorType>(VTy)->getNumElements() >
2232 std::numeric_limits<unsigned short>::max();
2233 });
2234
2235 for (VectorType *VTy : CandidateTys)
2236 if (checkVectorTypeForPromotion(P, VTy, DL))
2237 return VTy;
2238
2239 return nullptr;
2240 }
2241
2242 /// Test whether a slice of an alloca is valid for integer widening.
2243 ///
2244 /// This implements the necessary checking for the \c isIntegerWideningViable
2245 /// test below on a single slice of the alloca.
isIntegerWideningViableForSlice(const Slice & S,uint64_t AllocBeginOffset,Type * AllocaTy,const DataLayout & DL,bool & WholeAllocaOp)2246 static bool isIntegerWideningViableForSlice(const Slice &S,
2247 uint64_t AllocBeginOffset,
2248 Type *AllocaTy,
2249 const DataLayout &DL,
2250 bool &WholeAllocaOp) {
2251 uint64_t Size = DL.getTypeStoreSize(AllocaTy).getFixedValue();
2252
2253 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2254 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
2255
2256 Use *U = S.getUse();
2257
2258 // Lifetime intrinsics operate over the whole alloca whose sizes are usually
2259 // larger than other load/store slices (RelEnd > Size). But lifetime are
2260 // always promotable and should not impact other slices' promotability of the
2261 // partition.
2262 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2263 if (II->isLifetimeStartOrEnd() || II->isDroppable())
2264 return true;
2265 }
2266
2267 // We can't reasonably handle cases where the load or store extends past
2268 // the end of the alloca's type and into its padding.
2269 if (RelEnd > Size)
2270 return false;
2271
2272 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2273 if (LI->isVolatile())
2274 return false;
2275 // We can't handle loads that extend past the allocated memory.
2276 if (DL.getTypeStoreSize(LI->getType()).getFixedValue() > Size)
2277 return false;
2278 // So far, AllocaSliceRewriter does not support widening split slice tails
2279 // in rewriteIntegerLoad.
2280 if (S.beginOffset() < AllocBeginOffset)
2281 return false;
2282 // Note that we don't count vector loads or stores as whole-alloca
2283 // operations which enable integer widening because we would prefer to use
2284 // vector widening instead.
2285 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
2286 WholeAllocaOp = true;
2287 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2288 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedValue())
2289 return false;
2290 } else if (RelBegin != 0 || RelEnd != Size ||
2291 !canConvertValue(DL, AllocaTy, LI->getType())) {
2292 // Non-integer loads need to be convertible from the alloca type so that
2293 // they are promotable.
2294 return false;
2295 }
2296 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2297 Type *ValueTy = SI->getValueOperand()->getType();
2298 if (SI->isVolatile())
2299 return false;
2300 // We can't handle stores that extend past the allocated memory.
2301 if (DL.getTypeStoreSize(ValueTy).getFixedValue() > Size)
2302 return false;
2303 // So far, AllocaSliceRewriter does not support widening split slice tails
2304 // in rewriteIntegerStore.
2305 if (S.beginOffset() < AllocBeginOffset)
2306 return false;
2307 // Note that we don't count vector loads or stores as whole-alloca
2308 // operations which enable integer widening because we would prefer to use
2309 // vector widening instead.
2310 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
2311 WholeAllocaOp = true;
2312 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2313 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedValue())
2314 return false;
2315 } else if (RelBegin != 0 || RelEnd != Size ||
2316 !canConvertValue(DL, ValueTy, AllocaTy)) {
2317 // Non-integer stores need to be convertible to the alloca type so that
2318 // they are promotable.
2319 return false;
2320 }
2321 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2322 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2323 return false;
2324 if (!S.isSplittable())
2325 return false; // Skip any unsplittable intrinsics.
2326 } else {
2327 return false;
2328 }
2329
2330 return true;
2331 }
2332
2333 /// Test whether the given alloca partition's integer operations can be
2334 /// widened to promotable ones.
2335 ///
2336 /// This is a quick test to check whether we can rewrite the integer loads and
2337 /// stores to a particular alloca into wider loads and stores and be able to
2338 /// promote the resulting alloca.
isIntegerWideningViable(Partition & P,Type * AllocaTy,const DataLayout & DL)2339 static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
2340 const DataLayout &DL) {
2341 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy).getFixedValue();
2342 // Don't create integer types larger than the maximum bitwidth.
2343 if (SizeInBits > IntegerType::MAX_INT_BITS)
2344 return false;
2345
2346 // Don't try to handle allocas with bit-padding.
2347 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy).getFixedValue())
2348 return false;
2349
2350 // We need to ensure that an integer type with the appropriate bitwidth can
2351 // be converted to the alloca type, whatever that is. We don't want to force
2352 // the alloca itself to have an integer type if there is a more suitable one.
2353 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2354 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2355 !canConvertValue(DL, IntTy, AllocaTy))
2356 return false;
2357
2358 // While examining uses, we ensure that the alloca has a covering load or
2359 // store. We don't want to widen the integer operations only to fail to
2360 // promote due to some other unsplittable entry (which we may make splittable
2361 // later). However, if there are only splittable uses, go ahead and assume
2362 // that we cover the alloca.
2363 // FIXME: We shouldn't consider split slices that happen to start in the
2364 // partition here...
2365 bool WholeAllocaOp = P.empty() && DL.isLegalInteger(SizeInBits);
2366
2367 for (const Slice &S : P)
2368 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2369 WholeAllocaOp))
2370 return false;
2371
2372 for (const Slice *S : P.splitSliceTails())
2373 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2374 WholeAllocaOp))
2375 return false;
2376
2377 return WholeAllocaOp;
2378 }
2379
extractInteger(const DataLayout & DL,IRBuilderTy & IRB,Value * V,IntegerType * Ty,uint64_t Offset,const Twine & Name)2380 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2381 IntegerType *Ty, uint64_t Offset,
2382 const Twine &Name) {
2383 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
2384 IntegerType *IntTy = cast<IntegerType>(V->getType());
2385 assert(DL.getTypeStoreSize(Ty).getFixedValue() + Offset <=
2386 DL.getTypeStoreSize(IntTy).getFixedValue() &&
2387 "Element extends past full value");
2388 uint64_t ShAmt = 8 * Offset;
2389 if (DL.isBigEndian())
2390 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedValue() -
2391 DL.getTypeStoreSize(Ty).getFixedValue() - Offset);
2392 if (ShAmt) {
2393 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2394 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
2395 }
2396 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2397 "Cannot extract to a larger integer!");
2398 if (Ty != IntTy) {
2399 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2400 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n");
2401 }
2402 return V;
2403 }
2404
insertInteger(const DataLayout & DL,IRBuilderTy & IRB,Value * Old,Value * V,uint64_t Offset,const Twine & Name)2405 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2406 Value *V, uint64_t Offset, const Twine &Name) {
2407 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2408 IntegerType *Ty = cast<IntegerType>(V->getType());
2409 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2410 "Cannot insert a larger integer!");
2411 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
2412 if (Ty != IntTy) {
2413 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2414 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n");
2415 }
2416 assert(DL.getTypeStoreSize(Ty).getFixedValue() + Offset <=
2417 DL.getTypeStoreSize(IntTy).getFixedValue() &&
2418 "Element store outside of alloca store");
2419 uint64_t ShAmt = 8 * Offset;
2420 if (DL.isBigEndian())
2421 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedValue() -
2422 DL.getTypeStoreSize(Ty).getFixedValue() - Offset);
2423 if (ShAmt) {
2424 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2425 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
2426 }
2427
2428 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2429 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2430 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2431 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n");
2432 V = IRB.CreateOr(Old, V, Name + ".insert");
2433 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n");
2434 }
2435 return V;
2436 }
2437
extractVector(IRBuilderTy & IRB,Value * V,unsigned BeginIndex,unsigned EndIndex,const Twine & Name)2438 static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2439 unsigned EndIndex, const Twine &Name) {
2440 auto *VecTy = cast<FixedVectorType>(V->getType());
2441 unsigned NumElements = EndIndex - BeginIndex;
2442 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2443
2444 if (NumElements == VecTy->getNumElements())
2445 return V;
2446
2447 if (NumElements == 1) {
2448 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2449 Name + ".extract");
2450 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n");
2451 return V;
2452 }
2453
2454 auto Mask = llvm::to_vector<8>(llvm::seq<int>(BeginIndex, EndIndex));
2455 V = IRB.CreateShuffleVector(V, Mask, Name + ".extract");
2456 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
2457 return V;
2458 }
2459
insertVector(IRBuilderTy & IRB,Value * Old,Value * V,unsigned BeginIndex,const Twine & Name)2460 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2461 unsigned BeginIndex, const Twine &Name) {
2462 VectorType *VecTy = cast<VectorType>(Old->getType());
2463 assert(VecTy && "Can only insert a vector into a vector");
2464
2465 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2466 if (!Ty) {
2467 // Single element to insert.
2468 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2469 Name + ".insert");
2470 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n");
2471 return V;
2472 }
2473
2474 assert(cast<FixedVectorType>(Ty)->getNumElements() <=
2475 cast<FixedVectorType>(VecTy)->getNumElements() &&
2476 "Too many elements!");
2477 if (cast<FixedVectorType>(Ty)->getNumElements() ==
2478 cast<FixedVectorType>(VecTy)->getNumElements()) {
2479 assert(V->getType() == VecTy && "Vector type mismatch");
2480 return V;
2481 }
2482 unsigned EndIndex = BeginIndex + cast<FixedVectorType>(Ty)->getNumElements();
2483
2484 // When inserting a smaller vector into the larger to store, we first
2485 // use a shuffle vector to widen it with undef elements, and then
2486 // a second shuffle vector to select between the loaded vector and the
2487 // incoming vector.
2488 SmallVector<int, 8> Mask;
2489 Mask.reserve(cast<FixedVectorType>(VecTy)->getNumElements());
2490 for (unsigned i = 0; i != cast<FixedVectorType>(VecTy)->getNumElements(); ++i)
2491 if (i >= BeginIndex && i < EndIndex)
2492 Mask.push_back(i - BeginIndex);
2493 else
2494 Mask.push_back(-1);
2495 V = IRB.CreateShuffleVector(V, Mask, Name + ".expand");
2496 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
2497
2498 SmallVector<Constant *, 8> Mask2;
2499 Mask2.reserve(cast<FixedVectorType>(VecTy)->getNumElements());
2500 for (unsigned i = 0; i != cast<FixedVectorType>(VecTy)->getNumElements(); ++i)
2501 Mask2.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2502
2503 V = IRB.CreateSelect(ConstantVector::get(Mask2), V, Old, Name + "blend");
2504
2505 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n");
2506 return V;
2507 }
2508
2509 /// Visitor to rewrite instructions using p particular slice of an alloca
2510 /// to use a new alloca.
2511 ///
2512 /// Also implements the rewriting to vector-based accesses when the partition
2513 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2514 /// lives here.
2515 class llvm::sroa::AllocaSliceRewriter
2516 : public InstVisitor<AllocaSliceRewriter, bool> {
2517 // Befriend the base class so it can delegate to private visit methods.
2518 friend class InstVisitor<AllocaSliceRewriter, bool>;
2519
2520 using Base = InstVisitor<AllocaSliceRewriter, bool>;
2521
2522 const DataLayout &DL;
2523 AllocaSlices &AS;
2524 SROAPass &Pass;
2525 AllocaInst &OldAI, &NewAI;
2526 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2527 Type *NewAllocaTy;
2528
2529 // This is a convenience and flag variable that will be null unless the new
2530 // alloca's integer operations should be widened to this integer type due to
2531 // passing isIntegerWideningViable above. If it is non-null, the desired
2532 // integer type will be stored here for easy access during rewriting.
2533 IntegerType *IntTy;
2534
2535 // If we are rewriting an alloca partition which can be written as pure
2536 // vector operations, we stash extra information here. When VecTy is
2537 // non-null, we have some strict guarantees about the rewritten alloca:
2538 // - The new alloca is exactly the size of the vector type here.
2539 // - The accesses all either map to the entire vector or to a single
2540 // element.
2541 // - The set of accessing instructions is only one of those handled above
2542 // in isVectorPromotionViable. Generally these are the same access kinds
2543 // which are promotable via mem2reg.
2544 VectorType *VecTy;
2545 Type *ElementTy;
2546 uint64_t ElementSize;
2547
2548 // The original offset of the slice currently being rewritten relative to
2549 // the original alloca.
2550 uint64_t BeginOffset = 0;
2551 uint64_t EndOffset = 0;
2552
2553 // The new offsets of the slice currently being rewritten relative to the
2554 // original alloca.
2555 uint64_t NewBeginOffset = 0, NewEndOffset = 0;
2556
2557 uint64_t RelativeOffset = 0;
2558 uint64_t SliceSize = 0;
2559 bool IsSplittable = false;
2560 bool IsSplit = false;
2561 Use *OldUse = nullptr;
2562 Instruction *OldPtr = nullptr;
2563
2564 // Track post-rewrite users which are PHI nodes and Selects.
2565 SmallSetVector<PHINode *, 8> &PHIUsers;
2566 SmallSetVector<SelectInst *, 8> &SelectUsers;
2567
2568 // Utility IR builder, whose name prefix is setup for each visited use, and
2569 // the insertion point is set to point to the user.
2570 IRBuilderTy IRB;
2571
2572 // Return the new alloca, addrspacecasted if required to avoid changing the
2573 // addrspace of a volatile access.
getPtrToNewAI(unsigned AddrSpace,bool IsVolatile)2574 Value *getPtrToNewAI(unsigned AddrSpace, bool IsVolatile) {
2575 if (!IsVolatile || AddrSpace == NewAI.getType()->getPointerAddressSpace())
2576 return &NewAI;
2577
2578 Type *AccessTy = NewAI.getAllocatedType()->getPointerTo(AddrSpace);
2579 return IRB.CreateAddrSpaceCast(&NewAI, AccessTy);
2580 }
2581
2582 public:
AllocaSliceRewriter(const DataLayout & DL,AllocaSlices & AS,SROAPass & Pass,AllocaInst & OldAI,AllocaInst & NewAI,uint64_t NewAllocaBeginOffset,uint64_t NewAllocaEndOffset,bool IsIntegerPromotable,VectorType * PromotableVecTy,SmallSetVector<PHINode *,8> & PHIUsers,SmallSetVector<SelectInst *,8> & SelectUsers)2583 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROAPass &Pass,
2584 AllocaInst &OldAI, AllocaInst &NewAI,
2585 uint64_t NewAllocaBeginOffset,
2586 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2587 VectorType *PromotableVecTy,
2588 SmallSetVector<PHINode *, 8> &PHIUsers,
2589 SmallSetVector<SelectInst *, 8> &SelectUsers)
2590 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2591 NewAllocaBeginOffset(NewAllocaBeginOffset),
2592 NewAllocaEndOffset(NewAllocaEndOffset),
2593 NewAllocaTy(NewAI.getAllocatedType()),
2594 IntTy(
2595 IsIntegerPromotable
2596 ? Type::getIntNTy(NewAI.getContext(),
2597 DL.getTypeSizeInBits(NewAI.getAllocatedType())
2598 .getFixedValue())
2599 : nullptr),
2600 VecTy(PromotableVecTy),
2601 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2602 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy).getFixedValue() / 8
2603 : 0),
2604 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2605 IRB(NewAI.getContext(), ConstantFolder()) {
2606 if (VecTy) {
2607 assert((DL.getTypeSizeInBits(ElementTy).getFixedValue() % 8) == 0 &&
2608 "Only multiple-of-8 sized vector elements are viable");
2609 ++NumVectorized;
2610 }
2611 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2612 }
2613
visit(AllocaSlices::const_iterator I)2614 bool visit(AllocaSlices::const_iterator I) {
2615 bool CanSROA = true;
2616 BeginOffset = I->beginOffset();
2617 EndOffset = I->endOffset();
2618 IsSplittable = I->isSplittable();
2619 IsSplit =
2620 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2621 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2622 LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
2623 LLVM_DEBUG(dbgs() << "\n");
2624
2625 // Compute the intersecting offset range.
2626 assert(BeginOffset < NewAllocaEndOffset);
2627 assert(EndOffset > NewAllocaBeginOffset);
2628 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2629 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2630
2631 RelativeOffset = NewBeginOffset - BeginOffset;
2632 SliceSize = NewEndOffset - NewBeginOffset;
2633 LLVM_DEBUG(dbgs() << " Begin:(" << BeginOffset << ", " << EndOffset
2634 << ") NewBegin:(" << NewBeginOffset << ", "
2635 << NewEndOffset << ") NewAllocaBegin:("
2636 << NewAllocaBeginOffset << ", " << NewAllocaEndOffset
2637 << ")\n");
2638 assert(IsSplit || RelativeOffset == 0);
2639 OldUse = I->getUse();
2640 OldPtr = cast<Instruction>(OldUse->get());
2641
2642 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2643 IRB.SetInsertPoint(OldUserI);
2644 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2645 IRB.getInserter().SetNamePrefix(
2646 Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2647
2648 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2649 if (VecTy || IntTy)
2650 assert(CanSROA);
2651 return CanSROA;
2652 }
2653
2654 private:
2655 // Make sure the other visit overloads are visible.
2656 using Base::visit;
2657
2658 // Every instruction which can end up as a user must have a rewrite rule.
visitInstruction(Instruction & I)2659 bool visitInstruction(Instruction &I) {
2660 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2661 llvm_unreachable("No rewrite rule for this instruction!");
2662 }
2663
getNewAllocaSlicePtr(IRBuilderTy & IRB,Type * PointerTy)2664 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2665 // Note that the offset computation can use BeginOffset or NewBeginOffset
2666 // interchangeably for unsplit slices.
2667 assert(IsSplit || BeginOffset == NewBeginOffset);
2668 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2669
2670 #ifndef NDEBUG
2671 StringRef OldName = OldPtr->getName();
2672 // Skip through the last '.sroa.' component of the name.
2673 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2674 if (LastSROAPrefix != StringRef::npos) {
2675 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2676 // Look for an SROA slice index.
2677 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2678 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2679 // Strip the index and look for the offset.
2680 OldName = OldName.substr(IndexEnd + 1);
2681 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2682 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2683 // Strip the offset.
2684 OldName = OldName.substr(OffsetEnd + 1);
2685 }
2686 }
2687 // Strip any SROA suffixes as well.
2688 OldName = OldName.substr(0, OldName.find(".sroa_"));
2689 #endif
2690
2691 return getAdjustedPtr(IRB, DL, &NewAI,
2692 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
2693 PointerTy,
2694 #ifndef NDEBUG
2695 Twine(OldName) + "."
2696 #else
2697 Twine()
2698 #endif
2699 );
2700 }
2701
2702 /// Compute suitable alignment to access this slice of the *new*
2703 /// alloca.
2704 ///
2705 /// You can optionally pass a type to this routine and if that type's ABI
2706 /// alignment is itself suitable, this will return zero.
getSliceAlign()2707 Align getSliceAlign() {
2708 return commonAlignment(NewAI.getAlign(),
2709 NewBeginOffset - NewAllocaBeginOffset);
2710 }
2711
getIndex(uint64_t Offset)2712 unsigned getIndex(uint64_t Offset) {
2713 assert(VecTy && "Can only call getIndex when rewriting a vector");
2714 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2715 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2716 uint32_t Index = RelOffset / ElementSize;
2717 assert(Index * ElementSize == RelOffset);
2718 return Index;
2719 }
2720
deleteIfTriviallyDead(Value * V)2721 void deleteIfTriviallyDead(Value *V) {
2722 Instruction *I = cast<Instruction>(V);
2723 if (isInstructionTriviallyDead(I))
2724 Pass.DeadInsts.push_back(I);
2725 }
2726
rewriteVectorizedLoadInst(LoadInst & LI)2727 Value *rewriteVectorizedLoadInst(LoadInst &LI) {
2728 unsigned BeginIndex = getIndex(NewBeginOffset);
2729 unsigned EndIndex = getIndex(NewEndOffset);
2730 assert(EndIndex > BeginIndex && "Empty vector!");
2731
2732 LoadInst *Load = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2733 NewAI.getAlign(), "load");
2734
2735 Load->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
2736 LLVMContext::MD_access_group});
2737 return extractVector(IRB, Load, BeginIndex, EndIndex, "vec");
2738 }
2739
rewriteIntegerLoad(LoadInst & LI)2740 Value *rewriteIntegerLoad(LoadInst &LI) {
2741 assert(IntTy && "We cannot insert an integer to the alloca");
2742 assert(!LI.isVolatile());
2743 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2744 NewAI.getAlign(), "load");
2745 V = convertValue(DL, IRB, V, IntTy);
2746 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2747 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2748 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2749 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2750 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2751 }
2752 // It is possible that the extracted type is not the load type. This
2753 // happens if there is a load past the end of the alloca, and as
2754 // a consequence the slice is narrower but still a candidate for integer
2755 // lowering. To handle this case, we just zero extend the extracted
2756 // integer.
2757 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2758 "Can only handle an extract for an overly wide load");
2759 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2760 V = IRB.CreateZExt(V, LI.getType());
2761 return V;
2762 }
2763
visitLoadInst(LoadInst & LI)2764 bool visitLoadInst(LoadInst &LI) {
2765 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
2766 Value *OldOp = LI.getOperand(0);
2767 assert(OldOp == OldPtr);
2768
2769 AAMDNodes AATags = LI.getAAMetadata();
2770
2771 unsigned AS = LI.getPointerAddressSpace();
2772
2773 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2774 : LI.getType();
2775 const bool IsLoadPastEnd =
2776 DL.getTypeStoreSize(TargetTy).getFixedValue() > SliceSize;
2777 bool IsPtrAdjusted = false;
2778 Value *V;
2779 if (VecTy) {
2780 V = rewriteVectorizedLoadInst(LI);
2781 } else if (IntTy && LI.getType()->isIntegerTy()) {
2782 V = rewriteIntegerLoad(LI);
2783 } else if (NewBeginOffset == NewAllocaBeginOffset &&
2784 NewEndOffset == NewAllocaEndOffset &&
2785 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2786 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2787 TargetTy->isIntegerTy()))) {
2788 Value *NewPtr =
2789 getPtrToNewAI(LI.getPointerAddressSpace(), LI.isVolatile());
2790 LoadInst *NewLI = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), NewPtr,
2791 NewAI.getAlign(), LI.isVolatile(),
2792 LI.getName());
2793 if (LI.isVolatile())
2794 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
2795 if (NewLI->isAtomic())
2796 NewLI->setAlignment(LI.getAlign());
2797
2798 // Copy any metadata that is valid for the new load. This may require
2799 // conversion to a different kind of metadata, e.g. !nonnull might change
2800 // to !range or vice versa.
2801 copyMetadataForLoad(*NewLI, LI);
2802
2803 // Do this after copyMetadataForLoad() to preserve the TBAA shift.
2804 if (AATags)
2805 NewLI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2806
2807 // Try to preserve nonnull metadata
2808 V = NewLI;
2809
2810 // If this is an integer load past the end of the slice (which means the
2811 // bytes outside the slice are undef or this load is dead) just forcibly
2812 // fix the integer size with correct handling of endianness.
2813 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2814 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2815 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2816 V = IRB.CreateZExt(V, TITy, "load.ext");
2817 if (DL.isBigEndian())
2818 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2819 "endian_shift");
2820 }
2821 } else {
2822 Type *LTy = TargetTy->getPointerTo(AS);
2823 LoadInst *NewLI =
2824 IRB.CreateAlignedLoad(TargetTy, getNewAllocaSlicePtr(IRB, LTy),
2825 getSliceAlign(), LI.isVolatile(), LI.getName());
2826 if (AATags)
2827 NewLI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2828 if (LI.isVolatile())
2829 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
2830 NewLI->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
2831 LLVMContext::MD_access_group});
2832
2833 V = NewLI;
2834 IsPtrAdjusted = true;
2835 }
2836 V = convertValue(DL, IRB, V, TargetTy);
2837
2838 if (IsSplit) {
2839 assert(!LI.isVolatile());
2840 assert(LI.getType()->isIntegerTy() &&
2841 "Only integer type loads and stores are split");
2842 assert(SliceSize < DL.getTypeStoreSize(LI.getType()).getFixedValue() &&
2843 "Split load isn't smaller than original load");
2844 assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&
2845 "Non-byte-multiple bit width");
2846 // Move the insertion point just past the load so that we can refer to it.
2847 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
2848 // Create a placeholder value with the same type as LI to use as the
2849 // basis for the new value. This allows us to replace the uses of LI with
2850 // the computed value, and then replace the placeholder with LI, leaving
2851 // LI only used for this computation.
2852 Value *Placeholder = new LoadInst(
2853 LI.getType(), PoisonValue::get(LI.getType()->getPointerTo(AS)), "",
2854 false, Align(1));
2855 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2856 "insert");
2857 LI.replaceAllUsesWith(V);
2858 Placeholder->replaceAllUsesWith(&LI);
2859 Placeholder->deleteValue();
2860 } else {
2861 LI.replaceAllUsesWith(V);
2862 }
2863
2864 Pass.DeadInsts.push_back(&LI);
2865 deleteIfTriviallyDead(OldOp);
2866 LLVM_DEBUG(dbgs() << " to: " << *V << "\n");
2867 return !LI.isVolatile() && !IsPtrAdjusted;
2868 }
2869
rewriteVectorizedStoreInst(Value * V,StoreInst & SI,Value * OldOp,AAMDNodes AATags)2870 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2871 AAMDNodes AATags) {
2872 // Capture V for the purpose of debug-info accounting once it's converted
2873 // to a vector store.
2874 Value *OrigV = V;
2875 if (V->getType() != VecTy) {
2876 unsigned BeginIndex = getIndex(NewBeginOffset);
2877 unsigned EndIndex = getIndex(NewEndOffset);
2878 assert(EndIndex > BeginIndex && "Empty vector!");
2879 unsigned NumElements = EndIndex - BeginIndex;
2880 assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
2881 "Too many elements!");
2882 Type *SliceTy = (NumElements == 1)
2883 ? ElementTy
2884 : FixedVectorType::get(ElementTy, NumElements);
2885 if (V->getType() != SliceTy)
2886 V = convertValue(DL, IRB, V, SliceTy);
2887
2888 // Mix in the existing elements.
2889 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2890 NewAI.getAlign(), "load");
2891 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2892 }
2893 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
2894 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2895 LLVMContext::MD_access_group});
2896 if (AATags)
2897 Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2898 Pass.DeadInsts.push_back(&SI);
2899
2900 // NOTE: Careful to use OrigV rather than V.
2901 migrateDebugInfo(&OldAI, RelativeOffset * 8, SliceSize * 8, &SI, Store,
2902 Store->getPointerOperand(), OrigV, DL);
2903 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
2904 return true;
2905 }
2906
rewriteIntegerStore(Value * V,StoreInst & SI,AAMDNodes AATags)2907 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
2908 assert(IntTy && "We cannot extract an integer from the alloca");
2909 assert(!SI.isVolatile());
2910 if (DL.getTypeSizeInBits(V->getType()).getFixedValue() !=
2911 IntTy->getBitWidth()) {
2912 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2913 NewAI.getAlign(), "oldload");
2914 Old = convertValue(DL, IRB, Old, IntTy);
2915 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2916 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2917 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
2918 }
2919 V = convertValue(DL, IRB, V, NewAllocaTy);
2920 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
2921 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2922 LLVMContext::MD_access_group});
2923 if (AATags)
2924 Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
2925
2926 migrateDebugInfo(&OldAI, RelativeOffset * 8, SliceSize * 8, &SI, Store,
2927 Store->getPointerOperand(), Store->getValueOperand(), DL);
2928
2929 Pass.DeadInsts.push_back(&SI);
2930 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
2931 return true;
2932 }
2933
visitStoreInst(StoreInst & SI)2934 bool visitStoreInst(StoreInst &SI) {
2935 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
2936 Value *OldOp = SI.getOperand(1);
2937 assert(OldOp == OldPtr);
2938
2939 AAMDNodes AATags = SI.getAAMetadata();
2940 Value *V = SI.getValueOperand();
2941
2942 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2943 // alloca that should be re-examined after promoting this alloca.
2944 if (V->getType()->isPointerTy())
2945 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2946 Pass.PostPromotionWorklist.insert(AI);
2947
2948 if (SliceSize < DL.getTypeStoreSize(V->getType()).getFixedValue()) {
2949 assert(!SI.isVolatile());
2950 assert(V->getType()->isIntegerTy() &&
2951 "Only integer type loads and stores are split");
2952 assert(DL.typeSizeEqualsStoreSize(V->getType()) &&
2953 "Non-byte-multiple bit width");
2954 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2955 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2956 "extract");
2957 }
2958
2959 if (VecTy)
2960 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
2961 if (IntTy && V->getType()->isIntegerTy())
2962 return rewriteIntegerStore(V, SI, AATags);
2963
2964 const bool IsStorePastEnd =
2965 DL.getTypeStoreSize(V->getType()).getFixedValue() > SliceSize;
2966 StoreInst *NewSI;
2967 if (NewBeginOffset == NewAllocaBeginOffset &&
2968 NewEndOffset == NewAllocaEndOffset &&
2969 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2970 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2971 V->getType()->isIntegerTy()))) {
2972 // If this is an integer store past the end of slice (and thus the bytes
2973 // past that point are irrelevant or this is unreachable), truncate the
2974 // value prior to storing.
2975 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2976 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2977 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2978 if (DL.isBigEndian())
2979 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2980 "endian_shift");
2981 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2982 }
2983
2984 V = convertValue(DL, IRB, V, NewAllocaTy);
2985 Value *NewPtr =
2986 getPtrToNewAI(SI.getPointerAddressSpace(), SI.isVolatile());
2987
2988 NewSI =
2989 IRB.CreateAlignedStore(V, NewPtr, NewAI.getAlign(), SI.isVolatile());
2990 } else {
2991 unsigned AS = SI.getPointerAddressSpace();
2992 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
2993 NewSI =
2994 IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(), SI.isVolatile());
2995 }
2996 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2997 LLVMContext::MD_access_group});
2998 if (AATags)
2999 NewSI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
3000 if (SI.isVolatile())
3001 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
3002 if (NewSI->isAtomic())
3003 NewSI->setAlignment(SI.getAlign());
3004
3005 migrateDebugInfo(&OldAI, RelativeOffset * 8, SliceSize * 8, &SI, NewSI,
3006 NewSI->getPointerOperand(), NewSI->getValueOperand(), DL);
3007
3008 Pass.DeadInsts.push_back(&SI);
3009 deleteIfTriviallyDead(OldOp);
3010
3011 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n");
3012 return NewSI->getPointerOperand() == &NewAI &&
3013 NewSI->getValueOperand()->getType() == NewAllocaTy &&
3014 !SI.isVolatile();
3015 }
3016
3017 /// Compute an integer value from splatting an i8 across the given
3018 /// number of bytes.
3019 ///
3020 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
3021 /// call this routine.
3022 /// FIXME: Heed the advice above.
3023 ///
3024 /// \param V The i8 value to splat.
3025 /// \param Size The number of bytes in the output (assuming i8 is one byte)
getIntegerSplat(Value * V,unsigned Size)3026 Value *getIntegerSplat(Value *V, unsigned Size) {
3027 assert(Size > 0 && "Expected a positive number of bytes.");
3028 IntegerType *VTy = cast<IntegerType>(V->getType());
3029 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
3030 if (Size == 1)
3031 return V;
3032
3033 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
3034 V = IRB.CreateMul(
3035 IRB.CreateZExt(V, SplatIntTy, "zext"),
3036 IRB.CreateUDiv(Constant::getAllOnesValue(SplatIntTy),
3037 IRB.CreateZExt(Constant::getAllOnesValue(V->getType()),
3038 SplatIntTy)),
3039 "isplat");
3040 return V;
3041 }
3042
3043 /// Compute a vector splat for a given element value.
getVectorSplat(Value * V,unsigned NumElements)3044 Value *getVectorSplat(Value *V, unsigned NumElements) {
3045 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
3046 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n");
3047 return V;
3048 }
3049
visitMemSetInst(MemSetInst & II)3050 bool visitMemSetInst(MemSetInst &II) {
3051 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
3052 assert(II.getRawDest() == OldPtr);
3053
3054 AAMDNodes AATags = II.getAAMetadata();
3055
3056 // If the memset has a variable size, it cannot be split, just adjust the
3057 // pointer to the new alloca.
3058 if (!isa<ConstantInt>(II.getLength())) {
3059 assert(!IsSplit);
3060 assert(NewBeginOffset == BeginOffset);
3061 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
3062 II.setDestAlignment(getSliceAlign());
3063 // In theory we should call migrateDebugInfo here. However, we do not
3064 // emit dbg.assign intrinsics for mem intrinsics storing through non-
3065 // constant geps, or storing a variable number of bytes.
3066 assert(at::getAssignmentMarkers(&II).empty() &&
3067 "AT: Unexpected link to non-const GEP");
3068 deleteIfTriviallyDead(OldPtr);
3069 return false;
3070 }
3071
3072 // Record this instruction for deletion.
3073 Pass.DeadInsts.push_back(&II);
3074
3075 Type *AllocaTy = NewAI.getAllocatedType();
3076 Type *ScalarTy = AllocaTy->getScalarType();
3077
3078 const bool CanContinue = [&]() {
3079 if (VecTy || IntTy)
3080 return true;
3081 if (BeginOffset > NewAllocaBeginOffset ||
3082 EndOffset < NewAllocaEndOffset)
3083 return false;
3084 // Length must be in range for FixedVectorType.
3085 auto *C = cast<ConstantInt>(II.getLength());
3086 const uint64_t Len = C->getLimitedValue();
3087 if (Len > std::numeric_limits<unsigned>::max())
3088 return false;
3089 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
3090 auto *SrcTy = FixedVectorType::get(Int8Ty, Len);
3091 return canConvertValue(DL, SrcTy, AllocaTy) &&
3092 DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy).getFixedValue());
3093 }();
3094
3095 // If this doesn't map cleanly onto the alloca type, and that type isn't
3096 // a single value type, just emit a memset.
3097 if (!CanContinue) {
3098 Type *SizeTy = II.getLength()->getType();
3099 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
3100 MemIntrinsic *New = cast<MemIntrinsic>(IRB.CreateMemSet(
3101 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
3102 MaybeAlign(getSliceAlign()), II.isVolatile()));
3103 if (AATags)
3104 New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
3105
3106 migrateDebugInfo(&OldAI, RelativeOffset * 8, SliceSize * 8, &II, New,
3107 New->getRawDest(), nullptr, DL);
3108
3109 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
3110 return false;
3111 }
3112
3113 // If we can represent this as a simple value, we have to build the actual
3114 // value to store, which requires expanding the byte present in memset to
3115 // a sensible representation for the alloca type. This is essentially
3116 // splatting the byte to a sufficiently wide integer, splatting it across
3117 // any desired vector width, and bitcasting to the final type.
3118 Value *V;
3119
3120 if (VecTy) {
3121 // If this is a memset of a vectorized alloca, insert it.
3122 assert(ElementTy == ScalarTy);
3123
3124 unsigned BeginIndex = getIndex(NewBeginOffset);
3125 unsigned EndIndex = getIndex(NewEndOffset);
3126 assert(EndIndex > BeginIndex && "Empty vector!");
3127 unsigned NumElements = EndIndex - BeginIndex;
3128 assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
3129 "Too many elements!");
3130
3131 Value *Splat = getIntegerSplat(
3132 II.getValue(), DL.getTypeSizeInBits(ElementTy).getFixedValue() / 8);
3133 Splat = convertValue(DL, IRB, Splat, ElementTy);
3134 if (NumElements > 1)
3135 Splat = getVectorSplat(Splat, NumElements);
3136
3137 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3138 NewAI.getAlign(), "oldload");
3139 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
3140 } else if (IntTy) {
3141 // If this is a memset on an alloca where we can widen stores, insert the
3142 // set integer.
3143 assert(!II.isVolatile());
3144
3145 uint64_t Size = NewEndOffset - NewBeginOffset;
3146 V = getIntegerSplat(II.getValue(), Size);
3147
3148 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
3149 EndOffset != NewAllocaBeginOffset)) {
3150 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3151 NewAI.getAlign(), "oldload");
3152 Old = convertValue(DL, IRB, Old, IntTy);
3153 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3154 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
3155 } else {
3156 assert(V->getType() == IntTy &&
3157 "Wrong type for an alloca wide integer!");
3158 }
3159 V = convertValue(DL, IRB, V, AllocaTy);
3160 } else {
3161 // Established these invariants above.
3162 assert(NewBeginOffset == NewAllocaBeginOffset);
3163 assert(NewEndOffset == NewAllocaEndOffset);
3164
3165 V = getIntegerSplat(II.getValue(),
3166 DL.getTypeSizeInBits(ScalarTy).getFixedValue() / 8);
3167 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
3168 V = getVectorSplat(
3169 V, cast<FixedVectorType>(AllocaVecTy)->getNumElements());
3170
3171 V = convertValue(DL, IRB, V, AllocaTy);
3172 }
3173
3174 Value *NewPtr = getPtrToNewAI(II.getDestAddressSpace(), II.isVolatile());
3175 StoreInst *New =
3176 IRB.CreateAlignedStore(V, NewPtr, NewAI.getAlign(), II.isVolatile());
3177 New->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
3178 LLVMContext::MD_access_group});
3179 if (AATags)
3180 New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
3181
3182 migrateDebugInfo(&OldAI, RelativeOffset * 8, SliceSize * 8, &II, New,
3183 New->getPointerOperand(), V, DL);
3184
3185 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
3186 return !II.isVolatile();
3187 }
3188
visitMemTransferInst(MemTransferInst & II)3189 bool visitMemTransferInst(MemTransferInst &II) {
3190 // Rewriting of memory transfer instructions can be a bit tricky. We break
3191 // them into two categories: split intrinsics and unsplit intrinsics.
3192
3193 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
3194
3195 AAMDNodes AATags = II.getAAMetadata();
3196
3197 bool IsDest = &II.getRawDestUse() == OldUse;
3198 assert((IsDest && II.getRawDest() == OldPtr) ||
3199 (!IsDest && II.getRawSource() == OldPtr));
3200
3201 Align SliceAlign = getSliceAlign();
3202 // For unsplit intrinsics, we simply modify the source and destination
3203 // pointers in place. This isn't just an optimization, it is a matter of
3204 // correctness. With unsplit intrinsics we may be dealing with transfers
3205 // within a single alloca before SROA ran, or with transfers that have
3206 // a variable length. We may also be dealing with memmove instead of
3207 // memcpy, and so simply updating the pointers is the necessary for us to
3208 // update both source and dest of a single call.
3209 if (!IsSplittable) {
3210 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3211 if (IsDest) {
3212 // Update the address component of linked dbg.assigns.
3213 for (auto *DAI : at::getAssignmentMarkers(&II)) {
3214 if (any_of(DAI->location_ops(),
3215 [&](Value *V) { return V == II.getDest(); }) ||
3216 DAI->getAddress() == II.getDest())
3217 DAI->replaceVariableLocationOp(II.getDest(), AdjustedPtr);
3218 }
3219 II.setDest(AdjustedPtr);
3220 II.setDestAlignment(SliceAlign);
3221 } else {
3222 II.setSource(AdjustedPtr);
3223 II.setSourceAlignment(SliceAlign);
3224 }
3225
3226 LLVM_DEBUG(dbgs() << " to: " << II << "\n");
3227 deleteIfTriviallyDead(OldPtr);
3228 return false;
3229 }
3230 // For split transfer intrinsics we have an incredibly useful assurance:
3231 // the source and destination do not reside within the same alloca, and at
3232 // least one of them does not escape. This means that we can replace
3233 // memmove with memcpy, and we don't need to worry about all manner of
3234 // downsides to splitting and transforming the operations.
3235
3236 // If this doesn't map cleanly onto the alloca type, and that type isn't
3237 // a single value type, just emit a memcpy.
3238 bool EmitMemCpy =
3239 !VecTy && !IntTy &&
3240 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
3241 SliceSize !=
3242 DL.getTypeStoreSize(NewAI.getAllocatedType()).getFixedValue() ||
3243 !NewAI.getAllocatedType()->isSingleValueType());
3244
3245 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
3246 // size hasn't been shrunk based on analysis of the viable range, this is
3247 // a no-op.
3248 if (EmitMemCpy && &OldAI == &NewAI) {
3249 // Ensure the start lines up.
3250 assert(NewBeginOffset == BeginOffset);
3251
3252 // Rewrite the size as needed.
3253 if (NewEndOffset != EndOffset)
3254 II.setLength(ConstantInt::get(II.getLength()->getType(),
3255 NewEndOffset - NewBeginOffset));
3256 return false;
3257 }
3258 // Record this instruction for deletion.
3259 Pass.DeadInsts.push_back(&II);
3260
3261 // Strip all inbounds GEPs and pointer casts to try to dig out any root
3262 // alloca that should be re-examined after rewriting this instruction.
3263 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
3264 if (AllocaInst *AI =
3265 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
3266 assert(AI != &OldAI && AI != &NewAI &&
3267 "Splittable transfers cannot reach the same alloca on both ends.");
3268 Pass.Worklist.insert(AI);
3269 }
3270
3271 Type *OtherPtrTy = OtherPtr->getType();
3272 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
3273
3274 // Compute the relative offset for the other pointer within the transfer.
3275 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
3276 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
3277 Align OtherAlign =
3278 (IsDest ? II.getSourceAlign() : II.getDestAlign()).valueOrOne();
3279 OtherAlign =
3280 commonAlignment(OtherAlign, OtherOffset.zextOrTrunc(64).getZExtValue());
3281
3282 if (EmitMemCpy) {
3283 // Compute the other pointer, folding as much as possible to produce
3284 // a single, simple GEP in most cases.
3285 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
3286 OtherPtr->getName() + ".");
3287
3288 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3289 Type *SizeTy = II.getLength()->getType();
3290 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
3291
3292 Value *DestPtr, *SrcPtr;
3293 MaybeAlign DestAlign, SrcAlign;
3294 // Note: IsDest is true iff we're copying into the new alloca slice
3295 if (IsDest) {
3296 DestPtr = OurPtr;
3297 DestAlign = SliceAlign;
3298 SrcPtr = OtherPtr;
3299 SrcAlign = OtherAlign;
3300 } else {
3301 DestPtr = OtherPtr;
3302 DestAlign = OtherAlign;
3303 SrcPtr = OurPtr;
3304 SrcAlign = SliceAlign;
3305 }
3306 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
3307 Size, II.isVolatile());
3308 if (AATags)
3309 New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
3310
3311 migrateDebugInfo(&OldAI, RelativeOffset * 8, SliceSize * 8, &II, New,
3312 DestPtr, nullptr, DL);
3313 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
3314 return false;
3315 }
3316
3317 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
3318 NewEndOffset == NewAllocaEndOffset;
3319 uint64_t Size = NewEndOffset - NewBeginOffset;
3320 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
3321 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
3322 unsigned NumElements = EndIndex - BeginIndex;
3323 IntegerType *SubIntTy =
3324 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
3325
3326 // Reset the other pointer type to match the register type we're going to
3327 // use, but using the address space of the original other pointer.
3328 Type *OtherTy;
3329 if (VecTy && !IsWholeAlloca) {
3330 if (NumElements == 1)
3331 OtherTy = VecTy->getElementType();
3332 else
3333 OtherTy = FixedVectorType::get(VecTy->getElementType(), NumElements);
3334 } else if (IntTy && !IsWholeAlloca) {
3335 OtherTy = SubIntTy;
3336 } else {
3337 OtherTy = NewAllocaTy;
3338 }
3339 OtherPtrTy = OtherTy->getPointerTo(OtherAS);
3340
3341 Value *AdjPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
3342 OtherPtr->getName() + ".");
3343 MaybeAlign SrcAlign = OtherAlign;
3344 MaybeAlign DstAlign = SliceAlign;
3345 if (!IsDest)
3346 std::swap(SrcAlign, DstAlign);
3347
3348 Value *SrcPtr;
3349 Value *DstPtr;
3350
3351 if (IsDest) {
3352 DstPtr = getPtrToNewAI(II.getDestAddressSpace(), II.isVolatile());
3353 SrcPtr = AdjPtr;
3354 } else {
3355 DstPtr = AdjPtr;
3356 SrcPtr = getPtrToNewAI(II.getSourceAddressSpace(), II.isVolatile());
3357 }
3358
3359 Value *Src;
3360 if (VecTy && !IsWholeAlloca && !IsDest) {
3361 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3362 NewAI.getAlign(), "load");
3363 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
3364 } else if (IntTy && !IsWholeAlloca && !IsDest) {
3365 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3366 NewAI.getAlign(), "load");
3367 Src = convertValue(DL, IRB, Src, IntTy);
3368 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3369 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
3370 } else {
3371 LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
3372 II.isVolatile(), "copyload");
3373 Load->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
3374 LLVMContext::MD_access_group});
3375 if (AATags)
3376 Load->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
3377 Src = Load;
3378 }
3379
3380 if (VecTy && !IsWholeAlloca && IsDest) {
3381 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3382 NewAI.getAlign(), "oldload");
3383 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
3384 } else if (IntTy && !IsWholeAlloca && IsDest) {
3385 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3386 NewAI.getAlign(), "oldload");
3387 Old = convertValue(DL, IRB, Old, IntTy);
3388 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3389 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3390 Src = convertValue(DL, IRB, Src, NewAllocaTy);
3391 }
3392
3393 StoreInst *Store = cast<StoreInst>(
3394 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
3395 Store->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
3396 LLVMContext::MD_access_group});
3397 if (AATags)
3398 Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
3399
3400 migrateDebugInfo(&OldAI, RelativeOffset * 8, SliceSize * 8, &II, Store,
3401 DstPtr, Src, DL);
3402 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
3403 return !II.isVolatile();
3404 }
3405
visitIntrinsicInst(IntrinsicInst & II)3406 bool visitIntrinsicInst(IntrinsicInst &II) {
3407 assert((II.isLifetimeStartOrEnd() || II.isDroppable()) &&
3408 "Unexpected intrinsic!");
3409 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
3410
3411 // Record this instruction for deletion.
3412 Pass.DeadInsts.push_back(&II);
3413
3414 if (II.isDroppable()) {
3415 assert(II.getIntrinsicID() == Intrinsic::assume && "Expected assume");
3416 // TODO For now we forget assumed information, this can be improved.
3417 OldPtr->dropDroppableUsesIn(II);
3418 return true;
3419 }
3420
3421 assert(II.getArgOperand(1) == OldPtr);
3422 // Lifetime intrinsics are only promotable if they cover the whole alloca.
3423 // Therefore, we drop lifetime intrinsics which don't cover the whole
3424 // alloca.
3425 // (In theory, intrinsics which partially cover an alloca could be
3426 // promoted, but PromoteMemToReg doesn't handle that case.)
3427 // FIXME: Check whether the alloca is promotable before dropping the
3428 // lifetime intrinsics?
3429 if (NewBeginOffset != NewAllocaBeginOffset ||
3430 NewEndOffset != NewAllocaEndOffset)
3431 return true;
3432
3433 ConstantInt *Size =
3434 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
3435 NewEndOffset - NewBeginOffset);
3436 // Lifetime intrinsics always expect an i8* so directly get such a pointer
3437 // for the new alloca slice.
3438 Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace());
3439 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
3440 Value *New;
3441 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3442 New = IRB.CreateLifetimeStart(Ptr, Size);
3443 else
3444 New = IRB.CreateLifetimeEnd(Ptr, Size);
3445
3446 (void)New;
3447 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
3448
3449 return true;
3450 }
3451
fixLoadStoreAlign(Instruction & Root)3452 void fixLoadStoreAlign(Instruction &Root) {
3453 // This algorithm implements the same visitor loop as
3454 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
3455 // or store found.
3456 SmallPtrSet<Instruction *, 4> Visited;
3457 SmallVector<Instruction *, 4> Uses;
3458 Visited.insert(&Root);
3459 Uses.push_back(&Root);
3460 do {
3461 Instruction *I = Uses.pop_back_val();
3462
3463 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3464 LI->setAlignment(std::min(LI->getAlign(), getSliceAlign()));
3465 continue;
3466 }
3467 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3468 SI->setAlignment(std::min(SI->getAlign(), getSliceAlign()));
3469 continue;
3470 }
3471
3472 assert(isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) ||
3473 isa<PHINode>(I) || isa<SelectInst>(I) ||
3474 isa<GetElementPtrInst>(I));
3475 for (User *U : I->users())
3476 if (Visited.insert(cast<Instruction>(U)).second)
3477 Uses.push_back(cast<Instruction>(U));
3478 } while (!Uses.empty());
3479 }
3480
visitPHINode(PHINode & PN)3481 bool visitPHINode(PHINode &PN) {
3482 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
3483 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3484 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
3485
3486 // We would like to compute a new pointer in only one place, but have it be
3487 // as local as possible to the PHI. To do that, we re-use the location of
3488 // the old pointer, which necessarily must be in the right position to
3489 // dominate the PHI.
3490 IRBuilderBase::InsertPointGuard Guard(IRB);
3491 if (isa<PHINode>(OldPtr))
3492 IRB.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
3493 else
3494 IRB.SetInsertPoint(OldPtr);
3495 IRB.SetCurrentDebugLocation(OldPtr->getDebugLoc());
3496
3497 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3498 // Replace the operands which were using the old pointer.
3499 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3500
3501 LLVM_DEBUG(dbgs() << " to: " << PN << "\n");
3502 deleteIfTriviallyDead(OldPtr);
3503
3504 // Fix the alignment of any loads or stores using this PHI node.
3505 fixLoadStoreAlign(PN);
3506
3507 // PHIs can't be promoted on their own, but often can be speculated. We
3508 // check the speculation outside of the rewriter so that we see the
3509 // fully-rewritten alloca.
3510 PHIUsers.insert(&PN);
3511 return true;
3512 }
3513
visitSelectInst(SelectInst & SI)3514 bool visitSelectInst(SelectInst &SI) {
3515 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
3516 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3517 "Pointer isn't an operand!");
3518 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3519 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
3520
3521 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3522 // Replace the operands which were using the old pointer.
3523 if (SI.getOperand(1) == OldPtr)
3524 SI.setOperand(1, NewPtr);
3525 if (SI.getOperand(2) == OldPtr)
3526 SI.setOperand(2, NewPtr);
3527
3528 LLVM_DEBUG(dbgs() << " to: " << SI << "\n");
3529 deleteIfTriviallyDead(OldPtr);
3530
3531 // Fix the alignment of any loads or stores using this select.
3532 fixLoadStoreAlign(SI);
3533
3534 // Selects can't be promoted on their own, but often can be speculated. We
3535 // check the speculation outside of the rewriter so that we see the
3536 // fully-rewritten alloca.
3537 SelectUsers.insert(&SI);
3538 return true;
3539 }
3540 };
3541
3542 namespace {
3543
3544 /// Visitor to rewrite aggregate loads and stores as scalar.
3545 ///
3546 /// This pass aggressively rewrites all aggregate loads and stores on
3547 /// a particular pointer (or any pointer derived from it which we can identify)
3548 /// with scalar loads and stores.
3549 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3550 // Befriend the base class so it can delegate to private visit methods.
3551 friend class InstVisitor<AggLoadStoreRewriter, bool>;
3552
3553 /// Queue of pointer uses to analyze and potentially rewrite.
3554 SmallVector<Use *, 8> Queue;
3555
3556 /// Set to prevent us from cycling with phi nodes and loops.
3557 SmallPtrSet<User *, 8> Visited;
3558
3559 /// The current pointer use being rewritten. This is used to dig up the used
3560 /// value (as opposed to the user).
3561 Use *U = nullptr;
3562
3563 /// Used to calculate offsets, and hence alignment, of subobjects.
3564 const DataLayout &DL;
3565
3566 IRBuilderTy &IRB;
3567
3568 public:
AggLoadStoreRewriter(const DataLayout & DL,IRBuilderTy & IRB)3569 AggLoadStoreRewriter(const DataLayout &DL, IRBuilderTy &IRB)
3570 : DL(DL), IRB(IRB) {}
3571
3572 /// Rewrite loads and stores through a pointer and all pointers derived from
3573 /// it.
rewrite(Instruction & I)3574 bool rewrite(Instruction &I) {
3575 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3576 enqueueUsers(I);
3577 bool Changed = false;
3578 while (!Queue.empty()) {
3579 U = Queue.pop_back_val();
3580 Changed |= visit(cast<Instruction>(U->getUser()));
3581 }
3582 return Changed;
3583 }
3584
3585 private:
3586 /// Enqueue all the users of the given instruction for further processing.
3587 /// This uses a set to de-duplicate users.
enqueueUsers(Instruction & I)3588 void enqueueUsers(Instruction &I) {
3589 for (Use &U : I.uses())
3590 if (Visited.insert(U.getUser()).second)
3591 Queue.push_back(&U);
3592 }
3593
3594 // Conservative default is to not rewrite anything.
visitInstruction(Instruction & I)3595 bool visitInstruction(Instruction &I) { return false; }
3596
3597 /// Generic recursive split emission class.
3598 template <typename Derived> class OpSplitter {
3599 protected:
3600 /// The builder used to form new instructions.
3601 IRBuilderTy &IRB;
3602
3603 /// The indices which to be used with insert- or extractvalue to select the
3604 /// appropriate value within the aggregate.
3605 SmallVector<unsigned, 4> Indices;
3606
3607 /// The indices to a GEP instruction which will move Ptr to the correct slot
3608 /// within the aggregate.
3609 SmallVector<Value *, 4> GEPIndices;
3610
3611 /// The base pointer of the original op, used as a base for GEPing the
3612 /// split operations.
3613 Value *Ptr;
3614
3615 /// The base pointee type being GEPed into.
3616 Type *BaseTy;
3617
3618 /// Known alignment of the base pointer.
3619 Align BaseAlign;
3620
3621 /// To calculate offset of each component so we can correctly deduce
3622 /// alignments.
3623 const DataLayout &DL;
3624
3625 /// Initialize the splitter with an insertion point, Ptr and start with a
3626 /// single zero GEP index.
OpSplitter(Instruction * InsertionPoint,Value * Ptr,Type * BaseTy,Align BaseAlign,const DataLayout & DL,IRBuilderTy & IRB)3627 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3628 Align BaseAlign, const DataLayout &DL, IRBuilderTy &IRB)
3629 : IRB(IRB), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr), BaseTy(BaseTy),
3630 BaseAlign(BaseAlign), DL(DL) {
3631 IRB.SetInsertPoint(InsertionPoint);
3632 }
3633
3634 public:
3635 /// Generic recursive split emission routine.
3636 ///
3637 /// This method recursively splits an aggregate op (load or store) into
3638 /// scalar or vector ops. It splits recursively until it hits a single value
3639 /// and emits that single value operation via the template argument.
3640 ///
3641 /// The logic of this routine relies on GEPs and insertvalue and
3642 /// extractvalue all operating with the same fundamental index list, merely
3643 /// formatted differently (GEPs need actual values).
3644 ///
3645 /// \param Ty The type being split recursively into smaller ops.
3646 /// \param Agg The aggregate value being built up or stored, depending on
3647 /// whether this is splitting a load or a store respectively.
emitSplitOps(Type * Ty,Value * & Agg,const Twine & Name)3648 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3649 if (Ty->isSingleValueType()) {
3650 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
3651 return static_cast<Derived *>(this)->emitFunc(
3652 Ty, Agg, commonAlignment(BaseAlign, Offset), Name);
3653 }
3654
3655 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3656 unsigned OldSize = Indices.size();
3657 (void)OldSize;
3658 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3659 ++Idx) {
3660 assert(Indices.size() == OldSize && "Did not return to the old size");
3661 Indices.push_back(Idx);
3662 GEPIndices.push_back(IRB.getInt32(Idx));
3663 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3664 GEPIndices.pop_back();
3665 Indices.pop_back();
3666 }
3667 return;
3668 }
3669
3670 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3671 unsigned OldSize = Indices.size();
3672 (void)OldSize;
3673 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3674 ++Idx) {
3675 assert(Indices.size() == OldSize && "Did not return to the old size");
3676 Indices.push_back(Idx);
3677 GEPIndices.push_back(IRB.getInt32(Idx));
3678 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3679 GEPIndices.pop_back();
3680 Indices.pop_back();
3681 }
3682 return;
3683 }
3684
3685 llvm_unreachable("Only arrays and structs are aggregate loadable types");
3686 }
3687 };
3688
3689 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3690 AAMDNodes AATags;
3691
LoadOpSplitter__anon54bbb7c80c11::AggLoadStoreRewriter::LoadOpSplitter3692 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3693 AAMDNodes AATags, Align BaseAlign, const DataLayout &DL,
3694 IRBuilderTy &IRB)
3695 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, DL,
3696 IRB),
3697 AATags(AATags) {}
3698
3699 /// Emit a leaf load of a single value. This is called at the leaves of the
3700 /// recursive emission to actually load values.
emitFunc__anon54bbb7c80c11::AggLoadStoreRewriter::LoadOpSplitter3701 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
3702 assert(Ty->isSingleValueType());
3703 // Load the single value and insert it using the indices.
3704 Value *GEP =
3705 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
3706 LoadInst *Load =
3707 IRB.CreateAlignedLoad(Ty, GEP, Alignment, Name + ".load");
3708
3709 APInt Offset(
3710 DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
3711 if (AATags &&
3712 GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset))
3713 Load->setAAMetadata(AATags.shift(Offset.getZExtValue()));
3714
3715 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3716 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n");
3717 }
3718 };
3719
visitLoadInst(LoadInst & LI)3720 bool visitLoadInst(LoadInst &LI) {
3721 assert(LI.getPointerOperand() == *U);
3722 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3723 return false;
3724
3725 // We have an aggregate being loaded, split it apart.
3726 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
3727 LoadOpSplitter Splitter(&LI, *U, LI.getType(), LI.getAAMetadata(),
3728 getAdjustedAlignment(&LI, 0), DL, IRB);
3729 Value *V = PoisonValue::get(LI.getType());
3730 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3731 Visited.erase(&LI);
3732 LI.replaceAllUsesWith(V);
3733 LI.eraseFromParent();
3734 return true;
3735 }
3736
3737 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
StoreOpSplitter__anon54bbb7c80c11::AggLoadStoreRewriter::StoreOpSplitter3738 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3739 AAMDNodes AATags, StoreInst *AggStore, Align BaseAlign,
3740 const DataLayout &DL, IRBuilderTy &IRB)
3741 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3742 DL, IRB),
3743 AATags(AATags), AggStore(AggStore) {}
3744 AAMDNodes AATags;
3745 StoreInst *AggStore;
3746 /// Emit a leaf store of a single value. This is called at the leaves of the
3747 /// recursive emission to actually produce stores.
emitFunc__anon54bbb7c80c11::AggLoadStoreRewriter::StoreOpSplitter3748 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
3749 assert(Ty->isSingleValueType());
3750 // Extract the single value and store it using the indices.
3751 //
3752 // The gep and extractvalue values are factored out of the CreateStore
3753 // call to make the output independent of the argument evaluation order.
3754 Value *ExtractValue =
3755 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3756 Value *InBoundsGEP =
3757 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
3758 StoreInst *Store =
3759 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Alignment);
3760
3761 APInt Offset(
3762 DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
3763 if (AATags &&
3764 GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset))
3765 Store->setAAMetadata(AATags.shift(Offset.getZExtValue()));
3766
3767 // migrateDebugInfo requires the base Alloca. Walk to it from this gep.
3768 // If we cannot (because there's an intervening non-const or unbounded
3769 // gep) then we wouldn't expect to see dbg.assign intrinsics linked to
3770 // this instruction.
3771 APInt OffsetInBytes(DL.getTypeSizeInBits(Ptr->getType()), false);
3772 Value *Base = InBoundsGEP->stripAndAccumulateInBoundsConstantOffsets(
3773 DL, OffsetInBytes);
3774 if (auto *OldAI = dyn_cast<AllocaInst>(Base)) {
3775 uint64_t SizeInBits =
3776 DL.getTypeSizeInBits(Store->getValueOperand()->getType());
3777 migrateDebugInfo(OldAI, OffsetInBytes.getZExtValue() * 8, SizeInBits,
3778 AggStore, Store, Store->getPointerOperand(),
3779 Store->getValueOperand(), DL);
3780 } else {
3781 assert(at::getAssignmentMarkers(Store).empty() &&
3782 "AT: unexpected debug.assign linked to store through "
3783 "unbounded GEP");
3784 }
3785 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
3786 }
3787 };
3788
visitStoreInst(StoreInst & SI)3789 bool visitStoreInst(StoreInst &SI) {
3790 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3791 return false;
3792 Value *V = SI.getValueOperand();
3793 if (V->getType()->isSingleValueType())
3794 return false;
3795
3796 // We have an aggregate being stored, split it apart.
3797 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
3798 StoreOpSplitter Splitter(&SI, *U, V->getType(), SI.getAAMetadata(), &SI,
3799 getAdjustedAlignment(&SI, 0), DL, IRB);
3800 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3801 Visited.erase(&SI);
3802 SI.eraseFromParent();
3803 return true;
3804 }
3805
visitBitCastInst(BitCastInst & BC)3806 bool visitBitCastInst(BitCastInst &BC) {
3807 enqueueUsers(BC);
3808 return false;
3809 }
3810
visitAddrSpaceCastInst(AddrSpaceCastInst & ASC)3811 bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
3812 enqueueUsers(ASC);
3813 return false;
3814 }
3815
3816 // Fold gep (select cond, ptr1, ptr2) => select cond, gep(ptr1), gep(ptr2)
foldGEPSelect(GetElementPtrInst & GEPI)3817 bool foldGEPSelect(GetElementPtrInst &GEPI) {
3818 if (!GEPI.hasAllConstantIndices())
3819 return false;
3820
3821 SelectInst *Sel = cast<SelectInst>(GEPI.getPointerOperand());
3822
3823 LLVM_DEBUG(dbgs() << " Rewriting gep(select) -> select(gep):"
3824 << "\n original: " << *Sel
3825 << "\n " << GEPI);
3826
3827 IRB.SetInsertPoint(&GEPI);
3828 SmallVector<Value *, 4> Index(GEPI.indices());
3829 bool IsInBounds = GEPI.isInBounds();
3830
3831 Type *Ty = GEPI.getSourceElementType();
3832 Value *True = Sel->getTrueValue();
3833 Value *NTrue = IRB.CreateGEP(Ty, True, Index, True->getName() + ".sroa.gep",
3834 IsInBounds);
3835
3836 Value *False = Sel->getFalseValue();
3837
3838 Value *NFalse = IRB.CreateGEP(Ty, False, Index,
3839 False->getName() + ".sroa.gep", IsInBounds);
3840
3841 Value *NSel = IRB.CreateSelect(Sel->getCondition(), NTrue, NFalse,
3842 Sel->getName() + ".sroa.sel");
3843 Visited.erase(&GEPI);
3844 GEPI.replaceAllUsesWith(NSel);
3845 GEPI.eraseFromParent();
3846 Instruction *NSelI = cast<Instruction>(NSel);
3847 Visited.insert(NSelI);
3848 enqueueUsers(*NSelI);
3849
3850 LLVM_DEBUG(dbgs() << "\n to: " << *NTrue
3851 << "\n " << *NFalse
3852 << "\n " << *NSel << '\n');
3853
3854 return true;
3855 }
3856
3857 // Fold gep (phi ptr1, ptr2) => phi gep(ptr1), gep(ptr2)
foldGEPPhi(GetElementPtrInst & GEPI)3858 bool foldGEPPhi(GetElementPtrInst &GEPI) {
3859 if (!GEPI.hasAllConstantIndices())
3860 return false;
3861
3862 PHINode *PHI = cast<PHINode>(GEPI.getPointerOperand());
3863 if (GEPI.getParent() != PHI->getParent() ||
3864 llvm::any_of(PHI->incoming_values(), [](Value *In)
3865 { Instruction *I = dyn_cast<Instruction>(In);
3866 return !I || isa<GetElementPtrInst>(I) || isa<PHINode>(I) ||
3867 succ_empty(I->getParent()) ||
3868 !I->getParent()->isLegalToHoistInto();
3869 }))
3870 return false;
3871
3872 LLVM_DEBUG(dbgs() << " Rewriting gep(phi) -> phi(gep):"
3873 << "\n original: " << *PHI
3874 << "\n " << GEPI
3875 << "\n to: ");
3876
3877 SmallVector<Value *, 4> Index(GEPI.indices());
3878 bool IsInBounds = GEPI.isInBounds();
3879 IRB.SetInsertPoint(GEPI.getParent()->getFirstNonPHI());
3880 PHINode *NewPN = IRB.CreatePHI(GEPI.getType(), PHI->getNumIncomingValues(),
3881 PHI->getName() + ".sroa.phi");
3882 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I != E; ++I) {
3883 BasicBlock *B = PHI->getIncomingBlock(I);
3884 Value *NewVal = nullptr;
3885 int Idx = NewPN->getBasicBlockIndex(B);
3886 if (Idx >= 0) {
3887 NewVal = NewPN->getIncomingValue(Idx);
3888 } else {
3889 Instruction *In = cast<Instruction>(PHI->getIncomingValue(I));
3890
3891 IRB.SetInsertPoint(In->getParent(), std::next(In->getIterator()));
3892 Type *Ty = GEPI.getSourceElementType();
3893 NewVal = IRB.CreateGEP(Ty, In, Index, In->getName() + ".sroa.gep",
3894 IsInBounds);
3895 }
3896 NewPN->addIncoming(NewVal, B);
3897 }
3898
3899 Visited.erase(&GEPI);
3900 GEPI.replaceAllUsesWith(NewPN);
3901 GEPI.eraseFromParent();
3902 Visited.insert(NewPN);
3903 enqueueUsers(*NewPN);
3904
3905 LLVM_DEBUG(for (Value *In : NewPN->incoming_values())
3906 dbgs() << "\n " << *In;
3907 dbgs() << "\n " << *NewPN << '\n');
3908
3909 return true;
3910 }
3911
visitGetElementPtrInst(GetElementPtrInst & GEPI)3912 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3913 if (isa<SelectInst>(GEPI.getPointerOperand()) &&
3914 foldGEPSelect(GEPI))
3915 return true;
3916
3917 if (isa<PHINode>(GEPI.getPointerOperand()) &&
3918 foldGEPPhi(GEPI))
3919 return true;
3920
3921 enqueueUsers(GEPI);
3922 return false;
3923 }
3924
visitPHINode(PHINode & PN)3925 bool visitPHINode(PHINode &PN) {
3926 enqueueUsers(PN);
3927 return false;
3928 }
3929
visitSelectInst(SelectInst & SI)3930 bool visitSelectInst(SelectInst &SI) {
3931 enqueueUsers(SI);
3932 return false;
3933 }
3934 };
3935
3936 } // end anonymous namespace
3937
3938 /// Strip aggregate type wrapping.
3939 ///
3940 /// This removes no-op aggregate types wrapping an underlying type. It will
3941 /// strip as many layers of types as it can without changing either the type
3942 /// size or the allocated size.
stripAggregateTypeWrapping(const DataLayout & DL,Type * Ty)3943 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3944 if (Ty->isSingleValueType())
3945 return Ty;
3946
3947 uint64_t AllocSize = DL.getTypeAllocSize(Ty).getFixedValue();
3948 uint64_t TypeSize = DL.getTypeSizeInBits(Ty).getFixedValue();
3949
3950 Type *InnerTy;
3951 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3952 InnerTy = ArrTy->getElementType();
3953 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3954 const StructLayout *SL = DL.getStructLayout(STy);
3955 unsigned Index = SL->getElementContainingOffset(0);
3956 InnerTy = STy->getElementType(Index);
3957 } else {
3958 return Ty;
3959 }
3960
3961 if (AllocSize > DL.getTypeAllocSize(InnerTy).getFixedValue() ||
3962 TypeSize > DL.getTypeSizeInBits(InnerTy).getFixedValue())
3963 return Ty;
3964
3965 return stripAggregateTypeWrapping(DL, InnerTy);
3966 }
3967
3968 /// Try to find a partition of the aggregate type passed in for a given
3969 /// offset and size.
3970 ///
3971 /// This recurses through the aggregate type and tries to compute a subtype
3972 /// based on the offset and size. When the offset and size span a sub-section
3973 /// of an array, it will even compute a new array type for that sub-section,
3974 /// and the same for structs.
3975 ///
3976 /// Note that this routine is very strict and tries to find a partition of the
3977 /// type which produces the *exact* right offset and size. It is not forgiving
3978 /// when the size or offset cause either end of type-based partition to be off.
3979 /// Also, this is a best-effort routine. It is reasonable to give up and not
3980 /// return a type if necessary.
getTypePartition(const DataLayout & DL,Type * Ty,uint64_t Offset,uint64_t Size)3981 static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3982 uint64_t Size) {
3983 if (Offset == 0 && DL.getTypeAllocSize(Ty).getFixedValue() == Size)
3984 return stripAggregateTypeWrapping(DL, Ty);
3985 if (Offset > DL.getTypeAllocSize(Ty).getFixedValue() ||
3986 (DL.getTypeAllocSize(Ty).getFixedValue() - Offset) < Size)
3987 return nullptr;
3988
3989 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
3990 Type *ElementTy;
3991 uint64_t TyNumElements;
3992 if (auto *AT = dyn_cast<ArrayType>(Ty)) {
3993 ElementTy = AT->getElementType();
3994 TyNumElements = AT->getNumElements();
3995 } else {
3996 // FIXME: This isn't right for vectors with non-byte-sized or
3997 // non-power-of-two sized elements.
3998 auto *VT = cast<FixedVectorType>(Ty);
3999 ElementTy = VT->getElementType();
4000 TyNumElements = VT->getNumElements();
4001 }
4002 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedValue();
4003 uint64_t NumSkippedElements = Offset / ElementSize;
4004 if (NumSkippedElements >= TyNumElements)
4005 return nullptr;
4006 Offset -= NumSkippedElements * ElementSize;
4007
4008 // First check if we need to recurse.
4009 if (Offset > 0 || Size < ElementSize) {
4010 // Bail if the partition ends in a different array element.
4011 if ((Offset + Size) > ElementSize)
4012 return nullptr;
4013 // Recurse through the element type trying to peel off offset bytes.
4014 return getTypePartition(DL, ElementTy, Offset, Size);
4015 }
4016 assert(Offset == 0);
4017
4018 if (Size == ElementSize)
4019 return stripAggregateTypeWrapping(DL, ElementTy);
4020 assert(Size > ElementSize);
4021 uint64_t NumElements = Size / ElementSize;
4022 if (NumElements * ElementSize != Size)
4023 return nullptr;
4024 return ArrayType::get(ElementTy, NumElements);
4025 }
4026
4027 StructType *STy = dyn_cast<StructType>(Ty);
4028 if (!STy)
4029 return nullptr;
4030
4031 const StructLayout *SL = DL.getStructLayout(STy);
4032 if (Offset >= SL->getSizeInBytes())
4033 return nullptr;
4034 uint64_t EndOffset = Offset + Size;
4035 if (EndOffset > SL->getSizeInBytes())
4036 return nullptr;
4037
4038 unsigned Index = SL->getElementContainingOffset(Offset);
4039 Offset -= SL->getElementOffset(Index);
4040
4041 Type *ElementTy = STy->getElementType(Index);
4042 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedValue();
4043 if (Offset >= ElementSize)
4044 return nullptr; // The offset points into alignment padding.
4045
4046 // See if any partition must be contained by the element.
4047 if (Offset > 0 || Size < ElementSize) {
4048 if ((Offset + Size) > ElementSize)
4049 return nullptr;
4050 return getTypePartition(DL, ElementTy, Offset, Size);
4051 }
4052 assert(Offset == 0);
4053
4054 if (Size == ElementSize)
4055 return stripAggregateTypeWrapping(DL, ElementTy);
4056
4057 StructType::element_iterator EI = STy->element_begin() + Index,
4058 EE = STy->element_end();
4059 if (EndOffset < SL->getSizeInBytes()) {
4060 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
4061 if (Index == EndIndex)
4062 return nullptr; // Within a single element and its padding.
4063
4064 // Don't try to form "natural" types if the elements don't line up with the
4065 // expected size.
4066 // FIXME: We could potentially recurse down through the last element in the
4067 // sub-struct to find a natural end point.
4068 if (SL->getElementOffset(EndIndex) != EndOffset)
4069 return nullptr;
4070
4071 assert(Index < EndIndex);
4072 EE = STy->element_begin() + EndIndex;
4073 }
4074
4075 // Try to build up a sub-structure.
4076 StructType *SubTy =
4077 StructType::get(STy->getContext(), ArrayRef(EI, EE), STy->isPacked());
4078 const StructLayout *SubSL = DL.getStructLayout(SubTy);
4079 if (Size != SubSL->getSizeInBytes())
4080 return nullptr; // The sub-struct doesn't have quite the size needed.
4081
4082 return SubTy;
4083 }
4084
4085 /// Pre-split loads and stores to simplify rewriting.
4086 ///
4087 /// We want to break up the splittable load+store pairs as much as
4088 /// possible. This is important to do as a preprocessing step, as once we
4089 /// start rewriting the accesses to partitions of the alloca we lose the
4090 /// necessary information to correctly split apart paired loads and stores
4091 /// which both point into this alloca. The case to consider is something like
4092 /// the following:
4093 ///
4094 /// %a = alloca [12 x i8]
4095 /// %gep1 = getelementptr i8, ptr %a, i32 0
4096 /// %gep2 = getelementptr i8, ptr %a, i32 4
4097 /// %gep3 = getelementptr i8, ptr %a, i32 8
4098 /// store float 0.0, ptr %gep1
4099 /// store float 1.0, ptr %gep2
4100 /// %v = load i64, ptr %gep1
4101 /// store i64 %v, ptr %gep2
4102 /// %f1 = load float, ptr %gep2
4103 /// %f2 = load float, ptr %gep3
4104 ///
4105 /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
4106 /// promote everything so we recover the 2 SSA values that should have been
4107 /// there all along.
4108 ///
4109 /// \returns true if any changes are made.
presplitLoadsAndStores(AllocaInst & AI,AllocaSlices & AS)4110 bool SROAPass::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
4111 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
4112
4113 // Track the loads and stores which are candidates for pre-splitting here, in
4114 // the order they first appear during the partition scan. These give stable
4115 // iteration order and a basis for tracking which loads and stores we
4116 // actually split.
4117 SmallVector<LoadInst *, 4> Loads;
4118 SmallVector<StoreInst *, 4> Stores;
4119
4120 // We need to accumulate the splits required of each load or store where we
4121 // can find them via a direct lookup. This is important to cross-check loads
4122 // and stores against each other. We also track the slice so that we can kill
4123 // all the slices that end up split.
4124 struct SplitOffsets {
4125 Slice *S;
4126 std::vector<uint64_t> Splits;
4127 };
4128 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
4129
4130 // Track loads out of this alloca which cannot, for any reason, be pre-split.
4131 // This is important as we also cannot pre-split stores of those loads!
4132 // FIXME: This is all pretty gross. It means that we can be more aggressive
4133 // in pre-splitting when the load feeding the store happens to come from
4134 // a separate alloca. Put another way, the effectiveness of SROA would be
4135 // decreased by a frontend which just concatenated all of its local allocas
4136 // into one big flat alloca. But defeating such patterns is exactly the job
4137 // SROA is tasked with! Sadly, to not have this discrepancy we would have
4138 // change store pre-splitting to actually force pre-splitting of the load
4139 // that feeds it *and all stores*. That makes pre-splitting much harder, but
4140 // maybe it would make it more principled?
4141 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
4142
4143 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n");
4144 for (auto &P : AS.partitions()) {
4145 for (Slice &S : P) {
4146 Instruction *I = cast<Instruction>(S.getUse()->getUser());
4147 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
4148 // If this is a load we have to track that it can't participate in any
4149 // pre-splitting. If this is a store of a load we have to track that
4150 // that load also can't participate in any pre-splitting.
4151 if (auto *LI = dyn_cast<LoadInst>(I))
4152 UnsplittableLoads.insert(LI);
4153 else if (auto *SI = dyn_cast<StoreInst>(I))
4154 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
4155 UnsplittableLoads.insert(LI);
4156 continue;
4157 }
4158 assert(P.endOffset() > S.beginOffset() &&
4159 "Empty or backwards partition!");
4160
4161 // Determine if this is a pre-splittable slice.
4162 if (auto *LI = dyn_cast<LoadInst>(I)) {
4163 assert(!LI->isVolatile() && "Cannot split volatile loads!");
4164
4165 // The load must be used exclusively to store into other pointers for
4166 // us to be able to arbitrarily pre-split it. The stores must also be
4167 // simple to avoid changing semantics.
4168 auto IsLoadSimplyStored = [](LoadInst *LI) {
4169 for (User *LU : LI->users()) {
4170 auto *SI = dyn_cast<StoreInst>(LU);
4171 if (!SI || !SI->isSimple())
4172 return false;
4173 }
4174 return true;
4175 };
4176 if (!IsLoadSimplyStored(LI)) {
4177 UnsplittableLoads.insert(LI);
4178 continue;
4179 }
4180
4181 Loads.push_back(LI);
4182 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
4183 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
4184 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
4185 continue;
4186 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
4187 if (!StoredLoad || !StoredLoad->isSimple())
4188 continue;
4189 assert(!SI->isVolatile() && "Cannot split volatile stores!");
4190
4191 Stores.push_back(SI);
4192 } else {
4193 // Other uses cannot be pre-split.
4194 continue;
4195 }
4196
4197 // Record the initial split.
4198 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n");
4199 auto &Offsets = SplitOffsetsMap[I];
4200 assert(Offsets.Splits.empty() &&
4201 "Should not have splits the first time we see an instruction!");
4202 Offsets.S = &S;
4203 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
4204 }
4205
4206 // Now scan the already split slices, and add a split for any of them which
4207 // we're going to pre-split.
4208 for (Slice *S : P.splitSliceTails()) {
4209 auto SplitOffsetsMapI =
4210 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
4211 if (SplitOffsetsMapI == SplitOffsetsMap.end())
4212 continue;
4213 auto &Offsets = SplitOffsetsMapI->second;
4214
4215 assert(Offsets.S == S && "Found a mismatched slice!");
4216 assert(!Offsets.Splits.empty() &&
4217 "Cannot have an empty set of splits on the second partition!");
4218 assert(Offsets.Splits.back() ==
4219 P.beginOffset() - Offsets.S->beginOffset() &&
4220 "Previous split does not end where this one begins!");
4221
4222 // Record each split. The last partition's end isn't needed as the size
4223 // of the slice dictates that.
4224 if (S->endOffset() > P.endOffset())
4225 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
4226 }
4227 }
4228
4229 // We may have split loads where some of their stores are split stores. For
4230 // such loads and stores, we can only pre-split them if their splits exactly
4231 // match relative to their starting offset. We have to verify this prior to
4232 // any rewriting.
4233 llvm::erase_if(Stores, [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
4234 // Lookup the load we are storing in our map of split
4235 // offsets.
4236 auto *LI = cast<LoadInst>(SI->getValueOperand());
4237 // If it was completely unsplittable, then we're done,
4238 // and this store can't be pre-split.
4239 if (UnsplittableLoads.count(LI))
4240 return true;
4241
4242 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
4243 if (LoadOffsetsI == SplitOffsetsMap.end())
4244 return false; // Unrelated loads are definitely safe.
4245 auto &LoadOffsets = LoadOffsetsI->second;
4246
4247 // Now lookup the store's offsets.
4248 auto &StoreOffsets = SplitOffsetsMap[SI];
4249
4250 // If the relative offsets of each split in the load and
4251 // store match exactly, then we can split them and we
4252 // don't need to remove them here.
4253 if (LoadOffsets.Splits == StoreOffsets.Splits)
4254 return false;
4255
4256 LLVM_DEBUG(dbgs() << " Mismatched splits for load and store:\n"
4257 << " " << *LI << "\n"
4258 << " " << *SI << "\n");
4259
4260 // We've found a store and load that we need to split
4261 // with mismatched relative splits. Just give up on them
4262 // and remove both instructions from our list of
4263 // candidates.
4264 UnsplittableLoads.insert(LI);
4265 return true;
4266 });
4267 // Now we have to go *back* through all the stores, because a later store may
4268 // have caused an earlier store's load to become unsplittable and if it is
4269 // unsplittable for the later store, then we can't rely on it being split in
4270 // the earlier store either.
4271 llvm::erase_if(Stores, [&UnsplittableLoads](StoreInst *SI) {
4272 auto *LI = cast<LoadInst>(SI->getValueOperand());
4273 return UnsplittableLoads.count(LI);
4274 });
4275 // Once we've established all the loads that can't be split for some reason,
4276 // filter any that made it into our list out.
4277 llvm::erase_if(Loads, [&UnsplittableLoads](LoadInst *LI) {
4278 return UnsplittableLoads.count(LI);
4279 });
4280
4281 // If no loads or stores are left, there is no pre-splitting to be done for
4282 // this alloca.
4283 if (Loads.empty() && Stores.empty())
4284 return false;
4285
4286 // From here on, we can't fail and will be building new accesses, so rig up
4287 // an IR builder.
4288 IRBuilderTy IRB(&AI);
4289
4290 // Collect the new slices which we will merge into the alloca slices.
4291 SmallVector<Slice, 4> NewSlices;
4292
4293 // Track any allocas we end up splitting loads and stores for so we iterate
4294 // on them.
4295 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
4296
4297 // At this point, we have collected all of the loads and stores we can
4298 // pre-split, and the specific splits needed for them. We actually do the
4299 // splitting in a specific order in order to handle when one of the loads in
4300 // the value operand to one of the stores.
4301 //
4302 // First, we rewrite all of the split loads, and just accumulate each split
4303 // load in a parallel structure. We also build the slices for them and append
4304 // them to the alloca slices.
4305 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
4306 std::vector<LoadInst *> SplitLoads;
4307 const DataLayout &DL = AI.getModule()->getDataLayout();
4308 for (LoadInst *LI : Loads) {
4309 SplitLoads.clear();
4310
4311 auto &Offsets = SplitOffsetsMap[LI];
4312 unsigned SliceSize = Offsets.S->endOffset() - Offsets.S->beginOffset();
4313 assert(LI->getType()->getIntegerBitWidth() % 8 == 0 &&
4314 "Load must have type size equal to store size");
4315 assert(LI->getType()->getIntegerBitWidth() / 8 >= SliceSize &&
4316 "Load must be >= slice size");
4317
4318 uint64_t BaseOffset = Offsets.S->beginOffset();
4319 assert(BaseOffset + SliceSize > BaseOffset &&
4320 "Cannot represent alloca access size using 64-bit integers!");
4321
4322 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
4323 IRB.SetInsertPoint(LI);
4324
4325 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
4326
4327 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
4328 int Idx = 0, Size = Offsets.Splits.size();
4329 for (;;) {
4330 auto *PartTy = Type::getIntNTy(LI->getContext(), PartSize * 8);
4331 auto AS = LI->getPointerAddressSpace();
4332 auto *PartPtrTy = PartTy->getPointerTo(AS);
4333 LoadInst *PLoad = IRB.CreateAlignedLoad(
4334 PartTy,
4335 getAdjustedPtr(IRB, DL, BasePtr,
4336 APInt(DL.getIndexSizeInBits(AS), PartOffset),
4337 PartPtrTy, BasePtr->getName() + "."),
4338 getAdjustedAlignment(LI, PartOffset),
4339 /*IsVolatile*/ false, LI->getName());
4340 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
4341 LLVMContext::MD_access_group});
4342
4343 // Append this load onto the list of split loads so we can find it later
4344 // to rewrite the stores.
4345 SplitLoads.push_back(PLoad);
4346
4347 // Now build a new slice for the alloca.
4348 NewSlices.push_back(
4349 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
4350 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
4351 /*IsSplittable*/ false));
4352 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
4353 << ", " << NewSlices.back().endOffset()
4354 << "): " << *PLoad << "\n");
4355
4356 // See if we've handled all the splits.
4357 if (Idx >= Size)
4358 break;
4359
4360 // Setup the next partition.
4361 PartOffset = Offsets.Splits[Idx];
4362 ++Idx;
4363 PartSize = (Idx < Size ? Offsets.Splits[Idx] : SliceSize) - PartOffset;
4364 }
4365
4366 // Now that we have the split loads, do the slow walk over all uses of the
4367 // load and rewrite them as split stores, or save the split loads to use
4368 // below if the store is going to be split there anyways.
4369 bool DeferredStores = false;
4370 for (User *LU : LI->users()) {
4371 StoreInst *SI = cast<StoreInst>(LU);
4372 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
4373 DeferredStores = true;
4374 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI
4375 << "\n");
4376 continue;
4377 }
4378
4379 Value *StoreBasePtr = SI->getPointerOperand();
4380 IRB.SetInsertPoint(SI);
4381
4382 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
4383
4384 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
4385 LoadInst *PLoad = SplitLoads[Idx];
4386 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
4387 auto *PartPtrTy =
4388 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
4389
4390 auto AS = SI->getPointerAddressSpace();
4391 StoreInst *PStore = IRB.CreateAlignedStore(
4392 PLoad,
4393 getAdjustedPtr(IRB, DL, StoreBasePtr,
4394 APInt(DL.getIndexSizeInBits(AS), PartOffset),
4395 PartPtrTy, StoreBasePtr->getName() + "."),
4396 getAdjustedAlignment(SI, PartOffset),
4397 /*IsVolatile*/ false);
4398 PStore->copyMetadata(*SI, {LLVMContext::MD_mem_parallel_loop_access,
4399 LLVMContext::MD_access_group,
4400 LLVMContext::MD_DIAssignID});
4401 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
4402 }
4403
4404 // We want to immediately iterate on any allocas impacted by splitting
4405 // this store, and we have to track any promotable alloca (indicated by
4406 // a direct store) as needing to be resplit because it is no longer
4407 // promotable.
4408 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
4409 ResplitPromotableAllocas.insert(OtherAI);
4410 Worklist.insert(OtherAI);
4411 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
4412 StoreBasePtr->stripInBoundsOffsets())) {
4413 Worklist.insert(OtherAI);
4414 }
4415
4416 // Mark the original store as dead.
4417 DeadInsts.push_back(SI);
4418 }
4419
4420 // Save the split loads if there are deferred stores among the users.
4421 if (DeferredStores)
4422 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
4423
4424 // Mark the original load as dead and kill the original slice.
4425 DeadInsts.push_back(LI);
4426 Offsets.S->kill();
4427 }
4428
4429 // Second, we rewrite all of the split stores. At this point, we know that
4430 // all loads from this alloca have been split already. For stores of such
4431 // loads, we can simply look up the pre-existing split loads. For stores of
4432 // other loads, we split those loads first and then write split stores of
4433 // them.
4434 for (StoreInst *SI : Stores) {
4435 auto *LI = cast<LoadInst>(SI->getValueOperand());
4436 IntegerType *Ty = cast<IntegerType>(LI->getType());
4437 assert(Ty->getBitWidth() % 8 == 0);
4438 uint64_t StoreSize = Ty->getBitWidth() / 8;
4439 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
4440
4441 auto &Offsets = SplitOffsetsMap[SI];
4442 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
4443 "Slice size should always match load size exactly!");
4444 uint64_t BaseOffset = Offsets.S->beginOffset();
4445 assert(BaseOffset + StoreSize > BaseOffset &&
4446 "Cannot represent alloca access size using 64-bit integers!");
4447
4448 Value *LoadBasePtr = LI->getPointerOperand();
4449 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
4450
4451 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
4452
4453 // Check whether we have an already split load.
4454 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
4455 std::vector<LoadInst *> *SplitLoads = nullptr;
4456 if (SplitLoadsMapI != SplitLoadsMap.end()) {
4457 SplitLoads = &SplitLoadsMapI->second;
4458 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
4459 "Too few split loads for the number of splits in the store!");
4460 } else {
4461 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n");
4462 }
4463
4464 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
4465 int Idx = 0, Size = Offsets.Splits.size();
4466 for (;;) {
4467 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
4468 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
4469 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
4470
4471 // Either lookup a split load or create one.
4472 LoadInst *PLoad;
4473 if (SplitLoads) {
4474 PLoad = (*SplitLoads)[Idx];
4475 } else {
4476 IRB.SetInsertPoint(LI);
4477 auto AS = LI->getPointerAddressSpace();
4478 PLoad = IRB.CreateAlignedLoad(
4479 PartTy,
4480 getAdjustedPtr(IRB, DL, LoadBasePtr,
4481 APInt(DL.getIndexSizeInBits(AS), PartOffset),
4482 LoadPartPtrTy, LoadBasePtr->getName() + "."),
4483 getAdjustedAlignment(LI, PartOffset),
4484 /*IsVolatile*/ false, LI->getName());
4485 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
4486 LLVMContext::MD_access_group});
4487 }
4488
4489 // And store this partition.
4490 IRB.SetInsertPoint(SI);
4491 auto AS = SI->getPointerAddressSpace();
4492 StoreInst *PStore = IRB.CreateAlignedStore(
4493 PLoad,
4494 getAdjustedPtr(IRB, DL, StoreBasePtr,
4495 APInt(DL.getIndexSizeInBits(AS), PartOffset),
4496 StorePartPtrTy, StoreBasePtr->getName() + "."),
4497 getAdjustedAlignment(SI, PartOffset),
4498 /*IsVolatile*/ false);
4499 PStore->copyMetadata(*SI, {LLVMContext::MD_mem_parallel_loop_access,
4500 LLVMContext::MD_access_group});
4501
4502 // Now build a new slice for the alloca.
4503 NewSlices.push_back(
4504 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
4505 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
4506 /*IsSplittable*/ false));
4507 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
4508 << ", " << NewSlices.back().endOffset()
4509 << "): " << *PStore << "\n");
4510 if (!SplitLoads) {
4511 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
4512 }
4513
4514 // See if we've finished all the splits.
4515 if (Idx >= Size)
4516 break;
4517
4518 // Setup the next partition.
4519 PartOffset = Offsets.Splits[Idx];
4520 ++Idx;
4521 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
4522 }
4523
4524 // We want to immediately iterate on any allocas impacted by splitting
4525 // this load, which is only relevant if it isn't a load of this alloca and
4526 // thus we didn't already split the loads above. We also have to keep track
4527 // of any promotable allocas we split loads on as they can no longer be
4528 // promoted.
4529 if (!SplitLoads) {
4530 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
4531 assert(OtherAI != &AI && "We can't re-split our own alloca!");
4532 ResplitPromotableAllocas.insert(OtherAI);
4533 Worklist.insert(OtherAI);
4534 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
4535 LoadBasePtr->stripInBoundsOffsets())) {
4536 assert(OtherAI != &AI && "We can't re-split our own alloca!");
4537 Worklist.insert(OtherAI);
4538 }
4539 }
4540
4541 // Mark the original store as dead now that we've split it up and kill its
4542 // slice. Note that we leave the original load in place unless this store
4543 // was its only use. It may in turn be split up if it is an alloca load
4544 // for some other alloca, but it may be a normal load. This may introduce
4545 // redundant loads, but where those can be merged the rest of the optimizer
4546 // should handle the merging, and this uncovers SSA splits which is more
4547 // important. In practice, the original loads will almost always be fully
4548 // split and removed eventually, and the splits will be merged by any
4549 // trivial CSE, including instcombine.
4550 if (LI->hasOneUse()) {
4551 assert(*LI->user_begin() == SI && "Single use isn't this store!");
4552 DeadInsts.push_back(LI);
4553 }
4554 DeadInsts.push_back(SI);
4555 Offsets.S->kill();
4556 }
4557
4558 // Remove the killed slices that have ben pre-split.
4559 llvm::erase_if(AS, [](const Slice &S) { return S.isDead(); });
4560
4561 // Insert our new slices. This will sort and merge them into the sorted
4562 // sequence.
4563 AS.insert(NewSlices);
4564
4565 LLVM_DEBUG(dbgs() << " Pre-split slices:\n");
4566 #ifndef NDEBUG
4567 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
4568 LLVM_DEBUG(AS.print(dbgs(), I, " "));
4569 #endif
4570
4571 // Finally, don't try to promote any allocas that new require re-splitting.
4572 // They have already been added to the worklist above.
4573 llvm::erase_if(PromotableAllocas, [&](AllocaInst *AI) {
4574 return ResplitPromotableAllocas.count(AI);
4575 });
4576
4577 return true;
4578 }
4579
4580 /// Rewrite an alloca partition's users.
4581 ///
4582 /// This routine drives both of the rewriting goals of the SROA pass. It tries
4583 /// to rewrite uses of an alloca partition to be conducive for SSA value
4584 /// promotion. If the partition needs a new, more refined alloca, this will
4585 /// build that new alloca, preserving as much type information as possible, and
4586 /// rewrite the uses of the old alloca to point at the new one and have the
4587 /// appropriate new offsets. It also evaluates how successful the rewrite was
4588 /// at enabling promotion and if it was successful queues the alloca to be
4589 /// promoted.
rewritePartition(AllocaInst & AI,AllocaSlices & AS,Partition & P)4590 AllocaInst *SROAPass::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
4591 Partition &P) {
4592 // Try to compute a friendly type for this partition of the alloca. This
4593 // won't always succeed, in which case we fall back to a legal integer type
4594 // or an i8 array of an appropriate size.
4595 Type *SliceTy = nullptr;
4596 VectorType *SliceVecTy = nullptr;
4597 const DataLayout &DL = AI.getModule()->getDataLayout();
4598 std::pair<Type *, IntegerType *> CommonUseTy =
4599 findCommonType(P.begin(), P.end(), P.endOffset());
4600 // Do all uses operate on the same type?
4601 if (CommonUseTy.first)
4602 if (DL.getTypeAllocSize(CommonUseTy.first).getFixedValue() >= P.size()) {
4603 SliceTy = CommonUseTy.first;
4604 SliceVecTy = dyn_cast<VectorType>(SliceTy);
4605 }
4606 // If not, can we find an appropriate subtype in the original allocated type?
4607 if (!SliceTy)
4608 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
4609 P.beginOffset(), P.size()))
4610 SliceTy = TypePartitionTy;
4611
4612 // If still not, can we use the largest bitwidth integer type used?
4613 if (!SliceTy && CommonUseTy.second)
4614 if (DL.getTypeAllocSize(CommonUseTy.second).getFixedValue() >= P.size()) {
4615 SliceTy = CommonUseTy.second;
4616 SliceVecTy = dyn_cast<VectorType>(SliceTy);
4617 }
4618 if ((!SliceTy || (SliceTy->isArrayTy() &&
4619 SliceTy->getArrayElementType()->isIntegerTy())) &&
4620 DL.isLegalInteger(P.size() * 8)) {
4621 SliceTy = Type::getIntNTy(*C, P.size() * 8);
4622 }
4623
4624 // If the common use types are not viable for promotion then attempt to find
4625 // another type that is viable.
4626 if (SliceVecTy && !checkVectorTypeForPromotion(P, SliceVecTy, DL))
4627 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
4628 P.beginOffset(), P.size())) {
4629 VectorType *TypePartitionVecTy = dyn_cast<VectorType>(TypePartitionTy);
4630 if (TypePartitionVecTy &&
4631 checkVectorTypeForPromotion(P, TypePartitionVecTy, DL))
4632 SliceTy = TypePartitionTy;
4633 }
4634
4635 if (!SliceTy)
4636 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
4637 assert(DL.getTypeAllocSize(SliceTy).getFixedValue() >= P.size());
4638
4639 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
4640
4641 VectorType *VecTy =
4642 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
4643 if (VecTy)
4644 SliceTy = VecTy;
4645
4646 // Check for the case where we're going to rewrite to a new alloca of the
4647 // exact same type as the original, and with the same access offsets. In that
4648 // case, re-use the existing alloca, but still run through the rewriter to
4649 // perform phi and select speculation.
4650 // P.beginOffset() can be non-zero even with the same type in a case with
4651 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
4652 AllocaInst *NewAI;
4653 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) {
4654 NewAI = &AI;
4655 // FIXME: We should be able to bail at this point with "nothing changed".
4656 // FIXME: We might want to defer PHI speculation until after here.
4657 // FIXME: return nullptr;
4658 } else {
4659 // Make sure the alignment is compatible with P.beginOffset().
4660 const Align Alignment = commonAlignment(AI.getAlign(), P.beginOffset());
4661 // If we will get at least this much alignment from the type alone, leave
4662 // the alloca's alignment unconstrained.
4663 const bool IsUnconstrained = Alignment <= DL.getABITypeAlign(SliceTy);
4664 NewAI = new AllocaInst(
4665 SliceTy, AI.getAddressSpace(), nullptr,
4666 IsUnconstrained ? DL.getPrefTypeAlign(SliceTy) : Alignment,
4667 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
4668 // Copy the old AI debug location over to the new one.
4669 NewAI->setDebugLoc(AI.getDebugLoc());
4670 ++NumNewAllocas;
4671 }
4672
4673 LLVM_DEBUG(dbgs() << "Rewriting alloca partition "
4674 << "[" << P.beginOffset() << "," << P.endOffset()
4675 << ") to: " << *NewAI << "\n");
4676
4677 // Track the high watermark on the worklist as it is only relevant for
4678 // promoted allocas. We will reset it to this point if the alloca is not in
4679 // fact scheduled for promotion.
4680 unsigned PPWOldSize = PostPromotionWorklist.size();
4681 unsigned NumUses = 0;
4682 SmallSetVector<PHINode *, 8> PHIUsers;
4683 SmallSetVector<SelectInst *, 8> SelectUsers;
4684
4685 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
4686 P.endOffset(), IsIntegerPromotable, VecTy,
4687 PHIUsers, SelectUsers);
4688 bool Promotable = true;
4689 for (Slice *S : P.splitSliceTails()) {
4690 Promotable &= Rewriter.visit(S);
4691 ++NumUses;
4692 }
4693 for (Slice &S : P) {
4694 Promotable &= Rewriter.visit(&S);
4695 ++NumUses;
4696 }
4697
4698 NumAllocaPartitionUses += NumUses;
4699 MaxUsesPerAllocaPartition.updateMax(NumUses);
4700
4701 // Now that we've processed all the slices in the new partition, check if any
4702 // PHIs or Selects would block promotion.
4703 for (PHINode *PHI : PHIUsers)
4704 if (!isSafePHIToSpeculate(*PHI)) {
4705 Promotable = false;
4706 PHIUsers.clear();
4707 SelectUsers.clear();
4708 break;
4709 }
4710
4711 SmallVector<std::pair<SelectInst *, RewriteableMemOps>, 2>
4712 NewSelectsToRewrite;
4713 NewSelectsToRewrite.reserve(SelectUsers.size());
4714 for (SelectInst *Sel : SelectUsers) {
4715 std::optional<RewriteableMemOps> Ops =
4716 isSafeSelectToSpeculate(*Sel, PreserveCFG);
4717 if (!Ops) {
4718 Promotable = false;
4719 PHIUsers.clear();
4720 SelectUsers.clear();
4721 NewSelectsToRewrite.clear();
4722 break;
4723 }
4724 NewSelectsToRewrite.emplace_back(std::make_pair(Sel, *Ops));
4725 }
4726
4727 if (Promotable) {
4728 for (Use *U : AS.getDeadUsesIfPromotable()) {
4729 auto *OldInst = dyn_cast<Instruction>(U->get());
4730 Value::dropDroppableUse(*U);
4731 if (OldInst)
4732 if (isInstructionTriviallyDead(OldInst))
4733 DeadInsts.push_back(OldInst);
4734 }
4735 if (PHIUsers.empty() && SelectUsers.empty()) {
4736 // Promote the alloca.
4737 PromotableAllocas.push_back(NewAI);
4738 } else {
4739 // If we have either PHIs or Selects to speculate, add them to those
4740 // worklists and re-queue the new alloca so that we promote in on the
4741 // next iteration.
4742 for (PHINode *PHIUser : PHIUsers)
4743 SpeculatablePHIs.insert(PHIUser);
4744 SelectsToRewrite.reserve(SelectsToRewrite.size() +
4745 NewSelectsToRewrite.size());
4746 for (auto &&KV : llvm::make_range(
4747 std::make_move_iterator(NewSelectsToRewrite.begin()),
4748 std::make_move_iterator(NewSelectsToRewrite.end())))
4749 SelectsToRewrite.insert(std::move(KV));
4750 Worklist.insert(NewAI);
4751 }
4752 } else {
4753 // Drop any post-promotion work items if promotion didn't happen.
4754 while (PostPromotionWorklist.size() > PPWOldSize)
4755 PostPromotionWorklist.pop_back();
4756
4757 // We couldn't promote and we didn't create a new partition, nothing
4758 // happened.
4759 if (NewAI == &AI)
4760 return nullptr;
4761
4762 // If we can't promote the alloca, iterate on it to check for new
4763 // refinements exposed by splitting the current alloca. Don't iterate on an
4764 // alloca which didn't actually change and didn't get promoted.
4765 Worklist.insert(NewAI);
4766 }
4767
4768 return NewAI;
4769 }
4770
4771 /// Walks the slices of an alloca and form partitions based on them,
4772 /// rewriting each of their uses.
splitAlloca(AllocaInst & AI,AllocaSlices & AS)4773 bool SROAPass::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4774 if (AS.begin() == AS.end())
4775 return false;
4776
4777 unsigned NumPartitions = 0;
4778 bool Changed = false;
4779 const DataLayout &DL = AI.getModule()->getDataLayout();
4780
4781 // First try to pre-split loads and stores.
4782 Changed |= presplitLoadsAndStores(AI, AS);
4783
4784 // Now that we have identified any pre-splitting opportunities,
4785 // mark loads and stores unsplittable except for the following case.
4786 // We leave a slice splittable if all other slices are disjoint or fully
4787 // included in the slice, such as whole-alloca loads and stores.
4788 // If we fail to split these during pre-splitting, we want to force them
4789 // to be rewritten into a partition.
4790 bool IsSorted = true;
4791
4792 uint64_t AllocaSize =
4793 DL.getTypeAllocSize(AI.getAllocatedType()).getFixedValue();
4794 const uint64_t MaxBitVectorSize = 1024;
4795 if (AllocaSize <= MaxBitVectorSize) {
4796 // If a byte boundary is included in any load or store, a slice starting or
4797 // ending at the boundary is not splittable.
4798 SmallBitVector SplittableOffset(AllocaSize + 1, true);
4799 for (Slice &S : AS)
4800 for (unsigned O = S.beginOffset() + 1;
4801 O < S.endOffset() && O < AllocaSize; O++)
4802 SplittableOffset.reset(O);
4803
4804 for (Slice &S : AS) {
4805 if (!S.isSplittable())
4806 continue;
4807
4808 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4809 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4810 continue;
4811
4812 if (isa<LoadInst>(S.getUse()->getUser()) ||
4813 isa<StoreInst>(S.getUse()->getUser())) {
4814 S.makeUnsplittable();
4815 IsSorted = false;
4816 }
4817 }
4818 }
4819 else {
4820 // We only allow whole-alloca splittable loads and stores
4821 // for a large alloca to avoid creating too large BitVector.
4822 for (Slice &S : AS) {
4823 if (!S.isSplittable())
4824 continue;
4825
4826 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4827 continue;
4828
4829 if (isa<LoadInst>(S.getUse()->getUser()) ||
4830 isa<StoreInst>(S.getUse()->getUser())) {
4831 S.makeUnsplittable();
4832 IsSorted = false;
4833 }
4834 }
4835 }
4836
4837 if (!IsSorted)
4838 llvm::sort(AS);
4839
4840 /// Describes the allocas introduced by rewritePartition in order to migrate
4841 /// the debug info.
4842 struct Fragment {
4843 AllocaInst *Alloca;
4844 uint64_t Offset;
4845 uint64_t Size;
4846 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
4847 : Alloca(AI), Offset(O), Size(S) {}
4848 };
4849 SmallVector<Fragment, 4> Fragments;
4850
4851 // Rewrite each partition.
4852 for (auto &P : AS.partitions()) {
4853 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4854 Changed = true;
4855 if (NewAI != &AI) {
4856 uint64_t SizeOfByte = 8;
4857 uint64_t AllocaSize =
4858 DL.getTypeSizeInBits(NewAI->getAllocatedType()).getFixedValue();
4859 // Don't include any padding.
4860 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
4861 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
4862 }
4863 }
4864 ++NumPartitions;
4865 }
4866
4867 NumAllocaPartitions += NumPartitions;
4868 MaxPartitionsPerAlloca.updateMax(NumPartitions);
4869
4870 // Migrate debug information from the old alloca to the new alloca(s)
4871 // and the individual partitions.
4872 TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
4873 for (auto *DbgAssign : at::getAssignmentMarkers(&AI))
4874 DbgDeclares.push_back(DbgAssign);
4875 for (DbgVariableIntrinsic *DbgDeclare : DbgDeclares) {
4876 auto *Expr = DbgDeclare->getExpression();
4877 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
4878 uint64_t AllocaSize =
4879 DL.getTypeSizeInBits(AI.getAllocatedType()).getFixedValue();
4880 for (auto Fragment : Fragments) {
4881 // Create a fragment expression describing the new partition or reuse AI's
4882 // expression if there is only one partition.
4883 auto *FragmentExpr = Expr;
4884 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
4885 // If this alloca is already a scalar replacement of a larger aggregate,
4886 // Fragment.Offset describes the offset inside the scalar.
4887 auto ExprFragment = Expr->getFragmentInfo();
4888 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
4889 uint64_t Start = Offset + Fragment.Offset;
4890 uint64_t Size = Fragment.Size;
4891 if (ExprFragment) {
4892 uint64_t AbsEnd =
4893 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
4894 if (Start >= AbsEnd) {
4895 // No need to describe a SROAed padding.
4896 continue;
4897 }
4898 Size = std::min(Size, AbsEnd - Start);
4899 }
4900 // The new, smaller fragment is stenciled out from the old fragment.
4901 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4902 assert(Start >= OrigFragment->OffsetInBits &&
4903 "new fragment is outside of original fragment");
4904 Start -= OrigFragment->OffsetInBits;
4905 }
4906
4907 // The alloca may be larger than the variable.
4908 auto VarSize = DbgDeclare->getVariable()->getSizeInBits();
4909 if (VarSize) {
4910 if (Size > *VarSize)
4911 Size = *VarSize;
4912 if (Size == 0 || Start + Size > *VarSize)
4913 continue;
4914 }
4915
4916 // Avoid creating a fragment expression that covers the entire variable.
4917 if (!VarSize || *VarSize != Size) {
4918 if (auto E =
4919 DIExpression::createFragmentExpression(Expr, Start, Size))
4920 FragmentExpr = *E;
4921 else
4922 continue;
4923 }
4924 }
4925
4926 // Remove any existing intrinsics on the new alloca describing
4927 // the variable fragment.
4928 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca)) {
4929 auto SameVariableFragment = [](const DbgVariableIntrinsic *LHS,
4930 const DbgVariableIntrinsic *RHS) {
4931 return LHS->getVariable() == RHS->getVariable() &&
4932 LHS->getDebugLoc()->getInlinedAt() ==
4933 RHS->getDebugLoc()->getInlinedAt();
4934 };
4935 if (SameVariableFragment(OldDII, DbgDeclare))
4936 OldDII->eraseFromParent();
4937 }
4938
4939 if (auto *DbgAssign = dyn_cast<DbgAssignIntrinsic>(DbgDeclare)) {
4940 if (!Fragment.Alloca->hasMetadata(LLVMContext::MD_DIAssignID)) {
4941 Fragment.Alloca->setMetadata(
4942 LLVMContext::MD_DIAssignID,
4943 DIAssignID::getDistinct(AI.getContext()));
4944 }
4945 auto *NewAssign = DIB.insertDbgAssign(
4946 Fragment.Alloca, DbgAssign->getValue(), DbgAssign->getVariable(),
4947 FragmentExpr, Fragment.Alloca, DbgAssign->getAddressExpression(),
4948 DbgAssign->getDebugLoc());
4949 NewAssign->setDebugLoc(DbgAssign->getDebugLoc());
4950 LLVM_DEBUG(dbgs() << "Created new assign intrinsic: " << *NewAssign
4951 << "\n");
4952 } else {
4953 DIB.insertDeclare(Fragment.Alloca, DbgDeclare->getVariable(),
4954 FragmentExpr, DbgDeclare->getDebugLoc(), &AI);
4955 }
4956 }
4957 }
4958 return Changed;
4959 }
4960
4961 /// Clobber a use with poison, deleting the used value if it becomes dead.
clobberUse(Use & U)4962 void SROAPass::clobberUse(Use &U) {
4963 Value *OldV = U;
4964 // Replace the use with an poison value.
4965 U = PoisonValue::get(OldV->getType());
4966
4967 // Check for this making an instruction dead. We have to garbage collect
4968 // all the dead instructions to ensure the uses of any alloca end up being
4969 // minimal.
4970 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4971 if (isInstructionTriviallyDead(OldI)) {
4972 DeadInsts.push_back(OldI);
4973 }
4974 }
4975
4976 /// Analyze an alloca for SROA.
4977 ///
4978 /// This analyzes the alloca to ensure we can reason about it, builds
4979 /// the slices of the alloca, and then hands it off to be split and
4980 /// rewritten as needed.
4981 std::pair<bool /*Changed*/, bool /*CFGChanged*/>
runOnAlloca(AllocaInst & AI)4982 SROAPass::runOnAlloca(AllocaInst &AI) {
4983 bool Changed = false;
4984 bool CFGChanged = false;
4985
4986 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4987 ++NumAllocasAnalyzed;
4988
4989 // Special case dead allocas, as they're trivial.
4990 if (AI.use_empty()) {
4991 AI.eraseFromParent();
4992 Changed = true;
4993 return {Changed, CFGChanged};
4994 }
4995 const DataLayout &DL = AI.getModule()->getDataLayout();
4996
4997 // Skip alloca forms that this analysis can't handle.
4998 auto *AT = AI.getAllocatedType();
4999 if (AI.isArrayAllocation() || !AT->isSized() || isa<ScalableVectorType>(AT) ||
5000 DL.getTypeAllocSize(AT).getFixedValue() == 0)
5001 return {Changed, CFGChanged};
5002
5003 // First, split any FCA loads and stores touching this alloca to promote
5004 // better splitting and promotion opportunities.
5005 IRBuilderTy IRB(&AI);
5006 AggLoadStoreRewriter AggRewriter(DL, IRB);
5007 Changed |= AggRewriter.rewrite(AI);
5008
5009 // Build the slices using a recursive instruction-visiting builder.
5010 AllocaSlices AS(DL, AI);
5011 LLVM_DEBUG(AS.print(dbgs()));
5012 if (AS.isEscaped())
5013 return {Changed, CFGChanged};
5014
5015 // Delete all the dead users of this alloca before splitting and rewriting it.
5016 for (Instruction *DeadUser : AS.getDeadUsers()) {
5017 // Free up everything used by this instruction.
5018 for (Use &DeadOp : DeadUser->operands())
5019 clobberUse(DeadOp);
5020
5021 // Now replace the uses of this instruction.
5022 DeadUser->replaceAllUsesWith(PoisonValue::get(DeadUser->getType()));
5023
5024 // And mark it for deletion.
5025 DeadInsts.push_back(DeadUser);
5026 Changed = true;
5027 }
5028 for (Use *DeadOp : AS.getDeadOperands()) {
5029 clobberUse(*DeadOp);
5030 Changed = true;
5031 }
5032
5033 // No slices to split. Leave the dead alloca for a later pass to clean up.
5034 if (AS.begin() == AS.end())
5035 return {Changed, CFGChanged};
5036
5037 Changed |= splitAlloca(AI, AS);
5038
5039 LLVM_DEBUG(dbgs() << " Speculating PHIs\n");
5040 while (!SpeculatablePHIs.empty())
5041 speculatePHINodeLoads(IRB, *SpeculatablePHIs.pop_back_val());
5042
5043 LLVM_DEBUG(dbgs() << " Rewriting Selects\n");
5044 auto RemainingSelectsToRewrite = SelectsToRewrite.takeVector();
5045 while (!RemainingSelectsToRewrite.empty()) {
5046 const auto [K, V] = RemainingSelectsToRewrite.pop_back_val();
5047 CFGChanged |=
5048 rewriteSelectInstMemOps(*K, V, IRB, PreserveCFG ? nullptr : DTU);
5049 }
5050
5051 return {Changed, CFGChanged};
5052 }
5053
5054 /// Delete the dead instructions accumulated in this run.
5055 ///
5056 /// Recursively deletes the dead instructions we've accumulated. This is done
5057 /// at the very end to maximize locality of the recursive delete and to
5058 /// minimize the problems of invalidated instruction pointers as such pointers
5059 /// are used heavily in the intermediate stages of the algorithm.
5060 ///
5061 /// We also record the alloca instructions deleted here so that they aren't
5062 /// subsequently handed to mem2reg to promote.
deleteDeadInstructions(SmallPtrSetImpl<AllocaInst * > & DeletedAllocas)5063 bool SROAPass::deleteDeadInstructions(
5064 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
5065 bool Changed = false;
5066 while (!DeadInsts.empty()) {
5067 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
5068 if (!I)
5069 continue;
5070 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
5071
5072 // If the instruction is an alloca, find the possible dbg.declare connected
5073 // to it, and remove it too. We must do this before calling RAUW or we will
5074 // not be able to find it.
5075 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
5076 DeletedAllocas.insert(AI);
5077 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI))
5078 OldDII->eraseFromParent();
5079 }
5080
5081 at::deleteAssignmentMarkers(I);
5082 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5083
5084 for (Use &Operand : I->operands())
5085 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
5086 // Zero out the operand and see if it becomes trivially dead.
5087 Operand = nullptr;
5088 if (isInstructionTriviallyDead(U))
5089 DeadInsts.push_back(U);
5090 }
5091
5092 ++NumDeleted;
5093 I->eraseFromParent();
5094 Changed = true;
5095 }
5096 return Changed;
5097 }
5098
5099 /// Promote the allocas, using the best available technique.
5100 ///
5101 /// This attempts to promote whatever allocas have been identified as viable in
5102 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
5103 /// This function returns whether any promotion occurred.
promoteAllocas(Function & F)5104 bool SROAPass::promoteAllocas(Function &F) {
5105 if (PromotableAllocas.empty())
5106 return false;
5107
5108 NumPromoted += PromotableAllocas.size();
5109
5110 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
5111 PromoteMemToReg(PromotableAllocas, DTU->getDomTree(), AC);
5112 PromotableAllocas.clear();
5113 return true;
5114 }
5115
runImpl(Function & F,DomTreeUpdater & RunDTU,AssumptionCache & RunAC)5116 PreservedAnalyses SROAPass::runImpl(Function &F, DomTreeUpdater &RunDTU,
5117 AssumptionCache &RunAC) {
5118 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
5119 C = &F.getContext();
5120 DTU = &RunDTU;
5121 AC = &RunAC;
5122
5123 BasicBlock &EntryBB = F.getEntryBlock();
5124 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
5125 I != E; ++I) {
5126 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
5127 if (isa<ScalableVectorType>(AI->getAllocatedType())) {
5128 if (isAllocaPromotable(AI))
5129 PromotableAllocas.push_back(AI);
5130 } else {
5131 Worklist.insert(AI);
5132 }
5133 }
5134 }
5135
5136 bool Changed = false;
5137 bool CFGChanged = false;
5138 // A set of deleted alloca instruction pointers which should be removed from
5139 // the list of promotable allocas.
5140 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
5141
5142 do {
5143 while (!Worklist.empty()) {
5144 auto [IterationChanged, IterationCFGChanged] =
5145 runOnAlloca(*Worklist.pop_back_val());
5146 Changed |= IterationChanged;
5147 CFGChanged |= IterationCFGChanged;
5148
5149 Changed |= deleteDeadInstructions(DeletedAllocas);
5150
5151 // Remove the deleted allocas from various lists so that we don't try to
5152 // continue processing them.
5153 if (!DeletedAllocas.empty()) {
5154 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
5155 Worklist.remove_if(IsInSet);
5156 PostPromotionWorklist.remove_if(IsInSet);
5157 llvm::erase_if(PromotableAllocas, IsInSet);
5158 DeletedAllocas.clear();
5159 }
5160 }
5161
5162 Changed |= promoteAllocas(F);
5163
5164 Worklist = PostPromotionWorklist;
5165 PostPromotionWorklist.clear();
5166 } while (!Worklist.empty());
5167
5168 assert((!CFGChanged || Changed) && "Can not only modify the CFG.");
5169 assert((!CFGChanged || !PreserveCFG) &&
5170 "Should not have modified the CFG when told to preserve it.");
5171
5172 if (!Changed)
5173 return PreservedAnalyses::all();
5174
5175 PreservedAnalyses PA;
5176 if (!CFGChanged)
5177 PA.preserveSet<CFGAnalyses>();
5178 PA.preserve<DominatorTreeAnalysis>();
5179 return PA;
5180 }
5181
runImpl(Function & F,DominatorTree & RunDT,AssumptionCache & RunAC)5182 PreservedAnalyses SROAPass::runImpl(Function &F, DominatorTree &RunDT,
5183 AssumptionCache &RunAC) {
5184 DomTreeUpdater DTU(RunDT, DomTreeUpdater::UpdateStrategy::Lazy);
5185 return runImpl(F, DTU, RunAC);
5186 }
5187
run(Function & F,FunctionAnalysisManager & AM)5188 PreservedAnalyses SROAPass::run(Function &F, FunctionAnalysisManager &AM) {
5189 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
5190 AM.getResult<AssumptionAnalysis>(F));
5191 }
5192
printPipeline(raw_ostream & OS,function_ref<StringRef (StringRef)> MapClassName2PassName)5193 void SROAPass::printPipeline(
5194 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
5195 static_cast<PassInfoMixin<SROAPass> *>(this)->printPipeline(
5196 OS, MapClassName2PassName);
5197 OS << (PreserveCFG ? "<preserve-cfg>" : "<modify-cfg>");
5198 }
5199
SROAPass(SROAOptions PreserveCFG_)5200 SROAPass::SROAPass(SROAOptions PreserveCFG_)
5201 : PreserveCFG(PreserveCFG_ == SROAOptions::PreserveCFG) {}
5202
5203 /// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
5204 ///
5205 /// This is in the llvm namespace purely to allow it to be a friend of the \c
5206 /// SROA pass.
5207 class llvm::sroa::SROALegacyPass : public FunctionPass {
5208 /// The SROA implementation.
5209 SROAPass Impl;
5210
5211 public:
5212 static char ID;
5213
SROALegacyPass(SROAOptions PreserveCFG=SROAOptions::PreserveCFG)5214 SROALegacyPass(SROAOptions PreserveCFG = SROAOptions::PreserveCFG)
5215 : FunctionPass(ID), Impl(PreserveCFG) {
5216 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
5217 }
5218
runOnFunction(Function & F)5219 bool runOnFunction(Function &F) override {
5220 if (skipFunction(F))
5221 return false;
5222
5223 auto PA = Impl.runImpl(
5224 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
5225 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
5226 return !PA.areAllPreserved();
5227 }
5228
getAnalysisUsage(AnalysisUsage & AU) const5229 void getAnalysisUsage(AnalysisUsage &AU) const override {
5230 AU.addRequired<AssumptionCacheTracker>();
5231 AU.addRequired<DominatorTreeWrapperPass>();
5232 AU.addPreserved<GlobalsAAWrapperPass>();
5233 AU.addPreserved<DominatorTreeWrapperPass>();
5234 }
5235
getPassName() const5236 StringRef getPassName() const override { return "SROA"; }
5237 };
5238
5239 char SROALegacyPass::ID = 0;
5240
createSROAPass(bool PreserveCFG)5241 FunctionPass *llvm::createSROAPass(bool PreserveCFG) {
5242 return new SROALegacyPass(PreserveCFG ? SROAOptions::PreserveCFG
5243 : SROAOptions::ModifyCFG);
5244 }
5245
5246 INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
5247 "Scalar Replacement Of Aggregates", false, false)
5248 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5249 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5250 INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
5251 false, false)
5252