1ee8648bdSDimitry Andric //===- LoopVersioning.cpp - Utility to version a loop ---------------------===//
2ee8648bdSDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ee8648bdSDimitry Andric //
7ee8648bdSDimitry Andric //===----------------------------------------------------------------------===//
8ee8648bdSDimitry Andric //
9ee8648bdSDimitry Andric // This file defines a utility class to perform loop versioning. The versioned
10ee8648bdSDimitry Andric // loop speculates that otherwise may-aliasing memory accesses don't overlap and
11ee8648bdSDimitry Andric // emits checks to prove this.
12ee8648bdSDimitry Andric //
13ee8648bdSDimitry Andric //===----------------------------------------------------------------------===//
14ee8648bdSDimitry Andric
15dd58ef01SDimitry Andric #include "llvm/Transforms/Utils/LoopVersioning.h"
16cfca06d7SDimitry Andric #include "llvm/ADT/ArrayRef.h"
17c0981da4SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
186f8fc217SDimitry Andric #include "llvm/Analysis/InstSimplifyFolder.h"
19ee8648bdSDimitry Andric #include "llvm/Analysis/LoopAccessAnalysis.h"
20ee8648bdSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
21b60736ecSDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
22b60736ecSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
23ee8648bdSDimitry Andric #include "llvm/IR/Dominators.h"
2401095a5dSDimitry Andric #include "llvm/IR/MDBuilder.h"
25b60736ecSDimitry Andric #include "llvm/IR/PassManager.h"
26706b4fc4SDimitry Andric #include "llvm/Support/CommandLine.h"
27ee8648bdSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28ee8648bdSDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
29cfca06d7SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
30ee8648bdSDimitry Andric
31ee8648bdSDimitry Andric using namespace llvm;
32ee8648bdSDimitry Andric
337fa27ce4SDimitry Andric #define DEBUG_TYPE "loop-versioning"
347fa27ce4SDimitry Andric
3501095a5dSDimitry Andric static cl::opt<bool>
3601095a5dSDimitry Andric AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(true),
3701095a5dSDimitry Andric cl::Hidden,
3801095a5dSDimitry Andric cl::desc("Add no-alias annotation for instructions that "
3901095a5dSDimitry Andric "are disambiguated by memchecks"));
4001095a5dSDimitry Andric
LoopVersioning(const LoopAccessInfo & LAI,ArrayRef<RuntimePointerCheck> Checks,Loop * L,LoopInfo * LI,DominatorTree * DT,ScalarEvolution * SE)41b60736ecSDimitry Andric LoopVersioning::LoopVersioning(const LoopAccessInfo &LAI,
42b60736ecSDimitry Andric ArrayRef<RuntimePointerCheck> Checks, Loop *L,
43b60736ecSDimitry Andric LoopInfo *LI, DominatorTree *DT,
44b60736ecSDimitry Andric ScalarEvolution *SE)
45145449b1SDimitry Andric : VersionedLoop(L), AliasChecks(Checks.begin(), Checks.end()),
46145449b1SDimitry Andric Preds(LAI.getPSE().getPredicate()), LAI(LAI), LI(LI), DT(DT),
47dd58ef01SDimitry Andric SE(SE) {
48dd58ef01SDimitry Andric }
49dd58ef01SDimitry Andric
versionLoop(const SmallVectorImpl<Instruction * > & DefsUsedOutside)50dd58ef01SDimitry Andric void LoopVersioning::versionLoop(
51dd58ef01SDimitry Andric const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
52344a3780SDimitry Andric assert(VersionedLoop->getUniqueExitBlock() && "No single exit block");
53b60736ecSDimitry Andric assert(VersionedLoop->isLoopSimplifyForm() &&
54b60736ecSDimitry Andric "Loop is not in loop-simplify form");
55b60736ecSDimitry Andric
56c0981da4SDimitry Andric Value *MemRuntimeCheck;
57dd58ef01SDimitry Andric Value *SCEVRuntimeCheck;
58dd58ef01SDimitry Andric Value *RuntimeCheck = nullptr;
59dd58ef01SDimitry Andric
60ee8648bdSDimitry Andric // Add the memcheck in the original preheader (this is empty initially).
61dd58ef01SDimitry Andric BasicBlock *RuntimeCheckBB = VersionedLoop->getLoopPreheader();
62cfca06d7SDimitry Andric const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
63344a3780SDimitry Andric
64344a3780SDimitry Andric SCEVExpander Exp2(*RtPtrChecking.getSE(),
65ac9a064cSDimitry Andric VersionedLoop->getHeader()->getDataLayout(),
66344a3780SDimitry Andric "induction");
67c0981da4SDimitry Andric MemRuntimeCheck = addRuntimeChecks(RuntimeCheckBB->getTerminator(),
68c0981da4SDimitry Andric VersionedLoop, AliasChecks, Exp2);
69ee8648bdSDimitry Andric
70ac9a064cSDimitry Andric SCEVExpander Exp(*SE, RuntimeCheckBB->getDataLayout(),
71dd58ef01SDimitry Andric "scev.check");
72dd58ef01SDimitry Andric SCEVRuntimeCheck =
73b60736ecSDimitry Andric Exp.expandCodeForPredicate(&Preds, RuntimeCheckBB->getTerminator());
74dd58ef01SDimitry Andric
756f8fc217SDimitry Andric IRBuilder<InstSimplifyFolder> Builder(
766f8fc217SDimitry Andric RuntimeCheckBB->getContext(),
77ac9a064cSDimitry Andric InstSimplifyFolder(RuntimeCheckBB->getDataLayout()));
78dd58ef01SDimitry Andric if (MemRuntimeCheck && SCEVRuntimeCheck) {
796f8fc217SDimitry Andric Builder.SetInsertPoint(RuntimeCheckBB->getTerminator());
806f8fc217SDimitry Andric RuntimeCheck =
816f8fc217SDimitry Andric Builder.CreateOr(MemRuntimeCheck, SCEVRuntimeCheck, "lver.safe");
82dd58ef01SDimitry Andric } else
83dd58ef01SDimitry Andric RuntimeCheck = MemRuntimeCheck ? MemRuntimeCheck : SCEVRuntimeCheck;
84dd58ef01SDimitry Andric
85dd58ef01SDimitry Andric assert(RuntimeCheck && "called even though we don't need "
86dd58ef01SDimitry Andric "any runtime checks");
87dd58ef01SDimitry Andric
88ee8648bdSDimitry Andric // Rename the block to make the IR more readable.
89dd58ef01SDimitry Andric RuntimeCheckBB->setName(VersionedLoop->getHeader()->getName() +
90dd58ef01SDimitry Andric ".lver.check");
91ee8648bdSDimitry Andric
92ee8648bdSDimitry Andric // Create empty preheader for the loop (and after cloning for the
93ee8648bdSDimitry Andric // non-versioned loop).
94dd58ef01SDimitry Andric BasicBlock *PH =
951d5ae102SDimitry Andric SplitBlock(RuntimeCheckBB, RuntimeCheckBB->getTerminator(), DT, LI,
961d5ae102SDimitry Andric nullptr, VersionedLoop->getHeader()->getName() + ".ph");
97ee8648bdSDimitry Andric
98ee8648bdSDimitry Andric // Clone the loop including the preheader.
99ee8648bdSDimitry Andric //
100ee8648bdSDimitry Andric // FIXME: This does not currently preserve SimplifyLoop because the exit
101ee8648bdSDimitry Andric // block is a join between the two loops.
102ee8648bdSDimitry Andric SmallVector<BasicBlock *, 8> NonVersionedLoopBlocks;
103ee8648bdSDimitry Andric NonVersionedLoop =
104dd58ef01SDimitry Andric cloneLoopWithPreheader(PH, RuntimeCheckBB, VersionedLoop, VMap,
105dd58ef01SDimitry Andric ".lver.orig", LI, DT, NonVersionedLoopBlocks);
106ee8648bdSDimitry Andric remapInstructionsInBlocks(NonVersionedLoopBlocks, VMap);
107ee8648bdSDimitry Andric
108ee8648bdSDimitry Andric // Insert the conditional branch based on the result of the memchecks.
109dd58ef01SDimitry Andric Instruction *OrigTerm = RuntimeCheckBB->getTerminator();
1106f8fc217SDimitry Andric Builder.SetInsertPoint(OrigTerm);
1116f8fc217SDimitry Andric Builder.CreateCondBr(RuntimeCheck, NonVersionedLoop->getLoopPreheader(),
1126f8fc217SDimitry Andric VersionedLoop->getLoopPreheader());
113ee8648bdSDimitry Andric OrigTerm->eraseFromParent();
114ee8648bdSDimitry Andric
115ee8648bdSDimitry Andric // The loops merge in the original exit block. This is now dominated by the
116ee8648bdSDimitry Andric // memchecking block.
117dd58ef01SDimitry Andric DT->changeImmediateDominator(VersionedLoop->getExitBlock(), RuntimeCheckBB);
118dd58ef01SDimitry Andric
119dd58ef01SDimitry Andric // Adds the necessary PHI nodes for the versioned loops based on the
120dd58ef01SDimitry Andric // loop-defined values used outside of the loop.
121dd58ef01SDimitry Andric addPHINodes(DefsUsedOutside);
122b60736ecSDimitry Andric formDedicatedExitBlocks(NonVersionedLoop, DT, LI, nullptr, true);
123b60736ecSDimitry Andric formDedicatedExitBlocks(VersionedLoop, DT, LI, nullptr, true);
124b60736ecSDimitry Andric assert(NonVersionedLoop->isLoopSimplifyForm() &&
125b60736ecSDimitry Andric VersionedLoop->isLoopSimplifyForm() &&
126b60736ecSDimitry Andric "The versioned loops should be in simplify form.");
127ee8648bdSDimitry Andric }
128ee8648bdSDimitry Andric
addPHINodes(const SmallVectorImpl<Instruction * > & DefsUsedOutside)129ee8648bdSDimitry Andric void LoopVersioning::addPHINodes(
130ee8648bdSDimitry Andric const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
131ee8648bdSDimitry Andric BasicBlock *PHIBlock = VersionedLoop->getExitBlock();
132ee8648bdSDimitry Andric assert(PHIBlock && "No single successor to loop exit block");
133ee8648bdSDimitry Andric PHINode *PN;
134ee8648bdSDimitry Andric
13501095a5dSDimitry Andric // First add a single-operand PHI for each DefsUsedOutside if one does not
13601095a5dSDimitry Andric // exists yet.
13701095a5dSDimitry Andric for (auto *Inst : DefsUsedOutside) {
13801095a5dSDimitry Andric // See if we have a single-operand PHI with the value defined by the
139ee8648bdSDimitry Andric // original loop.
140ee8648bdSDimitry Andric for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
141e3b55780SDimitry Andric if (PN->getIncomingValue(0) == Inst) {
142e3b55780SDimitry Andric SE->forgetValue(PN);
143ee8648bdSDimitry Andric break;
144ee8648bdSDimitry Andric }
145e3b55780SDimitry Andric }
146ee8648bdSDimitry Andric // If not create it.
147ee8648bdSDimitry Andric if (!PN) {
148b1c73532SDimitry Andric PN = PHINode::Create(Inst->getType(), 2, Inst->getName() + ".lver");
149b1c73532SDimitry Andric PN->insertBefore(PHIBlock->begin());
150eb11fae6SDimitry Andric SmallVector<User*, 8> UsersToUpdate;
151eb11fae6SDimitry Andric for (User *U : Inst->users())
152eb11fae6SDimitry Andric if (!VersionedLoop->contains(cast<Instruction>(U)->getParent()))
153eb11fae6SDimitry Andric UsersToUpdate.push_back(U);
154eb11fae6SDimitry Andric for (User *U : UsersToUpdate)
155eb11fae6SDimitry Andric U->replaceUsesOfWith(Inst, PN);
156ee8648bdSDimitry Andric PN->addIncoming(Inst, VersionedLoop->getExitingBlock());
157ee8648bdSDimitry Andric }
15801095a5dSDimitry Andric }
15901095a5dSDimitry Andric
16001095a5dSDimitry Andric // Then for each PHI add the operand for the edge from the cloned loop.
16101095a5dSDimitry Andric for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
16201095a5dSDimitry Andric assert(PN->getNumOperands() == 1 &&
16301095a5dSDimitry Andric "Exit block should only have on predecessor");
16401095a5dSDimitry Andric
16501095a5dSDimitry Andric // If the definition was cloned used that otherwise use the same value.
16601095a5dSDimitry Andric Value *ClonedValue = PN->getIncomingValue(0);
16701095a5dSDimitry Andric auto Mapped = VMap.find(ClonedValue);
16801095a5dSDimitry Andric if (Mapped != VMap.end())
16901095a5dSDimitry Andric ClonedValue = Mapped->second;
17001095a5dSDimitry Andric
17101095a5dSDimitry Andric PN->addIncoming(ClonedValue, NonVersionedLoop->getExitingBlock());
17201095a5dSDimitry Andric }
17301095a5dSDimitry Andric }
17401095a5dSDimitry Andric
prepareNoAliasMetadata()17501095a5dSDimitry Andric void LoopVersioning::prepareNoAliasMetadata() {
17601095a5dSDimitry Andric // We need to turn the no-alias relation between pointer checking groups into
17701095a5dSDimitry Andric // no-aliasing annotations between instructions.
17801095a5dSDimitry Andric //
17901095a5dSDimitry Andric // We accomplish this by mapping each pointer checking group (a set of
18001095a5dSDimitry Andric // pointers memchecked together) to an alias scope and then also mapping each
18101095a5dSDimitry Andric // group to the list of scopes it can't alias.
18201095a5dSDimitry Andric
18301095a5dSDimitry Andric const RuntimePointerChecking *RtPtrChecking = LAI.getRuntimePointerChecking();
18401095a5dSDimitry Andric LLVMContext &Context = VersionedLoop->getHeader()->getContext();
18501095a5dSDimitry Andric
18601095a5dSDimitry Andric // First allocate an aliasing scope for each pointer checking group.
18701095a5dSDimitry Andric //
18801095a5dSDimitry Andric // While traversing through the checking groups in the loop, also create a
18901095a5dSDimitry Andric // reverse map from pointers to the pointer checking group they were assigned
19001095a5dSDimitry Andric // to.
19101095a5dSDimitry Andric MDBuilder MDB(Context);
19201095a5dSDimitry Andric MDNode *Domain = MDB.createAnonymousAliasScopeDomain("LVerDomain");
19301095a5dSDimitry Andric
19401095a5dSDimitry Andric for (const auto &Group : RtPtrChecking->CheckingGroups) {
19501095a5dSDimitry Andric GroupToScope[&Group] = MDB.createAnonymousAliasScope(Domain);
19601095a5dSDimitry Andric
19701095a5dSDimitry Andric for (unsigned PtrIdx : Group.Members)
19801095a5dSDimitry Andric PtrToGroup[RtPtrChecking->getPointerInfo(PtrIdx).PointerValue] = &Group;
19901095a5dSDimitry Andric }
20001095a5dSDimitry Andric
20101095a5dSDimitry Andric // Go through the checks and for each pointer group, collect the scopes for
20201095a5dSDimitry Andric // each non-aliasing pointer group.
203cfca06d7SDimitry Andric DenseMap<const RuntimeCheckingPtrGroup *, SmallVector<Metadata *, 4>>
20401095a5dSDimitry Andric GroupToNonAliasingScopes;
20501095a5dSDimitry Andric
20601095a5dSDimitry Andric for (const auto &Check : AliasChecks)
20701095a5dSDimitry Andric GroupToNonAliasingScopes[Check.first].push_back(GroupToScope[Check.second]);
20801095a5dSDimitry Andric
20901095a5dSDimitry Andric // Finally, transform the above to actually map to scope list which is what
21001095a5dSDimitry Andric // the metadata uses.
21101095a5dSDimitry Andric
2127fa27ce4SDimitry Andric for (const auto &Pair : GroupToNonAliasingScopes)
21301095a5dSDimitry Andric GroupToNonAliasingScopeList[Pair.first] = MDNode::get(Context, Pair.second);
21401095a5dSDimitry Andric }
21501095a5dSDimitry Andric
annotateLoopWithNoAlias()21601095a5dSDimitry Andric void LoopVersioning::annotateLoopWithNoAlias() {
21701095a5dSDimitry Andric if (!AnnotateNoAlias)
21801095a5dSDimitry Andric return;
21901095a5dSDimitry Andric
22001095a5dSDimitry Andric // First prepare the maps.
22101095a5dSDimitry Andric prepareNoAliasMetadata();
22201095a5dSDimitry Andric
22301095a5dSDimitry Andric // Add the scope and no-alias metadata to the instructions.
22401095a5dSDimitry Andric for (Instruction *I : LAI.getDepChecker().getMemoryInstructions()) {
22501095a5dSDimitry Andric annotateInstWithNoAlias(I);
22601095a5dSDimitry Andric }
22701095a5dSDimitry Andric }
22801095a5dSDimitry Andric
annotateInstWithNoAlias(Instruction * VersionedInst,const Instruction * OrigInst)22901095a5dSDimitry Andric void LoopVersioning::annotateInstWithNoAlias(Instruction *VersionedInst,
23001095a5dSDimitry Andric const Instruction *OrigInst) {
23101095a5dSDimitry Andric if (!AnnotateNoAlias)
23201095a5dSDimitry Andric return;
23301095a5dSDimitry Andric
23401095a5dSDimitry Andric LLVMContext &Context = VersionedLoop->getHeader()->getContext();
23501095a5dSDimitry Andric const Value *Ptr = isa<LoadInst>(OrigInst)
23601095a5dSDimitry Andric ? cast<LoadInst>(OrigInst)->getPointerOperand()
23701095a5dSDimitry Andric : cast<StoreInst>(OrigInst)->getPointerOperand();
23801095a5dSDimitry Andric
23901095a5dSDimitry Andric // Find the group for the pointer and then add the scope metadata.
24001095a5dSDimitry Andric auto Group = PtrToGroup.find(Ptr);
24101095a5dSDimitry Andric if (Group != PtrToGroup.end()) {
24201095a5dSDimitry Andric VersionedInst->setMetadata(
24301095a5dSDimitry Andric LLVMContext::MD_alias_scope,
24401095a5dSDimitry Andric MDNode::concatenate(
24501095a5dSDimitry Andric VersionedInst->getMetadata(LLVMContext::MD_alias_scope),
24601095a5dSDimitry Andric MDNode::get(Context, GroupToScope[Group->second])));
24701095a5dSDimitry Andric
24801095a5dSDimitry Andric // Add the no-alias metadata.
24901095a5dSDimitry Andric auto NonAliasingScopeList = GroupToNonAliasingScopeList.find(Group->second);
25001095a5dSDimitry Andric if (NonAliasingScopeList != GroupToNonAliasingScopeList.end())
25101095a5dSDimitry Andric VersionedInst->setMetadata(
25201095a5dSDimitry Andric LLVMContext::MD_noalias,
25301095a5dSDimitry Andric MDNode::concatenate(
25401095a5dSDimitry Andric VersionedInst->getMetadata(LLVMContext::MD_noalias),
25501095a5dSDimitry Andric NonAliasingScopeList->second));
25601095a5dSDimitry Andric }
25701095a5dSDimitry Andric }
25801095a5dSDimitry Andric
25901095a5dSDimitry Andric namespace {
runImpl(LoopInfo * LI,LoopAccessInfoManager & LAIs,DominatorTree * DT,ScalarEvolution * SE)260e3b55780SDimitry Andric bool runImpl(LoopInfo *LI, LoopAccessInfoManager &LAIs, DominatorTree *DT,
261e3b55780SDimitry Andric ScalarEvolution *SE) {
26201095a5dSDimitry Andric // Build up a worklist of inner-loops to version. This is necessary as the
26301095a5dSDimitry Andric // act of versioning a loop creates new loops and can invalidate iterators
26401095a5dSDimitry Andric // across the loops.
26501095a5dSDimitry Andric SmallVector<Loop *, 8> Worklist;
26601095a5dSDimitry Andric
26701095a5dSDimitry Andric for (Loop *TopLevelLoop : *LI)
26801095a5dSDimitry Andric for (Loop *L : depth_first(TopLevelLoop))
26901095a5dSDimitry Andric // We only handle inner-most loops.
270b60736ecSDimitry Andric if (L->isInnermost())
27101095a5dSDimitry Andric Worklist.push_back(L);
27201095a5dSDimitry Andric
27301095a5dSDimitry Andric // Now walk the identified inner loops.
27401095a5dSDimitry Andric bool Changed = false;
27501095a5dSDimitry Andric for (Loop *L : Worklist) {
276b60736ecSDimitry Andric if (!L->isLoopSimplifyForm() || !L->isRotatedForm() ||
277b60736ecSDimitry Andric !L->getExitingBlock())
278b60736ecSDimitry Andric continue;
279e3b55780SDimitry Andric const LoopAccessInfo &LAI = LAIs.getInfo(*L);
280b60736ecSDimitry Andric if (!LAI.hasConvergentOp() &&
281e6d15924SDimitry Andric (LAI.getNumRuntimePointerChecks() ||
282145449b1SDimitry Andric !LAI.getPSE().getPredicate().isAlwaysTrue())) {
283b60736ecSDimitry Andric LoopVersioning LVer(LAI, LAI.getRuntimePointerChecking()->getChecks(), L,
284b60736ecSDimitry Andric LI, DT, SE);
28501095a5dSDimitry Andric LVer.versionLoop();
28601095a5dSDimitry Andric LVer.annotateLoopWithNoAlias();
28701095a5dSDimitry Andric Changed = true;
288e3b55780SDimitry Andric LAIs.clear();
28901095a5dSDimitry Andric }
29001095a5dSDimitry Andric }
29101095a5dSDimitry Andric
29201095a5dSDimitry Andric return Changed;
29301095a5dSDimitry Andric }
294ee8648bdSDimitry Andric }
295b60736ecSDimitry Andric
run(Function & F,FunctionAnalysisManager & AM)296b60736ecSDimitry Andric PreservedAnalyses LoopVersioningPass::run(Function &F,
297b60736ecSDimitry Andric FunctionAnalysisManager &AM) {
298b60736ecSDimitry Andric auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
299b60736ecSDimitry Andric auto &LI = AM.getResult<LoopAnalysis>(F);
300e3b55780SDimitry Andric LoopAccessInfoManager &LAIs = AM.getResult<LoopAccessAnalysis>(F);
301b60736ecSDimitry Andric auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
302b60736ecSDimitry Andric
303e3b55780SDimitry Andric if (runImpl(&LI, LAIs, &DT, &SE))
304b60736ecSDimitry Andric return PreservedAnalyses::none();
305b60736ecSDimitry Andric return PreservedAnalyses::all();
306ee8648bdSDimitry Andric }
307