MachineBasicBlock.cpp 51 KB

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