MachineBasicBlock.cpp 51 KB

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