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