MachineBasicBlock.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Collect the sequence of machine instructions for a basic block.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/MachineBasicBlock.h"
  14. #include "llvm/BasicBlock.h"
  15. #include "llvm/CodeGen/LiveVariables.h"
  16. #include "llvm/CodeGen/MachineDominators.h"
  17. #include "llvm/CodeGen/MachineFunction.h"
  18. #include "llvm/CodeGen/MachineLoopInfo.h"
  19. #include "llvm/CodeGen/SlotIndexes.h"
  20. #include "llvm/MC/MCAsmInfo.h"
  21. #include "llvm/MC/MCContext.h"
  22. #include "llvm/Target/TargetRegisterInfo.h"
  23. #include "llvm/Target/TargetData.h"
  24. #include "llvm/Target/TargetInstrInfo.h"
  25. #include "llvm/Target/TargetMachine.h"
  26. #include "llvm/Assembly/Writer.h"
  27. #include "llvm/ADT/SmallString.h"
  28. #include "llvm/ADT/SmallPtrSet.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/LeakDetector.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <algorithm>
  33. using namespace llvm;
  34. MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
  35. : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
  36. AddressTaken(false) {
  37. Insts.Parent = this;
  38. }
  39. MachineBasicBlock::~MachineBasicBlock() {
  40. LeakDetector::removeGarbageObject(this);
  41. }
  42. /// getSymbol - Return the MCSymbol for this basic block.
  43. ///
  44. MCSymbol *MachineBasicBlock::getSymbol() const {
  45. const MachineFunction *MF = getParent();
  46. MCContext &Ctx = MF->getContext();
  47. const char *Prefix = Ctx.getAsmInfo().getPrivateGlobalPrefix();
  48. return Ctx.GetOrCreateSymbol(Twine(Prefix) + "BB" +
  49. Twine(MF->getFunctionNumber()) + "_" +
  50. Twine(getNumber()));
  51. }
  52. raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
  53. MBB.print(OS);
  54. return OS;
  55. }
  56. /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
  57. /// parent pointer of the MBB, the MBB numbering, and any instructions in the
  58. /// MBB to be on the right operand list for registers.
  59. ///
  60. /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
  61. /// gets the next available unique MBB number. If it is removed from a
  62. /// MachineFunction, it goes back to being #-1.
  63. void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
  64. MachineFunction &MF = *N->getParent();
  65. N->Number = MF.addToMBBNumbering(N);
  66. // Make sure the instructions have their operands in the reginfo lists.
  67. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  68. for (MachineBasicBlock::iterator I = N->begin(), E = N->end(); I != E; ++I)
  69. I->AddRegOperandsToUseLists(RegInfo);
  70. LeakDetector::removeGarbageObject(N);
  71. }
  72. void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
  73. N->getParent()->removeFromMBBNumbering(N->Number);
  74. N->Number = -1;
  75. LeakDetector::addGarbageObject(N);
  76. }
  77. /// addNodeToList (MI) - When we add an instruction to a basic block
  78. /// list, we update its parent pointer and add its operands from reg use/def
  79. /// lists if appropriate.
  80. void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
  81. assert(N->getParent() == 0 && "machine instruction already in a basic block");
  82. N->setParent(Parent);
  83. // Add the instruction's register operands to their corresponding
  84. // use/def lists.
  85. MachineFunction *MF = Parent->getParent();
  86. N->AddRegOperandsToUseLists(MF->getRegInfo());
  87. LeakDetector::removeGarbageObject(N);
  88. }
  89. /// removeNodeFromList (MI) - When we remove an instruction from a basic block
  90. /// list, we update its parent pointer and remove its operands from reg use/def
  91. /// lists if appropriate.
  92. void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
  93. assert(N->getParent() != 0 && "machine instruction not in a basic block");
  94. // Remove from the use/def lists.
  95. N->RemoveRegOperandsFromUseLists();
  96. N->setParent(0);
  97. LeakDetector::addGarbageObject(N);
  98. }
  99. /// transferNodesFromList (MI) - When moving a range of instructions from one
  100. /// MBB list to another, we need to update the parent pointers and the use/def
  101. /// lists.
  102. void ilist_traits<MachineInstr>::
  103. transferNodesFromList(ilist_traits<MachineInstr> &fromList,
  104. MachineBasicBlock::iterator first,
  105. MachineBasicBlock::iterator last) {
  106. assert(Parent->getParent() == fromList.Parent->getParent() &&
  107. "MachineInstr parent mismatch!");
  108. // Splice within the same MBB -> no change.
  109. if (Parent == fromList.Parent) return;
  110. // If splicing between two blocks within the same function, just update the
  111. // parent pointers.
  112. for (; first != last; ++first)
  113. first->setParent(Parent);
  114. }
  115. void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
  116. assert(!MI->getParent() && "MI is still in a block!");
  117. Parent->getParent()->DeleteMachineInstr(MI);
  118. }
  119. MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
  120. iterator I = begin();
  121. while (I != end() && I->isPHI())
  122. ++I;
  123. return I;
  124. }
  125. MachineBasicBlock::iterator
  126. MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
  127. while (I != end() && (I->isPHI() || I->isLabel() || I->isDebugValue()))
  128. ++I;
  129. return I;
  130. }
  131. MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
  132. iterator I = end();
  133. while (I != begin() && ((--I)->getDesc().isTerminator() || I->isDebugValue()))
  134. ; /*noop */
  135. while (I != end() && !I->getDesc().isTerminator())
  136. ++I;
  137. return I;
  138. }
  139. MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
  140. iterator B = begin(), I = end();
  141. while (I != B) {
  142. --I;
  143. if (I->isDebugValue())
  144. continue;
  145. return I;
  146. }
  147. // The block is all debug values.
  148. return end();
  149. }
  150. const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
  151. // A block with a landing pad successor only has one other successor.
  152. if (succ_size() > 2)
  153. return 0;
  154. for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
  155. if ((*I)->isLandingPad())
  156. return *I;
  157. return 0;
  158. }
  159. void MachineBasicBlock::dump() const {
  160. print(dbgs());
  161. }
  162. StringRef MachineBasicBlock::getName() const {
  163. if (const BasicBlock *LBB = getBasicBlock())
  164. return LBB->getName();
  165. else
  166. return "(null)";
  167. }
  168. void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
  169. const MachineFunction *MF = getParent();
  170. if (!MF) {
  171. OS << "Can't print out MachineBasicBlock because parent MachineFunction"
  172. << " is null\n";
  173. return;
  174. }
  175. if (Alignment) { OS << "Alignment " << Alignment << "\n"; }
  176. if (Indexes)
  177. OS << Indexes->getMBBStartIdx(this) << '\t';
  178. OS << "BB#" << getNumber() << ": ";
  179. const char *Comma = "";
  180. if (const BasicBlock *LBB = getBasicBlock()) {
  181. OS << Comma << "derived from LLVM BB ";
  182. WriteAsOperand(OS, LBB, /*PrintType=*/false);
  183. Comma = ", ";
  184. }
  185. if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
  186. if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
  187. OS << '\n';
  188. const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
  189. if (!livein_empty()) {
  190. if (Indexes) OS << '\t';
  191. OS << " Live Ins:";
  192. for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
  193. OS << ' ' << PrintReg(*I, TRI);
  194. OS << '\n';
  195. }
  196. // Print the preds of this block according to the CFG.
  197. if (!pred_empty()) {
  198. if (Indexes) OS << '\t';
  199. OS << " Predecessors according to CFG:";
  200. for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
  201. OS << " BB#" << (*PI)->getNumber();
  202. OS << '\n';
  203. }
  204. for (const_iterator I = begin(); I != end(); ++I) {
  205. if (Indexes) {
  206. if (Indexes->hasIndex(I))
  207. OS << Indexes->getInstructionIndex(I);
  208. OS << '\t';
  209. }
  210. OS << '\t';
  211. I->print(OS, &getParent()->getTarget());
  212. }
  213. // Print the successors of this block according to the CFG.
  214. if (!succ_empty()) {
  215. if (Indexes) OS << '\t';
  216. OS << " Successors according to CFG:";
  217. for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI)
  218. OS << " BB#" << (*SI)->getNumber();
  219. OS << '\n';
  220. }
  221. }
  222. void MachineBasicBlock::removeLiveIn(unsigned Reg) {
  223. std::vector<unsigned>::iterator I =
  224. std::find(LiveIns.begin(), LiveIns.end(), Reg);
  225. assert(I != LiveIns.end() && "Not a live in!");
  226. LiveIns.erase(I);
  227. }
  228. bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
  229. livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
  230. return I != livein_end();
  231. }
  232. void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
  233. getParent()->splice(NewAfter, this);
  234. }
  235. void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
  236. MachineFunction::iterator BBI = NewBefore;
  237. getParent()->splice(++BBI, this);
  238. }
  239. void MachineBasicBlock::updateTerminator() {
  240. const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
  241. // A block with no successors has no concerns with fall-through edges.
  242. if (this->succ_empty()) return;
  243. MachineBasicBlock *TBB = 0, *FBB = 0;
  244. SmallVector<MachineOperand, 4> Cond;
  245. DebugLoc dl; // FIXME: this is nowhere
  246. bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
  247. (void) B;
  248. assert(!B && "UpdateTerminators requires analyzable predecessors!");
  249. if (Cond.empty()) {
  250. if (TBB) {
  251. // The block has an unconditional branch. If its successor is now
  252. // its layout successor, delete the branch.
  253. if (isLayoutSuccessor(TBB))
  254. TII->RemoveBranch(*this);
  255. } else {
  256. // The block has an unconditional fallthrough. If its successor is not
  257. // its layout successor, insert a branch.
  258. TBB = *succ_begin();
  259. if (!isLayoutSuccessor(TBB))
  260. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  261. }
  262. } else {
  263. if (FBB) {
  264. // The block has a non-fallthrough conditional branch. If one of its
  265. // successors is its layout successor, rewrite it to a fallthrough
  266. // conditional branch.
  267. if (isLayoutSuccessor(TBB)) {
  268. if (TII->ReverseBranchCondition(Cond))
  269. return;
  270. TII->RemoveBranch(*this);
  271. TII->InsertBranch(*this, FBB, 0, Cond, dl);
  272. } else if (isLayoutSuccessor(FBB)) {
  273. TII->RemoveBranch(*this);
  274. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  275. }
  276. } else {
  277. // The block has a fallthrough conditional branch.
  278. MachineBasicBlock *MBBA = *succ_begin();
  279. MachineBasicBlock *MBBB = *llvm::next(succ_begin());
  280. if (MBBA == TBB) std::swap(MBBB, MBBA);
  281. if (isLayoutSuccessor(TBB)) {
  282. if (TII->ReverseBranchCondition(Cond)) {
  283. // We can't reverse the condition, add an unconditional branch.
  284. Cond.clear();
  285. TII->InsertBranch(*this, MBBA, 0, Cond, dl);
  286. return;
  287. }
  288. TII->RemoveBranch(*this);
  289. TII->InsertBranch(*this, MBBA, 0, Cond, dl);
  290. } else if (!isLayoutSuccessor(MBBA)) {
  291. TII->RemoveBranch(*this);
  292. TII->InsertBranch(*this, TBB, MBBA, Cond, dl);
  293. }
  294. }
  295. }
  296. }
  297. void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
  298. // If we see non-zero value for the first time it means we actually use Weight
  299. // list, so we fill all Weights with 0's.
  300. if (weight != 0 && Weights.empty())
  301. Weights.resize(Successors.size());
  302. if (weight != 0 || !Weights.empty())
  303. Weights.push_back(weight);
  304. Successors.push_back(succ);
  305. succ->addPredecessor(this);
  306. }
  307. void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
  308. succ->removePredecessor(this);
  309. succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
  310. assert(I != Successors.end() && "Not a current successor!");
  311. // If Weight list is empty it means we don't use it (disabled optimization).
  312. if (!Weights.empty()) {
  313. weight_iterator WI = getWeightIterator(I);
  314. Weights.erase(WI);
  315. }
  316. Successors.erase(I);
  317. }
  318. MachineBasicBlock::succ_iterator
  319. MachineBasicBlock::removeSuccessor(succ_iterator I) {
  320. assert(I != Successors.end() && "Not a current successor!");
  321. // If Weight list is empty it means we don't use it (disabled optimization).
  322. if (!Weights.empty()) {
  323. weight_iterator WI = getWeightIterator(I);
  324. Weights.erase(WI);
  325. }
  326. (*I)->removePredecessor(this);
  327. return Successors.erase(I);
  328. }
  329. void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
  330. MachineBasicBlock *New) {
  331. uint32_t weight = 0;
  332. succ_iterator SI = std::find(Successors.begin(), Successors.end(), Old);
  333. // If Weight list is empty it means we don't use it (disabled optimization).
  334. if (!Weights.empty()) {
  335. weight_iterator WI = getWeightIterator(SI);
  336. weight = *WI;
  337. }
  338. // Update the successor information.
  339. removeSuccessor(SI);
  340. addSuccessor(New, weight);
  341. }
  342. void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
  343. Predecessors.push_back(pred);
  344. }
  345. void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
  346. pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
  347. assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
  348. Predecessors.erase(I);
  349. }
  350. void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
  351. if (this == fromMBB)
  352. return;
  353. while (!fromMBB->succ_empty()) {
  354. MachineBasicBlock *Succ = *fromMBB->succ_begin();
  355. uint32_t weight = 0;
  356. // If Weight list is empty it means we don't use it (disabled optimization).
  357. if (!fromMBB->Weights.empty())
  358. weight = *fromMBB->Weights.begin();
  359. addSuccessor(Succ, weight);
  360. fromMBB->removeSuccessor(Succ);
  361. }
  362. }
  363. void
  364. MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
  365. if (this == fromMBB)
  366. return;
  367. while (!fromMBB->succ_empty()) {
  368. MachineBasicBlock *Succ = *fromMBB->succ_begin();
  369. addSuccessor(Succ);
  370. fromMBB->removeSuccessor(Succ);
  371. // Fix up any PHI nodes in the successor.
  372. for (MachineBasicBlock::iterator MI = Succ->begin(), ME = Succ->end();
  373. MI != ME && MI->isPHI(); ++MI)
  374. for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
  375. MachineOperand &MO = MI->getOperand(i);
  376. if (MO.getMBB() == fromMBB)
  377. MO.setMBB(this);
  378. }
  379. }
  380. }
  381. bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
  382. const_succ_iterator I = std::find(Successors.begin(), Successors.end(), MBB);
  383. return I != Successors.end();
  384. }
  385. bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
  386. MachineFunction::const_iterator I(this);
  387. return llvm::next(I) == MachineFunction::const_iterator(MBB);
  388. }
  389. bool MachineBasicBlock::canFallThrough() {
  390. MachineFunction::iterator Fallthrough = this;
  391. ++Fallthrough;
  392. // If FallthroughBlock is off the end of the function, it can't fall through.
  393. if (Fallthrough == getParent()->end())
  394. return false;
  395. // If FallthroughBlock isn't a successor, no fallthrough is possible.
  396. if (!isSuccessor(Fallthrough))
  397. return false;
  398. // Analyze the branches, if any, at the end of the block.
  399. MachineBasicBlock *TBB = 0, *FBB = 0;
  400. SmallVector<MachineOperand, 4> Cond;
  401. const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
  402. if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
  403. // If we couldn't analyze the branch, examine the last instruction.
  404. // If the block doesn't end in a known control barrier, assume fallthrough
  405. // is possible. The isPredicable check is needed because this code can be
  406. // called during IfConversion, where an instruction which is normally a
  407. // Barrier is predicated and thus no longer an actual control barrier. This
  408. // is over-conservative though, because if an instruction isn't actually
  409. // predicated we could still treat it like a barrier.
  410. return empty() || !back().getDesc().isBarrier() ||
  411. back().getDesc().isPredicable();
  412. }
  413. // If there is no branch, control always falls through.
  414. if (TBB == 0) return true;
  415. // If there is some explicit branch to the fallthrough block, it can obviously
  416. // reach, even though the branch should get folded to fall through implicitly.
  417. if (MachineFunction::iterator(TBB) == Fallthrough ||
  418. MachineFunction::iterator(FBB) == Fallthrough)
  419. return true;
  420. // If it's an unconditional branch to some block not the fall through, it
  421. // doesn't fall through.
  422. if (Cond.empty()) return false;
  423. // Otherwise, if it is conditional and has no explicit false block, it falls
  424. // through.
  425. return FBB == 0;
  426. }
  427. MachineBasicBlock *
  428. MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
  429. MachineFunction *MF = getParent();
  430. DebugLoc dl; // FIXME: this is nowhere
  431. // We may need to update this's terminator, but we can't do that if
  432. // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
  433. const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
  434. MachineBasicBlock *TBB = 0, *FBB = 0;
  435. SmallVector<MachineOperand, 4> Cond;
  436. if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
  437. return NULL;
  438. // Avoid bugpoint weirdness: A block may end with a conditional branch but
  439. // jumps to the same MBB is either case. We have duplicate CFG edges in that
  440. // case that we can't handle. Since this never happens in properly optimized
  441. // code, just skip those edges.
  442. if (TBB && TBB == FBB) {
  443. DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
  444. << getNumber() << '\n');
  445. return NULL;
  446. }
  447. MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
  448. MF->insert(llvm::next(MachineFunction::iterator(this)), NMBB);
  449. DEBUG(dbgs() << "Splitting critical edge:"
  450. " BB#" << getNumber()
  451. << " -- BB#" << NMBB->getNumber()
  452. << " -- BB#" << Succ->getNumber() << '\n');
  453. // On some targets like Mips, branches may kill virtual registers. Make sure
  454. // that LiveVariables is properly updated after updateTerminator replaces the
  455. // terminators.
  456. LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
  457. // Collect a list of virtual registers killed by the terminators.
  458. SmallVector<unsigned, 4> KilledRegs;
  459. if (LV)
  460. for (iterator I = getFirstTerminator(), E = end(); I != E; ++I) {
  461. MachineInstr *MI = I;
  462. for (MachineInstr::mop_iterator OI = MI->operands_begin(),
  463. OE = MI->operands_end(); OI != OE; ++OI) {
  464. if (!OI->isReg() || !OI->isUse() || !OI->isKill() || OI->isUndef())
  465. continue;
  466. unsigned Reg = OI->getReg();
  467. if (TargetRegisterInfo::isVirtualRegister(Reg) &&
  468. LV->getVarInfo(Reg).removeKill(MI)) {
  469. KilledRegs.push_back(Reg);
  470. DEBUG(dbgs() << "Removing terminator kill: " << *MI);
  471. OI->setIsKill(false);
  472. }
  473. }
  474. }
  475. ReplaceUsesOfBlockWith(Succ, NMBB);
  476. updateTerminator();
  477. // Insert unconditional "jump Succ" instruction in NMBB if necessary.
  478. NMBB->addSuccessor(Succ);
  479. if (!NMBB->isLayoutSuccessor(Succ)) {
  480. Cond.clear();
  481. MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, Succ, NULL, Cond, dl);
  482. }
  483. // Fix PHI nodes in Succ so they refer to NMBB instead of this
  484. for (MachineBasicBlock::iterator i = Succ->begin(), e = Succ->end();
  485. i != e && i->isPHI(); ++i)
  486. for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
  487. if (i->getOperand(ni+1).getMBB() == this)
  488. i->getOperand(ni+1).setMBB(NMBB);
  489. // Update LiveVariables.
  490. if (LV) {
  491. // Restore kills of virtual registers that were killed by the terminators.
  492. while (!KilledRegs.empty()) {
  493. unsigned Reg = KilledRegs.pop_back_val();
  494. for (iterator I = end(), E = begin(); I != E;) {
  495. if (!(--I)->addRegisterKilled(Reg, NULL, /* addIfNotFound= */ false))
  496. continue;
  497. LV->getVarInfo(Reg).Kills.push_back(I);
  498. DEBUG(dbgs() << "Restored terminator kill: " << *I);
  499. break;
  500. }
  501. }
  502. // Update relevant live-through information.
  503. LV->addNewBlock(NMBB, this, Succ);
  504. }
  505. if (MachineDominatorTree *MDT =
  506. P->getAnalysisIfAvailable<MachineDominatorTree>()) {
  507. // Update dominator information.
  508. MachineDomTreeNode *SucccDTNode = MDT->getNode(Succ);
  509. bool IsNewIDom = true;
  510. for (const_pred_iterator PI = Succ->pred_begin(), E = Succ->pred_end();
  511. PI != E; ++PI) {
  512. MachineBasicBlock *PredBB = *PI;
  513. if (PredBB == NMBB)
  514. continue;
  515. if (!MDT->dominates(SucccDTNode, MDT->getNode(PredBB))) {
  516. IsNewIDom = false;
  517. break;
  518. }
  519. }
  520. // We know "this" dominates the newly created basic block.
  521. MachineDomTreeNode *NewDTNode = MDT->addNewBlock(NMBB, this);
  522. // If all the other predecessors of "Succ" are dominated by "Succ" itself
  523. // then the new block is the new immediate dominator of "Succ". Otherwise,
  524. // the new block doesn't dominate anything.
  525. if (IsNewIDom)
  526. MDT->changeImmediateDominator(SucccDTNode, NewDTNode);
  527. }
  528. if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
  529. if (MachineLoop *TIL = MLI->getLoopFor(this)) {
  530. // If one or the other blocks were not in a loop, the new block is not
  531. // either, and thus LI doesn't need to be updated.
  532. if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
  533. if (TIL == DestLoop) {
  534. // Both in the same loop, the NMBB joins loop.
  535. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  536. } else if (TIL->contains(DestLoop)) {
  537. // Edge from an outer loop to an inner loop. Add to the outer loop.
  538. TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
  539. } else if (DestLoop->contains(TIL)) {
  540. // Edge from an inner loop to an outer loop. Add to the outer loop.
  541. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  542. } else {
  543. // Edge from two loops with no containment relation. Because these
  544. // are natural loops, we know that the destination block must be the
  545. // header of its loop (adding a branch into a loop elsewhere would
  546. // create an irreducible loop).
  547. assert(DestLoop->getHeader() == Succ &&
  548. "Should not create irreducible loops!");
  549. if (MachineLoop *P = DestLoop->getParentLoop())
  550. P->addBasicBlockToLoop(NMBB, MLI->getBase());
  551. }
  552. }
  553. }
  554. return NMBB;
  555. }
  556. /// removeFromParent - This method unlinks 'this' from the containing function,
  557. /// and returns it, but does not delete it.
  558. MachineBasicBlock *MachineBasicBlock::removeFromParent() {
  559. assert(getParent() && "Not embedded in a function!");
  560. getParent()->remove(this);
  561. return this;
  562. }
  563. /// eraseFromParent - This method unlinks 'this' from the containing function,
  564. /// and deletes it.
  565. void MachineBasicBlock::eraseFromParent() {
  566. assert(getParent() && "Not embedded in a function!");
  567. getParent()->erase(this);
  568. }
  569. /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
  570. /// 'Old', change the code and CFG so that it branches to 'New' instead.
  571. void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
  572. MachineBasicBlock *New) {
  573. assert(Old != New && "Cannot replace self with self!");
  574. MachineBasicBlock::iterator I = end();
  575. while (I != begin()) {
  576. --I;
  577. if (!I->getDesc().isTerminator()) break;
  578. // Scan the operands of this machine instruction, replacing any uses of Old
  579. // with New.
  580. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  581. if (I->getOperand(i).isMBB() &&
  582. I->getOperand(i).getMBB() == Old)
  583. I->getOperand(i).setMBB(New);
  584. }
  585. // Update the successor information.
  586. replaceSuccessor(Old, New);
  587. }
  588. /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
  589. /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
  590. /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be
  591. /// null.
  592. ///
  593. /// Besides DestA and DestB, retain other edges leading to LandingPads
  594. /// (currently there can be only one; we don't check or require that here).
  595. /// Note it is possible that DestA and/or DestB are LandingPads.
  596. bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
  597. MachineBasicBlock *DestB,
  598. bool isCond) {
  599. // The values of DestA and DestB frequently come from a call to the
  600. // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
  601. // values from there.
  602. //
  603. // 1. If both DestA and DestB are null, then the block ends with no branches
  604. // (it falls through to its successor).
  605. // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
  606. // with only an unconditional branch.
  607. // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
  608. // with a conditional branch that falls through to a successor (DestB).
  609. // 4. If DestA and DestB is set and isCond is true, then the block ends with a
  610. // conditional branch followed by an unconditional branch. DestA is the
  611. // 'true' destination and DestB is the 'false' destination.
  612. bool Changed = false;
  613. MachineFunction::iterator FallThru =
  614. llvm::next(MachineFunction::iterator(this));
  615. if (DestA == 0 && DestB == 0) {
  616. // Block falls through to successor.
  617. DestA = FallThru;
  618. DestB = FallThru;
  619. } else if (DestA != 0 && DestB == 0) {
  620. if (isCond)
  621. // Block ends in conditional jump that falls through to successor.
  622. DestB = FallThru;
  623. } else {
  624. assert(DestA && DestB && isCond &&
  625. "CFG in a bad state. Cannot correct CFG edges");
  626. }
  627. // Remove superfluous edges. I.e., those which aren't destinations of this
  628. // basic block, duplicate edges, or landing pads.
  629. SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
  630. MachineBasicBlock::succ_iterator SI = succ_begin();
  631. while (SI != succ_end()) {
  632. const MachineBasicBlock *MBB = *SI;
  633. if (!SeenMBBs.insert(MBB) ||
  634. (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
  635. // This is a superfluous edge, remove it.
  636. SI = removeSuccessor(SI);
  637. Changed = true;
  638. } else {
  639. ++SI;
  640. }
  641. }
  642. return Changed;
  643. }
  644. /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
  645. /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
  646. DebugLoc
  647. MachineBasicBlock::findDebugLoc(MachineBasicBlock::iterator &MBBI) {
  648. DebugLoc DL;
  649. MachineBasicBlock::iterator E = end();
  650. if (MBBI != E) {
  651. // Skip debug declarations, we don't want a DebugLoc from them.
  652. MachineBasicBlock::iterator MBBI2 = MBBI;
  653. while (MBBI2 != E && MBBI2->isDebugValue())
  654. MBBI2++;
  655. if (MBBI2 != E)
  656. DL = MBBI2->getDebugLoc();
  657. }
  658. return DL;
  659. }
  660. /// getSuccWeight - Return weight of the edge from this block to MBB.
  661. ///
  662. uint32_t MachineBasicBlock::getSuccWeight(MachineBasicBlock *succ) {
  663. if (Weights.empty())
  664. return 0;
  665. succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
  666. return *getWeightIterator(I);
  667. }
  668. /// getWeightIterator - Return wight iterator corresonding to the I successor
  669. /// iterator
  670. MachineBasicBlock::weight_iterator MachineBasicBlock::
  671. getWeightIterator(MachineBasicBlock::succ_iterator I) {
  672. assert(Weights.size() == Successors.size() && "Async weight list!");
  673. size_t index = std::distance(Successors.begin(), I);
  674. assert(index < Weights.size() && "Not a current successor!");
  675. return Weights.begin() + index;
  676. }
  677. void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
  678. bool t) {
  679. OS << "BB#" << MBB->getNumber();
  680. }