1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===// 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 // Collect the sequence of machine instructions for a basic block. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/MachineBasicBlock.h" 15 #include "llvm/ADT/SmallPtrSet.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 18 #include "llvm/CodeGen/LiveVariables.h" 19 #include "llvm/CodeGen/MachineDominators.h" 20 #include "llvm/CodeGen/MachineFunction.h" 21 #include "llvm/CodeGen/MachineInstrBuilder.h" 22 #include "llvm/CodeGen/MachineLoopInfo.h" 23 #include "llvm/CodeGen/MachineRegisterInfo.h" 24 #include "llvm/CodeGen/SlotIndexes.h" 25 #include "llvm/IR/BasicBlock.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/MC/MCAsmInfo.h" 28 #include "llvm/MC/MCContext.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include "llvm/Target/TargetInstrInfo.h" 32 #include "llvm/Target/TargetMachine.h" 33 #include "llvm/Target/TargetRegisterInfo.h" 34 #include "llvm/Target/TargetSubtargetInfo.h" 35 #include <algorithm> 36 using namespace llvm; 37 38 #define DEBUG_TYPE "codegen" 39 40 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb) 41 : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false), 42 AddressTaken(false), CachedMCSymbol(nullptr) { 43 Insts.Parent = this; 44 } 45 46 MachineBasicBlock::~MachineBasicBlock() { 47 } 48 49 /// getSymbol - Return the MCSymbol for this basic block. 50 /// 51 MCSymbol *MachineBasicBlock::getSymbol() const { 52 if (!CachedMCSymbol) { 53 const MachineFunction *MF = getParent(); 54 MCContext &Ctx = MF->getContext(); 55 const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix(); 56 CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" + 57 Twine(MF->getFunctionNumber()) + 58 "_" + Twine(getNumber())); 59 } 60 61 return CachedMCSymbol; 62 } 63 64 65 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) { 66 MBB.print(OS); 67 return OS; 68 } 69 70 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the 71 /// parent pointer of the MBB, the MBB numbering, and any instructions in the 72 /// MBB to be on the right operand list for registers. 73 /// 74 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it 75 /// gets the next available unique MBB number. If it is removed from a 76 /// MachineFunction, it goes back to being #-1. 77 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) { 78 MachineFunction &MF = *N->getParent(); 79 N->Number = MF.addToMBBNumbering(N); 80 81 // Make sure the instructions have their operands in the reginfo lists. 82 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 83 for (MachineBasicBlock::instr_iterator 84 I = N->instr_begin(), E = N->instr_end(); I != E; ++I) 85 I->AddRegOperandsToUseLists(RegInfo); 86 } 87 88 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) { 89 N->getParent()->removeFromMBBNumbering(N->Number); 90 N->Number = -1; 91 } 92 93 94 /// addNodeToList (MI) - When we add an instruction to a basic block 95 /// list, we update its parent pointer and add its operands from reg use/def 96 /// lists if appropriate. 97 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) { 98 assert(!N->getParent() && "machine instruction already in a basic block"); 99 N->setParent(Parent); 100 101 // Add the instruction's register operands to their corresponding 102 // use/def lists. 103 MachineFunction *MF = Parent->getParent(); 104 N->AddRegOperandsToUseLists(MF->getRegInfo()); 105 } 106 107 /// removeNodeFromList (MI) - When we remove an instruction from a basic block 108 /// list, we update its parent pointer and remove its operands from reg use/def 109 /// lists if appropriate. 110 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) { 111 assert(N->getParent() && "machine instruction not in a basic block"); 112 113 // Remove from the use/def lists. 114 if (MachineFunction *MF = N->getParent()->getParent()) 115 N->RemoveRegOperandsFromUseLists(MF->getRegInfo()); 116 117 N->setParent(nullptr); 118 } 119 120 /// transferNodesFromList (MI) - When moving a range of instructions from one 121 /// MBB list to another, we need to update the parent pointers and the use/def 122 /// lists. 123 void ilist_traits<MachineInstr>:: 124 transferNodesFromList(ilist_traits<MachineInstr> &fromList, 125 ilist_iterator<MachineInstr> first, 126 ilist_iterator<MachineInstr> last) { 127 assert(Parent->getParent() == fromList.Parent->getParent() && 128 "MachineInstr parent mismatch!"); 129 130 // Splice within the same MBB -> no change. 131 if (Parent == fromList.Parent) return; 132 133 // If splicing between two blocks within the same function, just update the 134 // parent pointers. 135 for (; first != last; ++first) 136 first->setParent(Parent); 137 } 138 139 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) { 140 assert(!MI->getParent() && "MI is still in a block!"); 141 Parent->getParent()->DeleteMachineInstr(MI); 142 } 143 144 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() { 145 instr_iterator I = instr_begin(), E = instr_end(); 146 while (I != E && I->isPHI()) 147 ++I; 148 assert((I == E || !I->isInsideBundle()) && 149 "First non-phi MI cannot be inside a bundle!"); 150 return I; 151 } 152 153 MachineBasicBlock::iterator 154 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) { 155 iterator E = end(); 156 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue())) 157 ++I; 158 // FIXME: This needs to change if we wish to bundle labels / dbg_values 159 // inside the bundle. 160 assert((I == E || !I->isInsideBundle()) && 161 "First non-phi / non-label instruction is inside a bundle!"); 162 return I; 163 } 164 165 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() { 166 iterator B = begin(), E = end(), I = E; 167 while (I != B && ((--I)->isTerminator() || I->isDebugValue())) 168 ; /*noop */ 169 while (I != E && !I->isTerminator()) 170 ++I; 171 return I; 172 } 173 174 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() { 175 instr_iterator B = instr_begin(), E = instr_end(), I = E; 176 while (I != B && ((--I)->isTerminator() || I->isDebugValue())) 177 ; /*noop */ 178 while (I != E && !I->isTerminator()) 179 ++I; 180 return I; 181 } 182 183 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() { 184 // Skip over begin-of-block dbg_value instructions. 185 iterator I = begin(), E = end(); 186 while (I != E && I->isDebugValue()) 187 ++I; 188 return I; 189 } 190 191 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() { 192 // Skip over end-of-block dbg_value instructions. 193 instr_iterator B = instr_begin(), I = instr_end(); 194 while (I != B) { 195 --I; 196 // Return instruction that starts a bundle. 197 if (I->isDebugValue() || I->isInsideBundle()) 198 continue; 199 return I; 200 } 201 // The block is all debug values. 202 return end(); 203 } 204 205 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const { 206 // A block with a landing pad successor only has one other successor. 207 if (succ_size() > 2) 208 return nullptr; 209 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I) 210 if ((*I)->isLandingPad()) 211 return *I; 212 return nullptr; 213 } 214 215 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 216 void MachineBasicBlock::dump() const { 217 print(dbgs()); 218 } 219 #endif 220 221 StringRef MachineBasicBlock::getName() const { 222 if (const BasicBlock *LBB = getBasicBlock()) 223 return LBB->getName(); 224 else 225 return "(null)"; 226 } 227 228 /// Return a hopefully unique identifier for this block. 229 std::string MachineBasicBlock::getFullName() const { 230 std::string Name; 231 if (getParent()) 232 Name = (getParent()->getName() + ":").str(); 233 if (getBasicBlock()) 234 Name += getBasicBlock()->getName(); 235 else 236 Name += ("BB" + Twine(getNumber())).str(); 237 return Name; 238 } 239 240 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const { 241 const MachineFunction *MF = getParent(); 242 if (!MF) { 243 OS << "Can't print out MachineBasicBlock because parent MachineFunction" 244 << " is null\n"; 245 return; 246 } 247 248 if (Indexes) 249 OS << Indexes->getMBBStartIdx(this) << '\t'; 250 251 OS << "BB#" << getNumber() << ": "; 252 253 const char *Comma = ""; 254 if (const BasicBlock *LBB = getBasicBlock()) { 255 OS << Comma << "derived from LLVM BB "; 256 LBB->printAsOperand(OS, /*PrintType=*/false); 257 Comma = ", "; 258 } 259 if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; } 260 if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; } 261 if (Alignment) 262 OS << Comma << "Align " << Alignment << " (" << (1u << Alignment) 263 << " bytes)"; 264 265 OS << '\n'; 266 267 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 268 if (!livein_empty()) { 269 if (Indexes) OS << '\t'; 270 OS << " Live Ins:"; 271 for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I) 272 OS << ' ' << PrintReg(*I, TRI); 273 OS << '\n'; 274 } 275 // Print the preds of this block according to the CFG. 276 if (!pred_empty()) { 277 if (Indexes) OS << '\t'; 278 OS << " Predecessors according to CFG:"; 279 for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI) 280 OS << " BB#" << (*PI)->getNumber(); 281 OS << '\n'; 282 } 283 284 for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) { 285 if (Indexes) { 286 if (Indexes->hasIndex(I)) 287 OS << Indexes->getInstructionIndex(I); 288 OS << '\t'; 289 } 290 OS << '\t'; 291 if (I->isInsideBundle()) 292 OS << " * "; 293 I->print(OS); 294 } 295 296 // Print the successors of this block according to the CFG. 297 if (!succ_empty()) { 298 if (Indexes) OS << '\t'; 299 OS << " Successors according to CFG:"; 300 for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) { 301 OS << " BB#" << (*SI)->getNumber(); 302 if (!Weights.empty()) 303 OS << '(' << *getWeightIterator(SI) << ')'; 304 } 305 OS << '\n'; 306 } 307 } 308 309 void MachineBasicBlock::printAsOperand(raw_ostream &OS, bool /*PrintType*/) const { 310 OS << "BB#" << getNumber(); 311 } 312 313 void MachineBasicBlock::removeLiveIn(unsigned Reg) { 314 std::vector<unsigned>::iterator I = 315 std::find(LiveIns.begin(), LiveIns.end(), Reg); 316 if (I != LiveIns.end()) 317 LiveIns.erase(I); 318 } 319 320 bool MachineBasicBlock::isLiveIn(unsigned Reg) const { 321 livein_iterator I = std::find(livein_begin(), livein_end(), Reg); 322 return I != livein_end(); 323 } 324 325 unsigned 326 MachineBasicBlock::addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC) { 327 assert(getParent() && "MBB must be inserted in function"); 328 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg"); 329 assert(RC && "Register class is required"); 330 assert((isLandingPad() || this == &getParent()->front()) && 331 "Only the entry block and landing pads can have physreg live ins"); 332 333 bool LiveIn = isLiveIn(PhysReg); 334 iterator I = SkipPHIsAndLabels(begin()), E = end(); 335 MachineRegisterInfo &MRI = getParent()->getRegInfo(); 336 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo(); 337 338 // Look for an existing copy. 339 if (LiveIn) 340 for (;I != E && I->isCopy(); ++I) 341 if (I->getOperand(1).getReg() == PhysReg) { 342 unsigned VirtReg = I->getOperand(0).getReg(); 343 if (!MRI.constrainRegClass(VirtReg, RC)) 344 llvm_unreachable("Incompatible live-in register class."); 345 return VirtReg; 346 } 347 348 // No luck, create a virtual register. 349 unsigned VirtReg = MRI.createVirtualRegister(RC); 350 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg) 351 .addReg(PhysReg, RegState::Kill); 352 if (!LiveIn) 353 addLiveIn(PhysReg); 354 return VirtReg; 355 } 356 357 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) { 358 getParent()->splice(NewAfter, this); 359 } 360 361 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) { 362 MachineFunction::iterator BBI = NewBefore; 363 getParent()->splice(++BBI, this); 364 } 365 366 void MachineBasicBlock::updateTerminator() { 367 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 368 // A block with no successors has no concerns with fall-through edges. 369 if (this->succ_empty()) return; 370 371 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 372 SmallVector<MachineOperand, 4> Cond; 373 DebugLoc dl; // FIXME: this is nowhere 374 bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond); 375 (void) B; 376 assert(!B && "UpdateTerminators requires analyzable predecessors!"); 377 if (Cond.empty()) { 378 if (TBB) { 379 // The block has an unconditional branch. If its successor is now 380 // its layout successor, delete the branch. 381 if (isLayoutSuccessor(TBB)) 382 TII->RemoveBranch(*this); 383 } else { 384 // The block has an unconditional fallthrough. If its successor is not 385 // its layout successor, insert a branch. First we have to locate the 386 // only non-landing-pad successor, as that is the fallthrough block. 387 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) { 388 if ((*SI)->isLandingPad()) 389 continue; 390 assert(!TBB && "Found more than one non-landing-pad successor!"); 391 TBB = *SI; 392 } 393 394 // If there is no non-landing-pad successor, the block has no 395 // fall-through edges to be concerned with. 396 if (!TBB) 397 return; 398 399 // Finally update the unconditional successor to be reached via a branch 400 // if it would not be reached by fallthrough. 401 if (!isLayoutSuccessor(TBB)) 402 TII->InsertBranch(*this, TBB, nullptr, Cond, dl); 403 } 404 } else { 405 if (FBB) { 406 // The block has a non-fallthrough conditional branch. If one of its 407 // successors is its layout successor, rewrite it to a fallthrough 408 // conditional branch. 409 if (isLayoutSuccessor(TBB)) { 410 if (TII->ReverseBranchCondition(Cond)) 411 return; 412 TII->RemoveBranch(*this); 413 TII->InsertBranch(*this, FBB, nullptr, Cond, dl); 414 } else if (isLayoutSuccessor(FBB)) { 415 TII->RemoveBranch(*this); 416 TII->InsertBranch(*this, TBB, nullptr, Cond, dl); 417 } 418 } else { 419 // Walk through the successors and find the successor which is not 420 // a landing pad and is not the conditional branch destination (in TBB) 421 // as the fallthrough successor. 422 MachineBasicBlock *FallthroughBB = nullptr; 423 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) { 424 if ((*SI)->isLandingPad() || *SI == TBB) 425 continue; 426 assert(!FallthroughBB && "Found more than one fallthrough successor."); 427 FallthroughBB = *SI; 428 } 429 if (!FallthroughBB && canFallThrough()) { 430 // We fallthrough to the same basic block as the conditional jump 431 // targets. Remove the conditional jump, leaving unconditional 432 // fallthrough. 433 // FIXME: This does not seem like a reasonable pattern to support, but it 434 // has been seen in the wild coming out of degenerate ARM test cases. 435 TII->RemoveBranch(*this); 436 437 // Finally update the unconditional successor to be reached via a branch 438 // if it would not be reached by fallthrough. 439 if (!isLayoutSuccessor(TBB)) 440 TII->InsertBranch(*this, TBB, nullptr, Cond, dl); 441 return; 442 } 443 444 // The block has a fallthrough conditional branch. 445 if (isLayoutSuccessor(TBB)) { 446 if (TII->ReverseBranchCondition(Cond)) { 447 // We can't reverse the condition, add an unconditional branch. 448 Cond.clear(); 449 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl); 450 return; 451 } 452 TII->RemoveBranch(*this); 453 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl); 454 } else if (!isLayoutSuccessor(FallthroughBB)) { 455 TII->RemoveBranch(*this); 456 TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl); 457 } 458 } 459 } 460 } 461 462 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) { 463 464 // If we see non-zero value for the first time it means we actually use Weight 465 // list, so we fill all Weights with 0's. 466 if (weight != 0 && Weights.empty()) 467 Weights.resize(Successors.size()); 468 469 if (weight != 0 || !Weights.empty()) 470 Weights.push_back(weight); 471 472 Successors.push_back(succ); 473 succ->addPredecessor(this); 474 } 475 476 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) { 477 succ->removePredecessor(this); 478 succ_iterator I = std::find(Successors.begin(), Successors.end(), succ); 479 assert(I != Successors.end() && "Not a current successor!"); 480 481 // If Weight list is empty it means we don't use it (disabled optimization). 482 if (!Weights.empty()) { 483 weight_iterator WI = getWeightIterator(I); 484 Weights.erase(WI); 485 } 486 487 Successors.erase(I); 488 } 489 490 MachineBasicBlock::succ_iterator 491 MachineBasicBlock::removeSuccessor(succ_iterator I) { 492 assert(I != Successors.end() && "Not a current successor!"); 493 494 // If Weight list is empty it means we don't use it (disabled optimization). 495 if (!Weights.empty()) { 496 weight_iterator WI = getWeightIterator(I); 497 Weights.erase(WI); 498 } 499 500 (*I)->removePredecessor(this); 501 return Successors.erase(I); 502 } 503 504 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old, 505 MachineBasicBlock *New) { 506 if (Old == New) 507 return; 508 509 succ_iterator E = succ_end(); 510 succ_iterator NewI = E; 511 succ_iterator OldI = E; 512 for (succ_iterator I = succ_begin(); I != E; ++I) { 513 if (*I == Old) { 514 OldI = I; 515 if (NewI != E) 516 break; 517 } 518 if (*I == New) { 519 NewI = I; 520 if (OldI != E) 521 break; 522 } 523 } 524 assert(OldI != E && "Old is not a successor of this block"); 525 Old->removePredecessor(this); 526 527 // If New isn't already a successor, let it take Old's place. 528 if (NewI == E) { 529 New->addPredecessor(this); 530 *OldI = New; 531 return; 532 } 533 534 // New is already a successor. 535 // Update its weight instead of adding a duplicate edge. 536 if (!Weights.empty()) { 537 weight_iterator OldWI = getWeightIterator(OldI); 538 *getWeightIterator(NewI) += *OldWI; 539 Weights.erase(OldWI); 540 } 541 Successors.erase(OldI); 542 } 543 544 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) { 545 Predecessors.push_back(pred); 546 } 547 548 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) { 549 pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred); 550 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!"); 551 Predecessors.erase(I); 552 } 553 554 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) { 555 if (this == fromMBB) 556 return; 557 558 while (!fromMBB->succ_empty()) { 559 MachineBasicBlock *Succ = *fromMBB->succ_begin(); 560 uint32_t Weight = 0; 561 562 // If Weight list is empty it means we don't use it (disabled optimization). 563 if (!fromMBB->Weights.empty()) 564 Weight = *fromMBB->Weights.begin(); 565 566 addSuccessor(Succ, Weight); 567 fromMBB->removeSuccessor(Succ); 568 } 569 } 570 571 void 572 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) { 573 if (this == fromMBB) 574 return; 575 576 while (!fromMBB->succ_empty()) { 577 MachineBasicBlock *Succ = *fromMBB->succ_begin(); 578 uint32_t Weight = 0; 579 if (!fromMBB->Weights.empty()) 580 Weight = *fromMBB->Weights.begin(); 581 addSuccessor(Succ, Weight); 582 fromMBB->removeSuccessor(Succ); 583 584 // Fix up any PHI nodes in the successor. 585 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(), 586 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI) 587 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) { 588 MachineOperand &MO = MI->getOperand(i); 589 if (MO.getMBB() == fromMBB) 590 MO.setMBB(this); 591 } 592 } 593 } 594 595 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const { 596 return std::find(pred_begin(), pred_end(), MBB) != pred_end(); 597 } 598 599 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const { 600 return std::find(succ_begin(), succ_end(), MBB) != succ_end(); 601 } 602 603 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const { 604 MachineFunction::const_iterator I(this); 605 return std::next(I) == MachineFunction::const_iterator(MBB); 606 } 607 608 bool MachineBasicBlock::canFallThrough() { 609 MachineFunction::iterator Fallthrough = this; 610 ++Fallthrough; 611 // If FallthroughBlock is off the end of the function, it can't fall through. 612 if (Fallthrough == getParent()->end()) 613 return false; 614 615 // If FallthroughBlock isn't a successor, no fallthrough is possible. 616 if (!isSuccessor(Fallthrough)) 617 return false; 618 619 // Analyze the branches, if any, at the end of the block. 620 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 621 SmallVector<MachineOperand, 4> Cond; 622 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 623 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) { 624 // If we couldn't analyze the branch, examine the last instruction. 625 // If the block doesn't end in a known control barrier, assume fallthrough 626 // is possible. The isPredicated check is needed because this code can be 627 // called during IfConversion, where an instruction which is normally a 628 // Barrier is predicated and thus no longer an actual control barrier. 629 return empty() || !back().isBarrier() || TII->isPredicated(&back()); 630 } 631 632 // If there is no branch, control always falls through. 633 if (!TBB) return true; 634 635 // If there is some explicit branch to the fallthrough block, it can obviously 636 // reach, even though the branch should get folded to fall through implicitly. 637 if (MachineFunction::iterator(TBB) == Fallthrough || 638 MachineFunction::iterator(FBB) == Fallthrough) 639 return true; 640 641 // If it's an unconditional branch to some block not the fall through, it 642 // doesn't fall through. 643 if (Cond.empty()) return false; 644 645 // Otherwise, if it is conditional and has no explicit false block, it falls 646 // through. 647 return FBB == nullptr; 648 } 649 650 MachineBasicBlock * 651 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) { 652 // Splitting the critical edge to a landing pad block is non-trivial. Don't do 653 // it in this generic function. 654 if (Succ->isLandingPad()) 655 return nullptr; 656 657 MachineFunction *MF = getParent(); 658 DebugLoc dl; // FIXME: this is nowhere 659 660 // Performance might be harmed on HW that implements branching using exec mask 661 // where both sides of the branches are always executed. 662 if (MF->getTarget().requiresStructuredCFG()) 663 return nullptr; 664 665 // We may need to update this's terminator, but we can't do that if 666 // AnalyzeBranch fails. If this uses a jump table, we won't touch it. 667 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 668 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 669 SmallVector<MachineOperand, 4> Cond; 670 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) 671 return nullptr; 672 673 // Avoid bugpoint weirdness: A block may end with a conditional branch but 674 // jumps to the same MBB is either case. We have duplicate CFG edges in that 675 // case that we can't handle. Since this never happens in properly optimized 676 // code, just skip those edges. 677 if (TBB && TBB == FBB) { 678 DEBUG(dbgs() << "Won't split critical edge after degenerate BB#" 679 << getNumber() << '\n'); 680 return nullptr; 681 } 682 683 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock(); 684 MF->insert(std::next(MachineFunction::iterator(this)), NMBB); 685 DEBUG(dbgs() << "Splitting critical edge:" 686 " BB#" << getNumber() 687 << " -- BB#" << NMBB->getNumber() 688 << " -- BB#" << Succ->getNumber() << '\n'); 689 690 LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>(); 691 SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>(); 692 if (LIS) 693 LIS->insertMBBInMaps(NMBB); 694 else if (Indexes) 695 Indexes->insertMBBInMaps(NMBB); 696 697 // On some targets like Mips, branches may kill virtual registers. Make sure 698 // that LiveVariables is properly updated after updateTerminator replaces the 699 // terminators. 700 LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>(); 701 702 // Collect a list of virtual registers killed by the terminators. 703 SmallVector<unsigned, 4> KilledRegs; 704 if (LV) 705 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 706 I != E; ++I) { 707 MachineInstr *MI = I; 708 for (MachineInstr::mop_iterator OI = MI->operands_begin(), 709 OE = MI->operands_end(); OI != OE; ++OI) { 710 if (!OI->isReg() || OI->getReg() == 0 || 711 !OI->isUse() || !OI->isKill() || OI->isUndef()) 712 continue; 713 unsigned Reg = OI->getReg(); 714 if (TargetRegisterInfo::isPhysicalRegister(Reg) || 715 LV->getVarInfo(Reg).removeKill(MI)) { 716 KilledRegs.push_back(Reg); 717 DEBUG(dbgs() << "Removing terminator kill: " << *MI); 718 OI->setIsKill(false); 719 } 720 } 721 } 722 723 SmallVector<unsigned, 4> UsedRegs; 724 if (LIS) { 725 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 726 I != E; ++I) { 727 MachineInstr *MI = I; 728 729 for (MachineInstr::mop_iterator OI = MI->operands_begin(), 730 OE = MI->operands_end(); OI != OE; ++OI) { 731 if (!OI->isReg() || OI->getReg() == 0) 732 continue; 733 734 unsigned Reg = OI->getReg(); 735 if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end()) 736 UsedRegs.push_back(Reg); 737 } 738 } 739 } 740 741 ReplaceUsesOfBlockWith(Succ, NMBB); 742 743 // If updateTerminator() removes instructions, we need to remove them from 744 // SlotIndexes. 745 SmallVector<MachineInstr*, 4> Terminators; 746 if (Indexes) { 747 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 748 I != E; ++I) 749 Terminators.push_back(I); 750 } 751 752 updateTerminator(); 753 754 if (Indexes) { 755 SmallVector<MachineInstr*, 4> NewTerminators; 756 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 757 I != E; ++I) 758 NewTerminators.push_back(I); 759 760 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(), 761 E = Terminators.end(); I != E; ++I) { 762 if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) == 763 NewTerminators.end()) 764 Indexes->removeMachineInstrFromMaps(*I); 765 } 766 } 767 768 // Insert unconditional "jump Succ" instruction in NMBB if necessary. 769 NMBB->addSuccessor(Succ); 770 if (!NMBB->isLayoutSuccessor(Succ)) { 771 Cond.clear(); 772 MF->getSubtarget().getInstrInfo()->InsertBranch(*NMBB, Succ, nullptr, Cond, 773 dl); 774 775 if (Indexes) { 776 for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end(); 777 I != E; ++I) { 778 // Some instructions may have been moved to NMBB by updateTerminator(), 779 // so we first remove any instruction that already has an index. 780 if (Indexes->hasIndex(I)) 781 Indexes->removeMachineInstrFromMaps(I); 782 Indexes->insertMachineInstrInMaps(I); 783 } 784 } 785 } 786 787 // Fix PHI nodes in Succ so they refer to NMBB instead of this 788 for (MachineBasicBlock::instr_iterator 789 i = Succ->instr_begin(),e = Succ->instr_end(); 790 i != e && i->isPHI(); ++i) 791 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2) 792 if (i->getOperand(ni+1).getMBB() == this) 793 i->getOperand(ni+1).setMBB(NMBB); 794 795 // Inherit live-ins from the successor 796 for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(), 797 E = Succ->livein_end(); I != E; ++I) 798 NMBB->addLiveIn(*I); 799 800 // Update LiveVariables. 801 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 802 if (LV) { 803 // Restore kills of virtual registers that were killed by the terminators. 804 while (!KilledRegs.empty()) { 805 unsigned Reg = KilledRegs.pop_back_val(); 806 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) { 807 if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false)) 808 continue; 809 if (TargetRegisterInfo::isVirtualRegister(Reg)) 810 LV->getVarInfo(Reg).Kills.push_back(I); 811 DEBUG(dbgs() << "Restored terminator kill: " << *I); 812 break; 813 } 814 } 815 // Update relevant live-through information. 816 LV->addNewBlock(NMBB, this, Succ); 817 } 818 819 if (LIS) { 820 // After splitting the edge and updating SlotIndexes, live intervals may be 821 // in one of two situations, depending on whether this block was the last in 822 // the function. If the original block was the last in the function, all live 823 // intervals will end prior to the beginning of the new split block. If the 824 // original block was not at the end of the function, all live intervals will 825 // extend to the end of the new split block. 826 827 bool isLastMBB = 828 std::next(MachineFunction::iterator(NMBB)) == getParent()->end(); 829 830 SlotIndex StartIndex = Indexes->getMBBEndIdx(this); 831 SlotIndex PrevIndex = StartIndex.getPrevSlot(); 832 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB); 833 834 // Find the registers used from NMBB in PHIs in Succ. 835 SmallSet<unsigned, 8> PHISrcRegs; 836 for (MachineBasicBlock::instr_iterator 837 I = Succ->instr_begin(), E = Succ->instr_end(); 838 I != E && I->isPHI(); ++I) { 839 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) { 840 if (I->getOperand(ni+1).getMBB() == NMBB) { 841 MachineOperand &MO = I->getOperand(ni); 842 unsigned Reg = MO.getReg(); 843 PHISrcRegs.insert(Reg); 844 if (MO.isUndef()) 845 continue; 846 847 LiveInterval &LI = LIS->getInterval(Reg); 848 VNInfo *VNI = LI.getVNInfoAt(PrevIndex); 849 assert(VNI && "PHI sources should be live out of their predecessors."); 850 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI)); 851 } 852 } 853 } 854 855 MachineRegisterInfo *MRI = &getParent()->getRegInfo(); 856 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 857 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 858 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg)) 859 continue; 860 861 LiveInterval &LI = LIS->getInterval(Reg); 862 if (!LI.liveAt(PrevIndex)) 863 continue; 864 865 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ)); 866 if (isLiveOut && isLastMBB) { 867 VNInfo *VNI = LI.getVNInfoAt(PrevIndex); 868 assert(VNI && "LiveInterval should have VNInfo where it is live."); 869 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI)); 870 } else if (!isLiveOut && !isLastMBB) { 871 LI.removeSegment(StartIndex, EndIndex); 872 } 873 } 874 875 // Update all intervals for registers whose uses may have been modified by 876 // updateTerminator(). 877 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs); 878 } 879 880 if (MachineDominatorTree *MDT = 881 P->getAnalysisIfAvailable<MachineDominatorTree>()) 882 MDT->recordSplitCriticalEdge(this, Succ, NMBB); 883 884 if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>()) 885 if (MachineLoop *TIL = MLI->getLoopFor(this)) { 886 // If one or the other blocks were not in a loop, the new block is not 887 // either, and thus LI doesn't need to be updated. 888 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) { 889 if (TIL == DestLoop) { 890 // Both in the same loop, the NMBB joins loop. 891 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase()); 892 } else if (TIL->contains(DestLoop)) { 893 // Edge from an outer loop to an inner loop. Add to the outer loop. 894 TIL->addBasicBlockToLoop(NMBB, MLI->getBase()); 895 } else if (DestLoop->contains(TIL)) { 896 // Edge from an inner loop to an outer loop. Add to the outer loop. 897 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase()); 898 } else { 899 // Edge from two loops with no containment relation. Because these 900 // are natural loops, we know that the destination block must be the 901 // header of its loop (adding a branch into a loop elsewhere would 902 // create an irreducible loop). 903 assert(DestLoop->getHeader() == Succ && 904 "Should not create irreducible loops!"); 905 if (MachineLoop *P = DestLoop->getParentLoop()) 906 P->addBasicBlockToLoop(NMBB, MLI->getBase()); 907 } 908 } 909 } 910 911 return NMBB; 912 } 913 914 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's 915 /// neighboring instructions so the bundle won't be broken by removing MI. 916 static void unbundleSingleMI(MachineInstr *MI) { 917 // Removing the first instruction in a bundle. 918 if (MI->isBundledWithSucc() && !MI->isBundledWithPred()) 919 MI->unbundleFromSucc(); 920 // Removing the last instruction in a bundle. 921 if (MI->isBundledWithPred() && !MI->isBundledWithSucc()) 922 MI->unbundleFromPred(); 923 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags 924 // are already fine. 925 } 926 927 MachineBasicBlock::instr_iterator 928 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) { 929 unbundleSingleMI(I); 930 return Insts.erase(I); 931 } 932 933 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) { 934 unbundleSingleMI(MI); 935 MI->clearFlag(MachineInstr::BundledPred); 936 MI->clearFlag(MachineInstr::BundledSucc); 937 return Insts.remove(MI); 938 } 939 940 MachineBasicBlock::instr_iterator 941 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) { 942 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() && 943 "Cannot insert instruction with bundle flags"); 944 // Set the bundle flags when inserting inside a bundle. 945 if (I != instr_end() && I->isBundledWithPred()) { 946 MI->setFlag(MachineInstr::BundledPred); 947 MI->setFlag(MachineInstr::BundledSucc); 948 } 949 return Insts.insert(I, MI); 950 } 951 952 /// removeFromParent - This method unlinks 'this' from the containing function, 953 /// and returns it, but does not delete it. 954 MachineBasicBlock *MachineBasicBlock::removeFromParent() { 955 assert(getParent() && "Not embedded in a function!"); 956 getParent()->remove(this); 957 return this; 958 } 959 960 961 /// eraseFromParent - This method unlinks 'this' from the containing function, 962 /// and deletes it. 963 void MachineBasicBlock::eraseFromParent() { 964 assert(getParent() && "Not embedded in a function!"); 965 getParent()->erase(this); 966 } 967 968 969 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to 970 /// 'Old', change the code and CFG so that it branches to 'New' instead. 971 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old, 972 MachineBasicBlock *New) { 973 assert(Old != New && "Cannot replace self with self!"); 974 975 MachineBasicBlock::instr_iterator I = instr_end(); 976 while (I != instr_begin()) { 977 --I; 978 if (!I->isTerminator()) break; 979 980 // Scan the operands of this machine instruction, replacing any uses of Old 981 // with New. 982 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 983 if (I->getOperand(i).isMBB() && 984 I->getOperand(i).getMBB() == Old) 985 I->getOperand(i).setMBB(New); 986 } 987 988 // Update the successor information. 989 replaceSuccessor(Old, New); 990 } 991 992 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the 993 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and 994 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be 995 /// null. 996 /// 997 /// Besides DestA and DestB, retain other edges leading to LandingPads 998 /// (currently there can be only one; we don't check or require that here). 999 /// Note it is possible that DestA and/or DestB are LandingPads. 1000 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA, 1001 MachineBasicBlock *DestB, 1002 bool isCond) { 1003 // The values of DestA and DestB frequently come from a call to the 1004 // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial 1005 // values from there. 1006 // 1007 // 1. If both DestA and DestB are null, then the block ends with no branches 1008 // (it falls through to its successor). 1009 // 2. If DestA is set, DestB is null, and isCond is false, then the block ends 1010 // with only an unconditional branch. 1011 // 3. If DestA is set, DestB is null, and isCond is true, then the block ends 1012 // with a conditional branch that falls through to a successor (DestB). 1013 // 4. If DestA and DestB is set and isCond is true, then the block ends with a 1014 // conditional branch followed by an unconditional branch. DestA is the 1015 // 'true' destination and DestB is the 'false' destination. 1016 1017 bool Changed = false; 1018 1019 MachineFunction::iterator FallThru = 1020 std::next(MachineFunction::iterator(this)); 1021 1022 if (!DestA && !DestB) { 1023 // Block falls through to successor. 1024 DestA = FallThru; 1025 DestB = FallThru; 1026 } else if (DestA && !DestB) { 1027 if (isCond) 1028 // Block ends in conditional jump that falls through to successor. 1029 DestB = FallThru; 1030 } else { 1031 assert(DestA && DestB && isCond && 1032 "CFG in a bad state. Cannot correct CFG edges"); 1033 } 1034 1035 // Remove superfluous edges. I.e., those which aren't destinations of this 1036 // basic block, duplicate edges, or landing pads. 1037 SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs; 1038 MachineBasicBlock::succ_iterator SI = succ_begin(); 1039 while (SI != succ_end()) { 1040 const MachineBasicBlock *MBB = *SI; 1041 if (!SeenMBBs.insert(MBB).second || 1042 (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) { 1043 // This is a superfluous edge, remove it. 1044 SI = removeSuccessor(SI); 1045 Changed = true; 1046 } else { 1047 ++SI; 1048 } 1049 } 1050 1051 return Changed; 1052 } 1053 1054 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping 1055 /// any DBG_VALUE instructions. Return UnknownLoc if there is none. 1056 DebugLoc 1057 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) { 1058 DebugLoc DL; 1059 instr_iterator E = instr_end(); 1060 if (MBBI == E) 1061 return DL; 1062 1063 // Skip debug declarations, we don't want a DebugLoc from them. 1064 while (MBBI != E && MBBI->isDebugValue()) 1065 MBBI++; 1066 if (MBBI != E) 1067 DL = MBBI->getDebugLoc(); 1068 return DL; 1069 } 1070 1071 /// getSuccWeight - Return weight of the edge from this block to MBB. 1072 /// 1073 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const { 1074 if (Weights.empty()) 1075 return 0; 1076 1077 return *getWeightIterator(Succ); 1078 } 1079 1080 /// Set successor weight of a given iterator. 1081 void MachineBasicBlock::setSuccWeight(succ_iterator I, uint32_t weight) { 1082 if (Weights.empty()) 1083 return; 1084 *getWeightIterator(I) = weight; 1085 } 1086 1087 /// getWeightIterator - Return wight iterator corresonding to the I successor 1088 /// iterator 1089 MachineBasicBlock::weight_iterator MachineBasicBlock:: 1090 getWeightIterator(MachineBasicBlock::succ_iterator I) { 1091 assert(Weights.size() == Successors.size() && "Async weight list!"); 1092 size_t index = std::distance(Successors.begin(), I); 1093 assert(index < Weights.size() && "Not a current successor!"); 1094 return Weights.begin() + index; 1095 } 1096 1097 /// getWeightIterator - Return wight iterator corresonding to the I successor 1098 /// iterator 1099 MachineBasicBlock::const_weight_iterator MachineBasicBlock:: 1100 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const { 1101 assert(Weights.size() == Successors.size() && "Async weight list!"); 1102 const size_t index = std::distance(Successors.begin(), I); 1103 assert(index < Weights.size() && "Not a current successor!"); 1104 return Weights.begin() + index; 1105 } 1106 1107 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed 1108 /// as of just before "MI". 1109 /// 1110 /// Search is localised to a neighborhood of 1111 /// Neighborhood instructions before (searching for defs or kills) and N 1112 /// instructions after (searching just for defs) MI. 1113 MachineBasicBlock::LivenessQueryResult 1114 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI, 1115 unsigned Reg, const_iterator Before, 1116 unsigned Neighborhood) const { 1117 unsigned N = Neighborhood; 1118 1119 // Start by searching backwards from Before, looking for kills, reads or defs. 1120 const_iterator I(Before); 1121 // If this is the first insn in the block, don't search backwards. 1122 if (I != begin()) { 1123 do { 1124 --I; 1125 1126 MachineOperandIteratorBase::PhysRegInfo Analysis = 1127 ConstMIOperands(I).analyzePhysReg(Reg, TRI); 1128 1129 if (Analysis.Defines) 1130 // Outputs happen after inputs so they take precedence if both are 1131 // present. 1132 return Analysis.DefinesDead ? LQR_Dead : LQR_Live; 1133 1134 if (Analysis.Kills || Analysis.Clobbers) 1135 // Register killed, so isn't live. 1136 return LQR_Dead; 1137 1138 else if (Analysis.ReadsOverlap) 1139 // Defined or read without a previous kill - live. 1140 return Analysis.Reads ? LQR_Live : LQR_OverlappingLive; 1141 1142 } while (I != begin() && --N > 0); 1143 } 1144 1145 // Did we get to the start of the block? 1146 if (I == begin()) { 1147 // If so, the register's state is definitely defined by the live-in state. 1148 for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true); 1149 RAI.isValid(); ++RAI) { 1150 if (isLiveIn(*RAI)) 1151 return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive; 1152 } 1153 1154 return LQR_Dead; 1155 } 1156 1157 N = Neighborhood; 1158 1159 // Try searching forwards from Before, looking for reads or defs. 1160 I = const_iterator(Before); 1161 // If this is the last insn in the block, don't search forwards. 1162 if (I != end()) { 1163 for (++I; I != end() && N > 0; ++I, --N) { 1164 MachineOperandIteratorBase::PhysRegInfo Analysis = 1165 ConstMIOperands(I).analyzePhysReg(Reg, TRI); 1166 1167 if (Analysis.ReadsOverlap) 1168 // Used, therefore must have been live. 1169 return (Analysis.Reads) ? 1170 LQR_Live : LQR_OverlappingLive; 1171 1172 else if (Analysis.Clobbers || Analysis.Defines) 1173 // Defined (but not read) therefore cannot have been live. 1174 return LQR_Dead; 1175 } 1176 } 1177 1178 // At this point we have no idea of the liveness of the register. 1179 return LQR_Unknown; 1180 } 1181