TargetRegisterInfo.h 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  1. //==- CodeGen/TargetRegisterInfo.h - Target Register Information -*- C++ -*-==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file describes an abstract interface used to get information about a
  10. // target machines register file. This information is used for a variety of
  11. // purposed, especially register allocation.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_CODEGEN_TARGETREGISTERINFO_H
  15. #define LLVM_CODEGEN_TARGETREGISTERINFO_H
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/ADT/iterator_range.h"
  20. #include "llvm/CodeGen/MachineBasicBlock.h"
  21. #include "llvm/IR/CallingConv.h"
  22. #include "llvm/MC/LaneBitmask.h"
  23. #include "llvm/MC/MCRegisterInfo.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/MachineValueType.h"
  26. #include "llvm/Support/MathExtras.h"
  27. #include "llvm/Support/Printable.h"
  28. #include <cassert>
  29. #include <cstdint>
  30. #include <functional>
  31. namespace llvm {
  32. class BitVector;
  33. class DIExpression;
  34. class LiveRegMatrix;
  35. class MachineFunction;
  36. class MachineInstr;
  37. class RegScavenger;
  38. class VirtRegMap;
  39. class LiveIntervals;
  40. class LiveInterval;
  41. class TargetRegisterClass {
  42. public:
  43. using iterator = const MCPhysReg *;
  44. using const_iterator = const MCPhysReg *;
  45. using sc_iterator = const TargetRegisterClass* const *;
  46. // Instance variables filled by tablegen, do not use!
  47. const MCRegisterClass *MC;
  48. const uint32_t *SubClassMask;
  49. const uint16_t *SuperRegIndices;
  50. const LaneBitmask LaneMask;
  51. /// Classes with a higher priority value are assigned first by register
  52. /// allocators using a greedy heuristic. The value is in the range [0,63].
  53. const uint8_t AllocationPriority;
  54. /// Whether the class supports two (or more) disjunct subregister indices.
  55. const bool HasDisjunctSubRegs;
  56. /// Whether a combination of subregisters can cover every register in the
  57. /// class. See also the CoveredBySubRegs description in Target.td.
  58. const bool CoveredBySubRegs;
  59. const sc_iterator SuperClasses;
  60. ArrayRef<MCPhysReg> (*OrderFunc)(const MachineFunction&);
  61. /// Return the register class ID number.
  62. unsigned getID() const { return MC->getID(); }
  63. /// begin/end - Return all of the registers in this class.
  64. ///
  65. iterator begin() const { return MC->begin(); }
  66. iterator end() const { return MC->end(); }
  67. /// Return the number of registers in this class.
  68. unsigned getNumRegs() const { return MC->getNumRegs(); }
  69. iterator_range<SmallVectorImpl<MCPhysReg>::const_iterator>
  70. getRegisters() const {
  71. return make_range(MC->begin(), MC->end());
  72. }
  73. /// Return the specified register in the class.
  74. MCRegister getRegister(unsigned i) const {
  75. return MC->getRegister(i);
  76. }
  77. /// Return true if the specified register is included in this register class.
  78. /// This does not include virtual registers.
  79. bool contains(Register Reg) const {
  80. /// FIXME: Historically this function has returned false when given vregs
  81. /// but it should probably only receive physical registers
  82. if (!Reg.isPhysical())
  83. return false;
  84. return MC->contains(Reg.asMCReg());
  85. }
  86. /// Return true if both registers are in this class.
  87. bool contains(Register Reg1, Register Reg2) const {
  88. /// FIXME: Historically this function has returned false when given a vregs
  89. /// but it should probably only receive physical registers
  90. if (!Reg1.isPhysical() || !Reg2.isPhysical())
  91. return false;
  92. return MC->contains(Reg1.asMCReg(), Reg2.asMCReg());
  93. }
  94. /// Return the cost of copying a value between two registers in this class.
  95. /// A negative number means the register class is very expensive
  96. /// to copy e.g. status flag register classes.
  97. int getCopyCost() const { return MC->getCopyCost(); }
  98. /// Return true if this register class may be used to create virtual
  99. /// registers.
  100. bool isAllocatable() const { return MC->isAllocatable(); }
  101. /// Return true if the specified TargetRegisterClass
  102. /// is a proper sub-class of this TargetRegisterClass.
  103. bool hasSubClass(const TargetRegisterClass *RC) const {
  104. return RC != this && hasSubClassEq(RC);
  105. }
  106. /// Returns true if RC is a sub-class of or equal to this class.
  107. bool hasSubClassEq(const TargetRegisterClass *RC) const {
  108. unsigned ID = RC->getID();
  109. return (SubClassMask[ID / 32] >> (ID % 32)) & 1;
  110. }
  111. /// Return true if the specified TargetRegisterClass is a
  112. /// proper super-class of this TargetRegisterClass.
  113. bool hasSuperClass(const TargetRegisterClass *RC) const {
  114. return RC->hasSubClass(this);
  115. }
  116. /// Returns true if RC is a super-class of or equal to this class.
  117. bool hasSuperClassEq(const TargetRegisterClass *RC) const {
  118. return RC->hasSubClassEq(this);
  119. }
  120. /// Returns a bit vector of subclasses, including this one.
  121. /// The vector is indexed by class IDs.
  122. ///
  123. /// To use it, consider the returned array as a chunk of memory that
  124. /// contains an array of bits of size NumRegClasses. Each 32-bit chunk
  125. /// contains a bitset of the ID of the subclasses in big-endian style.
  126. /// I.e., the representation of the memory from left to right at the
  127. /// bit level looks like:
  128. /// [31 30 ... 1 0] [ 63 62 ... 33 32] ...
  129. /// [ XXX NumRegClasses NumRegClasses - 1 ... ]
  130. /// Where the number represents the class ID and XXX bits that
  131. /// should be ignored.
  132. ///
  133. /// See the implementation of hasSubClassEq for an example of how it
  134. /// can be used.
  135. const uint32_t *getSubClassMask() const {
  136. return SubClassMask;
  137. }
  138. /// Returns a 0-terminated list of sub-register indices that project some
  139. /// super-register class into this register class. The list has an entry for
  140. /// each Idx such that:
  141. ///
  142. /// There exists SuperRC where:
  143. /// For all Reg in SuperRC:
  144. /// this->contains(Reg:Idx)
  145. const uint16_t *getSuperRegIndices() const {
  146. return SuperRegIndices;
  147. }
  148. /// Returns a NULL-terminated list of super-classes. The
  149. /// classes are ordered by ID which is also a topological ordering from large
  150. /// to small classes. The list does NOT include the current class.
  151. sc_iterator getSuperClasses() const {
  152. return SuperClasses;
  153. }
  154. /// Return true if this TargetRegisterClass is a subset
  155. /// class of at least one other TargetRegisterClass.
  156. bool isASubClass() const {
  157. return SuperClasses[0] != nullptr;
  158. }
  159. /// Returns the preferred order for allocating registers from this register
  160. /// class in MF. The raw order comes directly from the .td file and may
  161. /// include reserved registers that are not allocatable.
  162. /// Register allocators should also make sure to allocate
  163. /// callee-saved registers only after all the volatiles are used. The
  164. /// RegisterClassInfo class provides filtered allocation orders with
  165. /// callee-saved registers moved to the end.
  166. ///
  167. /// The MachineFunction argument can be used to tune the allocatable
  168. /// registers based on the characteristics of the function, subtarget, or
  169. /// other criteria.
  170. ///
  171. /// By default, this method returns all registers in the class.
  172. ArrayRef<MCPhysReg> getRawAllocationOrder(const MachineFunction &MF) const {
  173. return OrderFunc ? OrderFunc(MF) : makeArrayRef(begin(), getNumRegs());
  174. }
  175. /// Returns the combination of all lane masks of register in this class.
  176. /// The lane masks of the registers are the combination of all lane masks
  177. /// of their subregisters. Returns 1 if there are no subregisters.
  178. LaneBitmask getLaneMask() const {
  179. return LaneMask;
  180. }
  181. };
  182. /// Extra information, not in MCRegisterDesc, about registers.
  183. /// These are used by codegen, not by MC.
  184. struct TargetRegisterInfoDesc {
  185. const uint8_t *CostPerUse; // Extra cost of instructions using register.
  186. unsigned NumCosts; // Number of cost values associated with each register.
  187. const bool
  188. *InAllocatableClass; // Register belongs to an allocatable regclass.
  189. };
  190. /// Each TargetRegisterClass has a per register weight, and weight
  191. /// limit which must be less than the limits of its pressure sets.
  192. struct RegClassWeight {
  193. unsigned RegWeight;
  194. unsigned WeightLimit;
  195. };
  196. /// TargetRegisterInfo base class - We assume that the target defines a static
  197. /// array of TargetRegisterDesc objects that represent all of the machine
  198. /// registers that the target has. As such, we simply have to track a pointer
  199. /// to this array so that we can turn register number into a register
  200. /// descriptor.
  201. ///
  202. class TargetRegisterInfo : public MCRegisterInfo {
  203. public:
  204. using regclass_iterator = const TargetRegisterClass * const *;
  205. using vt_iterator = const MVT::SimpleValueType *;
  206. struct RegClassInfo {
  207. unsigned RegSize, SpillSize, SpillAlignment;
  208. vt_iterator VTList;
  209. };
  210. private:
  211. const TargetRegisterInfoDesc *InfoDesc; // Extra desc array for codegen
  212. const char *const *SubRegIndexNames; // Names of subreg indexes.
  213. // Pointer to array of lane masks, one per sub-reg index.
  214. const LaneBitmask *SubRegIndexLaneMasks;
  215. regclass_iterator RegClassBegin, RegClassEnd; // List of regclasses
  216. LaneBitmask CoveringLanes;
  217. const RegClassInfo *const RCInfos;
  218. unsigned HwMode;
  219. protected:
  220. TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
  221. regclass_iterator RCB,
  222. regclass_iterator RCE,
  223. const char *const *SRINames,
  224. const LaneBitmask *SRILaneMasks,
  225. LaneBitmask CoveringLanes,
  226. const RegClassInfo *const RCIs,
  227. unsigned Mode = 0);
  228. virtual ~TargetRegisterInfo();
  229. public:
  230. // Register numbers can represent physical registers, virtual registers, and
  231. // sometimes stack slots. The unsigned values are divided into these ranges:
  232. //
  233. // 0 Not a register, can be used as a sentinel.
  234. // [1;2^30) Physical registers assigned by TableGen.
  235. // [2^30;2^31) Stack slots. (Rarely used.)
  236. // [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
  237. //
  238. // Further sentinels can be allocated from the small negative integers.
  239. // DenseMapInfo<unsigned> uses -1u and -2u.
  240. /// Return the size in bits of a register from class RC.
  241. unsigned getRegSizeInBits(const TargetRegisterClass &RC) const {
  242. return getRegClassInfo(RC).RegSize;
  243. }
  244. /// Return the size in bytes of the stack slot allocated to hold a spilled
  245. /// copy of a register from class RC.
  246. unsigned getSpillSize(const TargetRegisterClass &RC) const {
  247. return getRegClassInfo(RC).SpillSize / 8;
  248. }
  249. /// Return the minimum required alignment in bytes for a spill slot for
  250. /// a register of this class.
  251. Align getSpillAlign(const TargetRegisterClass &RC) const {
  252. return Align(getRegClassInfo(RC).SpillAlignment / 8);
  253. }
  254. /// Return true if the given TargetRegisterClass has the ValueType T.
  255. bool isTypeLegalForClass(const TargetRegisterClass &RC, MVT T) const {
  256. for (auto I = legalclasstypes_begin(RC); *I != MVT::Other; ++I)
  257. if (MVT(*I) == T)
  258. return true;
  259. return false;
  260. }
  261. /// Return true if the given TargetRegisterClass is compatible with LLT T.
  262. bool isTypeLegalForClass(const TargetRegisterClass &RC, LLT T) const {
  263. for (auto I = legalclasstypes_begin(RC); *I != MVT::Other; ++I) {
  264. MVT VT(*I);
  265. if (VT == MVT::Untyped)
  266. return true;
  267. if (LLT(VT) == T)
  268. return true;
  269. }
  270. return false;
  271. }
  272. /// Loop over all of the value types that can be represented by values
  273. /// in the given register class.
  274. vt_iterator legalclasstypes_begin(const TargetRegisterClass &RC) const {
  275. return getRegClassInfo(RC).VTList;
  276. }
  277. vt_iterator legalclasstypes_end(const TargetRegisterClass &RC) const {
  278. vt_iterator I = legalclasstypes_begin(RC);
  279. while (*I != MVT::Other)
  280. ++I;
  281. return I;
  282. }
  283. /// Returns the Register Class of a physical register of the given type,
  284. /// picking the most sub register class of the right type that contains this
  285. /// physreg.
  286. const TargetRegisterClass *getMinimalPhysRegClass(MCRegister Reg,
  287. MVT VT = MVT::Other) const;
  288. /// Returns the Register Class of a physical register of the given type,
  289. /// picking the most sub register class of the right type that contains this
  290. /// physreg. If there is no register class compatible with the given type,
  291. /// returns nullptr.
  292. const TargetRegisterClass *getMinimalPhysRegClassLLT(MCRegister Reg,
  293. LLT Ty = LLT()) const;
  294. /// Return the maximal subclass of the given register class that is
  295. /// allocatable or NULL.
  296. const TargetRegisterClass *
  297. getAllocatableClass(const TargetRegisterClass *RC) const;
  298. /// Returns a bitset indexed by register number indicating if a register is
  299. /// allocatable or not. If a register class is specified, returns the subset
  300. /// for the class.
  301. BitVector getAllocatableSet(const MachineFunction &MF,
  302. const TargetRegisterClass *RC = nullptr) const;
  303. /// Get a list of cost values for all registers that correspond to the index
  304. /// returned by RegisterCostTableIndex.
  305. ArrayRef<uint8_t> getRegisterCosts(const MachineFunction &MF) const {
  306. unsigned Idx = getRegisterCostTableIndex(MF);
  307. unsigned NumRegs = getNumRegs();
  308. assert(Idx < InfoDesc->NumCosts && "CostPerUse index out of bounds");
  309. return makeArrayRef(&InfoDesc->CostPerUse[Idx * NumRegs], NumRegs);
  310. }
  311. /// Return true if the register is in the allocation of any register class.
  312. bool isInAllocatableClass(MCRegister RegNo) const {
  313. return InfoDesc->InAllocatableClass[RegNo];
  314. }
  315. /// Return the human-readable symbolic target-specific
  316. /// name for the specified SubRegIndex.
  317. const char *getSubRegIndexName(unsigned SubIdx) const {
  318. assert(SubIdx && SubIdx < getNumSubRegIndices() &&
  319. "This is not a subregister index");
  320. return SubRegIndexNames[SubIdx-1];
  321. }
  322. /// Return a bitmask representing the parts of a register that are covered by
  323. /// SubIdx \see LaneBitmask.
  324. ///
  325. /// SubIdx == 0 is allowed, it has the lane mask ~0u.
  326. LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const {
  327. assert(SubIdx < getNumSubRegIndices() && "This is not a subregister index");
  328. return SubRegIndexLaneMasks[SubIdx];
  329. }
  330. /// Try to find one or more subregister indexes to cover \p LaneMask.
  331. ///
  332. /// If this is possible, returns true and appends the best matching set of
  333. /// indexes to \p Indexes. If this is not possible, returns false.
  334. bool getCoveringSubRegIndexes(const MachineRegisterInfo &MRI,
  335. const TargetRegisterClass *RC,
  336. LaneBitmask LaneMask,
  337. SmallVectorImpl<unsigned> &Indexes) const;
  338. /// The lane masks returned by getSubRegIndexLaneMask() above can only be
  339. /// used to determine if sub-registers overlap - they can't be used to
  340. /// determine if a set of sub-registers completely cover another
  341. /// sub-register.
  342. ///
  343. /// The X86 general purpose registers have two lanes corresponding to the
  344. /// sub_8bit and sub_8bit_hi sub-registers. Both sub_32bit and sub_16bit have
  345. /// lane masks '3', but the sub_16bit sub-register doesn't fully cover the
  346. /// sub_32bit sub-register.
  347. ///
  348. /// On the other hand, the ARM NEON lanes fully cover their registers: The
  349. /// dsub_0 sub-register is completely covered by the ssub_0 and ssub_1 lanes.
  350. /// This is related to the CoveredBySubRegs property on register definitions.
  351. ///
  352. /// This function returns a bit mask of lanes that completely cover their
  353. /// sub-registers. More precisely, given:
  354. ///
  355. /// Covering = getCoveringLanes();
  356. /// MaskA = getSubRegIndexLaneMask(SubA);
  357. /// MaskB = getSubRegIndexLaneMask(SubB);
  358. ///
  359. /// If (MaskA & ~(MaskB & Covering)) == 0, then SubA is completely covered by
  360. /// SubB.
  361. LaneBitmask getCoveringLanes() const { return CoveringLanes; }
  362. /// Returns true if the two registers are equal or alias each other.
  363. /// The registers may be virtual registers.
  364. bool regsOverlap(Register regA, Register regB) const {
  365. if (regA == regB) return true;
  366. if (!regA.isPhysical() || !regB.isPhysical())
  367. return false;
  368. // Regunits are numerically ordered. Find a common unit.
  369. MCRegUnitIterator RUA(regA.asMCReg(), this);
  370. MCRegUnitIterator RUB(regB.asMCReg(), this);
  371. do {
  372. if (*RUA == *RUB) return true;
  373. if (*RUA < *RUB) ++RUA;
  374. else ++RUB;
  375. } while (RUA.isValid() && RUB.isValid());
  376. return false;
  377. }
  378. /// Returns true if Reg contains RegUnit.
  379. bool hasRegUnit(MCRegister Reg, Register RegUnit) const {
  380. for (MCRegUnitIterator Units(Reg, this); Units.isValid(); ++Units)
  381. if (Register(*Units) == RegUnit)
  382. return true;
  383. return false;
  384. }
  385. /// Returns the original SrcReg unless it is the target of a copy-like
  386. /// operation, in which case we chain backwards through all such operations
  387. /// to the ultimate source register. If a physical register is encountered,
  388. /// we stop the search.
  389. virtual Register lookThruCopyLike(Register SrcReg,
  390. const MachineRegisterInfo *MRI) const;
  391. /// Find the original SrcReg unless it is the target of a copy-like operation,
  392. /// in which case we chain backwards through all such operations to the
  393. /// ultimate source register. If a physical register is encountered, we stop
  394. /// the search.
  395. /// Return the original SrcReg if all the definitions in the chain only have
  396. /// one user and not a physical register.
  397. virtual Register
  398. lookThruSingleUseCopyChain(Register SrcReg,
  399. const MachineRegisterInfo *MRI) const;
  400. /// Return a null-terminated list of all of the callee-saved registers on
  401. /// this target. The register should be in the order of desired callee-save
  402. /// stack frame offset. The first register is closest to the incoming stack
  403. /// pointer if stack grows down, and vice versa.
  404. /// Notice: This function does not take into account disabled CSRs.
  405. /// In most cases you will want to use instead the function
  406. /// getCalleeSavedRegs that is implemented in MachineRegisterInfo.
  407. virtual const MCPhysReg*
  408. getCalleeSavedRegs(const MachineFunction *MF) const = 0;
  409. /// Return a mask of call-preserved registers for the given calling convention
  410. /// on the current function. The mask should include all call-preserved
  411. /// aliases. This is used by the register allocator to determine which
  412. /// registers can be live across a call.
  413. ///
  414. /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries.
  415. /// A set bit indicates that all bits of the corresponding register are
  416. /// preserved across the function call. The bit mask is expected to be
  417. /// sub-register complete, i.e. if A is preserved, so are all its
  418. /// sub-registers.
  419. ///
  420. /// Bits are numbered from the LSB, so the bit for physical register Reg can
  421. /// be found as (Mask[Reg / 32] >> Reg % 32) & 1.
  422. ///
  423. /// A NULL pointer means that no register mask will be used, and call
  424. /// instructions should use implicit-def operands to indicate call clobbered
  425. /// registers.
  426. ///
  427. virtual const uint32_t *getCallPreservedMask(const MachineFunction &MF,
  428. CallingConv::ID) const {
  429. // The default mask clobbers everything. All targets should override.
  430. return nullptr;
  431. }
  432. /// Return a register mask for the registers preserved by the unwinder,
  433. /// or nullptr if no custom mask is needed.
  434. virtual const uint32_t *
  435. getCustomEHPadPreservedMask(const MachineFunction &MF) const {
  436. return nullptr;
  437. }
  438. /// Return a register mask that clobbers everything.
  439. virtual const uint32_t *getNoPreservedMask() const {
  440. llvm_unreachable("target does not provide no preserved mask");
  441. }
  442. /// Return a list of all of the registers which are clobbered "inside" a call
  443. /// to the given function. For example, these might be needed for PLT
  444. /// sequences of long-branch veneers.
  445. virtual ArrayRef<MCPhysReg>
  446. getIntraCallClobberedRegs(const MachineFunction *MF) const {
  447. return {};
  448. }
  449. /// Return true if all bits that are set in mask \p mask0 are also set in
  450. /// \p mask1.
  451. bool regmaskSubsetEqual(const uint32_t *mask0, const uint32_t *mask1) const;
  452. /// Return all the call-preserved register masks defined for this target.
  453. virtual ArrayRef<const uint32_t *> getRegMasks() const = 0;
  454. virtual ArrayRef<const char *> getRegMaskNames() const = 0;
  455. /// Returns a bitset indexed by physical register number indicating if a
  456. /// register is a special register that has particular uses and should be
  457. /// considered unavailable at all times, e.g. stack pointer, return address.
  458. /// A reserved register:
  459. /// - is not allocatable
  460. /// - is considered always live
  461. /// - is ignored by liveness tracking
  462. /// It is often necessary to reserve the super registers of a reserved
  463. /// register as well, to avoid them getting allocated indirectly. You may use
  464. /// markSuperRegs() and checkAllSuperRegsMarked() in this case.
  465. virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
  466. /// Returns false if we can't guarantee that Physreg, specified as an IR asm
  467. /// clobber constraint, will be preserved across the statement.
  468. virtual bool isAsmClobberable(const MachineFunction &MF,
  469. MCRegister PhysReg) const {
  470. return true;
  471. }
  472. /// Returns true if PhysReg cannot be written to in inline asm statements.
  473. virtual bool isInlineAsmReadOnlyReg(const MachineFunction &MF,
  474. unsigned PhysReg) const {
  475. return false;
  476. }
  477. /// Returns true if PhysReg is unallocatable and constant throughout the
  478. /// function. Used by MachineRegisterInfo::isConstantPhysReg().
  479. virtual bool isConstantPhysReg(MCRegister PhysReg) const { return false; }
  480. /// Returns true if the register class is considered divergent.
  481. virtual bool isDivergentRegClass(const TargetRegisterClass *RC) const {
  482. return false;
  483. }
  484. /// Physical registers that may be modified within a function but are
  485. /// guaranteed to be restored before any uses. This is useful for targets that
  486. /// have call sequences where a GOT register may be updated by the caller
  487. /// prior to a call and is guaranteed to be restored (also by the caller)
  488. /// after the call.
  489. virtual bool isCallerPreservedPhysReg(MCRegister PhysReg,
  490. const MachineFunction &MF) const {
  491. return false;
  492. }
  493. /// This is a wrapper around getCallPreservedMask().
  494. /// Return true if the register is preserved after the call.
  495. virtual bool isCalleeSavedPhysReg(MCRegister PhysReg,
  496. const MachineFunction &MF) const;
  497. /// Prior to adding the live-out mask to a stackmap or patchpoint
  498. /// instruction, provide the target the opportunity to adjust it (mainly to
  499. /// remove pseudo-registers that should be ignored).
  500. virtual void adjustStackMapLiveOutMask(uint32_t *Mask) const {}
  501. /// Return a super-register of the specified register
  502. /// Reg so its sub-register of index SubIdx is Reg.
  503. MCRegister getMatchingSuperReg(MCRegister Reg, unsigned SubIdx,
  504. const TargetRegisterClass *RC) const {
  505. return MCRegisterInfo::getMatchingSuperReg(Reg, SubIdx, RC->MC);
  506. }
  507. /// Return a subclass of the specified register
  508. /// class A so that each register in it has a sub-register of the
  509. /// specified sub-register index which is in the specified register class B.
  510. ///
  511. /// TableGen will synthesize missing A sub-classes.
  512. virtual const TargetRegisterClass *
  513. getMatchingSuperRegClass(const TargetRegisterClass *A,
  514. const TargetRegisterClass *B, unsigned Idx) const;
  515. // For a copy-like instruction that defines a register of class DefRC with
  516. // subreg index DefSubReg, reading from another source with class SrcRC and
  517. // subregister SrcSubReg return true if this is a preferable copy
  518. // instruction or an earlier use should be used.
  519. virtual bool shouldRewriteCopySrc(const TargetRegisterClass *DefRC,
  520. unsigned DefSubReg,
  521. const TargetRegisterClass *SrcRC,
  522. unsigned SrcSubReg) const;
  523. /// Returns the largest legal sub-class of RC that
  524. /// supports the sub-register index Idx.
  525. /// If no such sub-class exists, return NULL.
  526. /// If all registers in RC already have an Idx sub-register, return RC.
  527. ///
  528. /// TableGen generates a version of this function that is good enough in most
  529. /// cases. Targets can override if they have constraints that TableGen
  530. /// doesn't understand. For example, the x86 sub_8bit sub-register index is
  531. /// supported by the full GR32 register class in 64-bit mode, but only by the
  532. /// GR32_ABCD regiister class in 32-bit mode.
  533. ///
  534. /// TableGen will synthesize missing RC sub-classes.
  535. virtual const TargetRegisterClass *
  536. getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const {
  537. assert(Idx == 0 && "Target has no sub-registers");
  538. return RC;
  539. }
  540. /// Return the subregister index you get from composing
  541. /// two subregister indices.
  542. ///
  543. /// The special null sub-register index composes as the identity.
  544. ///
  545. /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
  546. /// returns c. Note that composeSubRegIndices does not tell you about illegal
  547. /// compositions. If R does not have a subreg a, or R:a does not have a subreg
  548. /// b, composeSubRegIndices doesn't tell you.
  549. ///
  550. /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
  551. /// ssub_0:S0 - ssub_3:S3 subregs.
  552. /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
  553. unsigned composeSubRegIndices(unsigned a, unsigned b) const {
  554. if (!a) return b;
  555. if (!b) return a;
  556. return composeSubRegIndicesImpl(a, b);
  557. }
  558. /// Transforms a LaneMask computed for one subregister to the lanemask that
  559. /// would have been computed when composing the subsubregisters with IdxA
  560. /// first. @sa composeSubRegIndices()
  561. LaneBitmask composeSubRegIndexLaneMask(unsigned IdxA,
  562. LaneBitmask Mask) const {
  563. if (!IdxA)
  564. return Mask;
  565. return composeSubRegIndexLaneMaskImpl(IdxA, Mask);
  566. }
  567. /// Transform a lanemask given for a virtual register to the corresponding
  568. /// lanemask before using subregister with index \p IdxA.
  569. /// This is the reverse of composeSubRegIndexLaneMask(), assuming Mask is a
  570. /// valie lane mask (no invalid bits set) the following holds:
  571. /// X0 = composeSubRegIndexLaneMask(Idx, Mask)
  572. /// X1 = reverseComposeSubRegIndexLaneMask(Idx, X0)
  573. /// => X1 == Mask
  574. LaneBitmask reverseComposeSubRegIndexLaneMask(unsigned IdxA,
  575. LaneBitmask LaneMask) const {
  576. if (!IdxA)
  577. return LaneMask;
  578. return reverseComposeSubRegIndexLaneMaskImpl(IdxA, LaneMask);
  579. }
  580. /// Debugging helper: dump register in human readable form to dbgs() stream.
  581. static void dumpReg(Register Reg, unsigned SubRegIndex = 0,
  582. const TargetRegisterInfo *TRI = nullptr);
  583. protected:
  584. /// Overridden by TableGen in targets that have sub-registers.
  585. virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const {
  586. llvm_unreachable("Target has no sub-registers");
  587. }
  588. /// Overridden by TableGen in targets that have sub-registers.
  589. virtual LaneBitmask
  590. composeSubRegIndexLaneMaskImpl(unsigned, LaneBitmask) const {
  591. llvm_unreachable("Target has no sub-registers");
  592. }
  593. virtual LaneBitmask reverseComposeSubRegIndexLaneMaskImpl(unsigned,
  594. LaneBitmask) const {
  595. llvm_unreachable("Target has no sub-registers");
  596. }
  597. /// Return the register cost table index. This implementation is sufficient
  598. /// for most architectures and can be overriden by targets in case there are
  599. /// multiple cost values associated with each register.
  600. virtual unsigned getRegisterCostTableIndex(const MachineFunction &MF) const {
  601. return 0;
  602. }
  603. public:
  604. /// Find a common super-register class if it exists.
  605. ///
  606. /// Find a register class, SuperRC and two sub-register indices, PreA and
  607. /// PreB, such that:
  608. ///
  609. /// 1. PreA + SubA == PreB + SubB (using composeSubRegIndices()), and
  610. ///
  611. /// 2. For all Reg in SuperRC: Reg:PreA in RCA and Reg:PreB in RCB, and
  612. ///
  613. /// 3. SuperRC->getSize() >= max(RCA->getSize(), RCB->getSize()).
  614. ///
  615. /// SuperRC will be chosen such that no super-class of SuperRC satisfies the
  616. /// requirements, and there is no register class with a smaller spill size
  617. /// that satisfies the requirements.
  618. ///
  619. /// SubA and SubB must not be 0. Use getMatchingSuperRegClass() instead.
  620. ///
  621. /// Either of the PreA and PreB sub-register indices may be returned as 0. In
  622. /// that case, the returned register class will be a sub-class of the
  623. /// corresponding argument register class.
  624. ///
  625. /// The function returns NULL if no register class can be found.
  626. const TargetRegisterClass*
  627. getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
  628. const TargetRegisterClass *RCB, unsigned SubB,
  629. unsigned &PreA, unsigned &PreB) const;
  630. //===--------------------------------------------------------------------===//
  631. // Register Class Information
  632. //
  633. protected:
  634. const RegClassInfo &getRegClassInfo(const TargetRegisterClass &RC) const {
  635. return RCInfos[getNumRegClasses() * HwMode + RC.getID()];
  636. }
  637. public:
  638. /// Register class iterators
  639. regclass_iterator regclass_begin() const { return RegClassBegin; }
  640. regclass_iterator regclass_end() const { return RegClassEnd; }
  641. iterator_range<regclass_iterator> regclasses() const {
  642. return make_range(regclass_begin(), regclass_end());
  643. }
  644. unsigned getNumRegClasses() const {
  645. return (unsigned)(regclass_end()-regclass_begin());
  646. }
  647. /// Returns the register class associated with the enumeration value.
  648. /// See class MCOperandInfo.
  649. const TargetRegisterClass *getRegClass(unsigned i) const {
  650. assert(i < getNumRegClasses() && "Register Class ID out of range");
  651. return RegClassBegin[i];
  652. }
  653. /// Returns the name of the register class.
  654. const char *getRegClassName(const TargetRegisterClass *Class) const {
  655. return MCRegisterInfo::getRegClassName(Class->MC);
  656. }
  657. /// Find the largest common subclass of A and B.
  658. /// Return NULL if there is no common subclass.
  659. const TargetRegisterClass *
  660. getCommonSubClass(const TargetRegisterClass *A,
  661. const TargetRegisterClass *B) const;
  662. /// Returns a TargetRegisterClass used for pointer values.
  663. /// If a target supports multiple different pointer register classes,
  664. /// kind specifies which one is indicated.
  665. virtual const TargetRegisterClass *
  666. getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const {
  667. llvm_unreachable("Target didn't implement getPointerRegClass!");
  668. }
  669. /// Returns a legal register class to copy a register in the specified class
  670. /// to or from. If it is possible to copy the register directly without using
  671. /// a cross register class copy, return the specified RC. Returns NULL if it
  672. /// is not possible to copy between two registers of the specified class.
  673. virtual const TargetRegisterClass *
  674. getCrossCopyRegClass(const TargetRegisterClass *RC) const {
  675. return RC;
  676. }
  677. /// Returns the largest super class of RC that is legal to use in the current
  678. /// sub-target and has the same spill size.
  679. /// The returned register class can be used to create virtual registers which
  680. /// means that all its registers can be copied and spilled.
  681. virtual const TargetRegisterClass *
  682. getLargestLegalSuperClass(const TargetRegisterClass *RC,
  683. const MachineFunction &) const {
  684. /// The default implementation is very conservative and doesn't allow the
  685. /// register allocator to inflate register classes.
  686. return RC;
  687. }
  688. /// Return the register pressure "high water mark" for the specific register
  689. /// class. The scheduler is in high register pressure mode (for the specific
  690. /// register class) if it goes over the limit.
  691. ///
  692. /// Note: this is the old register pressure model that relies on a manually
  693. /// specified representative register class per value type.
  694. virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
  695. MachineFunction &MF) const {
  696. return 0;
  697. }
  698. /// Return a heuristic for the machine scheduler to compare the profitability
  699. /// of increasing one register pressure set versus another. The scheduler
  700. /// will prefer increasing the register pressure of the set which returns
  701. /// the largest value for this function.
  702. virtual unsigned getRegPressureSetScore(const MachineFunction &MF,
  703. unsigned PSetID) const {
  704. return PSetID;
  705. }
  706. /// Get the weight in units of pressure for this register class.
  707. virtual const RegClassWeight &getRegClassWeight(
  708. const TargetRegisterClass *RC) const = 0;
  709. /// Returns size in bits of a phys/virtual/generic register.
  710. unsigned getRegSizeInBits(Register Reg, const MachineRegisterInfo &MRI) const;
  711. /// Get the weight in units of pressure for this register unit.
  712. virtual unsigned getRegUnitWeight(unsigned RegUnit) const = 0;
  713. /// Get the number of dimensions of register pressure.
  714. virtual unsigned getNumRegPressureSets() const = 0;
  715. /// Get the name of this register unit pressure set.
  716. virtual const char *getRegPressureSetName(unsigned Idx) const = 0;
  717. /// Get the register unit pressure limit for this dimension.
  718. /// This limit must be adjusted dynamically for reserved registers.
  719. virtual unsigned getRegPressureSetLimit(const MachineFunction &MF,
  720. unsigned Idx) const = 0;
  721. /// Get the dimensions of register pressure impacted by this register class.
  722. /// Returns a -1 terminated array of pressure set IDs.
  723. virtual const int *getRegClassPressureSets(
  724. const TargetRegisterClass *RC) const = 0;
  725. /// Get the dimensions of register pressure impacted by this register unit.
  726. /// Returns a -1 terminated array of pressure set IDs.
  727. virtual const int *getRegUnitPressureSets(unsigned RegUnit) const = 0;
  728. /// Get a list of 'hint' registers that the register allocator should try
  729. /// first when allocating a physical register for the virtual register
  730. /// VirtReg. These registers are effectively moved to the front of the
  731. /// allocation order. If true is returned, regalloc will try to only use
  732. /// hints to the greatest extent possible even if it means spilling.
  733. ///
  734. /// The Order argument is the allocation order for VirtReg's register class
  735. /// as returned from RegisterClassInfo::getOrder(). The hint registers must
  736. /// come from Order, and they must not be reserved.
  737. ///
  738. /// The default implementation of this function will only add target
  739. /// independent register allocation hints. Targets that override this
  740. /// function should typically call this default implementation as well and
  741. /// expect to see generic copy hints added.
  742. virtual bool
  743. getRegAllocationHints(Register VirtReg, ArrayRef<MCPhysReg> Order,
  744. SmallVectorImpl<MCPhysReg> &Hints,
  745. const MachineFunction &MF,
  746. const VirtRegMap *VRM = nullptr,
  747. const LiveRegMatrix *Matrix = nullptr) const;
  748. /// A callback to allow target a chance to update register allocation hints
  749. /// when a register is "changed" (e.g. coalesced) to another register.
  750. /// e.g. On ARM, some virtual registers should target register pairs,
  751. /// if one of pair is coalesced to another register, the allocation hint of
  752. /// the other half of the pair should be changed to point to the new register.
  753. virtual void updateRegAllocHint(Register Reg, Register NewReg,
  754. MachineFunction &MF) const {
  755. // Do nothing.
  756. }
  757. /// Allow the target to reverse allocation order of local live ranges. This
  758. /// will generally allocate shorter local live ranges first. For targets with
  759. /// many registers, this could reduce regalloc compile time by a large
  760. /// factor. It is disabled by default for three reasons:
  761. /// (1) Top-down allocation is simpler and easier to debug for targets that
  762. /// don't benefit from reversing the order.
  763. /// (2) Bottom-up allocation could result in poor evicition decisions on some
  764. /// targets affecting the performance of compiled code.
  765. /// (3) Bottom-up allocation is no longer guaranteed to optimally color.
  766. virtual bool reverseLocalAssignment() const { return false; }
  767. /// Allow the target to override the cost of using a callee-saved register for
  768. /// the first time. Default value of 0 means we will use a callee-saved
  769. /// register if it is available.
  770. virtual unsigned getCSRFirstUseCost() const { return 0; }
  771. /// Returns true if the target requires (and can make use of) the register
  772. /// scavenger.
  773. virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
  774. return false;
  775. }
  776. /// Returns true if the target wants to use frame pointer based accesses to
  777. /// spill to the scavenger emergency spill slot.
  778. virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
  779. return true;
  780. }
  781. /// Returns true if the target requires post PEI scavenging of registers for
  782. /// materializing frame index constants.
  783. virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
  784. return false;
  785. }
  786. /// Returns true if the target requires using the RegScavenger directly for
  787. /// frame elimination despite using requiresFrameIndexScavenging.
  788. virtual bool requiresFrameIndexReplacementScavenging(
  789. const MachineFunction &MF) const {
  790. return false;
  791. }
  792. /// Returns true if the target wants the LocalStackAllocation pass to be run
  793. /// and virtual base registers used for more efficient stack access.
  794. virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
  795. return false;
  796. }
  797. /// Return true if target has reserved a spill slot in the stack frame of
  798. /// the given function for the specified register. e.g. On x86, if the frame
  799. /// register is required, the first fixed stack object is reserved as its
  800. /// spill slot. This tells PEI not to create a new stack frame
  801. /// object for the given register. It should be called only after
  802. /// determineCalleeSaves().
  803. virtual bool hasReservedSpillSlot(const MachineFunction &MF, Register Reg,
  804. int &FrameIdx) const {
  805. return false;
  806. }
  807. /// Returns true if the live-ins should be tracked after register allocation.
  808. virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
  809. return true;
  810. }
  811. /// True if the stack can be realigned for the target.
  812. virtual bool canRealignStack(const MachineFunction &MF) const;
  813. /// True if storage within the function requires the stack pointer to be
  814. /// aligned more than the normal calling convention calls for.
  815. virtual bool shouldRealignStack(const MachineFunction &MF) const;
  816. /// True if stack realignment is required and still possible.
  817. bool hasStackRealignment(const MachineFunction &MF) const {
  818. return shouldRealignStack(MF) && canRealignStack(MF);
  819. }
  820. /// Get the offset from the referenced frame index in the instruction,
  821. /// if there is one.
  822. virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
  823. int Idx) const {
  824. return 0;
  825. }
  826. /// Returns true if the instruction's frame index reference would be better
  827. /// served by a base register other than FP or SP.
  828. /// Used by LocalStackFrameAllocation to determine which frame index
  829. /// references it should create new base registers for.
  830. virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
  831. return false;
  832. }
  833. /// Insert defining instruction(s) for a pointer to FrameIdx before
  834. /// insertion point I. Return materialized frame pointer.
  835. virtual Register materializeFrameBaseRegister(MachineBasicBlock *MBB,
  836. int FrameIdx,
  837. int64_t Offset) const {
  838. llvm_unreachable("materializeFrameBaseRegister does not exist on this "
  839. "target");
  840. }
  841. /// Resolve a frame index operand of an instruction
  842. /// to reference the indicated base register plus offset instead.
  843. virtual void resolveFrameIndex(MachineInstr &MI, Register BaseReg,
  844. int64_t Offset) const {
  845. llvm_unreachable("resolveFrameIndex does not exist on this target");
  846. }
  847. /// Determine whether a given base register plus offset immediate is
  848. /// encodable to resolve a frame index.
  849. virtual bool isFrameOffsetLegal(const MachineInstr *MI, Register BaseReg,
  850. int64_t Offset) const {
  851. llvm_unreachable("isFrameOffsetLegal does not exist on this target");
  852. }
  853. /// Gets the DWARF expression opcodes for \p Offset.
  854. virtual void getOffsetOpcodes(const StackOffset &Offset,
  855. SmallVectorImpl<uint64_t> &Ops) const;
  856. /// Prepends a DWARF expression for \p Offset to DIExpression \p Expr.
  857. DIExpression *
  858. prependOffsetExpression(const DIExpression *Expr, unsigned PrependFlags,
  859. const StackOffset &Offset) const;
  860. /// Spill the register so it can be used by the register scavenger.
  861. /// Return true if the register was spilled, false otherwise.
  862. /// If this function does not spill the register, the scavenger
  863. /// will instead spill it to the emergency spill slot.
  864. virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
  865. MachineBasicBlock::iterator I,
  866. MachineBasicBlock::iterator &UseMI,
  867. const TargetRegisterClass *RC,
  868. Register Reg) const {
  869. return false;
  870. }
  871. /// This method must be overriden to eliminate abstract frame indices from
  872. /// instructions which may use them. The instruction referenced by the
  873. /// iterator contains an MO_FrameIndex operand which must be eliminated by
  874. /// this method. This method may modify or replace the specified instruction,
  875. /// as long as it keeps the iterator pointing at the finished product.
  876. /// SPAdj is the SP adjustment due to call frame setup instruction.
  877. /// FIOperandNum is the FI operand number.
  878. virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI,
  879. int SPAdj, unsigned FIOperandNum,
  880. RegScavenger *RS = nullptr) const = 0;
  881. /// Return the assembly name for \p Reg.
  882. virtual StringRef getRegAsmName(MCRegister Reg) const {
  883. // FIXME: We are assuming that the assembly name is equal to the TableGen
  884. // name converted to lower case
  885. //
  886. // The TableGen name is the name of the definition for this register in the
  887. // target's tablegen files. For example, the TableGen name of
  888. // def EAX : Register <...>; is "EAX"
  889. return StringRef(getName(Reg));
  890. }
  891. //===--------------------------------------------------------------------===//
  892. /// Subtarget Hooks
  893. /// SrcRC and DstRC will be morphed into NewRC if this returns true.
  894. virtual bool shouldCoalesce(MachineInstr *MI,
  895. const TargetRegisterClass *SrcRC,
  896. unsigned SubReg,
  897. const TargetRegisterClass *DstRC,
  898. unsigned DstSubReg,
  899. const TargetRegisterClass *NewRC,
  900. LiveIntervals &LIS) const
  901. { return true; }
  902. /// Region split has a high compile time cost especially for large live range.
  903. /// This method is used to decide whether or not \p VirtReg should
  904. /// go through this expensive splitting heuristic.
  905. virtual bool shouldRegionSplitForVirtReg(const MachineFunction &MF,
  906. const LiveInterval &VirtReg) const;
  907. /// Last chance recoloring has a high compile time cost especially for
  908. /// targets with a lot of registers.
  909. /// This method is used to decide whether or not \p VirtReg should
  910. /// go through this expensive heuristic.
  911. /// When this target hook is hit, by returning false, there is a high
  912. /// chance that the register allocation will fail altogether (usually with
  913. /// "ran out of registers").
  914. /// That said, this error usually points to another problem in the
  915. /// optimization pipeline.
  916. virtual bool
  917. shouldUseLastChanceRecoloringForVirtReg(const MachineFunction &MF,
  918. const LiveInterval &VirtReg) const {
  919. return true;
  920. }
  921. /// Deferred spilling delays the spill insertion of a virtual register
  922. /// after every other allocation. By deferring the spilling, it is
  923. /// sometimes possible to eliminate that spilling altogether because
  924. /// something else could have been eliminated, thus leaving some space
  925. /// for the virtual register.
  926. /// However, this comes with a compile time impact because it adds one
  927. /// more stage to the greedy register allocator.
  928. /// This method is used to decide whether \p VirtReg should use the deferred
  929. /// spilling stage instead of being spilled right away.
  930. virtual bool
  931. shouldUseDeferredSpillingForVirtReg(const MachineFunction &MF,
  932. const LiveInterval &VirtReg) const {
  933. return false;
  934. }
  935. //===--------------------------------------------------------------------===//
  936. /// Debug information queries.
  937. /// getFrameRegister - This method should return the register used as a base
  938. /// for values allocated in the current stack frame.
  939. virtual Register getFrameRegister(const MachineFunction &MF) const = 0;
  940. /// Mark a register and all its aliases as reserved in the given set.
  941. void markSuperRegs(BitVector &RegisterSet, MCRegister Reg) const;
  942. /// Returns true if for every register in the set all super registers are part
  943. /// of the set as well.
  944. bool checkAllSuperRegsMarked(const BitVector &RegisterSet,
  945. ArrayRef<MCPhysReg> Exceptions = ArrayRef<MCPhysReg>()) const;
  946. virtual const TargetRegisterClass *
  947. getConstrainedRegClassForOperand(const MachineOperand &MO,
  948. const MachineRegisterInfo &MRI) const {
  949. return nullptr;
  950. }
  951. /// Returns the physical register number of sub-register "Index"
  952. /// for physical register RegNo. Return zero if the sub-register does not
  953. /// exist.
  954. inline MCRegister getSubReg(MCRegister Reg, unsigned Idx) const {
  955. return static_cast<const MCRegisterInfo *>(this)->getSubReg(Reg, Idx);
  956. }
  957. };
  958. //===----------------------------------------------------------------------===//
  959. // SuperRegClassIterator
  960. //===----------------------------------------------------------------------===//
  961. //
  962. // Iterate over the possible super-registers for a given register class. The
  963. // iterator will visit a list of pairs (Idx, Mask) corresponding to the
  964. // possible classes of super-registers.
  965. //
  966. // Each bit mask will have at least one set bit, and each set bit in Mask
  967. // corresponds to a SuperRC such that:
  968. //
  969. // For all Reg in SuperRC: Reg:Idx is in RC.
  970. //
  971. // The iterator can include (O, RC->getSubClassMask()) as the first entry which
  972. // also satisfies the above requirement, assuming Reg:0 == Reg.
  973. //
  974. class SuperRegClassIterator {
  975. const unsigned RCMaskWords;
  976. unsigned SubReg = 0;
  977. const uint16_t *Idx;
  978. const uint32_t *Mask;
  979. public:
  980. /// Create a SuperRegClassIterator that visits all the super-register classes
  981. /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry.
  982. SuperRegClassIterator(const TargetRegisterClass *RC,
  983. const TargetRegisterInfo *TRI,
  984. bool IncludeSelf = false)
  985. : RCMaskWords((TRI->getNumRegClasses() + 31) / 32),
  986. Idx(RC->getSuperRegIndices()), Mask(RC->getSubClassMask()) {
  987. if (!IncludeSelf)
  988. ++*this;
  989. }
  990. /// Returns true if this iterator is still pointing at a valid entry.
  991. bool isValid() const { return Idx; }
  992. /// Returns the current sub-register index.
  993. unsigned getSubReg() const { return SubReg; }
  994. /// Returns the bit mask of register classes that getSubReg() projects into
  995. /// RC.
  996. /// See TargetRegisterClass::getSubClassMask() for how to use it.
  997. const uint32_t *getMask() const { return Mask; }
  998. /// Advance iterator to the next entry.
  999. void operator++() {
  1000. assert(isValid() && "Cannot move iterator past end.");
  1001. Mask += RCMaskWords;
  1002. SubReg = *Idx++;
  1003. if (!SubReg)
  1004. Idx = nullptr;
  1005. }
  1006. };
  1007. //===----------------------------------------------------------------------===//
  1008. // BitMaskClassIterator
  1009. //===----------------------------------------------------------------------===//
  1010. /// This class encapuslates the logic to iterate over bitmask returned by
  1011. /// the various RegClass related APIs.
  1012. /// E.g., this class can be used to iterate over the subclasses provided by
  1013. /// TargetRegisterClass::getSubClassMask or SuperRegClassIterator::getMask.
  1014. class BitMaskClassIterator {
  1015. /// Total number of register classes.
  1016. const unsigned NumRegClasses;
  1017. /// Base index of CurrentChunk.
  1018. /// In other words, the number of bit we read to get at the
  1019. /// beginning of that chunck.
  1020. unsigned Base = 0;
  1021. /// Adjust base index of CurrentChunk.
  1022. /// Base index + how many bit we read within CurrentChunk.
  1023. unsigned Idx = 0;
  1024. /// Current register class ID.
  1025. unsigned ID = 0;
  1026. /// Mask we are iterating over.
  1027. const uint32_t *Mask;
  1028. /// Current chunk of the Mask we are traversing.
  1029. uint32_t CurrentChunk;
  1030. /// Move ID to the next set bit.
  1031. void moveToNextID() {
  1032. // If the current chunk of memory is empty, move to the next one,
  1033. // while making sure we do not go pass the number of register
  1034. // classes.
  1035. while (!CurrentChunk) {
  1036. // Move to the next chunk.
  1037. Base += 32;
  1038. if (Base >= NumRegClasses) {
  1039. ID = NumRegClasses;
  1040. return;
  1041. }
  1042. CurrentChunk = *++Mask;
  1043. Idx = Base;
  1044. }
  1045. // Otherwise look for the first bit set from the right
  1046. // (representation of the class ID is big endian).
  1047. // See getSubClassMask for more details on the representation.
  1048. unsigned Offset = countTrailingZeros(CurrentChunk);
  1049. // Add the Offset to the adjusted base number of this chunk: Idx.
  1050. // This is the ID of the register class.
  1051. ID = Idx + Offset;
  1052. // Consume the zeros, if any, and the bit we just read
  1053. // so that we are at the right spot for the next call.
  1054. // Do not do Offset + 1 because Offset may be 31 and 32
  1055. // will be UB for the shift, though in that case we could
  1056. // have make the chunk being equal to 0, but that would
  1057. // have introduced a if statement.
  1058. moveNBits(Offset);
  1059. moveNBits(1);
  1060. }
  1061. /// Move \p NumBits Bits forward in CurrentChunk.
  1062. void moveNBits(unsigned NumBits) {
  1063. assert(NumBits < 32 && "Undefined behavior spotted!");
  1064. // Consume the bit we read for the next call.
  1065. CurrentChunk >>= NumBits;
  1066. // Adjust the base for the chunk.
  1067. Idx += NumBits;
  1068. }
  1069. public:
  1070. /// Create a BitMaskClassIterator that visits all the register classes
  1071. /// represented by \p Mask.
  1072. ///
  1073. /// \pre \p Mask != nullptr
  1074. BitMaskClassIterator(const uint32_t *Mask, const TargetRegisterInfo &TRI)
  1075. : NumRegClasses(TRI.getNumRegClasses()), Mask(Mask), CurrentChunk(*Mask) {
  1076. // Move to the first ID.
  1077. moveToNextID();
  1078. }
  1079. /// Returns true if this iterator is still pointing at a valid entry.
  1080. bool isValid() const { return getID() != NumRegClasses; }
  1081. /// Returns the current register class ID.
  1082. unsigned getID() const { return ID; }
  1083. /// Advance iterator to the next entry.
  1084. void operator++() {
  1085. assert(isValid() && "Cannot move iterator past end.");
  1086. moveToNextID();
  1087. }
  1088. };
  1089. // This is useful when building IndexedMaps keyed on virtual registers
  1090. struct VirtReg2IndexFunctor {
  1091. using argument_type = Register;
  1092. unsigned operator()(Register Reg) const {
  1093. return Register::virtReg2Index(Reg);
  1094. }
  1095. };
  1096. /// Prints virtual and physical registers with or without a TRI instance.
  1097. ///
  1098. /// The format is:
  1099. /// %noreg - NoRegister
  1100. /// %5 - a virtual register.
  1101. /// %5:sub_8bit - a virtual register with sub-register index (with TRI).
  1102. /// %eax - a physical register
  1103. /// %physreg17 - a physical register when no TRI instance given.
  1104. ///
  1105. /// Usage: OS << printReg(Reg, TRI, SubRegIdx) << '\n';
  1106. Printable printReg(Register Reg, const TargetRegisterInfo *TRI = nullptr,
  1107. unsigned SubIdx = 0,
  1108. const MachineRegisterInfo *MRI = nullptr);
  1109. /// Create Printable object to print register units on a \ref raw_ostream.
  1110. ///
  1111. /// Register units are named after their root registers:
  1112. ///
  1113. /// al - Single root.
  1114. /// fp0~st7 - Dual roots.
  1115. ///
  1116. /// Usage: OS << printRegUnit(Unit, TRI) << '\n';
  1117. Printable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI);
  1118. /// Create Printable object to print virtual registers and physical
  1119. /// registers on a \ref raw_ostream.
  1120. Printable printVRegOrUnit(unsigned VRegOrUnit, const TargetRegisterInfo *TRI);
  1121. /// Create Printable object to print register classes or register banks
  1122. /// on a \ref raw_ostream.
  1123. Printable printRegClassOrBank(Register Reg, const MachineRegisterInfo &RegInfo,
  1124. const TargetRegisterInfo *TRI);
  1125. } // end namespace llvm
  1126. #endif // LLVM_CODEGEN_TARGETREGISTERINFO_H