MachineBasicBlock.cpp 42 KB

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