66#define DEBUG_TYPE "memcpyopt"
68STATISTIC(NumMemCpyInstr,
"Number of memcpy instructions deleted");
69STATISTIC(NumMemMoveInstr,
"Number of memmove instructions deleted");
70STATISTIC(NumMemSetInfer,
"Number of memsets inferred");
71STATISTIC(NumMoveToCpy,
"Number of memmoves converted to memcpy");
72STATISTIC(NumCpyToSet,
"Number of memcpys converted to memset");
73STATISTIC(NumCallSlot,
"Number of call slot optimizations performed");
74STATISTIC(NumStackMove,
"Number of stack-move optimizations performed");
103 bool isProfitableToUseMemset(
const DataLayout &
DL)
const;
111bool MemsetRange::isProfitableToUseMemset(
const DataLayout &
DL)
const {
113 if (TheStores.
size() >= 4 ||
End - Start >= 16)
117 if (TheStores.
size() < 2)
122 for (Instruction *SI : TheStores)
128 if (TheStores.size() == 2)
141 unsigned Bytes = unsigned(
End - Start);
142 unsigned MaxIntSize =
DL.getLargestLegalIntTypeSizeInBits() / 8;
145 unsigned NumPointerStores = Bytes / MaxIntSize;
148 unsigned NumByteStores = Bytes % MaxIntSize;
153 return TheStores.size() > NumPointerStores + NumByteStores;
164 const DataLayout &
DL;
167 MemsetRanges(
const DataLayout &
DL) :
DL(
DL) {}
171 const_iterator
begin()
const {
return Ranges.begin(); }
172 const_iterator
end()
const {
return Ranges.end(); }
175 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
177 addStore(OffsetFromFirst, SI);
182 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
183 TypeSize StoreSize =
DL.getTypeStoreSize(
SI->getOperand(0)->getType());
186 SI->getPointerOperand(),
SI->getAlign(), SI);
189 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
203void MemsetRanges::addRange(int64_t Start, int64_t
Size,
Value *Ptr,
204 MaybeAlign Alignment, Instruction *Inst) {
208 Ranges, [=](
const MemsetRange &O) {
return O.End <
Start; });
214 MemsetRange &
R = *
Ranges.insert(
I, MemsetRange());
219 R.TheStores.push_back(Inst);
224 I->TheStores.push_back(Inst);
228 if (
I->Start <= Start &&
I->End >=
End)
237 if (Start < I->Start) {
248 range_iterator NextI =
I;
249 while (++NextI !=
Ranges.end() &&
End >= NextI->Start) {
251 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
252 if (NextI->End >
I->End)
268 assert(Start->getParent() ==
End->getParent() &&
"Must be in same block");
270 if (Start->getFunction()->doesNotThrow())
275 bool RequiresNoCaptureBeforeUnwind;
277 RequiresNoCaptureBeforeUnwind) &&
278 !RequiresNoCaptureBeforeUnwind)
286void MemCpyOptPass::eraseInstruction(Instruction *
I) {
287 MSSAU->removeMemoryAccess(
I);
288 EEA->removeInstruction(
I);
289 I->eraseFromParent();
300 assert(Start->getBlock() ==
End->getBlock() &&
"Only local supported");
306 if (
II &&
II->getIntrinsicID() == Intrinsic::lifetime_start &&
307 SkippedLifetimeStart && !*SkippedLifetimeStart) {
308 *SkippedLifetimeStart =
I;
327 return Start->getBlock() !=
End->getBlock() ||
329 make_range(std::next(Start->getIterator()),
End->getIterator()),
331 if (isa<MemoryUse>(&Acc))
333 Instruction *AccInst =
334 cast<MemoryUseOrDef>(&Acc)->getMemoryInst();
335 return isModSet(AA.getModRefInfo(AccInst, Loc));
348 bool IsForceInlined) {
350 return Builder.CreateMemSetInline(Ptr,
Align, Val,
Size);
351 return Builder.CreateMemSet(Ptr, Val,
Size,
Align);
358Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
365 if (
DL.getTypeStoreSize(
SI->getOperand(0)->getType()).isScalable())
379 MemoryUseOrDef *MemInsertPoint =
nullptr;
380 for (++BI; !BI->isTerminator(); ++BI) {
384 MemInsertPoint = CurrentAcc;
391 if (CB->onlyAccessesInaccessibleMemory())
399 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
406 if (!NextStore->isSimple())
409 Value *StoredVal = NextStore->getValueOperand();
417 if (
DL.getTypeStoreSize(StoredVal->
getType()).isScalable())
426 if (ByteVal != StoredByte)
430 std::optional<int64_t>
Offset =
431 NextStore->getPointerOperand()->getPointerOffsetFrom(StartPtr,
DL);
439 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
444 std::optional<int64_t>
Offset =
445 MSI->getDest()->getPointerOffsetFrom(StartPtr,
DL);
461 Ranges.addInst(0, StartInst);
471 for (
const MemsetRange &
Range : Ranges) {
472 if (
Range.TheStores.size() == 1)
476 if (!
Range.isProfitableToUseMemset(
DL))
481 StartPtr =
Range.StartPtr;
486 bool IsForceInlined =
487 !MemSets.empty() &&
all_of(MemSets, [](Instruction *
I) {
492 Range.Alignment, IsForceInlined);
493 AMemSet->mergeDIAssignID(
Range.TheStores);
498 dbgs() <<
"With: " << *AMemSet <<
'\n');
499 if (!
Range.TheStores.empty())
500 AMemSet->setDebugLoc(
Range.TheStores[0]->getDebugLoc());
504 ? MSSAU->createMemoryAccessBefore(AMemSet,
nullptr, MemInsertPoint)
505 : MSSAU->createMemoryAccessAfter(AMemSet,
nullptr, MemInsertPoint));
506 MSSAU->insertDef(NewDef,
true);
507 MemInsertPoint = NewDef;
510 for (Instruction *SI :
Range.TheStores)
523bool MemCpyOptPass::moveUp(StoreInst *SI, Instruction *
P,
const LoadInst *LI) {
531 DenseSet<Instruction *>
Args;
532 auto AddArg = [&](
Value *Arg) {
534 if (
I &&
I->getParent() ==
SI->getParent()) {
542 if (!AddArg(
SI->getPointerOperand()))
546 SmallVector<Instruction *, 8> ToLift{
SI};
556 for (
auto I = --
SI->getIterator(),
E =
P->getIterator();
I !=
E; --
I) {
564 bool MayAlias =
isModOrRefSet(AA->getModRefInfo(
C, std::nullopt));
566 bool NeedLift =
false;
586 if (
isModSet(AA->getModRefInfo(
C, LoadLoc)))
619 MemoryUseOrDef *MemInsertPoint =
nullptr;
620 if (MemoryUseOrDef *MA = MSSA->getMemoryAccess(
P)) {
626 if (MemoryUseOrDef *MA = MSSA->getMemoryAccess(&
I)) {
636 EEA->insertPotentialCapture(
I);
637 I->moveBefore(
P->getIterator());
638 assert(MemInsertPoint &&
"Must have found insert point");
639 if (MemoryUseOrDef *MA = MSSA->getMemoryAccess(
I)) {
640 MSSAU->moveAfter(MA, MemInsertPoint);
648bool MemCpyOptPass::processStoreOfLoad(StoreInst *SI, LoadInst *LI,
649 const DataLayout &
DL,
654 BatchAAResults BAA(*AA, EEA);
656 if (
T->isAggregateType()) {
666 if (
isModSet(BAA.getModRefInfo(&
I, LoadLoc))) {
676 if (
P == SI || moveUp(SI,
P, LI)) {
681 bool UseMemMove =
false;
682 if (
isModSet(AA->getModRefInfo(SI, LoadLoc)))
687 Builder.CreateTypeSize(Builder.getInt64Ty(),
DL.getTypeStoreSize(
T));
690 M = Builder.CreateMemMove(
SI->getPointerOperand(),
SI->getAlign(),
694 M = Builder.CreateMemCpy(
SI->getPointerOperand(),
SI->getAlign(),
696 M->copyMetadata(*SI, LLVMContext::MD_DIAssignID);
698 LLVM_DEBUG(
dbgs() <<
"Promoting " << *LI <<
" to " << *SI <<
" => " << *M
702 auto *NewAccess = MSSAU->createMemoryAccessAfter(M,
nullptr, LastDef);
710 BBI =
M->getIterator();
718 auto GetCall = [&]() -> CallInst * {
722 MSSA->getWalker()->getClobberingMemoryAccess(LI, BAA)))
727 bool Changed = performCallSlotOptzn(
728 LI, SI,
SI->getPointerOperand()->stripPointerCasts(),
730 DL.getTypeStoreSize(
SI->getOperand(0)->getType()),
731 std::min(
SI->getAlign(), LI->
getAlign()), BAA, GetCall);
742 if (performStackMoveOptzn(LI, SI,
SI->getPointerOperand(),
746 BBI =
SI->getNextNode()->getIterator();
766 if (
SI->getMetadata(LLVMContext::MD_nontemporal))
769 const DataLayout &
DL =
SI->getDataLayout();
771 Value *StoredVal =
SI->getValueOperand();
780 return processStoreOfLoad(SI, LI,
DL, BBI);
794 tryMergingIntoMemset(SI,
SI->getPointerOperand(), ByteVal)) {
795 BBI =
I->getIterator();
802 auto *
T =
V->getType();
803 if (!
T->isAggregateType())
806 TypeSize
Size =
DL.getTypeStoreSize(
T);
807 if (
Size.isScalable())
811 auto *
M = Builder.CreateMemSet(
SI->getPointerOperand(), ByteVal,
Size,
813 M->copyMetadata(*SI, LLVMContext::MD_DIAssignID);
815 LLVM_DEBUG(
dbgs() <<
"Promoting " << *SI <<
" to " << *M <<
"\n");
820 auto *NewAccess = MSSAU->createMemoryAccessBefore(M,
nullptr, StoreDef);
827 BBI =
M->getIterator();
837 BBI =
I->getIterator();
846bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpyLoad,
847 Instruction *cpyStore,
Value *cpyDest,
848 Value *cpySrc, TypeSize cpySize,
851 std::function<CallInst *()> GetC) {
877 std::optional<TypeSize> SrcAllocaSize = srcAlloca->getAllocationSize(
DL);
878 if (!SrcAllocaSize || SrcAllocaSize->isScalable())
880 uint64_t srcSize = SrcAllocaSize->getFixedValue();
882 if (cpySize < srcSize)
885 CallInst *
C = GetC();
891 if (
F->isIntrinsic() &&
F->getIntrinsicID() == Intrinsic::lifetime_start)
894 if (
C->getParent() != cpyStore->
getParent()) {
899 MemoryLocation DestLoc =
902 : MemoryLocation::getForDest(
cast<MemCpyInst>(cpyStore));
908 MSSA->getMemoryAccess(cpyStore), &SkippedLifetimeStart)) {
909 LLVM_DEBUG(dbgs() <<
"Call Slot: Dest pointer modified after call\n");
916 if (SkippedLifetimeStart) {
919 if (LifetimeArg && LifetimeArg->getParent() ==
C->getParent() &&
920 C->comesBefore(LifetimeArg))
926 bool ExplicitlyDereferenceableOnly;
928 ExplicitlyDereferenceableOnly) ||
930 SimplifyQuery(
DL, DT, AC,
C))) {
939 LLVM_DEBUG(
dbgs() <<
"Call Slot: Dest pointer not dereferenceable\n");
959 LLVM_DEBUG(
dbgs() <<
"Call Slot: Dest may be visible through unwinding\n");
964 Align srcAlign = srcAlloca->getAlign();
965 bool isDestSufficientlyAligned = srcAlign <= cpyDestAlign;
969 LLVM_DEBUG(
dbgs() <<
"Call Slot: Dest not sufficiently aligned\n");
978 while (!srcUseList.empty()) {
979 User *
U = srcUseList.pop_back_val();
988 if (U !=
C && U != cpyLoad) {
989 LLVM_DEBUG(
dbgs() <<
"Call slot: Source accessed by " << *U <<
"\n");
996 bool SrcIsCaptured =
any_of(
C->args(), [&](Use &U) {
997 return U->stripPointerCasts() == cpySrc &&
998 !C->doesNotCapture(C->getArgOperandNo(&U));
1004 if (SrcIsCaptured) {
1015 MemoryLocation SrcLoc =
1017 for (Instruction &
I :
1018 make_range(++
C->getIterator(),
C->getParent()->end())) {
1021 if (
II->getIntrinsicID() == Intrinsic::lifetime_end &&
1022 II->getArgOperand(0) == srcAlloca)
1045 bool NeedMoveGEP =
false;
1046 if (!DT->dominates(cpyDest,
C)) {
1049 if (
GEP &&
GEP->hasAllConstantIndices() &&
1050 DT->dominates(
GEP->getPointerOperand(),
C))
1072 for (
unsigned ArgI = 0; ArgI <
C->arg_size(); ++ArgI)
1073 if (
C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc &&
1074 cpySrc->
getType() !=
C->getArgOperand(ArgI)->getType())
1078 bool changedArgument =
false;
1079 for (
unsigned ArgI = 0; ArgI <
C->arg_size(); ++ArgI)
1080 if (
C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc) {
1081 changedArgument =
true;
1082 C->setArgOperand(ArgI, cpyDest);
1085 if (!changedArgument)
1089 if (!isDestSufficientlyAligned) {
1097 GEP->moveBefore(
C->getIterator());
1100 if (SkippedLifetimeStart) {
1101 SkippedLifetimeStart->
moveBefore(
C->getIterator());
1102 MSSAU->moveBefore(MSSA->getMemoryAccess(SkippedLifetimeStart),
1103 MSSA->getMemoryAccess(
C));
1107 if (cpyLoad != cpyStore)
1116bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
1118 BatchAAResults &BAA) {
1132 int64_t MForwardOffset = 0;
1133 const DataLayout &
DL =
M->getDataLayout();
1136 if (
M->getSource() != MDep->
getDest()) {
1137 std::optional<int64_t>
Offset =
1138 M->getSource()->getPointerOffsetFrom(MDep->
getDest(),
DL);
1141 MForwardOffset = *
Offset;
1144 Value *CopyLength =
M->getLength();
1149 if (MForwardOffset != 0 || MDep->
getLength() != CopyLength) {
1155 if (!MDepLen || !MLen)
1157 if (MDepLen->getZExtValue() < MLen->getZExtValue() + MForwardOffset) {
1160 if (MDepLen->getZExtValue() <= (
uint64_t)MForwardOffset)
1164 CopyLength = ConstantInt::get(CopyLength->
getType(),
1165 MDepLen->getZExtValue() - MForwardOffset);
1173 if (NewCopySource && NewCopySource->
use_empty())
1186 MCopyLoc = MCopyLoc.getWithNewSize(
1195 if (MForwardOffset > 0) {
1197 std::optional<int64_t> MDestOffset =
1199 if (MDestOffset == MForwardOffset)
1200 CopySource =
M->getDest();
1202 CopySource = Builder.CreatePtrAddWithSignedOffset(
1207 MCopyLoc = MCopyLoc.getWithNewPtr(CopySource);
1208 if (CopySourceAlign)
1221 if (
writtenBetween(MSSA, BAA, MCopyLoc, MSSA->getMemoryAccess(MDep),
1222 MSSA->getMemoryAccess(M)))
1238 bool UseMemMove =
false;
1243 if (
M->isForceInlined())
1249 LLVM_DEBUG(
dbgs() <<
"MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
1257 NewM = Builder.CreateMemMove(
M->getDest(),
M->getDestAlign(), CopySource,
1258 CopySourceAlign, CopyLength,
M->isVolatile());
1259 else if (
M->isForceInlined())
1263 NewM = Builder.CreateMemCpyInline(
M->getDest(),
M->getDestAlign(),
1264 CopySource, CopySourceAlign, CopyLength,
1267 NewM = Builder.CreateMemCpy(
M->getDest(),
M->getDestAlign(), CopySource,
1268 CopySourceAlign, CopyLength,
M->isVolatile());
1274 auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM,
nullptr, LastDef);
1302bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1304 BatchAAResults &BAA) {
1330 MSSA->getMemoryAccess(MemSet),
1331 MSSA->getMemoryAccess(MemCpy)))
1343 if (DestSize == SrcSize) {
1366 "Preserving debug location based on moving memset within BB.");
1367 Builder.SetCurrentDebugLocation(MemSet->
getDebugLoc());
1371 SrcSize = Builder.CreateZExtOrTrunc(SrcSize, IdxTy);
1372 DestSize = Builder.CreateZExtOrTrunc(DestSize, IdxTy);
1374 Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1375 Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1376 Value *MemsetLen = Builder.CreateSelect(
1377 Ule, ConstantInt::getNullValue(DestSize->
getType()), SizeDiff);
1383 Builder, Builder.CreatePtrAdd(Dest, SrcSize), MemSet->
getOperand(1),
1387 "MemCpy must be a MemoryDef");
1392 MSSAU->createMemoryAccessBefore(NewMemSet,
nullptr, LastDef);
1407 if (
II->getIntrinsicID() == Intrinsic::lifetime_start)
1409 return II->getArgOperand(0) == Alloca;
1442bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1444 BatchAAResults &BAA) {
1448 int64_t MOffset = 0;
1453 std::optional<int64_t>
Offset =
1464 if (MOffset != 0 || MemSetSize != CopySize) {
1471 if (!CMemSetSize || !CCopySize || MOffset < 0 ||
1472 CCopySize->getZExtValue() + MOffset > CMemSetSize->getZExtValue()) {
1476 if (CMemSetSize && CCopySize) {
1477 uint64_t MemSetSizeVal = CMemSetSize->getZExtValue();
1478 uint64_t MemCpySizeVal = CCopySize->getZExtValue();
1484 NewSize = MemCpySizeVal <=
Offset ? 0 : MemCpySizeVal -
Offset;
1485 }
else if (MOffset == 0) {
1486 NewSize = MemSetSizeVal;
1489 MemSetSizeVal <= (
uint64_t)MOffset ? 0 : MemSetSizeVal - MOffset;
1491 CopySize = ConstantInt::get(CopySize->
getType(), NewSize);
1503 DestPtr = Builder.CreatePtrAddWithSignedOffset(DestPtr, -MOffset);
1511 auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM,
nullptr, LastDef);
1529bool MemCpyOptPass::performStackMoveOptzn(Instruction *
Load, Instruction *
Store,
1531 TypeSize
Size, BatchAAResults &BAA) {
1546 if (SrcAlloca == DestAlloca)
1566 if (!SrcOffset || *SrcOffset < *DestOffset || *SrcOffset < 0)
1569 if ((*SrcOffset - *DestOffset) % DestAlloca->
getAlign().
value() != 0)
1573 if (!SrcSize || !DestSize)
1575 if (*SrcSize != *DestSize)
1576 if (!SrcSize->isFixed() || !DestSize->isFixed())
1579 if (
Size != *DestSize || *DestOffset != 0) {
1580 LLVM_DEBUG(
dbgs() <<
"Stack Move: Destination alloca size mismatch\n");
1586 if (
Size.isFixed()) {
1587 if (*SrcOffset +
Size > *SrcSize)
1589 }
else if (*SrcOffset != 0) {
1595 bool MoveSrc = !DT->dominates(SrcAlloca, DestAlloca);
1597 if (!DT->dominates(DestAlloca, SrcAlloca))
1606 SmallVector<Instruction *, 4> LifetimeMarkers;
1607 SmallPtrSet<Instruction *, 4> AAMetadataInstrs;
1609 auto CaptureTrackingWithModRef =
1610 [&](
Instruction *AI, function_ref<bool(Instruction *)> ModRefCallback,
1611 bool &AddressCaptured) ->
bool {
1612 SmallVector<Instruction *, 8> Worklist;
1615 Worklist.
reserve(MaxUsesToExplore);
1616 SmallPtrSet<const Use *, 20> Visited;
1617 while (!Worklist.
empty()) {
1619 for (
const Use &U :
I->uses()) {
1622 if (Visited.
size() >= MaxUsesToExplore) {
1625 <<
"Stack Move: Exceeded max uses to see ModRef, bailing\n");
1628 if (!Visited.
insert(&U).second)
1635 if (UI->mayReadOrWriteMemory()) {
1636 if (UI->isLifetimeStartOrEnd()) {
1645 AAMetadataInstrs.
insert(UI);
1647 if (!ModRefCallback(UI))
1662 ModRefInfo DestModRef = ModRefInfo::NoModRef;
1664 SmallVector<BasicBlock *, 8> ReachabilityWorklist;
1665 auto DestModRefCallback = [&](
Instruction *UI) ->
bool {
1675 if (UI->getParent() ==
Store->getParent()) {
1684 if (UI->comesBefore(
Store))
1694 ReachabilityWorklist.
push_back(UI->getParent());
1700 bool DestAddressCaptured =
false;
1701 if (!CaptureTrackingWithModRef(DestAlloca, DestModRefCallback,
1702 DestAddressCaptured))
1705 if (!ReachabilityWorklist.
empty() &&
1707 nullptr, DT,
nullptr))
1723 auto SrcModRefCallback = [&](
Instruction *UI) ->
bool {
1736 bool SrcAddressCaptured =
false;
1737 if (!CaptureTrackingWithModRef(SrcAlloca, SrcModRefCallback,
1738 SrcAddressCaptured))
1743 if (DestAddressCaptured && SrcAddressCaptured)
1755 if (*SrcSize != *DestSize) {
1758 if (DestSize->getFixedValue() > SrcSize->getFixedValue()) {
1765 Value *NewDestPtr = SrcAlloca;
1766 if (*SrcOffset != *DestOffset) {
1768 NewDestPtr = Builder.CreatePtrAddWithSignedOffset(
1780 if (!LifetimeMarkers.
empty()) {
1781 for (Instruction *
I : LifetimeMarkers)
1790 for (Instruction *
I : AAMetadataInstrs) {
1791 I->setMetadata(LLVMContext::MD_alias_scope,
nullptr);
1792 I->setMetadata(LLVMContext::MD_noalias,
nullptr);
1793 I->setMetadata(LLVMContext::MD_tbaa,
nullptr);
1794 I->setMetadata(LLVMContext::MD_tbaa_struct,
nullptr);
1797 LLVM_DEBUG(
dbgs() <<
"Stack Move: Performed stack-move optimization\n");
1819 if (
M->isVolatile())
1823 if (
M->getSource() ==
M->getDest()) {
1836 MemoryUseOrDef *MA = MSSA->getMemoryAccess(M);
1843 if (GV->isConstant() && GV->hasDefinitiveInitializer())
1845 M->getDataLayout())) {
1849 M->getDestAlign(),
M->isForceInlined());
1852 MSSAU->createMemoryAccessAfter(NewM,
nullptr, LastDef);
1860 BatchAAResults BAA(*AA, EEA);
1864 const MemoryAccess *DestClobber =
1865 MSSA->getWalker()->getClobberingMemoryAccess(AnyClobber, DestLoc, BAA);
1873 if (DestClobber->
getBlock() ==
M->getParent())
1874 if (processMemSetMemCpyDependence(M, MDep, BAA))
1877 MemoryAccess *SrcClobber = MSSA->getWalker()->getClobberingMemoryAccess(
1889 if (Instruction *
MI = MD->getMemoryInst()) {
1892 if (performCallSlotOptzn(M, M,
M->getDest(),
M->getSource(),
1894 M->getDestAlign().valueOrOne(), BAA,
1895 [
C]() -> CallInst * { return C; })) {
1897 <<
" call: " << *
C <<
"\n"
1898 <<
" memcpy: " << *M <<
"\n");
1906 if (processMemCpyMemCpyDependence(M, MDep, BAA))
1909 if (performMemCpyToMemSetOptzn(M, MDep, BAA)) {
1932 if (performStackMoveOptzn(M, M,
M->getDest(),
M->getSource(),
1935 BBI =
M->getNextNode()->getIterator();
1946bool MemCpyOptPass::isMemMoveMemSetDependency(MemMoveInst *M) {
1947 const auto &
DL =
M->getDataLayout();
1948 MemoryUseOrDef *MemMoveAccess = MSSA->getMemoryAccess(M);
1954 auto *MemMoveSourceOp =
M->getSource();
1960 LocationSize MemMoveLocSize = SourceLoc.
Size;
1961 if (
Source->getPointerOperand() !=
M->getDest() ||
1968 LocationSize TotalSize =
1970 MemoryLocation CombinedLoc(
M->getDest(), TotalSize);
1974 BatchAAResults BAA(*AA);
1977 MSSA->getWalker()->getClobberingMemoryAccess(FirstDef, CombinedLoc, BAA));
1987 if (!MemSetLength ||
1988 MemSetLength->getZExtValue() <
Offset.getZExtValue() + MemMoveSize)
2005 if (!
M->isVolatile() && isMemMoveMemSetDependency(M)) {
2015 LLVM_DEBUG(
dbgs() <<
"MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
2019 Type *ArgTys[3] = {
M->getRawDest()->getType(),
M->getRawSource()->getType(),
2020 M->getLength()->getType()};
2022 M->getModule(), Intrinsic::memcpy, ArgTys));
2032bool MemCpyOptPass::processByValArgument(CallBase &CB,
unsigned ArgNo) {
2037 TypeSize ByValSize =
DL.getTypeAllocSize(ByValTy);
2039 MemoryUseOrDef *CallAccess = MSSA->getMemoryAccess(&CB);
2042 MemCpyInst *MDep =
nullptr;
2043 BatchAAResults BAA(*AA, EEA);
2044 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
2058 if (!
C1 || !TypeSize::isKnownGE(
2071 if ((!MemDepAlign || *MemDepAlign < *ByValAlign) &&
2087 MSSA->getMemoryAccess(MDep), CallAccess))
2090 LLVM_DEBUG(
dbgs() <<
"MemCpyOptPass: Forwarding memcpy to byval:\n"
2091 <<
" " << *MDep <<
"\n"
2092 <<
" " << CB <<
"\n");
2115bool MemCpyOptPass::processImmutArgument(CallBase &CB,
unsigned ArgNo) {
2116 BatchAAResults BAA(*AA, EEA);
2140 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(
DL);
2143 if (!AllocaSize || AllocaSize->isScalable())
2146 MemoryUseOrDef *CallAccess = MSSA->getMemoryAccess(&CB);
2150 MemCpyInst *MDep =
nullptr;
2151 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
2167 if (!MDepLen || AllocaSize != MDepLen->getValue())
2174 Align AllocaAlign = AI->getAlign();
2175 if (MemDepAlign < AllocaAlign &&
2187 MSSA->getMemoryAccess(MDep), CallAccess))
2194 LLVM_DEBUG(
dbgs() <<
"MemCpyOptPass: Forwarding memcpy to Immut src:\n"
2195 <<
" " << *MDep <<
"\n"
2196 <<
" " << CB <<
"\n");
2206bool MemCpyOptPass::iterateOnFunction(
Function &
F) {
2207 bool MadeChange =
false;
2210 for (BasicBlock &BB :
F) {
2215 if (!DT->isReachableFromEntry(&BB))
2222 bool RepeatInstruction =
false;
2225 MadeChange |= processStore(SI, BI);
2227 RepeatInstruction = processMemSet(M, BI);
2229 RepeatInstruction = processMemCpy(M, BI);
2231 RepeatInstruction = processMemMove(M, BI);
2233 for (
unsigned i = 0, e = CB->
arg_size(); i != e; ++i) {
2235 MadeChange |= processByValArgument(*CB, i);
2237 MadeChange |= processImmutArgument(*CB, i);
2242 if (RepeatInstruction) {
2243 if (BI != BB.
begin())
2261 bool MadeChange =
runImpl(
F, &TLI, AA, AC, DT, PDT, &MSSA->getMSSA());
2275 bool MadeChange =
false;
2288 if (!iterateOnFunction(
F))
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool runImpl(MachineFunction &MF)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseSet and SmallDenseSet classes.
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.
static void eraseInstruction(Instruction &I, const LICMDependencies &Deps)
if(!TBB||Cond.size()< 1) return false
static bool mayBeVisibleThroughUnwinding(Value *V, Instruction *Start, Instruction *End)
static CallInst * createMemSet(IRBuilder<> &Builder, Value *Ptr, Value *Val, Value *Size, MaybeAlign Align, bool IsForceInlined)
Create a memset.inline if IsForceInlined is true, or a memset otherwise.
static bool isZeroSize(Value *Size)
static bool hasUndefContents(MemorySSA *MSSA, BatchAAResults &AA, Value *V, MemoryDef *Def)
Determine whether the pointer V had only undefined content (due to Def), either because it was freshl...
static bool accessedBetween(BatchAAResults &AA, MemoryLocation Loc, const MemoryUseOrDef *Start, const MemoryUseOrDef *End, Instruction **SkippedLifetimeStart=nullptr)
static bool overreadUndefContents(MemorySSA *MSSA, MemCpyInst *MemCpy, MemIntrinsic *MemSrc, BatchAAResults &BAA)
static bool writtenBetween(MemorySSA *MSSA, BatchAAResults &AA, MemoryLocation Loc, const MemoryUseOrDef *Start, const MemoryUseOrDef *End)
This file provides utility analysis objects describing memory locations.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
This file contains the declarations for profiling metadata utility functions.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
A manager for alias analyses.
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.
void setAllocatedType(Type *Ty)
for use only in special circumstances that need to generically transform a whole instruction (eg: IR ...
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setAlignment(Align Align)
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
iterator begin()
Instruction iterator methods.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
InstListType::iterator iterator
Instruction iterators...
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
ModRefInfo callCapturesBefore(const Instruction *I, const MemoryLocation &MemLoc, DominatorTree *DT)
Represents analyses that only rely on functions' control flow.
bool doesNotCapture(unsigned OpNo) const
Determine whether this data operand is not captured.
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
bool onlyReadsMemory(unsigned OpNo) const
Type * getParamByValType(unsigned ArgNo) const
Extract the byval type for a call or parameter.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
A parsed version of the target data layout string in and methods for querying it.
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Context-sensitive CaptureAnalysis provider, which computes and caches the earliest common dominator c...
static GEPNoWrapFlags inBounds()
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs={})
Drop all unknown metadata except for debug locations.
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.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
static LocationSize precise(uint64_t Value)
TypeSize getValue() const
This class wraps the llvm.memcpy intrinsic.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Value * getLength() const
Value * getRawDest() const
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
MaybeAlign getDestAlign() const
This is the common base class for memset/memcpy/memmove.
bool isForceInlined() const
Value * getRawSource() const
Return the arguments to the instruction.
MaybeAlign getSourceAlign() const
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it,...
BasicBlock * getBlock() const
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static LLVM_ABI MemoryLocation getForSource(const MemTransferInst *MTI)
Return a location representing the source of a memory transfer.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
static LLVM_ABI MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
An analysis that produces MemorySSA for a function.
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Encapsulates MemorySSA, including all data associated with memory accesses.
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
LLVM_ABI MemorySSAWalker * getWalker()
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Class that has the common methods + fields of memory uses/defs.
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
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.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void reserve(size_type N)
typename SuperClass::const_iterator const_iterator
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type 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.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVM_ABI std::optional< int64_t > getPointerOffsetFrom(const Value *Other, const DataLayout &DL) const
If this ptr is provably equal to Other plus a constant offset, return that offset in bytes.
constexpr ScalarTy getFixedValue() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
const ParentTy * getParent() const
reverse_self_iterator getReverseIterator()
self_iterator getIterator()
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
Abstract Attribute helper functions.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations=nullptr)
See if we can compute a simplified version of this instruction.
bool capturesAddress(CaptureComponents CC)
LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
scope_exit(Callable) -> scope_exit< Callable >
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
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.
auto cast_or_null(const Y &Val)
LLVM_ABI unsigned getDefaultMaxUsesToExploreForCaptureTracking()
getDefaultMaxUsesToExploreForCaptureTracking - Return default value of the maximal number of uses to ...
LLVM_ABI bool PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures, const Instruction *I, const DominatorTree *DT, bool IncludeI=false, unsigned MaxUsesToExplore=0, const LoopInfo *LI=nullptr)
PointerMayBeCapturedBefore - Return true if this pointer value may be captured by the enclosing funct...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto reverse(ContainerTy &&C)
bool isModSet(const ModRefInfo MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
bool isModOrRefSet(const ModRefInfo MRI)
LLVM_ABI bool isNotVisibleOnUnwind(const Value *Object, bool &RequiresNoCaptureBeforeUnwind)
Return true if Object memory is not visible after an unwind, in the sense that program semantics cann...
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
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...
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
DWARFExpression::Operation Op
LLVM_ABI bool isPotentiallyReachableFromMany(SmallVectorImpl< BasicBlock * > &Worklist, const BasicBlock *StopBB, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether there is at least one path from a block in 'Worklist' to 'StopBB' without passing t...
LLVM_ABI bool isIdentifiedFunctionLocal(const Value *V)
Return true if V is umabigously identified at the function-level.
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
LLVM_ABI void combineAAMetadata(Instruction *K, const Instruction *J)
Combine metadata of two instructions, where instruction J is a memory access that has been merged int...
bool capturesAnything(CaptureComponents CC)
LLVM_ABI UseCaptureInfo DetermineUseCaptureKind(const Use &U, const Value *Base)
Determine what kind of capture behaviour U may exhibit.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
@ End
Run the machine verifier once, at the end of the pipeline.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
bool capturesAnyProvenance(CaptureComponents CC)
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
bool isRefSet(const ModRefInfo MRI)
LLVM_ABI bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly)
Return true if the Object is writable, in the sense that any location based on this pointer that can ...
This struct is a compact representation of a valid (non-zero power of two) alignment.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
CaptureComponents UseCC
Components captured by this use.
CaptureComponents ResultCC
Components captured by the return value of the user of this Use.