MachineBasicBlock.h 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/CodeGen/MachineBasicBlock.h -------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // Collect the sequence of machine instructions for a basic block.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
  18. #define LLVM_CODEGEN_MACHINEBASICBLOCK_H
  19. #include "llvm/ADT/GraphTraits.h"
  20. #include "llvm/ADT/ilist.h"
  21. #include "llvm/ADT/iterator_range.h"
  22. #include "llvm/ADT/SparseBitVector.h"
  23. #include "llvm/CodeGen/MachineInstr.h"
  24. #include "llvm/CodeGen/MachineInstrBundleIterator.h"
  25. #include "llvm/IR/DebugLoc.h"
  26. #include "llvm/MC/LaneBitmask.h"
  27. #include "llvm/Support/BranchProbability.h"
  28. #include <cassert>
  29. #include <cstdint>
  30. #include <functional>
  31. #include <iterator>
  32. #include <string>
  33. #include <vector>
  34. namespace llvm {
  35. class BasicBlock;
  36. class MachineFunction;
  37. class MCSymbol;
  38. class ModuleSlotTracker;
  39. class Pass;
  40. class Printable;
  41. class SlotIndexes;
  42. class StringRef;
  43. class raw_ostream;
  44. class LiveIntervals;
  45. class TargetRegisterClass;
  46. class TargetRegisterInfo;
  47. // This structure uniquely identifies a basic block section.
  48. // Possible values are
  49. // {Type: Default, Number: (unsigned)} (These are regular section IDs)
  50. // {Type: Exception, Number: 0} (ExceptionSectionID)
  51. // {Type: Cold, Number: 0} (ColdSectionID)
  52. struct MBBSectionID {
  53. enum SectionType {
  54. Default = 0, // Regular section (these sections are distinguished by the
  55. // Number field).
  56. Exception, // Special section type for exception handling blocks
  57. Cold, // Special section type for cold blocks
  58. } Type;
  59. unsigned Number;
  60. MBBSectionID(unsigned N) : Type(Default), Number(N) {}
  61. // Special unique sections for cold and exception blocks.
  62. const static MBBSectionID ColdSectionID;
  63. const static MBBSectionID ExceptionSectionID;
  64. bool operator==(const MBBSectionID &Other) const {
  65. return Type == Other.Type && Number == Other.Number;
  66. }
  67. bool operator!=(const MBBSectionID &Other) const { return !(*this == Other); }
  68. private:
  69. // This is only used to construct the special cold and exception sections.
  70. MBBSectionID(SectionType T) : Type(T), Number(0) {}
  71. };
  72. template <> struct ilist_traits<MachineInstr> {
  73. private:
  74. friend class MachineBasicBlock; // Set by the owning MachineBasicBlock.
  75. MachineBasicBlock *Parent;
  76. using instr_iterator =
  77. simple_ilist<MachineInstr, ilist_sentinel_tracking<true>>::iterator;
  78. public:
  79. void addNodeToList(MachineInstr *N);
  80. void removeNodeFromList(MachineInstr *N);
  81. void transferNodesFromList(ilist_traits &FromList, instr_iterator First,
  82. instr_iterator Last);
  83. void deleteNode(MachineInstr *MI);
  84. };
  85. class MachineBasicBlock
  86. : public ilist_node_with_parent<MachineBasicBlock, MachineFunction> {
  87. public:
  88. /// Pair of physical register and lane mask.
  89. /// This is not simply a std::pair typedef because the members should be named
  90. /// clearly as they both have an integer type.
  91. struct RegisterMaskPair {
  92. public:
  93. MCPhysReg PhysReg;
  94. LaneBitmask LaneMask;
  95. RegisterMaskPair(MCPhysReg PhysReg, LaneBitmask LaneMask)
  96. : PhysReg(PhysReg), LaneMask(LaneMask) {}
  97. };
  98. private:
  99. using Instructions = ilist<MachineInstr, ilist_sentinel_tracking<true>>;
  100. Instructions Insts;
  101. const BasicBlock *BB;
  102. int Number;
  103. MachineFunction *xParent;
  104. /// Keep track of the predecessor / successor basic blocks.
  105. std::vector<MachineBasicBlock *> Predecessors;
  106. std::vector<MachineBasicBlock *> Successors;
  107. /// Keep track of the probabilities to the successors. This vector has the
  108. /// same order as Successors, or it is empty if we don't use it (disable
  109. /// optimization).
  110. std::vector<BranchProbability> Probs;
  111. using probability_iterator = std::vector<BranchProbability>::iterator;
  112. using const_probability_iterator =
  113. std::vector<BranchProbability>::const_iterator;
  114. Optional<uint64_t> IrrLoopHeaderWeight;
  115. /// Keep track of the physical registers that are livein of the basicblock.
  116. using LiveInVector = std::vector<RegisterMaskPair>;
  117. LiveInVector LiveIns;
  118. /// Alignment of the basic block. One if the basic block does not need to be
  119. /// aligned.
  120. Align Alignment;
  121. /// Maximum amount of bytes that can be added to align the basic block. If the
  122. /// alignment cannot be reached in this many bytes, no bytes are emitted.
  123. /// Zero to represent no maximum.
  124. unsigned MaxBytesForAlignment = 0;
  125. /// Indicate that this basic block is entered via an exception handler.
  126. bool IsEHPad = false;
  127. /// Indicate that this basic block is potentially the target of an indirect
  128. /// branch.
  129. bool AddressTaken = false;
  130. /// Indicate that this basic block needs its symbol be emitted regardless of
  131. /// whether the flow just falls-through to it.
  132. bool LabelMustBeEmitted = false;
  133. /// Indicate that this basic block is the entry block of an EH scope, i.e.,
  134. /// the block that used to have a catchpad or cleanuppad instruction in the
  135. /// LLVM IR.
  136. bool IsEHScopeEntry = false;
  137. /// Indicates if this is a target block of a catchret.
  138. bool IsEHCatchretTarget = false;
  139. /// Indicate that this basic block is the entry block of an EH funclet.
  140. bool IsEHFuncletEntry = false;
  141. /// Indicate that this basic block is the entry block of a cleanup funclet.
  142. bool IsCleanupFuncletEntry = false;
  143. /// With basic block sections, this stores the Section ID of the basic block.
  144. MBBSectionID SectionID{0};
  145. // Indicate that this basic block begins a section.
  146. bool IsBeginSection = false;
  147. // Indicate that this basic block ends a section.
  148. bool IsEndSection = false;
  149. /// Indicate that this basic block is the indirect dest of an INLINEASM_BR.
  150. bool IsInlineAsmBrIndirectTarget = false;
  151. /// since getSymbol is a relatively heavy-weight operation, the symbol
  152. /// is only computed once and is cached.
  153. mutable MCSymbol *CachedMCSymbol = nullptr;
  154. /// Cached MCSymbol for this block (used if IsEHCatchRetTarget).
  155. mutable MCSymbol *CachedEHCatchretMCSymbol = nullptr;
  156. /// Marks the end of the basic block. Used during basic block sections to
  157. /// calculate the size of the basic block, or the BB section ending with it.
  158. mutable MCSymbol *CachedEndMCSymbol = nullptr;
  159. // Intrusive list support
  160. MachineBasicBlock() = default;
  161. explicit MachineBasicBlock(MachineFunction &MF, const BasicBlock *BB);
  162. ~MachineBasicBlock();
  163. // MachineBasicBlocks are allocated and owned by MachineFunction.
  164. friend class MachineFunction;
  165. public:
  166. /// Return the LLVM basic block that this instance corresponded to originally.
  167. /// Note that this may be NULL if this instance does not correspond directly
  168. /// to an LLVM basic block.
  169. const BasicBlock *getBasicBlock() const { return BB; }
  170. /// Return the name of the corresponding LLVM basic block, or an empty string.
  171. StringRef getName() const;
  172. /// Return a formatted string to identify this block and its parent function.
  173. std::string getFullName() const;
  174. /// Test whether this block is potentially the target of an indirect branch.
  175. bool hasAddressTaken() const { return AddressTaken; }
  176. /// Set this block to reflect that it potentially is the target of an indirect
  177. /// branch.
  178. void setHasAddressTaken() { AddressTaken = true; }
  179. /// Test whether this block must have its label emitted.
  180. bool hasLabelMustBeEmitted() const { return LabelMustBeEmitted; }
  181. /// Set this block to reflect that, regardless how we flow to it, we need
  182. /// its label be emitted.
  183. void setLabelMustBeEmitted() { LabelMustBeEmitted = true; }
  184. /// Return the MachineFunction containing this basic block.
  185. const MachineFunction *getParent() const { return xParent; }
  186. MachineFunction *getParent() { return xParent; }
  187. using instr_iterator = Instructions::iterator;
  188. using const_instr_iterator = Instructions::const_iterator;
  189. using reverse_instr_iterator = Instructions::reverse_iterator;
  190. using const_reverse_instr_iterator = Instructions::const_reverse_iterator;
  191. using iterator = MachineInstrBundleIterator<MachineInstr>;
  192. using const_iterator = MachineInstrBundleIterator<const MachineInstr>;
  193. using reverse_iterator = MachineInstrBundleIterator<MachineInstr, true>;
  194. using const_reverse_iterator =
  195. MachineInstrBundleIterator<const MachineInstr, true>;
  196. unsigned size() const { return (unsigned)Insts.size(); }
  197. bool empty() const { return Insts.empty(); }
  198. MachineInstr &instr_front() { return Insts.front(); }
  199. MachineInstr &instr_back() { return Insts.back(); }
  200. const MachineInstr &instr_front() const { return Insts.front(); }
  201. const MachineInstr &instr_back() const { return Insts.back(); }
  202. MachineInstr &front() { return Insts.front(); }
  203. MachineInstr &back() { return *--end(); }
  204. const MachineInstr &front() const { return Insts.front(); }
  205. const MachineInstr &back() const { return *--end(); }
  206. instr_iterator instr_begin() { return Insts.begin(); }
  207. const_instr_iterator instr_begin() const { return Insts.begin(); }
  208. instr_iterator instr_end() { return Insts.end(); }
  209. const_instr_iterator instr_end() const { return Insts.end(); }
  210. reverse_instr_iterator instr_rbegin() { return Insts.rbegin(); }
  211. const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
  212. reverse_instr_iterator instr_rend () { return Insts.rend(); }
  213. const_reverse_instr_iterator instr_rend () const { return Insts.rend(); }
  214. using instr_range = iterator_range<instr_iterator>;
  215. using const_instr_range = iterator_range<const_instr_iterator>;
  216. instr_range instrs() { return instr_range(instr_begin(), instr_end()); }
  217. const_instr_range instrs() const {
  218. return const_instr_range(instr_begin(), instr_end());
  219. }
  220. iterator begin() { return instr_begin(); }
  221. const_iterator begin() const { return instr_begin(); }
  222. iterator end () { return instr_end(); }
  223. const_iterator end () const { return instr_end(); }
  224. reverse_iterator rbegin() {
  225. return reverse_iterator::getAtBundleBegin(instr_rbegin());
  226. }
  227. const_reverse_iterator rbegin() const {
  228. return const_reverse_iterator::getAtBundleBegin(instr_rbegin());
  229. }
  230. reverse_iterator rend() { return reverse_iterator(instr_rend()); }
  231. const_reverse_iterator rend() const {
  232. return const_reverse_iterator(instr_rend());
  233. }
  234. /// Support for MachineInstr::getNextNode().
  235. static Instructions MachineBasicBlock::*getSublistAccess(MachineInstr *) {
  236. return &MachineBasicBlock::Insts;
  237. }
  238. inline iterator_range<iterator> terminators() {
  239. return make_range(getFirstTerminator(), end());
  240. }
  241. inline iterator_range<const_iterator> terminators() const {
  242. return make_range(getFirstTerminator(), end());
  243. }
  244. /// Returns a range that iterates over the phis in the basic block.
  245. inline iterator_range<iterator> phis() {
  246. return make_range(begin(), getFirstNonPHI());
  247. }
  248. inline iterator_range<const_iterator> phis() const {
  249. return const_cast<MachineBasicBlock *>(this)->phis();
  250. }
  251. // Machine-CFG iterators
  252. using pred_iterator = std::vector<MachineBasicBlock *>::iterator;
  253. using const_pred_iterator = std::vector<MachineBasicBlock *>::const_iterator;
  254. using succ_iterator = std::vector<MachineBasicBlock *>::iterator;
  255. using const_succ_iterator = std::vector<MachineBasicBlock *>::const_iterator;
  256. using pred_reverse_iterator =
  257. std::vector<MachineBasicBlock *>::reverse_iterator;
  258. using const_pred_reverse_iterator =
  259. std::vector<MachineBasicBlock *>::const_reverse_iterator;
  260. using succ_reverse_iterator =
  261. std::vector<MachineBasicBlock *>::reverse_iterator;
  262. using const_succ_reverse_iterator =
  263. std::vector<MachineBasicBlock *>::const_reverse_iterator;
  264. pred_iterator pred_begin() { return Predecessors.begin(); }
  265. const_pred_iterator pred_begin() const { return Predecessors.begin(); }
  266. pred_iterator pred_end() { return Predecessors.end(); }
  267. const_pred_iterator pred_end() const { return Predecessors.end(); }
  268. pred_reverse_iterator pred_rbegin()
  269. { return Predecessors.rbegin();}
  270. const_pred_reverse_iterator pred_rbegin() const
  271. { return Predecessors.rbegin();}
  272. pred_reverse_iterator pred_rend()
  273. { return Predecessors.rend(); }
  274. const_pred_reverse_iterator pred_rend() const
  275. { return Predecessors.rend(); }
  276. unsigned pred_size() const {
  277. return (unsigned)Predecessors.size();
  278. }
  279. bool pred_empty() const { return Predecessors.empty(); }
  280. succ_iterator succ_begin() { return Successors.begin(); }
  281. const_succ_iterator succ_begin() const { return Successors.begin(); }
  282. succ_iterator succ_end() { return Successors.end(); }
  283. const_succ_iterator succ_end() const { return Successors.end(); }
  284. succ_reverse_iterator succ_rbegin()
  285. { return Successors.rbegin(); }
  286. const_succ_reverse_iterator succ_rbegin() const
  287. { return Successors.rbegin(); }
  288. succ_reverse_iterator succ_rend()
  289. { return Successors.rend(); }
  290. const_succ_reverse_iterator succ_rend() const
  291. { return Successors.rend(); }
  292. unsigned succ_size() const {
  293. return (unsigned)Successors.size();
  294. }
  295. bool succ_empty() const { return Successors.empty(); }
  296. inline iterator_range<pred_iterator> predecessors() {
  297. return make_range(pred_begin(), pred_end());
  298. }
  299. inline iterator_range<const_pred_iterator> predecessors() const {
  300. return make_range(pred_begin(), pred_end());
  301. }
  302. inline iterator_range<succ_iterator> successors() {
  303. return make_range(succ_begin(), succ_end());
  304. }
  305. inline iterator_range<const_succ_iterator> successors() const {
  306. return make_range(succ_begin(), succ_end());
  307. }
  308. // LiveIn management methods.
  309. /// Adds the specified register as a live in. Note that it is an error to add
  310. /// the same register to the same set more than once unless the intention is
  311. /// to call sortUniqueLiveIns after all registers are added.
  312. void addLiveIn(MCRegister PhysReg,
  313. LaneBitmask LaneMask = LaneBitmask::getAll()) {
  314. LiveIns.push_back(RegisterMaskPair(PhysReg, LaneMask));
  315. }
  316. void addLiveIn(const RegisterMaskPair &RegMaskPair) {
  317. LiveIns.push_back(RegMaskPair);
  318. }
  319. /// Sorts and uniques the LiveIns vector. It can be significantly faster to do
  320. /// this than repeatedly calling isLiveIn before calling addLiveIn for every
  321. /// LiveIn insertion.
  322. void sortUniqueLiveIns();
  323. /// Clear live in list.
  324. void clearLiveIns();
  325. /// Add PhysReg as live in to this block, and ensure that there is a copy of
  326. /// PhysReg to a virtual register of class RC. Return the virtual register
  327. /// that is a copy of the live in PhysReg.
  328. Register addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC);
  329. /// Remove the specified register from the live in set.
  330. void removeLiveIn(MCPhysReg Reg,
  331. LaneBitmask LaneMask = LaneBitmask::getAll());
  332. /// Return true if the specified register is in the live in set.
  333. bool isLiveIn(MCPhysReg Reg,
  334. LaneBitmask LaneMask = LaneBitmask::getAll()) const;
  335. // Iteration support for live in sets. These sets are kept in sorted
  336. // order by their register number.
  337. using livein_iterator = LiveInVector::const_iterator;
  338. #ifndef NDEBUG
  339. /// Unlike livein_begin, this method does not check that the liveness
  340. /// information is accurate. Still for debug purposes it may be useful
  341. /// to have iterators that won't assert if the liveness information
  342. /// is not current.
  343. livein_iterator livein_begin_dbg() const { return LiveIns.begin(); }
  344. iterator_range<livein_iterator> liveins_dbg() const {
  345. return make_range(livein_begin_dbg(), livein_end());
  346. }
  347. #endif
  348. livein_iterator livein_begin() const;
  349. livein_iterator livein_end() const { return LiveIns.end(); }
  350. bool livein_empty() const { return LiveIns.empty(); }
  351. iterator_range<livein_iterator> liveins() const {
  352. return make_range(livein_begin(), livein_end());
  353. }
  354. /// Remove entry from the livein set and return iterator to the next.
  355. livein_iterator removeLiveIn(livein_iterator I);
  356. class liveout_iterator {
  357. public:
  358. using iterator_category = std::input_iterator_tag;
  359. using difference_type = std::ptrdiff_t;
  360. using value_type = RegisterMaskPair;
  361. using pointer = const RegisterMaskPair *;
  362. using reference = const RegisterMaskPair &;
  363. liveout_iterator(const MachineBasicBlock &MBB, MCPhysReg ExceptionPointer,
  364. MCPhysReg ExceptionSelector, bool End)
  365. : ExceptionPointer(ExceptionPointer),
  366. ExceptionSelector(ExceptionSelector), BlockI(MBB.succ_begin()),
  367. BlockEnd(MBB.succ_end()) {
  368. if (End)
  369. BlockI = BlockEnd;
  370. else if (BlockI != BlockEnd) {
  371. LiveRegI = (*BlockI)->livein_begin();
  372. if (!advanceToValidPosition())
  373. return;
  374. if (LiveRegI->PhysReg == ExceptionPointer ||
  375. LiveRegI->PhysReg == ExceptionSelector)
  376. ++(*this);
  377. }
  378. }
  379. liveout_iterator &operator++() {
  380. do {
  381. ++LiveRegI;
  382. if (!advanceToValidPosition())
  383. return *this;
  384. } while ((*BlockI)->isEHPad() &&
  385. (LiveRegI->PhysReg == ExceptionPointer ||
  386. LiveRegI->PhysReg == ExceptionSelector));
  387. return *this;
  388. }
  389. liveout_iterator operator++(int) {
  390. liveout_iterator Tmp = *this;
  391. ++(*this);
  392. return Tmp;
  393. }
  394. reference operator*() const {
  395. return *LiveRegI;
  396. }
  397. pointer operator->() const {
  398. return &*LiveRegI;
  399. }
  400. bool operator==(const liveout_iterator &RHS) const {
  401. if (BlockI != BlockEnd)
  402. return BlockI == RHS.BlockI && LiveRegI == RHS.LiveRegI;
  403. return RHS.BlockI == BlockEnd;
  404. }
  405. bool operator!=(const liveout_iterator &RHS) const {
  406. return !(*this == RHS);
  407. }
  408. private:
  409. bool advanceToValidPosition() {
  410. if (LiveRegI != (*BlockI)->livein_end())
  411. return true;
  412. do {
  413. ++BlockI;
  414. } while (BlockI != BlockEnd && (*BlockI)->livein_empty());
  415. if (BlockI == BlockEnd)
  416. return false;
  417. LiveRegI = (*BlockI)->livein_begin();
  418. return true;
  419. }
  420. MCPhysReg ExceptionPointer, ExceptionSelector;
  421. const_succ_iterator BlockI;
  422. const_succ_iterator BlockEnd;
  423. livein_iterator LiveRegI;
  424. };
  425. /// Iterator scanning successor basic blocks' liveins to determine the
  426. /// registers potentially live at the end of this block. There may be
  427. /// duplicates or overlapping registers in the list returned.
  428. liveout_iterator liveout_begin() const;
  429. liveout_iterator liveout_end() const {
  430. return liveout_iterator(*this, 0, 0, true);
  431. }
  432. iterator_range<liveout_iterator> liveouts() const {
  433. return make_range(liveout_begin(), liveout_end());
  434. }
  435. /// Get the clobber mask for the start of this basic block. Funclets use this
  436. /// to prevent register allocation across funclet transitions.
  437. const uint32_t *getBeginClobberMask(const TargetRegisterInfo *TRI) const;
  438. /// Get the clobber mask for the end of the basic block.
  439. /// \see getBeginClobberMask()
  440. const uint32_t *getEndClobberMask(const TargetRegisterInfo *TRI) const;
  441. /// Return alignment of the basic block.
  442. Align getAlignment() const { return Alignment; }
  443. /// Set alignment of the basic block.
  444. void setAlignment(Align A) { Alignment = A; }
  445. void setAlignment(Align A, unsigned MaxBytes) {
  446. setAlignment(A);
  447. setMaxBytesForAlignment(MaxBytes);
  448. }
  449. /// Return the maximum amount of padding allowed for aligning the basic block.
  450. unsigned getMaxBytesForAlignment() const { return MaxBytesForAlignment; }
  451. /// Set the maximum amount of padding allowed for aligning the basic block
  452. void setMaxBytesForAlignment(unsigned MaxBytes) {
  453. MaxBytesForAlignment = MaxBytes;
  454. }
  455. /// Returns true if the block is a landing pad. That is this basic block is
  456. /// entered via an exception handler.
  457. bool isEHPad() const { return IsEHPad; }
  458. /// Indicates the block is a landing pad. That is this basic block is entered
  459. /// via an exception handler.
  460. void setIsEHPad(bool V = true) { IsEHPad = V; }
  461. bool hasEHPadSuccessor() const;
  462. /// Returns true if this is the entry block of the function.
  463. bool isEntryBlock() const;
  464. /// Returns true if this is the entry block of an EH scope, i.e., the block
  465. /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
  466. bool isEHScopeEntry() const { return IsEHScopeEntry; }
  467. /// Indicates if this is the entry block of an EH scope, i.e., the block that
  468. /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
  469. void setIsEHScopeEntry(bool V = true) { IsEHScopeEntry = V; }
  470. /// Returns true if this is a target block of a catchret.
  471. bool isEHCatchretTarget() const { return IsEHCatchretTarget; }
  472. /// Indicates if this is a target block of a catchret.
  473. void setIsEHCatchretTarget(bool V = true) { IsEHCatchretTarget = V; }
  474. /// Returns true if this is the entry block of an EH funclet.
  475. bool isEHFuncletEntry() const { return IsEHFuncletEntry; }
  476. /// Indicates if this is the entry block of an EH funclet.
  477. void setIsEHFuncletEntry(bool V = true) { IsEHFuncletEntry = V; }
  478. /// Returns true if this is the entry block of a cleanup funclet.
  479. bool isCleanupFuncletEntry() const { return IsCleanupFuncletEntry; }
  480. /// Indicates if this is the entry block of a cleanup funclet.
  481. void setIsCleanupFuncletEntry(bool V = true) { IsCleanupFuncletEntry = V; }
  482. /// Returns true if this block begins any section.
  483. bool isBeginSection() const { return IsBeginSection; }
  484. /// Returns true if this block ends any section.
  485. bool isEndSection() const { return IsEndSection; }
  486. void setIsBeginSection(bool V = true) { IsBeginSection = V; }
  487. void setIsEndSection(bool V = true) { IsEndSection = V; }
  488. /// Returns the section ID of this basic block.
  489. MBBSectionID getSectionID() const { return SectionID; }
  490. /// Returns the unique section ID number of this basic block.
  491. unsigned getSectionIDNum() const {
  492. return ((unsigned)MBBSectionID::SectionType::Cold) -
  493. ((unsigned)SectionID.Type) + SectionID.Number;
  494. }
  495. /// Sets the section ID for this basic block.
  496. void setSectionID(MBBSectionID V) { SectionID = V; }
  497. /// Returns the MCSymbol marking the end of this basic block.
  498. MCSymbol *getEndSymbol() const;
  499. /// Returns true if this block may have an INLINEASM_BR (overestimate, by
  500. /// checking if any of the successors are indirect targets of any inlineasm_br
  501. /// in the function).
  502. bool mayHaveInlineAsmBr() const;
  503. /// Returns true if this is the indirect dest of an INLINEASM_BR.
  504. bool isInlineAsmBrIndirectTarget() const {
  505. return IsInlineAsmBrIndirectTarget;
  506. }
  507. /// Indicates if this is the indirect dest of an INLINEASM_BR.
  508. void setIsInlineAsmBrIndirectTarget(bool V = true) {
  509. IsInlineAsmBrIndirectTarget = V;
  510. }
  511. /// Returns true if it is legal to hoist instructions into this block.
  512. bool isLegalToHoistInto() const;
  513. // Code Layout methods.
  514. /// Move 'this' block before or after the specified block. This only moves
  515. /// the block, it does not modify the CFG or adjust potential fall-throughs at
  516. /// the end of the block.
  517. void moveBefore(MachineBasicBlock *NewAfter);
  518. void moveAfter(MachineBasicBlock *NewBefore);
  519. /// Returns true if this and MBB belong to the same section.
  520. bool sameSection(const MachineBasicBlock *MBB) const {
  521. return getSectionID() == MBB->getSectionID();
  522. }
  523. /// Update the terminator instructions in block to account for changes to
  524. /// block layout which may have been made. PreviousLayoutSuccessor should be
  525. /// set to the block which may have been used as fallthrough before the block
  526. /// layout was modified. If the block previously fell through to that block,
  527. /// it may now need a branch. If it previously branched to another block, it
  528. /// may now be able to fallthrough to the current layout successor.
  529. void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor);
  530. // Machine-CFG mutators
  531. /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
  532. /// of Succ is automatically updated. PROB parameter is stored in
  533. /// Probabilities list. The default probability is set as unknown. Mixing
  534. /// known and unknown probabilities in successor list is not allowed. When all
  535. /// successors have unknown probabilities, 1 / N is returned as the
  536. /// probability for each successor, where N is the number of successors.
  537. ///
  538. /// Note that duplicate Machine CFG edges are not allowed.
  539. void addSuccessor(MachineBasicBlock *Succ,
  540. BranchProbability Prob = BranchProbability::getUnknown());
  541. /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
  542. /// of Succ is automatically updated. The probability is not provided because
  543. /// BPI is not available (e.g. -O0 is used), in which case edge probabilities
  544. /// won't be used. Using this interface can save some space.
  545. void addSuccessorWithoutProb(MachineBasicBlock *Succ);
  546. /// Set successor probability of a given iterator.
  547. void setSuccProbability(succ_iterator I, BranchProbability Prob);
  548. /// Normalize probabilities of all successors so that the sum of them becomes
  549. /// one. This is usually done when the current update on this MBB is done, and
  550. /// the sum of its successors' probabilities is not guaranteed to be one. The
  551. /// user is responsible for the correct use of this function.
  552. /// MBB::removeSuccessor() has an option to do this automatically.
  553. void normalizeSuccProbs() {
  554. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  555. }
  556. /// Validate successors' probabilities and check if the sum of them is
  557. /// approximate one. This only works in DEBUG mode.
  558. void validateSuccProbs() const;
  559. /// Remove successor from the successors list of this MachineBasicBlock. The
  560. /// Predecessors list of Succ is automatically updated.
  561. /// If NormalizeSuccProbs is true, then normalize successors' probabilities
  562. /// after the successor is removed.
  563. void removeSuccessor(MachineBasicBlock *Succ,
  564. bool NormalizeSuccProbs = false);
  565. /// Remove specified successor from the successors list of this
  566. /// MachineBasicBlock. The Predecessors list of Succ is automatically updated.
  567. /// If NormalizeSuccProbs is true, then normalize successors' probabilities
  568. /// after the successor is removed.
  569. /// Return the iterator to the element after the one removed.
  570. succ_iterator removeSuccessor(succ_iterator I,
  571. bool NormalizeSuccProbs = false);
  572. /// Replace successor OLD with NEW and update probability info.
  573. void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
  574. /// Copy a successor (and any probability info) from original block to this
  575. /// block's. Uses an iterator into the original blocks successors.
  576. ///
  577. /// This is useful when doing a partial clone of successors. Afterward, the
  578. /// probabilities may need to be normalized.
  579. void copySuccessor(MachineBasicBlock *Orig, succ_iterator I);
  580. /// Split the old successor into old plus new and updates the probability
  581. /// info.
  582. void splitSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New,
  583. bool NormalizeSuccProbs = false);
  584. /// Transfers all the successors from MBB to this machine basic block (i.e.,
  585. /// copies all the successors FromMBB and remove all the successors from
  586. /// FromMBB).
  587. void transferSuccessors(MachineBasicBlock *FromMBB);
  588. /// Transfers all the successors, as in transferSuccessors, and update PHI
  589. /// operands in the successor blocks which refer to FromMBB to refer to this.
  590. void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB);
  591. /// Return true if any of the successors have probabilities attached to them.
  592. bool hasSuccessorProbabilities() const { return !Probs.empty(); }
  593. /// Return true if the specified MBB is a predecessor of this block.
  594. bool isPredecessor(const MachineBasicBlock *MBB) const;
  595. /// Return true if the specified MBB is a successor of this block.
  596. bool isSuccessor(const MachineBasicBlock *MBB) const;
  597. /// Return true if the specified MBB will be emitted immediately after this
  598. /// block, such that if this block exits by falling through, control will
  599. /// transfer to the specified MBB. Note that MBB need not be a successor at
  600. /// all, for example if this block ends with an unconditional branch to some
  601. /// other block.
  602. bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
  603. /// Return the fallthrough block if the block can implicitly
  604. /// transfer control to the block after it by falling off the end of
  605. /// it. This should return null if it can reach the block after
  606. /// it, but it uses an explicit branch to do so (e.g., a table
  607. /// jump). Non-null return is a conservative answer.
  608. MachineBasicBlock *getFallThrough();
  609. /// Return true if the block can implicitly transfer control to the
  610. /// block after it by falling off the end of it. This should return
  611. /// false if it can reach the block after it, but it uses an
  612. /// explicit branch to do so (e.g., a table jump). True is a
  613. /// conservative answer.
  614. bool canFallThrough();
  615. /// Returns a pointer to the first instruction in this block that is not a
  616. /// PHINode instruction. When adding instructions to the beginning of the
  617. /// basic block, they should be added before the returned value, not before
  618. /// the first instruction, which might be PHI.
  619. /// Returns end() is there's no non-PHI instruction.
  620. iterator getFirstNonPHI();
  621. /// Return the first instruction in MBB after I that is not a PHI or a label.
  622. /// This is the correct point to insert lowered copies at the beginning of a
  623. /// basic block that must be before any debugging information.
  624. iterator SkipPHIsAndLabels(iterator I);
  625. /// Return the first instruction in MBB after I that is not a PHI, label or
  626. /// debug. This is the correct point to insert copies at the beginning of a
  627. /// basic block.
  628. iterator SkipPHIsLabelsAndDebug(iterator I, bool SkipPseudoOp = true);
  629. /// Returns an iterator to the first terminator instruction of this basic
  630. /// block. If a terminator does not exist, it returns end().
  631. iterator getFirstTerminator();
  632. const_iterator getFirstTerminator() const {
  633. return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
  634. }
  635. /// Same getFirstTerminator but it ignores bundles and return an
  636. /// instr_iterator instead.
  637. instr_iterator getFirstInstrTerminator();
  638. /// Returns an iterator to the first non-debug instruction in the basic block,
  639. /// or end(). Skip any pseudo probe operation if \c SkipPseudoOp is true.
  640. /// Pseudo probes are like debug instructions which do not turn into real
  641. /// machine code. We try to use the function to skip both debug instructions
  642. /// and pseudo probe operations to avoid API proliferation. This should work
  643. /// most of the time when considering optimizing the rest of code in the
  644. /// block, except for certain cases where pseudo probes are designed to block
  645. /// the optimizations. For example, code merge like optimizations are supposed
  646. /// to be blocked by pseudo probes for better AutoFDO profile quality.
  647. /// Therefore, they should be considered as a valid instruction when this
  648. /// function is called in a context of such optimizations. On the other hand,
  649. /// \c SkipPseudoOp should be true when it's used in optimizations that
  650. /// unlikely hurt profile quality, e.g., without block merging. The default
  651. /// value of \c SkipPseudoOp is set to true to maximize code quality in
  652. /// general, with an explict false value passed in in a few places like branch
  653. /// folding and if-conversion to favor profile quality.
  654. iterator getFirstNonDebugInstr(bool SkipPseudoOp = true);
  655. const_iterator getFirstNonDebugInstr(bool SkipPseudoOp = true) const {
  656. return const_cast<MachineBasicBlock *>(this)->getFirstNonDebugInstr(
  657. SkipPseudoOp);
  658. }
  659. /// Returns an iterator to the last non-debug instruction in the basic block,
  660. /// or end(). Skip any pseudo operation if \c SkipPseudoOp is true.
  661. /// Pseudo probes are like debug instructions which do not turn into real
  662. /// machine code. We try to use the function to skip both debug instructions
  663. /// and pseudo probe operations to avoid API proliferation. This should work
  664. /// most of the time when considering optimizing the rest of code in the
  665. /// block, except for certain cases where pseudo probes are designed to block
  666. /// the optimizations. For example, code merge like optimizations are supposed
  667. /// to be blocked by pseudo probes for better AutoFDO profile quality.
  668. /// Therefore, they should be considered as a valid instruction when this
  669. /// function is called in a context of such optimizations. On the other hand,
  670. /// \c SkipPseudoOp should be true when it's used in optimizations that
  671. /// unlikely hurt profile quality, e.g., without block merging. The default
  672. /// value of \c SkipPseudoOp is set to true to maximize code quality in
  673. /// general, with an explict false value passed in in a few places like branch
  674. /// folding and if-conversion to favor profile quality.
  675. iterator getLastNonDebugInstr(bool SkipPseudoOp = true);
  676. const_iterator getLastNonDebugInstr(bool SkipPseudoOp = true) const {
  677. return const_cast<MachineBasicBlock *>(this)->getLastNonDebugInstr(
  678. SkipPseudoOp);
  679. }
  680. /// Convenience function that returns true if the block ends in a return
  681. /// instruction.
  682. bool isReturnBlock() const {
  683. return !empty() && back().isReturn();
  684. }
  685. /// Convenience function that returns true if the bock ends in a EH scope
  686. /// return instruction.
  687. bool isEHScopeReturnBlock() const {
  688. return !empty() && back().isEHScopeReturn();
  689. }
  690. /// Split a basic block into 2 pieces at \p SplitPoint. A new block will be
  691. /// inserted after this block, and all instructions after \p SplitInst moved
  692. /// to it (\p SplitInst will be in the original block). If \p LIS is provided,
  693. /// LiveIntervals will be appropriately updated. \return the newly inserted
  694. /// block.
  695. ///
  696. /// If \p UpdateLiveIns is true, this will ensure the live ins list is
  697. /// accurate, including for physreg uses/defs in the original block.
  698. MachineBasicBlock *splitAt(MachineInstr &SplitInst, bool UpdateLiveIns = true,
  699. LiveIntervals *LIS = nullptr);
  700. /// Split the critical edge from this block to the given successor block, and
  701. /// return the newly created block, or null if splitting is not possible.
  702. ///
  703. /// This function updates LiveVariables, MachineDominatorTree, and
  704. /// MachineLoopInfo, as applicable.
  705. MachineBasicBlock *
  706. SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P,
  707. std::vector<SparseBitVector<>> *LiveInSets = nullptr);
  708. /// Check if the edge between this block and the given successor \p
  709. /// Succ, can be split. If this returns true a subsequent call to
  710. /// SplitCriticalEdge is guaranteed to return a valid basic block if
  711. /// no changes occurred in the meantime.
  712. bool canSplitCriticalEdge(const MachineBasicBlock *Succ) const;
  713. void pop_front() { Insts.pop_front(); }
  714. void pop_back() { Insts.pop_back(); }
  715. void push_back(MachineInstr *MI) { Insts.push_back(MI); }
  716. /// Insert MI into the instruction list before I, possibly inside a bundle.
  717. ///
  718. /// If the insertion point is inside a bundle, MI will be added to the bundle,
  719. /// otherwise MI will not be added to any bundle. That means this function
  720. /// alone can't be used to prepend or append instructions to bundles. See
  721. /// MIBundleBuilder::insert() for a more reliable way of doing that.
  722. instr_iterator insert(instr_iterator I, MachineInstr *M);
  723. /// Insert a range of instructions into the instruction list before I.
  724. template<typename IT>
  725. void insert(iterator I, IT S, IT E) {
  726. assert((I == end() || I->getParent() == this) &&
  727. "iterator points outside of basic block");
  728. Insts.insert(I.getInstrIterator(), S, E);
  729. }
  730. /// Insert MI into the instruction list before I.
  731. iterator insert(iterator I, MachineInstr *MI) {
  732. assert((I == end() || I->getParent() == this) &&
  733. "iterator points outside of basic block");
  734. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  735. "Cannot insert instruction with bundle flags");
  736. return Insts.insert(I.getInstrIterator(), MI);
  737. }
  738. /// Insert MI into the instruction list after I.
  739. iterator insertAfter(iterator I, MachineInstr *MI) {
  740. assert((I == end() || I->getParent() == this) &&
  741. "iterator points outside of basic block");
  742. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  743. "Cannot insert instruction with bundle flags");
  744. return Insts.insertAfter(I.getInstrIterator(), MI);
  745. }
  746. /// If I is bundled then insert MI into the instruction list after the end of
  747. /// the bundle, otherwise insert MI immediately after I.
  748. instr_iterator insertAfterBundle(instr_iterator I, MachineInstr *MI) {
  749. assert((I == instr_end() || I->getParent() == this) &&
  750. "iterator points outside of basic block");
  751. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  752. "Cannot insert instruction with bundle flags");
  753. while (I->isBundledWithSucc())
  754. ++I;
  755. return Insts.insertAfter(I, MI);
  756. }
  757. /// Remove an instruction from the instruction list and delete it.
  758. ///
  759. /// If the instruction is part of a bundle, the other instructions in the
  760. /// bundle will still be bundled after removing the single instruction.
  761. instr_iterator erase(instr_iterator I);
  762. /// Remove an instruction from the instruction list and delete it.
  763. ///
  764. /// If the instruction is part of a bundle, the other instructions in the
  765. /// bundle will still be bundled after removing the single instruction.
  766. instr_iterator erase_instr(MachineInstr *I) {
  767. return erase(instr_iterator(I));
  768. }
  769. /// Remove a range of instructions from the instruction list and delete them.
  770. iterator erase(iterator I, iterator E) {
  771. return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
  772. }
  773. /// Remove an instruction or bundle from the instruction list and delete it.
  774. ///
  775. /// If I points to a bundle of instructions, they are all erased.
  776. iterator erase(iterator I) {
  777. return erase(I, std::next(I));
  778. }
  779. /// Remove an instruction from the instruction list and delete it.
  780. ///
  781. /// If I is the head of a bundle of instructions, the whole bundle will be
  782. /// erased.
  783. iterator erase(MachineInstr *I) {
  784. return erase(iterator(I));
  785. }
  786. /// Remove the unbundled instruction from the instruction list without
  787. /// deleting it.
  788. ///
  789. /// This function can not be used to remove bundled instructions, use
  790. /// remove_instr to remove individual instructions from a bundle.
  791. MachineInstr *remove(MachineInstr *I) {
  792. assert(!I->isBundled() && "Cannot remove bundled instructions");
  793. return Insts.remove(instr_iterator(I));
  794. }
  795. /// Remove the possibly bundled instruction from the instruction list
  796. /// without deleting it.
  797. ///
  798. /// If the instruction is part of a bundle, the other instructions in the
  799. /// bundle will still be bundled after removing the single instruction.
  800. MachineInstr *remove_instr(MachineInstr *I);
  801. void clear() {
  802. Insts.clear();
  803. }
  804. /// Take an instruction from MBB 'Other' at the position From, and insert it
  805. /// into this MBB right before 'Where'.
  806. ///
  807. /// If From points to a bundle of instructions, the whole bundle is moved.
  808. void splice(iterator Where, MachineBasicBlock *Other, iterator From) {
  809. // The range splice() doesn't allow noop moves, but this one does.
  810. if (Where != From)
  811. splice(Where, Other, From, std::next(From));
  812. }
  813. /// Take a block of instructions from MBB 'Other' in the range [From, To),
  814. /// and insert them into this MBB right before 'Where'.
  815. ///
  816. /// The instruction at 'Where' must not be included in the range of
  817. /// instructions to move.
  818. void splice(iterator Where, MachineBasicBlock *Other,
  819. iterator From, iterator To) {
  820. Insts.splice(Where.getInstrIterator(), Other->Insts,
  821. From.getInstrIterator(), To.getInstrIterator());
  822. }
  823. /// This method unlinks 'this' from the containing function, and returns it,
  824. /// but does not delete it.
  825. MachineBasicBlock *removeFromParent();
  826. /// This method unlinks 'this' from the containing function and deletes it.
  827. void eraseFromParent();
  828. /// Given a machine basic block that branched to 'Old', change the code and
  829. /// CFG so that it branches to 'New' instead.
  830. void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
  831. /// Update all phi nodes in this basic block to refer to basic block \p New
  832. /// instead of basic block \p Old.
  833. void replacePhiUsesWith(MachineBasicBlock *Old, MachineBasicBlock *New);
  834. /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
  835. /// and DBG_LABEL instructions. Return UnknownLoc if there is none.
  836. DebugLoc findDebugLoc(instr_iterator MBBI);
  837. DebugLoc findDebugLoc(iterator MBBI) {
  838. return findDebugLoc(MBBI.getInstrIterator());
  839. }
  840. /// Has exact same behavior as @ref findDebugLoc (it also
  841. /// searches from the first to the last MI of this MBB) except
  842. /// that this takes reverse iterator.
  843. DebugLoc rfindDebugLoc(reverse_instr_iterator MBBI);
  844. DebugLoc rfindDebugLoc(reverse_iterator MBBI) {
  845. return rfindDebugLoc(MBBI.getInstrIterator());
  846. }
  847. /// Find the previous valid DebugLoc preceding MBBI, skipping and DBG_VALUE
  848. /// instructions. Return UnknownLoc if there is none.
  849. DebugLoc findPrevDebugLoc(instr_iterator MBBI);
  850. DebugLoc findPrevDebugLoc(iterator MBBI) {
  851. return findPrevDebugLoc(MBBI.getInstrIterator());
  852. }
  853. /// Has exact same behavior as @ref findPrevDebugLoc (it also
  854. /// searches from the last to the first MI of this MBB) except
  855. /// that this takes reverse iterator.
  856. DebugLoc rfindPrevDebugLoc(reverse_instr_iterator MBBI);
  857. DebugLoc rfindPrevDebugLoc(reverse_iterator MBBI) {
  858. return rfindPrevDebugLoc(MBBI.getInstrIterator());
  859. }
  860. /// Find and return the merged DebugLoc of the branch instructions of the
  861. /// block. Return UnknownLoc if there is none.
  862. DebugLoc findBranchDebugLoc();
  863. /// Possible outcome of a register liveness query to computeRegisterLiveness()
  864. enum LivenessQueryResult {
  865. LQR_Live, ///< Register is known to be (at least partially) live.
  866. LQR_Dead, ///< Register is known to be fully dead.
  867. LQR_Unknown ///< Register liveness not decidable from local neighborhood.
  868. };
  869. /// Return whether (physical) register \p Reg has been defined and not
  870. /// killed as of just before \p Before.
  871. ///
  872. /// Search is localised to a neighborhood of \p Neighborhood instructions
  873. /// before (searching for defs or kills) and \p Neighborhood instructions
  874. /// after (searching just for defs) \p Before.
  875. ///
  876. /// \p Reg must be a physical register.
  877. LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
  878. MCRegister Reg,
  879. const_iterator Before,
  880. unsigned Neighborhood = 10) const;
  881. // Debugging methods.
  882. void dump() const;
  883. void print(raw_ostream &OS, const SlotIndexes * = nullptr,
  884. bool IsStandalone = true) const;
  885. void print(raw_ostream &OS, ModuleSlotTracker &MST,
  886. const SlotIndexes * = nullptr, bool IsStandalone = true) const;
  887. enum PrintNameFlag {
  888. PrintNameIr = (1 << 0), ///< Add IR name where available
  889. PrintNameAttributes = (1 << 1), ///< Print attributes
  890. };
  891. void printName(raw_ostream &os, unsigned printNameFlags = PrintNameIr,
  892. ModuleSlotTracker *moduleSlotTracker = nullptr) const;
  893. // Printing method used by LoopInfo.
  894. void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
  895. /// MachineBasicBlocks are uniquely numbered at the function level, unless
  896. /// they're not in a MachineFunction yet, in which case this will return -1.
  897. int getNumber() const { return Number; }
  898. void setNumber(int N) { Number = N; }
  899. /// Return the MCSymbol for this basic block.
  900. MCSymbol *getSymbol() const;
  901. /// Return the EHCatchret Symbol for this basic block.
  902. MCSymbol *getEHCatchretSymbol() const;
  903. Optional<uint64_t> getIrrLoopHeaderWeight() const {
  904. return IrrLoopHeaderWeight;
  905. }
  906. void setIrrLoopHeaderWeight(uint64_t Weight) {
  907. IrrLoopHeaderWeight = Weight;
  908. }
  909. private:
  910. /// Return probability iterator corresponding to the I successor iterator.
  911. probability_iterator getProbabilityIterator(succ_iterator I);
  912. const_probability_iterator
  913. getProbabilityIterator(const_succ_iterator I) const;
  914. friend class MachineBranchProbabilityInfo;
  915. friend class MIPrinter;
  916. /// Return probability of the edge from this block to MBB. This method should
  917. /// NOT be called directly, but by using getEdgeProbability method from
  918. /// MachineBranchProbabilityInfo class.
  919. BranchProbability getSuccProbability(const_succ_iterator Succ) const;
  920. // Methods used to maintain doubly linked list of blocks...
  921. friend struct ilist_callback_traits<MachineBasicBlock>;
  922. // Machine-CFG mutators
  923. /// Add Pred as a predecessor of this MachineBasicBlock. Don't do this
  924. /// unless you know what you're doing, because it doesn't update Pred's
  925. /// successors list. Use Pred->addSuccessor instead.
  926. void addPredecessor(MachineBasicBlock *Pred);
  927. /// Remove Pred as a predecessor of this MachineBasicBlock. Don't do this
  928. /// unless you know what you're doing, because it doesn't update Pred's
  929. /// successors list. Use Pred->removeSuccessor instead.
  930. void removePredecessor(MachineBasicBlock *Pred);
  931. };
  932. raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
  933. /// Prints a machine basic block reference.
  934. ///
  935. /// The format is:
  936. /// %bb.5 - a machine basic block with MBB.getNumber() == 5.
  937. ///
  938. /// Usage: OS << printMBBReference(MBB) << '\n';
  939. Printable printMBBReference(const MachineBasicBlock &MBB);
  940. // This is useful when building IndexedMaps keyed on basic block pointers.
  941. struct MBB2NumberFunctor {
  942. using argument_type = const MachineBasicBlock *;
  943. unsigned operator()(const MachineBasicBlock *MBB) const {
  944. return MBB->getNumber();
  945. }
  946. };
  947. //===--------------------------------------------------------------------===//
  948. // GraphTraits specializations for machine basic block graphs (machine-CFGs)
  949. //===--------------------------------------------------------------------===//
  950. // Provide specializations of GraphTraits to be able to treat a
  951. // MachineFunction as a graph of MachineBasicBlocks.
  952. //
  953. template <> struct GraphTraits<MachineBasicBlock *> {
  954. using NodeRef = MachineBasicBlock *;
  955. using ChildIteratorType = MachineBasicBlock::succ_iterator;
  956. static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; }
  957. static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
  958. static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
  959. };
  960. template <> struct GraphTraits<const MachineBasicBlock *> {
  961. using NodeRef = const MachineBasicBlock *;
  962. using ChildIteratorType = MachineBasicBlock::const_succ_iterator;
  963. static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; }
  964. static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
  965. static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
  966. };
  967. // Provide specializations of GraphTraits to be able to treat a
  968. // MachineFunction as a graph of MachineBasicBlocks and to walk it
  969. // in inverse order. Inverse order for a function is considered
  970. // to be when traversing the predecessor edges of a MBB
  971. // instead of the successor edges.
  972. //
  973. template <> struct GraphTraits<Inverse<MachineBasicBlock*>> {
  974. using NodeRef = MachineBasicBlock *;
  975. using ChildIteratorType = MachineBasicBlock::pred_iterator;
  976. static NodeRef getEntryNode(Inverse<MachineBasicBlock *> G) {
  977. return G.Graph;
  978. }
  979. static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
  980. static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
  981. };
  982. template <> struct GraphTraits<Inverse<const MachineBasicBlock*>> {
  983. using NodeRef = const MachineBasicBlock *;
  984. using ChildIteratorType = MachineBasicBlock::const_pred_iterator;
  985. static NodeRef getEntryNode(Inverse<const MachineBasicBlock *> G) {
  986. return G.Graph;
  987. }
  988. static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
  989. static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
  990. };
  991. /// MachineInstrSpan provides an interface to get an iteration range
  992. /// containing the instruction it was initialized with, along with all
  993. /// those instructions inserted prior to or following that instruction
  994. /// at some point after the MachineInstrSpan is constructed.
  995. class MachineInstrSpan {
  996. MachineBasicBlock &MBB;
  997. MachineBasicBlock::iterator I, B, E;
  998. public:
  999. MachineInstrSpan(MachineBasicBlock::iterator I, MachineBasicBlock *BB)
  1000. : MBB(*BB), I(I), B(I == MBB.begin() ? MBB.end() : std::prev(I)),
  1001. E(std::next(I)) {
  1002. assert(I == BB->end() || I->getParent() == BB);
  1003. }
  1004. MachineBasicBlock::iterator begin() {
  1005. return B == MBB.end() ? MBB.begin() : std::next(B);
  1006. }
  1007. MachineBasicBlock::iterator end() { return E; }
  1008. bool empty() { return begin() == end(); }
  1009. MachineBasicBlock::iterator getInitial() { return I; }
  1010. };
  1011. /// Increment \p It until it points to a non-debug instruction or to \p End
  1012. /// and return the resulting iterator. This function should only be used
  1013. /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
  1014. /// const_instr_iterator} and the respective reverse iterators.
  1015. template <typename IterT>
  1016. inline IterT skipDebugInstructionsForward(IterT It, IterT End,
  1017. bool SkipPseudoOp = true) {
  1018. while (It != End &&
  1019. (It->isDebugInstr() || (SkipPseudoOp && It->isPseudoProbe())))
  1020. ++It;
  1021. return It;
  1022. }
  1023. /// Decrement \p It until it points to a non-debug instruction or to \p Begin
  1024. /// and return the resulting iterator. This function should only be used
  1025. /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
  1026. /// const_instr_iterator} and the respective reverse iterators.
  1027. template <class IterT>
  1028. inline IterT skipDebugInstructionsBackward(IterT It, IterT Begin,
  1029. bool SkipPseudoOp = true) {
  1030. while (It != Begin &&
  1031. (It->isDebugInstr() || (SkipPseudoOp && It->isPseudoProbe())))
  1032. --It;
  1033. return It;
  1034. }
  1035. /// Increment \p It, then continue incrementing it while it points to a debug
  1036. /// instruction. A replacement for std::next.
  1037. template <typename IterT>
  1038. inline IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp = true) {
  1039. return skipDebugInstructionsForward(std::next(It), End, SkipPseudoOp);
  1040. }
  1041. /// Decrement \p It, then continue decrementing it while it points to a debug
  1042. /// instruction. A replacement for std::prev.
  1043. template <typename IterT>
  1044. inline IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp = true) {
  1045. return skipDebugInstructionsBackward(std::prev(It), Begin, SkipPseudoOp);
  1046. }
  1047. /// Construct a range iterator which begins at \p It and moves forwards until
  1048. /// \p End is reached, skipping any debug instructions.
  1049. template <typename IterT>
  1050. inline auto instructionsWithoutDebug(IterT It, IterT End,
  1051. bool SkipPseudoOp = true) {
  1052. return make_filter_range(make_range(It, End), [=](const MachineInstr &MI) {
  1053. return !MI.isDebugInstr() && !(SkipPseudoOp && MI.isPseudoProbe());
  1054. });
  1055. }
  1056. } // end namespace llvm
  1057. #endif // LLVM_CODEGEN_MACHINEBASICBLOCK_H
  1058. #ifdef __GNUC__
  1059. #pragma GCC diagnostic pop
  1060. #endif