MachineBasicBlock.cpp 54 KB

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