MachineBasicBlock.cpp 42 KB

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