MachineBasicBlock.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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/BasicBlock.h"
  15. #include "llvm/CodeGen/LiveVariables.h"
  16. #include "llvm/CodeGen/MachineDominators.h"
  17. #include "llvm/CodeGen/MachineFunction.h"
  18. #include "llvm/CodeGen/MachineLoopInfo.h"
  19. #include "llvm/CodeGen/SlotIndexes.h"
  20. #include "llvm/MC/MCAsmInfo.h"
  21. #include "llvm/MC/MCContext.h"
  22. #include "llvm/Target/TargetRegisterInfo.h"
  23. #include "llvm/Target/TargetData.h"
  24. #include "llvm/Target/TargetInstrInfo.h"
  25. #include "llvm/Target/TargetMachine.h"
  26. #include "llvm/Assembly/Writer.h"
  27. #include "llvm/ADT/SmallString.h"
  28. #include "llvm/ADT/SmallPtrSet.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/LeakDetector.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <algorithm>
  33. using namespace llvm;
  34. MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
  35. : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
  36. AddressTaken(false) {
  37. Insts.Parent = this;
  38. }
  39. MachineBasicBlock::~MachineBasicBlock() {
  40. LeakDetector::removeGarbageObject(this);
  41. }
  42. /// getSymbol - Return the MCSymbol for this basic block.
  43. ///
  44. MCSymbol *MachineBasicBlock::getSymbol() const {
  45. const MachineFunction *MF = getParent();
  46. MCContext &Ctx = MF->getContext();
  47. const char *Prefix = Ctx.getAsmInfo().getPrivateGlobalPrefix();
  48. return Ctx.GetOrCreateSymbol(Twine(Prefix) + "BB" +
  49. Twine(MF->getFunctionNumber()) + "_" +
  50. Twine(getNumber()));
  51. }
  52. raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
  53. MBB.print(OS);
  54. return OS;
  55. }
  56. /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
  57. /// parent pointer of the MBB, the MBB numbering, and any instructions in the
  58. /// MBB to be on the right operand list for registers.
  59. ///
  60. /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
  61. /// gets the next available unique MBB number. If it is removed from a
  62. /// MachineFunction, it goes back to being #-1.
  63. void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
  64. MachineFunction &MF = *N->getParent();
  65. N->Number = MF.addToMBBNumbering(N);
  66. // Make sure the instructions have their operands in the reginfo lists.
  67. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  68. for (MachineBasicBlock::instr_iterator
  69. I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
  70. I->AddRegOperandsToUseLists(RegInfo);
  71. LeakDetector::removeGarbageObject(N);
  72. }
  73. void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
  74. N->getParent()->removeFromMBBNumbering(N->Number);
  75. N->Number = -1;
  76. LeakDetector::addGarbageObject(N);
  77. }
  78. /// addNodeToList (MI) - When we add an instruction to a basic block
  79. /// list, we update its parent pointer and add its operands from reg use/def
  80. /// lists if appropriate.
  81. void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
  82. assert(N->getParent() == 0 && "machine instruction already in a basic block");
  83. N->setParent(Parent);
  84. // Add the instruction's register operands to their corresponding
  85. // use/def lists.
  86. MachineFunction *MF = Parent->getParent();
  87. N->AddRegOperandsToUseLists(MF->getRegInfo());
  88. LeakDetector::removeGarbageObject(N);
  89. }
  90. /// removeNodeFromList (MI) - When we remove an instruction from a basic block
  91. /// list, we update its parent pointer and remove its operands from reg use/def
  92. /// lists if appropriate.
  93. void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
  94. assert(N->getParent() != 0 && "machine instruction not in a basic block");
  95. // Remove from the use/def lists.
  96. if (MachineFunction *MF = N->getParent()->getParent())
  97. N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
  98. N->setParent(0);
  99. LeakDetector::addGarbageObject(N);
  100. }
  101. /// transferNodesFromList (MI) - When moving a range of instructions from one
  102. /// MBB list to another, we need to update the parent pointers and the use/def
  103. /// lists.
  104. void ilist_traits<MachineInstr>::
  105. transferNodesFromList(ilist_traits<MachineInstr> &fromList,
  106. ilist_iterator<MachineInstr> first,
  107. ilist_iterator<MachineInstr> last) {
  108. assert(Parent->getParent() == fromList.Parent->getParent() &&
  109. "MachineInstr parent mismatch!");
  110. // Splice within the same MBB -> no change.
  111. if (Parent == fromList.Parent) return;
  112. // If splicing between two blocks within the same function, just update the
  113. // parent pointers.
  114. for (; first != last; ++first)
  115. first->setParent(Parent);
  116. }
  117. void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
  118. assert(!MI->getParent() && "MI is still in a block!");
  119. Parent->getParent()->DeleteMachineInstr(MI);
  120. }
  121. MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
  122. instr_iterator I = instr_begin(), E = instr_end();
  123. while (I != E && I->isPHI())
  124. ++I;
  125. assert(!I->isInsideBundle() && "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->isLabel() || 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->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::const_iterator
  148. MachineBasicBlock::getFirstTerminator() const {
  149. const_iterator B = begin(), E = end(), I = E;
  150. while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
  151. ; /*noop */
  152. while (I != E && !I->isTerminator())
  153. ++I;
  154. return I;
  155. }
  156. MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
  157. instr_iterator B = instr_begin(), E = instr_end(), I = E;
  158. while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
  159. ; /*noop */
  160. while (I != E && !I->isTerminator())
  161. ++I;
  162. return I;
  163. }
  164. MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
  165. // Skip over end-of-block dbg_value instructions.
  166. instr_iterator B = instr_begin(), I = instr_end();
  167. while (I != B) {
  168. --I;
  169. // Return instruction that starts a bundle.
  170. if (I->isDebugValue() || I->isInsideBundle())
  171. continue;
  172. return I;
  173. }
  174. // The block is all debug values.
  175. return end();
  176. }
  177. MachineBasicBlock::const_iterator
  178. MachineBasicBlock::getLastNonDebugInstr() const {
  179. // Skip over end-of-block dbg_value instructions.
  180. const_instr_iterator B = instr_begin(), I = instr_end();
  181. while (I != B) {
  182. --I;
  183. // Return instruction that starts a bundle.
  184. if (I->isDebugValue() || I->isInsideBundle())
  185. continue;
  186. return I;
  187. }
  188. // The block is all debug values.
  189. return end();
  190. }
  191. const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
  192. // A block with a landing pad successor only has one other successor.
  193. if (succ_size() > 2)
  194. return 0;
  195. for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
  196. if ((*I)->isLandingPad())
  197. return *I;
  198. return 0;
  199. }
  200. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  201. void MachineBasicBlock::dump() const {
  202. print(dbgs());
  203. }
  204. #endif
  205. StringRef MachineBasicBlock::getName() const {
  206. if (const BasicBlock *LBB = getBasicBlock())
  207. return LBB->getName();
  208. else
  209. return "(null)";
  210. }
  211. /// Return a hopefully unique identifier for this block.
  212. std::string MachineBasicBlock::getFullName() const {
  213. std::string Name;
  214. if (getParent())
  215. Name = (getParent()->getName() + ":").str();
  216. if (getBasicBlock())
  217. Name += getBasicBlock()->getName();
  218. else
  219. Name += (Twine("BB") + Twine(getNumber())).str();
  220. return Name;
  221. }
  222. void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
  223. const MachineFunction *MF = getParent();
  224. if (!MF) {
  225. OS << "Can't print out MachineBasicBlock because parent MachineFunction"
  226. << " is null\n";
  227. return;
  228. }
  229. if (Indexes)
  230. OS << Indexes->getMBBStartIdx(this) << '\t';
  231. OS << "BB#" << getNumber() << ": ";
  232. const char *Comma = "";
  233. if (const BasicBlock *LBB = getBasicBlock()) {
  234. OS << Comma << "derived from LLVM BB ";
  235. WriteAsOperand(OS, LBB, /*PrintType=*/false);
  236. Comma = ", ";
  237. }
  238. if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
  239. if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
  240. if (Alignment)
  241. OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
  242. << " bytes)";
  243. OS << '\n';
  244. const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
  245. if (!livein_empty()) {
  246. if (Indexes) OS << '\t';
  247. OS << " Live Ins:";
  248. for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
  249. OS << ' ' << PrintReg(*I, TRI);
  250. OS << '\n';
  251. }
  252. // Print the preds of this block according to the CFG.
  253. if (!pred_empty()) {
  254. if (Indexes) OS << '\t';
  255. OS << " Predecessors according to CFG:";
  256. for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
  257. OS << " BB#" << (*PI)->getNumber();
  258. OS << '\n';
  259. }
  260. for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
  261. if (Indexes) {
  262. if (Indexes->hasIndex(I))
  263. OS << Indexes->getInstructionIndex(I);
  264. OS << '\t';
  265. }
  266. OS << '\t';
  267. if (I->isInsideBundle())
  268. OS << " * ";
  269. I->print(OS, &getParent()->getTarget());
  270. }
  271. // Print the successors of this block according to the CFG.
  272. if (!succ_empty()) {
  273. if (Indexes) OS << '\t';
  274. OS << " Successors according to CFG:";
  275. for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
  276. OS << " BB#" << (*SI)->getNumber();
  277. if (!Weights.empty())
  278. OS << '(' << *getWeightIterator(SI) << ')';
  279. }
  280. OS << '\n';
  281. }
  282. }
  283. void MachineBasicBlock::removeLiveIn(unsigned Reg) {
  284. std::vector<unsigned>::iterator I =
  285. std::find(LiveIns.begin(), LiveIns.end(), Reg);
  286. if (I != LiveIns.end())
  287. LiveIns.erase(I);
  288. }
  289. bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
  290. livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
  291. return I != livein_end();
  292. }
  293. void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
  294. getParent()->splice(NewAfter, this);
  295. }
  296. void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
  297. MachineFunction::iterator BBI = NewBefore;
  298. getParent()->splice(++BBI, this);
  299. }
  300. void MachineBasicBlock::updateTerminator() {
  301. const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
  302. // A block with no successors has no concerns with fall-through edges.
  303. if (this->succ_empty()) return;
  304. MachineBasicBlock *TBB = 0, *FBB = 0;
  305. SmallVector<MachineOperand, 4> Cond;
  306. DebugLoc dl; // FIXME: this is nowhere
  307. bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
  308. (void) B;
  309. assert(!B && "UpdateTerminators requires analyzable predecessors!");
  310. if (Cond.empty()) {
  311. if (TBB) {
  312. // The block has an unconditional branch. If its successor is now
  313. // its layout successor, delete the branch.
  314. if (isLayoutSuccessor(TBB))
  315. TII->RemoveBranch(*this);
  316. } else {
  317. // The block has an unconditional fallthrough. If its successor is not
  318. // its layout successor, insert a branch. First we have to locate the
  319. // only non-landing-pad successor, as that is the fallthrough block.
  320. for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
  321. if ((*SI)->isLandingPad())
  322. continue;
  323. assert(!TBB && "Found more than one non-landing-pad successor!");
  324. TBB = *SI;
  325. }
  326. // If there is no non-landing-pad successor, the block has no
  327. // fall-through edges to be concerned with.
  328. if (!TBB)
  329. return;
  330. // Finally update the unconditional successor to be reached via a branch
  331. // if it would not be reached by fallthrough.
  332. if (!isLayoutSuccessor(TBB))
  333. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  334. }
  335. } else {
  336. if (FBB) {
  337. // The block has a non-fallthrough conditional branch. If one of its
  338. // successors is its layout successor, rewrite it to a fallthrough
  339. // conditional branch.
  340. if (isLayoutSuccessor(TBB)) {
  341. if (TII->ReverseBranchCondition(Cond))
  342. return;
  343. TII->RemoveBranch(*this);
  344. TII->InsertBranch(*this, FBB, 0, Cond, dl);
  345. } else if (isLayoutSuccessor(FBB)) {
  346. TII->RemoveBranch(*this);
  347. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  348. }
  349. } else {
  350. // Walk through the successors and find the successor which is not
  351. // a landing pad and is not the conditional branch destination (in TBB)
  352. // as the fallthrough successor.
  353. MachineBasicBlock *FallthroughBB = 0;
  354. for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
  355. if ((*SI)->isLandingPad() || *SI == TBB)
  356. continue;
  357. assert(!FallthroughBB && "Found more than one fallthrough successor.");
  358. FallthroughBB = *SI;
  359. }
  360. if (!FallthroughBB && canFallThrough()) {
  361. // We fallthrough to the same basic block as the conditional jump
  362. // targets. Remove the conditional jump, leaving unconditional
  363. // fallthrough.
  364. // FIXME: This does not seem like a reasonable pattern to support, but it
  365. // has been seen in the wild coming out of degenerate ARM test cases.
  366. TII->RemoveBranch(*this);
  367. // Finally update the unconditional successor to be reached via a branch
  368. // if it would not be reached by fallthrough.
  369. if (!isLayoutSuccessor(TBB))
  370. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  371. return;
  372. }
  373. // The block has a fallthrough conditional branch.
  374. if (isLayoutSuccessor(TBB)) {
  375. if (TII->ReverseBranchCondition(Cond)) {
  376. // We can't reverse the condition, add an unconditional branch.
  377. Cond.clear();
  378. TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
  379. return;
  380. }
  381. TII->RemoveBranch(*this);
  382. TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
  383. } else if (!isLayoutSuccessor(FallthroughBB)) {
  384. TII->RemoveBranch(*this);
  385. TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
  386. }
  387. }
  388. }
  389. }
  390. void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
  391. // If we see non-zero value for the first time it means we actually use Weight
  392. // list, so we fill all Weights with 0's.
  393. if (weight != 0 && Weights.empty())
  394. Weights.resize(Successors.size());
  395. if (weight != 0 || !Weights.empty())
  396. Weights.push_back(weight);
  397. Successors.push_back(succ);
  398. succ->addPredecessor(this);
  399. }
  400. void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
  401. succ->removePredecessor(this);
  402. succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
  403. assert(I != Successors.end() && "Not a current successor!");
  404. // If Weight list is empty it means we don't use it (disabled optimization).
  405. if (!Weights.empty()) {
  406. weight_iterator WI = getWeightIterator(I);
  407. Weights.erase(WI);
  408. }
  409. Successors.erase(I);
  410. }
  411. MachineBasicBlock::succ_iterator
  412. MachineBasicBlock::removeSuccessor(succ_iterator I) {
  413. assert(I != Successors.end() && "Not a current successor!");
  414. // If Weight list is empty it means we don't use it (disabled optimization).
  415. if (!Weights.empty()) {
  416. weight_iterator WI = getWeightIterator(I);
  417. Weights.erase(WI);
  418. }
  419. (*I)->removePredecessor(this);
  420. return Successors.erase(I);
  421. }
  422. void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
  423. MachineBasicBlock *New) {
  424. if (Old == New)
  425. return;
  426. succ_iterator E = succ_end();
  427. succ_iterator NewI = E;
  428. succ_iterator OldI = E;
  429. for (succ_iterator I = succ_begin(); I != E; ++I) {
  430. if (*I == Old) {
  431. OldI = I;
  432. if (NewI != E)
  433. break;
  434. }
  435. if (*I == New) {
  436. NewI = I;
  437. if (OldI != E)
  438. break;
  439. }
  440. }
  441. assert(OldI != E && "Old is not a successor of this block");
  442. Old->removePredecessor(this);
  443. // If New isn't already a successor, let it take Old's place.
  444. if (NewI == E) {
  445. New->addPredecessor(this);
  446. *OldI = New;
  447. return;
  448. }
  449. // New is already a successor.
  450. // Update its weight instead of adding a duplicate edge.
  451. if (!Weights.empty()) {
  452. weight_iterator OldWI = getWeightIterator(OldI);
  453. *getWeightIterator(NewI) += *OldWI;
  454. Weights.erase(OldWI);
  455. }
  456. Successors.erase(OldI);
  457. }
  458. void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
  459. Predecessors.push_back(pred);
  460. }
  461. void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
  462. pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
  463. assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
  464. Predecessors.erase(I);
  465. }
  466. void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
  467. if (this == fromMBB)
  468. return;
  469. while (!fromMBB->succ_empty()) {
  470. MachineBasicBlock *Succ = *fromMBB->succ_begin();
  471. uint32_t Weight = 0;
  472. // If Weight list is empty it means we don't use it (disabled optimization).
  473. if (!fromMBB->Weights.empty())
  474. Weight = *fromMBB->Weights.begin();
  475. addSuccessor(Succ, Weight);
  476. fromMBB->removeSuccessor(Succ);
  477. }
  478. }
  479. void
  480. MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
  481. if (this == fromMBB)
  482. return;
  483. while (!fromMBB->succ_empty()) {
  484. MachineBasicBlock *Succ = *fromMBB->succ_begin();
  485. uint32_t Weight = 0;
  486. if (!fromMBB->Weights.empty())
  487. Weight = *fromMBB->Weights.begin();
  488. addSuccessor(Succ, Weight);
  489. fromMBB->removeSuccessor(Succ);
  490. // Fix up any PHI nodes in the successor.
  491. for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
  492. ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
  493. for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
  494. MachineOperand &MO = MI->getOperand(i);
  495. if (MO.getMBB() == fromMBB)
  496. MO.setMBB(this);
  497. }
  498. }
  499. }
  500. bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
  501. return std::find(pred_begin(), pred_end(), MBB) != pred_end();
  502. }
  503. bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
  504. return std::find(succ_begin(), succ_end(), MBB) != succ_end();
  505. }
  506. bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
  507. MachineFunction::const_iterator I(this);
  508. return llvm::next(I) == MachineFunction::const_iterator(MBB);
  509. }
  510. bool MachineBasicBlock::canFallThrough() {
  511. MachineFunction::iterator Fallthrough = this;
  512. ++Fallthrough;
  513. // If FallthroughBlock is off the end of the function, it can't fall through.
  514. if (Fallthrough == getParent()->end())
  515. return false;
  516. // If FallthroughBlock isn't a successor, no fallthrough is possible.
  517. if (!isSuccessor(Fallthrough))
  518. return false;
  519. // Analyze the branches, if any, at the end of the block.
  520. MachineBasicBlock *TBB = 0, *FBB = 0;
  521. SmallVector<MachineOperand, 4> Cond;
  522. const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
  523. if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
  524. // If we couldn't analyze the branch, examine the last instruction.
  525. // If the block doesn't end in a known control barrier, assume fallthrough
  526. // is possible. The isPredicated check is needed because this code can be
  527. // called during IfConversion, where an instruction which is normally a
  528. // Barrier is predicated and thus no longer an actual control barrier.
  529. return empty() || !back().isBarrier() || TII->isPredicated(&back());
  530. }
  531. // If there is no branch, control always falls through.
  532. if (TBB == 0) return true;
  533. // If there is some explicit branch to the fallthrough block, it can obviously
  534. // reach, even though the branch should get folded to fall through implicitly.
  535. if (MachineFunction::iterator(TBB) == Fallthrough ||
  536. MachineFunction::iterator(FBB) == Fallthrough)
  537. return true;
  538. // If it's an unconditional branch to some block not the fall through, it
  539. // doesn't fall through.
  540. if (Cond.empty()) return false;
  541. // Otherwise, if it is conditional and has no explicit false block, it falls
  542. // through.
  543. return FBB == 0;
  544. }
  545. MachineBasicBlock *
  546. MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
  547. // Splitting the critical edge to a landing pad block is non-trivial. Don't do
  548. // it in this generic function.
  549. if (Succ->isLandingPad())
  550. return NULL;
  551. MachineFunction *MF = getParent();
  552. DebugLoc dl; // FIXME: this is nowhere
  553. // We may need to update this's terminator, but we can't do that if
  554. // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
  555. const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
  556. MachineBasicBlock *TBB = 0, *FBB = 0;
  557. SmallVector<MachineOperand, 4> Cond;
  558. if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
  559. return NULL;
  560. // Avoid bugpoint weirdness: A block may end with a conditional branch but
  561. // jumps to the same MBB is either case. We have duplicate CFG edges in that
  562. // case that we can't handle. Since this never happens in properly optimized
  563. // code, just skip those edges.
  564. if (TBB && TBB == FBB) {
  565. DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
  566. << getNumber() << '\n');
  567. return NULL;
  568. }
  569. MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
  570. MF->insert(llvm::next(MachineFunction::iterator(this)), NMBB);
  571. DEBUG(dbgs() << "Splitting critical edge:"
  572. " BB#" << getNumber()
  573. << " -- BB#" << NMBB->getNumber()
  574. << " -- BB#" << Succ->getNumber() << '\n');
  575. // On some targets like Mips, branches may kill virtual registers. Make sure
  576. // that LiveVariables is properly updated after updateTerminator replaces the
  577. // terminators.
  578. LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
  579. // Collect a list of virtual registers killed by the terminators.
  580. SmallVector<unsigned, 4> KilledRegs;
  581. if (LV)
  582. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  583. I != E; ++I) {
  584. MachineInstr *MI = I;
  585. for (MachineInstr::mop_iterator OI = MI->operands_begin(),
  586. OE = MI->operands_end(); OI != OE; ++OI) {
  587. if (!OI->isReg() || OI->getReg() == 0 ||
  588. !OI->isUse() || !OI->isKill() || OI->isUndef())
  589. continue;
  590. unsigned Reg = OI->getReg();
  591. if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
  592. LV->getVarInfo(Reg).removeKill(MI)) {
  593. KilledRegs.push_back(Reg);
  594. DEBUG(dbgs() << "Removing terminator kill: " << *MI);
  595. OI->setIsKill(false);
  596. }
  597. }
  598. }
  599. ReplaceUsesOfBlockWith(Succ, NMBB);
  600. updateTerminator();
  601. // Insert unconditional "jump Succ" instruction in NMBB if necessary.
  602. NMBB->addSuccessor(Succ);
  603. if (!NMBB->isLayoutSuccessor(Succ)) {
  604. Cond.clear();
  605. MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, Succ, NULL, Cond, dl);
  606. }
  607. // Fix PHI nodes in Succ so they refer to NMBB instead of this
  608. for (MachineBasicBlock::instr_iterator
  609. i = Succ->instr_begin(),e = Succ->instr_end();
  610. i != e && i->isPHI(); ++i)
  611. for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
  612. if (i->getOperand(ni+1).getMBB() == this)
  613. i->getOperand(ni+1).setMBB(NMBB);
  614. // Inherit live-ins from the successor
  615. for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
  616. E = Succ->livein_end(); I != E; ++I)
  617. NMBB->addLiveIn(*I);
  618. // Update LiveVariables.
  619. const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
  620. if (LV) {
  621. // Restore kills of virtual registers that were killed by the terminators.
  622. while (!KilledRegs.empty()) {
  623. unsigned Reg = KilledRegs.pop_back_val();
  624. for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
  625. if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
  626. continue;
  627. if (TargetRegisterInfo::isVirtualRegister(Reg))
  628. LV->getVarInfo(Reg).Kills.push_back(I);
  629. DEBUG(dbgs() << "Restored terminator kill: " << *I);
  630. break;
  631. }
  632. }
  633. // Update relevant live-through information.
  634. LV->addNewBlock(NMBB, this, Succ);
  635. }
  636. if (MachineDominatorTree *MDT =
  637. P->getAnalysisIfAvailable<MachineDominatorTree>()) {
  638. // Update dominator information.
  639. MachineDomTreeNode *SucccDTNode = MDT->getNode(Succ);
  640. bool IsNewIDom = true;
  641. for (const_pred_iterator PI = Succ->pred_begin(), E = Succ->pred_end();
  642. PI != E; ++PI) {
  643. MachineBasicBlock *PredBB = *PI;
  644. if (PredBB == NMBB)
  645. continue;
  646. if (!MDT->dominates(SucccDTNode, MDT->getNode(PredBB))) {
  647. IsNewIDom = false;
  648. break;
  649. }
  650. }
  651. // We know "this" dominates the newly created basic block.
  652. MachineDomTreeNode *NewDTNode = MDT->addNewBlock(NMBB, this);
  653. // If all the other predecessors of "Succ" are dominated by "Succ" itself
  654. // then the new block is the new immediate dominator of "Succ". Otherwise,
  655. // the new block doesn't dominate anything.
  656. if (IsNewIDom)
  657. MDT->changeImmediateDominator(SucccDTNode, NewDTNode);
  658. }
  659. if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
  660. if (MachineLoop *TIL = MLI->getLoopFor(this)) {
  661. // If one or the other blocks were not in a loop, the new block is not
  662. // either, and thus LI doesn't need to be updated.
  663. if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
  664. if (TIL == DestLoop) {
  665. // Both in the same loop, the NMBB joins loop.
  666. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  667. } else if (TIL->contains(DestLoop)) {
  668. // Edge from an outer loop to an inner loop. Add to the outer loop.
  669. TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
  670. } else if (DestLoop->contains(TIL)) {
  671. // Edge from an inner loop to an outer loop. Add to the outer loop.
  672. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  673. } else {
  674. // Edge from two loops with no containment relation. Because these
  675. // are natural loops, we know that the destination block must be the
  676. // header of its loop (adding a branch into a loop elsewhere would
  677. // create an irreducible loop).
  678. assert(DestLoop->getHeader() == Succ &&
  679. "Should not create irreducible loops!");
  680. if (MachineLoop *P = DestLoop->getParentLoop())
  681. P->addBasicBlockToLoop(NMBB, MLI->getBase());
  682. }
  683. }
  684. }
  685. return NMBB;
  686. }
  687. MachineBasicBlock::iterator
  688. MachineBasicBlock::erase(MachineBasicBlock::iterator I) {
  689. if (I->isBundle()) {
  690. MachineBasicBlock::iterator E = llvm::next(I);
  691. return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
  692. }
  693. return Insts.erase(I.getInstrIterator());
  694. }
  695. MachineInstr *MachineBasicBlock::remove(MachineInstr *I) {
  696. if (I->isBundle()) {
  697. instr_iterator MII = llvm::next(I);
  698. iterator E = end();
  699. while (MII != E && MII->isInsideBundle()) {
  700. MachineInstr *MI = &*MII++;
  701. Insts.remove(MI);
  702. }
  703. }
  704. return Insts.remove(I);
  705. }
  706. void MachineBasicBlock::splice(MachineBasicBlock::iterator where,
  707. MachineBasicBlock *Other,
  708. MachineBasicBlock::iterator From) {
  709. if (From->isBundle()) {
  710. MachineBasicBlock::iterator To = llvm::next(From);
  711. Insts.splice(where.getInstrIterator(), Other->Insts,
  712. From.getInstrIterator(), To.getInstrIterator());
  713. return;
  714. }
  715. Insts.splice(where.getInstrIterator(), Other->Insts, From.getInstrIterator());
  716. }
  717. /// removeFromParent - This method unlinks 'this' from the containing function,
  718. /// and returns it, but does not delete it.
  719. MachineBasicBlock *MachineBasicBlock::removeFromParent() {
  720. assert(getParent() && "Not embedded in a function!");
  721. getParent()->remove(this);
  722. return this;
  723. }
  724. /// eraseFromParent - This method unlinks 'this' from the containing function,
  725. /// and deletes it.
  726. void MachineBasicBlock::eraseFromParent() {
  727. assert(getParent() && "Not embedded in a function!");
  728. getParent()->erase(this);
  729. }
  730. /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
  731. /// 'Old', change the code and CFG so that it branches to 'New' instead.
  732. void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
  733. MachineBasicBlock *New) {
  734. assert(Old != New && "Cannot replace self with self!");
  735. MachineBasicBlock::instr_iterator I = instr_end();
  736. while (I != instr_begin()) {
  737. --I;
  738. if (!I->isTerminator()) break;
  739. // Scan the operands of this machine instruction, replacing any uses of Old
  740. // with New.
  741. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  742. if (I->getOperand(i).isMBB() &&
  743. I->getOperand(i).getMBB() == Old)
  744. I->getOperand(i).setMBB(New);
  745. }
  746. // Update the successor information.
  747. replaceSuccessor(Old, New);
  748. }
  749. /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
  750. /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
  751. /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be
  752. /// null.
  753. ///
  754. /// Besides DestA and DestB, retain other edges leading to LandingPads
  755. /// (currently there can be only one; we don't check or require that here).
  756. /// Note it is possible that DestA and/or DestB are LandingPads.
  757. bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
  758. MachineBasicBlock *DestB,
  759. bool isCond) {
  760. // The values of DestA and DestB frequently come from a call to the
  761. // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
  762. // values from there.
  763. //
  764. // 1. If both DestA and DestB are null, then the block ends with no branches
  765. // (it falls through to its successor).
  766. // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
  767. // with only an unconditional branch.
  768. // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
  769. // with a conditional branch that falls through to a successor (DestB).
  770. // 4. If DestA and DestB is set and isCond is true, then the block ends with a
  771. // conditional branch followed by an unconditional branch. DestA is the
  772. // 'true' destination and DestB is the 'false' destination.
  773. bool Changed = false;
  774. MachineFunction::iterator FallThru =
  775. llvm::next(MachineFunction::iterator(this));
  776. if (DestA == 0 && DestB == 0) {
  777. // Block falls through to successor.
  778. DestA = FallThru;
  779. DestB = FallThru;
  780. } else if (DestA != 0 && DestB == 0) {
  781. if (isCond)
  782. // Block ends in conditional jump that falls through to successor.
  783. DestB = FallThru;
  784. } else {
  785. assert(DestA && DestB && isCond &&
  786. "CFG in a bad state. Cannot correct CFG edges");
  787. }
  788. // Remove superfluous edges. I.e., those which aren't destinations of this
  789. // basic block, duplicate edges, or landing pads.
  790. SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
  791. MachineBasicBlock::succ_iterator SI = succ_begin();
  792. while (SI != succ_end()) {
  793. const MachineBasicBlock *MBB = *SI;
  794. if (!SeenMBBs.insert(MBB) ||
  795. (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
  796. // This is a superfluous edge, remove it.
  797. SI = removeSuccessor(SI);
  798. Changed = true;
  799. } else {
  800. ++SI;
  801. }
  802. }
  803. return Changed;
  804. }
  805. /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
  806. /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
  807. DebugLoc
  808. MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
  809. DebugLoc DL;
  810. instr_iterator E = instr_end();
  811. if (MBBI == E)
  812. return DL;
  813. // Skip debug declarations, we don't want a DebugLoc from them.
  814. while (MBBI != E && MBBI->isDebugValue())
  815. MBBI++;
  816. if (MBBI != E)
  817. DL = MBBI->getDebugLoc();
  818. return DL;
  819. }
  820. /// getSuccWeight - Return weight of the edge from this block to MBB.
  821. ///
  822. uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
  823. if (Weights.empty())
  824. return 0;
  825. return *getWeightIterator(Succ);
  826. }
  827. /// getWeightIterator - Return wight iterator corresonding to the I successor
  828. /// iterator
  829. MachineBasicBlock::weight_iterator MachineBasicBlock::
  830. getWeightIterator(MachineBasicBlock::succ_iterator I) {
  831. assert(Weights.size() == Successors.size() && "Async weight list!");
  832. size_t index = std::distance(Successors.begin(), I);
  833. assert(index < Weights.size() && "Not a current successor!");
  834. return Weights.begin() + index;
  835. }
  836. /// getWeightIterator - Return wight iterator corresonding to the I successor
  837. /// iterator
  838. MachineBasicBlock::const_weight_iterator MachineBasicBlock::
  839. getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
  840. assert(Weights.size() == Successors.size() && "Async weight list!");
  841. const size_t index = std::distance(Successors.begin(), I);
  842. assert(index < Weights.size() && "Not a current successor!");
  843. return Weights.begin() + index;
  844. }
  845. /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
  846. /// as of just before "MI".
  847. ///
  848. /// Search is localised to a neighborhood of
  849. /// Neighborhood instructions before (searching for defs or kills) and N
  850. /// instructions after (searching just for defs) MI.
  851. MachineBasicBlock::LivenessQueryResult
  852. MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
  853. unsigned Reg, MachineInstr *MI,
  854. unsigned Neighborhood) {
  855. unsigned N = Neighborhood;
  856. MachineBasicBlock *MBB = MI->getParent();
  857. // Start by searching backwards from MI, looking for kills, reads or defs.
  858. MachineBasicBlock::iterator I(MI);
  859. // If this is the first insn in the block, don't search backwards.
  860. if (I != MBB->begin()) {
  861. do {
  862. --I;
  863. MachineOperandIteratorBase::PhysRegInfo Analysis =
  864. MIOperands(I).analyzePhysReg(Reg, TRI);
  865. if (Analysis.Kills)
  866. // Register killed, so isn't live.
  867. return LQR_Dead;
  868. else if (Analysis.DefinesOverlap || Analysis.ReadsOverlap)
  869. // Defined or read without a previous kill - live.
  870. return (Analysis.Defines || Analysis.Reads) ?
  871. LQR_Live : LQR_OverlappingLive;
  872. } while (I != MBB->begin() && --N > 0);
  873. }
  874. // Did we get to the start of the block?
  875. if (I == MBB->begin()) {
  876. // If so, the register's state is definitely defined by the live-in state.
  877. for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
  878. RAI.isValid(); ++RAI) {
  879. if (MBB->isLiveIn(*RAI))
  880. return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
  881. }
  882. return LQR_Dead;
  883. }
  884. N = Neighborhood;
  885. // Try searching forwards from MI, looking for reads or defs.
  886. I = MachineBasicBlock::iterator(MI);
  887. // If this is the last insn in the block, don't search forwards.
  888. if (I != MBB->end()) {
  889. for (++I; I != MBB->end() && N > 0; ++I, --N) {
  890. MachineOperandIteratorBase::PhysRegInfo Analysis =
  891. MIOperands(I).analyzePhysReg(Reg, TRI);
  892. if (Analysis.ReadsOverlap)
  893. // Used, therefore must have been live.
  894. return (Analysis.Reads) ?
  895. LQR_Live : LQR_OverlappingLive;
  896. else if (Analysis.DefinesOverlap)
  897. // Defined (but not read) therefore cannot have been live.
  898. return LQR_Dead;
  899. }
  900. }
  901. // At this point we have no idea of the liveness of the register.
  902. return LQR_Unknown;
  903. }
  904. void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
  905. bool t) {
  906. OS << "BB#" << MBB->getNumber();
  907. }