MachineBasicBlock.cpp 42 KB

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