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