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