1 //===- CallSiteSplitting.cpp ----------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements a transformation that tries to split a call-site to pass 10 // more constrained arguments if its argument is predicated in the control flow 11 // so that we can expose better context to the later passes (e.g, inliner, jump 12 // threading, or IPA-CP based function cloning, etc.). 13 // As of now we support two cases : 14 // 15 // 1) Try to a split call-site with constrained arguments, if any constraints 16 // on any argument can be found by following the single predecessors of the 17 // all site's predecessors. Currently this pass only handles call-sites with 2 18 // predecessors. For example, in the code below, we try to split the call-site 19 // since we can predicate the argument(ptr) based on the OR condition. 20 // 21 // Split from : 22 // if (!ptr || c) 23 // callee(ptr); 24 // to : 25 // if (!ptr) 26 // callee(null) // set the known constant value 27 // else if (c) 28 // callee(nonnull ptr) // set non-null attribute in the argument 29 // 30 // 2) We can also split a call-site based on constant incoming values of a PHI 31 // For example, 32 // from : 33 // Header: 34 // %c = icmp eq i32 %i1, %i2 35 // br i1 %c, label %Tail, label %TBB 36 // TBB: 37 // br label Tail% 38 // Tail: 39 // %p = phi i32 [ 0, %Header], [ 1, %TBB] 40 // call void @bar(i32 %p) 41 // to 42 // Header: 43 // %c = icmp eq i32 %i1, %i2 44 // br i1 %c, label %Tail-split0, label %TBB 45 // TBB: 46 // br label %Tail-split1 47 // Tail-split0: 48 // call void @bar(i32 0) 49 // br label %Tail 50 // Tail-split1: 51 // call void @bar(i32 1) 52 // br label %Tail 53 // Tail: 54 // %p = phi i32 [ 0, %Tail-split0 ], [ 1, %Tail-split1 ] 55 // 56 //===----------------------------------------------------------------------===// 57 58 #include "llvm/Transforms/Scalar/CallSiteSplitting.h" 59 #include "llvm/ADT/Statistic.h" 60 #include "llvm/Analysis/DomTreeUpdater.h" 61 #include "llvm/Analysis/TargetLibraryInfo.h" 62 #include "llvm/Analysis/TargetTransformInfo.h" 63 #include "llvm/IR/IntrinsicInst.h" 64 #include "llvm/IR/PatternMatch.h" 65 #include "llvm/InitializePasses.h" 66 #include "llvm/Support/CommandLine.h" 67 #include "llvm/Support/Debug.h" 68 #include "llvm/Transforms/Scalar.h" 69 #include "llvm/Transforms/Utils/Cloning.h" 70 #include "llvm/Transforms/Utils/Local.h" 71 72 using namespace llvm; 73 using namespace PatternMatch; 74 75 #define DEBUG_TYPE "callsite-splitting" 76 77 STATISTIC(NumCallSiteSplit, "Number of call-site split"); 78 79 /// Only allow instructions before a call, if their CodeSize cost is below 80 /// DuplicationThreshold. Those instructions need to be duplicated in all 81 /// split blocks. 82 static cl::opt<unsigned> 83 DuplicationThreshold("callsite-splitting-duplication-threshold", cl::Hidden, 84 cl::desc("Only allow instructions before a call, if " 85 "their cost is below DuplicationThreshold"), 86 cl::init(5)); 87 88 static void addNonNullAttribute(CallBase &CB, Value *Op) { 89 unsigned ArgNo = 0; 90 for (auto &I : CB.args()) { 91 if (&*I == Op) 92 CB.addParamAttr(ArgNo, Attribute::NonNull); 93 ++ArgNo; 94 } 95 } 96 97 static void setConstantInArgument(CallBase &CB, Value *Op, 98 Constant *ConstValue) { 99 unsigned ArgNo = 0; 100 for (auto &I : CB.args()) { 101 if (&*I == Op) { 102 // It is possible we have already added the non-null attribute to the 103 // parameter by using an earlier constraining condition. 104 CB.removeParamAttr(ArgNo, Attribute::NonNull); 105 CB.setArgOperand(ArgNo, ConstValue); 106 } 107 ++ArgNo; 108 } 109 } 110 111 static bool isCondRelevantToAnyCallArgument(ICmpInst *Cmp, CallBase &CB) { 112 assert(isa<Constant>(Cmp->getOperand(1)) && "Expected a constant operand."); 113 Value *Op0 = Cmp->getOperand(0); 114 unsigned ArgNo = 0; 115 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I, ++ArgNo) { 116 // Don't consider constant or arguments that are already known non-null. 117 if (isa<Constant>(*I) || CB.paramHasAttr(ArgNo, Attribute::NonNull)) 118 continue; 119 120 if (*I == Op0) 121 return true; 122 } 123 return false; 124 } 125 126 using ConditionTy = std::pair<ICmpInst *, unsigned>; 127 using ConditionsTy = SmallVector<ConditionTy, 2>; 128 129 /// If From has a conditional jump to To, add the condition to Conditions, 130 /// if it is relevant to any argument at CB. 131 static void recordCondition(CallBase &CB, BasicBlock *From, BasicBlock *To, 132 ConditionsTy &Conditions) { 133 auto *BI = dyn_cast<BranchInst>(From->getTerminator()); 134 if (!BI || !BI->isConditional()) 135 return; 136 137 CmpInst::Predicate Pred; 138 Value *Cond = BI->getCondition(); 139 if (!match(Cond, m_ICmp(Pred, m_Value(), m_Constant()))) 140 return; 141 142 ICmpInst *Cmp = cast<ICmpInst>(Cond); 143 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) 144 if (isCondRelevantToAnyCallArgument(Cmp, CB)) 145 Conditions.push_back({Cmp, From->getTerminator()->getSuccessor(0) == To 146 ? Pred 147 : Cmp->getInversePredicate()}); 148 } 149 150 /// Record ICmp conditions relevant to any argument in CB following Pred's 151 /// single predecessors. If there are conflicting conditions along a path, like 152 /// x == 1 and x == 0, the first condition will be used. We stop once we reach 153 /// an edge to StopAt. 154 static void recordConditions(CallBase &CB, BasicBlock *Pred, 155 ConditionsTy &Conditions, BasicBlock *StopAt) { 156 BasicBlock *From = Pred; 157 BasicBlock *To = Pred; 158 SmallPtrSet<BasicBlock *, 4> Visited; 159 while (To != StopAt && !Visited.count(From->getSinglePredecessor()) && 160 (From = From->getSinglePredecessor())) { 161 recordCondition(CB, From, To, Conditions); 162 Visited.insert(From); 163 To = From; 164 } 165 } 166 167 static void addConditions(CallBase &CB, const ConditionsTy &Conditions) { 168 for (const auto &Cond : Conditions) { 169 Value *Arg = Cond.first->getOperand(0); 170 Constant *ConstVal = cast<Constant>(Cond.first->getOperand(1)); 171 if (Cond.second == ICmpInst::ICMP_EQ) 172 setConstantInArgument(CB, Arg, ConstVal); 173 else if (ConstVal->getType()->isPointerTy() && ConstVal->isNullValue()) { 174 assert(Cond.second == ICmpInst::ICMP_NE); 175 addNonNullAttribute(CB, Arg); 176 } 177 } 178 } 179 180 static SmallVector<BasicBlock *, 2> getTwoPredecessors(BasicBlock *BB) { 181 SmallVector<BasicBlock *, 2> Preds(predecessors((BB))); 182 assert(Preds.size() == 2 && "Expected exactly 2 predecessors!"); 183 return Preds; 184 } 185 186 static bool canSplitCallSite(CallBase &CB, TargetTransformInfo &TTI) { 187 if (CB.isConvergent() || CB.cannotDuplicate()) 188 return false; 189 190 // FIXME: As of now we handle only CallInst. InvokeInst could be handled 191 // without too much effort. 192 if (!isa<CallInst>(CB)) 193 return false; 194 195 BasicBlock *CallSiteBB = CB.getParent(); 196 // Need 2 predecessors and cannot split an edge from an IndirectBrInst. 197 SmallVector<BasicBlock *, 2> Preds(predecessors(CallSiteBB)); 198 if (Preds.size() != 2 || isa<IndirectBrInst>(Preds[0]->getTerminator()) || 199 isa<IndirectBrInst>(Preds[1]->getTerminator())) 200 return false; 201 202 // BasicBlock::canSplitPredecessors is more aggressive, so checking for 203 // BasicBlock::isEHPad as well. 204 if (!CallSiteBB->canSplitPredecessors() || CallSiteBB->isEHPad()) 205 return false; 206 207 // Allow splitting a call-site only when the CodeSize cost of the 208 // instructions before the call is less then DuplicationThreshold. The 209 // instructions before the call will be duplicated in the split blocks and 210 // corresponding uses will be updated. 211 InstructionCost Cost = 0; 212 for (auto &InstBeforeCall : 213 llvm::make_range(CallSiteBB->begin(), CB.getIterator())) { 214 Cost += TTI.getInstructionCost(&InstBeforeCall, 215 TargetTransformInfo::TCK_CodeSize); 216 if (Cost >= DuplicationThreshold) 217 return false; 218 } 219 220 return true; 221 } 222 223 static Instruction *cloneInstForMustTail(Instruction *I, Instruction *Before, 224 Value *V) { 225 Instruction *Copy = I->clone(); 226 Copy->setName(I->getName()); 227 Copy->insertBefore(Before); 228 if (V) 229 Copy->setOperand(0, V); 230 return Copy; 231 } 232 233 /// Copy mandatory `musttail` return sequence that follows original `CI`, and 234 /// link it up to `NewCI` value instead: 235 /// 236 /// * (optional) `bitcast NewCI to ...` 237 /// * `ret bitcast or NewCI` 238 /// 239 /// Insert this sequence right before `SplitBB`'s terminator, which will be 240 /// cleaned up later in `splitCallSite` below. 241 static void copyMustTailReturn(BasicBlock *SplitBB, Instruction *CI, 242 Instruction *NewCI) { 243 bool IsVoid = SplitBB->getParent()->getReturnType()->isVoidTy(); 244 auto II = std::next(CI->getIterator()); 245 246 BitCastInst* BCI = dyn_cast<BitCastInst>(&*II); 247 if (BCI) 248 ++II; 249 250 ReturnInst* RI = dyn_cast<ReturnInst>(&*II); 251 assert(RI && "`musttail` call must be followed by `ret` instruction"); 252 253 Instruction *TI = SplitBB->getTerminator(); 254 Value *V = NewCI; 255 if (BCI) 256 V = cloneInstForMustTail(BCI, TI, V); 257 cloneInstForMustTail(RI, TI, IsVoid ? nullptr : V); 258 259 // FIXME: remove TI here, `DuplicateInstructionsInSplitBetween` has a bug 260 // that prevents doing this now. 261 } 262 263 /// For each (predecessor, conditions from predecessors) pair, it will split the 264 /// basic block containing the call site, hook it up to the predecessor and 265 /// replace the call instruction with new call instructions, which contain 266 /// constraints based on the conditions from their predecessors. 267 /// For example, in the IR below with an OR condition, the call-site can 268 /// be split. In this case, Preds for Tail is [(Header, a == null), 269 /// (TBB, a != null, b == null)]. Tail is replaced by 2 split blocks, containing 270 /// CallInst1, which has constraints based on the conditions from Head and 271 /// CallInst2, which has constraints based on the conditions coming from TBB. 272 /// 273 /// From : 274 /// 275 /// Header: 276 /// %c = icmp eq i32* %a, null 277 /// br i1 %c %Tail, %TBB 278 /// TBB: 279 /// %c2 = icmp eq i32* %b, null 280 /// br i1 %c %Tail, %End 281 /// Tail: 282 /// %ca = call i1 @callee (i32* %a, i32* %b) 283 /// 284 /// to : 285 /// 286 /// Header: // PredBB1 is Header 287 /// %c = icmp eq i32* %a, null 288 /// br i1 %c %Tail-split1, %TBB 289 /// TBB: // PredBB2 is TBB 290 /// %c2 = icmp eq i32* %b, null 291 /// br i1 %c %Tail-split2, %End 292 /// Tail-split1: 293 /// %ca1 = call @callee (i32* null, i32* %b) // CallInst1 294 /// br %Tail 295 /// Tail-split2: 296 /// %ca2 = call @callee (i32* nonnull %a, i32* null) // CallInst2 297 /// br %Tail 298 /// Tail: 299 /// %p = phi i1 [%ca1, %Tail-split1],[%ca2, %Tail-split2] 300 /// 301 /// Note that in case any arguments at the call-site are constrained by its 302 /// predecessors, new call-sites with more constrained arguments will be 303 /// created in createCallSitesOnPredicatedArgument(). 304 static void splitCallSite(CallBase &CB, 305 ArrayRef<std::pair<BasicBlock *, ConditionsTy>> Preds, 306 DomTreeUpdater &DTU) { 307 BasicBlock *TailBB = CB.getParent(); 308 bool IsMustTailCall = CB.isMustTailCall(); 309 310 PHINode *CallPN = nullptr; 311 312 // `musttail` calls must be followed by optional `bitcast`, and `ret`. The 313 // split blocks will be terminated right after that so there're no users for 314 // this phi in a `TailBB`. 315 if (!IsMustTailCall && !CB.use_empty()) { 316 CallPN = PHINode::Create(CB.getType(), Preds.size(), "phi.call"); 317 CallPN->setDebugLoc(CB.getDebugLoc()); 318 } 319 320 LLVM_DEBUG(dbgs() << "split call-site : " << CB << " into \n"); 321 322 assert(Preds.size() == 2 && "The ValueToValueMaps array has size 2."); 323 // ValueToValueMapTy is neither copy nor moveable, so we use a simple array 324 // here. 325 ValueToValueMapTy ValueToValueMaps[2]; 326 for (unsigned i = 0; i < Preds.size(); i++) { 327 BasicBlock *PredBB = Preds[i].first; 328 BasicBlock *SplitBlock = DuplicateInstructionsInSplitBetween( 329 TailBB, PredBB, &*std::next(CB.getIterator()), ValueToValueMaps[i], 330 DTU); 331 assert(SplitBlock && "Unexpected new basic block split."); 332 333 auto *NewCI = 334 cast<CallBase>(&*std::prev(SplitBlock->getTerminator()->getIterator())); 335 addConditions(*NewCI, Preds[i].second); 336 337 // Handle PHIs used as arguments in the call-site. 338 for (PHINode &PN : TailBB->phis()) { 339 unsigned ArgNo = 0; 340 for (auto &CI : CB.args()) { 341 if (&*CI == &PN) { 342 NewCI->setArgOperand(ArgNo, PN.getIncomingValueForBlock(SplitBlock)); 343 } 344 ++ArgNo; 345 } 346 } 347 LLVM_DEBUG(dbgs() << " " << *NewCI << " in " << SplitBlock->getName() 348 << "\n"); 349 if (CallPN) 350 CallPN->addIncoming(NewCI, SplitBlock); 351 352 // Clone and place bitcast and return instructions before `TI` 353 if (IsMustTailCall) 354 copyMustTailReturn(SplitBlock, &CB, NewCI); 355 } 356 357 NumCallSiteSplit++; 358 359 // FIXME: remove TI in `copyMustTailReturn` 360 if (IsMustTailCall) { 361 // Remove superfluous `br` terminators from the end of the Split blocks 362 // NOTE: Removing terminator removes the SplitBlock from the TailBB's 363 // predecessors. Therefore we must get complete list of Splits before 364 // attempting removal. 365 SmallVector<BasicBlock *, 2> Splits(predecessors((TailBB))); 366 assert(Splits.size() == 2 && "Expected exactly 2 splits!"); 367 for (BasicBlock *BB : Splits) { 368 BB->getTerminator()->eraseFromParent(); 369 DTU.applyUpdatesPermissive({{DominatorTree::Delete, BB, TailBB}}); 370 } 371 372 // Erase the tail block once done with musttail patching 373 DTU.deleteBB(TailBB); 374 return; 375 } 376 377 auto *OriginalBegin = &*TailBB->begin(); 378 // Replace users of the original call with a PHI mering call-sites split. 379 if (CallPN) { 380 CallPN->insertBefore(OriginalBegin); 381 CB.replaceAllUsesWith(CallPN); 382 } 383 384 // Remove instructions moved to split blocks from TailBB, from the duplicated 385 // call instruction to the beginning of the basic block. If an instruction 386 // has any uses, add a new PHI node to combine the values coming from the 387 // split blocks. The new PHI nodes are placed before the first original 388 // instruction, so we do not end up deleting them. By using reverse-order, we 389 // do not introduce unnecessary PHI nodes for def-use chains from the call 390 // instruction to the beginning of the block. 391 auto I = CB.getReverseIterator(); 392 while (I != TailBB->rend()) { 393 Instruction *CurrentI = &*I++; 394 if (!CurrentI->use_empty()) { 395 // If an existing PHI has users after the call, there is no need to create 396 // a new one. 397 if (isa<PHINode>(CurrentI)) 398 continue; 399 PHINode *NewPN = PHINode::Create(CurrentI->getType(), Preds.size()); 400 NewPN->setDebugLoc(CurrentI->getDebugLoc()); 401 for (auto &Mapping : ValueToValueMaps) 402 NewPN->addIncoming(Mapping[CurrentI], 403 cast<Instruction>(Mapping[CurrentI])->getParent()); 404 NewPN->insertBefore(&*TailBB->begin()); 405 CurrentI->replaceAllUsesWith(NewPN); 406 } 407 CurrentI->eraseFromParent(); 408 // We are done once we handled the first original instruction in TailBB. 409 if (CurrentI == OriginalBegin) 410 break; 411 } 412 } 413 414 // Return true if the call-site has an argument which is a PHI with only 415 // constant incoming values. 416 static bool isPredicatedOnPHI(CallBase &CB) { 417 BasicBlock *Parent = CB.getParent(); 418 if (&CB != Parent->getFirstNonPHIOrDbg()) 419 return false; 420 421 for (auto &PN : Parent->phis()) { 422 for (auto &Arg : CB.args()) { 423 if (&*Arg != &PN) 424 continue; 425 assert(PN.getNumIncomingValues() == 2 && 426 "Unexpected number of incoming values"); 427 if (PN.getIncomingBlock(0) == PN.getIncomingBlock(1)) 428 return false; 429 if (PN.getIncomingValue(0) == PN.getIncomingValue(1)) 430 continue; 431 if (isa<Constant>(PN.getIncomingValue(0)) && 432 isa<Constant>(PN.getIncomingValue(1))) 433 return true; 434 } 435 } 436 return false; 437 } 438 439 using PredsWithCondsTy = SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2>; 440 441 // Check if any of the arguments in CS are predicated on a PHI node and return 442 // the set of predecessors we should use for splitting. 443 static PredsWithCondsTy shouldSplitOnPHIPredicatedArgument(CallBase &CB) { 444 if (!isPredicatedOnPHI(CB)) 445 return {}; 446 447 auto Preds = getTwoPredecessors(CB.getParent()); 448 return {{Preds[0], {}}, {Preds[1], {}}}; 449 } 450 451 // Checks if any of the arguments in CS are predicated in a predecessor and 452 // returns a list of predecessors with the conditions that hold on their edges 453 // to CS. 454 static PredsWithCondsTy shouldSplitOnPredicatedArgument(CallBase &CB, 455 DomTreeUpdater &DTU) { 456 auto Preds = getTwoPredecessors(CB.getParent()); 457 if (Preds[0] == Preds[1]) 458 return {}; 459 460 // We can stop recording conditions once we reached the immediate dominator 461 // for the block containing the call site. Conditions in predecessors of the 462 // that node will be the same for all paths to the call site and splitting 463 // is not beneficial. 464 assert(DTU.hasDomTree() && "We need a DTU with a valid DT!"); 465 auto *CSDTNode = DTU.getDomTree().getNode(CB.getParent()); 466 BasicBlock *StopAt = CSDTNode ? CSDTNode->getIDom()->getBlock() : nullptr; 467 468 SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS; 469 for (auto *Pred : llvm::reverse(Preds)) { 470 ConditionsTy Conditions; 471 // Record condition on edge BB(CS) <- Pred 472 recordCondition(CB, Pred, CB.getParent(), Conditions); 473 // Record conditions following Pred's single predecessors. 474 recordConditions(CB, Pred, Conditions, StopAt); 475 PredsCS.push_back({Pred, Conditions}); 476 } 477 478 if (all_of(PredsCS, [](const std::pair<BasicBlock *, ConditionsTy> &P) { 479 return P.second.empty(); 480 })) 481 return {}; 482 483 return PredsCS; 484 } 485 486 static bool tryToSplitCallSite(CallBase &CB, TargetTransformInfo &TTI, 487 DomTreeUpdater &DTU) { 488 // Check if we can split the call site. 489 if (!CB.arg_size() || !canSplitCallSite(CB, TTI)) 490 return false; 491 492 auto PredsWithConds = shouldSplitOnPredicatedArgument(CB, DTU); 493 if (PredsWithConds.empty()) 494 PredsWithConds = shouldSplitOnPHIPredicatedArgument(CB); 495 if (PredsWithConds.empty()) 496 return false; 497 498 splitCallSite(CB, PredsWithConds, DTU); 499 return true; 500 } 501 502 static bool doCallSiteSplitting(Function &F, TargetLibraryInfo &TLI, 503 TargetTransformInfo &TTI, DominatorTree &DT) { 504 505 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy); 506 bool Changed = false; 507 for (BasicBlock &BB : llvm::make_early_inc_range(F)) { 508 auto II = BB.getFirstNonPHIOrDbg()->getIterator(); 509 auto IE = BB.getTerminator()->getIterator(); 510 // Iterate until we reach the terminator instruction. tryToSplitCallSite 511 // can replace BB's terminator in case BB is a successor of itself. In that 512 // case, IE will be invalidated and we also have to check the current 513 // terminator. 514 while (II != IE && &*II != BB.getTerminator()) { 515 CallBase *CB = dyn_cast<CallBase>(&*II++); 516 if (!CB || isa<IntrinsicInst>(CB) || isInstructionTriviallyDead(CB, &TLI)) 517 continue; 518 519 Function *Callee = CB->getCalledFunction(); 520 if (!Callee || Callee->isDeclaration()) 521 continue; 522 523 // Successful musttail call-site splits result in erased CI and erased BB. 524 // Check if such path is possible before attempting the splitting. 525 bool IsMustTail = CB->isMustTailCall(); 526 527 Changed |= tryToSplitCallSite(*CB, TTI, DTU); 528 529 // There're no interesting instructions after this. The call site 530 // itself might have been erased on splitting. 531 if (IsMustTail) 532 break; 533 } 534 } 535 return Changed; 536 } 537 538 PreservedAnalyses CallSiteSplittingPass::run(Function &F, 539 FunctionAnalysisManager &AM) { 540 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 541 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 542 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 543 544 if (!doCallSiteSplitting(F, TLI, TTI, DT)) 545 return PreservedAnalyses::all(); 546 PreservedAnalyses PA; 547 PA.preserve<DominatorTreeAnalysis>(); 548 return PA; 549 } 550