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