MachineFunction.h 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. //===- llvm/CodeGen/MachineFunction.h ---------------------------*- 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 native machine code for a function. This class contains a list of
  11. // MachineBasicBlock instances that make up the current compiled function.
  12. //
  13. // This class also contains pointers to various classes which hold
  14. // target-specific information about the generated code.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CODEGEN_MACHINEFUNCTION_H
  18. #define LLVM_CODEGEN_MACHINEFUNCTION_H
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/BitVector.h"
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/GraphTraits.h"
  23. #include "llvm/ADT/Optional.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/ADT/ilist.h"
  27. #include "llvm/ADT/iterator.h"
  28. #include "llvm/Analysis/EHPersonalities.h"
  29. #include "llvm/CodeGen/MachineBasicBlock.h"
  30. #include "llvm/CodeGen/MachineInstr.h"
  31. #include "llvm/CodeGen/MachineMemOperand.h"
  32. #include "llvm/IR/DebugLoc.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/IR/Metadata.h"
  35. #include "llvm/MC/MCDwarf.h"
  36. #include "llvm/MC/MCSymbol.h"
  37. #include "llvm/Support/Allocator.h"
  38. #include "llvm/Support/ArrayRecycler.h"
  39. #include "llvm/Support/AtomicOrdering.h"
  40. #include "llvm/Support/Compiler.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/Recycler.h"
  43. #include <cassert>
  44. #include <cstdint>
  45. #include <memory>
  46. #include <utility>
  47. #include <vector>
  48. namespace llvm {
  49. class BasicBlock;
  50. class BlockAddress;
  51. class DataLayout;
  52. class DIExpression;
  53. class DILocalVariable;
  54. class DILocation;
  55. class Function;
  56. class GlobalValue;
  57. class MachineConstantPool;
  58. class MachineFrameInfo;
  59. class MachineFunction;
  60. class MachineJumpTableInfo;
  61. class MachineModuleInfo;
  62. class MachineRegisterInfo;
  63. class MCContext;
  64. class MCInstrDesc;
  65. class Pass;
  66. class PseudoSourceValueManager;
  67. class raw_ostream;
  68. class SlotIndexes;
  69. class TargetMachine;
  70. class TargetRegisterClass;
  71. class TargetSubtargetInfo;
  72. struct WasmEHFuncInfo;
  73. struct WinEHFuncInfo;
  74. template <> struct ilist_alloc_traits<MachineBasicBlock> {
  75. void deleteNode(MachineBasicBlock *MBB);
  76. };
  77. template <> struct ilist_callback_traits<MachineBasicBlock> {
  78. void addNodeToList(MachineBasicBlock* MBB);
  79. void removeNodeFromList(MachineBasicBlock* MBB);
  80. template <class Iterator>
  81. void transferNodesFromList(ilist_callback_traits &OldList, Iterator, Iterator) {
  82. llvm_unreachable("Never transfer between lists");
  83. }
  84. };
  85. /// MachineFunctionInfo - This class can be derived from and used by targets to
  86. /// hold private target-specific information for each MachineFunction. Objects
  87. /// of type are accessed/created with MF::getInfo and destroyed when the
  88. /// MachineFunction is destroyed.
  89. struct MachineFunctionInfo {
  90. virtual ~MachineFunctionInfo();
  91. /// Factory function: default behavior is to call new using the
  92. /// supplied allocator.
  93. ///
  94. /// This function can be overridden in a derive class.
  95. template<typename Ty>
  96. static Ty *create(BumpPtrAllocator &Allocator, MachineFunction &MF) {
  97. return new (Allocator.Allocate<Ty>()) Ty(MF);
  98. }
  99. };
  100. /// Properties which a MachineFunction may have at a given point in time.
  101. /// Each of these has checking code in the MachineVerifier, and passes can
  102. /// require that a property be set.
  103. class MachineFunctionProperties {
  104. // Possible TODO: Allow targets to extend this (perhaps by allowing the
  105. // constructor to specify the size of the bit vector)
  106. // Possible TODO: Allow requiring the negative (e.g. VRegsAllocated could be
  107. // stated as the negative of "has vregs"
  108. public:
  109. // The properties are stated in "positive" form; i.e. a pass could require
  110. // that the property hold, but not that it does not hold.
  111. // Property descriptions:
  112. // IsSSA: True when the machine function is in SSA form and virtual registers
  113. // have a single def.
  114. // NoPHIs: The machine function does not contain any PHI instruction.
  115. // TracksLiveness: True when tracking register liveness accurately.
  116. // While this property is set, register liveness information in basic block
  117. // live-in lists and machine instruction operands (e.g. kill flags, implicit
  118. // defs) is accurate. This means it can be used to change the code in ways
  119. // that affect the values in registers, for example by the register
  120. // scavenger.
  121. // When this property is clear, liveness is no longer reliable.
  122. // NoVRegs: The machine function does not use any virtual registers.
  123. // Legalized: In GlobalISel: the MachineLegalizer ran and all pre-isel generic
  124. // instructions have been legalized; i.e., all instructions are now one of:
  125. // - generic and always legal (e.g., COPY)
  126. // - target-specific
  127. // - legal pre-isel generic instructions.
  128. // RegBankSelected: In GlobalISel: the RegBankSelect pass ran and all generic
  129. // virtual registers have been assigned to a register bank.
  130. // Selected: In GlobalISel: the InstructionSelect pass ran and all pre-isel
  131. // generic instructions have been eliminated; i.e., all instructions are now
  132. // target-specific or non-pre-isel generic instructions (e.g., COPY).
  133. // Since only pre-isel generic instructions can have generic virtual register
  134. // operands, this also means that all generic virtual registers have been
  135. // constrained to virtual registers (assigned to register classes) and that
  136. // all sizes attached to them have been eliminated.
  137. enum class Property : unsigned {
  138. IsSSA,
  139. NoPHIs,
  140. TracksLiveness,
  141. NoVRegs,
  142. FailedISel,
  143. Legalized,
  144. RegBankSelected,
  145. Selected,
  146. LastProperty = Selected,
  147. };
  148. bool hasProperty(Property P) const {
  149. return Properties[static_cast<unsigned>(P)];
  150. }
  151. MachineFunctionProperties &set(Property P) {
  152. Properties.set(static_cast<unsigned>(P));
  153. return *this;
  154. }
  155. MachineFunctionProperties &reset(Property P) {
  156. Properties.reset(static_cast<unsigned>(P));
  157. return *this;
  158. }
  159. /// Reset all the properties.
  160. MachineFunctionProperties &reset() {
  161. Properties.reset();
  162. return *this;
  163. }
  164. MachineFunctionProperties &set(const MachineFunctionProperties &MFP) {
  165. Properties |= MFP.Properties;
  166. return *this;
  167. }
  168. MachineFunctionProperties &reset(const MachineFunctionProperties &MFP) {
  169. Properties.reset(MFP.Properties);
  170. return *this;
  171. }
  172. // Returns true if all properties set in V (i.e. required by a pass) are set
  173. // in this.
  174. bool verifyRequiredProperties(const MachineFunctionProperties &V) const {
  175. return !V.Properties.test(Properties);
  176. }
  177. /// Print the MachineFunctionProperties in human-readable form.
  178. void print(raw_ostream &OS) const;
  179. private:
  180. BitVector Properties =
  181. BitVector(static_cast<unsigned>(Property::LastProperty)+1);
  182. };
  183. struct SEHHandler {
  184. /// Filter or finally function. Null indicates a catch-all.
  185. const Function *FilterOrFinally;
  186. /// Address of block to recover at. Null for a finally handler.
  187. const BlockAddress *RecoverBA;
  188. };
  189. /// This structure is used to retain landing pad info for the current function.
  190. struct LandingPadInfo {
  191. MachineBasicBlock *LandingPadBlock; // Landing pad block.
  192. SmallVector<MCSymbol *, 1> BeginLabels; // Labels prior to invoke.
  193. SmallVector<MCSymbol *, 1> EndLabels; // Labels after invoke.
  194. SmallVector<SEHHandler, 1> SEHHandlers; // SEH handlers active at this lpad.
  195. MCSymbol *LandingPadLabel = nullptr; // Label at beginning of landing pad.
  196. std::vector<int> TypeIds; // List of type ids (filters negative).
  197. explicit LandingPadInfo(MachineBasicBlock *MBB)
  198. : LandingPadBlock(MBB) {}
  199. };
  200. class MachineFunction {
  201. const Function &F;
  202. const TargetMachine &Target;
  203. const TargetSubtargetInfo *STI;
  204. MCContext &Ctx;
  205. MachineModuleInfo &MMI;
  206. // RegInfo - Information about each register in use in the function.
  207. MachineRegisterInfo *RegInfo;
  208. // Used to keep track of target-specific per-machine function information for
  209. // the target implementation.
  210. MachineFunctionInfo *MFInfo;
  211. // Keep track of objects allocated on the stack.
  212. MachineFrameInfo *FrameInfo;
  213. // Keep track of constants which are spilled to memory
  214. MachineConstantPool *ConstantPool;
  215. // Keep track of jump tables for switch instructions
  216. MachineJumpTableInfo *JumpTableInfo;
  217. // Keeps track of Wasm exception handling related data. This will be null for
  218. // functions that aren't using a wasm EH personality.
  219. WasmEHFuncInfo *WasmEHInfo = nullptr;
  220. // Keeps track of Windows exception handling related data. This will be null
  221. // for functions that aren't using a funclet-based EH personality.
  222. WinEHFuncInfo *WinEHInfo = nullptr;
  223. // Function-level unique numbering for MachineBasicBlocks. When a
  224. // MachineBasicBlock is inserted into a MachineFunction is it automatically
  225. // numbered and this vector keeps track of the mapping from ID's to MBB's.
  226. std::vector<MachineBasicBlock*> MBBNumbering;
  227. // Pool-allocate MachineFunction-lifetime and IR objects.
  228. BumpPtrAllocator Allocator;
  229. // Allocation management for instructions in function.
  230. Recycler<MachineInstr> InstructionRecycler;
  231. // Allocation management for operand arrays on instructions.
  232. ArrayRecycler<MachineOperand> OperandRecycler;
  233. // Allocation management for basic blocks in function.
  234. Recycler<MachineBasicBlock> BasicBlockRecycler;
  235. // List of machine basic blocks in function
  236. using BasicBlockListType = ilist<MachineBasicBlock>;
  237. BasicBlockListType BasicBlocks;
  238. /// FunctionNumber - This provides a unique ID for each function emitted in
  239. /// this translation unit.
  240. ///
  241. unsigned FunctionNumber;
  242. /// Alignment - The alignment of the function.
  243. unsigned Alignment;
  244. /// ExposesReturnsTwice - True if the function calls setjmp or related
  245. /// functions with attribute "returns twice", but doesn't have
  246. /// the attribute itself.
  247. /// This is used to limit optimizations which cannot reason
  248. /// about the control flow of such functions.
  249. bool ExposesReturnsTwice = false;
  250. /// True if the function includes any inline assembly.
  251. bool HasInlineAsm = false;
  252. /// True if any WinCFI instruction have been emitted in this function.
  253. Optional<bool> HasWinCFI;
  254. /// Current high-level properties of the IR of the function (e.g. is in SSA
  255. /// form or whether registers have been allocated)
  256. MachineFunctionProperties Properties;
  257. // Allocation management for pseudo source values.
  258. std::unique_ptr<PseudoSourceValueManager> PSVManager;
  259. /// List of moves done by a function's prolog. Used to construct frame maps
  260. /// by debug and exception handling consumers.
  261. std::vector<MCCFIInstruction> FrameInstructions;
  262. /// \name Exception Handling
  263. /// \{
  264. /// List of LandingPadInfo describing the landing pad information.
  265. std::vector<LandingPadInfo> LandingPads;
  266. /// Map a landing pad's EH symbol to the call site indexes.
  267. DenseMap<MCSymbol*, SmallVector<unsigned, 4>> LPadToCallSiteMap;
  268. /// Map of invoke call site index values to associated begin EH_LABEL.
  269. DenseMap<MCSymbol*, unsigned> CallSiteMap;
  270. /// CodeView label annotations.
  271. std::vector<std::pair<MCSymbol *, MDNode *>> CodeViewAnnotations;
  272. bool CallsEHReturn = false;
  273. bool CallsUnwindInit = false;
  274. bool HasEHScopes = false;
  275. bool HasEHFunclets = false;
  276. /// List of C++ TypeInfo used.
  277. std::vector<const GlobalValue *> TypeInfos;
  278. /// List of typeids encoding filters used.
  279. std::vector<unsigned> FilterIds;
  280. /// List of the indices in FilterIds corresponding to filter terminators.
  281. std::vector<unsigned> FilterEnds;
  282. EHPersonality PersonalityTypeCache = EHPersonality::Unknown;
  283. /// \}
  284. /// Clear all the members of this MachineFunction, but the ones used
  285. /// to initialize again the MachineFunction.
  286. /// More specifically, this deallocates all the dynamically allocated
  287. /// objects and get rid of all the XXXInfo data structure, but keep
  288. /// unchanged the references to Fn, Target, MMI, and FunctionNumber.
  289. void clear();
  290. /// Allocate and initialize the different members.
  291. /// In particular, the XXXInfo data structure.
  292. /// \pre Fn, Target, MMI, and FunctionNumber are properly set.
  293. void init();
  294. public:
  295. struct VariableDbgInfo {
  296. const DILocalVariable *Var;
  297. const DIExpression *Expr;
  298. // The Slot can be negative for fixed stack objects.
  299. int Slot;
  300. const DILocation *Loc;
  301. VariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
  302. int Slot, const DILocation *Loc)
  303. : Var(Var), Expr(Expr), Slot(Slot), Loc(Loc) {}
  304. };
  305. using VariableDbgInfoMapTy = SmallVector<VariableDbgInfo, 4>;
  306. VariableDbgInfoMapTy VariableDbgInfos;
  307. MachineFunction(const Function &F, const TargetMachine &TM,
  308. const TargetSubtargetInfo &STI, unsigned FunctionNum,
  309. MachineModuleInfo &MMI);
  310. MachineFunction(const MachineFunction &) = delete;
  311. MachineFunction &operator=(const MachineFunction &) = delete;
  312. ~MachineFunction();
  313. /// Reset the instance as if it was just created.
  314. void reset() {
  315. clear();
  316. init();
  317. }
  318. MachineModuleInfo &getMMI() const { return MMI; }
  319. MCContext &getContext() const { return Ctx; }
  320. PseudoSourceValueManager &getPSVManager() const { return *PSVManager; }
  321. /// Return the DataLayout attached to the Module associated to this MF.
  322. const DataLayout &getDataLayout() const;
  323. /// Return the LLVM function that this machine code represents
  324. const Function &getFunction() const { return F; }
  325. /// getName - Return the name of the corresponding LLVM function.
  326. StringRef getName() const;
  327. /// getFunctionNumber - Return a unique ID for the current function.
  328. unsigned getFunctionNumber() const { return FunctionNumber; }
  329. /// getTarget - Return the target machine this machine code is compiled with
  330. const TargetMachine &getTarget() const { return Target; }
  331. /// getSubtarget - Return the subtarget for which this machine code is being
  332. /// compiled.
  333. const TargetSubtargetInfo &getSubtarget() const { return *STI; }
  334. void setSubtarget(const TargetSubtargetInfo *ST) { STI = ST; }
  335. /// getSubtarget - This method returns a pointer to the specified type of
  336. /// TargetSubtargetInfo. In debug builds, it verifies that the object being
  337. /// returned is of the correct type.
  338. template<typename STC> const STC &getSubtarget() const {
  339. return *static_cast<const STC *>(STI);
  340. }
  341. /// getRegInfo - Return information about the registers currently in use.
  342. MachineRegisterInfo &getRegInfo() { return *RegInfo; }
  343. const MachineRegisterInfo &getRegInfo() const { return *RegInfo; }
  344. /// getFrameInfo - Return the frame info object for the current function.
  345. /// This object contains information about objects allocated on the stack
  346. /// frame of the current function in an abstract way.
  347. MachineFrameInfo &getFrameInfo() { return *FrameInfo; }
  348. const MachineFrameInfo &getFrameInfo() const { return *FrameInfo; }
  349. /// getJumpTableInfo - Return the jump table info object for the current
  350. /// function. This object contains information about jump tables in the
  351. /// current function. If the current function has no jump tables, this will
  352. /// return null.
  353. const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; }
  354. MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; }
  355. /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
  356. /// does already exist, allocate one.
  357. MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind);
  358. /// getConstantPool - Return the constant pool object for the current
  359. /// function.
  360. MachineConstantPool *getConstantPool() { return ConstantPool; }
  361. const MachineConstantPool *getConstantPool() const { return ConstantPool; }
  362. /// getWasmEHFuncInfo - Return information about how the current function uses
  363. /// Wasm exception handling. Returns null for functions that don't use wasm
  364. /// exception handling.
  365. const WasmEHFuncInfo *getWasmEHFuncInfo() const { return WasmEHInfo; }
  366. WasmEHFuncInfo *getWasmEHFuncInfo() { return WasmEHInfo; }
  367. /// getWinEHFuncInfo - Return information about how the current function uses
  368. /// Windows exception handling. Returns null for functions that don't use
  369. /// funclets for exception handling.
  370. const WinEHFuncInfo *getWinEHFuncInfo() const { return WinEHInfo; }
  371. WinEHFuncInfo *getWinEHFuncInfo() { return WinEHInfo; }
  372. /// getAlignment - Return the alignment (log2, not bytes) of the function.
  373. unsigned getAlignment() const { return Alignment; }
  374. /// setAlignment - Set the alignment (log2, not bytes) of the function.
  375. void setAlignment(unsigned A) { Alignment = A; }
  376. /// ensureAlignment - Make sure the function is at least 1 << A bytes aligned.
  377. void ensureAlignment(unsigned A) {
  378. if (Alignment < A) Alignment = A;
  379. }
  380. /// exposesReturnsTwice - Returns true if the function calls setjmp or
  381. /// any other similar functions with attribute "returns twice" without
  382. /// having the attribute itself.
  383. bool exposesReturnsTwice() const {
  384. return ExposesReturnsTwice;
  385. }
  386. /// setCallsSetJmp - Set a flag that indicates if there's a call to
  387. /// a "returns twice" function.
  388. void setExposesReturnsTwice(bool B) {
  389. ExposesReturnsTwice = B;
  390. }
  391. /// Returns true if the function contains any inline assembly.
  392. bool hasInlineAsm() const {
  393. return HasInlineAsm;
  394. }
  395. /// Set a flag that indicates that the function contains inline assembly.
  396. void setHasInlineAsm(bool B) {
  397. HasInlineAsm = B;
  398. }
  399. bool hasWinCFI() const {
  400. assert(HasWinCFI.hasValue() && "HasWinCFI not set yet!");
  401. return *HasWinCFI;
  402. }
  403. void setHasWinCFI(bool v) { HasWinCFI = v; }
  404. /// Get the function properties
  405. const MachineFunctionProperties &getProperties() const { return Properties; }
  406. MachineFunctionProperties &getProperties() { return Properties; }
  407. /// getInfo - Keep track of various per-function pieces of information for
  408. /// backends that would like to do so.
  409. ///
  410. template<typename Ty>
  411. Ty *getInfo() {
  412. if (!MFInfo)
  413. MFInfo = Ty::template create<Ty>(Allocator, *this);
  414. return static_cast<Ty*>(MFInfo);
  415. }
  416. template<typename Ty>
  417. const Ty *getInfo() const {
  418. return const_cast<MachineFunction*>(this)->getInfo<Ty>();
  419. }
  420. /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they
  421. /// are inserted into the machine function. The block number for a machine
  422. /// basic block can be found by using the MBB::getNumber method, this method
  423. /// provides the inverse mapping.
  424. MachineBasicBlock *getBlockNumbered(unsigned N) const {
  425. assert(N < MBBNumbering.size() && "Illegal block number");
  426. assert(MBBNumbering[N] && "Block was removed from the machine function!");
  427. return MBBNumbering[N];
  428. }
  429. /// Should we be emitting segmented stack stuff for the function
  430. bool shouldSplitStack() const;
  431. /// getNumBlockIDs - Return the number of MBB ID's allocated.
  432. unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); }
  433. /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
  434. /// recomputes them. This guarantees that the MBB numbers are sequential,
  435. /// dense, and match the ordering of the blocks within the function. If a
  436. /// specific MachineBasicBlock is specified, only that block and those after
  437. /// it are renumbered.
  438. void RenumberBlocks(MachineBasicBlock *MBBFrom = nullptr);
  439. /// print - Print out the MachineFunction in a format suitable for debugging
  440. /// to the specified stream.
  441. void print(raw_ostream &OS, const SlotIndexes* = nullptr) const;
  442. /// viewCFG - This function is meant for use from the debugger. You can just
  443. /// say 'call F->viewCFG()' and a ghostview window should pop up from the
  444. /// program, displaying the CFG of the current function with the code for each
  445. /// basic block inside. This depends on there being a 'dot' and 'gv' program
  446. /// in your path.
  447. void viewCFG() const;
  448. /// viewCFGOnly - This function is meant for use from the debugger. It works
  449. /// just like viewCFG, but it does not include the contents of basic blocks
  450. /// into the nodes, just the label. If you are only interested in the CFG
  451. /// this can make the graph smaller.
  452. ///
  453. void viewCFGOnly() const;
  454. /// dump - Print the current MachineFunction to cerr, useful for debugger use.
  455. void dump() const;
  456. /// Run the current MachineFunction through the machine code verifier, useful
  457. /// for debugger use.
  458. /// \returns true if no problems were found.
  459. bool verify(Pass *p = nullptr, const char *Banner = nullptr,
  460. bool AbortOnError = true) const;
  461. // Provide accessors for the MachineBasicBlock list...
  462. using iterator = BasicBlockListType::iterator;
  463. using const_iterator = BasicBlockListType::const_iterator;
  464. using const_reverse_iterator = BasicBlockListType::const_reverse_iterator;
  465. using reverse_iterator = BasicBlockListType::reverse_iterator;
  466. /// Support for MachineBasicBlock::getNextNode().
  467. static BasicBlockListType MachineFunction::*
  468. getSublistAccess(MachineBasicBlock *) {
  469. return &MachineFunction::BasicBlocks;
  470. }
  471. /// addLiveIn - Add the specified physical register as a live-in value and
  472. /// create a corresponding virtual register for it.
  473. unsigned addLiveIn(unsigned PReg, const TargetRegisterClass *RC);
  474. //===--------------------------------------------------------------------===//
  475. // BasicBlock accessor functions.
  476. //
  477. iterator begin() { return BasicBlocks.begin(); }
  478. const_iterator begin() const { return BasicBlocks.begin(); }
  479. iterator end () { return BasicBlocks.end(); }
  480. const_iterator end () const { return BasicBlocks.end(); }
  481. reverse_iterator rbegin() { return BasicBlocks.rbegin(); }
  482. const_reverse_iterator rbegin() const { return BasicBlocks.rbegin(); }
  483. reverse_iterator rend () { return BasicBlocks.rend(); }
  484. const_reverse_iterator rend () const { return BasicBlocks.rend(); }
  485. unsigned size() const { return (unsigned)BasicBlocks.size();}
  486. bool empty() const { return BasicBlocks.empty(); }
  487. const MachineBasicBlock &front() const { return BasicBlocks.front(); }
  488. MachineBasicBlock &front() { return BasicBlocks.front(); }
  489. const MachineBasicBlock & back() const { return BasicBlocks.back(); }
  490. MachineBasicBlock & back() { return BasicBlocks.back(); }
  491. void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); }
  492. void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); }
  493. void insert(iterator MBBI, MachineBasicBlock *MBB) {
  494. BasicBlocks.insert(MBBI, MBB);
  495. }
  496. void splice(iterator InsertPt, iterator MBBI) {
  497. BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
  498. }
  499. void splice(iterator InsertPt, MachineBasicBlock *MBB) {
  500. BasicBlocks.splice(InsertPt, BasicBlocks, MBB);
  501. }
  502. void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
  503. BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
  504. }
  505. void remove(iterator MBBI) { BasicBlocks.remove(MBBI); }
  506. void remove(MachineBasicBlock *MBBI) { BasicBlocks.remove(MBBI); }
  507. void erase(iterator MBBI) { BasicBlocks.erase(MBBI); }
  508. void erase(MachineBasicBlock *MBBI) { BasicBlocks.erase(MBBI); }
  509. template <typename Comp>
  510. void sort(Comp comp) {
  511. BasicBlocks.sort(comp);
  512. }
  513. //===--------------------------------------------------------------------===//
  514. // Internal functions used to automatically number MachineBasicBlocks
  515. /// Adds the MBB to the internal numbering. Returns the unique number
  516. /// assigned to the MBB.
  517. unsigned addToMBBNumbering(MachineBasicBlock *MBB) {
  518. MBBNumbering.push_back(MBB);
  519. return (unsigned)MBBNumbering.size()-1;
  520. }
  521. /// removeFromMBBNumbering - Remove the specific machine basic block from our
  522. /// tracker, this is only really to be used by the MachineBasicBlock
  523. /// implementation.
  524. void removeFromMBBNumbering(unsigned N) {
  525. assert(N < MBBNumbering.size() && "Illegal basic block #");
  526. MBBNumbering[N] = nullptr;
  527. }
  528. /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
  529. /// of `new MachineInstr'.
  530. MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID, const DebugLoc &DL,
  531. bool NoImp = false);
  532. /// Create a new MachineInstr which is a copy of \p Orig, identical in all
  533. /// ways except the instruction has no parent, prev, or next. Bundling flags
  534. /// are reset.
  535. ///
  536. /// Note: Clones a single instruction, not whole instruction bundles.
  537. /// Does not perform target specific adjustments; consider using
  538. /// TargetInstrInfo::duplicate() instead.
  539. MachineInstr *CloneMachineInstr(const MachineInstr *Orig);
  540. /// Clones instruction or the whole instruction bundle \p Orig and insert
  541. /// into \p MBB before \p InsertBefore.
  542. ///
  543. /// Note: Does not perform target specific adjustments; consider using
  544. /// TargetInstrInfo::duplicate() intead.
  545. MachineInstr &CloneMachineInstrBundle(MachineBasicBlock &MBB,
  546. MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig);
  547. /// DeleteMachineInstr - Delete the given MachineInstr.
  548. void DeleteMachineInstr(MachineInstr *MI);
  549. /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
  550. /// instead of `new MachineBasicBlock'.
  551. MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = nullptr);
  552. /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
  553. void DeleteMachineBasicBlock(MachineBasicBlock *MBB);
  554. /// getMachineMemOperand - Allocate a new MachineMemOperand.
  555. /// MachineMemOperands are owned by the MachineFunction and need not be
  556. /// explicitly deallocated.
  557. MachineMemOperand *getMachineMemOperand(
  558. MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
  559. unsigned base_alignment, const AAMDNodes &AAInfo = AAMDNodes(),
  560. const MDNode *Ranges = nullptr,
  561. SyncScope::ID SSID = SyncScope::System,
  562. AtomicOrdering Ordering = AtomicOrdering::NotAtomic,
  563. AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic);
  564. /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
  565. /// an existing one, adjusting by an offset and using the given size.
  566. /// MachineMemOperands are owned by the MachineFunction and need not be
  567. /// explicitly deallocated.
  568. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  569. int64_t Offset, uint64_t Size);
  570. /// Allocate a new MachineMemOperand by copying an existing one,
  571. /// replacing only AliasAnalysis information. MachineMemOperands are owned
  572. /// by the MachineFunction and need not be explicitly deallocated.
  573. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  574. const AAMDNodes &AAInfo);
  575. using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
  576. /// Allocate an array of MachineOperands. This is only intended for use by
  577. /// internal MachineInstr functions.
  578. MachineOperand *allocateOperandArray(OperandCapacity Cap) {
  579. return OperandRecycler.allocate(Cap, Allocator);
  580. }
  581. /// Dellocate an array of MachineOperands and recycle the memory. This is
  582. /// only intended for use by internal MachineInstr functions.
  583. /// Cap must be the same capacity that was used to allocate the array.
  584. void deallocateOperandArray(OperandCapacity Cap, MachineOperand *Array) {
  585. OperandRecycler.deallocate(Cap, Array);
  586. }
  587. /// Allocate and initialize a register mask with @p NumRegister bits.
  588. uint32_t *allocateRegisterMask(unsigned NumRegister) {
  589. unsigned Size = (NumRegister + 31) / 32;
  590. uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
  591. for (unsigned i = 0; i != Size; ++i)
  592. Mask[i] = 0;
  593. return Mask;
  594. }
  595. /// allocateMemRefsArray - Allocate an array to hold MachineMemOperand
  596. /// pointers. This array is owned by the MachineFunction.
  597. MachineInstr::mmo_iterator allocateMemRefsArray(unsigned long Num);
  598. /// extractLoadMemRefs - Allocate an array and populate it with just the
  599. /// load information from the given MachineMemOperand sequence.
  600. std::pair<MachineInstr::mmo_iterator,
  601. MachineInstr::mmo_iterator>
  602. extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
  603. MachineInstr::mmo_iterator End);
  604. /// extractStoreMemRefs - Allocate an array and populate it with just the
  605. /// store information from the given MachineMemOperand sequence.
  606. std::pair<MachineInstr::mmo_iterator,
  607. MachineInstr::mmo_iterator>
  608. extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
  609. MachineInstr::mmo_iterator End);
  610. /// Allocate a string and populate it with the given external symbol name.
  611. const char *createExternalSymbolName(StringRef Name);
  612. //===--------------------------------------------------------------------===//
  613. // Label Manipulation.
  614. /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
  615. /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
  616. /// normal 'L' label is returned.
  617. MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx,
  618. bool isLinkerPrivate = false) const;
  619. /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
  620. /// base.
  621. MCSymbol *getPICBaseSymbol() const;
  622. /// Returns a reference to a list of cfi instructions in the function's
  623. /// prologue. Used to construct frame maps for debug and exception handling
  624. /// comsumers.
  625. const std::vector<MCCFIInstruction> &getFrameInstructions() const {
  626. return FrameInstructions;
  627. }
  628. LLVM_NODISCARD unsigned addFrameInst(const MCCFIInstruction &Inst) {
  629. FrameInstructions.push_back(Inst);
  630. return FrameInstructions.size() - 1;
  631. }
  632. /// \name Exception Handling
  633. /// \{
  634. bool callsEHReturn() const { return CallsEHReturn; }
  635. void setCallsEHReturn(bool b) { CallsEHReturn = b; }
  636. bool callsUnwindInit() const { return CallsUnwindInit; }
  637. void setCallsUnwindInit(bool b) { CallsUnwindInit = b; }
  638. bool hasEHScopes() const { return HasEHScopes; }
  639. void setHasEHScopes(bool V) { HasEHScopes = V; }
  640. bool hasEHFunclets() const { return HasEHFunclets; }
  641. void setHasEHFunclets(bool V) { HasEHFunclets = V; }
  642. /// Find or create an LandingPadInfo for the specified MachineBasicBlock.
  643. LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad);
  644. /// Remap landing pad labels and remove any deleted landing pads.
  645. void tidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap = nullptr);
  646. /// Return a reference to the landing pad info for the current function.
  647. const std::vector<LandingPadInfo> &getLandingPads() const {
  648. return LandingPads;
  649. }
  650. /// Provide the begin and end labels of an invoke style call and associate it
  651. /// with a try landing pad block.
  652. void addInvoke(MachineBasicBlock *LandingPad,
  653. MCSymbol *BeginLabel, MCSymbol *EndLabel);
  654. /// Add a new panding pad. Returns the label ID for the landing pad entry.
  655. MCSymbol *addLandingPad(MachineBasicBlock *LandingPad);
  656. /// Provide the catch typeinfo for a landing pad.
  657. void addCatchTypeInfo(MachineBasicBlock *LandingPad,
  658. ArrayRef<const GlobalValue *> TyInfo);
  659. /// Provide the filter typeinfo for a landing pad.
  660. void addFilterTypeInfo(MachineBasicBlock *LandingPad,
  661. ArrayRef<const GlobalValue *> TyInfo);
  662. /// Add a cleanup action for a landing pad.
  663. void addCleanup(MachineBasicBlock *LandingPad);
  664. void addSEHCatchHandler(MachineBasicBlock *LandingPad, const Function *Filter,
  665. const BlockAddress *RecoverLabel);
  666. void addSEHCleanupHandler(MachineBasicBlock *LandingPad,
  667. const Function *Cleanup);
  668. /// Return the type id for the specified typeinfo. This is function wide.
  669. unsigned getTypeIDFor(const GlobalValue *TI);
  670. /// Return the id of the filter encoded by TyIds. This is function wide.
  671. int getFilterIDFor(std::vector<unsigned> &TyIds);
  672. /// Map the landing pad's EH symbol to the call site indexes.
  673. void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef<unsigned> Sites);
  674. /// Get the call site indexes for a landing pad EH symbol.
  675. SmallVectorImpl<unsigned> &getCallSiteLandingPad(MCSymbol *Sym) {
  676. assert(hasCallSiteLandingPad(Sym) &&
  677. "missing call site number for landing pad!");
  678. return LPadToCallSiteMap[Sym];
  679. }
  680. /// Return true if the landing pad Eh symbol has an associated call site.
  681. bool hasCallSiteLandingPad(MCSymbol *Sym) {
  682. return !LPadToCallSiteMap[Sym].empty();
  683. }
  684. /// Map the begin label for a call site.
  685. void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site) {
  686. CallSiteMap[BeginLabel] = Site;
  687. }
  688. /// Get the call site number for a begin label.
  689. unsigned getCallSiteBeginLabel(MCSymbol *BeginLabel) const {
  690. assert(hasCallSiteBeginLabel(BeginLabel) &&
  691. "Missing call site number for EH_LABEL!");
  692. return CallSiteMap.lookup(BeginLabel);
  693. }
  694. /// Return true if the begin label has a call site number associated with it.
  695. bool hasCallSiteBeginLabel(MCSymbol *BeginLabel) const {
  696. return CallSiteMap.count(BeginLabel);
  697. }
  698. /// Record annotations associated with a particular label.
  699. void addCodeViewAnnotation(MCSymbol *Label, MDNode *MD) {
  700. CodeViewAnnotations.push_back({Label, MD});
  701. }
  702. ArrayRef<std::pair<MCSymbol *, MDNode *>> getCodeViewAnnotations() const {
  703. return CodeViewAnnotations;
  704. }
  705. /// Return a reference to the C++ typeinfo for the current function.
  706. const std::vector<const GlobalValue *> &getTypeInfos() const {
  707. return TypeInfos;
  708. }
  709. /// Return a reference to the typeids encoding filters used in the current
  710. /// function.
  711. const std::vector<unsigned> &getFilterIds() const {
  712. return FilterIds;
  713. }
  714. /// \}
  715. /// Collect information used to emit debugging information of a variable.
  716. void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
  717. int Slot, const DILocation *Loc) {
  718. VariableDbgInfos.emplace_back(Var, Expr, Slot, Loc);
  719. }
  720. VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfos; }
  721. const VariableDbgInfoMapTy &getVariableDbgInfo() const {
  722. return VariableDbgInfos;
  723. }
  724. };
  725. /// \name Exception Handling
  726. /// \{
  727. /// Extract the exception handling information from the landingpad instruction
  728. /// and add them to the specified machine module info.
  729. void addLandingPadInfo(const LandingPadInst &I, MachineBasicBlock &MBB);
  730. /// \}
  731. //===--------------------------------------------------------------------===//
  732. // GraphTraits specializations for function basic block graphs (CFGs)
  733. //===--------------------------------------------------------------------===//
  734. // Provide specializations of GraphTraits to be able to treat a
  735. // machine function as a graph of machine basic blocks... these are
  736. // the same as the machine basic block iterators, except that the root
  737. // node is implicitly the first node of the function.
  738. //
  739. template <> struct GraphTraits<MachineFunction*> :
  740. public GraphTraits<MachineBasicBlock*> {
  741. static NodeRef getEntryNode(MachineFunction *F) { return &F->front(); }
  742. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  743. using nodes_iterator = pointer_iterator<MachineFunction::iterator>;
  744. static nodes_iterator nodes_begin(MachineFunction *F) {
  745. return nodes_iterator(F->begin());
  746. }
  747. static nodes_iterator nodes_end(MachineFunction *F) {
  748. return nodes_iterator(F->end());
  749. }
  750. static unsigned size (MachineFunction *F) { return F->size(); }
  751. };
  752. template <> struct GraphTraits<const MachineFunction*> :
  753. public GraphTraits<const MachineBasicBlock*> {
  754. static NodeRef getEntryNode(const MachineFunction *F) { return &F->front(); }
  755. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  756. using nodes_iterator = pointer_iterator<MachineFunction::const_iterator>;
  757. static nodes_iterator nodes_begin(const MachineFunction *F) {
  758. return nodes_iterator(F->begin());
  759. }
  760. static nodes_iterator nodes_end (const MachineFunction *F) {
  761. return nodes_iterator(F->end());
  762. }
  763. static unsigned size (const MachineFunction *F) {
  764. return F->size();
  765. }
  766. };
  767. // Provide specializations of GraphTraits to be able to treat a function as a
  768. // graph of basic blocks... and to walk it in inverse order. Inverse order for
  769. // a function is considered to be when traversing the predecessor edges of a BB
  770. // instead of the successor edges.
  771. //
  772. template <> struct GraphTraits<Inverse<MachineFunction*>> :
  773. public GraphTraits<Inverse<MachineBasicBlock*>> {
  774. static NodeRef getEntryNode(Inverse<MachineFunction *> G) {
  775. return &G.Graph->front();
  776. }
  777. };
  778. template <> struct GraphTraits<Inverse<const MachineFunction*>> :
  779. public GraphTraits<Inverse<const MachineBasicBlock*>> {
  780. static NodeRef getEntryNode(Inverse<const MachineFunction *> G) {
  781. return &G.Graph->front();
  782. }
  783. };
  784. } // end namespace llvm
  785. #endif // LLVM_CODEGEN_MACHINEFUNCTION_H