MachineBasicBlock.cpp 44 KB

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