MachineBasicBlock.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  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/CodeGen/LiveIntervals.h"
  16. #include "llvm/CodeGen/LiveVariables.h"
  17. #include "llvm/CodeGen/MachineDominators.h"
  18. #include "llvm/CodeGen/MachineFunction.h"
  19. #include "llvm/CodeGen/MachineInstrBuilder.h"
  20. #include "llvm/CodeGen/MachineLoopInfo.h"
  21. #include "llvm/CodeGen/MachineRegisterInfo.h"
  22. #include "llvm/CodeGen/SlotIndexes.h"
  23. #include "llvm/CodeGen/TargetInstrInfo.h"
  24. #include "llvm/CodeGen/TargetRegisterInfo.h"
  25. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  26. #include "llvm/IR/BasicBlock.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/DebugInfoMetadata.h"
  29. #include "llvm/IR/ModuleSlotTracker.h"
  30. #include "llvm/MC/MCAsmInfo.h"
  31. #include "llvm/MC/MCContext.h"
  32. #include "llvm/Support/DataTypes.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/Target/TargetMachine.h"
  36. #include <algorithm>
  37. using namespace llvm;
  38. #define DEBUG_TYPE "codegen"
  39. MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
  40. : BB(B), Number(-1), xParent(&MF) {
  41. Insts.Parent = this;
  42. if (B)
  43. IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight();
  44. }
  45. MachineBasicBlock::~MachineBasicBlock() {
  46. }
  47. /// Return the MCSymbol for this basic block.
  48. MCSymbol *MachineBasicBlock::getSymbol() const {
  49. if (!CachedMCSymbol) {
  50. const MachineFunction *MF = getParent();
  51. MCContext &Ctx = MF->getContext();
  52. auto Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
  53. assert(getNumber() >= 0 && "cannot get label for unreachable MBB");
  54. CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
  55. Twine(MF->getFunctionNumber()) +
  56. "_" + Twine(getNumber()));
  57. }
  58. return CachedMCSymbol;
  59. }
  60. raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
  61. MBB.print(OS);
  62. return OS;
  63. }
  64. Printable llvm::printMBBReference(const MachineBasicBlock &MBB) {
  65. return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
  66. }
  67. /// When an MBB is added to an MF, we need to update the parent pointer of the
  68. /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
  69. /// operand list for registers.
  70. ///
  71. /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
  72. /// gets the next available unique MBB number. If it is removed from a
  73. /// MachineFunction, it goes back to being #-1.
  74. void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
  75. MachineBasicBlock *N) {
  76. MachineFunction &MF = *N->getParent();
  77. N->Number = MF.addToMBBNumbering(N);
  78. // Make sure the instructions have their operands in the reginfo lists.
  79. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  80. for (MachineBasicBlock::instr_iterator
  81. I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
  82. I->AddRegOperandsToUseLists(RegInfo);
  83. }
  84. void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
  85. MachineBasicBlock *N) {
  86. N->getParent()->removeFromMBBNumbering(N->Number);
  87. N->Number = -1;
  88. }
  89. /// When we add an instruction to a basic block list, we update its parent
  90. /// pointer and add its operands from reg use/def lists if appropriate.
  91. void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
  92. assert(!N->getParent() && "machine instruction already in a basic block");
  93. N->setParent(Parent);
  94. // Add the instruction's register operands to their corresponding
  95. // use/def lists.
  96. MachineFunction *MF = Parent->getParent();
  97. N->AddRegOperandsToUseLists(MF->getRegInfo());
  98. }
  99. /// When we remove an instruction from a basic block list, we update its parent
  100. /// pointer and remove its operands from reg use/def lists if appropriate.
  101. void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
  102. assert(N->getParent() && "machine instruction not in a basic block");
  103. // Remove from the use/def lists.
  104. if (MachineFunction *MF = N->getMF())
  105. N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
  106. N->setParent(nullptr);
  107. }
  108. /// When moving a range of instructions from one MBB list to another, we need to
  109. /// update the parent pointers and the use/def lists.
  110. void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
  111. instr_iterator First,
  112. instr_iterator Last) {
  113. assert(Parent->getParent() == FromList.Parent->getParent() &&
  114. "MachineInstr parent mismatch!");
  115. assert(this != &FromList && "Called without a real transfer...");
  116. assert(Parent != FromList.Parent && "Two lists have the same parent?");
  117. // If splicing between two blocks within the same function, just update the
  118. // parent pointers.
  119. for (; First != Last; ++First)
  120. First->setParent(Parent);
  121. }
  122. void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
  123. assert(!MI->getParent() && "MI is still in a block!");
  124. Parent->getParent()->DeleteMachineInstr(MI);
  125. }
  126. MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
  127. instr_iterator I = instr_begin(), E = instr_end();
  128. while (I != E && I->isPHI())
  129. ++I;
  130. assert((I == E || !I->isInsideBundle()) &&
  131. "First non-phi MI cannot be inside a bundle!");
  132. return I;
  133. }
  134. MachineBasicBlock::iterator
  135. MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
  136. const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
  137. iterator E = end();
  138. while (I != E && (I->isPHI() || I->isPosition() ||
  139. TII->isBasicBlockPrologue(*I)))
  140. ++I;
  141. // FIXME: This needs to change if we wish to bundle labels
  142. // inside the bundle.
  143. assert((I == E || !I->isInsideBundle()) &&
  144. "First non-phi / non-label instruction is inside a bundle!");
  145. return I;
  146. }
  147. MachineBasicBlock::iterator
  148. MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I) {
  149. const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
  150. iterator E = end();
  151. while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue() ||
  152. TII->isBasicBlockPrologue(*I)))
  153. ++I;
  154. // FIXME: This needs to change if we wish to bundle labels / dbg_values
  155. // inside the bundle.
  156. assert((I == E || !I->isInsideBundle()) &&
  157. "First non-phi / non-label / non-debug "
  158. "instruction is inside a bundle!");
  159. return I;
  160. }
  161. MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
  162. iterator B = begin(), E = end(), I = E;
  163. while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
  164. ; /*noop */
  165. while (I != E && !I->isTerminator())
  166. ++I;
  167. return I;
  168. }
  169. MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
  170. instr_iterator B = instr_begin(), E = instr_end(), I = E;
  171. while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
  172. ; /*noop */
  173. while (I != E && !I->isTerminator())
  174. ++I;
  175. return I;
  176. }
  177. MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() {
  178. // Skip over begin-of-block dbg_value instructions.
  179. return skipDebugInstructionsForward(begin(), end());
  180. }
  181. MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
  182. // Skip over end-of-block dbg_value instructions.
  183. instr_iterator B = instr_begin(), I = instr_end();
  184. while (I != B) {
  185. --I;
  186. // Return instruction that starts a bundle.
  187. if (I->isDebugValue() || I->isInsideBundle())
  188. continue;
  189. return I;
  190. }
  191. // The block is all debug values.
  192. return end();
  193. }
  194. bool MachineBasicBlock::hasEHPadSuccessor() const {
  195. for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
  196. if ((*I)->isEHPad())
  197. return true;
  198. return false;
  199. }
  200. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  201. LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
  202. print(dbgs());
  203. }
  204. #endif
  205. bool MachineBasicBlock::isLegalToHoistInto() const {
  206. if (isReturnBlock() || hasEHPadSuccessor())
  207. return false;
  208. return true;
  209. }
  210. StringRef MachineBasicBlock::getName() const {
  211. if (const BasicBlock *LBB = getBasicBlock())
  212. return LBB->getName();
  213. else
  214. return StringRef("", 0);
  215. }
  216. /// Return a hopefully unique identifier for this block.
  217. std::string MachineBasicBlock::getFullName() const {
  218. std::string Name;
  219. if (getParent())
  220. Name = (getParent()->getName() + ":").str();
  221. if (getBasicBlock())
  222. Name += getBasicBlock()->getName();
  223. else
  224. Name += ("BB" + Twine(getNumber())).str();
  225. return Name;
  226. }
  227. void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes,
  228. bool IsStandalone) const {
  229. const MachineFunction *MF = getParent();
  230. if (!MF) {
  231. OS << "Can't print out MachineBasicBlock because parent MachineFunction"
  232. << " is null\n";
  233. return;
  234. }
  235. const Function &F = MF->getFunction();
  236. const Module *M = F.getParent();
  237. ModuleSlotTracker MST(M);
  238. MST.incorporateFunction(F);
  239. print(OS, MST, Indexes, IsStandalone);
  240. }
  241. void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
  242. const SlotIndexes *Indexes,
  243. bool IsStandalone) const {
  244. const MachineFunction *MF = getParent();
  245. if (!MF) {
  246. OS << "Can't print out MachineBasicBlock because parent MachineFunction"
  247. << " is null\n";
  248. return;
  249. }
  250. if (Indexes)
  251. OS << Indexes->getMBBStartIdx(this) << '\t';
  252. OS << "bb." << getNumber();
  253. bool HasAttributes = false;
  254. if (const auto *BB = getBasicBlock()) {
  255. if (BB->hasName()) {
  256. OS << "." << BB->getName();
  257. } else {
  258. HasAttributes = true;
  259. OS << " (";
  260. int Slot = MST.getLocalSlot(BB);
  261. if (Slot == -1)
  262. OS << "<ir-block badref>";
  263. else
  264. OS << (Twine("%ir-block.") + Twine(Slot)).str();
  265. }
  266. }
  267. if (hasAddressTaken()) {
  268. OS << (HasAttributes ? ", " : " (");
  269. OS << "address-taken";
  270. HasAttributes = true;
  271. }
  272. if (isEHPad()) {
  273. OS << (HasAttributes ? ", " : " (");
  274. OS << "landing-pad";
  275. HasAttributes = true;
  276. }
  277. if (getAlignment()) {
  278. OS << (HasAttributes ? ", " : " (");
  279. OS << "align " << getAlignment();
  280. HasAttributes = true;
  281. }
  282. if (HasAttributes)
  283. OS << ")";
  284. OS << ":\n";
  285. const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
  286. const MachineRegisterInfo &MRI = MF->getRegInfo();
  287. const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
  288. if (!livein_empty() && MRI.tracksLiveness()) {
  289. if (Indexes) OS << '\t';
  290. OS.indent(2) << "liveins: ";
  291. bool First = true;
  292. for (const auto &LI : liveins()) {
  293. if (!First)
  294. OS << ", ";
  295. First = false;
  296. OS << printReg(LI.PhysReg, TRI);
  297. if (!LI.LaneMask.all())
  298. OS << ":0x" << PrintLaneMask(LI.LaneMask);
  299. }
  300. OS << '\n';
  301. }
  302. if (!succ_empty()) {
  303. if (Indexes) OS << '\t';
  304. // Print the successors
  305. OS.indent(2) << "successors: ";
  306. for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
  307. if (I != succ_begin())
  308. OS << ", ";
  309. OS << printMBBReference(**I);
  310. if (!Probs.empty())
  311. OS << '('
  312. << format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
  313. << ')';
  314. }
  315. if (!Probs.empty()) {
  316. // Print human readable probabilities as comments.
  317. OS << "; ";
  318. for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
  319. const BranchProbability &BP = *getProbabilityIterator(I);
  320. if (I != succ_begin())
  321. OS << ", ";
  322. OS << printMBBReference(**I) << '('
  323. << format("%.2f%%",
  324. rint(((double)BP.getNumerator() / BP.getDenominator()) *
  325. 100.0 * 100.0) /
  326. 100.0)
  327. << ')';
  328. }
  329. OS << '\n';
  330. }
  331. }
  332. // Print the preds of this block according to the CFG.
  333. if (!pred_empty()) {
  334. if (Indexes) OS << '\t';
  335. // Don't indent(2), align with previous line attributes.
  336. OS << "; predecessors: ";
  337. for (auto I = pred_begin(), E = pred_end(); I != E; ++I) {
  338. if (I != pred_begin())
  339. OS << ", ";
  340. OS << printMBBReference(**I);
  341. }
  342. OS << '\n';
  343. }
  344. bool IsInBundle = false;
  345. for (const MachineInstr &MI : instrs()) {
  346. if (Indexes) {
  347. if (Indexes->hasIndex(MI))
  348. OS << Indexes->getInstructionIndex(MI);
  349. OS << '\t';
  350. }
  351. if (IsInBundle && !MI.isInsideBundle()) {
  352. OS.indent(2) << "}\n";
  353. IsInBundle = false;
  354. }
  355. OS.indent(IsInBundle ? 4 : 2);
  356. MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
  357. &TII);
  358. if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
  359. OS << " {";
  360. IsInBundle = true;
  361. }
  362. OS << '\n';
  363. }
  364. if (IsInBundle)
  365. OS.indent(2) << "}\n";
  366. if (IrrLoopHeaderWeight) {
  367. if (Indexes) OS << '\t';
  368. OS << " Irreducible loop header weight: "
  369. << IrrLoopHeaderWeight.getValue();
  370. OS << '\n';
  371. }
  372. }
  373. void MachineBasicBlock::printAsOperand(raw_ostream &OS,
  374. bool /*PrintType*/) const {
  375. OS << "%bb." << getNumber();
  376. }
  377. void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
  378. LiveInVector::iterator I = find_if(
  379. LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
  380. if (I == LiveIns.end())
  381. return;
  382. I->LaneMask &= ~LaneMask;
  383. if (I->LaneMask.none())
  384. LiveIns.erase(I);
  385. }
  386. MachineBasicBlock::livein_iterator
  387. MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
  388. // Get non-const version of iterator.
  389. LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
  390. return LiveIns.erase(LI);
  391. }
  392. bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
  393. livein_iterator I = find_if(
  394. LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
  395. return I != livein_end() && (I->LaneMask & LaneMask).any();
  396. }
  397. void MachineBasicBlock::sortUniqueLiveIns() {
  398. std::sort(LiveIns.begin(), LiveIns.end(),
  399. [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
  400. return LI0.PhysReg < LI1.PhysReg;
  401. });
  402. // Liveins are sorted by physreg now we can merge their lanemasks.
  403. LiveInVector::const_iterator I = LiveIns.begin();
  404. LiveInVector::const_iterator J;
  405. LiveInVector::iterator Out = LiveIns.begin();
  406. for (; I != LiveIns.end(); ++Out, I = J) {
  407. unsigned PhysReg = I->PhysReg;
  408. LaneBitmask LaneMask = I->LaneMask;
  409. for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
  410. LaneMask |= J->LaneMask;
  411. Out->PhysReg = PhysReg;
  412. Out->LaneMask = LaneMask;
  413. }
  414. LiveIns.erase(Out, LiveIns.end());
  415. }
  416. unsigned
  417. MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) {
  418. assert(getParent() && "MBB must be inserted in function");
  419. assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
  420. assert(RC && "Register class is required");
  421. assert((isEHPad() || this == &getParent()->front()) &&
  422. "Only the entry block and landing pads can have physreg live ins");
  423. bool LiveIn = isLiveIn(PhysReg);
  424. iterator I = SkipPHIsAndLabels(begin()), E = end();
  425. MachineRegisterInfo &MRI = getParent()->getRegInfo();
  426. const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
  427. // Look for an existing copy.
  428. if (LiveIn)
  429. for (;I != E && I->isCopy(); ++I)
  430. if (I->getOperand(1).getReg() == PhysReg) {
  431. unsigned VirtReg = I->getOperand(0).getReg();
  432. if (!MRI.constrainRegClass(VirtReg, RC))
  433. llvm_unreachable("Incompatible live-in register class.");
  434. return VirtReg;
  435. }
  436. // No luck, create a virtual register.
  437. unsigned VirtReg = MRI.createVirtualRegister(RC);
  438. BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
  439. .addReg(PhysReg, RegState::Kill);
  440. if (!LiveIn)
  441. addLiveIn(PhysReg);
  442. return VirtReg;
  443. }
  444. void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
  445. getParent()->splice(NewAfter->getIterator(), getIterator());
  446. }
  447. void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
  448. getParent()->splice(++NewBefore->getIterator(), getIterator());
  449. }
  450. void MachineBasicBlock::updateTerminator() {
  451. const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
  452. // A block with no successors has no concerns with fall-through edges.
  453. if (this->succ_empty())
  454. return;
  455. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  456. SmallVector<MachineOperand, 4> Cond;
  457. DebugLoc DL = findBranchDebugLoc();
  458. bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
  459. (void) B;
  460. assert(!B && "UpdateTerminators requires analyzable predecessors!");
  461. if (Cond.empty()) {
  462. if (TBB) {
  463. // The block has an unconditional branch. If its successor is now its
  464. // layout successor, delete the branch.
  465. if (isLayoutSuccessor(TBB))
  466. TII->removeBranch(*this);
  467. } else {
  468. // The block has an unconditional fallthrough. If its successor is not its
  469. // layout successor, insert a branch. First we have to locate the only
  470. // non-landing-pad successor, as that is the fallthrough block.
  471. for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
  472. if ((*SI)->isEHPad())
  473. continue;
  474. assert(!TBB && "Found more than one non-landing-pad successor!");
  475. TBB = *SI;
  476. }
  477. // If there is no non-landing-pad successor, the block has no fall-through
  478. // edges to be concerned with.
  479. if (!TBB)
  480. return;
  481. // Finally update the unconditional successor to be reached via a branch
  482. // if it would not be reached by fallthrough.
  483. if (!isLayoutSuccessor(TBB))
  484. TII->insertBranch(*this, TBB, nullptr, Cond, DL);
  485. }
  486. return;
  487. }
  488. if (FBB) {
  489. // The block has a non-fallthrough conditional branch. If one of its
  490. // successors is its layout successor, rewrite it to a fallthrough
  491. // conditional branch.
  492. if (isLayoutSuccessor(TBB)) {
  493. if (TII->reverseBranchCondition(Cond))
  494. return;
  495. TII->removeBranch(*this);
  496. TII->insertBranch(*this, FBB, nullptr, Cond, DL);
  497. } else if (isLayoutSuccessor(FBB)) {
  498. TII->removeBranch(*this);
  499. TII->insertBranch(*this, TBB, nullptr, Cond, DL);
  500. }
  501. return;
  502. }
  503. // Walk through the successors and find the successor which is not a landing
  504. // pad and is not the conditional branch destination (in TBB) as the
  505. // fallthrough successor.
  506. MachineBasicBlock *FallthroughBB = nullptr;
  507. for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
  508. if ((*SI)->isEHPad() || *SI == TBB)
  509. continue;
  510. assert(!FallthroughBB && "Found more than one fallthrough successor.");
  511. FallthroughBB = *SI;
  512. }
  513. if (!FallthroughBB) {
  514. if (canFallThrough()) {
  515. // We fallthrough to the same basic block as the conditional jump targets.
  516. // Remove the conditional jump, leaving unconditional fallthrough.
  517. // FIXME: This does not seem like a reasonable pattern to support, but it
  518. // has been seen in the wild coming out of degenerate ARM test cases.
  519. TII->removeBranch(*this);
  520. // Finally update the unconditional successor to be reached via a branch if
  521. // it would not be reached by fallthrough.
  522. if (!isLayoutSuccessor(TBB))
  523. TII->insertBranch(*this, TBB, nullptr, Cond, DL);
  524. return;
  525. }
  526. // We enter here iff exactly one successor is TBB which cannot fallthrough
  527. // and the rest successors if any are EHPads. In this case, we need to
  528. // change the conditional branch into unconditional branch.
  529. TII->removeBranch(*this);
  530. Cond.clear();
  531. TII->insertBranch(*this, TBB, nullptr, Cond, DL);
  532. return;
  533. }
  534. // The block has a fallthrough conditional branch.
  535. if (isLayoutSuccessor(TBB)) {
  536. if (TII->reverseBranchCondition(Cond)) {
  537. // We can't reverse the condition, add an unconditional branch.
  538. Cond.clear();
  539. TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
  540. return;
  541. }
  542. TII->removeBranch(*this);
  543. TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
  544. } else if (!isLayoutSuccessor(FallthroughBB)) {
  545. TII->removeBranch(*this);
  546. TII->insertBranch(*this, TBB, FallthroughBB, Cond, DL);
  547. }
  548. }
  549. void MachineBasicBlock::validateSuccProbs() const {
  550. #ifndef NDEBUG
  551. int64_t Sum = 0;
  552. for (auto Prob : Probs)
  553. Sum += Prob.getNumerator();
  554. // Due to precision issue, we assume that the sum of probabilities is one if
  555. // the difference between the sum of their numerators and the denominator is
  556. // no greater than the number of successors.
  557. assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
  558. Probs.size() &&
  559. "The sum of successors's probabilities exceeds one.");
  560. #endif // NDEBUG
  561. }
  562. void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
  563. BranchProbability Prob) {
  564. // Probability list is either empty (if successor list isn't empty, this means
  565. // disabled optimization) or has the same size as successor list.
  566. if (!(Probs.empty() && !Successors.empty()))
  567. Probs.push_back(Prob);
  568. Successors.push_back(Succ);
  569. Succ->addPredecessor(this);
  570. }
  571. void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
  572. // We need to make sure probability list is either empty or has the same size
  573. // of successor list. When this function is called, we can safely delete all
  574. // probability in the list.
  575. Probs.clear();
  576. Successors.push_back(Succ);
  577. Succ->addPredecessor(this);
  578. }
  579. void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
  580. bool NormalizeSuccProbs) {
  581. succ_iterator I = find(Successors, Succ);
  582. removeSuccessor(I, NormalizeSuccProbs);
  583. }
  584. MachineBasicBlock::succ_iterator
  585. MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
  586. assert(I != Successors.end() && "Not a current successor!");
  587. // If probability list is empty it means we don't use it (disabled
  588. // optimization).
  589. if (!Probs.empty()) {
  590. probability_iterator WI = getProbabilityIterator(I);
  591. Probs.erase(WI);
  592. if (NormalizeSuccProbs)
  593. normalizeSuccProbs();
  594. }
  595. (*I)->removePredecessor(this);
  596. return Successors.erase(I);
  597. }
  598. void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
  599. MachineBasicBlock *New) {
  600. if (Old == New)
  601. return;
  602. succ_iterator E = succ_end();
  603. succ_iterator NewI = E;
  604. succ_iterator OldI = E;
  605. for (succ_iterator I = succ_begin(); I != E; ++I) {
  606. if (*I == Old) {
  607. OldI = I;
  608. if (NewI != E)
  609. break;
  610. }
  611. if (*I == New) {
  612. NewI = I;
  613. if (OldI != E)
  614. break;
  615. }
  616. }
  617. assert(OldI != E && "Old is not a successor of this block");
  618. // If New isn't already a successor, let it take Old's place.
  619. if (NewI == E) {
  620. Old->removePredecessor(this);
  621. New->addPredecessor(this);
  622. *OldI = New;
  623. return;
  624. }
  625. // New is already a successor.
  626. // Update its probability instead of adding a duplicate edge.
  627. if (!Probs.empty()) {
  628. auto ProbIter = getProbabilityIterator(NewI);
  629. if (!ProbIter->isUnknown())
  630. *ProbIter += *getProbabilityIterator(OldI);
  631. }
  632. removeSuccessor(OldI);
  633. }
  634. void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
  635. Predecessors.push_back(Pred);
  636. }
  637. void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
  638. pred_iterator I = find(Predecessors, Pred);
  639. assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
  640. Predecessors.erase(I);
  641. }
  642. void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
  643. if (this == FromMBB)
  644. return;
  645. while (!FromMBB->succ_empty()) {
  646. MachineBasicBlock *Succ = *FromMBB->succ_begin();
  647. // If probability list is empty it means we don't use it (disabled optimization).
  648. if (!FromMBB->Probs.empty()) {
  649. auto Prob = *FromMBB->Probs.begin();
  650. addSuccessor(Succ, Prob);
  651. } else
  652. addSuccessorWithoutProb(Succ);
  653. FromMBB->removeSuccessor(Succ);
  654. }
  655. }
  656. void
  657. MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
  658. if (this == FromMBB)
  659. return;
  660. while (!FromMBB->succ_empty()) {
  661. MachineBasicBlock *Succ = *FromMBB->succ_begin();
  662. if (!FromMBB->Probs.empty()) {
  663. auto Prob = *FromMBB->Probs.begin();
  664. addSuccessor(Succ, Prob);
  665. } else
  666. addSuccessorWithoutProb(Succ);
  667. FromMBB->removeSuccessor(Succ);
  668. // Fix up any PHI nodes in the successor.
  669. for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
  670. ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
  671. for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
  672. MachineOperand &MO = MI->getOperand(i);
  673. if (MO.getMBB() == FromMBB)
  674. MO.setMBB(this);
  675. }
  676. }
  677. normalizeSuccProbs();
  678. }
  679. bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
  680. return is_contained(predecessors(), MBB);
  681. }
  682. bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
  683. return is_contained(successors(), MBB);
  684. }
  685. bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
  686. MachineFunction::const_iterator I(this);
  687. return std::next(I) == MachineFunction::const_iterator(MBB);
  688. }
  689. MachineBasicBlock *MachineBasicBlock::getFallThrough() {
  690. MachineFunction::iterator Fallthrough = getIterator();
  691. ++Fallthrough;
  692. // If FallthroughBlock is off the end of the function, it can't fall through.
  693. if (Fallthrough == getParent()->end())
  694. return nullptr;
  695. // If FallthroughBlock isn't a successor, no fallthrough is possible.
  696. if (!isSuccessor(&*Fallthrough))
  697. return nullptr;
  698. // Analyze the branches, if any, at the end of the block.
  699. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  700. SmallVector<MachineOperand, 4> Cond;
  701. const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
  702. if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
  703. // If we couldn't analyze the branch, examine the last instruction.
  704. // If the block doesn't end in a known control barrier, assume fallthrough
  705. // is possible. The isPredicated check is needed because this code can be
  706. // called during IfConversion, where an instruction which is normally a
  707. // Barrier is predicated and thus no longer an actual control barrier.
  708. return (empty() || !back().isBarrier() || TII->isPredicated(back()))
  709. ? &*Fallthrough
  710. : nullptr;
  711. }
  712. // If there is no branch, control always falls through.
  713. if (!TBB) return &*Fallthrough;
  714. // If there is some explicit branch to the fallthrough block, it can obviously
  715. // reach, even though the branch should get folded to fall through implicitly.
  716. if (MachineFunction::iterator(TBB) == Fallthrough ||
  717. MachineFunction::iterator(FBB) == Fallthrough)
  718. return &*Fallthrough;
  719. // If it's an unconditional branch to some block not the fall through, it
  720. // doesn't fall through.
  721. if (Cond.empty()) return nullptr;
  722. // Otherwise, if it is conditional and has no explicit false block, it falls
  723. // through.
  724. return (FBB == nullptr) ? &*Fallthrough : nullptr;
  725. }
  726. bool MachineBasicBlock::canFallThrough() {
  727. return getFallThrough() != nullptr;
  728. }
  729. MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ,
  730. Pass &P) {
  731. if (!canSplitCriticalEdge(Succ))
  732. return nullptr;
  733. MachineFunction *MF = getParent();
  734. DebugLoc DL; // FIXME: this is nowhere
  735. MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
  736. MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
  737. DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
  738. << " -- " << printMBBReference(*NMBB) << " -- "
  739. << printMBBReference(*Succ) << '\n');
  740. LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
  741. SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
  742. if (LIS)
  743. LIS->insertMBBInMaps(NMBB);
  744. else if (Indexes)
  745. Indexes->insertMBBInMaps(NMBB);
  746. // On some targets like Mips, branches may kill virtual registers. Make sure
  747. // that LiveVariables is properly updated after updateTerminator replaces the
  748. // terminators.
  749. LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
  750. // Collect a list of virtual registers killed by the terminators.
  751. SmallVector<unsigned, 4> KilledRegs;
  752. if (LV)
  753. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  754. I != E; ++I) {
  755. MachineInstr *MI = &*I;
  756. for (MachineInstr::mop_iterator OI = MI->operands_begin(),
  757. OE = MI->operands_end(); OI != OE; ++OI) {
  758. if (!OI->isReg() || OI->getReg() == 0 ||
  759. !OI->isUse() || !OI->isKill() || OI->isUndef())
  760. continue;
  761. unsigned Reg = OI->getReg();
  762. if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
  763. LV->getVarInfo(Reg).removeKill(*MI)) {
  764. KilledRegs.push_back(Reg);
  765. DEBUG(dbgs() << "Removing terminator kill: " << *MI);
  766. OI->setIsKill(false);
  767. }
  768. }
  769. }
  770. SmallVector<unsigned, 4> UsedRegs;
  771. if (LIS) {
  772. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  773. I != E; ++I) {
  774. MachineInstr *MI = &*I;
  775. for (MachineInstr::mop_iterator OI = MI->operands_begin(),
  776. OE = MI->operands_end(); OI != OE; ++OI) {
  777. if (!OI->isReg() || OI->getReg() == 0)
  778. continue;
  779. unsigned Reg = OI->getReg();
  780. if (!is_contained(UsedRegs, Reg))
  781. UsedRegs.push_back(Reg);
  782. }
  783. }
  784. }
  785. ReplaceUsesOfBlockWith(Succ, NMBB);
  786. // If updateTerminator() removes instructions, we need to remove them from
  787. // SlotIndexes.
  788. SmallVector<MachineInstr*, 4> Terminators;
  789. if (Indexes) {
  790. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  791. I != E; ++I)
  792. Terminators.push_back(&*I);
  793. }
  794. updateTerminator();
  795. if (Indexes) {
  796. SmallVector<MachineInstr*, 4> NewTerminators;
  797. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  798. I != E; ++I)
  799. NewTerminators.push_back(&*I);
  800. for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
  801. E = Terminators.end(); I != E; ++I) {
  802. if (!is_contained(NewTerminators, *I))
  803. Indexes->removeMachineInstrFromMaps(**I);
  804. }
  805. }
  806. // Insert unconditional "jump Succ" instruction in NMBB if necessary.
  807. NMBB->addSuccessor(Succ);
  808. if (!NMBB->isLayoutSuccessor(Succ)) {
  809. SmallVector<MachineOperand, 4> Cond;
  810. const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
  811. TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
  812. if (Indexes) {
  813. for (MachineInstr &MI : NMBB->instrs()) {
  814. // Some instructions may have been moved to NMBB by updateTerminator(),
  815. // so we first remove any instruction that already has an index.
  816. if (Indexes->hasIndex(MI))
  817. Indexes->removeMachineInstrFromMaps(MI);
  818. Indexes->insertMachineInstrInMaps(MI);
  819. }
  820. }
  821. }
  822. // Fix PHI nodes in Succ so they refer to NMBB instead of this
  823. for (MachineBasicBlock::instr_iterator
  824. i = Succ->instr_begin(),e = Succ->instr_end();
  825. i != e && i->isPHI(); ++i)
  826. for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
  827. if (i->getOperand(ni+1).getMBB() == this)
  828. i->getOperand(ni+1).setMBB(NMBB);
  829. // Inherit live-ins from the successor
  830. for (const auto &LI : Succ->liveins())
  831. NMBB->addLiveIn(LI);
  832. // Update LiveVariables.
  833. const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
  834. if (LV) {
  835. // Restore kills of virtual registers that were killed by the terminators.
  836. while (!KilledRegs.empty()) {
  837. unsigned Reg = KilledRegs.pop_back_val();
  838. for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
  839. if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
  840. continue;
  841. if (TargetRegisterInfo::isVirtualRegister(Reg))
  842. LV->getVarInfo(Reg).Kills.push_back(&*I);
  843. DEBUG(dbgs() << "Restored terminator kill: " << *I);
  844. break;
  845. }
  846. }
  847. // Update relevant live-through information.
  848. LV->addNewBlock(NMBB, this, Succ);
  849. }
  850. if (LIS) {
  851. // After splitting the edge and updating SlotIndexes, live intervals may be
  852. // in one of two situations, depending on whether this block was the last in
  853. // the function. If the original block was the last in the function, all
  854. // live intervals will end prior to the beginning of the new split block. If
  855. // the original block was not at the end of the function, all live intervals
  856. // will extend to the end of the new split block.
  857. bool isLastMBB =
  858. std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
  859. SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
  860. SlotIndex PrevIndex = StartIndex.getPrevSlot();
  861. SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
  862. // Find the registers used from NMBB in PHIs in Succ.
  863. SmallSet<unsigned, 8> PHISrcRegs;
  864. for (MachineBasicBlock::instr_iterator
  865. I = Succ->instr_begin(), E = Succ->instr_end();
  866. I != E && I->isPHI(); ++I) {
  867. for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
  868. if (I->getOperand(ni+1).getMBB() == NMBB) {
  869. MachineOperand &MO = I->getOperand(ni);
  870. unsigned Reg = MO.getReg();
  871. PHISrcRegs.insert(Reg);
  872. if (MO.isUndef())
  873. continue;
  874. LiveInterval &LI = LIS->getInterval(Reg);
  875. VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
  876. assert(VNI &&
  877. "PHI sources should be live out of their predecessors.");
  878. LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
  879. }
  880. }
  881. }
  882. MachineRegisterInfo *MRI = &getParent()->getRegInfo();
  883. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  884. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  885. if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
  886. continue;
  887. LiveInterval &LI = LIS->getInterval(Reg);
  888. if (!LI.liveAt(PrevIndex))
  889. continue;
  890. bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
  891. if (isLiveOut && isLastMBB) {
  892. VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
  893. assert(VNI && "LiveInterval should have VNInfo where it is live.");
  894. LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
  895. } else if (!isLiveOut && !isLastMBB) {
  896. LI.removeSegment(StartIndex, EndIndex);
  897. }
  898. }
  899. // Update all intervals for registers whose uses may have been modified by
  900. // updateTerminator().
  901. LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
  902. }
  903. if (MachineDominatorTree *MDT =
  904. P.getAnalysisIfAvailable<MachineDominatorTree>())
  905. MDT->recordSplitCriticalEdge(this, Succ, NMBB);
  906. if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
  907. if (MachineLoop *TIL = MLI->getLoopFor(this)) {
  908. // If one or the other blocks were not in a loop, the new block is not
  909. // either, and thus LI doesn't need to be updated.
  910. if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
  911. if (TIL == DestLoop) {
  912. // Both in the same loop, the NMBB joins loop.
  913. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  914. } else if (TIL->contains(DestLoop)) {
  915. // Edge from an outer loop to an inner loop. Add to the outer loop.
  916. TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
  917. } else if (DestLoop->contains(TIL)) {
  918. // Edge from an inner loop to an outer loop. Add to the outer loop.
  919. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  920. } else {
  921. // Edge from two loops with no containment relation. Because these
  922. // are natural loops, we know that the destination block must be the
  923. // header of its loop (adding a branch into a loop elsewhere would
  924. // create an irreducible loop).
  925. assert(DestLoop->getHeader() == Succ &&
  926. "Should not create irreducible loops!");
  927. if (MachineLoop *P = DestLoop->getParentLoop())
  928. P->addBasicBlockToLoop(NMBB, MLI->getBase());
  929. }
  930. }
  931. }
  932. return NMBB;
  933. }
  934. bool MachineBasicBlock::canSplitCriticalEdge(
  935. const MachineBasicBlock *Succ) const {
  936. // Splitting the critical edge to a landing pad block is non-trivial. Don't do
  937. // it in this generic function.
  938. if (Succ->isEHPad())
  939. return false;
  940. const MachineFunction *MF = getParent();
  941. // Performance might be harmed on HW that implements branching using exec mask
  942. // where both sides of the branches are always executed.
  943. if (MF->getTarget().requiresStructuredCFG())
  944. return false;
  945. // We may need to update this's terminator, but we can't do that if
  946. // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
  947. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  948. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  949. SmallVector<MachineOperand, 4> Cond;
  950. // AnalyzeBanch should modify this, since we did not allow modification.
  951. if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
  952. /*AllowModify*/ false))
  953. return false;
  954. // Avoid bugpoint weirdness: A block may end with a conditional branch but
  955. // jumps to the same MBB is either case. We have duplicate CFG edges in that
  956. // case that we can't handle. Since this never happens in properly optimized
  957. // code, just skip those edges.
  958. if (TBB && TBB == FBB) {
  959. DEBUG(dbgs() << "Won't split critical edge after degenerate "
  960. << printMBBReference(*this) << '\n');
  961. return false;
  962. }
  963. return true;
  964. }
  965. /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
  966. /// neighboring instructions so the bundle won't be broken by removing MI.
  967. static void unbundleSingleMI(MachineInstr *MI) {
  968. // Removing the first instruction in a bundle.
  969. if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
  970. MI->unbundleFromSucc();
  971. // Removing the last instruction in a bundle.
  972. if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
  973. MI->unbundleFromPred();
  974. // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
  975. // are already fine.
  976. }
  977. MachineBasicBlock::instr_iterator
  978. MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
  979. unbundleSingleMI(&*I);
  980. return Insts.erase(I);
  981. }
  982. MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
  983. unbundleSingleMI(MI);
  984. MI->clearFlag(MachineInstr::BundledPred);
  985. MI->clearFlag(MachineInstr::BundledSucc);
  986. return Insts.remove(MI);
  987. }
  988. MachineBasicBlock::instr_iterator
  989. MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
  990. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  991. "Cannot insert instruction with bundle flags");
  992. // Set the bundle flags when inserting inside a bundle.
  993. if (I != instr_end() && I->isBundledWithPred()) {
  994. MI->setFlag(MachineInstr::BundledPred);
  995. MI->setFlag(MachineInstr::BundledSucc);
  996. }
  997. return Insts.insert(I, MI);
  998. }
  999. /// This method unlinks 'this' from the containing function, and returns it, but
  1000. /// does not delete it.
  1001. MachineBasicBlock *MachineBasicBlock::removeFromParent() {
  1002. assert(getParent() && "Not embedded in a function!");
  1003. getParent()->remove(this);
  1004. return this;
  1005. }
  1006. /// This method unlinks 'this' from the containing function, and deletes it.
  1007. void MachineBasicBlock::eraseFromParent() {
  1008. assert(getParent() && "Not embedded in a function!");
  1009. getParent()->erase(this);
  1010. }
  1011. /// Given a machine basic block that branched to 'Old', change the code and CFG
  1012. /// so that it branches to 'New' instead.
  1013. void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
  1014. MachineBasicBlock *New) {
  1015. assert(Old != New && "Cannot replace self with self!");
  1016. MachineBasicBlock::instr_iterator I = instr_end();
  1017. while (I != instr_begin()) {
  1018. --I;
  1019. if (!I->isTerminator()) break;
  1020. // Scan the operands of this machine instruction, replacing any uses of Old
  1021. // with New.
  1022. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  1023. if (I->getOperand(i).isMBB() &&
  1024. I->getOperand(i).getMBB() == Old)
  1025. I->getOperand(i).setMBB(New);
  1026. }
  1027. // Update the successor information.
  1028. replaceSuccessor(Old, New);
  1029. }
  1030. /// Various pieces of code can cause excess edges in the CFG to be inserted. If
  1031. /// we have proven that MBB can only branch to DestA and DestB, remove any other
  1032. /// MBB successors from the CFG. DestA and DestB can be null.
  1033. ///
  1034. /// Besides DestA and DestB, retain other edges leading to LandingPads
  1035. /// (currently there can be only one; we don't check or require that here).
  1036. /// Note it is possible that DestA and/or DestB are LandingPads.
  1037. bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
  1038. MachineBasicBlock *DestB,
  1039. bool IsCond) {
  1040. // The values of DestA and DestB frequently come from a call to the
  1041. // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
  1042. // values from there.
  1043. //
  1044. // 1. If both DestA and DestB are null, then the block ends with no branches
  1045. // (it falls through to its successor).
  1046. // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends
  1047. // with only an unconditional branch.
  1048. // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends
  1049. // with a conditional branch that falls through to a successor (DestB).
  1050. // 4. If DestA and DestB is set and IsCond is true, then the block ends with a
  1051. // conditional branch followed by an unconditional branch. DestA is the
  1052. // 'true' destination and DestB is the 'false' destination.
  1053. bool Changed = false;
  1054. MachineBasicBlock *FallThru = getNextNode();
  1055. if (!DestA && !DestB) {
  1056. // Block falls through to successor.
  1057. DestA = FallThru;
  1058. DestB = FallThru;
  1059. } else if (DestA && !DestB) {
  1060. if (IsCond)
  1061. // Block ends in conditional jump that falls through to successor.
  1062. DestB = FallThru;
  1063. } else {
  1064. assert(DestA && DestB && IsCond &&
  1065. "CFG in a bad state. Cannot correct CFG edges");
  1066. }
  1067. // Remove superfluous edges. I.e., those which aren't destinations of this
  1068. // basic block, duplicate edges, or landing pads.
  1069. SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
  1070. MachineBasicBlock::succ_iterator SI = succ_begin();
  1071. while (SI != succ_end()) {
  1072. const MachineBasicBlock *MBB = *SI;
  1073. if (!SeenMBBs.insert(MBB).second ||
  1074. (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
  1075. // This is a superfluous edge, remove it.
  1076. SI = removeSuccessor(SI);
  1077. Changed = true;
  1078. } else {
  1079. ++SI;
  1080. }
  1081. }
  1082. if (Changed)
  1083. normalizeSuccProbs();
  1084. return Changed;
  1085. }
  1086. /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
  1087. /// instructions. Return UnknownLoc if there is none.
  1088. DebugLoc
  1089. MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
  1090. // Skip debug declarations, we don't want a DebugLoc from them.
  1091. MBBI = skipDebugInstructionsForward(MBBI, instr_end());
  1092. if (MBBI != instr_end())
  1093. return MBBI->getDebugLoc();
  1094. return {};
  1095. }
  1096. /// Find and return the merged DebugLoc of the branch instructions of the block.
  1097. /// Return UnknownLoc if there is none.
  1098. DebugLoc
  1099. MachineBasicBlock::findBranchDebugLoc() {
  1100. DebugLoc DL;
  1101. auto TI = getFirstTerminator();
  1102. while (TI != end() && !TI->isBranch())
  1103. ++TI;
  1104. if (TI != end()) {
  1105. DL = TI->getDebugLoc();
  1106. for (++TI ; TI != end() ; ++TI)
  1107. if (TI->isBranch())
  1108. DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
  1109. }
  1110. return DL;
  1111. }
  1112. /// Return probability of the edge from this block to MBB.
  1113. BranchProbability
  1114. MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
  1115. if (Probs.empty())
  1116. return BranchProbability(1, succ_size());
  1117. const auto &Prob = *getProbabilityIterator(Succ);
  1118. if (Prob.isUnknown()) {
  1119. // For unknown probabilities, collect the sum of all known ones, and evenly
  1120. // ditribute the complemental of the sum to each unknown probability.
  1121. unsigned KnownProbNum = 0;
  1122. auto Sum = BranchProbability::getZero();
  1123. for (auto &P : Probs) {
  1124. if (!P.isUnknown()) {
  1125. Sum += P;
  1126. KnownProbNum++;
  1127. }
  1128. }
  1129. return Sum.getCompl() / (Probs.size() - KnownProbNum);
  1130. } else
  1131. return Prob;
  1132. }
  1133. /// Set successor probability of a given iterator.
  1134. void MachineBasicBlock::setSuccProbability(succ_iterator I,
  1135. BranchProbability Prob) {
  1136. assert(!Prob.isUnknown());
  1137. if (Probs.empty())
  1138. return;
  1139. *getProbabilityIterator(I) = Prob;
  1140. }
  1141. /// Return probability iterator corresonding to the I successor iterator
  1142. MachineBasicBlock::const_probability_iterator
  1143. MachineBasicBlock::getProbabilityIterator(
  1144. MachineBasicBlock::const_succ_iterator I) const {
  1145. assert(Probs.size() == Successors.size() && "Async probability list!");
  1146. const size_t index = std::distance(Successors.begin(), I);
  1147. assert(index < Probs.size() && "Not a current successor!");
  1148. return Probs.begin() + index;
  1149. }
  1150. /// Return probability iterator corresonding to the I successor iterator.
  1151. MachineBasicBlock::probability_iterator
  1152. MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
  1153. assert(Probs.size() == Successors.size() && "Async probability list!");
  1154. const size_t index = std::distance(Successors.begin(), I);
  1155. assert(index < Probs.size() && "Not a current successor!");
  1156. return Probs.begin() + index;
  1157. }
  1158. /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
  1159. /// as of just before "MI".
  1160. ///
  1161. /// Search is localised to a neighborhood of
  1162. /// Neighborhood instructions before (searching for defs or kills) and N
  1163. /// instructions after (searching just for defs) MI.
  1164. MachineBasicBlock::LivenessQueryResult
  1165. MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
  1166. unsigned Reg, const_iterator Before,
  1167. unsigned Neighborhood) const {
  1168. unsigned N = Neighborhood;
  1169. // Start by searching backwards from Before, looking for kills, reads or defs.
  1170. const_iterator I(Before);
  1171. // If this is the first insn in the block, don't search backwards.
  1172. if (I != begin()) {
  1173. do {
  1174. --I;
  1175. MachineOperandIteratorBase::PhysRegInfo Info =
  1176. ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
  1177. // Defs happen after uses so they take precedence if both are present.
  1178. // Register is dead after a dead def of the full register.
  1179. if (Info.DeadDef)
  1180. return LQR_Dead;
  1181. // Register is (at least partially) live after a def.
  1182. if (Info.Defined) {
  1183. if (!Info.PartialDeadDef)
  1184. return LQR_Live;
  1185. // As soon as we saw a partial definition (dead or not),
  1186. // we cannot tell if the value is partial live without
  1187. // tracking the lanemasks. We are not going to do this,
  1188. // so fall back on the remaining of the analysis.
  1189. break;
  1190. }
  1191. // Register is dead after a full kill or clobber and no def.
  1192. if (Info.Killed || Info.Clobbered)
  1193. return LQR_Dead;
  1194. // Register must be live if we read it.
  1195. if (Info.Read)
  1196. return LQR_Live;
  1197. } while (I != begin() && --N > 0);
  1198. }
  1199. // Did we get to the start of the block?
  1200. if (I == begin()) {
  1201. // If so, the register's state is definitely defined by the live-in state.
  1202. for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true); RAI.isValid();
  1203. ++RAI)
  1204. if (isLiveIn(*RAI))
  1205. return LQR_Live;
  1206. return LQR_Dead;
  1207. }
  1208. N = Neighborhood;
  1209. // Try searching forwards from Before, looking for reads or defs.
  1210. I = const_iterator(Before);
  1211. // If this is the last insn in the block, don't search forwards.
  1212. if (I != end()) {
  1213. for (++I; I != end() && N > 0; ++I, --N) {
  1214. MachineOperandIteratorBase::PhysRegInfo Info =
  1215. ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
  1216. // Register is live when we read it here.
  1217. if (Info.Read)
  1218. return LQR_Live;
  1219. // Register is dead if we can fully overwrite or clobber it here.
  1220. if (Info.FullyDefined || Info.Clobbered)
  1221. return LQR_Dead;
  1222. }
  1223. }
  1224. // At this point we have no idea of the liveness of the register.
  1225. return LQR_Unknown;
  1226. }
  1227. const uint32_t *
  1228. MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
  1229. // EH funclet entry does not preserve any registers.
  1230. return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
  1231. }
  1232. const uint32_t *
  1233. MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
  1234. // If we see a return block with successors, this must be a funclet return,
  1235. // which does not preserve any registers. If there are no successors, we don't
  1236. // care what kind of return it is, putting a mask after it is a no-op.
  1237. return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
  1238. }
  1239. void MachineBasicBlock::clearLiveIns() {
  1240. LiveIns.clear();
  1241. }
  1242. MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
  1243. assert(getParent()->getProperties().hasProperty(
  1244. MachineFunctionProperties::Property::TracksLiveness) &&
  1245. "Liveness information is accurate");
  1246. return LiveIns.begin();
  1247. }