Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Scalar/CallSiteSplitting.cpp
35294 views
//===- CallSiteSplitting.cpp ----------------------------------------------===//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 implements a transformation that tries to split a call-site to pass9// more constrained arguments if its argument is predicated in the control flow10// so that we can expose better context to the later passes (e.g, inliner, jump11// threading, or IPA-CP based function cloning, etc.).12// As of now we support two cases :13//14// 1) Try to a split call-site with constrained arguments, if any constraints15// on any argument can be found by following the single predecessors of the16// all site's predecessors. Currently this pass only handles call-sites with 217// predecessors. For example, in the code below, we try to split the call-site18// since we can predicate the argument(ptr) based on the OR condition.19//20// Split from :21// if (!ptr || c)22// callee(ptr);23// to :24// if (!ptr)25// callee(null) // set the known constant value26// else if (c)27// callee(nonnull ptr) // set non-null attribute in the argument28//29// 2) We can also split a call-site based on constant incoming values of a PHI30// For example,31// from :32// Header:33// %c = icmp eq i32 %i1, %i234// br i1 %c, label %Tail, label %TBB35// TBB:36// br label Tail%37// Tail:38// %p = phi i32 [ 0, %Header], [ 1, %TBB]39// call void @bar(i32 %p)40// to41// Header:42// %c = icmp eq i32 %i1, %i243// br i1 %c, label %Tail-split0, label %TBB44// TBB:45// br label %Tail-split146// Tail-split0:47// call void @bar(i32 0)48// br label %Tail49// Tail-split1:50// call void @bar(i32 1)51// br label %Tail52// Tail:53// %p = phi i32 [ 0, %Tail-split0 ], [ 1, %Tail-split1 ]54//55//===----------------------------------------------------------------------===//5657#include "llvm/Transforms/Scalar/CallSiteSplitting.h"58#include "llvm/ADT/Statistic.h"59#include "llvm/Analysis/DomTreeUpdater.h"60#include "llvm/Analysis/TargetLibraryInfo.h"61#include "llvm/Analysis/TargetTransformInfo.h"62#include "llvm/IR/IntrinsicInst.h"63#include "llvm/IR/PatternMatch.h"64#include "llvm/Support/CommandLine.h"65#include "llvm/Support/Debug.h"66#include "llvm/Transforms/Utils/Cloning.h"67#include "llvm/Transforms/Utils/Local.h"6869using namespace llvm;70using namespace PatternMatch;7172#define DEBUG_TYPE "callsite-splitting"7374STATISTIC(NumCallSiteSplit, "Number of call-site split");7576/// Only allow instructions before a call, if their CodeSize cost is below77/// DuplicationThreshold. Those instructions need to be duplicated in all78/// split blocks.79static cl::opt<unsigned>80DuplicationThreshold("callsite-splitting-duplication-threshold", cl::Hidden,81cl::desc("Only allow instructions before a call, if "82"their cost is below DuplicationThreshold"),83cl::init(5));8485static void addNonNullAttribute(CallBase &CB, Value *Op) {86unsigned ArgNo = 0;87for (auto &I : CB.args()) {88if (&*I == Op)89CB.addParamAttr(ArgNo, Attribute::NonNull);90++ArgNo;91}92}9394static void setConstantInArgument(CallBase &CB, Value *Op,95Constant *ConstValue) {96unsigned ArgNo = 0;97for (auto &I : CB.args()) {98if (&*I == Op) {99// It is possible we have already added the non-null attribute to the100// parameter by using an earlier constraining condition.101CB.removeParamAttr(ArgNo, Attribute::NonNull);102CB.setArgOperand(ArgNo, ConstValue);103}104++ArgNo;105}106}107108static bool isCondRelevantToAnyCallArgument(ICmpInst *Cmp, CallBase &CB) {109assert(isa<Constant>(Cmp->getOperand(1)) && "Expected a constant operand.");110Value *Op0 = Cmp->getOperand(0);111unsigned ArgNo = 0;112for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I, ++ArgNo) {113// Don't consider constant or arguments that are already known non-null.114if (isa<Constant>(*I) || CB.paramHasAttr(ArgNo, Attribute::NonNull))115continue;116117if (*I == Op0)118return true;119}120return false;121}122123using ConditionTy = std::pair<ICmpInst *, unsigned>;124using ConditionsTy = SmallVector<ConditionTy, 2>;125126/// If From has a conditional jump to To, add the condition to Conditions,127/// if it is relevant to any argument at CB.128static void recordCondition(CallBase &CB, BasicBlock *From, BasicBlock *To,129ConditionsTy &Conditions) {130auto *BI = dyn_cast<BranchInst>(From->getTerminator());131if (!BI || !BI->isConditional())132return;133134CmpInst::Predicate Pred;135Value *Cond = BI->getCondition();136if (!match(Cond, m_ICmp(Pred, m_Value(), m_Constant())))137return;138139ICmpInst *Cmp = cast<ICmpInst>(Cond);140if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)141if (isCondRelevantToAnyCallArgument(Cmp, CB))142Conditions.push_back({Cmp, From->getTerminator()->getSuccessor(0) == To143? Pred144: Cmp->getInversePredicate()});145}146147/// Record ICmp conditions relevant to any argument in CB following Pred's148/// single predecessors. If there are conflicting conditions along a path, like149/// x == 1 and x == 0, the first condition will be used. We stop once we reach150/// an edge to StopAt.151static void recordConditions(CallBase &CB, BasicBlock *Pred,152ConditionsTy &Conditions, BasicBlock *StopAt) {153BasicBlock *From = Pred;154BasicBlock *To = Pred;155SmallPtrSet<BasicBlock *, 4> Visited;156while (To != StopAt && !Visited.count(From->getSinglePredecessor()) &&157(From = From->getSinglePredecessor())) {158recordCondition(CB, From, To, Conditions);159Visited.insert(From);160To = From;161}162}163164static void addConditions(CallBase &CB, const ConditionsTy &Conditions) {165for (const auto &Cond : Conditions) {166Value *Arg = Cond.first->getOperand(0);167Constant *ConstVal = cast<Constant>(Cond.first->getOperand(1));168if (Cond.second == ICmpInst::ICMP_EQ)169setConstantInArgument(CB, Arg, ConstVal);170else if (ConstVal->getType()->isPointerTy() && ConstVal->isNullValue()) {171assert(Cond.second == ICmpInst::ICMP_NE);172addNonNullAttribute(CB, Arg);173}174}175}176177static SmallVector<BasicBlock *, 2> getTwoPredecessors(BasicBlock *BB) {178SmallVector<BasicBlock *, 2> Preds(predecessors((BB)));179assert(Preds.size() == 2 && "Expected exactly 2 predecessors!");180return Preds;181}182183static bool canSplitCallSite(CallBase &CB, TargetTransformInfo &TTI) {184if (CB.isConvergent() || CB.cannotDuplicate())185return false;186187// FIXME: As of now we handle only CallInst. InvokeInst could be handled188// without too much effort.189if (!isa<CallInst>(CB))190return false;191192BasicBlock *CallSiteBB = CB.getParent();193// Need 2 predecessors and cannot split an edge from an IndirectBrInst.194SmallVector<BasicBlock *, 2> Preds(predecessors(CallSiteBB));195if (Preds.size() != 2 || isa<IndirectBrInst>(Preds[0]->getTerminator()) ||196isa<IndirectBrInst>(Preds[1]->getTerminator()))197return false;198199// BasicBlock::canSplitPredecessors is more aggressive, so checking for200// BasicBlock::isEHPad as well.201if (!CallSiteBB->canSplitPredecessors() || CallSiteBB->isEHPad())202return false;203204// Allow splitting a call-site only when the CodeSize cost of the205// instructions before the call is less then DuplicationThreshold. The206// instructions before the call will be duplicated in the split blocks and207// corresponding uses will be updated.208InstructionCost Cost = 0;209for (auto &InstBeforeCall :210llvm::make_range(CallSiteBB->begin(), CB.getIterator())) {211Cost += TTI.getInstructionCost(&InstBeforeCall,212TargetTransformInfo::TCK_CodeSize);213if (Cost >= DuplicationThreshold)214return false;215}216217return true;218}219220static Instruction *cloneInstForMustTail(Instruction *I, Instruction *Before,221Value *V) {222Instruction *Copy = I->clone();223Copy->setName(I->getName());224Copy->insertBefore(Before);225if (V)226Copy->setOperand(0, V);227return Copy;228}229230/// Copy mandatory `musttail` return sequence that follows original `CI`, and231/// link it up to `NewCI` value instead:232///233/// * (optional) `bitcast NewCI to ...`234/// * `ret bitcast or NewCI`235///236/// Insert this sequence right before `SplitBB`'s terminator, which will be237/// cleaned up later in `splitCallSite` below.238static void copyMustTailReturn(BasicBlock *SplitBB, Instruction *CI,239Instruction *NewCI) {240bool IsVoid = SplitBB->getParent()->getReturnType()->isVoidTy();241auto II = std::next(CI->getIterator());242243BitCastInst* BCI = dyn_cast<BitCastInst>(&*II);244if (BCI)245++II;246247ReturnInst* RI = dyn_cast<ReturnInst>(&*II);248assert(RI && "`musttail` call must be followed by `ret` instruction");249250Instruction *TI = SplitBB->getTerminator();251Value *V = NewCI;252if (BCI)253V = cloneInstForMustTail(BCI, TI, V);254cloneInstForMustTail(RI, TI, IsVoid ? nullptr : V);255256// FIXME: remove TI here, `DuplicateInstructionsInSplitBetween` has a bug257// that prevents doing this now.258}259260/// For each (predecessor, conditions from predecessors) pair, it will split the261/// basic block containing the call site, hook it up to the predecessor and262/// replace the call instruction with new call instructions, which contain263/// constraints based on the conditions from their predecessors.264/// For example, in the IR below with an OR condition, the call-site can265/// be split. In this case, Preds for Tail is [(Header, a == null),266/// (TBB, a != null, b == null)]. Tail is replaced by 2 split blocks, containing267/// CallInst1, which has constraints based on the conditions from Head and268/// CallInst2, which has constraints based on the conditions coming from TBB.269///270/// From :271///272/// Header:273/// %c = icmp eq i32* %a, null274/// br i1 %c %Tail, %TBB275/// TBB:276/// %c2 = icmp eq i32* %b, null277/// br i1 %c %Tail, %End278/// Tail:279/// %ca = call i1 @callee (i32* %a, i32* %b)280///281/// to :282///283/// Header: // PredBB1 is Header284/// %c = icmp eq i32* %a, null285/// br i1 %c %Tail-split1, %TBB286/// TBB: // PredBB2 is TBB287/// %c2 = icmp eq i32* %b, null288/// br i1 %c %Tail-split2, %End289/// Tail-split1:290/// %ca1 = call @callee (i32* null, i32* %b) // CallInst1291/// br %Tail292/// Tail-split2:293/// %ca2 = call @callee (i32* nonnull %a, i32* null) // CallInst2294/// br %Tail295/// Tail:296/// %p = phi i1 [%ca1, %Tail-split1],[%ca2, %Tail-split2]297///298/// Note that in case any arguments at the call-site are constrained by its299/// predecessors, new call-sites with more constrained arguments will be300/// created in createCallSitesOnPredicatedArgument().301static void splitCallSite(CallBase &CB,302ArrayRef<std::pair<BasicBlock *, ConditionsTy>> Preds,303DomTreeUpdater &DTU) {304BasicBlock *TailBB = CB.getParent();305bool IsMustTailCall = CB.isMustTailCall();306307PHINode *CallPN = nullptr;308309// `musttail` calls must be followed by optional `bitcast`, and `ret`. The310// split blocks will be terminated right after that so there're no users for311// this phi in a `TailBB`.312if (!IsMustTailCall && !CB.use_empty()) {313CallPN = PHINode::Create(CB.getType(), Preds.size(), "phi.call");314CallPN->setDebugLoc(CB.getDebugLoc());315}316317LLVM_DEBUG(dbgs() << "split call-site : " << CB << " into \n");318319assert(Preds.size() == 2 && "The ValueToValueMaps array has size 2.");320// ValueToValueMapTy is neither copy nor moveable, so we use a simple array321// here.322ValueToValueMapTy ValueToValueMaps[2];323for (unsigned i = 0; i < Preds.size(); i++) {324BasicBlock *PredBB = Preds[i].first;325BasicBlock *SplitBlock = DuplicateInstructionsInSplitBetween(326TailBB, PredBB, &*std::next(CB.getIterator()), ValueToValueMaps[i],327DTU);328assert(SplitBlock && "Unexpected new basic block split.");329330auto *NewCI =331cast<CallBase>(&*std::prev(SplitBlock->getTerminator()->getIterator()));332addConditions(*NewCI, Preds[i].second);333334// Handle PHIs used as arguments in the call-site.335for (PHINode &PN : TailBB->phis()) {336unsigned ArgNo = 0;337for (auto &CI : CB.args()) {338if (&*CI == &PN) {339NewCI->setArgOperand(ArgNo, PN.getIncomingValueForBlock(SplitBlock));340}341++ArgNo;342}343}344LLVM_DEBUG(dbgs() << " " << *NewCI << " in " << SplitBlock->getName()345<< "\n");346if (CallPN)347CallPN->addIncoming(NewCI, SplitBlock);348349// Clone and place bitcast and return instructions before `TI`350if (IsMustTailCall)351copyMustTailReturn(SplitBlock, &CB, NewCI);352}353354NumCallSiteSplit++;355356// FIXME: remove TI in `copyMustTailReturn`357if (IsMustTailCall) {358// Remove superfluous `br` terminators from the end of the Split blocks359// NOTE: Removing terminator removes the SplitBlock from the TailBB's360// predecessors. Therefore we must get complete list of Splits before361// attempting removal.362SmallVector<BasicBlock *, 2> Splits(predecessors((TailBB)));363assert(Splits.size() == 2 && "Expected exactly 2 splits!");364for (BasicBlock *BB : Splits) {365BB->getTerminator()->eraseFromParent();366DTU.applyUpdatesPermissive({{DominatorTree::Delete, BB, TailBB}});367}368369// Erase the tail block once done with musttail patching370DTU.deleteBB(TailBB);371return;372}373374BasicBlock::iterator OriginalBegin = TailBB->begin();375// Replace users of the original call with a PHI mering call-sites split.376if (CallPN) {377CallPN->insertBefore(*TailBB, OriginalBegin);378CB.replaceAllUsesWith(CallPN);379}380381// Remove instructions moved to split blocks from TailBB, from the duplicated382// call instruction to the beginning of the basic block. If an instruction383// has any uses, add a new PHI node to combine the values coming from the384// split blocks. The new PHI nodes are placed before the first original385// instruction, so we do not end up deleting them. By using reverse-order, we386// do not introduce unnecessary PHI nodes for def-use chains from the call387// instruction to the beginning of the block.388auto I = CB.getReverseIterator();389Instruction *OriginalBeginInst = &*OriginalBegin;390while (I != TailBB->rend()) {391Instruction *CurrentI = &*I++;392if (!CurrentI->use_empty()) {393// If an existing PHI has users after the call, there is no need to create394// a new one.395if (isa<PHINode>(CurrentI))396continue;397PHINode *NewPN = PHINode::Create(CurrentI->getType(), Preds.size());398NewPN->setDebugLoc(CurrentI->getDebugLoc());399for (auto &Mapping : ValueToValueMaps)400NewPN->addIncoming(Mapping[CurrentI],401cast<Instruction>(Mapping[CurrentI])->getParent());402NewPN->insertBefore(*TailBB, TailBB->begin());403CurrentI->replaceAllUsesWith(NewPN);404}405CurrentI->dropDbgRecords();406CurrentI->eraseFromParent();407// We are done once we handled the first original instruction in TailBB.408if (CurrentI == OriginalBeginInst)409break;410}411}412413// Return true if the call-site has an argument which is a PHI with only414// constant incoming values.415static bool isPredicatedOnPHI(CallBase &CB) {416BasicBlock *Parent = CB.getParent();417if (&CB != Parent->getFirstNonPHIOrDbg())418return false;419420for (auto &PN : Parent->phis()) {421for (auto &Arg : CB.args()) {422if (&*Arg != &PN)423continue;424assert(PN.getNumIncomingValues() == 2 &&425"Unexpected number of incoming values");426if (PN.getIncomingBlock(0) == PN.getIncomingBlock(1))427return false;428if (PN.getIncomingValue(0) == PN.getIncomingValue(1))429continue;430if (isa<Constant>(PN.getIncomingValue(0)) &&431isa<Constant>(PN.getIncomingValue(1)))432return true;433}434}435return false;436}437438using PredsWithCondsTy = SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2>;439440// Check if any of the arguments in CS are predicated on a PHI node and return441// the set of predecessors we should use for splitting.442static PredsWithCondsTy shouldSplitOnPHIPredicatedArgument(CallBase &CB) {443if (!isPredicatedOnPHI(CB))444return {};445446auto Preds = getTwoPredecessors(CB.getParent());447return {{Preds[0], {}}, {Preds[1], {}}};448}449450// Checks if any of the arguments in CS are predicated in a predecessor and451// returns a list of predecessors with the conditions that hold on their edges452// to CS.453static PredsWithCondsTy shouldSplitOnPredicatedArgument(CallBase &CB,454DomTreeUpdater &DTU) {455auto Preds = getTwoPredecessors(CB.getParent());456if (Preds[0] == Preds[1])457return {};458459// We can stop recording conditions once we reached the immediate dominator460// for the block containing the call site. Conditions in predecessors of the461// that node will be the same for all paths to the call site and splitting462// is not beneficial.463assert(DTU.hasDomTree() && "We need a DTU with a valid DT!");464auto *CSDTNode = DTU.getDomTree().getNode(CB.getParent());465BasicBlock *StopAt = CSDTNode ? CSDTNode->getIDom()->getBlock() : nullptr;466467SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS;468for (auto *Pred : llvm::reverse(Preds)) {469ConditionsTy Conditions;470// Record condition on edge BB(CS) <- Pred471recordCondition(CB, Pred, CB.getParent(), Conditions);472// Record conditions following Pred's single predecessors.473recordConditions(CB, Pred, Conditions, StopAt);474PredsCS.push_back({Pred, Conditions});475}476477if (all_of(PredsCS, [](const std::pair<BasicBlock *, ConditionsTy> &P) {478return P.second.empty();479}))480return {};481482return PredsCS;483}484485static bool tryToSplitCallSite(CallBase &CB, TargetTransformInfo &TTI,486DomTreeUpdater &DTU) {487// Check if we can split the call site.488if (!CB.arg_size() || !canSplitCallSite(CB, TTI))489return false;490491auto PredsWithConds = shouldSplitOnPredicatedArgument(CB, DTU);492if (PredsWithConds.empty())493PredsWithConds = shouldSplitOnPHIPredicatedArgument(CB);494if (PredsWithConds.empty())495return false;496497splitCallSite(CB, PredsWithConds, DTU);498return true;499}500501static bool doCallSiteSplitting(Function &F, TargetLibraryInfo &TLI,502TargetTransformInfo &TTI, DominatorTree &DT) {503504DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy);505bool Changed = false;506for (BasicBlock &BB : llvm::make_early_inc_range(F)) {507auto II = BB.getFirstNonPHIOrDbg()->getIterator();508auto IE = BB.getTerminator()->getIterator();509// Iterate until we reach the terminator instruction. tryToSplitCallSite510// can replace BB's terminator in case BB is a successor of itself. In that511// case, IE will be invalidated and we also have to check the current512// terminator.513while (II != IE && &*II != BB.getTerminator()) {514CallBase *CB = dyn_cast<CallBase>(&*II++);515if (!CB || isa<IntrinsicInst>(CB) || isInstructionTriviallyDead(CB, &TLI))516continue;517518Function *Callee = CB->getCalledFunction();519if (!Callee || Callee->isDeclaration())520continue;521522// Successful musttail call-site splits result in erased CI and erased BB.523// Check if such path is possible before attempting the splitting.524bool IsMustTail = CB->isMustTailCall();525526Changed |= tryToSplitCallSite(*CB, TTI, DTU);527528// There're no interesting instructions after this. The call site529// itself might have been erased on splitting.530if (IsMustTail)531break;532}533}534return Changed;535}536537PreservedAnalyses CallSiteSplittingPass::run(Function &F,538FunctionAnalysisManager &AM) {539auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);540auto &TTI = AM.getResult<TargetIRAnalysis>(F);541auto &DT = AM.getResult<DominatorTreeAnalysis>(F);542543if (!doCallSiteSplitting(F, TLI, TTI, DT))544return PreservedAnalyses::all();545PreservedAnalyses PA;546PA.preserve<DominatorTreeAnalysis>();547return PA;548}549550551