1 //===- BranchFolding.cpp - Fold machine code branch instructions ----------===// 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 pass forwards branches to unconditional branches to make them branch 10 // directly to the target block. This pass often results in dead MBB's, which 11 // it then removes. 12 // 13 // Note that this pass must be run after register allocation, it cannot handle 14 // SSA form. It also must handle virtual registers for targets that emit virtual 15 // ISA (e.g. NVPTX). 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "BranchFolding.h" 20 #include "llvm/ADT/BitVector.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/Statistic.h" 27 #include "llvm/CodeGen/Analysis.h" 28 #include "llvm/CodeGen/LivePhysRegs.h" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 31 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 32 #include "llvm/CodeGen/MachineFunction.h" 33 #include "llvm/CodeGen/MachineFunctionPass.h" 34 #include "llvm/CodeGen/MachineInstr.h" 35 #include "llvm/CodeGen/MachineInstrBuilder.h" 36 #include "llvm/CodeGen/MachineJumpTableInfo.h" 37 #include "llvm/CodeGen/MachineLoopInfo.h" 38 #include "llvm/CodeGen/MachineModuleInfo.h" 39 #include "llvm/CodeGen/MachineOperand.h" 40 #include "llvm/CodeGen/MachineRegisterInfo.h" 41 #include "llvm/CodeGen/TargetInstrInfo.h" 42 #include "llvm/CodeGen/TargetOpcodes.h" 43 #include "llvm/CodeGen/TargetPassConfig.h" 44 #include "llvm/CodeGen/TargetRegisterInfo.h" 45 #include "llvm/CodeGen/TargetSubtargetInfo.h" 46 #include "llvm/IR/DebugInfoMetadata.h" 47 #include "llvm/IR/DebugLoc.h" 48 #include "llvm/IR/Function.h" 49 #include "llvm/InitializePasses.h" 50 #include "llvm/MC/LaneBitmask.h" 51 #include "llvm/MC/MCRegisterInfo.h" 52 #include "llvm/Pass.h" 53 #include "llvm/Support/BlockFrequency.h" 54 #include "llvm/Support/BranchProbability.h" 55 #include "llvm/Support/CommandLine.h" 56 #include "llvm/Support/Debug.h" 57 #include "llvm/Support/ErrorHandling.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include "llvm/Target/TargetMachine.h" 60 #include <cassert> 61 #include <cstddef> 62 #include <iterator> 63 #include <numeric> 64 #include <vector> 65 66 using namespace llvm; 67 68 #define DEBUG_TYPE "branch-folder" 69 70 STATISTIC(NumDeadBlocks, "Number of dead blocks removed"); 71 STATISTIC(NumBranchOpts, "Number of branches optimized"); 72 STATISTIC(NumTailMerge , "Number of block tails merged"); 73 STATISTIC(NumHoist , "Number of times common instructions are hoisted"); 74 STATISTIC(NumTailCalls, "Number of tail calls optimized"); 75 76 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge", 77 cl::init(cl::BOU_UNSET), cl::Hidden); 78 79 // Throttle for huge numbers of predecessors (compile speed problems) 80 static cl::opt<unsigned> 81 TailMergeThreshold("tail-merge-threshold", 82 cl::desc("Max number of predecessors to consider tail merging"), 83 cl::init(150), cl::Hidden); 84 85 // Heuristic for tail merging (and, inversely, tail duplication). 86 // TODO: This should be replaced with a target query. 87 static cl::opt<unsigned> 88 TailMergeSize("tail-merge-size", 89 cl::desc("Min number of instructions to consider tail merging"), 90 cl::init(3), cl::Hidden); 91 92 namespace { 93 94 /// BranchFolderPass - Wrap branch folder in a machine function pass. 95 class BranchFolderPass : public MachineFunctionPass { 96 public: 97 static char ID; 98 99 explicit BranchFolderPass(): MachineFunctionPass(ID) {} 100 101 bool runOnMachineFunction(MachineFunction &MF) override; 102 103 void getAnalysisUsage(AnalysisUsage &AU) const override { 104 AU.addRequired<MachineBlockFrequencyInfo>(); 105 AU.addRequired<MachineBranchProbabilityInfo>(); 106 AU.addRequired<TargetPassConfig>(); 107 MachineFunctionPass::getAnalysisUsage(AU); 108 } 109 }; 110 111 } // end anonymous namespace 112 113 char BranchFolderPass::ID = 0; 114 115 char &llvm::BranchFolderPassID = BranchFolderPass::ID; 116 117 INITIALIZE_PASS(BranchFolderPass, DEBUG_TYPE, 118 "Control Flow Optimizer", false, false) 119 120 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) { 121 if (skipFunction(MF.getFunction())) 122 return false; 123 124 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); 125 // TailMerge can create jump into if branches that make CFG irreducible for 126 // HW that requires structurized CFG. 127 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && 128 PassConfig->getEnableTailMerge(); 129 BranchFolder::MBFIWrapper MBBFreqInfo( 130 getAnalysis<MachineBlockFrequencyInfo>()); 131 BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo, 132 getAnalysis<MachineBranchProbabilityInfo>()); 133 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>(); 134 return Folder.OptimizeFunction( 135 MF, MF.getSubtarget().getInstrInfo(), MF.getSubtarget().getRegisterInfo(), 136 MMIWP ? &MMIWP->getMMI() : nullptr); 137 } 138 139 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist, 140 MBFIWrapper &FreqInfo, 141 const MachineBranchProbabilityInfo &ProbInfo, 142 unsigned MinTailLength) 143 : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength), 144 MBBFreqInfo(FreqInfo), MBPI(ProbInfo) { 145 if (MinCommonTailLength == 0) 146 MinCommonTailLength = TailMergeSize; 147 switch (FlagEnableTailMerge) { 148 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break; 149 case cl::BOU_TRUE: EnableTailMerge = true; break; 150 case cl::BOU_FALSE: EnableTailMerge = false; break; 151 } 152 } 153 154 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) { 155 assert(MBB->pred_empty() && "MBB must be dead!"); 156 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB); 157 158 MachineFunction *MF = MBB->getParent(); 159 // drop all successors. 160 while (!MBB->succ_empty()) 161 MBB->removeSuccessor(MBB->succ_end()-1); 162 163 // Avoid matching if this pointer gets reused. 164 TriedMerging.erase(MBB); 165 166 // Update call site info. 167 std::for_each(MBB->begin(), MBB->end(), [MF](const MachineInstr &MI) { 168 if (MI.isCall(MachineInstr::IgnoreBundle)) 169 MF->eraseCallSiteInfo(&MI); 170 }); 171 // Remove the block. 172 MF->erase(MBB); 173 EHScopeMembership.erase(MBB); 174 if (MLI) 175 MLI->removeBlock(MBB); 176 } 177 178 bool BranchFolder::OptimizeFunction(MachineFunction &MF, 179 const TargetInstrInfo *tii, 180 const TargetRegisterInfo *tri, 181 MachineModuleInfo *mmi, 182 MachineLoopInfo *mli, bool AfterPlacement) { 183 if (!tii) return false; 184 185 TriedMerging.clear(); 186 187 MachineRegisterInfo &MRI = MF.getRegInfo(); 188 AfterBlockPlacement = AfterPlacement; 189 TII = tii; 190 TRI = tri; 191 MMI = mmi; 192 MLI = mli; 193 this->MRI = &MRI; 194 195 UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF); 196 if (!UpdateLiveIns) 197 MRI.invalidateLiveness(); 198 199 // Fix CFG. The later algorithms expect it to be right. 200 bool MadeChange = false; 201 for (MachineBasicBlock &MBB : MF) { 202 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 203 SmallVector<MachineOperand, 4> Cond; 204 if (!TII->analyzeBranch(MBB, TBB, FBB, Cond, true)) 205 MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty()); 206 } 207 208 // Recalculate EH scope membership. 209 EHScopeMembership = getEHScopeMembership(MF); 210 211 bool MadeChangeThisIteration = true; 212 while (MadeChangeThisIteration) { 213 MadeChangeThisIteration = TailMergeBlocks(MF); 214 // No need to clean up if tail merging does not change anything after the 215 // block placement. 216 if (!AfterBlockPlacement || MadeChangeThisIteration) 217 MadeChangeThisIteration |= OptimizeBranches(MF); 218 if (EnableHoistCommonCode) 219 MadeChangeThisIteration |= HoistCommonCode(MF); 220 MadeChange |= MadeChangeThisIteration; 221 } 222 223 // See if any jump tables have become dead as the code generator 224 // did its thing. 225 MachineJumpTableInfo *JTI = MF.getJumpTableInfo(); 226 if (!JTI) 227 return MadeChange; 228 229 // Walk the function to find jump tables that are live. 230 BitVector JTIsLive(JTI->getJumpTables().size()); 231 for (const MachineBasicBlock &BB : MF) { 232 for (const MachineInstr &I : BB) 233 for (const MachineOperand &Op : I.operands()) { 234 if (!Op.isJTI()) continue; 235 236 // Remember that this JT is live. 237 JTIsLive.set(Op.getIndex()); 238 } 239 } 240 241 // Finally, remove dead jump tables. This happens when the 242 // indirect jump was unreachable (and thus deleted). 243 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i) 244 if (!JTIsLive.test(i)) { 245 JTI->RemoveJumpTable(i); 246 MadeChange = true; 247 } 248 249 return MadeChange; 250 } 251 252 //===----------------------------------------------------------------------===// 253 // Tail Merging of Blocks 254 //===----------------------------------------------------------------------===// 255 256 /// HashMachineInstr - Compute a hash value for MI and its operands. 257 static unsigned HashMachineInstr(const MachineInstr &MI) { 258 unsigned Hash = MI.getOpcode(); 259 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 260 const MachineOperand &Op = MI.getOperand(i); 261 262 // Merge in bits from the operand if easy. We can't use MachineOperand's 263 // hash_code here because it's not deterministic and we sort by hash value 264 // later. 265 unsigned OperandHash = 0; 266 switch (Op.getType()) { 267 case MachineOperand::MO_Register: 268 OperandHash = Op.getReg(); 269 break; 270 case MachineOperand::MO_Immediate: 271 OperandHash = Op.getImm(); 272 break; 273 case MachineOperand::MO_MachineBasicBlock: 274 OperandHash = Op.getMBB()->getNumber(); 275 break; 276 case MachineOperand::MO_FrameIndex: 277 case MachineOperand::MO_ConstantPoolIndex: 278 case MachineOperand::MO_JumpTableIndex: 279 OperandHash = Op.getIndex(); 280 break; 281 case MachineOperand::MO_GlobalAddress: 282 case MachineOperand::MO_ExternalSymbol: 283 // Global address / external symbol are too hard, don't bother, but do 284 // pull in the offset. 285 OperandHash = Op.getOffset(); 286 break; 287 default: 288 break; 289 } 290 291 Hash += ((OperandHash << 3) | Op.getType()) << (i & 31); 292 } 293 return Hash; 294 } 295 296 /// HashEndOfMBB - Hash the last instruction in the MBB. 297 static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) { 298 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr(); 299 if (I == MBB.end()) 300 return 0; 301 302 return HashMachineInstr(*I); 303 } 304 305 /// Whether MI should be counted as an instruction when calculating common tail. 306 static bool countsAsInstruction(const MachineInstr &MI) { 307 return !(MI.isDebugInstr() || MI.isCFIInstruction()); 308 } 309 310 /// Iterate backwards from the given iterator \p I, towards the beginning of the 311 /// block. If a MI satisfying 'countsAsInstruction' is found, return an iterator 312 /// pointing to that MI. If no such MI is found, return the end iterator. 313 static MachineBasicBlock::iterator 314 skipBackwardPastNonInstructions(MachineBasicBlock::iterator I, 315 MachineBasicBlock *MBB) { 316 while (I != MBB->begin()) { 317 --I; 318 if (countsAsInstruction(*I)) 319 return I; 320 } 321 return MBB->end(); 322 } 323 324 /// Given two machine basic blocks, return the number of instructions they 325 /// actually have in common together at their end. If a common tail is found (at 326 /// least by one instruction), then iterators for the first shared instruction 327 /// in each block are returned as well. 328 /// 329 /// Non-instructions according to countsAsInstruction are ignored. 330 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1, 331 MachineBasicBlock *MBB2, 332 MachineBasicBlock::iterator &I1, 333 MachineBasicBlock::iterator &I2) { 334 MachineBasicBlock::iterator MBBI1 = MBB1->end(); 335 MachineBasicBlock::iterator MBBI2 = MBB2->end(); 336 337 unsigned TailLen = 0; 338 while (true) { 339 MBBI1 = skipBackwardPastNonInstructions(MBBI1, MBB1); 340 MBBI2 = skipBackwardPastNonInstructions(MBBI2, MBB2); 341 if (MBBI1 == MBB1->end() || MBBI2 == MBB2->end()) 342 break; 343 if (!MBBI1->isIdenticalTo(*MBBI2) || 344 // FIXME: This check is dubious. It's used to get around a problem where 345 // people incorrectly expect inline asm directives to remain in the same 346 // relative order. This is untenable because normal compiler 347 // optimizations (like this one) may reorder and/or merge these 348 // directives. 349 MBBI1->isInlineAsm()) { 350 break; 351 } 352 ++TailLen; 353 I1 = MBBI1; 354 I2 = MBBI2; 355 } 356 357 return TailLen; 358 } 359 360 void BranchFolder::replaceTailWithBranchTo(MachineBasicBlock::iterator OldInst, 361 MachineBasicBlock &NewDest) { 362 if (UpdateLiveIns) { 363 // OldInst should always point to an instruction. 364 MachineBasicBlock &OldMBB = *OldInst->getParent(); 365 LiveRegs.clear(); 366 LiveRegs.addLiveOuts(OldMBB); 367 // Move backward to the place where will insert the jump. 368 MachineBasicBlock::iterator I = OldMBB.end(); 369 do { 370 --I; 371 LiveRegs.stepBackward(*I); 372 } while (I != OldInst); 373 374 // Merging the tails may have switched some undef operand to non-undef ones. 375 // Add IMPLICIT_DEFS into OldMBB as necessary to have a definition of the 376 // register. 377 for (MachineBasicBlock::RegisterMaskPair P : NewDest.liveins()) { 378 // We computed the liveins with computeLiveIn earlier and should only see 379 // full registers: 380 assert(P.LaneMask == LaneBitmask::getAll() && 381 "Can only handle full register."); 382 MCPhysReg Reg = P.PhysReg; 383 if (!LiveRegs.available(*MRI, Reg)) 384 continue; 385 DebugLoc DL; 386 BuildMI(OldMBB, OldInst, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Reg); 387 } 388 } 389 390 TII->ReplaceTailWithBranchTo(OldInst, &NewDest); 391 ++NumTailMerge; 392 } 393 394 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB, 395 MachineBasicBlock::iterator BBI1, 396 const BasicBlock *BB) { 397 if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1)) 398 return nullptr; 399 400 MachineFunction &MF = *CurMBB.getParent(); 401 402 // Create the fall-through block. 403 MachineFunction::iterator MBBI = CurMBB.getIterator(); 404 MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(BB); 405 CurMBB.getParent()->insert(++MBBI, NewMBB); 406 407 // Move all the successors of this block to the specified block. 408 NewMBB->transferSuccessors(&CurMBB); 409 410 // Add an edge from CurMBB to NewMBB for the fall-through. 411 CurMBB.addSuccessor(NewMBB); 412 413 // Splice the code over. 414 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end()); 415 416 // NewMBB belongs to the same loop as CurMBB. 417 if (MLI) 418 if (MachineLoop *ML = MLI->getLoopFor(&CurMBB)) 419 ML->addBasicBlockToLoop(NewMBB, MLI->getBase()); 420 421 // NewMBB inherits CurMBB's block frequency. 422 MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB)); 423 424 if (UpdateLiveIns) 425 computeAndAddLiveIns(LiveRegs, *NewMBB); 426 427 // Add the new block to the EH scope. 428 const auto &EHScopeI = EHScopeMembership.find(&CurMBB); 429 if (EHScopeI != EHScopeMembership.end()) { 430 auto n = EHScopeI->second; 431 EHScopeMembership[NewMBB] = n; 432 } 433 434 return NewMBB; 435 } 436 437 /// EstimateRuntime - Make a rough estimate for how long it will take to run 438 /// the specified code. 439 static unsigned EstimateRuntime(MachineBasicBlock::iterator I, 440 MachineBasicBlock::iterator E) { 441 unsigned Time = 0; 442 for (; I != E; ++I) { 443 if (!countsAsInstruction(*I)) 444 continue; 445 if (I->isCall()) 446 Time += 10; 447 else if (I->mayLoad() || I->mayStore()) 448 Time += 2; 449 else 450 ++Time; 451 } 452 return Time; 453 } 454 455 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these 456 // branches temporarily for tail merging). In the case where CurMBB ends 457 // with a conditional branch to the next block, optimize by reversing the 458 // test and conditionally branching to SuccMBB instead. 459 static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB, 460 const TargetInstrInfo *TII) { 461 MachineFunction *MF = CurMBB->getParent(); 462 MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB)); 463 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 464 SmallVector<MachineOperand, 4> Cond; 465 DebugLoc dl = CurMBB->findBranchDebugLoc(); 466 if (I != MF->end() && !TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)) { 467 MachineBasicBlock *NextBB = &*I; 468 if (TBB == NextBB && !Cond.empty() && !FBB) { 469 if (!TII->reverseBranchCondition(Cond)) { 470 TII->removeBranch(*CurMBB); 471 TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl); 472 return; 473 } 474 } 475 } 476 TII->insertBranch(*CurMBB, SuccBB, nullptr, 477 SmallVector<MachineOperand, 0>(), dl); 478 } 479 480 bool 481 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const { 482 if (getHash() < o.getHash()) 483 return true; 484 if (getHash() > o.getHash()) 485 return false; 486 if (getBlock()->getNumber() < o.getBlock()->getNumber()) 487 return true; 488 if (getBlock()->getNumber() > o.getBlock()->getNumber()) 489 return false; 490 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing 491 // an object with itself. 492 #ifndef _GLIBCXX_DEBUG 493 llvm_unreachable("Predecessor appears twice"); 494 #else 495 return false; 496 #endif 497 } 498 499 BlockFrequency 500 BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const { 501 auto I = MergedBBFreq.find(MBB); 502 503 if (I != MergedBBFreq.end()) 504 return I->second; 505 506 return MBFI.getBlockFreq(MBB); 507 } 508 509 void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB, 510 BlockFrequency F) { 511 MergedBBFreq[MBB] = F; 512 } 513 514 raw_ostream & 515 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS, 516 const MachineBasicBlock *MBB) const { 517 return MBFI.printBlockFreq(OS, getBlockFreq(MBB)); 518 } 519 520 raw_ostream & 521 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS, 522 const BlockFrequency Freq) const { 523 return MBFI.printBlockFreq(OS, Freq); 524 } 525 526 void BranchFolder::MBFIWrapper::view(const Twine &Name, bool isSimple) { 527 MBFI.view(Name, isSimple); 528 } 529 530 uint64_t 531 BranchFolder::MBFIWrapper::getEntryFreq() const { 532 return MBFI.getEntryFreq(); 533 } 534 535 /// CountTerminators - Count the number of terminators in the given 536 /// block and set I to the position of the first non-terminator, if there 537 /// is one, or MBB->end() otherwise. 538 static unsigned CountTerminators(MachineBasicBlock *MBB, 539 MachineBasicBlock::iterator &I) { 540 I = MBB->end(); 541 unsigned NumTerms = 0; 542 while (true) { 543 if (I == MBB->begin()) { 544 I = MBB->end(); 545 break; 546 } 547 --I; 548 if (!I->isTerminator()) break; 549 ++NumTerms; 550 } 551 return NumTerms; 552 } 553 554 /// A no successor, non-return block probably ends in unreachable and is cold. 555 /// Also consider a block that ends in an indirect branch to be a return block, 556 /// since many targets use plain indirect branches to return. 557 static bool blockEndsInUnreachable(const MachineBasicBlock *MBB) { 558 if (!MBB->succ_empty()) 559 return false; 560 if (MBB->empty()) 561 return true; 562 return !(MBB->back().isReturn() || MBB->back().isIndirectBranch()); 563 } 564 565 /// ProfitableToMerge - Check if two machine basic blocks have a common tail 566 /// and decide if it would be profitable to merge those tails. Return the 567 /// length of the common tail and iterators to the first common instruction 568 /// in each block. 569 /// MBB1, MBB2 The blocks to check 570 /// MinCommonTailLength Minimum size of tail block to be merged. 571 /// CommonTailLen Out parameter to record the size of the shared tail between 572 /// MBB1 and MBB2 573 /// I1, I2 Iterator references that will be changed to point to the first 574 /// instruction in the common tail shared by MBB1,MBB2 575 /// SuccBB A common successor of MBB1, MBB2 which are in a canonical form 576 /// relative to SuccBB 577 /// PredBB The layout predecessor of SuccBB, if any. 578 /// EHScopeMembership map from block to EH scope #. 579 /// AfterPlacement True if we are merging blocks after layout. Stricter 580 /// thresholds apply to prevent undoing tail-duplication. 581 static bool 582 ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2, 583 unsigned MinCommonTailLength, unsigned &CommonTailLen, 584 MachineBasicBlock::iterator &I1, 585 MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB, 586 MachineBasicBlock *PredBB, 587 DenseMap<const MachineBasicBlock *, int> &EHScopeMembership, 588 bool AfterPlacement) { 589 // It is never profitable to tail-merge blocks from two different EH scopes. 590 if (!EHScopeMembership.empty()) { 591 auto EHScope1 = EHScopeMembership.find(MBB1); 592 assert(EHScope1 != EHScopeMembership.end()); 593 auto EHScope2 = EHScopeMembership.find(MBB2); 594 assert(EHScope2 != EHScopeMembership.end()); 595 if (EHScope1->second != EHScope2->second) 596 return false; 597 } 598 599 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2); 600 if (CommonTailLen == 0) 601 return false; 602 LLVM_DEBUG(dbgs() << "Common tail length of " << printMBBReference(*MBB1) 603 << " and " << printMBBReference(*MBB2) << " is " 604 << CommonTailLen << '\n'); 605 606 // Move the iterators to the beginning of the MBB if we only got debug 607 // instructions before the tail. This is to avoid splitting a block when we 608 // only got debug instructions before the tail (to be invariant on -g). 609 if (skipDebugInstructionsForward(MBB1->begin(), MBB1->end()) == I1) 610 I1 = MBB1->begin(); 611 if (skipDebugInstructionsForward(MBB2->begin(), MBB2->end()) == I2) 612 I2 = MBB2->begin(); 613 614 bool FullBlockTail1 = I1 == MBB1->begin(); 615 bool FullBlockTail2 = I2 == MBB2->begin(); 616 617 // It's almost always profitable to merge any number of non-terminator 618 // instructions with the block that falls through into the common successor. 619 // This is true only for a single successor. For multiple successors, we are 620 // trading a conditional branch for an unconditional one. 621 // TODO: Re-visit successor size for non-layout tail merging. 622 if ((MBB1 == PredBB || MBB2 == PredBB) && 623 (!AfterPlacement || MBB1->succ_size() == 1)) { 624 MachineBasicBlock::iterator I; 625 unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I); 626 if (CommonTailLen > NumTerms) 627 return true; 628 } 629 630 // If these are identical non-return blocks with no successors, merge them. 631 // Such blocks are typically cold calls to noreturn functions like abort, and 632 // are unlikely to become a fallthrough target after machine block placement. 633 // Tail merging these blocks is unlikely to create additional unconditional 634 // branches, and will reduce the size of this cold code. 635 if (FullBlockTail1 && FullBlockTail2 && 636 blockEndsInUnreachable(MBB1) && blockEndsInUnreachable(MBB2)) 637 return true; 638 639 // If one of the blocks can be completely merged and happens to be in 640 // a position where the other could fall through into it, merge any number 641 // of instructions, because it can be done without a branch. 642 // TODO: If the blocks are not adjacent, move one of them so that they are? 643 if (MBB1->isLayoutSuccessor(MBB2) && FullBlockTail2) 644 return true; 645 if (MBB2->isLayoutSuccessor(MBB1) && FullBlockTail1) 646 return true; 647 648 // If both blocks are identical and end in a branch, merge them unless they 649 // both have a fallthrough predecessor and successor. 650 // We can only do this after block placement because it depends on whether 651 // there are fallthroughs, and we don't know until after layout. 652 if (AfterPlacement && FullBlockTail1 && FullBlockTail2) { 653 auto BothFallThrough = [](MachineBasicBlock *MBB) { 654 if (MBB->succ_size() != 0 && !MBB->canFallThrough()) 655 return false; 656 MachineFunction::iterator I(MBB); 657 MachineFunction *MF = MBB->getParent(); 658 return (MBB != &*MF->begin()) && std::prev(I)->canFallThrough(); 659 }; 660 if (!BothFallThrough(MBB1) || !BothFallThrough(MBB2)) 661 return true; 662 } 663 664 // If both blocks have an unconditional branch temporarily stripped out, 665 // count that as an additional common instruction for the following 666 // heuristics. This heuristic is only accurate for single-succ blocks, so to 667 // make sure that during layout merging and duplicating don't crash, we check 668 // for that when merging during layout. 669 unsigned EffectiveTailLen = CommonTailLen; 670 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB && 671 (MBB1->succ_size() == 1 || !AfterPlacement) && 672 !MBB1->back().isBarrier() && 673 !MBB2->back().isBarrier()) 674 ++EffectiveTailLen; 675 676 // Check if the common tail is long enough to be worthwhile. 677 if (EffectiveTailLen >= MinCommonTailLength) 678 return true; 679 680 // If we are optimizing for code size, 2 instructions in common is enough if 681 // we don't have to split a block. At worst we will be introducing 1 new 682 // branch instruction, which is likely to be smaller than the 2 683 // instructions that would be deleted in the merge. 684 MachineFunction *MF = MBB1->getParent(); 685 return EffectiveTailLen >= 2 && MF->getFunction().hasOptSize() && 686 (FullBlockTail1 || FullBlockTail2); 687 } 688 689 unsigned BranchFolder::ComputeSameTails(unsigned CurHash, 690 unsigned MinCommonTailLength, 691 MachineBasicBlock *SuccBB, 692 MachineBasicBlock *PredBB) { 693 unsigned maxCommonTailLength = 0U; 694 SameTails.clear(); 695 MachineBasicBlock::iterator TrialBBI1, TrialBBI2; 696 MPIterator HighestMPIter = std::prev(MergePotentials.end()); 697 for (MPIterator CurMPIter = std::prev(MergePotentials.end()), 698 B = MergePotentials.begin(); 699 CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) { 700 for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) { 701 unsigned CommonTailLen; 702 if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(), 703 MinCommonTailLength, 704 CommonTailLen, TrialBBI1, TrialBBI2, 705 SuccBB, PredBB, 706 EHScopeMembership, 707 AfterBlockPlacement)) { 708 if (CommonTailLen > maxCommonTailLength) { 709 SameTails.clear(); 710 maxCommonTailLength = CommonTailLen; 711 HighestMPIter = CurMPIter; 712 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1)); 713 } 714 if (HighestMPIter == CurMPIter && 715 CommonTailLen == maxCommonTailLength) 716 SameTails.push_back(SameTailElt(I, TrialBBI2)); 717 } 718 if (I == B) 719 break; 720 } 721 } 722 return maxCommonTailLength; 723 } 724 725 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash, 726 MachineBasicBlock *SuccBB, 727 MachineBasicBlock *PredBB) { 728 MPIterator CurMPIter, B; 729 for (CurMPIter = std::prev(MergePotentials.end()), 730 B = MergePotentials.begin(); 731 CurMPIter->getHash() == CurHash; --CurMPIter) { 732 // Put the unconditional branch back, if we need one. 733 MachineBasicBlock *CurMBB = CurMPIter->getBlock(); 734 if (SuccBB && CurMBB != PredBB) 735 FixTail(CurMBB, SuccBB, TII); 736 if (CurMPIter == B) 737 break; 738 } 739 if (CurMPIter->getHash() != CurHash) 740 CurMPIter++; 741 MergePotentials.erase(CurMPIter, MergePotentials.end()); 742 } 743 744 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB, 745 MachineBasicBlock *SuccBB, 746 unsigned maxCommonTailLength, 747 unsigned &commonTailIndex) { 748 commonTailIndex = 0; 749 unsigned TimeEstimate = ~0U; 750 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) { 751 // Use PredBB if possible; that doesn't require a new branch. 752 if (SameTails[i].getBlock() == PredBB) { 753 commonTailIndex = i; 754 break; 755 } 756 // Otherwise, make a (fairly bogus) choice based on estimate of 757 // how long it will take the various blocks to execute. 758 unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(), 759 SameTails[i].getTailStartPos()); 760 if (t <= TimeEstimate) { 761 TimeEstimate = t; 762 commonTailIndex = i; 763 } 764 } 765 766 MachineBasicBlock::iterator BBI = 767 SameTails[commonTailIndex].getTailStartPos(); 768 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock(); 769 770 LLVM_DEBUG(dbgs() << "\nSplitting " << printMBBReference(*MBB) << ", size " 771 << maxCommonTailLength); 772 773 // If the split block unconditionally falls-thru to SuccBB, it will be 774 // merged. In control flow terms it should then take SuccBB's name. e.g. If 775 // SuccBB is an inner loop, the common tail is still part of the inner loop. 776 const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ? 777 SuccBB->getBasicBlock() : MBB->getBasicBlock(); 778 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB); 779 if (!newMBB) { 780 LLVM_DEBUG(dbgs() << "... failed!"); 781 return false; 782 } 783 784 SameTails[commonTailIndex].setBlock(newMBB); 785 SameTails[commonTailIndex].setTailStartPos(newMBB->begin()); 786 787 // If we split PredBB, newMBB is the new predecessor. 788 if (PredBB == MBB) 789 PredBB = newMBB; 790 791 return true; 792 } 793 794 static void 795 mergeOperations(MachineBasicBlock::iterator MBBIStartPos, 796 MachineBasicBlock &MBBCommon) { 797 MachineBasicBlock *MBB = MBBIStartPos->getParent(); 798 // Note CommonTailLen does not necessarily matches the size of 799 // the common BB nor all its instructions because of debug 800 // instructions differences. 801 unsigned CommonTailLen = 0; 802 for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos) 803 ++CommonTailLen; 804 805 MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin(); 806 MachineBasicBlock::reverse_iterator MBBIE = MBB->rend(); 807 MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin(); 808 MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend(); 809 810 while (CommonTailLen--) { 811 assert(MBBI != MBBIE && "Reached BB end within common tail length!"); 812 (void)MBBIE; 813 814 if (!countsAsInstruction(*MBBI)) { 815 ++MBBI; 816 continue; 817 } 818 819 while ((MBBICommon != MBBIECommon) && !countsAsInstruction(*MBBICommon)) 820 ++MBBICommon; 821 822 assert(MBBICommon != MBBIECommon && 823 "Reached BB end within common tail length!"); 824 assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!"); 825 826 // Merge MMOs from memory operations in the common block. 827 if (MBBICommon->mayLoad() || MBBICommon->mayStore()) 828 MBBICommon->cloneMergedMemRefs(*MBB->getParent(), {&*MBBICommon, &*MBBI}); 829 // Drop undef flags if they aren't present in all merged instructions. 830 for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; ++I) { 831 MachineOperand &MO = MBBICommon->getOperand(I); 832 if (MO.isReg() && MO.isUndef()) { 833 const MachineOperand &OtherMO = MBBI->getOperand(I); 834 if (!OtherMO.isUndef()) 835 MO.setIsUndef(false); 836 } 837 } 838 839 ++MBBI; 840 ++MBBICommon; 841 } 842 } 843 844 void BranchFolder::mergeCommonTails(unsigned commonTailIndex) { 845 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock(); 846 847 std::vector<MachineBasicBlock::iterator> NextCommonInsts(SameTails.size()); 848 for (unsigned int i = 0 ; i != SameTails.size() ; ++i) { 849 if (i != commonTailIndex) { 850 NextCommonInsts[i] = SameTails[i].getTailStartPos(); 851 mergeOperations(SameTails[i].getTailStartPos(), *MBB); 852 } else { 853 assert(SameTails[i].getTailStartPos() == MBB->begin() && 854 "MBB is not a common tail only block"); 855 } 856 } 857 858 for (auto &MI : *MBB) { 859 if (!countsAsInstruction(MI)) 860 continue; 861 DebugLoc DL = MI.getDebugLoc(); 862 for (unsigned int i = 0 ; i < NextCommonInsts.size() ; i++) { 863 if (i == commonTailIndex) 864 continue; 865 866 auto &Pos = NextCommonInsts[i]; 867 assert(Pos != SameTails[i].getBlock()->end() && 868 "Reached BB end within common tail"); 869 while (!countsAsInstruction(*Pos)) { 870 ++Pos; 871 assert(Pos != SameTails[i].getBlock()->end() && 872 "Reached BB end within common tail"); 873 } 874 assert(MI.isIdenticalTo(*Pos) && "Expected matching MIIs!"); 875 DL = DILocation::getMergedLocation(DL, Pos->getDebugLoc()); 876 NextCommonInsts[i] = ++Pos; 877 } 878 MI.setDebugLoc(DL); 879 } 880 881 if (UpdateLiveIns) { 882 LivePhysRegs NewLiveIns(*TRI); 883 computeLiveIns(NewLiveIns, *MBB); 884 LiveRegs.init(*TRI); 885 886 // The flag merging may lead to some register uses no longer using the 887 // <undef> flag, add IMPLICIT_DEFs in the predecessors as necessary. 888 for (MachineBasicBlock *Pred : MBB->predecessors()) { 889 LiveRegs.clear(); 890 LiveRegs.addLiveOuts(*Pred); 891 MachineBasicBlock::iterator InsertBefore = Pred->getFirstTerminator(); 892 for (unsigned Reg : NewLiveIns) { 893 if (!LiveRegs.available(*MRI, Reg)) 894 continue; 895 DebugLoc DL; 896 BuildMI(*Pred, InsertBefore, DL, TII->get(TargetOpcode::IMPLICIT_DEF), 897 Reg); 898 } 899 } 900 901 MBB->clearLiveIns(); 902 addLiveIns(*MBB, NewLiveIns); 903 } 904 } 905 906 // See if any of the blocks in MergePotentials (which all have SuccBB as a 907 // successor, or all have no successor if it is null) can be tail-merged. 908 // If there is a successor, any blocks in MergePotentials that are not 909 // tail-merged and are not immediately before Succ must have an unconditional 910 // branch to Succ added (but the predecessor/successor lists need no 911 // adjustment). The lone predecessor of Succ that falls through into Succ, 912 // if any, is given in PredBB. 913 // MinCommonTailLength - Except for the special cases below, tail-merge if 914 // there are at least this many instructions in common. 915 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB, 916 MachineBasicBlock *PredBB, 917 unsigned MinCommonTailLength) { 918 bool MadeChange = false; 919 920 LLVM_DEBUG( 921 dbgs() << "\nTryTailMergeBlocks: "; 922 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) dbgs() 923 << printMBBReference(*MergePotentials[i].getBlock()) 924 << (i == e - 1 ? "" : ", "); 925 dbgs() << "\n"; if (SuccBB) { 926 dbgs() << " with successor " << printMBBReference(*SuccBB) << '\n'; 927 if (PredBB) 928 dbgs() << " which has fall-through from " 929 << printMBBReference(*PredBB) << "\n"; 930 } dbgs() << "Looking for common tails of at least " 931 << MinCommonTailLength << " instruction" 932 << (MinCommonTailLength == 1 ? "" : "s") << '\n';); 933 934 // Sort by hash value so that blocks with identical end sequences sort 935 // together. 936 array_pod_sort(MergePotentials.begin(), MergePotentials.end()); 937 938 // Walk through equivalence sets looking for actual exact matches. 939 while (MergePotentials.size() > 1) { 940 unsigned CurHash = MergePotentials.back().getHash(); 941 942 // Build SameTails, identifying the set of blocks with this hash code 943 // and with the maximum number of instructions in common. 944 unsigned maxCommonTailLength = ComputeSameTails(CurHash, 945 MinCommonTailLength, 946 SuccBB, PredBB); 947 948 // If we didn't find any pair that has at least MinCommonTailLength 949 // instructions in common, remove all blocks with this hash code and retry. 950 if (SameTails.empty()) { 951 RemoveBlocksWithHash(CurHash, SuccBB, PredBB); 952 continue; 953 } 954 955 // If one of the blocks is the entire common tail (and not the entry 956 // block, which we can't jump to), we can treat all blocks with this same 957 // tail at once. Use PredBB if that is one of the possibilities, as that 958 // will not introduce any extra branches. 959 MachineBasicBlock *EntryBB = 960 &MergePotentials.front().getBlock()->getParent()->front(); 961 unsigned commonTailIndex = SameTails.size(); 962 // If there are two blocks, check to see if one can be made to fall through 963 // into the other. 964 if (SameTails.size() == 2 && 965 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) && 966 SameTails[1].tailIsWholeBlock()) 967 commonTailIndex = 1; 968 else if (SameTails.size() == 2 && 969 SameTails[1].getBlock()->isLayoutSuccessor( 970 SameTails[0].getBlock()) && 971 SameTails[0].tailIsWholeBlock()) 972 commonTailIndex = 0; 973 else { 974 // Otherwise just pick one, favoring the fall-through predecessor if 975 // there is one. 976 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) { 977 MachineBasicBlock *MBB = SameTails[i].getBlock(); 978 if (MBB == EntryBB && SameTails[i].tailIsWholeBlock()) 979 continue; 980 if (MBB == PredBB) { 981 commonTailIndex = i; 982 break; 983 } 984 if (SameTails[i].tailIsWholeBlock()) 985 commonTailIndex = i; 986 } 987 } 988 989 if (commonTailIndex == SameTails.size() || 990 (SameTails[commonTailIndex].getBlock() == PredBB && 991 !SameTails[commonTailIndex].tailIsWholeBlock())) { 992 // None of the blocks consist entirely of the common tail. 993 // Split a block so that one does. 994 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB, 995 maxCommonTailLength, commonTailIndex)) { 996 RemoveBlocksWithHash(CurHash, SuccBB, PredBB); 997 continue; 998 } 999 } 1000 1001 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock(); 1002 1003 // Recompute common tail MBB's edge weights and block frequency. 1004 setCommonTailEdgeWeights(*MBB); 1005 1006 // Merge debug locations, MMOs and undef flags across identical instructions 1007 // for common tail. 1008 mergeCommonTails(commonTailIndex); 1009 1010 // MBB is common tail. Adjust all other BB's to jump to this one. 1011 // Traversal must be forwards so erases work. 1012 LLVM_DEBUG(dbgs() << "\nUsing common tail in " << printMBBReference(*MBB) 1013 << " for "); 1014 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) { 1015 if (commonTailIndex == i) 1016 continue; 1017 LLVM_DEBUG(dbgs() << printMBBReference(*SameTails[i].getBlock()) 1018 << (i == e - 1 ? "" : ", ")); 1019 // Hack the end off BB i, making it jump to BB commonTailIndex instead. 1020 replaceTailWithBranchTo(SameTails[i].getTailStartPos(), *MBB); 1021 // BB i is no longer a predecessor of SuccBB; remove it from the worklist. 1022 MergePotentials.erase(SameTails[i].getMPIter()); 1023 } 1024 LLVM_DEBUG(dbgs() << "\n"); 1025 // We leave commonTailIndex in the worklist in case there are other blocks 1026 // that match it with a smaller number of instructions. 1027 MadeChange = true; 1028 } 1029 return MadeChange; 1030 } 1031 1032 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) { 1033 bool MadeChange = false; 1034 if (!EnableTailMerge) 1035 return MadeChange; 1036 1037 // First find blocks with no successors. 1038 // Block placement may create new tail merging opportunities for these blocks. 1039 MergePotentials.clear(); 1040 for (MachineBasicBlock &MBB : MF) { 1041 if (MergePotentials.size() == TailMergeThreshold) 1042 break; 1043 if (!TriedMerging.count(&MBB) && MBB.succ_empty()) 1044 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB)); 1045 } 1046 1047 // If this is a large problem, avoid visiting the same basic blocks 1048 // multiple times. 1049 if (MergePotentials.size() == TailMergeThreshold) 1050 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) 1051 TriedMerging.insert(MergePotentials[i].getBlock()); 1052 1053 // See if we can do any tail merging on those. 1054 if (MergePotentials.size() >= 2) 1055 MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength); 1056 1057 // Look at blocks (IBB) with multiple predecessors (PBB). 1058 // We change each predecessor to a canonical form, by 1059 // (1) temporarily removing any unconditional branch from the predecessor 1060 // to IBB, and 1061 // (2) alter conditional branches so they branch to the other block 1062 // not IBB; this may require adding back an unconditional branch to IBB 1063 // later, where there wasn't one coming in. E.g. 1064 // Bcc IBB 1065 // fallthrough to QBB 1066 // here becomes 1067 // Bncc QBB 1068 // with a conceptual B to IBB after that, which never actually exists. 1069 // With those changes, we see whether the predecessors' tails match, 1070 // and merge them if so. We change things out of canonical form and 1071 // back to the way they were later in the process. (OptimizeBranches 1072 // would undo some of this, but we can't use it, because we'd get into 1073 // a compile-time infinite loop repeatedly doing and undoing the same 1074 // transformations.) 1075 1076 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end(); 1077 I != E; ++I) { 1078 if (I->pred_size() < 2) continue; 1079 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds; 1080 MachineBasicBlock *IBB = &*I; 1081 MachineBasicBlock *PredBB = &*std::prev(I); 1082 MergePotentials.clear(); 1083 MachineLoop *ML; 1084 1085 // Bail if merging after placement and IBB is the loop header because 1086 // -- If merging predecessors that belong to the same loop as IBB, the 1087 // common tail of merged predecessors may become the loop top if block 1088 // placement is called again and the predecessors may branch to this common 1089 // tail and require more branches. This can be relaxed if 1090 // MachineBlockPlacement::findBestLoopTop is more flexible. 1091 // --If merging predecessors that do not belong to the same loop as IBB, the 1092 // loop info of IBB's loop and the other loops may be affected. Calling the 1093 // block placement again may make big change to the layout and eliminate the 1094 // reason to do tail merging here. 1095 if (AfterBlockPlacement && MLI) { 1096 ML = MLI->getLoopFor(IBB); 1097 if (ML && IBB == ML->getHeader()) 1098 continue; 1099 } 1100 1101 for (MachineBasicBlock *PBB : I->predecessors()) { 1102 if (MergePotentials.size() == TailMergeThreshold) 1103 break; 1104 1105 if (TriedMerging.count(PBB)) 1106 continue; 1107 1108 // Skip blocks that loop to themselves, can't tail merge these. 1109 if (PBB == IBB) 1110 continue; 1111 1112 // Visit each predecessor only once. 1113 if (!UniquePreds.insert(PBB).second) 1114 continue; 1115 1116 // Skip blocks which may jump to a landing pad. Can't tail merge these. 1117 if (PBB->hasEHPadSuccessor()) 1118 continue; 1119 1120 // After block placement, only consider predecessors that belong to the 1121 // same loop as IBB. The reason is the same as above when skipping loop 1122 // header. 1123 if (AfterBlockPlacement && MLI) 1124 if (ML != MLI->getLoopFor(PBB)) 1125 continue; 1126 1127 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1128 SmallVector<MachineOperand, 4> Cond; 1129 if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) { 1130 // Failing case: IBB is the target of a cbr, and we cannot reverse the 1131 // branch. 1132 SmallVector<MachineOperand, 4> NewCond(Cond); 1133 if (!Cond.empty() && TBB == IBB) { 1134 if (TII->reverseBranchCondition(NewCond)) 1135 continue; 1136 // This is the QBB case described above 1137 if (!FBB) { 1138 auto Next = ++PBB->getIterator(); 1139 if (Next != MF.end()) 1140 FBB = &*Next; 1141 } 1142 } 1143 1144 // Remove the unconditional branch at the end, if any. 1145 if (TBB && (Cond.empty() || FBB)) { 1146 DebugLoc dl = PBB->findBranchDebugLoc(); 1147 TII->removeBranch(*PBB); 1148 if (!Cond.empty()) 1149 // reinsert conditional branch only, for now 1150 TII->insertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr, 1151 NewCond, dl); 1152 } 1153 1154 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(*PBB), PBB)); 1155 } 1156 } 1157 1158 // If this is a large problem, avoid visiting the same basic blocks multiple 1159 // times. 1160 if (MergePotentials.size() == TailMergeThreshold) 1161 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) 1162 TriedMerging.insert(MergePotentials[i].getBlock()); 1163 1164 if (MergePotentials.size() >= 2) 1165 MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength); 1166 1167 // Reinsert an unconditional branch if needed. The 1 below can occur as a 1168 // result of removing blocks in TryTailMergeBlocks. 1169 PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks 1170 if (MergePotentials.size() == 1 && 1171 MergePotentials.begin()->getBlock() != PredBB) 1172 FixTail(MergePotentials.begin()->getBlock(), IBB, TII); 1173 } 1174 1175 return MadeChange; 1176 } 1177 1178 void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) { 1179 SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size()); 1180 BlockFrequency AccumulatedMBBFreq; 1181 1182 // Aggregate edge frequency of successor edge j: 1183 // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)), 1184 // where bb is a basic block that is in SameTails. 1185 for (const auto &Src : SameTails) { 1186 const MachineBasicBlock *SrcMBB = Src.getBlock(); 1187 BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB); 1188 AccumulatedMBBFreq += BlockFreq; 1189 1190 // It is not necessary to recompute edge weights if TailBB has less than two 1191 // successors. 1192 if (TailMBB.succ_size() <= 1) 1193 continue; 1194 1195 auto EdgeFreq = EdgeFreqLs.begin(); 1196 1197 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end(); 1198 SuccI != SuccE; ++SuccI, ++EdgeFreq) 1199 *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI); 1200 } 1201 1202 MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq); 1203 1204 if (TailMBB.succ_size() <= 1) 1205 return; 1206 1207 auto SumEdgeFreq = 1208 std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0)) 1209 .getFrequency(); 1210 auto EdgeFreq = EdgeFreqLs.begin(); 1211 1212 if (SumEdgeFreq > 0) { 1213 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end(); 1214 SuccI != SuccE; ++SuccI, ++EdgeFreq) { 1215 auto Prob = BranchProbability::getBranchProbability( 1216 EdgeFreq->getFrequency(), SumEdgeFreq); 1217 TailMBB.setSuccProbability(SuccI, Prob); 1218 } 1219 } 1220 } 1221 1222 //===----------------------------------------------------------------------===// 1223 // Branch Optimization 1224 //===----------------------------------------------------------------------===// 1225 1226 bool BranchFolder::OptimizeBranches(MachineFunction &MF) { 1227 bool MadeChange = false; 1228 1229 // Make sure blocks are numbered in order 1230 MF.RenumberBlocks(); 1231 // Renumbering blocks alters EH scope membership, recalculate it. 1232 EHScopeMembership = getEHScopeMembership(MF); 1233 1234 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end(); 1235 I != E; ) { 1236 MachineBasicBlock *MBB = &*I++; 1237 MadeChange |= OptimizeBlock(MBB); 1238 1239 // If it is dead, remove it. 1240 if (MBB->pred_empty()) { 1241 RemoveDeadBlock(MBB); 1242 MadeChange = true; 1243 ++NumDeadBlocks; 1244 } 1245 } 1246 1247 return MadeChange; 1248 } 1249 1250 // Blocks should be considered empty if they contain only debug info; 1251 // else the debug info would affect codegen. 1252 static bool IsEmptyBlock(MachineBasicBlock *MBB) { 1253 return MBB->getFirstNonDebugInstr() == MBB->end(); 1254 } 1255 1256 // Blocks with only debug info and branches should be considered the same 1257 // as blocks with only branches. 1258 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) { 1259 MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr(); 1260 assert(I != MBB->end() && "empty block!"); 1261 return I->isBranch(); 1262 } 1263 1264 /// IsBetterFallthrough - Return true if it would be clearly better to 1265 /// fall-through to MBB1 than to fall through into MBB2. This has to return 1266 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will 1267 /// result in infinite loops. 1268 static bool IsBetterFallthrough(MachineBasicBlock *MBB1, 1269 MachineBasicBlock *MBB2) { 1270 assert(MBB1 && MBB2 && "Unknown MachineBasicBlock"); 1271 1272 // Right now, we use a simple heuristic. If MBB2 ends with a call, and 1273 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to 1274 // optimize branches that branch to either a return block or an assert block 1275 // into a fallthrough to the return. 1276 MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr(); 1277 MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr(); 1278 if (MBB1I == MBB1->end() || MBB2I == MBB2->end()) 1279 return false; 1280 1281 // If there is a clear successor ordering we make sure that one block 1282 // will fall through to the next 1283 if (MBB1->isSuccessor(MBB2)) return true; 1284 if (MBB2->isSuccessor(MBB1)) return false; 1285 1286 return MBB2I->isCall() && !MBB1I->isCall(); 1287 } 1288 1289 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch 1290 /// instructions on the block. 1291 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) { 1292 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); 1293 if (I != MBB.end() && I->isBranch()) 1294 return I->getDebugLoc(); 1295 return DebugLoc(); 1296 } 1297 1298 static void copyDebugInfoToPredecessor(const TargetInstrInfo *TII, 1299 MachineBasicBlock &MBB, 1300 MachineBasicBlock &PredMBB) { 1301 auto InsertBefore = PredMBB.getFirstTerminator(); 1302 for (MachineInstr &MI : MBB.instrs()) 1303 if (MI.isDebugInstr()) { 1304 TII->duplicate(PredMBB, InsertBefore, MI); 1305 LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to pred: " 1306 << MI); 1307 } 1308 } 1309 1310 static void copyDebugInfoToSuccessor(const TargetInstrInfo *TII, 1311 MachineBasicBlock &MBB, 1312 MachineBasicBlock &SuccMBB) { 1313 auto InsertBefore = SuccMBB.SkipPHIsAndLabels(SuccMBB.begin()); 1314 for (MachineInstr &MI : MBB.instrs()) 1315 if (MI.isDebugInstr()) { 1316 TII->duplicate(SuccMBB, InsertBefore, MI); 1317 LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to succ: " 1318 << MI); 1319 } 1320 } 1321 1322 // Try to salvage DBG_VALUE instructions from an otherwise empty block. If such 1323 // a basic block is removed we would lose the debug information unless we have 1324 // copied the information to a predecessor/successor. 1325 // 1326 // TODO: This function only handles some simple cases. An alternative would be 1327 // to run a heavier analysis, such as the LiveDebugValues pass, before we do 1328 // branch folding. 1329 static void salvageDebugInfoFromEmptyBlock(const TargetInstrInfo *TII, 1330 MachineBasicBlock &MBB) { 1331 assert(IsEmptyBlock(&MBB) && "Expected an empty block (except debug info)."); 1332 // If this MBB is the only predecessor of a successor it is legal to copy 1333 // DBG_VALUE instructions to the beginning of the successor. 1334 for (MachineBasicBlock *SuccBB : MBB.successors()) 1335 if (SuccBB->pred_size() == 1) 1336 copyDebugInfoToSuccessor(TII, MBB, *SuccBB); 1337 // If this MBB is the only successor of a predecessor it is legal to copy the 1338 // DBG_VALUE instructions to the end of the predecessor (just before the 1339 // terminators, assuming that the terminator isn't affecting the DBG_VALUE). 1340 for (MachineBasicBlock *PredBB : MBB.predecessors()) 1341 if (PredBB->succ_size() == 1) 1342 copyDebugInfoToPredecessor(TII, MBB, *PredBB); 1343 } 1344 1345 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) { 1346 bool MadeChange = false; 1347 MachineFunction &MF = *MBB->getParent(); 1348 ReoptimizeBlock: 1349 1350 MachineFunction::iterator FallThrough = MBB->getIterator(); 1351 ++FallThrough; 1352 1353 // Make sure MBB and FallThrough belong to the same EH scope. 1354 bool SameEHScope = true; 1355 if (!EHScopeMembership.empty() && FallThrough != MF.end()) { 1356 auto MBBEHScope = EHScopeMembership.find(MBB); 1357 assert(MBBEHScope != EHScopeMembership.end()); 1358 auto FallThroughEHScope = EHScopeMembership.find(&*FallThrough); 1359 assert(FallThroughEHScope != EHScopeMembership.end()); 1360 SameEHScope = MBBEHScope->second == FallThroughEHScope->second; 1361 } 1362 1363 // If this block is empty, make everyone use its fall-through, not the block 1364 // explicitly. Landing pads should not do this since the landing-pad table 1365 // points to this block. Blocks with their addresses taken shouldn't be 1366 // optimized away. 1367 if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() && 1368 SameEHScope) { 1369 salvageDebugInfoFromEmptyBlock(TII, *MBB); 1370 // Dead block? Leave for cleanup later. 1371 if (MBB->pred_empty()) return MadeChange; 1372 1373 if (FallThrough == MF.end()) { 1374 // TODO: Simplify preds to not branch here if possible! 1375 } else if (FallThrough->isEHPad()) { 1376 // Don't rewrite to a landing pad fallthough. That could lead to the case 1377 // where a BB jumps to more than one landing pad. 1378 // TODO: Is it ever worth rewriting predecessors which don't already 1379 // jump to a landing pad, and so can safely jump to the fallthrough? 1380 } else if (MBB->isSuccessor(&*FallThrough)) { 1381 // Rewrite all predecessors of the old block to go to the fallthrough 1382 // instead. 1383 while (!MBB->pred_empty()) { 1384 MachineBasicBlock *Pred = *(MBB->pred_end()-1); 1385 Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough); 1386 } 1387 // If MBB was the target of a jump table, update jump tables to go to the 1388 // fallthrough instead. 1389 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo()) 1390 MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough); 1391 MadeChange = true; 1392 } 1393 return MadeChange; 1394 } 1395 1396 // Check to see if we can simplify the terminator of the block before this 1397 // one. 1398 MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB)); 1399 1400 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr; 1401 SmallVector<MachineOperand, 4> PriorCond; 1402 bool PriorUnAnalyzable = 1403 TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true); 1404 if (!PriorUnAnalyzable) { 1405 // If the CFG for the prior block has extra edges, remove them. 1406 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB, 1407 !PriorCond.empty()); 1408 1409 // If the previous branch is conditional and both conditions go to the same 1410 // destination, remove the branch, replacing it with an unconditional one or 1411 // a fall-through. 1412 if (PriorTBB && PriorTBB == PriorFBB) { 1413 DebugLoc dl = getBranchDebugLoc(PrevBB); 1414 TII->removeBranch(PrevBB); 1415 PriorCond.clear(); 1416 if (PriorTBB != MBB) 1417 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl); 1418 MadeChange = true; 1419 ++NumBranchOpts; 1420 goto ReoptimizeBlock; 1421 } 1422 1423 // If the previous block unconditionally falls through to this block and 1424 // this block has no other predecessors, move the contents of this block 1425 // into the prior block. This doesn't usually happen when SimplifyCFG 1426 // has been used, but it can happen if tail merging splits a fall-through 1427 // predecessor of a block. 1428 // This has to check PrevBB->succ_size() because EH edges are ignored by 1429 // AnalyzeBranch. 1430 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 && 1431 PrevBB.succ_size() == 1 && 1432 !MBB->hasAddressTaken() && !MBB->isEHPad()) { 1433 LLVM_DEBUG(dbgs() << "\nMerging into block: " << PrevBB 1434 << "From MBB: " << *MBB); 1435 // Remove redundant DBG_VALUEs first. 1436 if (PrevBB.begin() != PrevBB.end()) { 1437 MachineBasicBlock::iterator PrevBBIter = PrevBB.end(); 1438 --PrevBBIter; 1439 MachineBasicBlock::iterator MBBIter = MBB->begin(); 1440 // Check if DBG_VALUE at the end of PrevBB is identical to the 1441 // DBG_VALUE at the beginning of MBB. 1442 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end() 1443 && PrevBBIter->isDebugInstr() && MBBIter->isDebugInstr()) { 1444 if (!MBBIter->isIdenticalTo(*PrevBBIter)) 1445 break; 1446 MachineInstr &DuplicateDbg = *MBBIter; 1447 ++MBBIter; -- PrevBBIter; 1448 DuplicateDbg.eraseFromParent(); 1449 } 1450 } 1451 PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end()); 1452 PrevBB.removeSuccessor(PrevBB.succ_begin()); 1453 assert(PrevBB.succ_empty()); 1454 PrevBB.transferSuccessors(MBB); 1455 MadeChange = true; 1456 return MadeChange; 1457 } 1458 1459 // If the previous branch *only* branches to *this* block (conditional or 1460 // not) remove the branch. 1461 if (PriorTBB == MBB && !PriorFBB) { 1462 TII->removeBranch(PrevBB); 1463 MadeChange = true; 1464 ++NumBranchOpts; 1465 goto ReoptimizeBlock; 1466 } 1467 1468 // If the prior block branches somewhere else on the condition and here if 1469 // the condition is false, remove the uncond second branch. 1470 if (PriorFBB == MBB) { 1471 DebugLoc dl = getBranchDebugLoc(PrevBB); 1472 TII->removeBranch(PrevBB); 1473 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl); 1474 MadeChange = true; 1475 ++NumBranchOpts; 1476 goto ReoptimizeBlock; 1477 } 1478 1479 // If the prior block branches here on true and somewhere else on false, and 1480 // if the branch condition is reversible, reverse the branch to create a 1481 // fall-through. 1482 if (PriorTBB == MBB) { 1483 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond); 1484 if (!TII->reverseBranchCondition(NewPriorCond)) { 1485 DebugLoc dl = getBranchDebugLoc(PrevBB); 1486 TII->removeBranch(PrevBB); 1487 TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl); 1488 MadeChange = true; 1489 ++NumBranchOpts; 1490 goto ReoptimizeBlock; 1491 } 1492 } 1493 1494 // If this block has no successors (e.g. it is a return block or ends with 1495 // a call to a no-return function like abort or __cxa_throw) and if the pred 1496 // falls through into this block, and if it would otherwise fall through 1497 // into the block after this, move this block to the end of the function. 1498 // 1499 // We consider it more likely that execution will stay in the function (e.g. 1500 // due to loops) than it is to exit it. This asserts in loops etc, moving 1501 // the assert condition out of the loop body. 1502 if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB && 1503 MachineFunction::iterator(PriorTBB) == FallThrough && 1504 !MBB->canFallThrough()) { 1505 bool DoTransform = true; 1506 1507 // We have to be careful that the succs of PredBB aren't both no-successor 1508 // blocks. If neither have successors and if PredBB is the second from 1509 // last block in the function, we'd just keep swapping the two blocks for 1510 // last. Only do the swap if one is clearly better to fall through than 1511 // the other. 1512 if (FallThrough == --MF.end() && 1513 !IsBetterFallthrough(PriorTBB, MBB)) 1514 DoTransform = false; 1515 1516 if (DoTransform) { 1517 // Reverse the branch so we will fall through on the previous true cond. 1518 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond); 1519 if (!TII->reverseBranchCondition(NewPriorCond)) { 1520 LLVM_DEBUG(dbgs() << "\nMoving MBB: " << *MBB 1521 << "To make fallthrough to: " << *PriorTBB << "\n"); 1522 1523 DebugLoc dl = getBranchDebugLoc(PrevBB); 1524 TII->removeBranch(PrevBB); 1525 TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl); 1526 1527 // Move this block to the end of the function. 1528 MBB->moveAfter(&MF.back()); 1529 MadeChange = true; 1530 ++NumBranchOpts; 1531 return MadeChange; 1532 } 1533 } 1534 } 1535 } 1536 1537 if (!IsEmptyBlock(MBB) && MBB->pred_size() == 1 && 1538 MF.getFunction().hasOptSize()) { 1539 // Changing "Jcc foo; foo: jmp bar;" into "Jcc bar;" might change the branch 1540 // direction, thereby defeating careful block placement and regressing 1541 // performance. Therefore, only consider this for optsize functions. 1542 MachineInstr &TailCall = *MBB->getFirstNonDebugInstr(); 1543 if (TII->isUnconditionalTailCall(TailCall)) { 1544 MachineBasicBlock *Pred = *MBB->pred_begin(); 1545 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 1546 SmallVector<MachineOperand, 4> PredCond; 1547 bool PredAnalyzable = 1548 !TII->analyzeBranch(*Pred, PredTBB, PredFBB, PredCond, true); 1549 1550 if (PredAnalyzable && !PredCond.empty() && PredTBB == MBB && 1551 PredTBB != PredFBB) { 1552 // The predecessor has a conditional branch to this block which consists 1553 // of only a tail call. Try to fold the tail call into the conditional 1554 // branch. 1555 if (TII->canMakeTailCallConditional(PredCond, TailCall)) { 1556 // TODO: It would be nice if analyzeBranch() could provide a pointer 1557 // to the branch instruction so replaceBranchWithTailCall() doesn't 1558 // have to search for it. 1559 TII->replaceBranchWithTailCall(*Pred, PredCond, TailCall); 1560 ++NumTailCalls; 1561 Pred->removeSuccessor(MBB); 1562 MadeChange = true; 1563 return MadeChange; 1564 } 1565 } 1566 // If the predecessor is falling through to this block, we could reverse 1567 // the branch condition and fold the tail call into that. However, after 1568 // that we might have to re-arrange the CFG to fall through to the other 1569 // block and there is a high risk of regressing code size rather than 1570 // improving it. 1571 } 1572 } 1573 1574 // Analyze the branch in the current block. 1575 MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr; 1576 SmallVector<MachineOperand, 4> CurCond; 1577 bool CurUnAnalyzable = 1578 TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true); 1579 if (!CurUnAnalyzable) { 1580 // If the CFG for the prior block has extra edges, remove them. 1581 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty()); 1582 1583 // If this is a two-way branch, and the FBB branches to this block, reverse 1584 // the condition so the single-basic-block loop is faster. Instead of: 1585 // Loop: xxx; jcc Out; jmp Loop 1586 // we want: 1587 // Loop: xxx; jncc Loop; jmp Out 1588 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) { 1589 SmallVector<MachineOperand, 4> NewCond(CurCond); 1590 if (!TII->reverseBranchCondition(NewCond)) { 1591 DebugLoc dl = getBranchDebugLoc(*MBB); 1592 TII->removeBranch(*MBB); 1593 TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, dl); 1594 MadeChange = true; 1595 ++NumBranchOpts; 1596 goto ReoptimizeBlock; 1597 } 1598 } 1599 1600 // If this branch is the only thing in its block, see if we can forward 1601 // other blocks across it. 1602 if (CurTBB && CurCond.empty() && !CurFBB && 1603 IsBranchOnlyBlock(MBB) && CurTBB != MBB && 1604 !MBB->hasAddressTaken() && !MBB->isEHPad()) { 1605 DebugLoc dl = getBranchDebugLoc(*MBB); 1606 // This block may contain just an unconditional branch. Because there can 1607 // be 'non-branch terminators' in the block, try removing the branch and 1608 // then seeing if the block is empty. 1609 TII->removeBranch(*MBB); 1610 // If the only things remaining in the block are debug info, remove these 1611 // as well, so this will behave the same as an empty block in non-debug 1612 // mode. 1613 if (IsEmptyBlock(MBB)) { 1614 // Make the block empty, losing the debug info (we could probably 1615 // improve this in some cases.) 1616 MBB->erase(MBB->begin(), MBB->end()); 1617 } 1618 // If this block is just an unconditional branch to CurTBB, we can 1619 // usually completely eliminate the block. The only case we cannot 1620 // completely eliminate the block is when the block before this one 1621 // falls through into MBB and we can't understand the prior block's branch 1622 // condition. 1623 if (MBB->empty()) { 1624 bool PredHasNoFallThrough = !PrevBB.canFallThrough(); 1625 if (PredHasNoFallThrough || !PriorUnAnalyzable || 1626 !PrevBB.isSuccessor(MBB)) { 1627 // If the prior block falls through into us, turn it into an 1628 // explicit branch to us to make updates simpler. 1629 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) && 1630 PriorTBB != MBB && PriorFBB != MBB) { 1631 if (!PriorTBB) { 1632 assert(PriorCond.empty() && !PriorFBB && 1633 "Bad branch analysis"); 1634 PriorTBB = MBB; 1635 } else { 1636 assert(!PriorFBB && "Machine CFG out of date!"); 1637 PriorFBB = MBB; 1638 } 1639 DebugLoc pdl = getBranchDebugLoc(PrevBB); 1640 TII->removeBranch(PrevBB); 1641 TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl); 1642 } 1643 1644 // Iterate through all the predecessors, revectoring each in-turn. 1645 size_t PI = 0; 1646 bool DidChange = false; 1647 bool HasBranchToSelf = false; 1648 while(PI != MBB->pred_size()) { 1649 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI); 1650 if (PMBB == MBB) { 1651 // If this block has an uncond branch to itself, leave it. 1652 ++PI; 1653 HasBranchToSelf = true; 1654 } else { 1655 DidChange = true; 1656 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB); 1657 // If this change resulted in PMBB ending in a conditional 1658 // branch where both conditions go to the same destination, 1659 // change this to an unconditional branch (and fix the CFG). 1660 MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr; 1661 SmallVector<MachineOperand, 4> NewCurCond; 1662 bool NewCurUnAnalyzable = TII->analyzeBranch( 1663 *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true); 1664 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) { 1665 DebugLoc pdl = getBranchDebugLoc(*PMBB); 1666 TII->removeBranch(*PMBB); 1667 NewCurCond.clear(); 1668 TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl); 1669 MadeChange = true; 1670 ++NumBranchOpts; 1671 PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false); 1672 } 1673 } 1674 } 1675 1676 // Change any jumptables to go to the new MBB. 1677 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo()) 1678 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB); 1679 if (DidChange) { 1680 ++NumBranchOpts; 1681 MadeChange = true; 1682 if (!HasBranchToSelf) return MadeChange; 1683 } 1684 } 1685 } 1686 1687 // Add the branch back if the block is more than just an uncond branch. 1688 TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, dl); 1689 } 1690 } 1691 1692 // If the prior block doesn't fall through into this block, and if this 1693 // block doesn't fall through into some other block, see if we can find a 1694 // place to move this block where a fall-through will happen. 1695 if (!PrevBB.canFallThrough()) { 1696 // Now we know that there was no fall-through into this block, check to 1697 // see if it has a fall-through into its successor. 1698 bool CurFallsThru = MBB->canFallThrough(); 1699 1700 if (!MBB->isEHPad()) { 1701 // Check all the predecessors of this block. If one of them has no fall 1702 // throughs, move this block right after it. 1703 for (MachineBasicBlock *PredBB : MBB->predecessors()) { 1704 // Analyze the branch at the end of the pred. 1705 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 1706 SmallVector<MachineOperand, 4> PredCond; 1707 if (PredBB != MBB && !PredBB->canFallThrough() && 1708 !TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) && 1709 (!CurFallsThru || !CurTBB || !CurFBB) && 1710 (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) { 1711 // If the current block doesn't fall through, just move it. 1712 // If the current block can fall through and does not end with a 1713 // conditional branch, we need to append an unconditional jump to 1714 // the (current) next block. To avoid a possible compile-time 1715 // infinite loop, move blocks only backward in this case. 1716 // Also, if there are already 2 branches here, we cannot add a third; 1717 // this means we have the case 1718 // Bcc next 1719 // B elsewhere 1720 // next: 1721 if (CurFallsThru) { 1722 MachineBasicBlock *NextBB = &*std::next(MBB->getIterator()); 1723 CurCond.clear(); 1724 TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc()); 1725 } 1726 MBB->moveAfter(PredBB); 1727 MadeChange = true; 1728 goto ReoptimizeBlock; 1729 } 1730 } 1731 } 1732 1733 if (!CurFallsThru) { 1734 // Check all successors to see if we can move this block before it. 1735 for (MachineBasicBlock *SuccBB : MBB->successors()) { 1736 // Analyze the branch at the end of the block before the succ. 1737 MachineFunction::iterator SuccPrev = --SuccBB->getIterator(); 1738 1739 // If this block doesn't already fall-through to that successor, and if 1740 // the succ doesn't already have a block that can fall through into it, 1741 // and if the successor isn't an EH destination, we can arrange for the 1742 // fallthrough to happen. 1743 if (SuccBB != MBB && &*SuccPrev != MBB && 1744 !SuccPrev->canFallThrough() && !CurUnAnalyzable && 1745 !SuccBB->isEHPad()) { 1746 MBB->moveBefore(SuccBB); 1747 MadeChange = true; 1748 goto ReoptimizeBlock; 1749 } 1750 } 1751 1752 // Okay, there is no really great place to put this block. If, however, 1753 // the block before this one would be a fall-through if this block were 1754 // removed, move this block to the end of the function. There is no real 1755 // advantage in "falling through" to an EH block, so we don't want to 1756 // perform this transformation for that case. 1757 // 1758 // Also, Windows EH introduced the possibility of an arbitrary number of 1759 // successors to a given block. The analyzeBranch call does not consider 1760 // exception handling and so we can get in a state where a block 1761 // containing a call is followed by multiple EH blocks that would be 1762 // rotated infinitely at the end of the function if the transformation 1763 // below were performed for EH "FallThrough" blocks. Therefore, even if 1764 // that appears not to be happening anymore, we should assume that it is 1765 // possible and not remove the "!FallThrough()->isEHPad" condition below. 1766 MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr; 1767 SmallVector<MachineOperand, 4> PrevCond; 1768 if (FallThrough != MF.end() && 1769 !FallThrough->isEHPad() && 1770 !TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) && 1771 PrevBB.isSuccessor(&*FallThrough)) { 1772 MBB->moveAfter(&MF.back()); 1773 MadeChange = true; 1774 return MadeChange; 1775 } 1776 } 1777 } 1778 1779 return MadeChange; 1780 } 1781 1782 //===----------------------------------------------------------------------===// 1783 // Hoist Common Code 1784 //===----------------------------------------------------------------------===// 1785 1786 bool BranchFolder::HoistCommonCode(MachineFunction &MF) { 1787 bool MadeChange = false; 1788 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) { 1789 MachineBasicBlock *MBB = &*I++; 1790 MadeChange |= HoistCommonCodeInSuccs(MBB); 1791 } 1792 1793 return MadeChange; 1794 } 1795 1796 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given 1797 /// its 'true' successor. 1798 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB, 1799 MachineBasicBlock *TrueBB) { 1800 for (MachineBasicBlock *SuccBB : BB->successors()) 1801 if (SuccBB != TrueBB) 1802 return SuccBB; 1803 return nullptr; 1804 } 1805 1806 template <class Container> 1807 static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI, 1808 Container &Set) { 1809 if (Register::isPhysicalRegister(Reg)) { 1810 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) 1811 Set.insert(*AI); 1812 } else { 1813 Set.insert(Reg); 1814 } 1815 } 1816 1817 /// findHoistingInsertPosAndDeps - Find the location to move common instructions 1818 /// in successors to. The location is usually just before the terminator, 1819 /// however if the terminator is a conditional branch and its previous 1820 /// instruction is the flag setting instruction, the previous instruction is 1821 /// the preferred location. This function also gathers uses and defs of the 1822 /// instructions from the insertion point to the end of the block. The data is 1823 /// used by HoistCommonCodeInSuccs to ensure safety. 1824 static 1825 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB, 1826 const TargetInstrInfo *TII, 1827 const TargetRegisterInfo *TRI, 1828 SmallSet<unsigned,4> &Uses, 1829 SmallSet<unsigned,4> &Defs) { 1830 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator(); 1831 if (!TII->isUnpredicatedTerminator(*Loc)) 1832 return MBB->end(); 1833 1834 for (const MachineOperand &MO : Loc->operands()) { 1835 if (!MO.isReg()) 1836 continue; 1837 Register Reg = MO.getReg(); 1838 if (!Reg) 1839 continue; 1840 if (MO.isUse()) { 1841 addRegAndItsAliases(Reg, TRI, Uses); 1842 } else { 1843 if (!MO.isDead()) 1844 // Don't try to hoist code in the rare case the terminator defines a 1845 // register that is later used. 1846 return MBB->end(); 1847 1848 // If the terminator defines a register, make sure we don't hoist 1849 // the instruction whose def might be clobbered by the terminator. 1850 addRegAndItsAliases(Reg, TRI, Defs); 1851 } 1852 } 1853 1854 if (Uses.empty()) 1855 return Loc; 1856 // If the terminator is the only instruction in the block and Uses is not 1857 // empty (or we would have returned above), we can still safely hoist 1858 // instructions just before the terminator as long as the Defs/Uses are not 1859 // violated (which is checked in HoistCommonCodeInSuccs). 1860 if (Loc == MBB->begin()) 1861 return Loc; 1862 1863 // The terminator is probably a conditional branch, try not to separate the 1864 // branch from condition setting instruction. 1865 MachineBasicBlock::iterator PI = 1866 skipDebugInstructionsBackward(std::prev(Loc), MBB->begin()); 1867 1868 bool IsDef = false; 1869 for (const MachineOperand &MO : PI->operands()) { 1870 // If PI has a regmask operand, it is probably a call. Separate away. 1871 if (MO.isRegMask()) 1872 return Loc; 1873 if (!MO.isReg() || MO.isUse()) 1874 continue; 1875 Register Reg = MO.getReg(); 1876 if (!Reg) 1877 continue; 1878 if (Uses.count(Reg)) { 1879 IsDef = true; 1880 break; 1881 } 1882 } 1883 if (!IsDef) 1884 // The condition setting instruction is not just before the conditional 1885 // branch. 1886 return Loc; 1887 1888 // Be conservative, don't insert instruction above something that may have 1889 // side-effects. And since it's potentially bad to separate flag setting 1890 // instruction from the conditional branch, just abort the optimization 1891 // completely. 1892 // Also avoid moving code above predicated instruction since it's hard to 1893 // reason about register liveness with predicated instruction. 1894 bool DontMoveAcrossStore = true; 1895 if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(*PI)) 1896 return MBB->end(); 1897 1898 // Find out what registers are live. Note this routine is ignoring other live 1899 // registers which are only used by instructions in successor blocks. 1900 for (const MachineOperand &MO : PI->operands()) { 1901 if (!MO.isReg()) 1902 continue; 1903 Register Reg = MO.getReg(); 1904 if (!Reg) 1905 continue; 1906 if (MO.isUse()) { 1907 addRegAndItsAliases(Reg, TRI, Uses); 1908 } else { 1909 if (Uses.erase(Reg)) { 1910 if (Register::isPhysicalRegister(Reg)) { 1911 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) 1912 Uses.erase(*SubRegs); // Use sub-registers to be conservative 1913 } 1914 } 1915 addRegAndItsAliases(Reg, TRI, Defs); 1916 } 1917 } 1918 1919 return PI; 1920 } 1921 1922 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) { 1923 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1924 SmallVector<MachineOperand, 4> Cond; 1925 if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty()) 1926 return false; 1927 1928 if (!FBB) FBB = findFalseBlock(MBB, TBB); 1929 if (!FBB) 1930 // Malformed bcc? True and false blocks are the same? 1931 return false; 1932 1933 // Restrict the optimization to cases where MBB is the only predecessor, 1934 // it is an obvious win. 1935 if (TBB->pred_size() > 1 || FBB->pred_size() > 1) 1936 return false; 1937 1938 // Find a suitable position to hoist the common instructions to. Also figure 1939 // out which registers are used or defined by instructions from the insertion 1940 // point to the end of the block. 1941 SmallSet<unsigned, 4> Uses, Defs; 1942 MachineBasicBlock::iterator Loc = 1943 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs); 1944 if (Loc == MBB->end()) 1945 return false; 1946 1947 bool HasDups = false; 1948 SmallSet<unsigned, 4> ActiveDefsSet, AllDefsSet; 1949 MachineBasicBlock::iterator TIB = TBB->begin(); 1950 MachineBasicBlock::iterator FIB = FBB->begin(); 1951 MachineBasicBlock::iterator TIE = TBB->end(); 1952 MachineBasicBlock::iterator FIE = FBB->end(); 1953 while (TIB != TIE && FIB != FIE) { 1954 // Skip dbg_value instructions. These do not count. 1955 TIB = skipDebugInstructionsForward(TIB, TIE); 1956 FIB = skipDebugInstructionsForward(FIB, FIE); 1957 if (TIB == TIE || FIB == FIE) 1958 break; 1959 1960 if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead)) 1961 break; 1962 1963 if (TII->isPredicated(*TIB)) 1964 // Hard to reason about register liveness with predicated instruction. 1965 break; 1966 1967 bool IsSafe = true; 1968 for (MachineOperand &MO : TIB->operands()) { 1969 // Don't attempt to hoist instructions with register masks. 1970 if (MO.isRegMask()) { 1971 IsSafe = false; 1972 break; 1973 } 1974 if (!MO.isReg()) 1975 continue; 1976 Register Reg = MO.getReg(); 1977 if (!Reg) 1978 continue; 1979 if (MO.isDef()) { 1980 if (Uses.count(Reg)) { 1981 // Avoid clobbering a register that's used by the instruction at 1982 // the point of insertion. 1983 IsSafe = false; 1984 break; 1985 } 1986 1987 if (Defs.count(Reg) && !MO.isDead()) { 1988 // Don't hoist the instruction if the def would be clobber by the 1989 // instruction at the point insertion. FIXME: This is overly 1990 // conservative. It should be possible to hoist the instructions 1991 // in BB2 in the following example: 1992 // BB1: 1993 // r1, eflag = op1 r2, r3 1994 // brcc eflag 1995 // 1996 // BB2: 1997 // r1 = op2, ... 1998 // = op3, killed r1 1999 IsSafe = false; 2000 break; 2001 } 2002 } else if (!ActiveDefsSet.count(Reg)) { 2003 if (Defs.count(Reg)) { 2004 // Use is defined by the instruction at the point of insertion. 2005 IsSafe = false; 2006 break; 2007 } 2008 2009 if (MO.isKill() && Uses.count(Reg)) 2010 // Kills a register that's read by the instruction at the point of 2011 // insertion. Remove the kill marker. 2012 MO.setIsKill(false); 2013 } 2014 } 2015 if (!IsSafe) 2016 break; 2017 2018 bool DontMoveAcrossStore = true; 2019 if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore)) 2020 break; 2021 2022 // Remove kills from ActiveDefsSet, these registers had short live ranges. 2023 for (const MachineOperand &MO : TIB->operands()) { 2024 if (!MO.isReg() || !MO.isUse() || !MO.isKill()) 2025 continue; 2026 Register Reg = MO.getReg(); 2027 if (!Reg) 2028 continue; 2029 if (!AllDefsSet.count(Reg)) { 2030 continue; 2031 } 2032 if (Register::isPhysicalRegister(Reg)) { 2033 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) 2034 ActiveDefsSet.erase(*AI); 2035 } else { 2036 ActiveDefsSet.erase(Reg); 2037 } 2038 } 2039 2040 // Track local defs so we can update liveins. 2041 for (const MachineOperand &MO : TIB->operands()) { 2042 if (!MO.isReg() || !MO.isDef() || MO.isDead()) 2043 continue; 2044 Register Reg = MO.getReg(); 2045 if (!Reg || Register::isVirtualRegister(Reg)) 2046 continue; 2047 addRegAndItsAliases(Reg, TRI, ActiveDefsSet); 2048 addRegAndItsAliases(Reg, TRI, AllDefsSet); 2049 } 2050 2051 HasDups = true; 2052 ++TIB; 2053 ++FIB; 2054 } 2055 2056 if (!HasDups) 2057 return false; 2058 2059 MBB->splice(Loc, TBB, TBB->begin(), TIB); 2060 FBB->erase(FBB->begin(), FIB); 2061 2062 if (UpdateLiveIns) { 2063 recomputeLiveIns(*TBB); 2064 recomputeLiveIns(*FBB); 2065 } 2066 2067 ++NumHoist; 2068 return true; 2069 } 2070