Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Utils/LoopVersioning.cpp
35271 views
//===- LoopVersioning.cpp - Utility to version a loop ---------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file defines a utility class to perform loop versioning. The versioned9// loop speculates that otherwise may-aliasing memory accesses don't overlap and10// emits checks to prove this.11//12//===----------------------------------------------------------------------===//1314#include "llvm/Transforms/Utils/LoopVersioning.h"15#include "llvm/ADT/ArrayRef.h"16#include "llvm/Analysis/AliasAnalysis.h"17#include "llvm/Analysis/InstSimplifyFolder.h"18#include "llvm/Analysis/LoopAccessAnalysis.h"19#include "llvm/Analysis/LoopInfo.h"20#include "llvm/Analysis/ScalarEvolution.h"21#include "llvm/Analysis/TargetLibraryInfo.h"22#include "llvm/IR/Dominators.h"23#include "llvm/IR/MDBuilder.h"24#include "llvm/IR/PassManager.h"25#include "llvm/Support/CommandLine.h"26#include "llvm/Transforms/Utils/BasicBlockUtils.h"27#include "llvm/Transforms/Utils/Cloning.h"28#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"2930using namespace llvm;3132#define DEBUG_TYPE "loop-versioning"3334static cl::opt<bool>35AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(true),36cl::Hidden,37cl::desc("Add no-alias annotation for instructions that "38"are disambiguated by memchecks"));3940LoopVersioning::LoopVersioning(const LoopAccessInfo &LAI,41ArrayRef<RuntimePointerCheck> Checks, Loop *L,42LoopInfo *LI, DominatorTree *DT,43ScalarEvolution *SE)44: VersionedLoop(L), AliasChecks(Checks.begin(), Checks.end()),45Preds(LAI.getPSE().getPredicate()), LAI(LAI), LI(LI), DT(DT),46SE(SE) {47}4849void LoopVersioning::versionLoop(50const SmallVectorImpl<Instruction *> &DefsUsedOutside) {51assert(VersionedLoop->getUniqueExitBlock() && "No single exit block");52assert(VersionedLoop->isLoopSimplifyForm() &&53"Loop is not in loop-simplify form");5455Value *MemRuntimeCheck;56Value *SCEVRuntimeCheck;57Value *RuntimeCheck = nullptr;5859// Add the memcheck in the original preheader (this is empty initially).60BasicBlock *RuntimeCheckBB = VersionedLoop->getLoopPreheader();61const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();6263SCEVExpander Exp2(*RtPtrChecking.getSE(),64VersionedLoop->getHeader()->getDataLayout(),65"induction");66MemRuntimeCheck = addRuntimeChecks(RuntimeCheckBB->getTerminator(),67VersionedLoop, AliasChecks, Exp2);6869SCEVExpander Exp(*SE, RuntimeCheckBB->getDataLayout(),70"scev.check");71SCEVRuntimeCheck =72Exp.expandCodeForPredicate(&Preds, RuntimeCheckBB->getTerminator());7374IRBuilder<InstSimplifyFolder> Builder(75RuntimeCheckBB->getContext(),76InstSimplifyFolder(RuntimeCheckBB->getDataLayout()));77if (MemRuntimeCheck && SCEVRuntimeCheck) {78Builder.SetInsertPoint(RuntimeCheckBB->getTerminator());79RuntimeCheck =80Builder.CreateOr(MemRuntimeCheck, SCEVRuntimeCheck, "lver.safe");81} else82RuntimeCheck = MemRuntimeCheck ? MemRuntimeCheck : SCEVRuntimeCheck;8384assert(RuntimeCheck && "called even though we don't need "85"any runtime checks");8687// Rename the block to make the IR more readable.88RuntimeCheckBB->setName(VersionedLoop->getHeader()->getName() +89".lver.check");9091// Create empty preheader for the loop (and after cloning for the92// non-versioned loop).93BasicBlock *PH =94SplitBlock(RuntimeCheckBB, RuntimeCheckBB->getTerminator(), DT, LI,95nullptr, VersionedLoop->getHeader()->getName() + ".ph");9697// Clone the loop including the preheader.98//99// FIXME: This does not currently preserve SimplifyLoop because the exit100// block is a join between the two loops.101SmallVector<BasicBlock *, 8> NonVersionedLoopBlocks;102NonVersionedLoop =103cloneLoopWithPreheader(PH, RuntimeCheckBB, VersionedLoop, VMap,104".lver.orig", LI, DT, NonVersionedLoopBlocks);105remapInstructionsInBlocks(NonVersionedLoopBlocks, VMap);106107// Insert the conditional branch based on the result of the memchecks.108Instruction *OrigTerm = RuntimeCheckBB->getTerminator();109Builder.SetInsertPoint(OrigTerm);110Builder.CreateCondBr(RuntimeCheck, NonVersionedLoop->getLoopPreheader(),111VersionedLoop->getLoopPreheader());112OrigTerm->eraseFromParent();113114// The loops merge in the original exit block. This is now dominated by the115// memchecking block.116DT->changeImmediateDominator(VersionedLoop->getExitBlock(), RuntimeCheckBB);117118// Adds the necessary PHI nodes for the versioned loops based on the119// loop-defined values used outside of the loop.120addPHINodes(DefsUsedOutside);121formDedicatedExitBlocks(NonVersionedLoop, DT, LI, nullptr, true);122formDedicatedExitBlocks(VersionedLoop, DT, LI, nullptr, true);123assert(NonVersionedLoop->isLoopSimplifyForm() &&124VersionedLoop->isLoopSimplifyForm() &&125"The versioned loops should be in simplify form.");126}127128void LoopVersioning::addPHINodes(129const SmallVectorImpl<Instruction *> &DefsUsedOutside) {130BasicBlock *PHIBlock = VersionedLoop->getExitBlock();131assert(PHIBlock && "No single successor to loop exit block");132PHINode *PN;133134// First add a single-operand PHI for each DefsUsedOutside if one does not135// exists yet.136for (auto *Inst : DefsUsedOutside) {137// See if we have a single-operand PHI with the value defined by the138// original loop.139for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {140if (PN->getIncomingValue(0) == Inst) {141SE->forgetValue(PN);142break;143}144}145// If not create it.146if (!PN) {147PN = PHINode::Create(Inst->getType(), 2, Inst->getName() + ".lver");148PN->insertBefore(PHIBlock->begin());149SmallVector<User*, 8> UsersToUpdate;150for (User *U : Inst->users())151if (!VersionedLoop->contains(cast<Instruction>(U)->getParent()))152UsersToUpdate.push_back(U);153for (User *U : UsersToUpdate)154U->replaceUsesOfWith(Inst, PN);155PN->addIncoming(Inst, VersionedLoop->getExitingBlock());156}157}158159// Then for each PHI add the operand for the edge from the cloned loop.160for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {161assert(PN->getNumOperands() == 1 &&162"Exit block should only have on predecessor");163164// If the definition was cloned used that otherwise use the same value.165Value *ClonedValue = PN->getIncomingValue(0);166auto Mapped = VMap.find(ClonedValue);167if (Mapped != VMap.end())168ClonedValue = Mapped->second;169170PN->addIncoming(ClonedValue, NonVersionedLoop->getExitingBlock());171}172}173174void LoopVersioning::prepareNoAliasMetadata() {175// We need to turn the no-alias relation between pointer checking groups into176// no-aliasing annotations between instructions.177//178// We accomplish this by mapping each pointer checking group (a set of179// pointers memchecked together) to an alias scope and then also mapping each180// group to the list of scopes it can't alias.181182const RuntimePointerChecking *RtPtrChecking = LAI.getRuntimePointerChecking();183LLVMContext &Context = VersionedLoop->getHeader()->getContext();184185// First allocate an aliasing scope for each pointer checking group.186//187// While traversing through the checking groups in the loop, also create a188// reverse map from pointers to the pointer checking group they were assigned189// to.190MDBuilder MDB(Context);191MDNode *Domain = MDB.createAnonymousAliasScopeDomain("LVerDomain");192193for (const auto &Group : RtPtrChecking->CheckingGroups) {194GroupToScope[&Group] = MDB.createAnonymousAliasScope(Domain);195196for (unsigned PtrIdx : Group.Members)197PtrToGroup[RtPtrChecking->getPointerInfo(PtrIdx).PointerValue] = &Group;198}199200// Go through the checks and for each pointer group, collect the scopes for201// each non-aliasing pointer group.202DenseMap<const RuntimeCheckingPtrGroup *, SmallVector<Metadata *, 4>>203GroupToNonAliasingScopes;204205for (const auto &Check : AliasChecks)206GroupToNonAliasingScopes[Check.first].push_back(GroupToScope[Check.second]);207208// Finally, transform the above to actually map to scope list which is what209// the metadata uses.210211for (const auto &Pair : GroupToNonAliasingScopes)212GroupToNonAliasingScopeList[Pair.first] = MDNode::get(Context, Pair.second);213}214215void LoopVersioning::annotateLoopWithNoAlias() {216if (!AnnotateNoAlias)217return;218219// First prepare the maps.220prepareNoAliasMetadata();221222// Add the scope and no-alias metadata to the instructions.223for (Instruction *I : LAI.getDepChecker().getMemoryInstructions()) {224annotateInstWithNoAlias(I);225}226}227228void LoopVersioning::annotateInstWithNoAlias(Instruction *VersionedInst,229const Instruction *OrigInst) {230if (!AnnotateNoAlias)231return;232233LLVMContext &Context = VersionedLoop->getHeader()->getContext();234const Value *Ptr = isa<LoadInst>(OrigInst)235? cast<LoadInst>(OrigInst)->getPointerOperand()236: cast<StoreInst>(OrigInst)->getPointerOperand();237238// Find the group for the pointer and then add the scope metadata.239auto Group = PtrToGroup.find(Ptr);240if (Group != PtrToGroup.end()) {241VersionedInst->setMetadata(242LLVMContext::MD_alias_scope,243MDNode::concatenate(244VersionedInst->getMetadata(LLVMContext::MD_alias_scope),245MDNode::get(Context, GroupToScope[Group->second])));246247// Add the no-alias metadata.248auto NonAliasingScopeList = GroupToNonAliasingScopeList.find(Group->second);249if (NonAliasingScopeList != GroupToNonAliasingScopeList.end())250VersionedInst->setMetadata(251LLVMContext::MD_noalias,252MDNode::concatenate(253VersionedInst->getMetadata(LLVMContext::MD_noalias),254NonAliasingScopeList->second));255}256}257258namespace {259bool runImpl(LoopInfo *LI, LoopAccessInfoManager &LAIs, DominatorTree *DT,260ScalarEvolution *SE) {261// Build up a worklist of inner-loops to version. This is necessary as the262// act of versioning a loop creates new loops and can invalidate iterators263// across the loops.264SmallVector<Loop *, 8> Worklist;265266for (Loop *TopLevelLoop : *LI)267for (Loop *L : depth_first(TopLevelLoop))268// We only handle inner-most loops.269if (L->isInnermost())270Worklist.push_back(L);271272// Now walk the identified inner loops.273bool Changed = false;274for (Loop *L : Worklist) {275if (!L->isLoopSimplifyForm() || !L->isRotatedForm() ||276!L->getExitingBlock())277continue;278const LoopAccessInfo &LAI = LAIs.getInfo(*L);279if (!LAI.hasConvergentOp() &&280(LAI.getNumRuntimePointerChecks() ||281!LAI.getPSE().getPredicate().isAlwaysTrue())) {282LoopVersioning LVer(LAI, LAI.getRuntimePointerChecking()->getChecks(), L,283LI, DT, SE);284LVer.versionLoop();285LVer.annotateLoopWithNoAlias();286Changed = true;287LAIs.clear();288}289}290291return Changed;292}293}294295PreservedAnalyses LoopVersioningPass::run(Function &F,296FunctionAnalysisManager &AM) {297auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);298auto &LI = AM.getResult<LoopAnalysis>(F);299LoopAccessInfoManager &LAIs = AM.getResult<LoopAccessAnalysis>(F);300auto &DT = AM.getResult<DominatorTreeAnalysis>(F);301302if (runImpl(&LI, LAIs, &DT, &SE))303return PreservedAnalyses::none();304return PreservedAnalyses::all();305}306307308