1 //===- TailDuplicator.cpp - Duplicate blocks into predecessors' tails -----===// 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 utility class duplicates basic blocks ending in unconditional branches 10 // into the tails of their predecessors. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/TailDuplicator.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/DenseSet.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/ProfileSummaryInfo.h" 23 #include "llvm/CodeGen/MachineBasicBlock.h" 24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/MachineInstr.h" 28 #include "llvm/CodeGen/MachineInstrBuilder.h" 29 #include "llvm/CodeGen/MachineOperand.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/CodeGen/MachineSizeOpts.h" 32 #include "llvm/CodeGen/MachineSSAUpdater.h" 33 #include "llvm/CodeGen/TargetInstrInfo.h" 34 #include "llvm/CodeGen/TargetRegisterInfo.h" 35 #include "llvm/CodeGen/TargetSubtargetInfo.h" 36 #include "llvm/IR/DebugLoc.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/Support/CommandLine.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/ErrorHandling.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include "llvm/Target/TargetMachine.h" 43 #include <algorithm> 44 #include <cassert> 45 #include <iterator> 46 #include <utility> 47 48 using namespace llvm; 49 50 #define DEBUG_TYPE "tailduplication" 51 52 STATISTIC(NumTails, "Number of tails duplicated"); 53 STATISTIC(NumTailDups, "Number of tail duplicated blocks"); 54 STATISTIC(NumTailDupAdded, 55 "Number of instructions added due to tail duplication"); 56 STATISTIC(NumTailDupRemoved, 57 "Number of instructions removed due to tail duplication"); 58 STATISTIC(NumDeadBlocks, "Number of dead blocks removed"); 59 STATISTIC(NumAddedPHIs, "Number of phis added"); 60 61 // Heuristic for tail duplication. 62 static cl::opt<unsigned> TailDuplicateSize( 63 "tail-dup-size", 64 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2), 65 cl::Hidden); 66 67 static cl::opt<unsigned> TailDupIndirectBranchSize( 68 "tail-dup-indirect-size", 69 cl::desc("Maximum instructions to consider tail duplicating blocks that " 70 "end with indirect branches."), cl::init(20), 71 cl::Hidden); 72 73 static cl::opt<bool> 74 TailDupVerify("tail-dup-verify", 75 cl::desc("Verify sanity of PHI instructions during taildup"), 76 cl::init(false), cl::Hidden); 77 78 static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U), 79 cl::Hidden); 80 81 void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc, 82 const MachineBranchProbabilityInfo *MBPIin, 83 const MachineBlockFrequencyInfo *MBFIin, 84 ProfileSummaryInfo *PSIin, 85 bool LayoutModeIn, unsigned TailDupSizeIn) { 86 MF = &MFin; 87 TII = MF->getSubtarget().getInstrInfo(); 88 TRI = MF->getSubtarget().getRegisterInfo(); 89 MRI = &MF->getRegInfo(); 90 MMI = &MF->getMMI(); 91 MBPI = MBPIin; 92 MBFI = MBFIin; 93 PSI = PSIin; 94 TailDupSize = TailDupSizeIn; 95 96 assert(MBPI != nullptr && "Machine Branch Probability Info required"); 97 98 LayoutMode = LayoutModeIn; 99 this->PreRegAlloc = PreRegAlloc; 100 } 101 102 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) { 103 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) { 104 MachineBasicBlock *MBB = &*I; 105 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(), 106 MBB->pred_end()); 107 MachineBasicBlock::iterator MI = MBB->begin(); 108 while (MI != MBB->end()) { 109 if (!MI->isPHI()) 110 break; 111 for (MachineBasicBlock *PredBB : Preds) { 112 bool Found = false; 113 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) { 114 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB(); 115 if (PHIBB == PredBB) { 116 Found = true; 117 break; 118 } 119 } 120 if (!Found) { 121 dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": " 122 << *MI; 123 dbgs() << " missing input from predecessor " 124 << printMBBReference(*PredBB) << '\n'; 125 llvm_unreachable(nullptr); 126 } 127 } 128 129 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) { 130 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB(); 131 if (CheckExtra && !Preds.count(PHIBB)) { 132 dbgs() << "Warning: malformed PHI in " << printMBBReference(*MBB) 133 << ": " << *MI; 134 dbgs() << " extra input from predecessor " 135 << printMBBReference(*PHIBB) << '\n'; 136 llvm_unreachable(nullptr); 137 } 138 if (PHIBB->getNumber() < 0) { 139 dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": " 140 << *MI; 141 dbgs() << " non-existing " << printMBBReference(*PHIBB) << '\n'; 142 llvm_unreachable(nullptr); 143 } 144 } 145 ++MI; 146 } 147 } 148 } 149 150 /// Tail duplicate the block and cleanup. 151 /// \p IsSimple - return value of isSimpleBB 152 /// \p MBB - block to be duplicated 153 /// \p ForcedLayoutPred - If non-null, treat this block as the layout 154 /// predecessor, instead of using the ordering in MF 155 /// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of 156 /// all Preds that received a copy of \p MBB. 157 /// \p RemovalCallback - if non-null, called just before MBB is deleted. 158 bool TailDuplicator::tailDuplicateAndUpdate( 159 bool IsSimple, MachineBasicBlock *MBB, 160 MachineBasicBlock *ForcedLayoutPred, 161 SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds, 162 function_ref<void(MachineBasicBlock *)> *RemovalCallback) { 163 // Save the successors list. 164 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(), 165 MBB->succ_end()); 166 167 SmallVector<MachineBasicBlock *, 8> TDBBs; 168 SmallVector<MachineInstr *, 16> Copies; 169 if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred, TDBBs, Copies)) 170 return false; 171 172 ++NumTails; 173 174 SmallVector<MachineInstr *, 8> NewPHIs; 175 MachineSSAUpdater SSAUpdate(*MF, &NewPHIs); 176 177 // TailBB's immediate successors are now successors of those predecessors 178 // which duplicated TailBB. Add the predecessors as sources to the PHI 179 // instructions. 180 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken(); 181 if (PreRegAlloc) 182 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs); 183 184 // If it is dead, remove it. 185 if (isDead) { 186 NumTailDupRemoved += MBB->size(); 187 removeDeadBlock(MBB, RemovalCallback); 188 ++NumDeadBlocks; 189 } 190 191 // Update SSA form. 192 if (!SSAUpdateVRs.empty()) { 193 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) { 194 unsigned VReg = SSAUpdateVRs[i]; 195 SSAUpdate.Initialize(VReg); 196 197 // If the original definition is still around, add it as an available 198 // value. 199 MachineInstr *DefMI = MRI->getVRegDef(VReg); 200 MachineBasicBlock *DefBB = nullptr; 201 if (DefMI) { 202 DefBB = DefMI->getParent(); 203 SSAUpdate.AddAvailableValue(DefBB, VReg); 204 } 205 206 // Add the new vregs as available values. 207 DenseMap<unsigned, AvailableValsTy>::iterator LI = 208 SSAUpdateVals.find(VReg); 209 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) { 210 MachineBasicBlock *SrcBB = LI->second[j].first; 211 unsigned SrcReg = LI->second[j].second; 212 SSAUpdate.AddAvailableValue(SrcBB, SrcReg); 213 } 214 215 // Rewrite uses that are outside of the original def's block. 216 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg); 217 while (UI != MRI->use_end()) { 218 MachineOperand &UseMO = *UI; 219 MachineInstr *UseMI = UseMO.getParent(); 220 ++UI; 221 if (UseMI->isDebugValue()) { 222 // SSAUpdate can replace the use with an undef. That creates 223 // a debug instruction that is a kill. 224 // FIXME: Should it SSAUpdate job to delete debug instructions 225 // instead of replacing the use with undef? 226 UseMI->eraseFromParent(); 227 continue; 228 } 229 if (UseMI->getParent() == DefBB && !UseMI->isPHI()) 230 continue; 231 SSAUpdate.RewriteUse(UseMO); 232 } 233 } 234 235 SSAUpdateVRs.clear(); 236 SSAUpdateVals.clear(); 237 } 238 239 // Eliminate some of the copies inserted by tail duplication to maintain 240 // SSA form. 241 for (unsigned i = 0, e = Copies.size(); i != e; ++i) { 242 MachineInstr *Copy = Copies[i]; 243 if (!Copy->isCopy()) 244 continue; 245 Register Dst = Copy->getOperand(0).getReg(); 246 Register Src = Copy->getOperand(1).getReg(); 247 if (MRI->hasOneNonDBGUse(Src) && 248 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) { 249 // Copy is the only use. Do trivial copy propagation here. 250 MRI->replaceRegWith(Dst, Src); 251 Copy->eraseFromParent(); 252 } 253 } 254 255 if (NewPHIs.size()) 256 NumAddedPHIs += NewPHIs.size(); 257 258 if (DuplicatedPreds) 259 *DuplicatedPreds = std::move(TDBBs); 260 261 return true; 262 } 263 264 /// Look for small blocks that are unconditionally branched to and do not fall 265 /// through. Tail-duplicate their instructions into their predecessors to 266 /// eliminate (dynamic) branches. 267 bool TailDuplicator::tailDuplicateBlocks() { 268 bool MadeChange = false; 269 270 if (PreRegAlloc && TailDupVerify) { 271 LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n"); 272 VerifyPHIs(*MF, true); 273 } 274 275 for (MachineFunction::iterator I = ++MF->begin(), E = MF->end(); I != E;) { 276 MachineBasicBlock *MBB = &*I++; 277 278 if (NumTails == TailDupLimit) 279 break; 280 281 bool IsSimple = isSimpleBB(MBB); 282 283 if (!shouldTailDuplicate(IsSimple, *MBB)) 284 continue; 285 286 MadeChange |= tailDuplicateAndUpdate(IsSimple, MBB, nullptr); 287 } 288 289 if (PreRegAlloc && TailDupVerify) 290 VerifyPHIs(*MF, false); 291 292 return MadeChange; 293 } 294 295 static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB, 296 const MachineRegisterInfo *MRI) { 297 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) { 298 if (UseMI.isDebugValue()) 299 continue; 300 if (UseMI.getParent() != BB) 301 return true; 302 } 303 return false; 304 } 305 306 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) { 307 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) 308 if (MI->getOperand(i + 1).getMBB() == SrcBB) 309 return i; 310 return 0; 311 } 312 313 // Remember which registers are used by phis in this block. This is 314 // used to determine which registers are liveout while modifying the 315 // block (which is why we need to copy the information). 316 static void getRegsUsedByPHIs(const MachineBasicBlock &BB, 317 DenseSet<unsigned> *UsedByPhi) { 318 for (const auto &MI : BB) { 319 if (!MI.isPHI()) 320 break; 321 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) { 322 Register SrcReg = MI.getOperand(i).getReg(); 323 UsedByPhi->insert(SrcReg); 324 } 325 } 326 } 327 328 /// Add a definition and source virtual registers pair for SSA update. 329 void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg, 330 MachineBasicBlock *BB) { 331 DenseMap<unsigned, AvailableValsTy>::iterator LI = 332 SSAUpdateVals.find(OrigReg); 333 if (LI != SSAUpdateVals.end()) 334 LI->second.push_back(std::make_pair(BB, NewReg)); 335 else { 336 AvailableValsTy Vals; 337 Vals.push_back(std::make_pair(BB, NewReg)); 338 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals)); 339 SSAUpdateVRs.push_back(OrigReg); 340 } 341 } 342 343 /// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the 344 /// source register that's contributed by PredBB and update SSA update map. 345 void TailDuplicator::processPHI( 346 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB, 347 DenseMap<unsigned, RegSubRegPair> &LocalVRMap, 348 SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies, 349 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) { 350 Register DefReg = MI->getOperand(0).getReg(); 351 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB); 352 assert(SrcOpIdx && "Unable to find matching PHI source?"); 353 Register SrcReg = MI->getOperand(SrcOpIdx).getReg(); 354 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg(); 355 const TargetRegisterClass *RC = MRI->getRegClass(DefReg); 356 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg))); 357 358 // Insert a copy from source to the end of the block. The def register is the 359 // available value liveout of the block. 360 Register NewDef = MRI->createVirtualRegister(RC); 361 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg))); 362 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg)) 363 addSSAUpdateEntry(DefReg, NewDef, PredBB); 364 365 if (!Remove) 366 return; 367 368 // Remove PredBB from the PHI node. 369 MI->RemoveOperand(SrcOpIdx + 1); 370 MI->RemoveOperand(SrcOpIdx); 371 if (MI->getNumOperands() == 1) 372 MI->eraseFromParent(); 373 } 374 375 /// Duplicate a TailBB instruction to PredBB and update 376 /// the source operands due to earlier PHI translation. 377 void TailDuplicator::duplicateInstruction( 378 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB, 379 DenseMap<unsigned, RegSubRegPair> &LocalVRMap, 380 const DenseSet<unsigned> &UsedByPhi) { 381 // Allow duplication of CFI instructions. 382 if (MI->isCFIInstruction()) { 383 BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()), 384 TII->get(TargetOpcode::CFI_INSTRUCTION)).addCFIIndex( 385 MI->getOperand(0).getCFIIndex()); 386 return; 387 } 388 MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI); 389 if (PreRegAlloc) { 390 for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) { 391 MachineOperand &MO = NewMI.getOperand(i); 392 if (!MO.isReg()) 393 continue; 394 Register Reg = MO.getReg(); 395 if (!Register::isVirtualRegister(Reg)) 396 continue; 397 if (MO.isDef()) { 398 const TargetRegisterClass *RC = MRI->getRegClass(Reg); 399 Register NewReg = MRI->createVirtualRegister(RC); 400 MO.setReg(NewReg); 401 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0))); 402 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg)) 403 addSSAUpdateEntry(Reg, NewReg, PredBB); 404 } else { 405 auto VI = LocalVRMap.find(Reg); 406 if (VI != LocalVRMap.end()) { 407 // Need to make sure that the register class of the mapped register 408 // will satisfy the constraints of the class of the register being 409 // replaced. 410 auto *OrigRC = MRI->getRegClass(Reg); 411 auto *MappedRC = MRI->getRegClass(VI->second.Reg); 412 const TargetRegisterClass *ConstrRC; 413 if (VI->second.SubReg != 0) { 414 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC, 415 VI->second.SubReg); 416 if (ConstrRC) { 417 // The actual constraining (as in "find appropriate new class") 418 // is done by getMatchingSuperRegClass, so now we only need to 419 // change the class of the mapped register. 420 MRI->setRegClass(VI->second.Reg, ConstrRC); 421 } 422 } else { 423 // For mapped registers that do not have sub-registers, simply 424 // restrict their class to match the original one. 425 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC); 426 } 427 428 if (ConstrRC) { 429 // If the class constraining succeeded, we can simply replace 430 // the old register with the mapped one. 431 MO.setReg(VI->second.Reg); 432 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a 433 // sub-register, we need to compose the sub-register indices. 434 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(), 435 VI->second.SubReg)); 436 } else { 437 // The direct replacement is not possible, due to failing register 438 // class constraints. An explicit COPY is necessary. Create one 439 // that can be reused 440 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI); 441 if (NewRC == nullptr) 442 NewRC = OrigRC; 443 Register NewReg = MRI->createVirtualRegister(NewRC); 444 BuildMI(*PredBB, NewMI, NewMI.getDebugLoc(), 445 TII->get(TargetOpcode::COPY), NewReg) 446 .addReg(VI->second.Reg, 0, VI->second.SubReg); 447 LocalVRMap.erase(VI); 448 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0))); 449 MO.setReg(NewReg); 450 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which 451 // is equivalent to the whole register Reg. Hence, Reg:subreg 452 // is same as NewReg:subreg, so keep the sub-register index 453 // unchanged. 454 } 455 // Clear any kill flags from this operand. The new register could 456 // have uses after this one, so kills are not valid here. 457 MO.setIsKill(false); 458 } 459 } 460 } 461 } 462 } 463 464 /// After FromBB is tail duplicated into its predecessor blocks, the successors 465 /// have gained new predecessors. Update the PHI instructions in them 466 /// accordingly. 467 void TailDuplicator::updateSuccessorsPHIs( 468 MachineBasicBlock *FromBB, bool isDead, 469 SmallVectorImpl<MachineBasicBlock *> &TDBBs, 470 SmallSetVector<MachineBasicBlock *, 8> &Succs) { 471 for (MachineBasicBlock *SuccBB : Succs) { 472 for (MachineInstr &MI : *SuccBB) { 473 if (!MI.isPHI()) 474 break; 475 MachineInstrBuilder MIB(*FromBB->getParent(), MI); 476 unsigned Idx = 0; 477 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) { 478 MachineOperand &MO = MI.getOperand(i + 1); 479 if (MO.getMBB() == FromBB) { 480 Idx = i; 481 break; 482 } 483 } 484 485 assert(Idx != 0); 486 MachineOperand &MO0 = MI.getOperand(Idx); 487 Register Reg = MO0.getReg(); 488 if (isDead) { 489 // Folded into the previous BB. 490 // There could be duplicate phi source entries. FIXME: Should sdisel 491 // or earlier pass fixed this? 492 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) { 493 MachineOperand &MO = MI.getOperand(i + 1); 494 if (MO.getMBB() == FromBB) { 495 MI.RemoveOperand(i + 1); 496 MI.RemoveOperand(i); 497 } 498 } 499 } else 500 Idx = 0; 501 502 // If Idx is set, the operands at Idx and Idx+1 must be removed. 503 // We reuse the location to avoid expensive RemoveOperand calls. 504 505 DenseMap<unsigned, AvailableValsTy>::iterator LI = 506 SSAUpdateVals.find(Reg); 507 if (LI != SSAUpdateVals.end()) { 508 // This register is defined in the tail block. 509 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) { 510 MachineBasicBlock *SrcBB = LI->second[j].first; 511 // If we didn't duplicate a bb into a particular predecessor, we 512 // might still have added an entry to SSAUpdateVals to correcly 513 // recompute SSA. If that case, avoid adding a dummy extra argument 514 // this PHI. 515 if (!SrcBB->isSuccessor(SuccBB)) 516 continue; 517 518 unsigned SrcReg = LI->second[j].second; 519 if (Idx != 0) { 520 MI.getOperand(Idx).setReg(SrcReg); 521 MI.getOperand(Idx + 1).setMBB(SrcBB); 522 Idx = 0; 523 } else { 524 MIB.addReg(SrcReg).addMBB(SrcBB); 525 } 526 } 527 } else { 528 // Live in tail block, must also be live in predecessors. 529 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) { 530 MachineBasicBlock *SrcBB = TDBBs[j]; 531 if (Idx != 0) { 532 MI.getOperand(Idx).setReg(Reg); 533 MI.getOperand(Idx + 1).setMBB(SrcBB); 534 Idx = 0; 535 } else { 536 MIB.addReg(Reg).addMBB(SrcBB); 537 } 538 } 539 } 540 if (Idx != 0) { 541 MI.RemoveOperand(Idx + 1); 542 MI.RemoveOperand(Idx); 543 } 544 } 545 } 546 } 547 548 /// Determine if it is profitable to duplicate this block. 549 bool TailDuplicator::shouldTailDuplicate(bool IsSimple, 550 MachineBasicBlock &TailBB) { 551 // When doing tail-duplication during layout, the block ordering is in flux, 552 // so canFallThrough returns a result based on incorrect information and 553 // should just be ignored. 554 if (!LayoutMode && TailBB.canFallThrough()) 555 return false; 556 557 // Don't try to tail-duplicate single-block loops. 558 if (TailBB.isSuccessor(&TailBB)) 559 return false; 560 561 // Set the limit on the cost to duplicate. When optimizing for size, 562 // duplicate only one, because one branch instruction can be eliminated to 563 // compensate for the duplication. 564 unsigned MaxDuplicateCount; 565 bool OptForSize = MF->getFunction().hasOptSize() || 566 llvm::shouldOptimizeForSize(&TailBB, PSI, MBFI); 567 if (TailDupSize == 0) 568 MaxDuplicateCount = TailDuplicateSize; 569 else 570 MaxDuplicateCount = TailDupSize; 571 if (OptForSize) 572 MaxDuplicateCount = 1; 573 574 // If the block to be duplicated ends in an unanalyzable fallthrough, don't 575 // duplicate it. 576 // A similar check is necessary in MachineBlockPlacement to make sure pairs of 577 // blocks with unanalyzable fallthrough get layed out contiguously. 578 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 579 SmallVector<MachineOperand, 4> PredCond; 580 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) && 581 TailBB.canFallThrough()) 582 return false; 583 584 // If the target has hardware branch prediction that can handle indirect 585 // branches, duplicating them can often make them predictable when there 586 // are common paths through the code. The limit needs to be high enough 587 // to allow undoing the effects of tail merging and other optimizations 588 // that rearrange the predecessors of the indirect branch. 589 590 bool HasIndirectbr = false; 591 if (!TailBB.empty()) 592 HasIndirectbr = TailBB.back().isIndirectBranch(); 593 594 if (HasIndirectbr && PreRegAlloc) 595 MaxDuplicateCount = TailDupIndirectBranchSize; 596 597 // Check the instructions in the block to determine whether tail-duplication 598 // is invalid or unlikely to be profitable. 599 unsigned InstrCount = 0; 600 for (MachineInstr &MI : TailBB) { 601 // Non-duplicable things shouldn't be tail-duplicated. 602 // CFI instructions are marked as non-duplicable, because Darwin compact 603 // unwind info emission can't handle multiple prologue setups. In case of 604 // DWARF, allow them be duplicated, so that their existence doesn't prevent 605 // tail duplication of some basic blocks, that would be duplicated otherwise. 606 if (MI.isNotDuplicable() && 607 (TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() || 608 !MI.isCFIInstruction())) 609 return false; 610 611 // Convergent instructions can be duplicated only if doing so doesn't add 612 // new control dependencies, which is what we're going to do here. 613 if (MI.isConvergent()) 614 return false; 615 616 // Do not duplicate 'return' instructions if this is a pre-regalloc run. 617 // A return may expand into a lot more instructions (e.g. reload of callee 618 // saved registers) after PEI. 619 if (PreRegAlloc && MI.isReturn()) 620 return false; 621 622 // Avoid duplicating calls before register allocation. Calls presents a 623 // barrier to register allocation so duplicating them may end up increasing 624 // spills. 625 if (PreRegAlloc && MI.isCall()) 626 return false; 627 628 if (MI.isBundle()) 629 InstrCount += MI.getBundleSize(); 630 else if (!MI.isPHI() && !MI.isMetaInstruction()) 631 InstrCount += 1; 632 633 if (InstrCount > MaxDuplicateCount) 634 return false; 635 } 636 637 // Check if any of the successors of TailBB has a PHI node in which the 638 // value corresponding to TailBB uses a subregister. 639 // If a phi node uses a register paired with a subregister, the actual 640 // "value type" of the phi may differ from the type of the register without 641 // any subregisters. Due to a bug, tail duplication may add a new operand 642 // without a necessary subregister, producing an invalid code. This is 643 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll. 644 // Disable tail duplication for this case for now, until the problem is 645 // fixed. 646 for (auto SB : TailBB.successors()) { 647 for (auto &I : *SB) { 648 if (!I.isPHI()) 649 break; 650 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB); 651 assert(Idx != 0); 652 MachineOperand &PU = I.getOperand(Idx); 653 if (PU.getSubReg() != 0) 654 return false; 655 } 656 } 657 658 if (HasIndirectbr && PreRegAlloc) 659 return true; 660 661 if (IsSimple) 662 return true; 663 664 if (!PreRegAlloc) 665 return true; 666 667 return canCompletelyDuplicateBB(TailBB); 668 } 669 670 /// True if this BB has only one unconditional jump. 671 bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) { 672 if (TailBB->succ_size() != 1) 673 return false; 674 if (TailBB->pred_empty()) 675 return false; 676 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr(); 677 if (I == TailBB->end()) 678 return true; 679 return I->isUnconditionalBranch(); 680 } 681 682 static bool bothUsedInPHI(const MachineBasicBlock &A, 683 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) { 684 for (MachineBasicBlock *BB : A.successors()) 685 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI()) 686 return true; 687 688 return false; 689 } 690 691 bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) { 692 for (MachineBasicBlock *PredBB : BB.predecessors()) { 693 if (PredBB->succ_size() > 1) 694 return false; 695 696 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 697 SmallVector<MachineOperand, 4> PredCond; 698 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond)) 699 return false; 700 701 if (!PredCond.empty()) 702 return false; 703 } 704 return true; 705 } 706 707 bool TailDuplicator::duplicateSimpleBB( 708 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs, 709 const DenseSet<unsigned> &UsedByPhi, 710 SmallVectorImpl<MachineInstr *> &Copies) { 711 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(), 712 TailBB->succ_end()); 713 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(), 714 TailBB->pred_end()); 715 bool Changed = false; 716 for (MachineBasicBlock *PredBB : Preds) { 717 if (PredBB->hasEHPadSuccessor()) 718 continue; 719 720 if (bothUsedInPHI(*PredBB, Succs)) 721 continue; 722 723 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 724 SmallVector<MachineOperand, 4> PredCond; 725 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond)) 726 continue; 727 728 Changed = true; 729 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB 730 << "From simple Succ: " << *TailBB); 731 732 MachineBasicBlock *NewTarget = *TailBB->succ_begin(); 733 MachineBasicBlock *NextBB = PredBB->getNextNode(); 734 735 // Make PredFBB explicit. 736 if (PredCond.empty()) 737 PredFBB = PredTBB; 738 739 // Make fall through explicit. 740 if (!PredTBB) 741 PredTBB = NextBB; 742 if (!PredFBB) 743 PredFBB = NextBB; 744 745 // Redirect 746 if (PredFBB == TailBB) 747 PredFBB = NewTarget; 748 if (PredTBB == TailBB) 749 PredTBB = NewTarget; 750 751 // Make the branch unconditional if possible 752 if (PredTBB == PredFBB) { 753 PredCond.clear(); 754 PredFBB = nullptr; 755 } 756 757 // Avoid adding fall through branches. 758 if (PredFBB == NextBB) 759 PredFBB = nullptr; 760 if (PredTBB == NextBB && PredFBB == nullptr) 761 PredTBB = nullptr; 762 763 auto DL = PredBB->findBranchDebugLoc(); 764 TII->removeBranch(*PredBB); 765 766 if (!PredBB->isSuccessor(NewTarget)) 767 PredBB->replaceSuccessor(TailBB, NewTarget); 768 else { 769 PredBB->removeSuccessor(TailBB, true); 770 assert(PredBB->succ_size() <= 1); 771 } 772 773 if (PredTBB) 774 TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL); 775 776 TDBBs.push_back(PredBB); 777 } 778 return Changed; 779 } 780 781 bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB, 782 MachineBasicBlock *PredBB) { 783 // EH edges are ignored by analyzeBranch. 784 if (PredBB->succ_size() > 1) 785 return false; 786 787 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 788 SmallVector<MachineOperand, 4> PredCond; 789 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond)) 790 return false; 791 if (!PredCond.empty()) 792 return false; 793 return true; 794 } 795 796 /// If it is profitable, duplicate TailBB's contents in each 797 /// of its predecessors. 798 /// \p IsSimple result of isSimpleBB 799 /// \p TailBB Block to be duplicated. 800 /// \p ForcedLayoutPred When non-null, use this block as the layout predecessor 801 /// instead of the previous block in MF's order. 802 /// \p TDBBs A vector to keep track of all blocks tail-duplicated 803 /// into. 804 /// \p Copies A vector of copy instructions inserted. Used later to 805 /// walk all the inserted copies and remove redundant ones. 806 bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB, 807 MachineBasicBlock *ForcedLayoutPred, 808 SmallVectorImpl<MachineBasicBlock *> &TDBBs, 809 SmallVectorImpl<MachineInstr *> &Copies) { 810 LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB) 811 << '\n'); 812 813 DenseSet<unsigned> UsedByPhi; 814 getRegsUsedByPHIs(*TailBB, &UsedByPhi); 815 816 if (IsSimple) 817 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies); 818 819 // Iterate through all the unique predecessors and tail-duplicate this 820 // block into them, if possible. Copying the list ahead of time also 821 // avoids trouble with the predecessor list reallocating. 822 bool Changed = false; 823 SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(), 824 TailBB->pred_end()); 825 for (MachineBasicBlock *PredBB : Preds) { 826 assert(TailBB != PredBB && 827 "Single-block loop should have been rejected earlier!"); 828 829 if (!canTailDuplicate(TailBB, PredBB)) 830 continue; 831 832 // Don't duplicate into a fall-through predecessor (at least for now). 833 bool IsLayoutSuccessor = false; 834 if (ForcedLayoutPred) 835 IsLayoutSuccessor = (ForcedLayoutPred == PredBB); 836 else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough()) 837 IsLayoutSuccessor = true; 838 if (IsLayoutSuccessor) 839 continue; 840 841 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB 842 << "From Succ: " << *TailBB); 843 844 TDBBs.push_back(PredBB); 845 846 // Remove PredBB's unconditional branch. 847 TII->removeBranch(*PredBB); 848 849 // Clone the contents of TailBB into PredBB. 850 DenseMap<unsigned, RegSubRegPair> LocalVRMap; 851 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos; 852 for (MachineBasicBlock::iterator I = TailBB->begin(), E = TailBB->end(); 853 I != E; /* empty */) { 854 MachineInstr *MI = &*I; 855 ++I; 856 if (MI->isPHI()) { 857 // Replace the uses of the def of the PHI with the register coming 858 // from PredBB. 859 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true); 860 } else { 861 // Replace def of virtual registers with new registers, and update 862 // uses with PHI source register or the new registers. 863 duplicateInstruction(MI, TailBB, PredBB, LocalVRMap, UsedByPhi); 864 } 865 } 866 appendCopies(PredBB, CopyInfos, Copies); 867 868 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch 869 870 // Update the CFG. 871 PredBB->removeSuccessor(PredBB->succ_begin()); 872 assert(PredBB->succ_empty() && 873 "TailDuplicate called on block with multiple successors!"); 874 for (MachineBasicBlock *Succ : TailBB->successors()) 875 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ)); 876 877 Changed = true; 878 ++NumTailDups; 879 } 880 881 // If TailBB was duplicated into all its predecessors except for the prior 882 // block, which falls through unconditionally, move the contents of this 883 // block into the prior block. 884 MachineBasicBlock *PrevBB = ForcedLayoutPred; 885 if (!PrevBB) 886 PrevBB = &*std::prev(TailBB->getIterator()); 887 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr; 888 SmallVector<MachineOperand, 4> PriorCond; 889 // This has to check PrevBB->succ_size() because EH edges are ignored by 890 // analyzeBranch. 891 if (PrevBB->succ_size() == 1 && 892 // Layout preds are not always CFG preds. Check. 893 *PrevBB->succ_begin() == TailBB && 894 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) && 895 PriorCond.empty() && 896 (!PriorTBB || PriorTBB == TailBB) && 897 TailBB->pred_size() == 1 && 898 !TailBB->hasAddressTaken()) { 899 LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB 900 << "From MBB: " << *TailBB); 901 // There may be a branch to the layout successor. This is unlikely but it 902 // happens. The correct thing to do is to remove the branch before 903 // duplicating the instructions in all cases. 904 TII->removeBranch(*PrevBB); 905 if (PreRegAlloc) { 906 DenseMap<unsigned, RegSubRegPair> LocalVRMap; 907 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos; 908 MachineBasicBlock::iterator I = TailBB->begin(); 909 // Process PHI instructions first. 910 while (I != TailBB->end() && I->isPHI()) { 911 // Replace the uses of the def of the PHI with the register coming 912 // from PredBB. 913 MachineInstr *MI = &*I++; 914 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true); 915 } 916 917 // Now copy the non-PHI instructions. 918 while (I != TailBB->end()) { 919 // Replace def of virtual registers with new registers, and update 920 // uses with PHI source register or the new registers. 921 MachineInstr *MI = &*I++; 922 assert(!MI->isBundle() && "Not expecting bundles before regalloc!"); 923 duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi); 924 MI->eraseFromParent(); 925 } 926 appendCopies(PrevBB, CopyInfos, Copies); 927 } else { 928 TII->removeBranch(*PrevBB); 929 // No PHIs to worry about, just splice the instructions over. 930 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end()); 931 } 932 PrevBB->removeSuccessor(PrevBB->succ_begin()); 933 assert(PrevBB->succ_empty()); 934 PrevBB->transferSuccessors(TailBB); 935 TDBBs.push_back(PrevBB); 936 Changed = true; 937 } 938 939 // If this is after register allocation, there are no phis to fix. 940 if (!PreRegAlloc) 941 return Changed; 942 943 // If we made no changes so far, we are safe. 944 if (!Changed) 945 return Changed; 946 947 // Handle the nasty case in that we duplicated a block that is part of a loop 948 // into some but not all of its predecessors. For example: 949 // 1 -> 2 <-> 3 | 950 // \ | 951 // \---> rest | 952 // if we duplicate 2 into 1 but not into 3, we end up with 953 // 12 -> 3 <-> 2 -> rest | 954 // \ / | 955 // \----->-----/ | 956 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced 957 // with a phi in 3 (which now dominates 2). 958 // What we do here is introduce a copy in 3 of the register defined by the 959 // phi, just like when we are duplicating 2 into 3, but we don't copy any 960 // real instructions or remove the 3 -> 2 edge from the phi in 2. 961 for (MachineBasicBlock *PredBB : Preds) { 962 if (is_contained(TDBBs, PredBB)) 963 continue; 964 965 // EH edges 966 if (PredBB->succ_size() != 1) 967 continue; 968 969 DenseMap<unsigned, RegSubRegPair> LocalVRMap; 970 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos; 971 MachineBasicBlock::iterator I = TailBB->begin(); 972 // Process PHI instructions first. 973 while (I != TailBB->end() && I->isPHI()) { 974 // Replace the uses of the def of the PHI with the register coming 975 // from PredBB. 976 MachineInstr *MI = &*I++; 977 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false); 978 } 979 appendCopies(PredBB, CopyInfos, Copies); 980 } 981 982 return Changed; 983 } 984 985 /// At the end of the block \p MBB generate COPY instructions between registers 986 /// described by \p CopyInfos. Append resulting instructions to \p Copies. 987 void TailDuplicator::appendCopies(MachineBasicBlock *MBB, 988 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos, 989 SmallVectorImpl<MachineInstr*> &Copies) { 990 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator(); 991 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY); 992 for (auto &CI : CopyInfos) { 993 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first) 994 .addReg(CI.second.Reg, 0, CI.second.SubReg); 995 Copies.push_back(C); 996 } 997 } 998 999 /// Remove the specified dead machine basic block from the function, updating 1000 /// the CFG. 1001 void TailDuplicator::removeDeadBlock( 1002 MachineBasicBlock *MBB, 1003 function_ref<void(MachineBasicBlock *)> *RemovalCallback) { 1004 assert(MBB->pred_empty() && "MBB must be dead!"); 1005 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB); 1006 1007 if (RemovalCallback) 1008 (*RemovalCallback)(MBB); 1009 1010 // Remove all successors. 1011 while (!MBB->succ_empty()) 1012 MBB->removeSuccessor(MBB->succ_end() - 1); 1013 1014 // Remove the block. 1015 MBB->eraseFromParent(); 1016 } 1017