#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/CaptureTracking.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
using namespace llvm;
#define DEBUG_TYPE "memcpyopt"
static cl::opt<bool> EnableMemCpyOptWithoutLibcalls(
"enable-memcpyopt-without-libcalls", cl::Hidden,
cl::desc("Enable memcpyopt even when libcalls are disabled"));
STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
STATISTIC(NumMemSetInfer, "Number of memsets inferred");
STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
STATISTIC(NumCallSlot, "Number of call slot optimizations performed");
namespace {
struct MemsetRange {
int64_t Start, End;
Value *StartPtr;
MaybeAlign Alignment;
SmallVector<Instruction*, 16> TheStores;
bool isProfitableToUseMemset(const DataLayout &DL) const;
};
}
bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
if (TheStores.size() >= 4 || End-Start >= 16) return true;
if (TheStores.size() < 2) return false;
for (Instruction *SI : TheStores)
if (!isa<StoreInst>(SI))
return true;
if (TheStores.size() == 2) return false;
unsigned Bytes = unsigned(End-Start);
unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
if (MaxIntSize == 0)
MaxIntSize = 1;
unsigned NumPointerStores = Bytes / MaxIntSize;
unsigned NumByteStores = Bytes % MaxIntSize;
return TheStores.size() > NumPointerStores+NumByteStores;
}
namespace {
class MemsetRanges {
using range_iterator = SmallVectorImpl<MemsetRange>::iterator;
SmallVector<MemsetRange, 8> Ranges;
const DataLayout &DL;
public:
MemsetRanges(const DataLayout &DL) : DL(DL) {}
using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator;
const_iterator begin() const { return Ranges.begin(); }
const_iterator end() const { return Ranges.end(); }
bool empty() const { return Ranges.empty(); }
void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
if (auto *SI = dyn_cast<StoreInst>(Inst))
addStore(OffsetFromFirst, SI);
else
addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
}
void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
TypeSize StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
assert(!StoreSize.isScalable() && "Can't track scalable-typed stores");
addRange(OffsetFromFirst, StoreSize.getFixedSize(), SI->getPointerOperand(),
SI->getAlign(), SI);
}
void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getDestAlign(), MSI);
}
void addRange(int64_t Start, int64_t Size, Value *Ptr, MaybeAlign Alignment,
Instruction *Inst);
};
}
void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
MaybeAlign Alignment, Instruction *Inst) {
int64_t End = Start+Size;
range_iterator I = partition_point(
Ranges, [=](const MemsetRange &O) { return O.End < Start; });
if (I == Ranges.end() || End < I->Start) {
MemsetRange &R = *Ranges.insert(I, MemsetRange());
R.Start = Start;
R.End = End;
R.StartPtr = Ptr;
R.Alignment = Alignment;
R.TheStores.push_back(Inst);
return;
}
I->TheStores.push_back(Inst);
if (I->Start <= Start && I->End >= End)
return;
if (Start < I->Start) {
I->Start = Start;
I->StartPtr = Ptr;
I->Alignment = Alignment;
}
if (End > I->End) {
I->End = End;
range_iterator NextI = I;
while (++NextI != Ranges.end() && End >= NextI->Start) {
I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
if (NextI->End > I->End)
I->End = NextI->End;
Ranges.erase(NextI);
NextI = I;
}
}
}
namespace {
class MemCpyOptLegacyPass : public FunctionPass {
MemCpyOptPass Impl;
public:
static char ID;
MemCpyOptLegacyPass() : FunctionPass(ID) {
initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
private:
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
AU.addRequired<TargetLibraryInfoWrapperPass>();
AU.addRequired<AAResultsWrapperPass>();
AU.addPreserved<AAResultsWrapperPass>();
AU.addRequired<MemorySSAWrapperPass>();
AU.addPreserved<MemorySSAWrapperPass>();
}
};
}
char MemCpyOptLegacyPass::ID = 0;
FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
false, false)
static bool mayBeVisibleThroughUnwinding(Value *V, Instruction *Start,
Instruction *End) {
assert(Start->getParent() == End->getParent() && "Must be in same block");
if (Start->getFunction()->doesNotThrow())
return false;
bool RequiresNoCaptureBeforeUnwind;
if (isNotVisibleOnUnwind(getUnderlyingObject(V),
RequiresNoCaptureBeforeUnwind) &&
!RequiresNoCaptureBeforeUnwind)
return false;
return any_of(make_range(Start->getIterator(), End->getIterator()),
[](const Instruction &I) { return I.mayThrow(); });
}
void MemCpyOptPass::eraseInstruction(Instruction *I) {
MSSAU->removeMemoryAccess(I);
I->eraseFromParent();
}
static bool accessedBetween(AliasAnalysis &AA, MemoryLocation Loc,
const MemoryUseOrDef *Start,
const MemoryUseOrDef *End) {
assert(Start->getBlock() == End->getBlock() && "Only local supported");
for (const MemoryAccess &MA :
make_range(++Start->getIterator(), End->getIterator())) {
if (isModOrRefSet(AA.getModRefInfo(cast<MemoryUseOrDef>(MA).getMemoryInst(),
Loc)))
return true;
}
return false;
}
static bool writtenBetween(MemorySSA *MSSA, AliasAnalysis &AA,
MemoryLocation Loc, const MemoryUseOrDef *Start,
const MemoryUseOrDef *End) {
if (isa<MemoryUse>(End)) {
return Start->getBlock() != End->getBlock() ||
any_of(
make_range(std::next(Start->getIterator()), End->getIterator()),
[&AA, Loc](const MemoryAccess &Acc) {
if (isa<MemoryUse>(&Acc))
return false;
Instruction *AccInst =
cast<MemoryUseOrDef>(&Acc)->getMemoryInst();
return isModSet(AA.getModRefInfo(AccInst, Loc));
});
}
MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
End->getDefiningAccess(), Loc);
return !MSSA->dominates(Clobber, Start);
}
Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
Value *StartPtr,
Value *ByteVal) {
const DataLayout &DL = StartInst->getModule()->getDataLayout();
if (auto *SI = dyn_cast<StoreInst>(StartInst))
if (DL.getTypeStoreSize(SI->getOperand(0)->getType()).isScalable())
return nullptr;
MemsetRanges Ranges(DL);
BasicBlock::iterator BI(StartInst);
MemoryUseOrDef *MemInsertPoint = nullptr;
MemoryDef *LastMemDef = nullptr;
for (++BI; !BI->isTerminator(); ++BI) {
auto *CurrentAcc = cast_or_null<MemoryUseOrDef>(
MSSAU->getMemorySSA()->getMemoryAccess(&*BI));
if (CurrentAcc) {
MemInsertPoint = CurrentAcc;
if (auto *CurrentDef = dyn_cast<MemoryDef>(CurrentAcc))
LastMemDef = CurrentDef;
}
if (auto *CB = dyn_cast<CallBase>(BI)) {
if (CB->onlyAccessesInaccessibleMemory())
continue;
}
if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
break;
continue;
}
if (auto *NextStore = dyn_cast<StoreInst>(BI)) {
if (!NextStore->isSimple()) break;
Value *StoredVal = NextStore->getValueOperand();
if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
break;
if (DL.getTypeStoreSize(StoredVal->getType()).isScalable())
break;
Value *StoredByte = isBytewiseValue(StoredVal, DL);
if (isa<UndefValue>(ByteVal) && StoredByte)
ByteVal = StoredByte;
if (ByteVal != StoredByte)
break;
Optional<int64_t> Offset =
isPointerOffset(StartPtr, NextStore->getPointerOperand(), DL);
if (!Offset)
break;
Ranges.addStore(*Offset, NextStore);
} else {
auto *MSI = cast<MemSetInst>(BI);
if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
!isa<ConstantInt>(MSI->getLength()))
break;
Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), DL);
if (!Offset)
break;
Ranges.addMemSet(*Offset, MSI);
}
}
if (Ranges.empty())
return nullptr;
Ranges.addInst(0, StartInst);
IRBuilder<> Builder(&*BI);
Instruction *AMemSet = nullptr;
for (const MemsetRange &Range : Ranges) {
if (Range.TheStores.size() == 1) continue;
if (!Range.isProfitableToUseMemset(DL))
continue;
StartPtr = Range.StartPtr;
AMemSet = Builder.CreateMemSet(StartPtr, ByteVal, Range.End - Range.Start,
Range.Alignment);
LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SI
: Range.TheStores) dbgs()
<< *SI << '\n';
dbgs() << "With: " << *AMemSet << '\n');
if (!Range.TheStores.empty())
AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
assert(LastMemDef && MemInsertPoint &&
"Both LastMemDef and MemInsertPoint need to be set");
auto *NewDef =
cast<MemoryDef>(MemInsertPoint->getMemoryInst() == &*BI
? MSSAU->createMemoryAccessBefore(
AMemSet, LastMemDef, MemInsertPoint)
: MSSAU->createMemoryAccessAfter(
AMemSet, LastMemDef, MemInsertPoint));
MSSAU->insertDef(NewDef, true);
LastMemDef = NewDef;
MemInsertPoint = NewDef;
for (Instruction *SI : Range.TheStores)
eraseInstruction(SI);
++NumMemSetInfer;
}
return AMemSet;
}
bool MemCpyOptPass::moveUp(StoreInst *SI, Instruction *P, const LoadInst *LI) {
MemoryLocation StoreLoc = MemoryLocation::get(SI);
if (isModOrRefSet(AA->getModRefInfo(P, StoreLoc)))
return false;
DenseSet<Instruction*> Args;
if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
if (Ptr->getParent() == SI->getParent())
Args.insert(Ptr);
SmallVector<Instruction *, 8> ToLift{SI};
SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
SmallVector<const CallBase *, 8> Calls;
const MemoryLocation LoadLoc = MemoryLocation::get(LI);
for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
auto *C = &*I;
if (!isGuaranteedToTransferExecutionToSuccessor(C))
return false;
bool MayAlias = isModOrRefSet(AA->getModRefInfo(C, None));
bool NeedLift = false;
if (Args.erase(C))
NeedLift = true;
else if (MayAlias) {
NeedLift = llvm::any_of(MemLocs, [C, this](const MemoryLocation &ML) {
return isModOrRefSet(AA->getModRefInfo(C, ML));
});
if (!NeedLift)
NeedLift = llvm::any_of(Calls, [C, this](const CallBase *Call) {
return isModOrRefSet(AA->getModRefInfo(C, Call));
});
}
if (!NeedLift)
continue;
if (MayAlias) {
if (isModSet(AA->getModRefInfo(C, LoadLoc)))
return false;
else if (const auto *Call = dyn_cast<CallBase>(C)) {
if (isModOrRefSet(AA->getModRefInfo(P, Call)))
return false;
Calls.push_back(Call);
} else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
auto ML = MemoryLocation::get(C);
if (isModOrRefSet(AA->getModRefInfo(P, ML)))
return false;
MemLocs.push_back(ML);
} else
return false;
}
ToLift.push_back(C);
for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
if (auto *A = dyn_cast<Instruction>(C->getOperand(k))) {
if (A->getParent() == SI->getParent()) {
if(A == P) return false;
Args.insert(A);
}
}
}
MemoryUseOrDef *MemInsertPoint = nullptr;
if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(P)) {
MemInsertPoint = cast<MemoryUseOrDef>(--MA->getIterator());
} else {
const Instruction *ConstP = P;
for (const Instruction &I : make_range(++ConstP->getReverseIterator(),
++LI->getReverseIterator())) {
if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
MemInsertPoint = MA;
break;
}
}
}
for (auto *I : llvm::reverse(ToLift)) {
LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
I->moveBefore(P);
assert(MemInsertPoint && "Must have found insert point");
if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(I)) {
MSSAU->moveAfter(MA, MemInsertPoint);
MemInsertPoint = MA;
}
}
return true;
}
bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
if (!SI->isSimple()) return false;
if (SI->getMetadata(LLVMContext::MD_nontemporal))
return false;
const DataLayout &DL = SI->getModule()->getDataLayout();
Value *StoredVal = SI->getValueOperand();
if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
return false;
if (auto *LI = dyn_cast<LoadInst>(StoredVal)) {
if (LI->isSimple() && LI->hasOneUse() &&
LI->getParent() == SI->getParent()) {
auto *T = LI->getType();
if (T->isAggregateType() &&
(EnableMemCpyOptWithoutLibcalls ||
(TLI->has(LibFunc_memcpy) && TLI->has(LibFunc_memmove)))) {
MemoryLocation LoadLoc = MemoryLocation::get(LI);
Instruction *P = SI;
for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
if (isModSet(AA->getModRefInfo(&I, LoadLoc))) {
P = &I;
break;
}
}
if (P && P != SI) {
if (!moveUp(SI, P, LI))
P = nullptr;
}
if (P) {
bool UseMemMove = false;
if (isModSet(AA->getModRefInfo(SI, LoadLoc)))
UseMemMove = true;
uint64_t Size = DL.getTypeStoreSize(T);
IRBuilder<> Builder(P);
Instruction *M;
if (UseMemMove)
M = Builder.CreateMemMove(
SI->getPointerOperand(), SI->getAlign(),
LI->getPointerOperand(), LI->getAlign(), Size);
else
M = Builder.CreateMemCpy(
SI->getPointerOperand(), SI->getAlign(),
LI->getPointerOperand(), LI->getAlign(), Size);
LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "
<< *M << "\n");
auto *LastDef =
cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI));
auto *NewAccess = MSSAU->createMemoryAccessAfter(M, LastDef, LastDef);
MSSAU->insertDef(cast<MemoryDef>(NewAccess), true);
eraseInstruction(SI);
eraseInstruction(LI);
++NumMemCpyInstr;
BBI = M->getIterator();
return true;
}
}
auto GetCall = [&]() -> CallInst * {
if (auto *LoadClobber = dyn_cast<MemoryUseOrDef>(
MSSA->getWalker()->getClobberingMemoryAccess(LI)))
return dyn_cast_or_null<CallInst>(LoadClobber->getMemoryInst());
return nullptr;
};
bool changed = performCallSlotOptzn(
LI, SI, SI->getPointerOperand()->stripPointerCasts(),
LI->getPointerOperand()->stripPointerCasts(),
DL.getTypeStoreSize(SI->getOperand(0)->getType()),
std::min(SI->getAlign(), LI->getAlign()), GetCall);
if (changed) {
eraseInstruction(SI);
eraseInstruction(LI);
++NumMemCpyInstr;
return true;
}
}
}
if (!(TLI->has(LibFunc_memset) || EnableMemCpyOptWithoutLibcalls))
return false;
auto *V = SI->getOperand(0);
if (Value *ByteVal = isBytewiseValue(V, DL)) {
if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
ByteVal)) {
BBI = I->getIterator(); return true;
}
auto *T = V->getType();
if (T->isAggregateType()) {
uint64_t Size = DL.getTypeStoreSize(T);
IRBuilder<> Builder(SI);
auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, Size,
SI->getAlign());
LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
auto *StoreDef = cast<MemoryDef>(MSSA->getMemoryAccess(SI));
auto *NewAccess = MSSAU->createMemoryAccessBefore(
M, StoreDef->getDefiningAccess(), StoreDef);
MSSAU->insertDef(cast<MemoryDef>(NewAccess), false);
eraseInstruction(SI);
NumMemSetInfer++;
BBI = M->getIterator();
return true;
}
}
return false;
}
bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
MSI->getValue())) {
BBI = I->getIterator(); return true;
}
return false;
}
bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpyLoad,
Instruction *cpyStore, Value *cpyDest,
Value *cpySrc, TypeSize cpySize,
Align cpyAlign,
std::function<CallInst *()> GetC) {
if (cpySize.isScalable())
return false;
auto *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
if (!srcAlloca)
return false;
ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
if (!srcArraySize)
return false;
const DataLayout &DL = cpyLoad->getModule()->getDataLayout();
uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
srcArraySize->getZExtValue();
if (cpySize < srcSize)
return false;
CallInst *C = GetC();
if (!C)
return false;
if (Function *F = C->getCalledFunction())
if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
return false;
if (C->getParent() != cpyStore->getParent()) {
LLVM_DEBUG(dbgs() << "Call Slot: block local restriction\n");
return false;
}
MemoryLocation DestLoc = isa<StoreInst>(cpyStore) ?
MemoryLocation::get(cpyStore) :
MemoryLocation::getForDest(cast<MemCpyInst>(cpyStore));
if (accessedBetween(*AA, DestLoc, MSSA->getMemoryAccess(C),
MSSA->getMemoryAccess(cpyStore))) {
LLVM_DEBUG(dbgs() << "Call Slot: Dest pointer modified after call\n");
return false;
}
if (!isDereferenceableAndAlignedPointer(cpyDest, Align(1), APInt(64, cpySize),
DL, C, DT)) {
LLVM_DEBUG(dbgs() << "Call Slot: Dest pointer not dereferenceable\n");
return false;
}
if (mayBeVisibleThroughUnwinding(cpyDest, C, cpyStore)) {
LLVM_DEBUG(dbgs() << "Call Slot: Dest may be visible through unwinding");
return false;
}
Align srcAlign = srcAlloca->getAlign();
bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
return false;
SmallVector<User *, 8> srcUseList(srcAlloca->users());
while (!srcUseList.empty()) {
User *U = srcUseList.pop_back_val();
if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
append_range(srcUseList, U->users());
continue;
}
if (const auto *G = dyn_cast<GetElementPtrInst>(U)) {
if (!G->hasAllZeroIndices())
return false;
append_range(srcUseList, U->users());
continue;
}
if (const auto *IT = dyn_cast<IntrinsicInst>(U))
if (IT->isLifetimeStartOrEnd())
continue;
if (U != C && U != cpyLoad)
return false;
}
bool SrcIsCaptured = any_of(C->args(), [&](Use &U) {
return U->stripPointerCasts() == cpySrc &&
!C->doesNotCapture(C->getArgOperandNo(&U));
});
if (SrcIsCaptured) {
Value *DestObj = getUnderlyingObject(cpyDest);
if (!isIdentifiedFunctionLocal(DestObj) ||
PointerMayBeCapturedBefore(DestObj, true,
true, C, DT,
true))
return false;
MemoryLocation SrcLoc =
MemoryLocation(srcAlloca, LocationSize::precise(srcSize));
for (Instruction &I :
make_range(++C->getIterator(), C->getParent()->end())) {
if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
if (II->getIntrinsicID() == Intrinsic::lifetime_end &&
II->getArgOperand(1)->stripPointerCasts() == srcAlloca &&
cast<ConstantInt>(II->getArgOperand(0))->uge(srcSize))
break;
}
if (isa<ReturnInst>(&I))
break;
if (&I == cpyLoad)
continue;
if (isModOrRefSet(AA->getModRefInfo(&I, SrcLoc)) || I.isTerminator())
return false;
}
}
if (!DT->dominates(cpyDest, C)) {
auto *GEP = dyn_cast<GetElementPtrInst>(cpyDest);
if (GEP && GEP->hasAllConstantIndices() &&
DT->dominates(GEP->getPointerOperand(), C))
GEP->moveBefore(C);
else
return false;
}
ModRefInfo MR = AA->getModRefInfo(C, cpyDest, LocationSize::precise(srcSize));
if (isModOrRefSet(MR))
MR = AA->callCapturesBefore(C, cpyDest, LocationSize::precise(srcSize), DT);
if (isModOrRefSet(MR))
return false;
if (cpySrc->getType()->getPointerAddressSpace() !=
cpyDest->getType()->getPointerAddressSpace())
return false;
for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc &&
cpySrc->getType()->getPointerAddressSpace() !=
C->getArgOperand(ArgI)->getType()->getPointerAddressSpace())
return false;
bool changedArgument = false;
for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc) {
Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
: CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
cpyDest->getName(), C);
changedArgument = true;
if (C->getArgOperand(ArgI)->getType() == Dest->getType())
C->setArgOperand(ArgI, Dest);
else
C->setArgOperand(ArgI, CastInst::CreatePointerCast(
Dest, C->getArgOperand(ArgI)->getType(),
Dest->getName(), C));
}
if (!changedArgument)
return false;
if (!isDestSufficientlyAligned) {
assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
}
unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
LLVMContext::MD_noalias,
LLVMContext::MD_invariant_group,
LLVMContext::MD_access_group};
combineMetadata(C, cpyLoad, KnownIDs, true);
if (cpyLoad != cpyStore)
combineMetadata(C, cpyStore, KnownIDs, true);
++NumCallSlot;
return true;
}
bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
MemCpyInst *MDep) {
if (M->getSource() != MDep->getDest() || MDep->isVolatile())
return false;
if (M->getSource() == MDep->getSource())
return false;
if (MDep->getLength() != M->getLength()) {
auto *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
auto *MLen = dyn_cast<ConstantInt>(M->getLength());
if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
return false;
}
if (writtenBetween(MSSA, *AA, MemoryLocation::getForSource(MDep),
MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(M)))
return false;
bool UseMemMove = false;
if (isModSet(AA->getModRefInfo(M, MemoryLocation::getForSource(MDep))))
UseMemMove = true;
LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
<< *MDep << '\n' << *M << '\n');
IRBuilder<> Builder(M);
Instruction *NewM;
if (UseMemMove)
NewM = Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(),
MDep->getRawSource(), MDep->getSourceAlign(),
M->getLength(), M->isVolatile());
else if (isa<MemCpyInlineInst>(M)) {
NewM = Builder.CreateMemCpyInline(
M->getRawDest(), M->getDestAlign(), MDep->getRawSource(),
MDep->getSourceAlign(), M->getLength(), M->isVolatile());
} else
NewM = Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(),
MDep->getRawSource(), MDep->getSourceAlign(),
M->getLength(), M->isVolatile());
assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M)));
auto *LastDef = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
MSSAU->insertDef(cast<MemoryDef>(NewAccess), true);
eraseInstruction(M);
++NumMemCpyInstr;
return true;
}
bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
MemSetInst *MemSet) {
if (!AA->isMustAlias(MemSet->getDest(), MemCpy->getDest()))
return false;
if (isModSet(AA->getModRefInfo(MemCpy, MemoryLocation::getForSource(MemCpy))))
return false;
if (accessedBetween(*AA, MemoryLocation::getForDest(MemSet),
MSSA->getMemoryAccess(MemSet),
MSSA->getMemoryAccess(MemCpy)))
return false;
Value *Dest = MemCpy->getRawDest();
Value *DestSize = MemSet->getLength();
Value *SrcSize = MemCpy->getLength();
if (mayBeVisibleThroughUnwinding(Dest, MemSet, MemCpy))
return false;
if (DestSize == SrcSize) {
eraseInstruction(MemSet);
return true;
}
Align Alignment = Align(1);
const Align DestAlign = std::max(MemSet->getDestAlign().valueOrOne(),
MemCpy->getDestAlign().valueOrOne());
if (DestAlign > 1)
if (auto *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
Alignment = commonAlignment(DestAlign, SrcSizeC->getZExtValue());
IRBuilder<> Builder(MemCpy);
if (DestSize->getType() != SrcSize->getType()) {
if (DestSize->getType()->getIntegerBitWidth() >
SrcSize->getType()->getIntegerBitWidth())
SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
else
DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
}
Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
Value *MemsetLen = Builder.CreateSelect(
Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
unsigned DestAS = Dest->getType()->getPointerAddressSpace();
Instruction *NewMemSet = Builder.CreateMemSet(
Builder.CreateGEP(
Builder.getInt8Ty(),
Builder.CreatePointerCast(Dest, Builder.getInt8PtrTy(DestAS)),
SrcSize),
MemSet->getOperand(1), MemsetLen, Alignment);
assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) &&
"MemCpy must be a MemoryDef");
auto *LastDef =
cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
auto *NewAccess = MSSAU->createMemoryAccessBefore(
NewMemSet, LastDef->getDefiningAccess(), LastDef);
MSSAU->insertDef(cast<MemoryDef>(NewAccess), true);
eraseInstruction(MemSet);
return true;
}
static bool hasUndefContents(MemorySSA *MSSA, AliasAnalysis *AA, Value *V,
MemoryDef *Def, Value *Size) {
if (MSSA->isLiveOnEntryDef(Def))
return isa<AllocaInst>(getUnderlyingObject(V));
if (auto *II = dyn_cast_or_null<IntrinsicInst>(Def->getMemoryInst())) {
if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
auto *LTSize = cast<ConstantInt>(II->getArgOperand(0));
if (auto *CSize = dyn_cast<ConstantInt>(Size)) {
if (AA->isMustAlias(V, II->getArgOperand(1)) &&
LTSize->getZExtValue() >= CSize->getZExtValue())
return true;
}
if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(V))) {
if (getUnderlyingObject(II->getArgOperand(1)) == Alloca) {
const DataLayout &DL = Alloca->getModule()->getDataLayout();
if (Optional<TypeSize> AllocaSize =
Alloca->getAllocationSizeInBits(DL))
if (*AllocaSize == LTSize->getValue() * 8)
return true;
}
}
}
}
return false;
}
bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
MemSetInst *MemSet) {
if (!AA->isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
return false;
Value *MemSetSize = MemSet->getLength();
Value *CopySize = MemCpy->getLength();
if (MemSetSize != CopySize) {
auto *CMemSetSize = dyn_cast<ConstantInt>(MemSetSize);
if (!CMemSetSize)
return false;
auto *CCopySize = dyn_cast<ConstantInt>(CopySize);
if (!CCopySize)
return false;
if (CCopySize->getZExtValue() > CMemSetSize->getZExtValue()) {
MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy);
bool CanReduceSize = false;
MemoryUseOrDef *MemSetAccess = MSSA->getMemoryAccess(MemSet);
MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
MemSetAccess->getDefiningAccess(), MemCpyLoc);
if (auto *MD = dyn_cast<MemoryDef>(Clobber))
if (hasUndefContents(MSSA, AA, MemCpy->getSource(), MD, CopySize))
CanReduceSize = true;
if (!CanReduceSize)
return false;
CopySize = MemSetSize;
}
}
IRBuilder<> Builder(MemCpy);
Instruction *NewM =
Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
CopySize, MaybeAlign(MemCpy->getDestAlignment()));
auto *LastDef =
cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
MSSAU->insertDef(cast<MemoryDef>(NewAccess), true);
return true;
}
bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) {
if (M->isVolatile()) return false;
if (M->getSource() == M->getDest()) {
++BBI;
eraseInstruction(M);
return true;
}
if (auto *GV = dyn_cast<GlobalVariable>(M->getSource()))
if (GV->isConstant() && GV->hasDefinitiveInitializer())
if (Value *ByteVal = isBytewiseValue(GV->getInitializer(),
M->getModule()->getDataLayout())) {
IRBuilder<> Builder(M);
Instruction *NewM =
Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
MaybeAlign(M->getDestAlignment()), false);
auto *LastDef =
cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
auto *NewAccess =
MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
MSSAU->insertDef(cast<MemoryDef>(NewAccess), true);
eraseInstruction(M);
++NumCpyToSet;
return true;
}
MemoryUseOrDef *MA = MSSA->getMemoryAccess(M);
MemoryAccess *AnyClobber = MA->getDefiningAccess();
MemoryLocation DestLoc = MemoryLocation::getForDest(M);
const MemoryAccess *DestClobber =
MSSA->getWalker()->getClobberingMemoryAccess(AnyClobber, DestLoc);
if (auto *MD = dyn_cast<MemoryDef>(DestClobber))
if (auto *MDep = dyn_cast_or_null<MemSetInst>(MD->getMemoryInst()))
if (DestClobber->getBlock() == M->getParent())
if (processMemSetMemCpyDependence(M, MDep))
return true;
MemoryAccess *SrcClobber = MSSA->getWalker()->getClobberingMemoryAccess(
AnyClobber, MemoryLocation::getForSource(M));
if (auto *MD = dyn_cast<MemoryDef>(SrcClobber)) {
if (Instruction *MI = MD->getMemoryInst()) {
if (auto *CopySize = dyn_cast<ConstantInt>(M->getLength())) {
if (auto *C = dyn_cast<CallInst>(MI)) {
Align Alignment = std::min(M->getDestAlign().valueOrOne(),
M->getSourceAlign().valueOrOne());
if (performCallSlotOptzn(
M, M, M->getDest(), M->getSource(),
TypeSize::getFixed(CopySize->getZExtValue()), Alignment,
[C]() -> CallInst * { return C; })) {
LLVM_DEBUG(dbgs() << "Performed call slot optimization:\n"
<< " call: " << *C << "\n"
<< " memcpy: " << *M << "\n");
eraseInstruction(M);
++NumMemCpyInstr;
return true;
}
}
}
if (auto *MDep = dyn_cast<MemCpyInst>(MI))
return processMemCpyMemCpyDependence(M, MDep);
if (auto *MDep = dyn_cast<MemSetInst>(MI)) {
if (performMemCpyToMemSetOptzn(M, MDep)) {
LLVM_DEBUG(dbgs() << "Converted memcpy to memset\n");
eraseInstruction(M);
++NumCpyToSet;
return true;
}
}
}
if (hasUndefContents(MSSA, AA, M->getSource(), MD, M->getLength())) {
LLVM_DEBUG(dbgs() << "Removed memcpy from undef\n");
eraseInstruction(M);
++NumMemCpyInstr;
return true;
}
}
return false;
}
bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
if (isModSet(AA->getModRefInfo(M, MemoryLocation::getForSource(M))))
return false;
LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
<< "\n");
Type *ArgTys[3] = { M->getRawDest()->getType(),
M->getRawSource()->getType(),
M->getLength()->getType() };
M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
Intrinsic::memcpy, ArgTys));
++NumMoveToCpy;
return true;
}
bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) {
const DataLayout &DL = CB.getCaller()->getParent()->getDataLayout();
Value *ByValArg = CB.getArgOperand(ArgNo);
Type *ByValTy = CB.getParamByValType(ArgNo);
TypeSize ByValSize = DL.getTypeAllocSize(ByValTy);
MemoryLocation Loc(ByValArg, LocationSize::precise(ByValSize));
MemoryUseOrDef *CallAccess = MSSA->getMemoryAccess(&CB);
if (!CallAccess)
return false;
MemCpyInst *MDep = nullptr;
MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
CallAccess->getDefiningAccess(), Loc);
if (auto *MD = dyn_cast<MemoryDef>(Clobber))
MDep = dyn_cast_or_null<MemCpyInst>(MD->getMemoryInst());
if (!MDep || MDep->isVolatile() ||
ByValArg->stripPointerCasts() != MDep->getDest())
return false;
auto *C1 = dyn_cast<ConstantInt>(MDep->getLength());
if (!C1 || !TypeSize::isKnownGE(
TypeSize::getFixed(C1->getValue().getZExtValue()), ByValSize))
return false;
MaybeAlign ByValAlign = CB.getParamAlign(ArgNo);
if (!ByValAlign) return false;
MaybeAlign MemDepAlign = MDep->getSourceAlign();
if ((!MemDepAlign || *MemDepAlign < *ByValAlign) &&
getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, &CB, AC,
DT) < *ByValAlign)
return false;
if (MDep->getSource()->getType()->getPointerAddressSpace() !=
ByValArg->getType()->getPointerAddressSpace())
return false;
if (writtenBetween(MSSA, *AA, MemoryLocation::getForSource(MDep),
MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(&CB)))
return false;
Value *TmpCast = MDep->getSource();
if (MDep->getSource()->getType() != ByValArg->getType()) {
BitCastInst *TmpBitCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
"tmpcast", &CB);
TmpBitCast->setDebugLoc(MDep->getDebugLoc());
TmpCast = TmpBitCast;
}
LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
<< " " << *MDep << "\n"
<< " " << CB << "\n");
CB.setArgOperand(ArgNo, TmpCast);
++NumMemCpyInstr;
return true;
}
bool MemCpyOptPass::iterateOnFunction(Function &F) {
bool MadeChange = false;
for (BasicBlock &BB : F) {
if (!DT->isReachableFromEntry(&BB))
continue;
for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Instruction *I = &*BI++;
bool RepeatInstruction = false;
if (auto *SI = dyn_cast<StoreInst>(I))
MadeChange |= processStore(SI, BI);
else if (auto *M = dyn_cast<MemSetInst>(I))
RepeatInstruction = processMemSet(M, BI);
else if (auto *M = dyn_cast<MemCpyInst>(I))
RepeatInstruction = processMemCpy(M, BI);
else if (auto *M = dyn_cast<MemMoveInst>(I))
RepeatInstruction = processMemMove(M);
else if (auto *CB = dyn_cast<CallBase>(I)) {
for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
if (CB->isByValArgument(i))
MadeChange |= processByValArgument(*CB, i);
}
if (RepeatInstruction) {
if (BI != BB.begin())
--BI;
MadeChange = true;
}
}
}
return MadeChange;
}
PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
auto *AA = &AM.getResult<AAManager>(F);
auto *AC = &AM.getResult<AssumptionAnalysis>(F);
auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
auto *MSSA = &AM.getResult<MemorySSAAnalysis>(F);
bool MadeChange = runImpl(F, &TLI, AA, AC, DT, &MSSA->getMSSA());
if (!MadeChange)
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
PA.preserve<MemorySSAAnalysis>();
return PA;
}
bool MemCpyOptPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
AliasAnalysis *AA_, AssumptionCache *AC_,
DominatorTree *DT_, MemorySSA *MSSA_) {
bool MadeChange = false;
TLI = TLI_;
AA = AA_;
AC = AC_;
DT = DT_;
MSSA = MSSA_;
MemorySSAUpdater MSSAU_(MSSA_);
MSSAU = &MSSAU_;
while (true) {
if (!iterateOnFunction(F))
break;
MadeChange = true;
}
if (VerifyMemorySSA)
MSSA_->verifyMemorySSA();
return MadeChange;
}
bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
if (skipFunction(F))
return false;
auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
return Impl.runImpl(F, TLI, AA, AC, DT, MSSA);
}