#include "llvm/Transforms/Utils/LoopVersioning.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/InstSimplifyFolder.h"
#include "llvm/Analysis/LoopAccessAnalysis.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/PassManager.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
using namespace llvm;
static cl::opt<bool>
AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(true),
cl::Hidden,
cl::desc("Add no-alias annotation for instructions that "
"are disambiguated by memchecks"));
LoopVersioning::LoopVersioning(const LoopAccessInfo &LAI,
ArrayRef<RuntimePointerCheck> Checks, Loop *L,
LoopInfo *LI, DominatorTree *DT,
ScalarEvolution *SE)
: VersionedLoop(L), AliasChecks(Checks.begin(), Checks.end()),
Preds(LAI.getPSE().getPredicate()), LAI(LAI), LI(LI), DT(DT),
SE(SE) {
}
void LoopVersioning::versionLoop(
const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
assert(VersionedLoop->getUniqueExitBlock() && "No single exit block");
assert(VersionedLoop->isLoopSimplifyForm() &&
"Loop is not in loop-simplify form");
Value *MemRuntimeCheck;
Value *SCEVRuntimeCheck;
Value *RuntimeCheck = nullptr;
BasicBlock *RuntimeCheckBB = VersionedLoop->getLoopPreheader();
const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
SCEVExpander Exp2(*RtPtrChecking.getSE(),
VersionedLoop->getHeader()->getModule()->getDataLayout(),
"induction");
MemRuntimeCheck = addRuntimeChecks(RuntimeCheckBB->getTerminator(),
VersionedLoop, AliasChecks, Exp2);
SCEVExpander Exp(*SE, RuntimeCheckBB->getModule()->getDataLayout(),
"scev.check");
SCEVRuntimeCheck =
Exp.expandCodeForPredicate(&Preds, RuntimeCheckBB->getTerminator());
IRBuilder<InstSimplifyFolder> Builder(
RuntimeCheckBB->getContext(),
InstSimplifyFolder(RuntimeCheckBB->getModule()->getDataLayout()));
if (MemRuntimeCheck && SCEVRuntimeCheck) {
Builder.SetInsertPoint(RuntimeCheckBB->getTerminator());
RuntimeCheck =
Builder.CreateOr(MemRuntimeCheck, SCEVRuntimeCheck, "lver.safe");
} else
RuntimeCheck = MemRuntimeCheck ? MemRuntimeCheck : SCEVRuntimeCheck;
assert(RuntimeCheck && "called even though we don't need "
"any runtime checks");
RuntimeCheckBB->setName(VersionedLoop->getHeader()->getName() +
".lver.check");
BasicBlock *PH =
SplitBlock(RuntimeCheckBB, RuntimeCheckBB->getTerminator(), DT, LI,
nullptr, VersionedLoop->getHeader()->getName() + ".ph");
SmallVector<BasicBlock *, 8> NonVersionedLoopBlocks;
NonVersionedLoop =
cloneLoopWithPreheader(PH, RuntimeCheckBB, VersionedLoop, VMap,
".lver.orig", LI, DT, NonVersionedLoopBlocks);
remapInstructionsInBlocks(NonVersionedLoopBlocks, VMap);
Instruction *OrigTerm = RuntimeCheckBB->getTerminator();
Builder.SetInsertPoint(OrigTerm);
Builder.CreateCondBr(RuntimeCheck, NonVersionedLoop->getLoopPreheader(),
VersionedLoop->getLoopPreheader());
OrigTerm->eraseFromParent();
DT->changeImmediateDominator(VersionedLoop->getExitBlock(), RuntimeCheckBB);
addPHINodes(DefsUsedOutside);
formDedicatedExitBlocks(NonVersionedLoop, DT, LI, nullptr, true);
formDedicatedExitBlocks(VersionedLoop, DT, LI, nullptr, true);
assert(NonVersionedLoop->isLoopSimplifyForm() &&
VersionedLoop->isLoopSimplifyForm() &&
"The versioned loops should be in simplify form.");
}
void LoopVersioning::addPHINodes(
const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
BasicBlock *PHIBlock = VersionedLoop->getExitBlock();
assert(PHIBlock && "No single successor to loop exit block");
PHINode *PN;
for (auto *Inst : DefsUsedOutside) {
for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
if (PN->getIncomingValue(0) == Inst) {
SE->forgetValue(PN);
break;
}
}
if (!PN) {
PN = PHINode::Create(Inst->getType(), 2, Inst->getName() + ".lver",
&PHIBlock->front());
SmallVector<User*, 8> UsersToUpdate;
for (User *U : Inst->users())
if (!VersionedLoop->contains(cast<Instruction>(U)->getParent()))
UsersToUpdate.push_back(U);
for (User *U : UsersToUpdate)
U->replaceUsesOfWith(Inst, PN);
PN->addIncoming(Inst, VersionedLoop->getExitingBlock());
}
}
for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
assert(PN->getNumOperands() == 1 &&
"Exit block should only have on predecessor");
Value *ClonedValue = PN->getIncomingValue(0);
auto Mapped = VMap.find(ClonedValue);
if (Mapped != VMap.end())
ClonedValue = Mapped->second;
PN->addIncoming(ClonedValue, NonVersionedLoop->getExitingBlock());
}
}
void LoopVersioning::prepareNoAliasMetadata() {
const RuntimePointerChecking *RtPtrChecking = LAI.getRuntimePointerChecking();
LLVMContext &Context = VersionedLoop->getHeader()->getContext();
MDBuilder MDB(Context);
MDNode *Domain = MDB.createAnonymousAliasScopeDomain("LVerDomain");
for (const auto &Group : RtPtrChecking->CheckingGroups) {
GroupToScope[&Group] = MDB.createAnonymousAliasScope(Domain);
for (unsigned PtrIdx : Group.Members)
PtrToGroup[RtPtrChecking->getPointerInfo(PtrIdx).PointerValue] = &Group;
}
DenseMap<const RuntimeCheckingPtrGroup *, SmallVector<Metadata *, 4>>
GroupToNonAliasingScopes;
for (const auto &Check : AliasChecks)
GroupToNonAliasingScopes[Check.first].push_back(GroupToScope[Check.second]);
for (auto Pair : GroupToNonAliasingScopes)
GroupToNonAliasingScopeList[Pair.first] = MDNode::get(Context, Pair.second);
}
void LoopVersioning::annotateLoopWithNoAlias() {
if (!AnnotateNoAlias)
return;
prepareNoAliasMetadata();
for (Instruction *I : LAI.getDepChecker().getMemoryInstructions()) {
annotateInstWithNoAlias(I);
}
}
void LoopVersioning::annotateInstWithNoAlias(Instruction *VersionedInst,
const Instruction *OrigInst) {
if (!AnnotateNoAlias)
return;
LLVMContext &Context = VersionedLoop->getHeader()->getContext();
const Value *Ptr = isa<LoadInst>(OrigInst)
? cast<LoadInst>(OrigInst)->getPointerOperand()
: cast<StoreInst>(OrigInst)->getPointerOperand();
auto Group = PtrToGroup.find(Ptr);
if (Group != PtrToGroup.end()) {
VersionedInst->setMetadata(
LLVMContext::MD_alias_scope,
MDNode::concatenate(
VersionedInst->getMetadata(LLVMContext::MD_alias_scope),
MDNode::get(Context, GroupToScope[Group->second])));
auto NonAliasingScopeList = GroupToNonAliasingScopeList.find(Group->second);
if (NonAliasingScopeList != GroupToNonAliasingScopeList.end())
VersionedInst->setMetadata(
LLVMContext::MD_noalias,
MDNode::concatenate(
VersionedInst->getMetadata(LLVMContext::MD_noalias),
NonAliasingScopeList->second));
}
}
namespace {
bool runImpl(LoopInfo *LI, function_ref<const LoopAccessInfo &(Loop &)> GetLAA,
DominatorTree *DT, ScalarEvolution *SE) {
SmallVector<Loop *, 8> Worklist;
for (Loop *TopLevelLoop : *LI)
for (Loop *L : depth_first(TopLevelLoop))
if (L->isInnermost())
Worklist.push_back(L);
bool Changed = false;
for (Loop *L : Worklist) {
if (!L->isLoopSimplifyForm() || !L->isRotatedForm() ||
!L->getExitingBlock())
continue;
const LoopAccessInfo &LAI = GetLAA(*L);
if (!LAI.hasConvergentOp() &&
(LAI.getNumRuntimePointerChecks() ||
!LAI.getPSE().getPredicate().isAlwaysTrue())) {
LoopVersioning LVer(LAI, LAI.getRuntimePointerChecking()->getChecks(), L,
LI, DT, SE);
LVer.versionLoop();
LVer.annotateLoopWithNoAlias();
Changed = true;
}
}
return Changed;
}
class LoopVersioningLegacyPass : public FunctionPass {
public:
LoopVersioningLegacyPass() : FunctionPass(ID) {
initializeLoopVersioningLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
auto GetLAA = [&](Loop &L) -> const LoopAccessInfo & {
return getAnalysis<LoopAccessLegacyAnalysis>().getInfo(&L);
};
auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
return runImpl(LI, GetLAA, DT, SE);
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<LoopInfoWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
AU.addRequired<LoopAccessLegacyAnalysis>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addRequired<ScalarEvolutionWrapperPass>();
}
static char ID;
};
}
#define LVER_OPTION "loop-versioning"
#define DEBUG_TYPE LVER_OPTION
char LoopVersioningLegacyPass::ID;
static const char LVer_name[] = "Loop Versioning";
INITIALIZE_PASS_BEGIN(LoopVersioningLegacyPass, LVER_OPTION, LVer_name, false,
false)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
INITIALIZE_PASS_END(LoopVersioningLegacyPass, LVER_OPTION, LVer_name, false,
false)
namespace llvm {
FunctionPass *createLoopVersioningLegacyPass() {
return new LoopVersioningLegacyPass();
}
PreservedAnalyses LoopVersioningPass::run(Function &F,
FunctionAnalysisManager &AM) {
auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
auto &LI = AM.getResult<LoopAnalysis>(F);
auto &TTI = AM.getResult<TargetIRAnalysis>(F);
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
auto &AA = AM.getResult<AAManager>(F);
auto &AC = AM.getResult<AssumptionAnalysis>(F);
auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
auto GetLAA = [&](Loop &L) -> const LoopAccessInfo & {
LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE,
TLI, TTI, nullptr, nullptr, nullptr};
return LAM.getResult<LoopAccessAnalysis>(L, AR);
};
if (runImpl(&LI, GetLAA, &DT, &SE))
return PreservedAnalyses::none();
return PreservedAnalyses::all();
}
}