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