102#define DEBUG_TYPE "sroa"
104STATISTIC(NumAllocasAnalyzed,
"Number of allocas analyzed for replacement");
105STATISTIC(NumAllocaPartitions,
"Number of alloca partitions formed");
106STATISTIC(MaxPartitionsPerAlloca,
"Maximum number of partitions per alloca");
107STATISTIC(NumAllocaPartitionUses,
"Number of alloca partition uses rewritten");
108STATISTIC(MaxUsesPerAllocaPartition,
"Maximum number of uses of a partition");
109STATISTIC(NumNewAllocas,
"Number of new, smaller allocas introduced");
110STATISTIC(NumPromoted,
"Number of allocas promoted to SSA values");
111STATISTIC(NumLoadsSpeculated,
"Number of loads speculated to allow promotion");
113 "Number of loads rewritten into predicated loads to allow promotion");
116 "Number of stores rewritten into predicated stores to allow promotion");
118STATISTIC(NumVectorized,
"Number of vectorized aggregates");
122class AllocaSliceRewriter;
127class SelectHandSpeculativity {
128 unsigned char Storage = 0;
132 SelectHandSpeculativity() =
default;
133 SelectHandSpeculativity &setAsSpeculatable(
bool isTrueVal);
134 bool isSpeculatable(
bool isTrueVal)
const;
135 bool areAllSpeculatable()
const;
136 bool areAnySpeculatable()
const;
137 bool areNoneSpeculatable()
const;
139 explicit operator intptr_t()
const {
return static_cast<intptr_t
>(Storage); }
140 explicit SelectHandSpeculativity(intptr_t Storage_) : Storage(Storage_) {}
142static_assert(
sizeof(SelectHandSpeculativity) ==
sizeof(
unsigned char));
144using PossiblySpeculatableLoad =
147using RewriteableMemOp =
148 std::variant<PossiblySpeculatableLoad, UnspeculatableStore>;
150using InstructionSliceMap =
172 LLVMContext *
const C;
173 DomTreeUpdater *
const DTU;
174 AssumptionCache *
const AC;
175 const bool PreserveCFG;
176 const bool AggregateToVector;
185 SmallSetVector<AllocaInst *, 16> Worklist;
200 SmallSetVector<AllocaInst *, 16> PostPromotionWorklist;
203 SetVector<AllocaInst *, SmallVector<AllocaInst *>,
204 SmallPtrSet<AllocaInst *, 16>, 16>
212 SmallSetVector<PHINode *, 8> SpeculatablePHIs;
219 SmallSetVector<PHINode *, 8> PHIsWithStoreToRewrite;
223 SmallMapVector<SelectInst *, RewriteableMemOps, 8> SelectsToRewrite;
268 static std::optional<RewriteableMemOps>
269 isSafeSelectToSpeculateOrPredicate(SelectInst &SI,
bool PreserveCFG);
272 SROA(LLVMContext *C, DomTreeUpdater *DTU, AssumptionCache *AC,
274 : C(C), DTU(DTU), AC(AC),
275 PreserveCFG(
Options.
CFG == SROAOptions::PreserveCFG),
276 AggregateToVector(
Options.AggregateToVector) {}
279 std::pair<
bool ,
bool > runSROA(
Function &
F);
282 friend class AllocaSliceRewriter;
284 bool presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS);
285 std::pair<AllocaInst *, uint64_t>
286 rewritePartition(AllocaInst &AI, AllocaSlices &AS, Partition &
P);
287 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
288 bool propagateStoredValuesToLoads(AllocaInst &AI, AllocaSlices &AS);
289 std::pair<
bool ,
bool > runOnAlloca(AllocaInst &AI);
290 void clobberUse(Use &U);
291 bool deleteDeadInstructions(AllocaInst *AI,
292 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
293 bool promoteAllocas();
307enum FragCalcResult { UseFrag, UseNoFrag,
Skip };
311 uint64_t NewStorageSliceOffsetInBits,
313 std::optional<DIExpression::FragmentInfo> StorageFragment,
314 std::optional<DIExpression::FragmentInfo> CurrentFragment,
318 if (StorageFragment) {
320 std::min(NewStorageSliceSizeInBits, StorageFragment->SizeInBits);
322 NewStorageSliceOffsetInBits + StorageFragment->OffsetInBits;
324 Target.SizeInBits = NewStorageSliceSizeInBits;
325 Target.OffsetInBits = NewStorageSliceOffsetInBits;
331 if (!CurrentFragment) {
332 if (
auto Size = Variable->getSizeInBits()) {
335 if (
Target == CurrentFragment)
342 if (!CurrentFragment || *CurrentFragment ==
Target)
348 if (
Target.startInBits() < CurrentFragment->startInBits() ||
349 Target.endInBits() > CurrentFragment->endInBits())
388 if (DVRAssignMarkerRange.empty())
394 LLVM_DEBUG(
dbgs() <<
" OldAllocaOffsetInBits: " << OldAllocaOffsetInBits
396 LLVM_DEBUG(
dbgs() <<
" SliceSizeInBits: " << SliceSizeInBits <<
"\n");
408 DVR->getExpression()->getFragmentInfo();
421 auto *Expr = DbgAssign->getExpression();
422 bool SetKillLocation =
false;
425 std::optional<DIExpression::FragmentInfo> BaseFragment;
428 if (R == BaseFragments.
end())
430 BaseFragment = R->second;
432 std::optional<DIExpression::FragmentInfo> CurrentFragment =
433 Expr->getFragmentInfo();
436 DbgAssign->getVariable(), OldAllocaOffsetInBits, SliceSizeInBits,
437 BaseFragment, CurrentFragment, NewFragment);
441 if (Result == UseFrag && !(NewFragment == CurrentFragment)) {
442 if (CurrentFragment) {
447 NewFragment.
OffsetInBits -= CurrentFragment->OffsetInBits;
460 SetKillLocation =
true;
468 Inst->
setMetadata(LLVMContext::MD_DIAssignID, NewID);
475 Inst, NewValue, DbgAssign->getVariable(), Expr, Dest,
479 NewAssign = DbgAssign;
498 Value && (DbgAssign->hasArgList() ||
499 !DbgAssign->getExpression()->isSingleLocationExpression());
516 if (NewAssign != DbgAssign) {
517 NewAssign->
moveBefore(DbgAssign->getIterator());
520 LLVM_DEBUG(
dbgs() <<
"Created new assign: " << *NewAssign <<
"\n");
523 for_each(DVRAssignMarkerRange, MigrateDbgAssign);
533 Twine getNameWithPrefix(
const Twine &Name)
const {
538 void SetNamePrefix(
const Twine &
P) { Prefix =
P.str(); }
540 void InsertHelper(Instruction *
I,
const Twine &Name,
565 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
571 : BeginOffset(BeginOffset), EndOffset(EndOffset),
572 UseAndIsSplittable(
U, IsSplittable) {}
574 uint64_t beginOffset()
const {
return BeginOffset; }
575 uint64_t endOffset()
const {
return EndOffset; }
577 bool isSplittable()
const {
return UseAndIsSplittable.getInt(); }
578 void makeUnsplittable() { UseAndIsSplittable.setInt(
false); }
580 Use *getUse()
const {
return UseAndIsSplittable.getPointer(); }
582 bool isDead()
const {
return getUse() ==
nullptr; }
583 void kill() { UseAndIsSplittable.setPointer(
nullptr); }
592 if (beginOffset() <
RHS.beginOffset())
594 if (beginOffset() >
RHS.beginOffset())
596 if (isSplittable() !=
RHS.isSplittable())
597 return !isSplittable();
598 if (endOffset() >
RHS.endOffset())
605 return LHS.beginOffset() < RHSOffset;
608 return LHSOffset <
RHS.beginOffset();
612 return isSplittable() ==
RHS.isSplittable() &&
613 beginOffset() ==
RHS.beginOffset() && endOffset() ==
RHS.endOffset();
628 AllocaSlices(
const DataLayout &
DL, AllocaInst &AI);
634 bool isEscaped()
const {
return PointerEscapingInstr; }
635 bool isEscapedReadOnly()
const {
return PointerEscapingInstrReadOnly; }
640 using range = iterator_range<iterator>;
642 iterator
begin() {
return Slices.begin(); }
643 iterator
end() {
return Slices.end(); }
647 const_iterator
begin()
const {
return Slices.begin(); }
648 const_iterator
end()
const {
return Slices.end(); }
652 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
660 int OldSize = Slices.size();
661 Slices.append(NewSlices.
begin(), NewSlices.
end());
662 auto SliceI = Slices.begin() + OldSize;
663 std::stable_sort(SliceI, Slices.end());
664 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
673 ArrayRef<Instruction *> getDeadUsers()
const {
return DeadUsers; }
677 return DeadUseIfPromotable;
688#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
689 void print(raw_ostream &OS, const_iterator
I, StringRef Indent =
" ")
const;
690 void printSlice(raw_ostream &OS, const_iterator
I,
691 StringRef Indent =
" ")
const;
692 void printUse(raw_ostream &OS, const_iterator
I,
693 StringRef Indent =
" ")
const;
694 void print(raw_ostream &OS)
const;
695 void dump(const_iterator
I)
const;
702 friend class AllocaSlices::SliceBuilder;
704#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
732 SmallVector<Instruction *, 8> DeadUsers;
759 friend class AllocaSlices;
760 friend class AllocaSlices::partition_iterator;
762 using iterator = AllocaSlices::iterator;
766 uint64_t BeginOffset = 0, EndOffset = 0;
776 Partition(iterator SI) : SI(SI), SJ(SI) {}
782 uint64_t beginOffset()
const {
return BeginOffset; }
787 uint64_t endOffset()
const {
return EndOffset; }
793 assert(BeginOffset < EndOffset &&
"Partitions must span some bytes!");
794 return EndOffset - BeginOffset;
799 bool empty()
const {
return SI == SJ; }
810 iterator
begin()
const {
return SI; }
811 iterator
end()
const {
return SJ; }
843 AllocaSlices::iterator SE;
847 uint64_t MaxSplitSliceEndOffset = 0;
851 partition_iterator(AllocaSlices::iterator
SI, AllocaSlices::iterator SE)
863 assert((
P.SI != SE || !
P.SplitTails.empty()) &&
864 "Cannot advance past the end of the slices!");
867 if (!
P.SplitTails.empty()) {
868 if (
P.EndOffset >= MaxSplitSliceEndOffset) {
870 P.SplitTails.clear();
871 MaxSplitSliceEndOffset = 0;
877 [&](Slice *S) { return S->endOffset() <= P.EndOffset; });
880 return S->endOffset() == MaxSplitSliceEndOffset;
882 "Could not find the current max split slice offset!");
885 return S->endOffset() <= MaxSplitSliceEndOffset;
887 "Max split slice end offset is not actually the max!");
894 assert(P.SplitTails.empty() &&
"Failed to clear the split slices!");
904 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
905 P.SplitTails.push_back(&S);
906 MaxSplitSliceEndOffset =
907 std::max(S.endOffset(), MaxSplitSliceEndOffset);
915 P.BeginOffset = P.EndOffset;
916 P.EndOffset = MaxSplitSliceEndOffset;
923 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
924 !P.SI->isSplittable()) {
925 P.BeginOffset = P.EndOffset;
926 P.EndOffset = P.SI->beginOffset();
936 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
937 P.EndOffset = P.SI->endOffset();
942 if (!P.SI->isSplittable()) {
945 assert(P.BeginOffset == P.SI->beginOffset());
949 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
950 if (!P.SJ->isSplittable())
951 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
963 assert(P.SI->isSplittable() &&
"Forming a splittable partition!");
966 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
967 P.SJ->isSplittable()) {
968 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
975 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
976 assert(!P.SJ->isSplittable());
977 P.EndOffset = P.SJ->beginOffset();
984 "End iterators don't match between compared partition iterators!");
991 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
992 assert(P.SJ == RHS.P.SJ &&
993 "Same set of slices formed two different sized partitions!");
994 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
995 "Same slice position with differently sized non-empty split "
1018 return make_range(partition_iterator(begin(), end()),
1019 partition_iterator(end(), end()));
1027 return SI.getOperand(1 + CI->isZero());
1028 if (
SI.getOperand(1) ==
SI.getOperand(2))
1029 return SI.getOperand(1);
1038 return PN->hasConstantValue();
1053 const uint64_t AllocSize;
1069 if (VisitedDeadInsts.
insert(&
I).second)
1074 bool IsSplittable =
false) {
1080 <<
" which has zero size or starts outside of the "
1081 << AllocSize <<
" byte alloca:\n"
1082 <<
" alloca: " << AS.AI <<
"\n"
1083 <<
" use: " <<
I <<
"\n");
1084 return markAsDead(
I);
1096 assert(AllocSize >= BeginOffset);
1097 if (
Size > AllocSize - BeginOffset) {
1099 <<
Offset <<
" to remain within the " << AllocSize
1100 <<
" byte alloca:\n"
1101 <<
" alloca: " << AS.AI <<
"\n"
1102 <<
" use: " <<
I <<
"\n");
1103 EndOffset = AllocSize;
1106 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
1109 void visitBitCastInst(BitCastInst &BC) {
1111 return markAsDead(BC);
1113 return Base::visitBitCastInst(BC);
1116 void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
1118 return markAsDead(ASC);
1120 return Base::visitAddrSpaceCastInst(ASC);
1123 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1125 return markAsDead(GEPI);
1127 return Base::visitGetElementPtrInst(GEPI);
1130 void handleLoadOrStore(
Type *Ty, Instruction &
I,
const APInt &
Offset,
1141 void visitLoadInst(LoadInst &LI) {
1143 "All simple FCA loads should have been pre-split");
1148 return PI.setEscapedReadOnly(&LI);
1151 if (
Size.isScalable()) {
1154 return PI.setAborted(&LI);
1163 void visitStoreInst(StoreInst &SI) {
1164 Value *ValOp =
SI.getValueOperand();
1166 return PI.setEscapedAndAborted(&SI);
1168 return PI.setAborted(&SI);
1170 TypeSize StoreSize =
DL.getTypeStoreSize(ValOp->
getType());
1172 unsigned VScale =
SI.getFunction()->getVScaleValue();
1174 return PI.setAborted(&SI);
1190 <<
Offset <<
" which extends past the end of the "
1191 << AllocSize <<
" byte alloca:\n"
1192 <<
" alloca: " << AS.AI <<
"\n"
1193 <<
" use: " << SI <<
"\n");
1194 return markAsDead(SI);
1198 "All simple FCA stores should have been pre-split");
1202 void visitMemSetInst(MemSetInst &
II) {
1203 assert(
II.getRawDest() == *U &&
"Pointer use is not the destination?");
1206 (IsOffsetKnown &&
Offset.uge(AllocSize)))
1208 return markAsDead(
II);
1211 return PI.setAborted(&
II);
1215 : AllocSize -
Offset.getLimitedValue(),
1219 void visitMemTransferInst(MemTransferInst &
II) {
1223 return markAsDead(
II);
1227 if (VisitedDeadInsts.
count(&
II))
1231 return PI.setAborted(&
II);
1238 if (
Offset.uge(AllocSize)) {
1239 auto MTPI = MemTransferSliceMap.
find(&
II);
1240 if (MTPI != MemTransferSliceMap.
end())
1241 AS.Slices[MTPI->second].kill();
1242 return markAsDead(
II);
1250 if (*U ==
II.getRawDest() && *U ==
II.getRawSource()) {
1252 if (!
II.isVolatile())
1253 return markAsDead(
II);
1261 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
1262 std::tie(MTPI, Inserted) =
1263 MemTransferSliceMap.
insert(std::make_pair(&
II, AS.Slices.size()));
1264 unsigned PrevIdx = MTPI->second;
1266 Slice &PrevP = AS.Slices[PrevIdx];
1270 if (!
II.isVolatile() && PrevP.beginOffset() == RawOffset) {
1272 return markAsDead(
II);
1277 PrevP.makeUnsplittable();
1284 assert(AS.Slices[PrevIdx].getUse()->getUser() == &
II &&
1285 "Map index doesn't point back to a slice with this user.");
1291 void visitIntrinsicInst(IntrinsicInst &
II) {
1292 if (
II.isDroppable()) {
1293 AS.DeadUseIfPromotable.push_back(U);
1298 return PI.setAborted(&
II);
1300 if (
II.isLifetimeStartOrEnd()) {
1301 insertUse(
II,
Offset, AllocSize,
true);
1305 Base::visitIntrinsicInst(
II);
1313 SmallPtrSet<Instruction *, 4> Visited;
1323 std::tie(UsedI,
I) =
Uses.pop_back_val();
1326 TypeSize LoadSize =
DL.getTypeStoreSize(LI->
getType());
1338 TypeSize StoreSize =
DL.getTypeStoreSize(
Op->getType());
1348 if (!
GEP->hasAllZeroIndices())
1355 for (User *U :
I->users())
1358 }
while (!
Uses.empty());
1363 void visitPHINodeOrSelectInst(Instruction &
I) {
1366 return markAsDead(
I);
1372 return PI.setAborted(&
I);
1390 AS.DeadOperands.push_back(U);
1396 return PI.setAborted(&
I);
1402 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&
I,
Size))
1403 return PI.setAborted(UnsafeI);
1412 if (
Offset.uge(AllocSize)) {
1413 AS.DeadOperands.push_back(U);
1420 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
1422 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
1425 void visitInstruction(Instruction &
I) { PI.setAborted(&
I); }
1427 void visitCallBase(CallBase &CB) {
1433 PI.setEscapedReadOnly(&CB);
1437 Base::visitCallBase(CB);
1441AllocaSlices::AllocaSlices(
const DataLayout &
DL, AllocaInst &AI)
1443#
if !defined(
NDEBUG) || defined(LLVM_ENABLE_DUMP)
1446 PointerEscapingInstr(nullptr), PointerEscapingInstrReadOnly(nullptr) {
1448 SliceBuilder::PtrInfo PtrI =
PB.visitPtr(AI);
1449 if (PtrI.isEscaped() || PtrI.isAborted()) {
1452 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1453 : PtrI.getAbortingInst();
1454 assert(PointerEscapingInstr &&
"Did not track a bad instruction");
1457 PointerEscapingInstrReadOnly = PtrI.getEscapedReadOnlyInst();
1459 llvm::erase_if(Slices, [](
const Slice &S) {
return S.isDead(); });
1466#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1468void AllocaSlices::print(raw_ostream &OS, const_iterator
I,
1469 StringRef Indent)
const {
1470 printSlice(OS,
I, Indent);
1472 printUse(OS,
I, Indent);
1475void AllocaSlices::printSlice(raw_ostream &OS, const_iterator
I,
1476 StringRef Indent)
const {
1477 OS << Indent <<
"[" <<
I->beginOffset() <<
"," <<
I->endOffset() <<
")"
1478 <<
" slice #" << (
I -
begin())
1479 << (
I->isSplittable() ?
" (splittable)" :
"");
1482void AllocaSlices::printUse(raw_ostream &OS, const_iterator
I,
1483 StringRef Indent)
const {
1484 OS << Indent <<
" used by: " << *
I->getUse()->getUser() <<
"\n";
1487void AllocaSlices::print(raw_ostream &OS)
const {
1488 if (PointerEscapingInstr) {
1489 OS <<
"Can't analyze slices for alloca: " << AI <<
"\n"
1490 <<
" A pointer to this alloca escaped by:\n"
1491 <<
" " << *PointerEscapingInstr <<
"\n";
1495 if (PointerEscapingInstrReadOnly)
1496 OS <<
"Escapes into ReadOnly: " << *PointerEscapingInstrReadOnly <<
"\n";
1498 OS <<
"Slices of alloca: " << AI <<
"\n";
1519 for (
User *U :
I.users()) {
1520 Type *UserTy =
nullptr;
1526 UserTy =
Store->getValueOperand()->getType();
1528 if (!UserTy || (Ty && Ty != UserTy))
1538static std::pair<Type *, IntegerType *>
1542 bool TyIsCommon =
true;
1547 for (AllocaSlices::const_iterator
I =
B;
I !=
E; ++
I) {
1548 Use *U =
I->getUse();
1551 if (
I->beginOffset() !=
B->beginOffset() ||
I->endOffset() != EndOffset)
1554 Type *UserTy =
nullptr;
1558 UserTy =
SI->getValueOperand()->getType();
1569 if (UserITy->getBitWidth() % 8 != 0 ||
1570 UserITy->getBitWidth() / 8 > (EndOffset -
B->beginOffset()))
1575 if (!ITy || ITy->
getBitWidth() < UserITy->getBitWidth())
1581 if (!UserTy || (Ty && Ty != UserTy))
1587 return {TyIsCommon ? Ty :
nullptr, ITy};
1617 Type *LoadType =
nullptr;
1630 if (LoadType != LI->
getType())
1639 if (BBI->mayWriteToMemory())
1642 MaxAlign = std::max(MaxAlign, LI->
getAlign());
1649 APInt(APWidth,
DL.getTypeStoreSize(LoadType).getFixedValue());
1692 if (!
SI ||
SI->getPointerOperand() != &PN)
1695 if (
SI->isVolatile())
1703 Value *StoredValue =
SI->getValueOperand();
1742 IRB.SetInsertPoint(&PN);
1744 PN.
getName() +
".sroa.speculated");
1774 IRB.SetInsertPoint(TI);
1777 LoadTy, InVal, Alignment,
1778 (PN.
getName() +
".sroa.speculate.load." +
Pred->getName()));
1779 ++NumLoadsSpeculated;
1781 Load->setAAMetadata(AATags);
1795 <<
" " <<
SI <<
"\n");
1813 bool CFGChanged =
false;
1815 for (
auto [
Pred, InVal] : IncomingValues) {
1817 if (
Pred->getTerminator()->getNumSuccessors() != 1) {
1819 assert(StoreBB &&
"store edge was not checked for splitting");
1826 ++NumStoresPredicated;
1830 SI.eraseFromParent();
1835SelectHandSpeculativity &
1836SelectHandSpeculativity::setAsSpeculatable(
bool isTrueVal) {
1844bool SelectHandSpeculativity::isSpeculatable(
bool isTrueVal)
const {
1849bool SelectHandSpeculativity::areAllSpeculatable()
const {
1850 return isSpeculatable(
true) &&
1851 isSpeculatable(
false);
1854bool SelectHandSpeculativity::areAnySpeculatable()
const {
1855 return isSpeculatable(
true) ||
1856 isSpeculatable(
false);
1858bool SelectHandSpeculativity::areNoneSpeculatable()
const {
1859 return !areAnySpeculatable();
1862static SelectHandSpeculativity
1865 SelectHandSpeculativity
Spec;
1871 Spec.setAsSpeculatable(
Value ==
SI.getTrueValue());
1872 else if (PreserveCFG)
1878std::optional<RewriteableMemOps>
1879SROA::isSafeSelectToSpeculateOrPredicate(SelectInst &SI,
bool PreserveCFG) {
1880 RewriteableMemOps
Ops;
1883 for (User *U :
SI.users()) {
1890 for (User *U :
Users) {
1893 if (
Store->isVolatile() || PreserveCFG)
1904 PossiblySpeculatableLoad
Load(LI);
1919 SelectHandSpeculativity Spec =
1921 if (PreserveCFG && !Spec.areAllSpeculatable())
1935 Value *TV =
SI.getTrueValue();
1936 Value *FV =
SI.getFalseValue();
1941 IRB.SetInsertPoint(&LI);
1945 LI.
getName() +
".sroa.speculate.cast.true");
1947 LI.
getName() +
".sroa.speculate.cast.false");
1951 LI.
getName() +
".sroa.speculate.load.true");
1954 LI.
getName() +
".sroa.speculate.load.false");
1955 NumLoadsSpeculated += 2;
1967 Value *
V = IRB.CreateSelect(
SI.getCondition(), TL, FL,
1968 LI.
getName() +
".sroa.speculated", &
SI);
1974template <
typename T>
1976 SelectHandSpeculativity
Spec, IRBuilderTy &IRB,
1983 if (
Spec.areNoneSpeculatable())
1985 SI.getMetadata(LLVMContext::MD_prof), &DTU);
1988 SI.getMetadata(LLVMContext::MD_prof), &DTU,
1990 if (
Spec.isSpeculatable(
true))
1996 Tail->setName(Head->
getName() +
".cont");
2001 bool IsThen = SuccBB == HeadBI->getSuccessor(0);
2002 int SuccIdx = IsThen ? 0 : 1;
2003 auto *NewMemOpBB = SuccBB == Tail ? Head : SuccBB;
2004 auto &CondMemOp =
cast<T>(*
I.clone());
2005 if (NewMemOpBB != Head) {
2006 NewMemOpBB->setName(Head->
getName() + (IsThen ?
".then" :
".else"));
2008 ++NumLoadsPredicated;
2010 ++NumStoresPredicated;
2012 CondMemOp.dropUBImplyingAttrsAndMetadata();
2013 ++NumLoadsSpeculated;
2015 CondMemOp.insertBefore(NewMemOpBB->getTerminator()->getIterator());
2016 Value *Ptr =
SI.getOperand(1 + SuccIdx);
2019 IRB.SetInsertPoint(&CondMemOp);
2020 Ptr = IRB.CreateAddrSpaceCast(Ptr,
I.getPointerOperandType(),
2021 I.getName() + (IsThen ?
".then" :
".else") +
2023 CondMemOp.setOperand(
I.getPointerOperandIndex(), Ptr);
2025 CondMemOp.setName(
I.getName() + (IsThen ?
".then" :
".else") +
".val");
2033 I.replaceAllUsesWith(PN);
2038 SelectHandSpeculativity
Spec, IRBuilderTy &IRB,
2049 const RewriteableMemOps &
Ops,
2051 bool CFGChanged =
false;
2054 for (
const RewriteableMemOp &
Op :
Ops) {
2055 SelectHandSpeculativity
Spec;
2057 if (
auto *
const *US = std::get_if<UnspeculatableStore>(&
Op)) {
2060 auto PSL = std::get<PossiblySpeculatableLoad>(
Op);
2061 I = PSL.getPointer();
2062 Spec = PSL.getInt();
2064 if (
Spec.areAllSpeculatable()) {
2067 assert(DTU &&
"Should not get here when not allowed to modify the CFG!");
2071 I->eraseFromParent();
2076 SI.eraseFromParent();
2084 const Twine &NamePrefix) {
2086 Ptr = IRB.CreateInBoundsPtrAdd(Ptr, IRB.getInt(
Offset),
2087 NamePrefix +
"sroa_idx");
2088 return IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr,
PointerTy,
2089 NamePrefix +
"sroa_cast");
2104 unsigned VScale = 0) {
2114 "We can't have the same bitwidth for different int types");
2118 TypeSize NewSize =
DL.getTypeSizeInBits(NewTy);
2119 TypeSize OldSize =
DL.getTypeSizeInBits(OldTy);
2146 if (NewSize != OldSize)
2162 return OldAS == NewAS ||
2163 (!
DL.isNonIntegralAddressSpace(OldAS) &&
2164 !
DL.isNonIntegralAddressSpace(NewAS) &&
2165 DL.getPointerSize(OldAS) ==
DL.getPointerSize(NewAS));
2171 return !
DL.isNonIntegralPointerType(NewTy);
2175 if (!
DL.isNonIntegralPointerType(OldTy))
2199 (std::max(S.beginOffset(),
P.beginOffset()) -
P.beginOffset()) * 8;
2200 uint64_t BeginIndex = BeginBit / ElementBits;
2201 if (BeginIndex * ElementBits != BeginBit ||
2205 (std::min(S.endOffset(),
P.endOffset()) -
P.beginOffset()) * 8;
2206 uint64_t EndIndex = EndBit / ElementBits;
2207 if (EndIndex * ElementBits != EndBit ||
2211 assert(EndIndex > BeginIndex &&
"Empty vector!");
2212 uint64_t NumElements = EndIndex - BeginIndex;
2213 Type *SliceTy = (NumElements == 1)
2214 ? Ty->getElementType()
2220 Use *U = S.getUse();
2223 if (
MI->isVolatile())
2225 if (!S.isSplittable())
2230 Type *SplatDstTy = ElementBits % 8 ? SliceTy : Ty->getElementType();
2232 Ty->getContext(),
DL.getTypeSizeInBits(SplatDstTy).getFixedValue());
2237 if (!
II->isLifetimeStartOrEnd() && !
II->isDroppable())
2244 if (LTy->isStructTy())
2246 if (
P.beginOffset() > S.beginOffset() ||
P.endOffset() < S.endOffset()) {
2247 assert(LTy->isIntegerTy());
2253 if (
SI->isVolatile())
2255 Type *STy =
SI->getValueOperand()->getType();
2259 if (
P.beginOffset() > S.beginOffset() ||
P.endOffset() < S.endOffset()) {
2279 bool HaveCommonEltTy,
Type *CommonEltTy,
2280 bool HaveVecPtrTy,
bool HaveCommonVecPtrTy,
2281 VectorType *CommonVecPtrTy,
unsigned VScale) {
2283 if (CandidateTys.
empty())
2290 if (HaveVecPtrTy && !HaveCommonVecPtrTy)
2294 if (!HaveCommonEltTy && HaveVecPtrTy) {
2296 CandidateTys.
clear();
2298 }
else if (!HaveCommonEltTy && !HaveVecPtrTy) {
2301 if (!VTy->getElementType()->isIntegerTy())
2303 VTy->getContext(), VTy->getScalarSizeInBits())));
2310 assert(
DL.getTypeSizeInBits(RHSTy).getFixedValue() ==
2311 DL.getTypeSizeInBits(LHSTy).getFixedValue() &&
2312 "Cannot have vector types of different sizes!");
2313 assert(RHSTy->getElementType()->isIntegerTy() &&
2314 "All non-integer types eliminated!");
2315 assert(LHSTy->getElementType()->isIntegerTy() &&
2316 "All non-integer types eliminated!");
2322 assert(
DL.getTypeSizeInBits(RHSTy).getFixedValue() ==
2323 DL.getTypeSizeInBits(LHSTy).getFixedValue() &&
2324 "Cannot have vector types of different sizes!");
2325 assert(RHSTy->getElementType()->isIntegerTy() &&
2326 "All non-integer types eliminated!");
2327 assert(LHSTy->getElementType()->isIntegerTy() &&
2328 "All non-integer types eliminated!");
2332 llvm::sort(CandidateTys, RankVectorTypesComp);
2333 CandidateTys.erase(
llvm::unique(CandidateTys, RankVectorTypesEq),
2334 CandidateTys.end());
2340 assert(VTy->getElementType() == CommonEltTy &&
2341 "Unaccounted for element type!");
2342 assert(VTy == CandidateTys[0] &&
2343 "Different vector types with the same element type!");
2346 CandidateTys.resize(1);
2353 std::numeric_limits<unsigned short>::max();
2359 DL.getTypeSizeInBits(VTy->getElementType()).getFixedValue();
2363 if (ElementBits > 8 && ElementBits % 8)
2366 for (
const Slice &S :
P)
2370 for (
const Slice *S :
P.splitSliceTails())
2376 return VTy != CandidateTys.
end() ? *VTy :
nullptr;
2383 bool &HaveCommonEltTy,
Type *&CommonEltTy,
bool &HaveVecPtrTy,
2384 bool &HaveCommonVecPtrTy,
VectorType *&CommonVecPtrTy,
unsigned VScale) {
2386 CandidateTysCopy.
size() ? CandidateTysCopy[0] :
nullptr;
2389 for (
Type *Ty : OtherTys) {
2392 unsigned TypeSize =
DL.getTypeSizeInBits(Ty).getFixedValue();
2395 for (
VectorType *
const VTy : CandidateTysCopy) {
2397 assert(CandidateTysCopy[0] == OriginalElt &&
"Different Element");
2398 unsigned VectorSize =
DL.getTypeSizeInBits(VTy).getFixedValue();
2399 unsigned ElementSize =
2400 DL.getTypeSizeInBits(VTy->getElementType()).getFixedValue();
2404 CheckCandidateType(NewVTy);
2410 P,
DL, CandidateTys, HaveCommonEltTy, CommonEltTy, HaveVecPtrTy,
2411 HaveCommonVecPtrTy, CommonVecPtrTy, VScale);
2430 Type *CommonEltTy =
nullptr;
2432 bool HaveVecPtrTy =
false;
2433 bool HaveCommonEltTy =
true;
2434 bool HaveCommonVecPtrTy =
true;
2435 auto CheckCandidateType = [&](
Type *Ty) {
2438 if (!CandidateTys.
empty()) {
2440 if (
DL.getTypeSizeInBits(VTy).getFixedValue() !=
2441 DL.getTypeSizeInBits(
V).getFixedValue()) {
2442 CandidateTys.
clear();
2447 Type *EltTy = VTy->getElementType();
2450 CommonEltTy = EltTy;
2451 else if (CommonEltTy != EltTy)
2452 HaveCommonEltTy =
false;
2455 HaveVecPtrTy =
true;
2456 if (!CommonVecPtrTy)
2457 CommonVecPtrTy = VTy;
2458 else if (CommonVecPtrTy != VTy)
2459 HaveCommonVecPtrTy =
false;
2465 for (
const Slice &S :
P) {
2470 Ty =
SI->getValueOperand()->getType();
2474 auto CandTy = Ty->getScalarType();
2475 if (CandTy->isPointerTy() && (S.beginOffset() !=
P.beginOffset() ||
2476 S.endOffset() !=
P.endOffset())) {
2483 if (S.beginOffset() ==
P.beginOffset() && S.endOffset() ==
P.endOffset())
2484 CheckCandidateType(Ty);
2489 LoadStoreTys, CandidateTysCopy, CheckCandidateType,
P,
DL,
2490 CandidateTys, HaveCommonEltTy, CommonEltTy, HaveVecPtrTy,
2491 HaveCommonVecPtrTy, CommonVecPtrTy, VScale))
2494 CandidateTys.
clear();
2496 DeferredTys, CandidateTysCopy, CheckCandidateType,
P,
DL, CandidateTys,
2497 HaveCommonEltTy, CommonEltTy, HaveVecPtrTy, HaveCommonVecPtrTy,
2498 CommonVecPtrTy, VScale);
2509 bool &WholeAllocaOp) {
2512 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2513 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
2515 Use *U = S.getUse();
2522 if (
II->isLifetimeStartOrEnd() ||
II->isDroppable())
2540 if (S.beginOffset() < AllocBeginOffset)
2546 WholeAllocaOp =
true;
2548 if (ITy->getBitWidth() <
DL.getTypeStoreSizeInBits(ITy).getFixedValue())
2550 }
else if (RelBegin != 0 || RelEnd !=
Size ||
2557 Type *ValueTy =
SI->getValueOperand()->getType();
2558 if (
SI->isVolatile())
2561 TypeSize StoreSize =
DL.getTypeStoreSize(ValueTy);
2566 if (S.beginOffset() < AllocBeginOffset)
2572 WholeAllocaOp =
true;
2574 if (ITy->getBitWidth() <
DL.getTypeStoreSizeInBits(ITy).getFixedValue())
2576 }
else if (RelBegin != 0 || RelEnd !=
Size ||
2585 if (!S.isSplittable())
2602 uint64_t SizeInBits =
DL.getTypeSizeInBits(AllocaTy).getFixedValue();
2608 if (SizeInBits !=
DL.getTypeStoreSizeInBits(AllocaTy).getFixedValue())
2626 bool WholeAllocaOp =
P.empty() &&
DL.isLegalInteger(SizeInBits);
2628 for (
const Slice &S :
P)
2633 for (
const Slice *S :
P.splitSliceTails())
2638 return WholeAllocaOp;
2643 const Twine &Name) {
2647 DL.getTypeStoreSize(IntTy).getFixedValue() &&
2648 "Element extends past full value");
2650 if (
DL.isBigEndian())
2651 ShAmt = 8 * (
DL.getTypeStoreSize(IntTy).getFixedValue() -
2652 DL.getTypeStoreSize(Ty).getFixedValue() -
Offset);
2654 V = IRB.CreateLShr(
V, ShAmt, Name +
".shift");
2657 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2658 "Cannot extract to a larger integer!");
2660 V = IRB.CreateTrunc(
V, Ty, Name +
".trunc");
2670 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2671 "Cannot insert a larger integer!");
2674 V = IRB.CreateZExt(
V, IntTy, Name +
".ext");
2678 DL.getTypeStoreSize(IntTy).getFixedValue() &&
2679 "Element store outside of alloca store");
2681 if (
DL.isBigEndian())
2682 ShAmt = 8 * (
DL.getTypeStoreSize(IntTy).getFixedValue() -
2683 DL.getTypeStoreSize(Ty).getFixedValue() -
Offset);
2685 V = IRB.CreateShl(
V, ShAmt, Name +
".shift");
2689 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2690 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2691 Old = IRB.CreateAnd(Old, Mask, Name +
".mask");
2693 V = IRB.CreateOr(Old,
V, Name +
".insert");
2700 unsigned EndIndex,
const Twine &Name) {
2702 unsigned NumElements = EndIndex - BeginIndex;
2703 assert(NumElements <= VecTy->getNumElements() &&
"Too many elements!");
2705 if (NumElements == VecTy->getNumElements())
2708 if (NumElements == 1) {
2709 V = IRB.CreateExtractElement(
V, BeginIndex, Name +
".extract");
2715 V = IRB.CreateShuffleVector(
V, Mask, Name +
".extract");
2721 unsigned BeginIndex,
const Twine &Name) {
2723 assert(VecTy &&
"Can only insert a vector into a vector");
2728 V = IRB.CreateInsertElement(Old,
V, BeginIndex, Name +
".insert");
2736 assert(NumSubElements <= NumElements &&
"Too many elements!");
2737 if (NumSubElements == NumElements) {
2738 assert(
V->getType() == VecTy &&
"Vector type mismatch");
2741 unsigned EndIndex = BeginIndex + NumSubElements;
2748 Mask.reserve(NumElements);
2749 for (
unsigned Idx = 0; Idx != NumElements; ++Idx)
2750 if (Idx >= BeginIndex && Idx < EndIndex)
2751 Mask.push_back(Idx - BeginIndex);
2754 V = IRB.CreateShuffleVector(
V, Mask, Name +
".expand");
2758 for (
unsigned Idx = 0; Idx != NumElements; ++Idx)
2759 if (Idx >= BeginIndex && Idx < EndIndex)
2760 Mask.push_back(Idx);
2762 Mask.push_back(Idx + NumElements);
2763 V = IRB.CreateShuffleVector(
V, Old, Mask, Name +
"blend");
2802 const char *DebugName) {
2803 Type *EltType = VecType->getElementType();
2804 if (EltType != NewAIEltTy) {
2806 unsigned TotalBits =
2807 VecType->getNumElements() *
DL.getTypeSizeInBits(EltType);
2808 unsigned NewNumElts = TotalBits /
DL.getTypeSizeInBits(NewAIEltTy);
2811 V = Builder.CreateBitCast(
V, NewVecType);
2812 VecType = NewVecType;
2817 BitcastIfNeeded(V0, VecType0,
"V0");
2818 BitcastIfNeeded(
V1, VecType1,
"V1");
2820 unsigned NumElts0 = VecType0->getNumElements();
2821 unsigned NumElts1 = VecType1->getNumElements();
2825 if (NumElts0 == NumElts1) {
2826 for (
unsigned i = 0; i < NumElts0 + NumElts1; ++i)
2827 ShuffleMask.push_back(i);
2831 unsigned SmallSize = std::min(NumElts0, NumElts1);
2832 unsigned LargeSize = std::max(NumElts0, NumElts1);
2833 bool IsV0Smaller = NumElts0 < NumElts1;
2834 Value *&ExtendedVec = IsV0Smaller ? V0 :
V1;
2836 for (
unsigned i = 0; i < SmallSize; ++i)
2838 for (
unsigned i = SmallSize; i < LargeSize; ++i)
2840 ExtendedVec = Builder.CreateShuffleVector(
2842 LLVM_DEBUG(
dbgs() <<
" shufflevector: " << *ExtendedVec <<
"\n");
2843 for (
unsigned i = 0; i < NumElts0; ++i)
2844 ShuffleMask.push_back(i);
2845 for (
unsigned i = 0; i < NumElts1; ++i)
2846 ShuffleMask.push_back(LargeSize + i);
2849 return Builder.CreateShuffleVector(V0,
V1, ShuffleMask);
2860class AllocaSliceRewriter :
public InstVisitor<AllocaSliceRewriter, bool> {
2862 friend class InstVisitor<AllocaSliceRewriter, bool>;
2864 using Base = InstVisitor<AllocaSliceRewriter, bool>;
2866 const DataLayout &
DL;
2869 AllocaInst &OldAI, &NewAI;
2870 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2899 uint64_t NewBeginOffset = 0, NewEndOffset = 0;
2902 bool IsSplittable =
false;
2903 bool IsSplit =
false;
2904 Use *OldUse =
nullptr;
2908 SmallSetVector<PHINode *, 8> &PHIUsers;
2909 SmallSetVector<SelectInst *, 8> &SelectUsers;
2917 Value *getPtrToNewAI(
unsigned AddrSpace,
bool IsVolatile) {
2921 Type *AccessTy = IRB.getPtrTy(AddrSpace);
2922 return IRB.CreateAddrSpaceCast(&NewAI, AccessTy);
2926 AllocaSliceRewriter(
const DataLayout &
DL, AllocaSlices &AS, SROA &
Pass,
2927 AllocaInst &OldAI, AllocaInst &NewAI,
Type *NewAllocaTy,
2929 uint64_t NewAllocaEndOffset,
bool IsIntegerPromotable,
2930 VectorType *PromotableVecTy,
2931 SmallSetVector<PHINode *, 8> &PHIUsers,
2932 SmallSetVector<SelectInst *, 8> &SelectUsers)
2933 :
DL(
DL), AS(AS),
Pass(
Pass), OldAI(OldAI), NewAI(NewAI),
2934 NewAllocaBeginOffset(NewAllocaBeginOffset),
2935 NewAllocaEndOffset(NewAllocaEndOffset), NewAllocaTy(NewAllocaTy),
2936 IntTy(IsIntegerPromotable
2939 DL.getTypeSizeInBits(NewAllocaTy).getFixedValue())
2941 VecTy(PromotableVecTy),
2942 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2943 ElementBits(VecTy ?
DL.getTypeSizeInBits(ElementTy).getFixedValue()
2945 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2946 IRB(*NewAI.getModule(), ConstantFolder()) {
2948 assert((
DL.getTypeSizeInBits(VecTy).getFixedValue() % 8) == 0 &&
2949 "Only vectors of whole bytes are viable");
2952 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2955 bool visit(AllocaSlices::const_iterator
I) {
2956 bool CanSROA =
true;
2957 BeginOffset =
I->beginOffset();
2958 EndOffset =
I->endOffset();
2959 IsSplittable =
I->isSplittable();
2961 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2962 LLVM_DEBUG(
dbgs() <<
" rewriting " << (IsSplit ?
"split " :
""));
2967 assert(BeginOffset < NewAllocaEndOffset);
2968 assert(EndOffset > NewAllocaBeginOffset);
2969 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2970 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2972 SliceSize = NewEndOffset - NewBeginOffset;
2973 LLVM_DEBUG(
dbgs() <<
" Begin:(" << BeginOffset <<
", " << EndOffset
2974 <<
") NewBegin:(" << NewBeginOffset <<
", "
2975 << NewEndOffset <<
") NewAllocaBegin:("
2976 << NewAllocaBeginOffset <<
", " << NewAllocaEndOffset
2978 assert(IsSplit || NewBeginOffset == BeginOffset);
2979 OldUse =
I->getUse();
2983 IRB.SetInsertPoint(OldUserI);
2984 IRB.SetCurrentDebugLocation(OldUserI->
getDebugLoc());
2986 if (!IRB.getContext().shouldDiscardValueNames())
2987 IRB.getInserter().SetNamePrefix(Twine(NewAI.
getName()) +
"." +
2988 Twine(BeginOffset) +
".");
3050 std::optional<SmallVector<Value *, 4>>
3051 rewriteTreeStructuredMerge(Partition &
P) {
3053 if (
P.splitSliceTails().size() > 0)
3054 return std::nullopt;
3063 :
Store(
SI), BeginOffset(Begin), EndOffset(
End), StoredValue(Val) {}
3073 LoadInst *FullLoad =
nullptr;
3074 StoreInst *InitStore =
nullptr;
3078 Type *AllocatedEltTy =
3082 unsigned AllocatedEltTySize =
DL.getTypeSizeInBits(AllocatedEltTy);
3089 auto IsTypeValidForTreeStructuredMerge = [&](
Type *Ty) ->
bool {
3091 return FixedVecTy &&
3092 DL.getTypeSizeInBits(FixedVecTy->getElementType()) % 8 == 0 &&
3093 !FixedVecTy->getElementType()->isPointerTy();
3096 for (Slice &S :
P) {
3100 bool IsFullWidth = (S.beginOffset() == NewAllocaBeginOffset &&
3101 S.endOffset() == NewAllocaEndOffset);
3105 !IsTypeValidForTreeStructuredMerge(LI->
getType()))
3106 return std::nullopt;
3111 return std::nullopt;
3115 LoadInfos.
push_back({LI, S.beginOffset(), S.endOffset()});
3127 if (!
SI->isSimple() || !IsTypeValidForTreeStructuredMerge(
3128 SI->getValueOperand()->getType()))
3129 return std::nullopt;
3131 unsigned NumElts = StVecTy->getNumElements();
3132 unsigned EltSize =
DL.getTypeSizeInBits(StVecTy->getElementType());
3133 if (NumElts * EltSize % AllocatedEltTySize != 0)
3134 return std::nullopt;
3139 return std::nullopt;
3142 StoreInfos.
emplace_back(SI, S.beginOffset(), S.endOffset(),
3143 SI->getValueOperand());
3148 return std::nullopt;
3155 if (StoreInfos.
size() < 2)
3156 return std::nullopt;
3164 bool IsRMWPattern = InitStore && VecTy && !LoadInfos.
empty();
3165 bool IsStoresOnlyPattern = !InitStore && FullLoad && LoadInfos.
empty();
3166 if (!IsRMWPattern && !IsStoresOnlyPattern)
3167 return std::nullopt;
3171 BasicBlock *StoreBB = StoreInfos[0].Store->getParent();
3172 for (
auto &Info : StoreInfos)
3173 if (
Info.Store->getParent() != StoreBB)
3174 return std::nullopt;
3176 SmallVector<Value *, 4> DeletedValues;
3183 auto TreeMerge = [&](SmallVectorImpl<Value *> &Vals,
3186 while (Vals.
size() > 1) {
3187 SmallVector<Value *, 8>
Next;
3188 for (
unsigned I = 0,
E = Vals.
size();
I + 1 <
E;
I += 2) {
3194 if (Vals.
size() % 2 == 1)
3196 Vals = std::move(
Next);
3205 auto ReplaceFullLoad = [&](LoadInst *LoadToReplace,
Value *Merged) {
3207 Value *NewLoad = LoadBuilder.CreateAlignedLoad(
3208 Merged->getType(), &NewAI, getSliceAlign(),
3210 LoadToReplace->
getName() +
".sroa.new.load");
3212 NewLoad = LoadBuilder.CreateBitCast(NewLoad, LoadToReplace->
getType());
3217 if (IsStoresOnlyPattern) {
3220 llvm::sort(StoreInfos, [](
const StoreInfo &
A,
const StoreInfo &
B) {
3221 return A.BeginOffset <
B.BeginOffset;
3226 uint64_t Expected = NewAllocaBeginOffset;
3227 for (
auto &Info : StoreInfos) {
3228 if (
Info.BeginOffset != Expected)
3229 return std::nullopt;
3230 Expected =
Info.EndOffset;
3233 if (Expected != NewAllocaEndOffset)
3234 return std::nullopt;
3244 if (LoadBB == StoreBB) {
3245 for (
auto &Info : StoreInfos)
3246 if (!
Info.Store->comesBefore(FullLoad))
3247 return std::nullopt;
3251 dbgs() <<
"Tree structured merge rewrite (stores-only):\n";
3252 dbgs() <<
" Load: " << *FullLoad <<
"\n Ordered stores:\n";
3253 for (
auto [
I, Info] :
enumerate(StoreInfos)) {
3254 dbgs() <<
" [" <<
I <<
"] Range[" <<
Info.BeginOffset <<
", "
3255 <<
Info.EndOffset <<
") \tStore: " << *
Info.Store
3256 <<
"\tValue: " << *
Info.StoredValue <<
"\n";
3269 SmallVector<Value *, 8> Vals;
3270 for (
const auto &Info : StoreInfos) {
3275 Value *Merged = TreeMerge(Vals, Builder);
3276 Builder.CreateAlignedStore(Merged, &NewAI, getSliceAlign());
3279 ReplaceFullLoad(FullLoad, Merged);
3280 return DeletedValues;
3288 return std::nullopt;
3289 if (
any_of(LoadInfos, [&](
const LoadInfo &
I) {
3290 return I.Load->getParent() != StoreBB;
3292 return std::nullopt;
3308 Accesses.reserve(LoadInfos.
size() + StoreInfos.size());
3309 for (
const auto &L : LoadInfos)
3310 Accesses.push_back({
L.Load,
L.BeginOffset,
L.EndOffset,
false});
3311 for (
const auto &S : StoreInfos)
3312 Accesses.push_back({S.Store, S.BeginOffset, S.EndOffset,
true});
3314 return A.Inst->comesBefore(
B.Inst);
3322 return std::nullopt;
3328 if (FullLoad && FullLoad->
getParent() == StoreBB &&
3329 !
Accesses.back().Inst->comesBefore(FullLoad))
3330 return std::nullopt;
3341 using SliceRange = std::pair<uint64_t, uint64_t>;
3345 SortedRanges.
emplace_back(Acc.BeginOffset, Acc.EndOffset);
3349 uint64_t Expected = NewAllocaBeginOffset;
3350 for (
auto &
Range : SortedRanges) {
3351 if (
Range.first != Expected)
3352 return std::nullopt;
3353 Expected =
Range.second;
3355 if (Expected != NewAllocaEndOffset)
3356 return std::nullopt;
3359 dbgs() <<
"Tree structured merge rewrite (RMW):\n";
3360 dbgs() <<
" Init store: " << *InitStore <<
"\n";
3362 dbgs() <<
" Final load: " << *FullLoad <<
"\n";
3363 dbgs() <<
" Slice ranges (" << SortedRanges.size() <<
"):\n";
3364 for (
auto &
Range : SortedRanges)
3375 if (InitVec->
getType() != NewAllocaTy)
3376 InitVec = IRB.CreateBitCast(InitVec, NewAllocaTy,
"init.cast");
3377 DenseMap<SliceRange, Value *> SliceValues;
3378 for (
auto &
Range : SortedRanges) {
3379 unsigned BeginIdx = getIndex(
Range.first);
3380 unsigned EndIdx = getIndex(
Range.second);
3381 SliceValues[
Range] = IRB.CreateShuffleVector(
3397 SliceRange
Range{Acc.BeginOffset, Acc.EndOffset};
3400 if (
V->getType() != Acc.Inst->getType()) {
3402 V = IRB.CreateBitCast(
V, Acc.Inst->getType());
3404 Acc.Inst->replaceAllUsesWith(
V);
3421 SmallVector<Value *, 8> Vals;
3422 for (
auto &
Range : SortedRanges)
3424 Value *Merged = TreeMerge(Vals, Builder);
3425 Builder.CreateAlignedStore(Merged, &NewAI, getSliceAlign());
3430 ReplaceFullLoad(FullLoad, Merged);
3432 return DeletedValues;
3440 bool visitInstruction(Instruction &
I) {
3448 assert(IsSplit || BeginOffset == NewBeginOffset);
3451 StringRef OldName = OldPtr->
getName();
3453 size_t LastSROAPrefix = OldName.
rfind(
".sroa.");
3455 OldName = OldName.
substr(LastSROAPrefix + strlen(
".sroa."));
3460 OldName = OldName.
substr(IndexEnd + 1);
3464 OldName = OldName.
substr(OffsetEnd + 1);
3468 OldName = OldName.
substr(0, OldName.
find(
".sroa_"));
3473 Twine(OldName) +
".");
3481 Align getSliceAlign() {
3483 NewBeginOffset - NewAllocaBeginOffset);
3487 assert(VecTy &&
"Can only call getIndex when rewriting a vector");
3489 assert(RelBit / ElementBits < UINT32_MAX &&
"Index out of bounds");
3490 uint32_t
Index = RelBit / ElementBits;
3491 assert(Index * ElementBits == RelBit);
3495 void deleteIfTriviallyDead(
Value *
V) {
3498 Pass.DeadInsts.push_back(
I);
3501 Value *rewriteVectorizedLoadInst(LoadInst &LI) {
3502 unsigned BeginIndex = getIndex(NewBeginOffset);
3503 unsigned EndIndex = getIndex(NewEndOffset);
3504 assert(EndIndex > BeginIndex &&
"Empty vector!");
3507 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.
getAlign(),
"load");
3509 Load->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
3510 LLVMContext::MD_access_group});
3514 Value *rewriteIntegerLoad(LoadInst &LI) {
3515 assert(IntTy &&
"We cannot insert an integer to the alloca");
3518 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.
getAlign(),
"load");
3519 V = IRB.CreateBitPreservingCastChain(
DL,
V, IntTy);
3520 assert(NewBeginOffset >= NewAllocaBeginOffset &&
"Out of bounds offset");
3522 if (
Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
3523 IntegerType *ExtractTy = Type::getIntNTy(LI.
getContext(), SliceSize * 8);
3532 "Can only handle an extract for an overly wide load");
3538 bool visitLoadInst(LoadInst &LI) {
3547 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.
getContext(), SliceSize * 8)
3549 bool IsPtrAdjusted =
false;
3552 V = rewriteVectorizedLoadInst(LI);
3554 V = rewriteIntegerLoad(LI);
3555 }
else if (NewBeginOffset == NewAllocaBeginOffset &&
3556 NewEndOffset == NewAllocaEndOffset &&
3559 DL.getTypeStoreSize(TargetTy).getFixedValue() > SliceSize &&
3562 getPtrToNewAI(LI.getPointerAddressSpace(), LI.isVolatile());
3563 LoadInst *NewLI = IRB.CreateAlignedLoad(
3564 NewAllocaTy, NewPtr, NewAI.getAlign(), LI.isVolatile(), LI.getName());
3565 if (LI.isVolatile())
3566 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
3567 if (NewLI->isAtomic())
3568 NewLI->setAlignment(LI.getAlign());
3573 copyMetadataForLoad(*NewLI, LI);
3577 NewLI->setAAMetadata(AATags.adjustForAccess(
3578 NewBeginOffset - BeginOffset, NewLI->getType(), DL));
3586 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
3587 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
3588 if (AITy->getBitWidth() < TITy->getBitWidth()) {
3589 V = IRB.CreateZExt(V, TITy,
"load.ext");
3590 if (DL.isBigEndian())
3591 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
3595 Type *LTy = IRB.getPtrTy(AS);
3597 IRB.CreateAlignedLoad(TargetTy, getNewAllocaSlicePtr(IRB, LTy),
3602 NewBeginOffset - BeginOffset, NewLI->
getType(),
DL));
3606 NewLI->
copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
3607 LLVMContext::MD_access_group});
3610 IsPtrAdjusted =
true;
3612 V = IRB.CreateBitPreservingCastChain(
DL,
V, TargetTy);
3617 "Only integer type loads and stores are split");
3618 assert(SliceSize <
DL.getTypeStoreSize(LI.
getType()).getFixedValue() &&
3619 "Split load isn't smaller than original load");
3621 "Non-byte-multiple bit width");
3627 LIIt.setHeadBit(
true);
3628 IRB.SetInsertPoint(LIIt);
3633 Value *Placeholder =
3639 Placeholder->replaceAllUsesWith(&LI);
3640 Placeholder->deleteValue();
3645 Pass.DeadInsts.push_back(&LI);
3646 deleteIfTriviallyDead(OldOp);
3651 bool rewriteVectorizedStoreInst(
Value *
V, StoreInst &SI,
Value *OldOp,
3656 if (
V->getType() != VecTy) {
3657 unsigned BeginIndex = getIndex(NewBeginOffset);
3658 unsigned EndIndex = getIndex(NewEndOffset);
3659 assert(EndIndex > BeginIndex &&
"Empty vector!");
3660 unsigned NumElements = EndIndex - BeginIndex;
3662 "Too many elements!");
3663 Type *SliceTy = (NumElements == 1)
3665 : FixedVectorType::
get(ElementTy, NumElements);
3666 if (
V->getType() != SliceTy)
3667 V = IRB.CreateBitPreservingCastChain(
DL,
V, SliceTy);
3671 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.
getAlign(),
"load");
3674 StoreInst *
Store = IRB.CreateAlignedStore(
V, &NewAI, NewAI.
getAlign());
3675 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3676 LLVMContext::MD_access_group});
3680 Pass.DeadInsts.push_back(&SI);
3689 bool rewriteIntegerStore(
Value *
V, StoreInst &SI, AAMDNodes AATags) {
3690 assert(IntTy &&
"We cannot extract an integer from the alloca");
3692 if (
DL.getTypeSizeInBits(
V->getType()).getFixedValue() !=
3694 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.
getAlign(),
3696 Old = IRB.CreateBitPreservingCastChain(
DL, Old, IntTy);
3697 assert(BeginOffset >= NewAllocaBeginOffset &&
"Out of bounds offset");
3701 V = IRB.CreateBitPreservingCastChain(
DL,
V, NewAllocaTy);
3702 StoreInst *
Store = IRB.CreateAlignedStore(
V, &NewAI, NewAI.
getAlign());
3703 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3704 LLVMContext::MD_access_group});
3711 Store->getValueOperand(),
DL);
3713 Pass.DeadInsts.push_back(&SI);
3718 bool visitStoreInst(StoreInst &SI) {
3720 Value *OldOp =
SI.getOperand(1);
3723 AAMDNodes AATags =
SI.getAAMetadata();
3728 if (
V->getType()->isPointerTy())
3730 Pass.PostPromotionWorklist.insert(AI);
3732 TypeSize StoreSize =
DL.getTypeStoreSize(
V->getType());
3735 assert(
V->getType()->isIntegerTy() &&
3736 "Only integer type loads and stores are split");
3737 assert(
DL.typeSizeEqualsStoreSize(
V->getType()) &&
3738 "Non-byte-multiple bit width");
3739 IntegerType *NarrowTy = Type::getIntNTy(
SI.getContext(), SliceSize * 8);
3745 return rewriteVectorizedStoreInst(
V, SI, OldOp, AATags);
3746 if (IntTy &&
V->getType()->isIntegerTy())
3747 return rewriteIntegerStore(
V, SI, AATags);
3750 if (NewBeginOffset == NewAllocaBeginOffset &&
3751 NewEndOffset == NewAllocaEndOffset &&
3753 V = IRB.CreateBitPreservingCastChain(
DL,
V, NewAllocaTy);
3755 getPtrToNewAI(
SI.getPointerAddressSpace(),
SI.isVolatile());
3758 IRB.CreateAlignedStore(
V, NewPtr, NewAI.
getAlign(),
SI.isVolatile());
3760 unsigned AS =
SI.getPointerAddressSpace();
3761 Value *NewPtr = getNewAllocaSlicePtr(IRB, IRB.getPtrTy(AS));
3763 IRB.CreateAlignedStore(
V, NewPtr, getSliceAlign(),
SI.isVolatile());
3765 NewSI->
copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3766 LLVMContext::MD_access_group});
3770 if (
SI.isVolatile())
3779 Pass.DeadInsts.push_back(&SI);
3780 deleteIfTriviallyDead(OldOp);
3798 assert(
Size > 0 &&
"Expected a positive number of bytes.");
3806 IRB.CreateZExt(
V, SplatIntTy,
"zext"),
3816 V = IRB.CreateVectorSplat(NumElements,
V,
"vsplat");
3821 bool visitMemSetInst(MemSetInst &
II) {
3825 AAMDNodes AATags =
II.getAAMetadata();
3831 assert(NewBeginOffset == BeginOffset);
3832 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->
getType()));
3833 II.setDestAlignment(getSliceAlign());
3838 "AT: Unexpected link to non-const GEP");
3839 deleteIfTriviallyDead(OldPtr);
3844 Pass.DeadInsts.push_back(&
II);
3848 const bool CanContinue = [&]() {
3851 if (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset)
3856 if (Len > std::numeric_limits<unsigned>::max())
3858 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.
getContext());
3861 DL.isLegalInteger(
DL.getTypeSizeInBits(ScalarTy).getFixedValue());
3867 Type *SizeTy =
II.getLength()->getType();
3868 unsigned Sz = NewEndOffset - NewBeginOffset;
3871 getNewAllocaSlicePtr(IRB, OldPtr->
getType()),
II.getValue(),
Size,
3872 MaybeAlign(getSliceAlign()),
II.isVolatile()));
3878 New,
New->getRawDest(),
nullptr,
DL);
3893 assert(ElementTy == ScalarTy);
3895 unsigned BeginIndex = getIndex(NewBeginOffset);
3896 unsigned EndIndex = getIndex(NewEndOffset);
3897 assert(EndIndex > BeginIndex &&
"Empty vector!");
3898 unsigned NumElements = EndIndex - BeginIndex;
3900 "Too many elements!");
3903 if (ElementBits % 8) {
3906 Splat = getIntegerSplat(
II.getValue(), NewEndOffset - NewBeginOffset);
3907 Splat = IRB.CreateBitPreservingCastChain(
3910 Splat = getIntegerSplat(
II.getValue(), ElementBits / 8);
3911 Splat = IRB.CreateBitPreservingCastChain(
DL,
Splat, ElementTy);
3912 if (NumElements > 1)
3916 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.
getAlign(),
3925 V = getIntegerSplat(
II.getValue(),
Size);
3927 if (IntTy && (NewBeginOffset != NewAllocaBeginOffset ||
3928 NewEndOffset != NewAllocaEndOffset)) {
3929 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI,
3931 Old = IRB.CreateBitPreservingCastChain(
DL, Old, IntTy);
3935 assert(
V->getType() == IntTy &&
3936 "Wrong type for an alloca wide integer!");
3938 V = IRB.CreateBitPreservingCastChain(
DL,
V, NewAllocaTy);
3941 assert(NewBeginOffset == NewAllocaBeginOffset);
3942 assert(NewEndOffset == NewAllocaEndOffset);
3944 V = getIntegerSplat(
II.getValue(),
3945 DL.getTypeSizeInBits(ScalarTy).getFixedValue() / 8);
3950 V = IRB.CreateBitPreservingCastChain(
DL,
V, NewAllocaTy);
3953 Value *NewPtr = getPtrToNewAI(
II.getDestAddressSpace(),
II.isVolatile());
3955 IRB.CreateAlignedStore(
V, NewPtr, NewAI.
getAlign(),
II.isVolatile());
3956 New->copyMetadata(
II, {LLVMContext::MD_mem_parallel_loop_access,
3957 LLVMContext::MD_access_group});
3963 New,
New->getPointerOperand(),
V,
DL);
3966 return !
II.isVolatile();
3969 bool visitMemTransferInst(MemTransferInst &
II) {
3975 AAMDNodes AATags =
II.getAAMetadata();
3977 bool IsDest = &
II.getRawDestUse() == OldUse;
3978 assert((IsDest &&
II.getRawDest() == OldPtr) ||
3979 (!IsDest &&
II.getRawSource() == OldPtr));
3981 Align SliceAlign = getSliceAlign();
3989 if (!IsSplittable) {
3990 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->
getType());
3995 DbgAssign->getAddress() ==
II.getDest())
3996 DbgAssign->replaceVariableLocationOp(
II.getDest(), AdjustedPtr);
3998 II.setDest(AdjustedPtr);
3999 II.setDestAlignment(SliceAlign);
4001 II.setSource(AdjustedPtr);
4002 II.setSourceAlignment(SliceAlign);
4006 deleteIfTriviallyDead(OldPtr);
4019 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
4020 SliceSize !=
DL.getTypeStoreSize(NewAllocaTy).getFixedValue() ||
4021 !
DL.typeSizeEqualsStoreSize(NewAllocaTy) ||
4027 if (EmitMemCpy && &OldAI == &NewAI) {
4029 assert(NewBeginOffset == BeginOffset);
4032 if (NewEndOffset != EndOffset)
4033 II.setLength(NewEndOffset - NewBeginOffset);
4037 Pass.DeadInsts.push_back(&
II);
4041 Value *OtherPtr = IsDest ?
II.getRawSource() :
II.getRawDest();
4042 if (AllocaInst *AI =
4044 assert(AI != &OldAI && AI != &NewAI &&
4045 "Splittable transfers cannot reach the same alloca on both ends.");
4046 Pass.Worklist.insert(AI);
4053 unsigned OffsetWidth =
DL.getIndexSizeInBits(OtherAS);
4054 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
4056 (IsDest ?
II.getSourceAlign() :
II.getDestAlign()).valueOrOne();
4058 commonAlignment(OtherAlign, OtherOffset.zextOrTrunc(64).getZExtValue());
4066 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->
getType());
4067 Type *SizeTy =
II.getLength()->getType();
4068 Constant *
Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
4070 Value *DestPtr, *SrcPtr;
4071 MaybeAlign DestAlign, SrcAlign;
4075 DestAlign = SliceAlign;
4077 SrcAlign = OtherAlign;
4080 DestAlign = OtherAlign;
4082 SrcAlign = SliceAlign;
4084 CallInst *
New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
4087 New->setAAMetadata(AATags.
shift(NewBeginOffset - BeginOffset));
4092 &
II, New, DestPtr,
nullptr,
DL);
4097 SliceSize * 8, &
II, New, DestPtr,
nullptr,
DL);
4103 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
4104 NewEndOffset == NewAllocaEndOffset;
4106 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
4107 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
4108 unsigned NumElements = EndIndex - BeginIndex;
4109 IntegerType *SubIntTy =
4110 IntTy ? Type::getIntNTy(IntTy->
getContext(),
Size * 8) : nullptr;
4115 if (VecTy && !IsWholeAlloca) {
4116 if (NumElements == 1)
4117 OtherTy = VecTy->getElementType();
4120 }
else if (IntTy && !IsWholeAlloca) {
4123 OtherTy = NewAllocaTy;
4128 MaybeAlign SrcAlign = OtherAlign;
4129 MaybeAlign DstAlign = SliceAlign;
4137 DstPtr = getPtrToNewAI(
II.getDestAddressSpace(),
II.isVolatile());
4141 SrcPtr = getPtrToNewAI(
II.getSourceAddressSpace(),
II.isVolatile());
4145 if (VecTy && !IsWholeAlloca && !IsDest) {
4147 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.
getAlign(),
"load");
4149 }
else if (IntTy && !IsWholeAlloca && !IsDest) {
4151 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.
getAlign(),
"load");
4152 Src = IRB.CreateBitPreservingCastChain(
DL, Src, IntTy);
4156 LoadInst *
Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
4157 II.isVolatile(),
"copyload");
4158 Load->copyMetadata(
II, {LLVMContext::MD_mem_parallel_loop_access,
4159 LLVMContext::MD_access_group});
4166 if (VecTy && !IsWholeAlloca && IsDest) {
4167 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.
getAlign(),
4170 }
else if (IntTy && !IsWholeAlloca && IsDest) {
4171 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.
getAlign(),
4173 Old = IRB.CreateBitPreservingCastChain(
DL, Old, IntTy);
4176 Src = IRB.CreateBitPreservingCastChain(
DL, Src, NewAllocaTy);
4180 IRB.CreateAlignedStore(Src, DstPtr, DstAlign,
II.isVolatile()));
4181 Store->copyMetadata(
II, {LLVMContext::MD_mem_parallel_loop_access,
4182 LLVMContext::MD_access_group});
4185 Src->getType(),
DL));
4200 return !
II.isVolatile();
4203 bool visitIntrinsicInst(IntrinsicInst &
II) {
4204 assert((
II.isLifetimeStartOrEnd() ||
II.isDroppable()) &&
4205 "Unexpected intrinsic!");
4209 Pass.DeadInsts.push_back(&
II);
4211 if (
II.isDroppable()) {
4212 assert(
II.getIntrinsicID() == Intrinsic::assume &&
"Expected assume");
4218 assert(
II.getArgOperand(0) == OldPtr);
4222 if (
II.getIntrinsicID() == Intrinsic::lifetime_start)
4223 New = IRB.CreateLifetimeStart(Ptr);
4225 New = IRB.CreateLifetimeEnd(Ptr);
4233 void fixLoadStoreAlign(Instruction &Root) {
4237 SmallPtrSet<Instruction *, 4> Visited;
4238 SmallVector<Instruction *, 4>
Uses;
4240 Uses.push_back(&Root);
4249 SI->setAlignment(std::min(
SI->getAlign(), getSliceAlign()));
4256 for (User *U :
I->users())
4259 }
while (!
Uses.empty());
4262 bool visitPHINode(PHINode &PN) {
4264 assert(BeginOffset >= NewAllocaBeginOffset &&
"PHIs are unsplittable");
4265 assert(EndOffset <= NewAllocaEndOffset &&
"PHIs are unsplittable");
4271 IRBuilderBase::InsertPointGuard Guard(IRB);
4273 IRB.SetInsertPoint(OldPtr->
getParent()->getFirstInsertionPt());
4275 IRB.SetInsertPoint(OldPtr);
4276 IRB.SetCurrentDebugLocation(OldPtr->
getDebugLoc());
4278 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->
getType());
4283 deleteIfTriviallyDead(OldPtr);
4286 fixLoadStoreAlign(PN);
4295 bool visitSelectInst(SelectInst &SI) {
4297 assert((
SI.getTrueValue() == OldPtr ||
SI.getFalseValue() == OldPtr) &&
4298 "Pointer isn't an operand!");
4299 assert(BeginOffset >= NewAllocaBeginOffset &&
"Selects are unsplittable");
4300 assert(EndOffset <= NewAllocaEndOffset &&
"Selects are unsplittable");
4302 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->
getType());
4304 if (
SI.getOperand(1) == OldPtr)
4305 SI.setOperand(1, NewPtr);
4306 if (
SI.getOperand(2) == OldPtr)
4307 SI.setOperand(2, NewPtr);
4310 deleteIfTriviallyDead(OldPtr);
4313 fixLoadStoreAlign(SI);
4328class AggLoadStoreRewriter :
public InstVisitor<AggLoadStoreRewriter, bool> {
4330 friend class InstVisitor<AggLoadStoreRewriter, bool>;
4336 SmallPtrSet<User *, 8> Visited;
4343 const DataLayout &
DL;
4348 AggLoadStoreRewriter(
const DataLayout &
DL, IRBuilderTy &IRB)
4349 :
DL(
DL), IRB(IRB) {}
4353 bool rewrite(Instruction &
I) {
4357 while (!
Queue.empty()) {
4358 U =
Queue.pop_back_val();
4367 void enqueueUsers(Instruction &
I) {
4368 for (Use &U :
I.uses())
4369 if (Visited.
insert(
U.getUser()).second)
4370 Queue.push_back(&U);
4374 bool visitInstruction(Instruction &
I) {
return false; }
4377 template <
typename Derived>
class OpSplitter {
4384 SmallVector<unsigned, 4> Indices;
4388 SmallVector<Value *, 4> GEPIndices;
4402 const DataLayout &
DL;
4406 OpSplitter(Instruction *InsertionPoint,
Value *Ptr,
Type *BaseTy,
4407 Align BaseAlign,
const DataLayout &
DL, IRBuilderTy &IRB)
4408 : IRB(IRB), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr), BaseTy(BaseTy),
4409 BaseAlign(BaseAlign),
DL(
DL) {
4410 IRB.SetInsertPoint(InsertionPoint);
4427 void emitSplitOps(
Type *Ty,
Value *&Agg,
const Twine &Name) {
4429 unsigned Offset =
DL.getIndexedOffsetInType(BaseTy, GEPIndices);
4430 return static_cast<Derived *
>(
this)->emitFunc(
4435 unsigned OldSize = Indices.
size();
4437 for (
unsigned Idx = 0,
Size = ATy->getNumElements(); Idx !=
Size;
4439 assert(Indices.
size() == OldSize &&
"Did not return to the old size");
4441 GEPIndices.
push_back(IRB.getInt32(Idx));
4442 emitSplitOps(ATy->getElementType(), Agg, Name +
"." + Twine(Idx));
4450 unsigned OldSize = Indices.
size();
4452 for (
unsigned Idx = 0,
Size = STy->getNumElements(); Idx !=
Size;
4454 assert(Indices.
size() == OldSize &&
"Did not return to the old size");
4456 GEPIndices.
push_back(IRB.getInt32(Idx));
4457 emitSplitOps(STy->getElementType(Idx), Agg, Name +
"." + Twine(Idx));
4468 struct LoadOpSplitter :
public OpSplitter<LoadOpSplitter> {
4472 SmallVector<Value *, 4> Components;
4477 LoadOpSplitter(Instruction *InsertionPoint,
Value *Ptr,
Type *BaseTy,
4478 AAMDNodes AATags, Align BaseAlign,
const DataLayout &
DL,
4480 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
DL,
4486 void emitFunc(
Type *Ty,
Value *&Agg, Align Alignment,
const Twine &Name) {
4490 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name +
".gep");
4492 IRB.CreateAlignedLoad(Ty,
GEP, Alignment, Name +
".load");
4498 Load->setAAMetadata(
4504 Agg = IRB.CreateInsertValue(Agg,
Load, Indices, Name +
".insert");
4509 void recordFakeUses(LoadInst &LI) {
4510 for (Use &U : LI.
uses())
4512 if (
II->getIntrinsicID() == Intrinsic::fake_use)
4518 void emitFakeUses() {
4519 for (Instruction *
I : FakeUses) {
4520 IRB.SetInsertPoint(
I);
4521 for (
auto *
V : Components)
4522 IRB.CreateIntrinsic(Intrinsic::fake_use, {
V});
4523 I->eraseFromParent();
4528 bool visitLoadInst(LoadInst &LI) {
4537 Splitter.recordFakeUses(LI);
4540 Splitter.emitFakeUses();
4547 struct StoreOpSplitter :
public OpSplitter<StoreOpSplitter> {
4548 StoreOpSplitter(Instruction *InsertionPoint,
Value *Ptr,
Type *BaseTy,
4549 AAMDNodes AATags, StoreInst *AggStore, Align BaseAlign,
4550 const DataLayout &
DL, IRBuilderTy &IRB)
4551 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
4553 AATags(AATags), AggStore(AggStore) {}
4555 StoreInst *AggStore;
4558 void emitFunc(
Type *Ty,
Value *&Agg, Align Alignment,
const Twine &Name) {
4564 Value *ExtractValue =
4565 IRB.CreateExtractValue(Agg, Indices, Name +
".extract");
4566 Value *InBoundsGEP =
4567 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name +
".gep");
4569 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Alignment);
4586 DL.getTypeSizeInBits(
Store->getValueOperand()->getType());
4588 SizeInBits, AggStore,
Store,
4589 Store->getPointerOperand(),
Store->getValueOperand(),
4593 "AT: unexpected debug.assign linked to store through "
4600 bool visitStoreInst(StoreInst &SI) {
4601 if (!
SI.isSimple() ||
SI.getPointerOperand() != *U)
4604 if (
V->getType()->isSingleValueType())
4609 StoreOpSplitter Splitter(&SI, *U,
V->getType(),
SI.getAAMetadata(), &SI,
4611 Splitter.emitSplitOps(
V->getType(),
V,
V->getName() +
".fca");
4616 SI.eraseFromParent();
4620 bool visitBitCastInst(BitCastInst &BC) {
4625 bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
4635 bool unfoldGEPSelect(GetElementPtrInst &GEPI) {
4654 if (!ZI->getSrcTy()->isIntegerTy(1))
4667 dbgs() <<
" original: " << *Sel <<
"\n";
4668 dbgs() <<
" " << GEPI <<
"\n";);
4670 auto GetNewOps = [&](
Value *SelOp) {
4683 Cond =
SI->getCondition();
4684 True =
SI->getTrueValue();
4688 Cond = Sel->getOperand(0);
4689 True = ConstantInt::get(Sel->getType(), 1);
4690 False = ConstantInt::get(Sel->getType(), 0);
4695 IRB.SetInsertPoint(&GEPI);
4699 Value *NTrue = IRB.CreateGEP(Ty, TrueOps[0],
ArrayRef(TrueOps).drop_front(),
4700 True->getName() +
".sroa.gep", NW);
4703 IRB.CreateGEP(Ty, FalseOps[0],
ArrayRef(FalseOps).drop_front(),
4704 False->getName() +
".sroa.gep", NW);
4706 Value *NSel = MDFrom
4707 ? IRB.CreateSelect(
Cond, NTrue, NFalse,
4708 Sel->getName() +
".sroa.sel", MDFrom)
4709 : IRB.CreateSelectWithUnknownProfile(
4711 Sel->getName() +
".sroa.sel");
4712 Visited.
erase(&GEPI);
4717 enqueueUsers(*NSelI);
4720 dbgs() <<
" " << *NFalse <<
"\n";
4721 dbgs() <<
" " << *NSel <<
"\n";);
4730 bool unfoldGEPPhi(GetElementPtrInst &GEPI) {
4735 auto IsInvalidPointerOperand = [](
Value *
V) {
4739 return !AI->isStaticAlloca();
4743 if (
any_of(
Phi->operands(), IsInvalidPointerOperand))
4758 [](
Value *
V) { return isa<ConstantInt>(V); }))
4771 dbgs() <<
" original: " << *
Phi <<
"\n";
4772 dbgs() <<
" " << GEPI <<
"\n";);
4774 auto GetNewOps = [&](
Value *PhiOp) {
4784 IRB.SetInsertPoint(Phi);
4785 PHINode *NewPhi = IRB.CreatePHI(GEPI.
getType(),
Phi->getNumIncomingValues(),
4786 Phi->getName() +
".sroa.phi");
4792 for (
unsigned I = 0,
E =
Phi->getNumIncomingValues();
I !=
E; ++
I) {
4801 IRB.CreateGEP(SourceTy, NewOps[0],
ArrayRef(NewOps).drop_front(),
4807 Visited.
erase(&GEPI);
4811 enqueueUsers(*NewPhi);
4817 dbgs() <<
"\n " << *NewPhi <<
'\n');
4822 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
4823 if (unfoldGEPSelect(GEPI))
4826 if (unfoldGEPPhi(GEPI))
4833 bool visitPHINode(PHINode &PN) {
4838 bool visitSelectInst(SelectInst &SI) {
4852 if (Ty->isSingleValueType())
4855 uint64_t AllocSize =
DL.getTypeAllocSize(Ty).getFixedValue();
4860 InnerTy = ArrTy->getElementType();
4864 InnerTy = STy->getElementType(Index);
4869 if (AllocSize >
DL.getTypeAllocSize(InnerTy).getFixedValue() ||
4870 TypeSize >
DL.getTypeSizeInBits(InnerTy).getFixedValue())
4891 if (
Offset == 0 &&
DL.getTypeAllocSize(Ty).getFixedValue() ==
Size)
4893 if (
Offset >
DL.getTypeAllocSize(Ty).getFixedValue() ||
4894 (
DL.getTypeAllocSize(Ty).getFixedValue() -
Offset) <
Size)
4901 ElementTy = AT->getElementType();
4902 TyNumElements = AT->getNumElements();
4907 ElementTy = VT->getElementType();
4908 TyNumElements = VT->getNumElements();
4910 uint64_t ElementSize =
DL.getTypeAllocSize(ElementTy).getFixedValue();
4912 if (NumSkippedElements >= TyNumElements)
4914 Offset -= NumSkippedElements * ElementSize;
4926 if (
Size == ElementSize)
4930 if (NumElements * ElementSize !=
Size)
4954 uint64_t ElementSize =
DL.getTypeAllocSize(ElementTy).getFixedValue();
4955 if (
Offset >= ElementSize)
4966 if (
Size == ElementSize)
4973 if (Index == EndIndex)
4983 assert(Index < EndIndex);
5008 const std::vector<uint64_t> &Splits;
5015 std::vector<uint64_t> &Splits,
unsigned SliceSize)
5016 : IRB(IRB), DL(DL), Splits(Splits), SliceSize(SliceSize) {}
5026 Idx = IsEnd ?
SS.Splits.size() + 1 : 0;
5031 uint64_t NextOffset =
5032 Idx <
SS.Splits.size() ?
SS.Splits[
Idx] :
SS.SliceSize;
5048 Type *PartPtrTy = BasePtr->getType();
5050 LoadInst *PLoad = IRB.CreateAlignedLoad(
5054 PartPtrTy, BasePtr->getName() +
"."),
5057 PLoad->
copyMetadata(*SplitI, {LLVMContext::MD_mem_parallel_loop_access,
5058 LLVMContext::MD_access_group});
5064 Type *PartPtrTy = BasePtr->getType();
5066 StoreInst *PStore = IRB.CreateAlignedStore(
5070 PartPtrTy, BasePtr->getName() +
"."),
5073 PStore->
copyMetadata(*SplitI, {LLVMContext::MD_mem_parallel_loop_access,
5074 LLVMContext::MD_access_group,
5075 LLVMContext::MD_DIAssignID});
5085 unsigned PtrIdx = 0;
5089 PtrIdx =
SI->getPointerOperandIndex();
5096 &
I->getOperandUse(PtrIdx),
false);
5098 << S.endOffset() <<
"): " << *
I <<
"\n");
5109 InstructionSliceMap &SliceMap) {
5111 if (S.endOffset() - S.beginOffset() == 1)
5129 for (Slice *JS : SliceMap[J]) {
5130 if (S.beginOffset() > JS->beginOffset() &&
5131 S.beginOffset() < JS->endOffset())
5133 if (JS->beginOffset() > S.beginOffset() &&
5134 JS->beginOffset() < S.endOffset())
5165bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
5179 struct SplitOffsets {
5181 std::vector<uint64_t> Splits;
5183 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
5196 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
5198 LLVM_DEBUG(
dbgs() <<
" Searching for candidate loads and stores\n");
5199 for (
auto &
P : AS.partitions()) {
5200 InstructionSliceMap SliceMap;
5201 for (Slice &S :
P) {
5204 for (Slice &S :
P) {
5206 bool ExtendsPastPartitionEnd = S.endOffset() >
P.endOffset();
5208 if (!S.isSplittable() || (!ExtendsPastPartitionEnd && !CopyOverlap)) {
5213 UnsplittableLoads.
insert(LI);
5216 UnsplittableLoads.
insert(LI);
5219 assert(
P.endOffset() > S.beginOffset() &&
5220 "Empty or backwards partition!");
5229 auto IsLoadSimplyStored = [](LoadInst *LI) {
5230 for (User *LU : LI->
users()) {
5232 if (!SI || !
SI->isSimple())
5237 if (!IsLoadSimplyStored(LI)) {
5238 UnsplittableLoads.
insert(LI);
5244 if (S.getUse() != &
SI->getOperandUse(
SI->getPointerOperandIndex()))
5248 if (!StoredLoad || !StoredLoad->isSimple())
5250 assert(!
SI->isVolatile() &&
"Cannot split volatile stores!");
5260 auto &
Offsets = SplitOffsetsMap[
I];
5262 "Should not have splits the first time we see an instruction!");
5277 std::max(S.beginOffset(), CopyOverlap->beginOffset());
5278 uint64_t OverlapEnd = std::min(S.endOffset(), CopyOverlap->endOffset());
5279 uint64_t OverlapSize = OverlapEnd - OverlapStart;
5280 uint64_t SliceSize = S.endOffset() - S.beginOffset();
5281 uint64_t NonOverlapSize = SliceSize - OverlapSize;
5282 if (OverlapSize < NonOverlapSize) {
5287 Offsets.Splits.push_back(OverlapSize);
5288 Offsets.Splits.push_back(SliceSize - OverlapSize);
5289 }
else if (OverlapSize > NonOverlapSize) {
5292 for (
uint64_t Split = NonOverlapSize;
Split <= SliceSize / 2;
5293 Split += NonOverlapSize) {
5294 Offsets.Splits.push_back(Split);
5295 if (Split != SliceSize - Split) {
5296 Offsets.Splits.push_back(SliceSize - Split);
5304 Offsets.Splits.push_back(OverlapSize);
5307 Offsets.Splits.push_back(
P.endOffset() - S.beginOffset());
5316 llvm::erase_if(Stores, [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
5322 if (UnsplittableLoads.
count(LI))
5325 auto LoadOffsetsI = SplitOffsetsMap.
find(LI);
5326 if (LoadOffsetsI == SplitOffsetsMap.
end())
5328 auto &LoadOffsets = LoadOffsetsI->second;
5331 auto &StoreOffsets = SplitOffsetsMap[
SI];
5336 if (LoadOffsets.Splits == StoreOffsets.Splits)
5340 <<
" " << *LI <<
"\n"
5341 <<
" " << *SI <<
"\n");
5347 UnsplittableLoads.
insert(LI);
5356 return UnsplittableLoads.
count(LI);
5361 return UnsplittableLoads.
count(LI);
5371 IRBuilderTy IRB(&AI);
5372 IRB.disableGEPCanonicalization();
5379 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
5389 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
5390 std::vector<LoadInst *> SplitLoads;
5391 const DataLayout &
DL = AI.getDataLayout();
5392 for (LoadInst *LI : Loads) {
5395 auto &
Offsets = SplitOffsetsMap[LI];
5396 unsigned SliceSize =
Offsets.S->endOffset() -
Offsets.S->beginOffset();
5398 "Load must have type size equal to store size");
5400 "Load must be >= slice size");
5403 assert(BaseOffset + SliceSize > BaseOffset &&
5404 "Cannot represent alloca access size using 64-bit integers!");
5407 IRB.SetInsertPoint(LI);
5411 SliceSplitter Splitter(IRB,
DL,
Offsets.Splits, SliceSize);
5412 for (
auto Part : Splitter) {
5413 LoadInst *PLoad = Splitter.createLoad(BasePtr, Part, LI);
5417 SplitLoads.push_back(PLoad);
5420 NewSlices.
push_back(Splitter.createSlice(PLoad, BaseOffset, Part));
5426 bool DeferredStores =
false;
5427 for (User *LU : LI->
users()) {
5429 if (!Stores.
empty() && SplitOffsetsMap.
count(SI)) {
5430 DeferredStores =
true;
5436 Value *StoreBasePtr =
SI->getPointerOperand();
5437 IRB.SetInsertPoint(SI);
5439 LLVM_DEBUG(
dbgs() <<
" Splitting store of load: " << *SI <<
"\n");
5441 for (
auto Part : Splitter) {
5442 LoadInst *PLoad = SplitLoads[Part.Idx];
5443 StoreInst *PStore = Splitter.createStore(PLoad, StoreBasePtr, Part, SI);
5454 ResplitPromotableAllocas.
insert(OtherAI);
5455 Worklist.insert(OtherAI);
5458 Worklist.insert(OtherAI);
5462 DeadInsts.push_back(SI);
5467 SplitLoadsMap.
insert(std::make_pair(LI, std::move(SplitLoads)));
5470 DeadInsts.push_back(LI);
5479 for (StoreInst *SI : Stores) {
5484 assert(StoreSize > 0 &&
"Cannot have a zero-sized integer store!");
5488 "Slice size should always match load size exactly!");
5490 assert(BaseOffset + StoreSize > BaseOffset &&
5491 "Cannot represent alloca access size using 64-bit integers!");
5499 auto SplitLoadsMapI = SplitLoadsMap.
find(LI);
5500 std::vector<LoadInst *> *SplitLoads =
nullptr;
5501 if (SplitLoadsMapI != SplitLoadsMap.
end()) {
5502 SplitLoads = &SplitLoadsMapI->second;
5504 "Too few split loads for the number of splits in the store!");
5509 SliceSplitter Splitter(IRB,
DL,
Offsets.Splits, StoreSize);
5510 for (
auto Part : Splitter) {
5514 PLoad = (*SplitLoads)[Part.Idx];
5516 IRB.SetInsertPoint(LI);
5517 PLoad = Splitter.createLoad(LoadBasePtr, Part, LI);
5521 IRB.SetInsertPoint(SI);
5522 StoreInst *PStore = Splitter.createStore(PLoad, StoreBasePtr, Part, SI);
5525 NewSlices.
push_back(Splitter.createSlice(PStore, BaseOffset, Part));
5538 assert(OtherAI != &AI &&
"We can't re-split our own alloca!");
5539 ResplitPromotableAllocas.
insert(OtherAI);
5540 Worklist.insert(OtherAI);
5543 assert(StrippedAI != &AI &&
"We can't re-split our own alloca!");
5544 Worklist.insert(StrippedAI);
5559 DeadInsts.push_back(LI);
5561 DeadInsts.push_back(SI);
5570 AS.insert(NewSlices);
5574 for (
auto I = AS.begin(),
E = AS.end();
I !=
E; ++
I)
5580 PromotableAllocas.set_subtract(ResplitPromotableAllocas);
5617 bool IsIntegralPointerTy =
5618 EltTy->
isPointerTy() && !
DL.isNonIntegralPointerType(EltTy);
5620 !IsIntegralPointerTy)
5627 if (
DL.getTypeSizeInBits(EltTy) !=
DL.getTypeAllocSizeInBits(EltTy))
5631 TypeSize StructSize =
DL.getStructLayout(STy)->getSizeInBytes();
5632 TypeSize VectorSize =
DL.getTypeStoreSize(VTy);
5635 if (StructSize != VectorSize)
5638 auto IsIgnorableOrMemIntrinsicSlice = [](
const Slice &S) {
5641 auto *U = S.getUse();
5645 for (
const Slice &S :
P)
5646 if (!IsIgnorableOrMemIntrinsicSlice(S))
5649 for (
const Slice *S :
P.splitSliceTails())
5650 if (!IsIgnorableOrMemIntrinsicSlice(*S))
5667static std::tuple<Type *, bool, VectorType *>
5671 VectorType *SelectedVecTy,
bool SelectedIntWidening) {
5673 dbgs() <<
"selectPartitionType path=" << Path
5678 dbgs() <<
"<unnamed>";
5679 dbgs() <<
" partition=[" <<
P.beginOffset() <<
"," <<
P.endOffset()
5680 <<
") size=" <<
P.size();
5682 dbgs() <<
" alloc-size=" << AllocSize->getKnownMinValue();
5684 dbgs() <<
" chosen=" << *SelectedTy;
5686 dbgs() <<
" vec=" << *SelectedVecTy;
5687 dbgs() <<
" intwiden=" << SelectedIntWidening <<
"\n";
5705 if (VecTy && VecTy->getElementType()->isFloatingPointTy() &&
5706 VecTy->getElementCount().getFixedValue() > 1) {
5707 LogSelection(
"direct-fp-vecty", VecTy, VecTy,
false);
5708 return {VecTy,
false, VecTy};
5713 auto [CommonUseTy, LargestIntTy] =
5716 TypeSize CommonUseSize =
DL.getTypeAllocSize(CommonUseTy);
5722 LogSelection(
"common-type-vecty", VecTy, VecTy,
false);
5723 return {VecTy,
false, VecTy};
5726 LogSelection(
"common-type", CommonUseTy,
nullptr, IntWiden);
5727 return {CommonUseTy, IntWiden,
nullptr};
5734 P.beginOffset(),
P.size())) {
5738 if (TypePartitionTy->isArrayTy() &&
5739 TypePartitionTy->getArrayElementType()->isIntegerTy() &&
5740 DL.isLegalInteger(
P.size() * 8))
5744 LogSelection(
"type-partition-int-widen", TypePartitionTy,
nullptr,
true);
5745 return {TypePartitionTy,
true,
nullptr};
5748 LogSelection(
"type-partition-vecty", VecTy, VecTy,
false);
5749 return {VecTy,
false, VecTy};
5754 DL.getTypeAllocSize(LargestIntTy).getFixedValue() >=
P.size() &&
5756 LogSelection(
"largest-int-int-widen", LargestIntTy,
nullptr,
true);
5757 return {LargestIntTy,
true,
nullptr};
5762 if (AggregateToVector) {
5765 LogSelection(
"struct-fallback-vecty", VTy,
nullptr,
false);
5766 return {VTy,
false,
nullptr};
5772 LogSelection(
"type-partition-fallback", TypePartitionTy,
nullptr,
false);
5773 return {TypePartitionTy,
false,
nullptr};
5778 DL.getTypeAllocSize(LargestIntTy).getFixedValue() >=
P.size()) {
5779 LogSelection(
"largest-int-fallback", LargestIntTy,
nullptr,
false);
5780 return {LargestIntTy,
false,
nullptr};
5784 if (
DL.isLegalInteger(
P.size() * 8)) {
5786 LogSelection(
"legal-int-fallback", IntTy,
nullptr,
false);
5787 return {IntTy,
false,
nullptr};
5792 LogSelection(
"byte-array-fallback", ArrayTy,
nullptr,
false);
5793 return {ArrayTy,
false,
nullptr};
5806std::pair<AllocaInst *, uint64_t>
5807SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS, Partition &
P) {
5808 const DataLayout &
DL = AI.getDataLayout();
5810 auto [PartitionTy, IsIntegerWideningViable, VecTy] =
5820 if (PartitionTy == AI.getAllocatedType() &&
P.beginOffset() == 0) {
5829 new AllocaInst(PartitionTy, AI.getAddressSpace(),
nullptr, Alignment,
5830 AI.getName() +
".sroa." + Twine(
P.begin() - AS.begin()),
5838 LLVM_DEBUG(
dbgs() <<
"Rewriting alloca partition " <<
"[" <<
P.beginOffset()
5839 <<
"," <<
P.endOffset() <<
") to: " << *NewAI <<
"\n");
5844 unsigned PPWOldSize = PostPromotionWorklist.size();
5845 unsigned NumUses = 0;
5846 SmallSetVector<PHINode *, 8> PHIUsers;
5847 SmallSetVector<SelectInst *, 8> SelectUsers;
5850 DL, AS, *
this, AI, *NewAI, PartitionTy,
P.beginOffset(),
P.endOffset(),
5851 IsIntegerWideningViable, VecTy, PHIUsers, SelectUsers);
5852 bool Promotable =
true;
5854 if (
auto DeletedValues =
Rewriter.rewriteTreeStructuredMerge(
P)) {
5855 NumUses += DeletedValues->
size() + 1;
5856 for (
Value *
V : *DeletedValues)
5857 DeadInsts.push_back(
V);
5859 for (Slice *S :
P.splitSliceTails()) {
5863 for (Slice &S :
P) {
5869 NumAllocaPartitionUses += NumUses;
5870 MaxUsesPerAllocaPartition.updateMax(NumUses);
5876 for (PHINode *
PHI : PHIUsers) {
5887 SelectUsers.
clear();
5892 NewSelectsToRewrite;
5894 for (SelectInst *Sel : SelectUsers) {
5895 std::optional<RewriteableMemOps>
Ops =
5896 isSafeSelectToSpeculateOrPredicate(*Sel, PreserveCFG);
5905 for (Use *U : AS.getDeadUsesIfPromotable()) {
5907 Value::dropDroppableUse(*U);
5910 DeadInsts.push_back(OldInst);
5912 if (NewSpeculatablePHIs.
empty() && NewPHIsWithStoreToRewrite.
empty() &&
5913 SelectUsers.empty()) {
5915 PromotableAllocas.insert(NewAI);
5920 SpeculatablePHIs.insert_range(NewSpeculatablePHIs);
5921 PHIsWithStoreToRewrite.insert_range(NewPHIsWithStoreToRewrite);
5922 SelectsToRewrite.reserve(SelectsToRewrite.size() +
5923 NewSelectsToRewrite.
size());
5925 std::make_move_iterator(NewSelectsToRewrite.
begin()),
5926 std::make_move_iterator(NewSelectsToRewrite.
end())))
5927 SelectsToRewrite.insert(std::move(KV));
5928 Worklist.insert(NewAI);
5932 while (PostPromotionWorklist.size() > PPWOldSize)
5933 PostPromotionWorklist.pop_back();
5938 return {
nullptr, 0};
5943 Worklist.insert(NewAI);
5946 return {NewAI,
DL.getTypeSizeInBits(PartitionTy).getFixedValue()};
5990 int64_t BitExtractOffset) {
5992 bool HasFragment =
false;
5993 bool HasBitExtract =
false;
6001 HasBitExtract =
true;
6002 int64_t ExtractOffsetInBits = Extract.getOffsetInBits();
6003 int64_t ExtractSizeInBits = Extract.getSizeInBits();
6012 assert(BitExtractOffset <= 0);
6013 int64_t AdjustedOffset = ExtractOffsetInBits + BitExtractOffset;
6019 if (AdjustedOffset < 0)
6022 Ops.push_back(
Op.getOp());
6023 Ops.push_back(std::max<int64_t>(0, AdjustedOffset));
6024 Ops.push_back(ExtractSizeInBits);
6027 Op.appendToVector(
Ops);
6032 if (HasFragment && HasBitExtract)
6035 if (!HasBitExtract) {
6054 std::optional<DIExpression::FragmentInfo> NewFragment,
6055 int64_t BitExtractAdjustment) {
6065 BitExtractAdjustment);
6066 if (!NewFragmentExpr)
6072 BeforeInst->
getParent()->insertDbgRecordBefore(DVR,
6085 BeforeInst->
getParent()->insertDbgRecordBefore(DVR,
6091 if (!NewAddr->
hasMetadata(LLVMContext::MD_DIAssignID)) {
6099 LLVM_DEBUG(
dbgs() <<
"Created new DVRAssign: " << *NewAssign <<
"\n");
6105bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
6106 if (AS.begin() == AS.end())
6109 unsigned NumPartitions = 0;
6111 const DataLayout &
DL = AI.getDataLayout();
6114 Changed |= presplitLoadsAndStores(AI, AS);
6122 bool IsSorted =
true;
6124 uint64_t AllocaSize = AI.getAllocationSize(
DL)->getFixedValue();
6132 SparseBitVector<> SplittableOffset;
6134 for (Slice &S : AS) {
6136 if (S.beginOffset() > CurBegin || S.endOffset() > CurEnd) {
6138 if (S.beginOffset() >= CurEnd) {
6139 SplittableOffset.
set(S.beginOffset());
6142 if (CurEnd > S.beginOffset() && CurEnd < S.endOffset()) {
6143 SplittableOffset.
reset(CurEnd);
6145 CurBegin = S.beginOffset();
6149 if (S.endOffset() > CurEnd) {
6150 CurEnd = S.endOffset();
6151 SplittableOffset.
set(CurEnd);
6156 for (Slice &S : AS) {
6157 if (!S.isSplittable())
6160 if ((S.beginOffset() > AllocaSize ||
6161 SplittableOffset.
test(S.beginOffset())) &&
6162 (S.endOffset() > AllocaSize || SplittableOffset.
test(S.endOffset())))
6167 S.makeUnsplittable();
6187 for (
auto &
P : AS.partitions()) {
6188 auto [NewAI, ActiveBits] = rewritePartition(AI, AS, P);
6192 uint64_t SizeOfByte = 8;
6194 uint64_t Size = std::min(ActiveBits, P.size() * SizeOfByte);
6195 Fragments.push_back(
6196 Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
6202 NumAllocaPartitions += NumPartitions;
6203 MaxPartitionsPerAlloca.updateMax(NumPartitions);
6207 auto MigrateOne = [&](DbgVariableRecord *DbgVariable) {
6212 const Value *DbgPtr = DbgVariable->getAddress();
6214 DbgVariable->getFragmentOrEntireVariable();
6217 int64_t CurrentExprOffsetInBytes = 0;
6218 SmallVector<uint64_t> PostOffsetOps;
6220 ->extractLeadingOffset(CurrentExprOffsetInBytes, PostOffsetOps))
6224 int64_t ExtractOffsetInBits = 0;
6227 ExtractOffsetInBits = Extract.getOffsetInBits();
6232 DIBuilder DIB(*AI.getModule(),
false);
6234 int64_t OffsetFromLocationInBits;
6235 std::optional<DIExpression::FragmentInfo> NewDbgFragment;
6241 CurrentExprOffsetInBytes * 8, ExtractOffsetInBits, VarFrag,
6242 NewDbgFragment, OffsetFromLocationInBits))
6248 if (NewDbgFragment && !NewDbgFragment->SizeInBits)
6253 if (!NewDbgFragment)
6254 NewDbgFragment = DbgVariable->getFragment();
6258 int64_t OffestFromNewAllocaInBits =
6259 OffsetFromLocationInBits - ExtractOffsetInBits;
6262 int64_t BitExtractOffset =
6263 std::min<int64_t>(0, OffestFromNewAllocaInBits);
6268 OffestFromNewAllocaInBits =
6269 std::max(int64_t(0), OffestFromNewAllocaInBits);
6275 DIExpression *NewExpr = DIExpression::get(AI.getContext(), PostOffsetOps);
6276 if (OffestFromNewAllocaInBits > 0) {
6277 int64_t OffsetInBytes = (OffestFromNewAllocaInBits + 7) / 8;
6283 auto RemoveOne = [DbgVariable](
auto *OldDII) {
6284 auto SameVariableFragment = [](
const auto *
LHS,
const auto *
RHS) {
6285 return LHS->getVariable() ==
RHS->getVariable() &&
6286 LHS->getDebugLoc()->getInlinedAt() ==
6287 RHS->getDebugLoc()->getInlinedAt();
6289 if (SameVariableFragment(OldDII, DbgVariable))
6290 OldDII->eraseFromParent();
6295 NewDbgFragment, BitExtractOffset);
6309void SROA::clobberUse(Use &U) {
6319 DeadInsts.push_back(OldI);
6341bool SROA::propagateStoredValuesToLoads(AllocaInst &AI, AllocaSlices &AS) {
6346 LLVM_DEBUG(
dbgs() <<
"Attempting to propagate values on " << AI <<
"\n");
6347 bool AllSameAndValid =
true;
6348 Type *PartitionType =
nullptr;
6349 SmallVector<Instruction *> Insts;
6353 auto Flush = [&]() {
6354 if (AllSameAndValid && !Insts.
empty()) {
6355 LLVM_DEBUG(
dbgs() <<
"Propagate values on slice [" << BeginOffset <<
", "
6356 << EndOffset <<
")\n");
6358 SSAUpdater
SSA(&NewPHIs);
6360 BasicLoadAndStorePromoter Promoter(Insts,
SSA, PartitionType);
6361 Promoter.run(Insts);
6363 AllSameAndValid =
true;
6364 PartitionType =
nullptr;
6368 for (Slice &S : AS) {
6372 dbgs() <<
"Ignoring slice: ";
6373 AS.print(
dbgs(), &S);
6377 if (S.beginOffset() >= EndOffset) {
6379 BeginOffset = S.beginOffset();
6380 EndOffset = S.endOffset();
6381 }
else if (S.beginOffset() != BeginOffset || S.endOffset() != EndOffset) {
6382 if (AllSameAndValid) {
6384 dbgs() <<
"Slice does not match range [" << BeginOffset <<
", "
6385 << EndOffset <<
")";
6386 AS.print(
dbgs(), &S);
6388 AllSameAndValid =
false;
6390 EndOffset = std::max(EndOffset, S.endOffset());
6397 if (!LI->
isSimple() || (PartitionType && UserTy != PartitionType))
6398 AllSameAndValid =
false;
6399 PartitionType = UserTy;
6402 Type *UserTy =
SI->getValueOperand()->getType();
6403 if (!
SI->isSimple() || (PartitionType && UserTy != PartitionType))
6404 AllSameAndValid =
false;
6405 PartitionType = UserTy;
6408 AllSameAndValid =
false;
6421std::pair<
bool ,
bool >
6422SROA::runOnAlloca(AllocaInst &AI) {
6424 bool CFGChanged =
false;
6427 ++NumAllocasAnalyzed;
6430 if (AI.use_empty()) {
6431 DeadInsts.push_back(&AI);
6435 const DataLayout &
DL = AI.getDataLayout();
6438 std::optional<TypeSize>
Size = AI.getAllocationSize(
DL);
6439 if (AI.isArrayAllocation() || !
Size ||
Size->isScalable() ||
Size->isZero())
6444 IRBuilderTy IRB(&AI);
6445 IRB.disableGEPCanonicalization();
6446 AggLoadStoreRewriter AggRewriter(
DL, IRB);
6447 Changed |= AggRewriter.rewrite(AI);
6450 AllocaSlices AS(
DL, AI);
6455 if (AS.isEscapedReadOnly()) {
6456 Changed |= propagateStoredValuesToLoads(AI, AS);
6461 for (Instruction *DeadUser : AS.getDeadUsers()) {
6463 for (Use &DeadOp : DeadUser->operands())
6470 DeadInsts.push_back(DeadUser);
6473 for (Use *DeadOp : AS.getDeadOperands()) {
6474 clobberUse(*DeadOp);
6479 if (AS.begin() == AS.end())
6482 Changed |= splitAlloca(AI, AS);
6485 while (!SpeculatablePHIs.empty())
6489 auto RemainingPHIsWithStoreToRewrite = PHIsWithStoreToRewrite.takeVector();
6490 while (!RemainingPHIsWithStoreToRewrite.empty()) {
6491 PHINode *PN = RemainingPHIsWithStoreToRewrite.pop_back_val();
6497 auto RemainingSelectsToRewrite = SelectsToRewrite.takeVector();
6498 while (!RemainingSelectsToRewrite.empty()) {
6499 const auto [
K,
V] = RemainingSelectsToRewrite.pop_back_val();
6516bool SROA::deleteDeadInstructions(
6517 AllocaInst *AI, SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
6519 while (!DeadInsts.empty()) {
6529 DeletedAllocas.
insert(AI);
6531 OldDII->eraseFromParent();
6537 for (Use &Operand :
I->operands())
6542 DeadInsts.push_back(U);
6546 I->eraseFromParent();
6550 if (!DeletedAllocas.
contains(AI) && AI->hasNUndroppableUses(0)) {
6551 DeletedAllocas.
insert(AI);
6552 AI->dropDroppableUses();
6554 OldDII->eraseFromParent();
6556 AI->eraseFromParent();
6567bool SROA::promoteAllocas() {
6568 if (PromotableAllocas.empty())
6575 NumPromoted += PromotableAllocas.size();
6576 PromoteMemToReg(PromotableAllocas.getArrayRef(), DTU->getDomTree(), AC);
6579 PromotableAllocas.clear();
6583std::pair<
bool ,
bool > SROA::runSROA(
Function &
F) {
6586 const DataLayout &
DL =
F.getDataLayout();
6591 std::optional<TypeSize>
Size = AI->getAllocationSize(
DL);
6593 PromotableAllocas.insert(AI);
6595 Worklist.insert(AI);
6600 bool CFGChanged =
false;
6603 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
6606 while (!Worklist.empty()) {
6607 AllocaInst *AI = Worklist.pop_back_val();
6608 auto [IterationChanged, IterationCFGChanged] = runOnAlloca(*AI);
6610 CFGChanged |= IterationCFGChanged;
6612 Changed |= deleteDeadInstructions(AI, DeletedAllocas);
6616 if (!DeletedAllocas.
empty()) {
6617 Worklist.set_subtract(DeletedAllocas);
6618 PostPromotionWorklist.set_subtract(DeletedAllocas);
6619 PromotableAllocas.set_subtract(DeletedAllocas);
6620 DeletedAllocas.
clear();
6626 Worklist = PostPromotionWorklist;
6627 PostPromotionWorklist.clear();
6628 }
while (!Worklist.empty());
6630 assert((!CFGChanged ||
Changed) &&
"Can not only modify the CFG.");
6631 assert((!CFGChanged || !PreserveCFG) &&
6632 "Should not have modified the CFG when told to preserve it.");
6635 for (
auto &BB :
F) {
6648 SROA(&
F.getContext(), &DTU, &AC, Options).runSROA(
F);
6660 static_cast<PassInfoMixin<SROAPass> *
>(
this)->
printPipeline(
6661 OS, MapClassName2PassName);
6665 if (Options.AggregateToVector)
6666 OS <<
";aggregate-to-vector";
6687 if (skipFunction(
F))
6690 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
6692 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
F);
6698 void getAnalysisUsage(AnalysisUsage &AU)
const override {
6705 StringRef getPassName()
const override {
return "SROA"; }
6710char SROALegacyPass::ID = 0;
6715 AggregateToVector));
6719 "Scalar Replacement Of Aggregates",
false,
false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Forward Handle Accesses
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
iv Induction Variable Users
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
print mir2vec MIR2Vec Vocabulary Printer Pass
This file implements a map that provides insertion order iteration.
static std::optional< AllocFnsTy > getAllocationSize(const CallBase *CB, const TargetLibraryInfo *TLI)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the PointerIntPair class.
This file provides a collection of visitors which walk the (instruction) uses of a pointer.
SmallVector< MachineOperand, 4 > Cond
Remove Loads Into Fake Uses
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
static void migrateDebugInfo(AllocaInst *OldAlloca, bool IsSplit, uint64_t OldAllocaOffsetInBits, uint64_t SliceSizeInBits, Instruction *OldInst, Instruction *Inst, Value *Dest, Value *Value, const DataLayout &DL)
Find linked dbg.assign and generate a new one with the correct FragmentInfo.
static VectorType * isVectorPromotionViable(Partition &P, const DataLayout &DL, unsigned VScale)
Test whether the given alloca partitioning and range of slices can be promoted to a vector.
static Align getAdjustedAlignment(Instruction *I, uint64_t Offset)
Compute the adjusted alignment for a load or store from an offset.
static VectorType * checkVectorTypesForPromotion(Partition &P, const DataLayout &DL, SmallVectorImpl< VectorType * > &CandidateTys, bool HaveCommonEltTy, Type *CommonEltTy, bool HaveVecPtrTy, bool HaveCommonVecPtrTy, VectorType *CommonVecPtrTy, unsigned VScale)
Test whether any vector type in CandidateTys is viable for promotion.
static std::pair< Type *, IntegerType * > findCommonType(AllocaSlices::const_iterator B, AllocaSlices::const_iterator E, uint64_t EndOffset)
Walk the range of a partitioning looking for a common type to cover this sequence of slices.
static Type * stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty)
Strip aggregate type wrapping.
static void rewriteMemOpOfSelect(SelectInst &SI, T &I, SelectHandSpeculativity Spec, IRBuilderTy &IRB, DomTreeUpdater &DTU)
static FragCalcResult calculateFragment(DILocalVariable *Variable, uint64_t NewStorageSliceOffsetInBits, uint64_t NewStorageSliceSizeInBits, std::optional< DIExpression::FragmentInfo > StorageFragment, std::optional< DIExpression::FragmentInfo > CurrentFragment, DIExpression::FragmentInfo &Target)
static DIExpression * createOrReplaceFragment(const DIExpression *Expr, DIExpression::FragmentInfo Frag, int64_t BitExtractOffset)
Create or replace an existing fragment in a DIExpression with Frag.
static Value * insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old, Value *V, uint64_t Offset, const Twine &Name)
static Value * getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr, APInt Offset, Type *PointerTy, const Twine &NamePrefix)
Compute an adjusted pointer from Ptr by Offset bytes where the resulting pointer has PointerTy.
static bool isIntegerWideningViableForSlice(const Slice &S, uint64_t AllocBeginOffset, Type *AllocaTy, const DataLayout &DL, bool &WholeAllocaOp)
Test whether a slice of an alloca is valid for integer widening.
static bool rewritePHINodeStore(PHINode &PN, StoreInst &SI, DomTreeUpdater &DTU, SmallSetVector< AllocaInst *, 16 > &Worklist)
Move a store through a pointer PHI onto each of the PHI's incoming edges.
static Value * extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex, unsigned EndIndex, const Twine &Name)
static Value * foldPHINodeOrSelectInst(Instruction &I)
A helper that folds a PHI node or a select.
static bool rewriteSelectInstMemOps(SelectInst &SI, const RewriteableMemOps &Ops, IRBuilderTy &IRB, DomTreeUpdater *DTU)
static Slice * findOverlappingCopySlice(Slice &S, InstructionSliceMap &SliceMap)
Try to find a slice in the map that partially overlaps with S, i.e.
static Value * foldSelectInst(SelectInst &SI)
bool isKillAddress(const DbgVariableRecord *DVR)
static Value * insertVector(IRBuilderTy &IRB, Value *Old, Value *V, unsigned BeginIndex, const Twine &Name)
static bool isIntegerWideningViable(Partition &P, Type *AllocaTy, const DataLayout &DL)
Test whether the given alloca partition's integer operations can be widened to promotable ones.
static void speculatePHINodeLoads(IRBuilderTy &IRB, PHINode &PN)
static VectorType * createAndCheckVectorTypesForPromotion(SetVector< Type * > &OtherTys, ArrayRef< VectorType * > CandidateTysCopy, function_ref< void(Type *)> CheckCandidateType, Partition &P, const DataLayout &DL, SmallVectorImpl< VectorType * > &CandidateTys, bool &HaveCommonEltTy, Type *&CommonEltTy, bool &HaveVecPtrTy, bool &HaveCommonVecPtrTy, VectorType *&CommonVecPtrTy, unsigned VScale)
static DebugVariable getAggregateVariable(DbgVariableRecord *DVR)
static std::tuple< Type *, bool, VectorType * > selectPartitionType(Partition &P, const DataLayout &DL, AllocaInst &AI, LLVMContext &C, bool AggregateToVector)
Select a partition type for an alloca partition.
static bool isSafePHIToSpeculate(PHINode &PN)
PHI instructions that use an alloca and are subsequently loaded can be rewritten to load both input p...
static FixedVectorType * tryCanonicalizeStructToVector(StructType *STy, Partition &P, const DataLayout &DL)
Try to canonicalize a homogeneous struct partition to a vector type.
static Value * extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V, IntegerType *Ty, uint64_t Offset, const Twine &Name)
static void insertNewDbgInst(DIBuilder &DIB, DbgVariableRecord *Orig, AllocaInst *NewAddr, DIExpression *NewAddrExpr, Instruction *BeforeInst, std::optional< DIExpression::FragmentInfo > NewFragment, int64_t BitExtractAdjustment)
Insert a new DbgRecord.
static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S, VectorType *Ty, uint64_t ElementBits, const DataLayout &DL, unsigned VScale)
Test whether the given slice use can be promoted to a vector.
static void speculateSelectInstLoads(SelectInst &SI, LoadInst &LI, IRBuilderTy &IRB)
static Value * mergeTwoVectors(Value *V0, Value *V1, const DataLayout &DL, Type *NewAIEltTy, IRBuilder<> &Builder)
This function takes two vector values and combines them into a single vector by concatenating their e...
const DIExpression * getAddressExpression(const DbgVariableRecord *DVR)
static Type * getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset, uint64_t Size)
Try to find a partition of the aggregate type passed in for a given offset and size.
static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy, unsigned VScale=0)
Test whether we can convert a value from the old to the new type.
static SelectHandSpeculativity isSafeLoadOfSelectToSpeculate(LoadInst &LI, SelectInst &SI, bool PreserveCFG)
static StoreInst * getPHIStoreToRewrite(PHINode &PN, bool PreserveCFG, DominatorTree &DT)
Check whether a single store through PN can be moved onto each incoming edge.
static Type * findCommonTypeThroughPHIOrSelect(Instruction &I)
Find a common load/store type used through a pointer PHI or select.
This file provides the interface for LLVM's Scalar Replacement of Aggregates pass.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the SparseBitVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static SymbolRef::Type getType(const Symbol *Sym)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
virt reg Virtual Register Rewriter
Builder for the alloca slices.
SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
An iterator over partitions of the alloca's slices.
bool operator==(const partition_iterator &RHS) const
friend class AllocaSlices
partition_iterator & operator++()
SliceSplitter(IRBuilderTy &IRB, const DataLayout &DL, std::vector< uint64_t > &Splits, unsigned SliceSize)
StoreInst * createStore(Value *StoreVal, Value *BasePtr, Iterator &It, Instruction *SplitI)
Slice createSlice(Instruction *I, uint64_t BaseOffset, Iterator &It)
LoadInst * createLoad(Value *BasePtr, Iterator &It, Instruction *SplitI)
Class for arbitrary precision integers.
an instruction to allocate memory on the stack
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI bool canSplitPredecessors() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Represents analyses that only rely on functions' control flow.
LLVM_ABI CaptureInfo getCaptureInfo(unsigned OpNo) const
Return which pointer components this operand may capture.
bool onlyReadsMemory(unsigned OpNo) const
bool isDataOperand(const Use *U) const
This is the shared class of boolean and integer constants.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static DIAssignID * getDistinct(LLVMContext &Context)
LLVM_ABI DbgRecord * insertDbgAssign(Instruction *LinkedInstr, Value *Val, DILocalVariable *SrcVar, DIExpression *ValExpr, Value *Addr, DIExpression *AddrExpr, const DILocation *DL)
Insert a new dbg_assign record.
iterator_range< expr_op_iterator > expr_ops() const
DbgVariableFragmentInfo FragmentInfo
LLVM_ABI bool startsWithDeref() const
Return whether the first element a DW_OP_deref.
static LLVM_ABI bool calculateFragmentIntersect(const DataLayout &DL, const Value *SliceStart, uint64_t SliceOffsetInBits, uint64_t SliceSizeInBits, const Value *DbgPtr, int64_t DbgPtrOffsetInBits, int64_t DbgExtractOffsetInBits, DIExpression::FragmentInfo VarFrag, std::optional< DIExpression::FragmentInfo > &Result, int64_t &OffsetFromLocationInBits)
Computes a fragment, bit-extract operation if needed, and new constant offset to describe a part of a...
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
A parsed version of the target data layout string in and methods for querying it.
LLVM_ABI void moveBefore(DbgRecord *MoveBefore)
DebugLoc getDebugLoc() const
void setDebugLoc(DebugLoc Loc)
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI void setKillAddress()
Kill the address component.
LLVM_ABI bool isKillLocation() const
LocationType getType() const
LLVM_ABI bool isKillAddress() const
Check whether this kills the address component.
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
Value * getValue(unsigned OpIdx=0) const
static LLVM_ABI DbgVariableRecord * createLinkedDVRAssign(Instruction *LinkedInstr, Value *Val, DILocalVariable *Variable, DIExpression *Expression, Value *Address, DIExpression *AddressExpression, const DILocation *DI)
LLVM_ABI void setAssignId(DIAssignID *New)
DIExpression * getExpression() const
static LLVM_ABI DbgVariableRecord * createDVRDeclare(Value *Address, DILocalVariable *DV, DIExpression *Expr, const DILocation *DI)
static LLVM_ABI DbgVariableRecord * createDbgVariableRecord(Value *Location, DILocalVariable *DV, DIExpression *Expr, const DILocation *DI)
DILocalVariable * getVariable() const
LLVM_ABI void setKillLocation()
bool isDbgDeclare() const
void setAddress(Value *V)
DIExpression * getAddressExpression() const
LLVM_ABI DILocation * getInlinedAt() const
Identifies a unique instance of a variable.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Analysis pass which computes a DominatorTree.
Legacy analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Class to represent fixed width SIMD vectors.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
FunctionPass class - This class is used to implement most global optimizations.
unsigned getVScaleValue() const
Return the value for vscale based on the vscale_range attribute or 0 when unknown.
const BasicBlock & getEntryBlock() const
LLVM_ABI bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset, function_ref< bool(Value &, APInt &)> ExternalAnalysis=nullptr) const
Accumulate the constant address offset of this GEP if possible.
Value * getPointerOperand()
iterator_range< op_iterator > indices()
Type * getSourceElementType() const
LLVM_ABI GEPNoWrapFlags getNoWrapFlags() const
Get the nowrap flags for the GEP instruction.
This provides the default implementation of the IRBuilder 'InsertHelper' method that is called whenev...
void InsertHelper(Instruction *I, const Twine &Name, BasicBlock::iterator InsertPt) const
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Base class for instruction visitors.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
void setAlignment(Align Align)
Value * getPointerOperand()
bool isVolatile() const
Return true if this is a load from a volatile memory location.
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this load instruction.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
Type * getPointerOperandType() const
static unsigned getPointerOperandIndex()
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
LLVMContext & getContext() const
This is the common base class for memset/memcpy/memmove.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
PtrUseVisitor(const DataLayout &DL)
LLVM_ABI SROAPass(SROAOptions Options)
If PreserveCFG is set, then the pass is not allowed to modify CFG in any way, even if it would update...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Helper class for SSA formation on a set of values defined in multiple blocks.
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
size_type size() const
Determine the number of elements in the SetVector.
void clear()
Completely clear the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
typename SuperClass::const_iterator const_iterator
typename SuperClass::iterator iterator
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
bool test(unsigned Idx) const
An instruction for storing to memory.
bool isAtomic() const
Return true if this store has an atomic ordering.
void setAlignment(Align Align)
Value * getValueOperand()
static unsigned getPointerOperandIndex()
Value * getPointerOperand()
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this store instruction.
Represent a constant reference to a string, i.e.
static constexpr size_t npos
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
LLVM_ABI size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
LLVM_ABI size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
TypeSize getSizeInBytes() const
LLVM_ABI unsigned getElementContainingOffset(uint64_t FixedOffset) const
Given a valid byte offset into the structure, returns the structure index that contains it.
TypeSize getElementOffset(unsigned Idx) const
TypeSize getSizeInBits() const
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
element_iterator element_end() const
ArrayRef< Type * > elements() const
element_iterator element_begin() const
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Type::subtype_iterator element_iterator
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static constexpr TypeSize getFixed(ScalarTy ExactSize)
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isStructTy() const
True if this is an instance of StructType.
bool isTargetExtTy() const
Return true if this is a target extension type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isIntegerTy() const
True if this is an instance of IntegerType.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
LLVM_ABI void dropDroppableUsesIn(User &Usr)
Remove every use of this value in User that can safely be removed.
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static VectorType * getWithSizeAndScalar(VectorType *SizeTy, Type *EltTy)
This static method attempts to construct a VectorType with the same size-in-bits as SizeTy but with a...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
constexpr ScalarTy getFixedValue() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ BasicBlock
Various leaf nodes.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
LLVM_ABI void deleteAssignmentMarkers(const Instruction *Inst)
Delete the llvm.dbg.assign intrinsics linked to Inst.
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
NodeAddr< UseNode * > Use
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI iterator begin() const
unsigned getNumElements(Type *Ty)
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
bool operator<(int64_t V1, const APSInt &V2)
void stable_sort(R &&Range)
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI void PromoteMemToReg(ArrayRef< AllocaInst * > Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool operator!=(uint64_t V1, const APInt &V2)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
const ScalarOptions & getScalarOptions(const LLVMContext &C)
auto unique(Range &&R, Predicate P)
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
bool capturesFullProvenance(CaptureComponents CC)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void initializeSROALegacyPassPass(PassRegistry &)
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRValues(Value *V)
As above, for DVRValues.
LLVM_ABI void llvm_unreachable_internal(const char *msg=nullptr, const char *file=nullptr, unsigned line=0)
This function calls abort(), and prints the optional message to stderr.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
constexpr int PoisonMaskElem
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ, bool IgnoreFree=false)
Return true if we know that executing a load from this value cannot trap.
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
DWARFExpression::Operation Op
LLVM_ABI Align tryEnforceAlignment(Value *V, Align PrefAlign, const DataLayout &DL)
If the specified pointer points to an object that we control, try to modify the object's alignment to...
LLVM_ABI FunctionPass * createSROAPass(bool PreserveCFG=true, bool AggregateToVector=false)
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRDeclares(Value *V)
Finds dbg.declare records declaring local variables as living in the memory that 'V' points to.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
LLVM_ABI std::optional< Register > getVectorSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI)
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI llvm::SmallVector< int, 16 > createSequentialMask(unsigned Start, unsigned NumInts, unsigned NumUndefs)
Create a sequential shuffle mask.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
An iterator which iterates over the sub-slices that we want to split the slice into.
bool operator==(const Iterator &Other) const
const Iterator & operator*() const
uint64_t getOffset() const
Iterator(SliceSplitter &SS, bool IsEnd)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
AAMDNodes shift(size_t Offset) const
Create a new AAMDNode that describes this AAMDNode after applying a constant offset to the start of t...
LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize)
Create a new AAMDNode for accessing AccessSize bytes of this AAMDNode.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Describes an element of a Bitfield.
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.