MachineBasicBlock.cpp 41 KB

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