MachineFunction.h 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/CodeGen/MachineFunction.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 native machine code for a function. This class contains a list of
  15. // MachineBasicBlock instances that make up the current compiled function.
  16. //
  17. // This class also contains pointers to various classes which hold
  18. // target-specific information about the generated code.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #ifndef LLVM_CODEGEN_MACHINEFUNCTION_H
  22. #define LLVM_CODEGEN_MACHINEFUNCTION_H
  23. #include "llvm/ADT/ArrayRef.h"
  24. #include "llvm/ADT/BitVector.h"
  25. #include "llvm/ADT/DenseMap.h"
  26. #include "llvm/ADT/GraphTraits.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/ilist.h"
  29. #include "llvm/ADT/iterator.h"
  30. #include "llvm/Analysis/EHPersonalities.h"
  31. #include "llvm/CodeGen/MachineBasicBlock.h"
  32. #include "llvm/CodeGen/MachineInstr.h"
  33. #include "llvm/CodeGen/MachineMemOperand.h"
  34. #include "llvm/Support/Allocator.h"
  35. #include "llvm/Support/ArrayRecycler.h"
  36. #include "llvm/Support/AtomicOrdering.h"
  37. #include "llvm/Support/Compiler.h"
  38. #include "llvm/Support/Recycler.h"
  39. #include "llvm/Target/TargetOptions.h"
  40. #include <cassert>
  41. #include <cstdint>
  42. #include <memory>
  43. #include <utility>
  44. #include <vector>
  45. namespace llvm {
  46. class BasicBlock;
  47. class BlockAddress;
  48. class DataLayout;
  49. class DebugLoc;
  50. struct DenormalMode;
  51. class DIExpression;
  52. class DILocalVariable;
  53. class DILocation;
  54. class Function;
  55. class GISelChangeObserver;
  56. class GlobalValue;
  57. class LLVMTargetMachine;
  58. class MachineConstantPool;
  59. class MachineFrameInfo;
  60. class MachineFunction;
  61. class MachineJumpTableInfo;
  62. class MachineModuleInfo;
  63. class MachineRegisterInfo;
  64. class MCContext;
  65. class MCInstrDesc;
  66. class MCSymbol;
  67. class MCSection;
  68. class Pass;
  69. class PseudoSourceValueManager;
  70. class raw_ostream;
  71. class SlotIndexes;
  72. class StringRef;
  73. class TargetRegisterClass;
  74. class TargetSubtargetInfo;
  75. struct WasmEHFuncInfo;
  76. struct WinEHFuncInfo;
  77. template <> struct ilist_alloc_traits<MachineBasicBlock> {
  78. void deleteNode(MachineBasicBlock *MBB);
  79. };
  80. template <> struct ilist_callback_traits<MachineBasicBlock> {
  81. void addNodeToList(MachineBasicBlock* N);
  82. void removeNodeFromList(MachineBasicBlock* N);
  83. template <class Iterator>
  84. void transferNodesFromList(ilist_callback_traits &OldList, Iterator, Iterator) {
  85. assert(this == &OldList && "never transfer MBBs between functions");
  86. }
  87. };
  88. /// MachineFunctionInfo - This class can be derived from and used by targets to
  89. /// hold private target-specific information for each MachineFunction. Objects
  90. /// of type are accessed/created with MF::getInfo and destroyed when the
  91. /// MachineFunction is destroyed.
  92. struct MachineFunctionInfo {
  93. virtual ~MachineFunctionInfo();
  94. /// Factory function: default behavior is to call new using the
  95. /// supplied allocator.
  96. ///
  97. /// This function can be overridden in a derive class.
  98. template <typename FuncInfoTy, typename SubtargetTy = TargetSubtargetInfo>
  99. static FuncInfoTy *create(BumpPtrAllocator &Allocator, const Function &F,
  100. const SubtargetTy *STI) {
  101. return new (Allocator.Allocate<FuncInfoTy>()) FuncInfoTy(F, STI);
  102. }
  103. template <typename Ty>
  104. static Ty *create(BumpPtrAllocator &Allocator, const Ty &MFI) {
  105. return new (Allocator.Allocate<Ty>()) Ty(MFI);
  106. }
  107. /// Make a functionally equivalent copy of this MachineFunctionInfo in \p MF.
  108. /// This requires remapping MachineBasicBlock references from the original
  109. /// parent to values in the new function. Targets may assume that virtual
  110. /// register and frame index values are preserved in the new function.
  111. virtual MachineFunctionInfo *
  112. clone(BumpPtrAllocator &Allocator, MachineFunction &DestMF,
  113. const DenseMap<MachineBasicBlock *, MachineBasicBlock *> &Src2DstMBB)
  114. const {
  115. return nullptr;
  116. }
  117. };
  118. /// Properties which a MachineFunction may have at a given point in time.
  119. /// Each of these has checking code in the MachineVerifier, and passes can
  120. /// require that a property be set.
  121. class MachineFunctionProperties {
  122. // Possible TODO: Allow targets to extend this (perhaps by allowing the
  123. // constructor to specify the size of the bit vector)
  124. // Possible TODO: Allow requiring the negative (e.g. VRegsAllocated could be
  125. // stated as the negative of "has vregs"
  126. public:
  127. // The properties are stated in "positive" form; i.e. a pass could require
  128. // that the property hold, but not that it does not hold.
  129. // Property descriptions:
  130. // IsSSA: True when the machine function is in SSA form and virtual registers
  131. // have a single def.
  132. // NoPHIs: The machine function does not contain any PHI instruction.
  133. // TracksLiveness: True when tracking register liveness accurately.
  134. // While this property is set, register liveness information in basic block
  135. // live-in lists and machine instruction operands (e.g. implicit defs) is
  136. // accurate, kill flags are conservatively accurate (kill flag correctly
  137. // indicates the last use of a register, an operand without kill flag may or
  138. // may not be the last use of a register). This means it can be used to
  139. // change the code in ways that affect the values in registers, for example
  140. // by the register scavenger.
  141. // When this property is cleared at a very late time, liveness is no longer
  142. // reliable.
  143. // NoVRegs: The machine function does not use any virtual registers.
  144. // Legalized: In GlobalISel: the MachineLegalizer ran and all pre-isel generic
  145. // instructions have been legalized; i.e., all instructions are now one of:
  146. // - generic and always legal (e.g., COPY)
  147. // - target-specific
  148. // - legal pre-isel generic instructions.
  149. // RegBankSelected: In GlobalISel: the RegBankSelect pass ran and all generic
  150. // virtual registers have been assigned to a register bank.
  151. // Selected: In GlobalISel: the InstructionSelect pass ran and all pre-isel
  152. // generic instructions have been eliminated; i.e., all instructions are now
  153. // target-specific or non-pre-isel generic instructions (e.g., COPY).
  154. // Since only pre-isel generic instructions can have generic virtual register
  155. // operands, this also means that all generic virtual registers have been
  156. // constrained to virtual registers (assigned to register classes) and that
  157. // all sizes attached to them have been eliminated.
  158. // TiedOpsRewritten: The twoaddressinstruction pass will set this flag, it
  159. // means that tied-def have been rewritten to meet the RegConstraint.
  160. // FailsVerification: Means that the function is not expected to pass machine
  161. // verification. This can be set by passes that introduce known problems that
  162. // have not been fixed yet.
  163. // TracksDebugUserValues: Without this property enabled, debug instructions
  164. // such as DBG_VALUE are allowed to reference virtual registers even if those
  165. // registers do not have a definition. With the property enabled virtual
  166. // registers must only be used if they have a definition. This property
  167. // allows earlier passes in the pipeline to skip updates of `DBG_VALUE`
  168. // instructions to save compile time.
  169. enum class Property : unsigned {
  170. IsSSA,
  171. NoPHIs,
  172. TracksLiveness,
  173. NoVRegs,
  174. FailedISel,
  175. Legalized,
  176. RegBankSelected,
  177. Selected,
  178. TiedOpsRewritten,
  179. FailsVerification,
  180. TracksDebugUserValues,
  181. LastProperty = TracksDebugUserValues,
  182. };
  183. bool hasProperty(Property P) const {
  184. return Properties[static_cast<unsigned>(P)];
  185. }
  186. MachineFunctionProperties &set(Property P) {
  187. Properties.set(static_cast<unsigned>(P));
  188. return *this;
  189. }
  190. MachineFunctionProperties &reset(Property P) {
  191. Properties.reset(static_cast<unsigned>(P));
  192. return *this;
  193. }
  194. /// Reset all the properties.
  195. MachineFunctionProperties &reset() {
  196. Properties.reset();
  197. return *this;
  198. }
  199. MachineFunctionProperties &set(const MachineFunctionProperties &MFP) {
  200. Properties |= MFP.Properties;
  201. return *this;
  202. }
  203. MachineFunctionProperties &reset(const MachineFunctionProperties &MFP) {
  204. Properties.reset(MFP.Properties);
  205. return *this;
  206. }
  207. // Returns true if all properties set in V (i.e. required by a pass) are set
  208. // in this.
  209. bool verifyRequiredProperties(const MachineFunctionProperties &V) const {
  210. return !V.Properties.test(Properties);
  211. }
  212. /// Print the MachineFunctionProperties in human-readable form.
  213. void print(raw_ostream &OS) const;
  214. private:
  215. BitVector Properties =
  216. BitVector(static_cast<unsigned>(Property::LastProperty)+1);
  217. };
  218. struct SEHHandler {
  219. /// Filter or finally function. Null indicates a catch-all.
  220. const Function *FilterOrFinally;
  221. /// Address of block to recover at. Null for a finally handler.
  222. const BlockAddress *RecoverBA;
  223. };
  224. /// This structure is used to retain landing pad info for the current function.
  225. struct LandingPadInfo {
  226. MachineBasicBlock *LandingPadBlock; // Landing pad block.
  227. SmallVector<MCSymbol *, 1> BeginLabels; // Labels prior to invoke.
  228. SmallVector<MCSymbol *, 1> EndLabels; // Labels after invoke.
  229. SmallVector<SEHHandler, 1> SEHHandlers; // SEH handlers active at this lpad.
  230. MCSymbol *LandingPadLabel = nullptr; // Label at beginning of landing pad.
  231. std::vector<int> TypeIds; // List of type ids (filters negative).
  232. explicit LandingPadInfo(MachineBasicBlock *MBB)
  233. : LandingPadBlock(MBB) {}
  234. };
  235. class LLVM_EXTERNAL_VISIBILITY MachineFunction {
  236. Function &F;
  237. const LLVMTargetMachine &Target;
  238. const TargetSubtargetInfo *STI;
  239. MCContext &Ctx;
  240. MachineModuleInfo &MMI;
  241. // RegInfo - Information about each register in use in the function.
  242. MachineRegisterInfo *RegInfo;
  243. // Used to keep track of target-specific per-machine function information for
  244. // the target implementation.
  245. MachineFunctionInfo *MFInfo;
  246. // Keep track of objects allocated on the stack.
  247. MachineFrameInfo *FrameInfo;
  248. // Keep track of constants which are spilled to memory
  249. MachineConstantPool *ConstantPool;
  250. // Keep track of jump tables for switch instructions
  251. MachineJumpTableInfo *JumpTableInfo;
  252. // Keep track of the function section.
  253. MCSection *Section = nullptr;
  254. // Catchpad unwind destination info for wasm EH.
  255. // Keeps track of Wasm exception handling related data. This will be null for
  256. // functions that aren't using a wasm EH personality.
  257. WasmEHFuncInfo *WasmEHInfo = nullptr;
  258. // Keeps track of Windows exception handling related data. This will be null
  259. // for functions that aren't using a funclet-based EH personality.
  260. WinEHFuncInfo *WinEHInfo = nullptr;
  261. // Function-level unique numbering for MachineBasicBlocks. When a
  262. // MachineBasicBlock is inserted into a MachineFunction is it automatically
  263. // numbered and this vector keeps track of the mapping from ID's to MBB's.
  264. std::vector<MachineBasicBlock*> MBBNumbering;
  265. // Pool-allocate MachineFunction-lifetime and IR objects.
  266. BumpPtrAllocator Allocator;
  267. // Allocation management for instructions in function.
  268. Recycler<MachineInstr> InstructionRecycler;
  269. // Allocation management for operand arrays on instructions.
  270. ArrayRecycler<MachineOperand> OperandRecycler;
  271. // Allocation management for basic blocks in function.
  272. Recycler<MachineBasicBlock> BasicBlockRecycler;
  273. // List of machine basic blocks in function
  274. using BasicBlockListType = ilist<MachineBasicBlock>;
  275. BasicBlockListType BasicBlocks;
  276. /// FunctionNumber - This provides a unique ID for each function emitted in
  277. /// this translation unit.
  278. ///
  279. unsigned FunctionNumber;
  280. /// Alignment - The alignment of the function.
  281. Align Alignment;
  282. /// ExposesReturnsTwice - True if the function calls setjmp or related
  283. /// functions with attribute "returns twice", but doesn't have
  284. /// the attribute itself.
  285. /// This is used to limit optimizations which cannot reason
  286. /// about the control flow of such functions.
  287. bool ExposesReturnsTwice = false;
  288. /// True if the function includes any inline assembly.
  289. bool HasInlineAsm = false;
  290. /// True if any WinCFI instruction have been emitted in this function.
  291. bool HasWinCFI = false;
  292. /// Current high-level properties of the IR of the function (e.g. is in SSA
  293. /// form or whether registers have been allocated)
  294. MachineFunctionProperties Properties;
  295. // Allocation management for pseudo source values.
  296. std::unique_ptr<PseudoSourceValueManager> PSVManager;
  297. /// List of moves done by a function's prolog. Used to construct frame maps
  298. /// by debug and exception handling consumers.
  299. std::vector<MCCFIInstruction> FrameInstructions;
  300. /// List of basic blocks immediately following calls to _setjmp. Used to
  301. /// construct a table of valid longjmp targets for Windows Control Flow Guard.
  302. std::vector<MCSymbol *> LongjmpTargets;
  303. /// List of basic blocks that are the target of catchrets. Used to construct
  304. /// a table of valid targets for Windows EHCont Guard.
  305. std::vector<MCSymbol *> CatchretTargets;
  306. /// \name Exception Handling
  307. /// \{
  308. /// List of LandingPadInfo describing the landing pad information.
  309. std::vector<LandingPadInfo> LandingPads;
  310. /// Map a landing pad's EH symbol to the call site indexes.
  311. DenseMap<MCSymbol*, SmallVector<unsigned, 4>> LPadToCallSiteMap;
  312. /// Map a landing pad to its index.
  313. DenseMap<const MachineBasicBlock *, unsigned> WasmLPadToIndexMap;
  314. /// Map of invoke call site index values to associated begin EH_LABEL.
  315. DenseMap<MCSymbol*, unsigned> CallSiteMap;
  316. /// CodeView label annotations.
  317. std::vector<std::pair<MCSymbol *, MDNode *>> CodeViewAnnotations;
  318. bool CallsEHReturn = false;
  319. bool CallsUnwindInit = false;
  320. bool HasEHCatchret = false;
  321. bool HasEHScopes = false;
  322. bool HasEHFunclets = false;
  323. /// BBID to assign to the next basic block of this function.
  324. unsigned NextBBID = 0;
  325. /// Section Type for basic blocks, only relevant with basic block sections.
  326. BasicBlockSection BBSectionsType = BasicBlockSection::None;
  327. /// List of C++ TypeInfo used.
  328. std::vector<const GlobalValue *> TypeInfos;
  329. /// List of typeids encoding filters used.
  330. std::vector<unsigned> FilterIds;
  331. /// List of the indices in FilterIds corresponding to filter terminators.
  332. std::vector<unsigned> FilterEnds;
  333. EHPersonality PersonalityTypeCache = EHPersonality::Unknown;
  334. /// \}
  335. /// Clear all the members of this MachineFunction, but the ones used
  336. /// to initialize again the MachineFunction.
  337. /// More specifically, this deallocates all the dynamically allocated
  338. /// objects and get rid of all the XXXInfo data structure, but keep
  339. /// unchanged the references to Fn, Target, MMI, and FunctionNumber.
  340. void clear();
  341. /// Allocate and initialize the different members.
  342. /// In particular, the XXXInfo data structure.
  343. /// \pre Fn, Target, MMI, and FunctionNumber are properly set.
  344. void init();
  345. public:
  346. struct VariableDbgInfo {
  347. const DILocalVariable *Var;
  348. const DIExpression *Expr;
  349. // The Slot can be negative for fixed stack objects.
  350. int Slot;
  351. const DILocation *Loc;
  352. VariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
  353. int Slot, const DILocation *Loc)
  354. : Var(Var), Expr(Expr), Slot(Slot), Loc(Loc) {}
  355. };
  356. class Delegate {
  357. virtual void anchor();
  358. public:
  359. virtual ~Delegate() = default;
  360. /// Callback after an insertion. This should not modify the MI directly.
  361. virtual void MF_HandleInsertion(MachineInstr &MI) = 0;
  362. /// Callback before a removal. This should not modify the MI directly.
  363. virtual void MF_HandleRemoval(MachineInstr &MI) = 0;
  364. };
  365. /// Structure used to represent pair of argument number after call lowering
  366. /// and register used to transfer that argument.
  367. /// For now we support only cases when argument is transferred through one
  368. /// register.
  369. struct ArgRegPair {
  370. Register Reg;
  371. uint16_t ArgNo;
  372. ArgRegPair(Register R, unsigned Arg) : Reg(R), ArgNo(Arg) {
  373. assert(Arg < (1 << 16) && "Arg out of range");
  374. }
  375. };
  376. /// Vector of call argument and its forwarding register.
  377. using CallSiteInfo = SmallVector<ArgRegPair, 1>;
  378. using CallSiteInfoImpl = SmallVectorImpl<ArgRegPair>;
  379. private:
  380. Delegate *TheDelegate = nullptr;
  381. GISelChangeObserver *Observer = nullptr;
  382. using CallSiteInfoMap = DenseMap<const MachineInstr *, CallSiteInfo>;
  383. /// Map a call instruction to call site arguments forwarding info.
  384. CallSiteInfoMap CallSitesInfo;
  385. /// A helper function that returns call site info for a give call
  386. /// instruction if debug entry value support is enabled.
  387. CallSiteInfoMap::iterator getCallSiteInfo(const MachineInstr *MI);
  388. // Callbacks for insertion and removal.
  389. void handleInsertion(MachineInstr &MI);
  390. void handleRemoval(MachineInstr &MI);
  391. friend struct ilist_traits<MachineInstr>;
  392. public:
  393. using VariableDbgInfoMapTy = SmallVector<VariableDbgInfo, 4>;
  394. VariableDbgInfoMapTy VariableDbgInfos;
  395. /// A count of how many instructions in the function have had numbers
  396. /// assigned to them. Used for debug value tracking, to determine the
  397. /// next instruction number.
  398. unsigned DebugInstrNumberingCount = 0;
  399. /// Set value of DebugInstrNumberingCount field. Avoid using this unless
  400. /// you're deserializing this data.
  401. void setDebugInstrNumberingCount(unsigned Num);
  402. /// Pair of instruction number and operand number.
  403. using DebugInstrOperandPair = std::pair<unsigned, unsigned>;
  404. /// Replacement definition for a debug instruction reference. Made up of a
  405. /// source instruction / operand pair, destination pair, and a qualifying
  406. /// subregister indicating what bits in the operand make up the substitution.
  407. // For example, a debug user
  408. /// of %1:
  409. /// %0:gr32 = someinst, debug-instr-number 1
  410. /// %1:gr16 = %0.some_16_bit_subreg, debug-instr-number 2
  411. /// Would receive the substitution {{2, 0}, {1, 0}, $subreg}, where $subreg is
  412. /// the subregister number for some_16_bit_subreg.
  413. class DebugSubstitution {
  414. public:
  415. DebugInstrOperandPair Src; ///< Source instruction / operand pair.
  416. DebugInstrOperandPair Dest; ///< Replacement instruction / operand pair.
  417. unsigned Subreg; ///< Qualifier for which part of Dest is read.
  418. DebugSubstitution(const DebugInstrOperandPair &Src,
  419. const DebugInstrOperandPair &Dest, unsigned Subreg)
  420. : Src(Src), Dest(Dest), Subreg(Subreg) {}
  421. /// Order only by source instruction / operand pair: there should never
  422. /// be duplicate entries for the same source in any collection.
  423. bool operator<(const DebugSubstitution &Other) const {
  424. return Src < Other.Src;
  425. }
  426. };
  427. /// Debug value substitutions: a collection of DebugSubstitution objects,
  428. /// recording changes in where a value is defined. For example, when one
  429. /// instruction is substituted for another. Keeping a record allows recovery
  430. /// of variable locations after compilation finishes.
  431. SmallVector<DebugSubstitution, 8> DebugValueSubstitutions;
  432. /// Location of a PHI instruction that is also a debug-info variable value,
  433. /// for the duration of register allocation. Loaded by the PHI-elimination
  434. /// pass, and emitted as DBG_PHI instructions during VirtRegRewriter, with
  435. /// maintenance applied by intermediate passes that edit registers (such as
  436. /// coalescing and the allocator passes).
  437. class DebugPHIRegallocPos {
  438. public:
  439. MachineBasicBlock *MBB; ///< Block where this PHI was originally located.
  440. Register Reg; ///< VReg where the control-flow-merge happens.
  441. unsigned SubReg; ///< Optional subreg qualifier within Reg.
  442. DebugPHIRegallocPos(MachineBasicBlock *MBB, Register Reg, unsigned SubReg)
  443. : MBB(MBB), Reg(Reg), SubReg(SubReg) {}
  444. };
  445. /// Map of debug instruction numbers to the position of their PHI instructions
  446. /// during register allocation. See DebugPHIRegallocPos.
  447. DenseMap<unsigned, DebugPHIRegallocPos> DebugPHIPositions;
  448. /// Flag for whether this function contains DBG_VALUEs (false) or
  449. /// DBG_INSTR_REF (true).
  450. bool UseDebugInstrRef = false;
  451. /// Create a substitution between one <instr,operand> value to a different,
  452. /// new value.
  453. void makeDebugValueSubstitution(DebugInstrOperandPair, DebugInstrOperandPair,
  454. unsigned SubReg = 0);
  455. /// Create substitutions for any tracked values in \p Old, to point at
  456. /// \p New. Needed when we re-create an instruction during optimization,
  457. /// which has the same signature (i.e., def operands in the same place) but
  458. /// a modified instruction type, flags, or otherwise. An example: X86 moves
  459. /// are sometimes transformed into equivalent LEAs.
  460. /// If the two instructions are not the same opcode, limit which operands to
  461. /// examine for substitutions to the first N operands by setting
  462. /// \p MaxOperand.
  463. void substituteDebugValuesForInst(const MachineInstr &Old, MachineInstr &New,
  464. unsigned MaxOperand = UINT_MAX);
  465. /// Find the underlying defining instruction / operand for a COPY instruction
  466. /// while in SSA form. Copies do not actually define values -- they move them
  467. /// between registers. Labelling a COPY-like instruction with an instruction
  468. /// number is to be avoided as it makes value numbers non-unique later in
  469. /// compilation. This method follows the definition chain for any sequence of
  470. /// COPY-like instructions to find whatever non-COPY-like instruction defines
  471. /// the copied value; or for parameters, creates a DBG_PHI on entry.
  472. /// May insert instructions into the entry block!
  473. /// \p MI The copy-like instruction to salvage.
  474. /// \p DbgPHICache A container to cache already-solved COPYs.
  475. /// \returns An instruction/operand pair identifying the defining value.
  476. DebugInstrOperandPair
  477. salvageCopySSA(MachineInstr &MI,
  478. DenseMap<Register, DebugInstrOperandPair> &DbgPHICache);
  479. DebugInstrOperandPair salvageCopySSAImpl(MachineInstr &MI);
  480. /// Finalise any partially emitted debug instructions. These are DBG_INSTR_REF
  481. /// instructions where we only knew the vreg of the value they use, not the
  482. /// instruction that defines that vreg. Once isel finishes, we should have
  483. /// enough information for every DBG_INSTR_REF to point at an instruction
  484. /// (or DBG_PHI).
  485. void finalizeDebugInstrRefs();
  486. /// Determine whether, in the current machine configuration, we should use
  487. /// instruction referencing or not.
  488. bool shouldUseDebugInstrRef() const;
  489. /// Returns true if the function's variable locations are tracked with
  490. /// instruction referencing.
  491. bool useDebugInstrRef() const;
  492. /// Set whether this function will use instruction referencing or not.
  493. void setUseDebugInstrRef(bool UseInstrRef);
  494. /// A reserved operand number representing the instructions memory operand,
  495. /// for instructions that have a stack spill fused into them.
  496. const static unsigned int DebugOperandMemNumber;
  497. MachineFunction(Function &F, const LLVMTargetMachine &Target,
  498. const TargetSubtargetInfo &STI, unsigned FunctionNum,
  499. MachineModuleInfo &MMI);
  500. MachineFunction(const MachineFunction &) = delete;
  501. MachineFunction &operator=(const MachineFunction &) = delete;
  502. ~MachineFunction();
  503. /// Reset the instance as if it was just created.
  504. void reset() {
  505. clear();
  506. init();
  507. }
  508. /// Reset the currently registered delegate - otherwise assert.
  509. void resetDelegate(Delegate *delegate) {
  510. assert(TheDelegate == delegate &&
  511. "Only the current delegate can perform reset!");
  512. TheDelegate = nullptr;
  513. }
  514. /// Set the delegate. resetDelegate must be called before attempting
  515. /// to set.
  516. void setDelegate(Delegate *delegate) {
  517. assert(delegate && !TheDelegate &&
  518. "Attempted to set delegate to null, or to change it without "
  519. "first resetting it!");
  520. TheDelegate = delegate;
  521. }
  522. void setObserver(GISelChangeObserver *O) { Observer = O; }
  523. GISelChangeObserver *getObserver() const { return Observer; }
  524. MachineModuleInfo &getMMI() const { return MMI; }
  525. MCContext &getContext() const { return Ctx; }
  526. /// Returns the Section this function belongs to.
  527. MCSection *getSection() const { return Section; }
  528. /// Indicates the Section this function belongs to.
  529. void setSection(MCSection *S) { Section = S; }
  530. PseudoSourceValueManager &getPSVManager() const { return *PSVManager; }
  531. /// Return the DataLayout attached to the Module associated to this MF.
  532. const DataLayout &getDataLayout() const;
  533. /// Return the LLVM function that this machine code represents
  534. Function &getFunction() { return F; }
  535. /// Return the LLVM function that this machine code represents
  536. const Function &getFunction() const { return F; }
  537. /// getName - Return the name of the corresponding LLVM function.
  538. StringRef getName() const;
  539. /// getFunctionNumber - Return a unique ID for the current function.
  540. unsigned getFunctionNumber() const { return FunctionNumber; }
  541. /// Returns true if this function has basic block sections enabled.
  542. bool hasBBSections() const {
  543. return (BBSectionsType == BasicBlockSection::All ||
  544. BBSectionsType == BasicBlockSection::List ||
  545. BBSectionsType == BasicBlockSection::Preset);
  546. }
  547. /// Returns true if basic block labels are to be generated for this function.
  548. bool hasBBLabels() const {
  549. return BBSectionsType == BasicBlockSection::Labels;
  550. }
  551. void setBBSectionsType(BasicBlockSection V) { BBSectionsType = V; }
  552. /// Assign IsBeginSection IsEndSection fields for basic blocks in this
  553. /// function.
  554. void assignBeginEndSections();
  555. /// getTarget - Return the target machine this machine code is compiled with
  556. const LLVMTargetMachine &getTarget() const { return Target; }
  557. /// getSubtarget - Return the subtarget for which this machine code is being
  558. /// compiled.
  559. const TargetSubtargetInfo &getSubtarget() const { return *STI; }
  560. /// getSubtarget - This method returns a pointer to the specified type of
  561. /// TargetSubtargetInfo. In debug builds, it verifies that the object being
  562. /// returned is of the correct type.
  563. template<typename STC> const STC &getSubtarget() const {
  564. return *static_cast<const STC *>(STI);
  565. }
  566. /// getRegInfo - Return information about the registers currently in use.
  567. MachineRegisterInfo &getRegInfo() { return *RegInfo; }
  568. const MachineRegisterInfo &getRegInfo() const { return *RegInfo; }
  569. /// getFrameInfo - Return the frame info object for the current function.
  570. /// This object contains information about objects allocated on the stack
  571. /// frame of the current function in an abstract way.
  572. MachineFrameInfo &getFrameInfo() { return *FrameInfo; }
  573. const MachineFrameInfo &getFrameInfo() const { return *FrameInfo; }
  574. /// getJumpTableInfo - Return the jump table info object for the current
  575. /// function. This object contains information about jump tables in the
  576. /// current function. If the current function has no jump tables, this will
  577. /// return null.
  578. const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; }
  579. MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; }
  580. /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
  581. /// does already exist, allocate one.
  582. MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind);
  583. /// getConstantPool - Return the constant pool object for the current
  584. /// function.
  585. MachineConstantPool *getConstantPool() { return ConstantPool; }
  586. const MachineConstantPool *getConstantPool() const { return ConstantPool; }
  587. /// getWasmEHFuncInfo - Return information about how the current function uses
  588. /// Wasm exception handling. Returns null for functions that don't use wasm
  589. /// exception handling.
  590. const WasmEHFuncInfo *getWasmEHFuncInfo() const { return WasmEHInfo; }
  591. WasmEHFuncInfo *getWasmEHFuncInfo() { return WasmEHInfo; }
  592. /// getWinEHFuncInfo - Return information about how the current function uses
  593. /// Windows exception handling. Returns null for functions that don't use
  594. /// funclets for exception handling.
  595. const WinEHFuncInfo *getWinEHFuncInfo() const { return WinEHInfo; }
  596. WinEHFuncInfo *getWinEHFuncInfo() { return WinEHInfo; }
  597. /// getAlignment - Return the alignment of the function.
  598. Align getAlignment() const { return Alignment; }
  599. /// setAlignment - Set the alignment of the function.
  600. void setAlignment(Align A) { Alignment = A; }
  601. /// ensureAlignment - Make sure the function is at least A bytes aligned.
  602. void ensureAlignment(Align A) {
  603. if (Alignment < A)
  604. Alignment = A;
  605. }
  606. /// exposesReturnsTwice - Returns true if the function calls setjmp or
  607. /// any other similar functions with attribute "returns twice" without
  608. /// having the attribute itself.
  609. bool exposesReturnsTwice() const {
  610. return ExposesReturnsTwice;
  611. }
  612. /// setCallsSetJmp - Set a flag that indicates if there's a call to
  613. /// a "returns twice" function.
  614. void setExposesReturnsTwice(bool B) {
  615. ExposesReturnsTwice = B;
  616. }
  617. /// Returns true if the function contains any inline assembly.
  618. bool hasInlineAsm() const {
  619. return HasInlineAsm;
  620. }
  621. /// Set a flag that indicates that the function contains inline assembly.
  622. void setHasInlineAsm(bool B) {
  623. HasInlineAsm = B;
  624. }
  625. bool hasWinCFI() const {
  626. return HasWinCFI;
  627. }
  628. void setHasWinCFI(bool v) { HasWinCFI = v; }
  629. /// True if this function needs frame moves for debug or exceptions.
  630. bool needsFrameMoves() const;
  631. /// Get the function properties
  632. const MachineFunctionProperties &getProperties() const { return Properties; }
  633. MachineFunctionProperties &getProperties() { return Properties; }
  634. /// getInfo - Keep track of various per-function pieces of information for
  635. /// backends that would like to do so.
  636. ///
  637. template<typename Ty>
  638. Ty *getInfo() {
  639. return static_cast<Ty*>(MFInfo);
  640. }
  641. template<typename Ty>
  642. const Ty *getInfo() const {
  643. return static_cast<const Ty *>(MFInfo);
  644. }
  645. template <typename Ty> Ty *cloneInfo(const Ty &Old) {
  646. assert(!MFInfo);
  647. MFInfo = Ty::template create<Ty>(Allocator, Old);
  648. return static_cast<Ty *>(MFInfo);
  649. }
  650. /// Initialize the target specific MachineFunctionInfo
  651. void initTargetMachineFunctionInfo(const TargetSubtargetInfo &STI);
  652. MachineFunctionInfo *cloneInfoFrom(
  653. const MachineFunction &OrigMF,
  654. const DenseMap<MachineBasicBlock *, MachineBasicBlock *> &Src2DstMBB) {
  655. assert(!MFInfo && "new function already has MachineFunctionInfo");
  656. if (!OrigMF.MFInfo)
  657. return nullptr;
  658. return OrigMF.MFInfo->clone(Allocator, *this, Src2DstMBB);
  659. }
  660. /// Returns the denormal handling type for the default rounding mode of the
  661. /// function.
  662. DenormalMode getDenormalMode(const fltSemantics &FPType) const;
  663. /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they
  664. /// are inserted into the machine function. The block number for a machine
  665. /// basic block can be found by using the MBB::getNumber method, this method
  666. /// provides the inverse mapping.
  667. MachineBasicBlock *getBlockNumbered(unsigned N) const {
  668. assert(N < MBBNumbering.size() && "Illegal block number");
  669. assert(MBBNumbering[N] && "Block was removed from the machine function!");
  670. return MBBNumbering[N];
  671. }
  672. /// Should we be emitting segmented stack stuff for the function
  673. bool shouldSplitStack() const;
  674. /// getNumBlockIDs - Return the number of MBB ID's allocated.
  675. unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); }
  676. /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
  677. /// recomputes them. This guarantees that the MBB numbers are sequential,
  678. /// dense, and match the ordering of the blocks within the function. If a
  679. /// specific MachineBasicBlock is specified, only that block and those after
  680. /// it are renumbered.
  681. void RenumberBlocks(MachineBasicBlock *MBBFrom = nullptr);
  682. /// print - Print out the MachineFunction in a format suitable for debugging
  683. /// to the specified stream.
  684. void print(raw_ostream &OS, const SlotIndexes* = nullptr) const;
  685. /// viewCFG - This function is meant for use from the debugger. You can just
  686. /// say 'call F->viewCFG()' and a ghostview window should pop up from the
  687. /// program, displaying the CFG of the current function with the code for each
  688. /// basic block inside. This depends on there being a 'dot' and 'gv' program
  689. /// in your path.
  690. void viewCFG() const;
  691. /// viewCFGOnly - This function is meant for use from the debugger. It works
  692. /// just like viewCFG, but it does not include the contents of basic blocks
  693. /// into the nodes, just the label. If you are only interested in the CFG
  694. /// this can make the graph smaller.
  695. ///
  696. void viewCFGOnly() const;
  697. /// dump - Print the current MachineFunction to cerr, useful for debugger use.
  698. void dump() const;
  699. /// Run the current MachineFunction through the machine code verifier, useful
  700. /// for debugger use.
  701. /// \returns true if no problems were found.
  702. bool verify(Pass *p = nullptr, const char *Banner = nullptr,
  703. bool AbortOnError = true) const;
  704. // Provide accessors for the MachineBasicBlock list...
  705. using iterator = BasicBlockListType::iterator;
  706. using const_iterator = BasicBlockListType::const_iterator;
  707. using const_reverse_iterator = BasicBlockListType::const_reverse_iterator;
  708. using reverse_iterator = BasicBlockListType::reverse_iterator;
  709. /// Support for MachineBasicBlock::getNextNode().
  710. static BasicBlockListType MachineFunction::*
  711. getSublistAccess(MachineBasicBlock *) {
  712. return &MachineFunction::BasicBlocks;
  713. }
  714. /// addLiveIn - Add the specified physical register as a live-in value and
  715. /// create a corresponding virtual register for it.
  716. Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC);
  717. //===--------------------------------------------------------------------===//
  718. // BasicBlock accessor functions.
  719. //
  720. iterator begin() { return BasicBlocks.begin(); }
  721. const_iterator begin() const { return BasicBlocks.begin(); }
  722. iterator end () { return BasicBlocks.end(); }
  723. const_iterator end () const { return BasicBlocks.end(); }
  724. reverse_iterator rbegin() { return BasicBlocks.rbegin(); }
  725. const_reverse_iterator rbegin() const { return BasicBlocks.rbegin(); }
  726. reverse_iterator rend () { return BasicBlocks.rend(); }
  727. const_reverse_iterator rend () const { return BasicBlocks.rend(); }
  728. unsigned size() const { return (unsigned)BasicBlocks.size();}
  729. bool empty() const { return BasicBlocks.empty(); }
  730. const MachineBasicBlock &front() const { return BasicBlocks.front(); }
  731. MachineBasicBlock &front() { return BasicBlocks.front(); }
  732. const MachineBasicBlock & back() const { return BasicBlocks.back(); }
  733. MachineBasicBlock & back() { return BasicBlocks.back(); }
  734. void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); }
  735. void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); }
  736. void insert(iterator MBBI, MachineBasicBlock *MBB) {
  737. BasicBlocks.insert(MBBI, MBB);
  738. }
  739. void splice(iterator InsertPt, iterator MBBI) {
  740. BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
  741. }
  742. void splice(iterator InsertPt, MachineBasicBlock *MBB) {
  743. BasicBlocks.splice(InsertPt, BasicBlocks, MBB);
  744. }
  745. void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
  746. BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
  747. }
  748. void remove(iterator MBBI) { BasicBlocks.remove(MBBI); }
  749. void remove(MachineBasicBlock *MBBI) { BasicBlocks.remove(MBBI); }
  750. void erase(iterator MBBI) { BasicBlocks.erase(MBBI); }
  751. void erase(MachineBasicBlock *MBBI) { BasicBlocks.erase(MBBI); }
  752. template <typename Comp>
  753. void sort(Comp comp) {
  754. BasicBlocks.sort(comp);
  755. }
  756. /// Return the number of \p MachineInstrs in this \p MachineFunction.
  757. unsigned getInstructionCount() const {
  758. unsigned InstrCount = 0;
  759. for (const MachineBasicBlock &MBB : BasicBlocks)
  760. InstrCount += MBB.size();
  761. return InstrCount;
  762. }
  763. //===--------------------------------------------------------------------===//
  764. // Internal functions used to automatically number MachineBasicBlocks
  765. /// Adds the MBB to the internal numbering. Returns the unique number
  766. /// assigned to the MBB.
  767. unsigned addToMBBNumbering(MachineBasicBlock *MBB) {
  768. MBBNumbering.push_back(MBB);
  769. return (unsigned)MBBNumbering.size()-1;
  770. }
  771. /// removeFromMBBNumbering - Remove the specific machine basic block from our
  772. /// tracker, this is only really to be used by the MachineBasicBlock
  773. /// implementation.
  774. void removeFromMBBNumbering(unsigned N) {
  775. assert(N < MBBNumbering.size() && "Illegal basic block #");
  776. MBBNumbering[N] = nullptr;
  777. }
  778. /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
  779. /// of `new MachineInstr'.
  780. MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID, DebugLoc DL,
  781. bool NoImplicit = false);
  782. /// Create a new MachineInstr which is a copy of \p Orig, identical in all
  783. /// ways except the instruction has no parent, prev, or next. Bundling flags
  784. /// are reset.
  785. ///
  786. /// Note: Clones a single instruction, not whole instruction bundles.
  787. /// Does not perform target specific adjustments; consider using
  788. /// TargetInstrInfo::duplicate() instead.
  789. MachineInstr *CloneMachineInstr(const MachineInstr *Orig);
  790. /// Clones instruction or the whole instruction bundle \p Orig and insert
  791. /// into \p MBB before \p InsertBefore.
  792. ///
  793. /// Note: Does not perform target specific adjustments; consider using
  794. /// TargetInstrInfo::duplicate() intead.
  795. MachineInstr &
  796. cloneMachineInstrBundle(MachineBasicBlock &MBB,
  797. MachineBasicBlock::iterator InsertBefore,
  798. const MachineInstr &Orig);
  799. /// DeleteMachineInstr - Delete the given MachineInstr.
  800. void deleteMachineInstr(MachineInstr *MI);
  801. /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
  802. /// instead of `new MachineBasicBlock'.
  803. MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = nullptr);
  804. /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
  805. void deleteMachineBasicBlock(MachineBasicBlock *MBB);
  806. /// getMachineMemOperand - Allocate a new MachineMemOperand.
  807. /// MachineMemOperands are owned by the MachineFunction and need not be
  808. /// explicitly deallocated.
  809. MachineMemOperand *getMachineMemOperand(
  810. MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
  811. Align base_alignment, const AAMDNodes &AAInfo = AAMDNodes(),
  812. const MDNode *Ranges = nullptr, SyncScope::ID SSID = SyncScope::System,
  813. AtomicOrdering Ordering = AtomicOrdering::NotAtomic,
  814. AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic);
  815. MachineMemOperand *getMachineMemOperand(
  816. MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
  817. Align base_alignment, const AAMDNodes &AAInfo = AAMDNodes(),
  818. const MDNode *Ranges = nullptr, SyncScope::ID SSID = SyncScope::System,
  819. AtomicOrdering Ordering = AtomicOrdering::NotAtomic,
  820. AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic);
  821. /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
  822. /// an existing one, adjusting by an offset and using the given size.
  823. /// MachineMemOperands are owned by the MachineFunction and need not be
  824. /// explicitly deallocated.
  825. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  826. int64_t Offset, LLT Ty);
  827. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  828. int64_t Offset, uint64_t Size) {
  829. return getMachineMemOperand(
  830. MMO, Offset, Size == ~UINT64_C(0) ? LLT() : LLT::scalar(8 * Size));
  831. }
  832. /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
  833. /// an existing one, replacing only the MachinePointerInfo and size.
  834. /// MachineMemOperands are owned by the MachineFunction and need not be
  835. /// explicitly deallocated.
  836. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  837. const MachinePointerInfo &PtrInfo,
  838. uint64_t Size);
  839. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  840. const MachinePointerInfo &PtrInfo,
  841. LLT Ty);
  842. /// Allocate a new MachineMemOperand by copying an existing one,
  843. /// replacing only AliasAnalysis information. MachineMemOperands are owned
  844. /// by the MachineFunction and need not be explicitly deallocated.
  845. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  846. const AAMDNodes &AAInfo);
  847. /// Allocate a new MachineMemOperand by copying an existing one,
  848. /// replacing the flags. MachineMemOperands are owned
  849. /// by the MachineFunction and need not be explicitly deallocated.
  850. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  851. MachineMemOperand::Flags Flags);
  852. using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
  853. /// Allocate an array of MachineOperands. This is only intended for use by
  854. /// internal MachineInstr functions.
  855. MachineOperand *allocateOperandArray(OperandCapacity Cap) {
  856. return OperandRecycler.allocate(Cap, Allocator);
  857. }
  858. /// Dellocate an array of MachineOperands and recycle the memory. This is
  859. /// only intended for use by internal MachineInstr functions.
  860. /// Cap must be the same capacity that was used to allocate the array.
  861. void deallocateOperandArray(OperandCapacity Cap, MachineOperand *Array) {
  862. OperandRecycler.deallocate(Cap, Array);
  863. }
  864. /// Allocate and initialize a register mask with @p NumRegister bits.
  865. uint32_t *allocateRegMask();
  866. ArrayRef<int> allocateShuffleMask(ArrayRef<int> Mask);
  867. /// Allocate and construct an extra info structure for a `MachineInstr`.
  868. ///
  869. /// This is allocated on the function's allocator and so lives the life of
  870. /// the function.
  871. MachineInstr::ExtraInfo *createMIExtraInfo(
  872. ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol = nullptr,
  873. MCSymbol *PostInstrSymbol = nullptr, MDNode *HeapAllocMarker = nullptr,
  874. MDNode *PCSections = nullptr, uint32_t CFIType = 0);
  875. /// Allocate a string and populate it with the given external symbol name.
  876. const char *createExternalSymbolName(StringRef Name);
  877. //===--------------------------------------------------------------------===//
  878. // Label Manipulation.
  879. /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
  880. /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
  881. /// normal 'L' label is returned.
  882. MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx,
  883. bool isLinkerPrivate = false) const;
  884. /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
  885. /// base.
  886. MCSymbol *getPICBaseSymbol() const;
  887. /// Returns a reference to a list of cfi instructions in the function's
  888. /// prologue. Used to construct frame maps for debug and exception handling
  889. /// comsumers.
  890. const std::vector<MCCFIInstruction> &getFrameInstructions() const {
  891. return FrameInstructions;
  892. }
  893. [[nodiscard]] unsigned addFrameInst(const MCCFIInstruction &Inst);
  894. /// Returns a reference to a list of symbols immediately following calls to
  895. /// _setjmp in the function. Used to construct the longjmp target table used
  896. /// by Windows Control Flow Guard.
  897. const std::vector<MCSymbol *> &getLongjmpTargets() const {
  898. return LongjmpTargets;
  899. }
  900. /// Add the specified symbol to the list of valid longjmp targets for Windows
  901. /// Control Flow Guard.
  902. void addLongjmpTarget(MCSymbol *Target) { LongjmpTargets.push_back(Target); }
  903. /// Returns a reference to a list of symbols that we have catchrets.
  904. /// Used to construct the catchret target table used by Windows EHCont Guard.
  905. const std::vector<MCSymbol *> &getCatchretTargets() const {
  906. return CatchretTargets;
  907. }
  908. /// Add the specified symbol to the list of valid catchret targets for Windows
  909. /// EHCont Guard.
  910. void addCatchretTarget(MCSymbol *Target) {
  911. CatchretTargets.push_back(Target);
  912. }
  913. /// \name Exception Handling
  914. /// \{
  915. bool callsEHReturn() const { return CallsEHReturn; }
  916. void setCallsEHReturn(bool b) { CallsEHReturn = b; }
  917. bool callsUnwindInit() const { return CallsUnwindInit; }
  918. void setCallsUnwindInit(bool b) { CallsUnwindInit = b; }
  919. bool hasEHCatchret() const { return HasEHCatchret; }
  920. void setHasEHCatchret(bool V) { HasEHCatchret = V; }
  921. bool hasEHScopes() const { return HasEHScopes; }
  922. void setHasEHScopes(bool V) { HasEHScopes = V; }
  923. bool hasEHFunclets() const { return HasEHFunclets; }
  924. void setHasEHFunclets(bool V) { HasEHFunclets = V; }
  925. /// Find or create an LandingPadInfo for the specified MachineBasicBlock.
  926. LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad);
  927. /// Return a reference to the landing pad info for the current function.
  928. const std::vector<LandingPadInfo> &getLandingPads() const {
  929. return LandingPads;
  930. }
  931. /// Provide the begin and end labels of an invoke style call and associate it
  932. /// with a try landing pad block.
  933. void addInvoke(MachineBasicBlock *LandingPad,
  934. MCSymbol *BeginLabel, MCSymbol *EndLabel);
  935. /// Add a new panding pad, and extract the exception handling information from
  936. /// the landingpad instruction. Returns the label ID for the landing pad
  937. /// entry.
  938. MCSymbol *addLandingPad(MachineBasicBlock *LandingPad);
  939. /// Return the type id for the specified typeinfo. This is function wide.
  940. unsigned getTypeIDFor(const GlobalValue *TI);
  941. /// Return the id of the filter encoded by TyIds. This is function wide.
  942. int getFilterIDFor(ArrayRef<unsigned> TyIds);
  943. /// Map the landing pad's EH symbol to the call site indexes.
  944. void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef<unsigned> Sites);
  945. /// Return if there is any wasm exception handling.
  946. bool hasAnyWasmLandingPadIndex() const {
  947. return !WasmLPadToIndexMap.empty();
  948. }
  949. /// Map the landing pad to its index. Used for Wasm exception handling.
  950. void setWasmLandingPadIndex(const MachineBasicBlock *LPad, unsigned Index) {
  951. WasmLPadToIndexMap[LPad] = Index;
  952. }
  953. /// Returns true if the landing pad has an associate index in wasm EH.
  954. bool hasWasmLandingPadIndex(const MachineBasicBlock *LPad) const {
  955. return WasmLPadToIndexMap.count(LPad);
  956. }
  957. /// Get the index in wasm EH for a given landing pad.
  958. unsigned getWasmLandingPadIndex(const MachineBasicBlock *LPad) const {
  959. assert(hasWasmLandingPadIndex(LPad));
  960. return WasmLPadToIndexMap.lookup(LPad);
  961. }
  962. bool hasAnyCallSiteLandingPad() const {
  963. return !LPadToCallSiteMap.empty();
  964. }
  965. /// Get the call site indexes for a landing pad EH symbol.
  966. SmallVectorImpl<unsigned> &getCallSiteLandingPad(MCSymbol *Sym) {
  967. assert(hasCallSiteLandingPad(Sym) &&
  968. "missing call site number for landing pad!");
  969. return LPadToCallSiteMap[Sym];
  970. }
  971. /// Return true if the landing pad Eh symbol has an associated call site.
  972. bool hasCallSiteLandingPad(MCSymbol *Sym) {
  973. return !LPadToCallSiteMap[Sym].empty();
  974. }
  975. bool hasAnyCallSiteLabel() const {
  976. return !CallSiteMap.empty();
  977. }
  978. /// Map the begin label for a call site.
  979. void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site) {
  980. CallSiteMap[BeginLabel] = Site;
  981. }
  982. /// Get the call site number for a begin label.
  983. unsigned getCallSiteBeginLabel(MCSymbol *BeginLabel) const {
  984. assert(hasCallSiteBeginLabel(BeginLabel) &&
  985. "Missing call site number for EH_LABEL!");
  986. return CallSiteMap.lookup(BeginLabel);
  987. }
  988. /// Return true if the begin label has a call site number associated with it.
  989. bool hasCallSiteBeginLabel(MCSymbol *BeginLabel) const {
  990. return CallSiteMap.count(BeginLabel);
  991. }
  992. /// Record annotations associated with a particular label.
  993. void addCodeViewAnnotation(MCSymbol *Label, MDNode *MD) {
  994. CodeViewAnnotations.push_back({Label, MD});
  995. }
  996. ArrayRef<std::pair<MCSymbol *, MDNode *>> getCodeViewAnnotations() const {
  997. return CodeViewAnnotations;
  998. }
  999. /// Return a reference to the C++ typeinfo for the current function.
  1000. const std::vector<const GlobalValue *> &getTypeInfos() const {
  1001. return TypeInfos;
  1002. }
  1003. /// Return a reference to the typeids encoding filters used in the current
  1004. /// function.
  1005. const std::vector<unsigned> &getFilterIds() const {
  1006. return FilterIds;
  1007. }
  1008. /// \}
  1009. /// Collect information used to emit debugging information of a variable.
  1010. void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
  1011. int Slot, const DILocation *Loc) {
  1012. VariableDbgInfos.emplace_back(Var, Expr, Slot, Loc);
  1013. }
  1014. VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfos; }
  1015. const VariableDbgInfoMapTy &getVariableDbgInfo() const {
  1016. return VariableDbgInfos;
  1017. }
  1018. /// Start tracking the arguments passed to the call \p CallI.
  1019. void addCallArgsForwardingRegs(const MachineInstr *CallI,
  1020. CallSiteInfoImpl &&CallInfo) {
  1021. assert(CallI->isCandidateForCallSiteEntry());
  1022. bool Inserted =
  1023. CallSitesInfo.try_emplace(CallI, std::move(CallInfo)).second;
  1024. (void)Inserted;
  1025. assert(Inserted && "Call site info not unique");
  1026. }
  1027. const CallSiteInfoMap &getCallSitesInfo() const {
  1028. return CallSitesInfo;
  1029. }
  1030. /// Following functions update call site info. They should be called before
  1031. /// removing, replacing or copying call instruction.
  1032. /// Erase the call site info for \p MI. It is used to remove a call
  1033. /// instruction from the instruction stream.
  1034. void eraseCallSiteInfo(const MachineInstr *MI);
  1035. /// Copy the call site info from \p Old to \ New. Its usage is when we are
  1036. /// making a copy of the instruction that will be inserted at different point
  1037. /// of the instruction stream.
  1038. void copyCallSiteInfo(const MachineInstr *Old,
  1039. const MachineInstr *New);
  1040. /// Move the call site info from \p Old to \New call site info. This function
  1041. /// is used when we are replacing one call instruction with another one to
  1042. /// the same callee.
  1043. void moveCallSiteInfo(const MachineInstr *Old,
  1044. const MachineInstr *New);
  1045. unsigned getNewDebugInstrNum() {
  1046. return ++DebugInstrNumberingCount;
  1047. }
  1048. };
  1049. //===--------------------------------------------------------------------===//
  1050. // GraphTraits specializations for function basic block graphs (CFGs)
  1051. //===--------------------------------------------------------------------===//
  1052. // Provide specializations of GraphTraits to be able to treat a
  1053. // machine function as a graph of machine basic blocks... these are
  1054. // the same as the machine basic block iterators, except that the root
  1055. // node is implicitly the first node of the function.
  1056. //
  1057. template <> struct GraphTraits<MachineFunction*> :
  1058. public GraphTraits<MachineBasicBlock*> {
  1059. static NodeRef getEntryNode(MachineFunction *F) { return &F->front(); }
  1060. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  1061. using nodes_iterator = pointer_iterator<MachineFunction::iterator>;
  1062. static nodes_iterator nodes_begin(MachineFunction *F) {
  1063. return nodes_iterator(F->begin());
  1064. }
  1065. static nodes_iterator nodes_end(MachineFunction *F) {
  1066. return nodes_iterator(F->end());
  1067. }
  1068. static unsigned size (MachineFunction *F) { return F->size(); }
  1069. };
  1070. template <> struct GraphTraits<const MachineFunction*> :
  1071. public GraphTraits<const MachineBasicBlock*> {
  1072. static NodeRef getEntryNode(const MachineFunction *F) { return &F->front(); }
  1073. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  1074. using nodes_iterator = pointer_iterator<MachineFunction::const_iterator>;
  1075. static nodes_iterator nodes_begin(const MachineFunction *F) {
  1076. return nodes_iterator(F->begin());
  1077. }
  1078. static nodes_iterator nodes_end (const MachineFunction *F) {
  1079. return nodes_iterator(F->end());
  1080. }
  1081. static unsigned size (const MachineFunction *F) {
  1082. return F->size();
  1083. }
  1084. };
  1085. // Provide specializations of GraphTraits to be able to treat a function as a
  1086. // graph of basic blocks... and to walk it in inverse order. Inverse order for
  1087. // a function is considered to be when traversing the predecessor edges of a BB
  1088. // instead of the successor edges.
  1089. //
  1090. template <> struct GraphTraits<Inverse<MachineFunction*>> :
  1091. public GraphTraits<Inverse<MachineBasicBlock*>> {
  1092. static NodeRef getEntryNode(Inverse<MachineFunction *> G) {
  1093. return &G.Graph->front();
  1094. }
  1095. };
  1096. template <> struct GraphTraits<Inverse<const MachineFunction*>> :
  1097. public GraphTraits<Inverse<const MachineBasicBlock*>> {
  1098. static NodeRef getEntryNode(Inverse<const MachineFunction *> G) {
  1099. return &G.Graph->front();
  1100. }
  1101. };
  1102. class MachineFunctionAnalysisManager;
  1103. void verifyMachineFunction(MachineFunctionAnalysisManager *,
  1104. const std::string &Banner,
  1105. const MachineFunction &MF);
  1106. } // end namespace llvm
  1107. #endif // LLVM_CODEGEN_MACHINEFUNCTION_H
  1108. #ifdef __GNUC__
  1109. #pragma GCC diagnostic pop
  1110. #endif