MachineBasicBlock.cpp 43 KB

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