Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:34

0001 //===- llvm/CodeGen/RegisterBankInfo.h --------------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 /// \file This file declares the API for the register bank info.
0010 /// This API is responsible for handling the register banks.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_CODEGEN_REGISTERBANKINFO_H
0015 #define LLVM_CODEGEN_REGISTERBANKINFO_H
0016 
0017 #include "llvm/ADT/DenseMap.h"
0018 #include "llvm/ADT/Hashing.h"
0019 #include "llvm/ADT/SmallVector.h"
0020 #include "llvm/ADT/iterator_range.h"
0021 #include "llvm/CodeGen/Register.h"
0022 #include "llvm/CodeGen/RegisterBank.h"
0023 #include "llvm/CodeGenTypes/LowLevelType.h"
0024 #include "llvm/Support/ErrorHandling.h"
0025 #include <cassert>
0026 #include <initializer_list>
0027 #include <memory>
0028 
0029 namespace llvm {
0030 
0031 class MachineInstr;
0032 class MachineIRBuilder;
0033 class MachineRegisterInfo;
0034 class raw_ostream;
0035 class TargetInstrInfo;
0036 class TargetRegisterClass;
0037 class TargetRegisterInfo;
0038 
0039 /// Holds all the information related to register banks.
0040 class RegisterBankInfo {
0041 public:
0042   /// Helper struct that represents how a value is partially mapped
0043   /// into a register.
0044   /// The StartIdx and Length represent what region of the orginal
0045   /// value this partial mapping covers.
0046   /// This can be represented as a Mask of contiguous bit starting
0047   /// at StartIdx bit and spanning Length bits.
0048   /// StartIdx is the number of bits from the less significant bits.
0049   struct PartialMapping {
0050     /// Number of bits at which this partial mapping starts in the
0051     /// original value.  The bits are counted from less significant
0052     /// bits to most significant bits.
0053     unsigned StartIdx;
0054 
0055     /// Length of this mapping in bits. This is how many bits this
0056     /// partial mapping covers in the original value:
0057     /// from StartIdx to StartIdx + Length -1.
0058     unsigned Length;
0059 
0060     /// Register bank where the partial value lives.
0061     const RegisterBank *RegBank;
0062 
0063     PartialMapping() = default;
0064 
0065     /// Provide a shortcut for quickly building PartialMapping.
0066     constexpr PartialMapping(unsigned StartIdx, unsigned Length,
0067                              const RegisterBank &RegBank)
0068         : StartIdx(StartIdx), Length(Length), RegBank(&RegBank) {}
0069 
0070     /// \return the index of in the original value of the most
0071     /// significant bit that this partial mapping covers.
0072     unsigned getHighBitIdx() const { return StartIdx + Length - 1; }
0073 
0074     /// Print this partial mapping on dbgs() stream.
0075     void dump() const;
0076 
0077     /// Print this partial mapping on \p OS;
0078     void print(raw_ostream &OS) const;
0079 
0080     /// Check that the Mask is compatible with the RegBank.
0081     /// Indeed, if the RegBank cannot accomadate the "active bits" of the mask,
0082     /// there is no way this mapping is valid.
0083     ///
0084     /// \note This method does not check anything when assertions are disabled.
0085     ///
0086     /// \return True is the check was successful.
0087     bool verify(const RegisterBankInfo &RBI) const;
0088   };
0089 
0090   /// Helper struct that represents how a value is mapped through
0091   /// different register banks.
0092   ///
0093   /// \note: So far we do not have any users of the complex mappings
0094   /// (mappings with more than one partial mapping), but when we do,
0095   /// we would have needed to duplicate partial mappings.
0096   /// The alternative could be to use an array of pointers of partial
0097   /// mapping (i.e., PartialMapping **BreakDown) and duplicate the
0098   /// pointers instead.
0099   ///
0100   /// E.g.,
0101   /// Let say we have a 32-bit add and a <2 x 32-bit> vadd. We
0102   /// can expand the
0103   /// <2 x 32-bit> add into 2 x 32-bit add.
0104   ///
0105   /// Currently the TableGen-like file would look like:
0106   /// \code
0107   /// PartialMapping[] = {
0108   /// /*32-bit add*/      {0, 32, GPR}, // Scalar entry repeated for first
0109   ///                                   // vec elt.
0110   /// /*2x32-bit add*/    {0, 32, GPR}, {32, 32, GPR},
0111   /// /*<2x32-bit> vadd*/ {0, 64, VPR}
0112   /// }; // PartialMapping duplicated.
0113   ///
0114   /// ValueMapping[] {
0115   ///   /*plain 32-bit add*/       {&PartialMapping[0], 1},
0116   ///   /*expanded vadd on 2xadd*/ {&PartialMapping[1], 2},
0117   ///   /*plain <2x32-bit> vadd*/  {&PartialMapping[3], 1}
0118   /// };
0119   /// \endcode
0120   ///
0121   /// With the array of pointer, we would have:
0122   /// \code
0123   /// PartialMapping[] = {
0124   /// /*32-bit add lower */ { 0, 32, GPR},
0125   /// /*32-bit add upper */ {32, 32, GPR},
0126   /// /*<2x32-bit> vadd */  { 0, 64, VPR}
0127   /// }; // No more duplication.
0128   ///
0129   /// BreakDowns[] = {
0130   /// /*AddBreakDown*/   &PartialMapping[0],
0131   /// /*2xAddBreakDown*/ &PartialMapping[0], &PartialMapping[1],
0132   /// /*VAddBreakDown*/  &PartialMapping[2]
0133   /// }; // Addresses of PartialMapping duplicated (smaller).
0134   ///
0135   /// ValueMapping[] {
0136   ///   /*plain 32-bit add*/       {&BreakDowns[0], 1},
0137   ///   /*expanded vadd on 2xadd*/ {&BreakDowns[1], 2},
0138   ///   /*plain <2x32-bit> vadd*/  {&BreakDowns[3], 1}
0139   /// };
0140   /// \endcode
0141   ///
0142   /// Given that a PartialMapping is actually small, the code size
0143   /// impact is actually a degradation. Moreover the compile time will
0144   /// be hit by the additional indirection.
0145   /// If PartialMapping gets bigger we may reconsider.
0146   struct ValueMapping {
0147     /// How the value is broken down between the different register banks.
0148     const PartialMapping *BreakDown;
0149 
0150     /// Number of partial mapping to break down this value.
0151     unsigned NumBreakDowns;
0152 
0153     /// The default constructor creates an invalid (isValid() == false)
0154     /// instance.
0155     ValueMapping() : ValueMapping(nullptr, 0) {}
0156 
0157     /// Initialize a ValueMapping with the given parameter.
0158     /// \p BreakDown needs to have a life time at least as long
0159     /// as this instance.
0160     constexpr ValueMapping(const PartialMapping *BreakDown,
0161                            unsigned NumBreakDowns)
0162         : BreakDown(BreakDown), NumBreakDowns(NumBreakDowns) {}
0163 
0164     /// Iterators through the PartialMappings.
0165     const PartialMapping *begin() const { return BreakDown; }
0166     const PartialMapping *end() const { return BreakDown + NumBreakDowns; }
0167 
0168     /// \return true if all partial mappings are the same size and register
0169     /// bank.
0170     bool partsAllUniform() const;
0171 
0172     /// Check if this ValueMapping is valid.
0173     bool isValid() const { return BreakDown && NumBreakDowns; }
0174 
0175     /// Verify that this mapping makes sense for a value of
0176     /// \p MeaningfulBitWidth.
0177     /// \note This method does not check anything when assertions are disabled.
0178     ///
0179     /// \return True is the check was successful.
0180     bool verify(const RegisterBankInfo &RBI, TypeSize MeaningfulBitWidth) const;
0181 
0182     /// Print this on dbgs() stream.
0183     void dump() const;
0184 
0185     /// Print this on \p OS;
0186     void print(raw_ostream &OS) const;
0187   };
0188 
0189   /// Helper class that represents how the value of an instruction may be
0190   /// mapped and what is the related cost of such mapping.
0191   class InstructionMapping {
0192     /// Identifier of the mapping.
0193     /// This is used to communicate between the target and the optimizers
0194     /// which mapping should be realized.
0195     unsigned ID = InvalidMappingID;
0196 
0197     /// Cost of this mapping.
0198     unsigned Cost = 0;
0199 
0200     /// Mapping of all the operands.
0201     const ValueMapping *OperandsMapping = nullptr;
0202 
0203     /// Number of operands.
0204     unsigned NumOperands = 0;
0205 
0206     const ValueMapping &getOperandMapping(unsigned i) {
0207       assert(i < getNumOperands() && "Out of bound operand");
0208       return OperandsMapping[i];
0209     }
0210 
0211   public:
0212     /// Constructor for the mapping of an instruction.
0213     /// \p NumOperands must be equal to number of all the operands of
0214     /// the related instruction.
0215     /// The rationale is that it is more efficient for the optimizers
0216     /// to be able to assume that the mapping of the ith operand is
0217     /// at the index i.
0218     InstructionMapping(unsigned ID, unsigned Cost,
0219                        const ValueMapping *OperandsMapping,
0220                        unsigned NumOperands)
0221         : ID(ID), Cost(Cost), OperandsMapping(OperandsMapping),
0222           NumOperands(NumOperands) {}
0223 
0224     /// Default constructor.
0225     /// Use this constructor to express that the mapping is invalid.
0226     InstructionMapping() = default;
0227 
0228     /// Get the cost.
0229     unsigned getCost() const { return Cost; }
0230 
0231     /// Get the ID.
0232     unsigned getID() const { return ID; }
0233 
0234     /// Get the number of operands.
0235     unsigned getNumOperands() const { return NumOperands; }
0236 
0237     /// Get the value mapping of the ith operand.
0238     /// \pre The mapping for the ith operand has been set.
0239     /// \pre The ith operand is a register.
0240     const ValueMapping &getOperandMapping(unsigned i) const {
0241       const ValueMapping &ValMapping =
0242           const_cast<InstructionMapping *>(this)->getOperandMapping(i);
0243       return ValMapping;
0244     }
0245 
0246     /// Set the mapping for all the operands.
0247     /// In other words, OpdsMapping should hold at least getNumOperands
0248     /// ValueMapping.
0249     void setOperandsMapping(const ValueMapping *OpdsMapping) {
0250       OperandsMapping = OpdsMapping;
0251     }
0252 
0253     /// Check whether this object is valid.
0254     /// This is a lightweight check for obvious wrong instance.
0255     bool isValid() const {
0256       return getID() != InvalidMappingID && OperandsMapping;
0257     }
0258 
0259     /// Verifiy that this mapping makes sense for \p MI.
0260     /// \pre \p MI must be connected to a MachineFunction.
0261     ///
0262     /// \note This method does not check anything when assertions are disabled.
0263     ///
0264     /// \return True is the check was successful.
0265     bool verify(const MachineInstr &MI) const;
0266 
0267     /// Print this on dbgs() stream.
0268     void dump() const;
0269 
0270     /// Print this on \p OS;
0271     void print(raw_ostream &OS) const;
0272   };
0273 
0274   /// Convenient type to represent the alternatives for mapping an
0275   /// instruction.
0276   /// \todo When we move to TableGen this should be an array ref.
0277   using InstructionMappings = SmallVector<const InstructionMapping *, 4>;
0278 
0279   /// Helper class used to get/create the virtual registers that will be used
0280   /// to replace the MachineOperand when applying a mapping.
0281   class OperandsMapper {
0282     /// The OpIdx-th cell contains the index in NewVRegs where the VRegs of the
0283     /// OpIdx-th operand starts. -1 means we do not have such mapping yet.
0284     /// Note: We use a SmallVector to avoid heap allocation for most cases.
0285     SmallVector<int, 8> OpToNewVRegIdx;
0286 
0287     /// Hold the registers that will be used to map MI with InstrMapping.
0288     SmallVector<Register, 8> NewVRegs;
0289 
0290     /// Current MachineRegisterInfo, used to create new virtual registers.
0291     MachineRegisterInfo &MRI;
0292 
0293     /// Instruction being remapped.
0294     MachineInstr &MI;
0295 
0296     /// New mapping of the instruction.
0297     const InstructionMapping &InstrMapping;
0298 
0299     /// Constant value identifying that the index in OpToNewVRegIdx
0300     /// for an operand has not been set yet.
0301     static const int DontKnowIdx;
0302 
0303     /// Get the range in NewVRegs to store all the partial
0304     /// values for the \p OpIdx-th operand.
0305     ///
0306     /// \return The iterator range for the space created.
0307     //
0308     /// \pre getMI().getOperand(OpIdx).isReg()
0309     iterator_range<SmallVectorImpl<Register>::iterator>
0310     getVRegsMem(unsigned OpIdx);
0311 
0312     /// Get the end iterator for a range starting at \p StartIdx and
0313     /// spannig \p NumVal in NewVRegs.
0314     /// \pre StartIdx + NumVal <= NewVRegs.size()
0315     SmallVectorImpl<Register>::const_iterator
0316     getNewVRegsEnd(unsigned StartIdx, unsigned NumVal) const;
0317     SmallVectorImpl<Register>::iterator getNewVRegsEnd(unsigned StartIdx,
0318                                                        unsigned NumVal);
0319 
0320   public:
0321     /// Create an OperandsMapper that will hold the information to apply \p
0322     /// InstrMapping to \p MI.
0323     /// \pre InstrMapping.verify(MI)
0324     OperandsMapper(MachineInstr &MI, const InstructionMapping &InstrMapping,
0325                    MachineRegisterInfo &MRI);
0326 
0327     /// \name Getters.
0328     /// @{
0329     /// The MachineInstr being remapped.
0330     MachineInstr &getMI() const { return MI; }
0331 
0332     /// The final mapping of the instruction.
0333     const InstructionMapping &getInstrMapping() const { return InstrMapping; }
0334 
0335     /// The MachineRegisterInfo we used to realize the mapping.
0336     MachineRegisterInfo &getMRI() const { return MRI; }
0337     /// @}
0338 
0339     /// Create as many new virtual registers as needed for the mapping of the \p
0340     /// OpIdx-th operand.
0341     /// The number of registers is determined by the number of breakdown for the
0342     /// related operand in the instruction mapping.
0343     /// The type of the new registers is a plain scalar of the right size.
0344     /// The proper type is expected to be set when the mapping is applied to
0345     /// the instruction(s) that realizes the mapping.
0346     ///
0347     /// \pre getMI().getOperand(OpIdx).isReg()
0348     ///
0349     /// \post All the partial mapping of the \p OpIdx-th operand have been
0350     /// assigned a new virtual register.
0351     void createVRegs(unsigned OpIdx);
0352 
0353     /// Set the virtual register of the \p PartialMapIdx-th partial mapping of
0354     /// the OpIdx-th operand to \p NewVReg.
0355     ///
0356     /// \pre getMI().getOperand(OpIdx).isReg()
0357     /// \pre getInstrMapping().getOperandMapping(OpIdx).BreakDown.size() >
0358     /// PartialMapIdx
0359     /// \pre NewReg != 0
0360     ///
0361     /// \post the \p PartialMapIdx-th register of the value mapping of the \p
0362     /// OpIdx-th operand has been set.
0363     void setVRegs(unsigned OpIdx, unsigned PartialMapIdx, Register NewVReg);
0364 
0365     /// Get all the virtual registers required to map the \p OpIdx-th operand of
0366     /// the instruction.
0367     ///
0368     /// This return an empty range when createVRegs or setVRegs has not been
0369     /// called.
0370     /// The iterator may be invalidated by a call to setVRegs or createVRegs.
0371     ///
0372     /// When \p ForDebug is true, we will not check that the list of new virtual
0373     /// registers does not contain uninitialized values.
0374     ///
0375     /// \pre getMI().getOperand(OpIdx).isReg()
0376     /// \pre ForDebug || All partial mappings have been set a register
0377     iterator_range<SmallVectorImpl<Register>::const_iterator>
0378     getVRegs(unsigned OpIdx, bool ForDebug = false) const;
0379 
0380     /// Print this operands mapper on dbgs() stream.
0381     void dump() const;
0382 
0383     /// Print this operands mapper on \p OS stream.
0384     void print(raw_ostream &OS, bool ForDebug = false) const;
0385   };
0386 
0387 protected:
0388   /// Hold the set of supported register banks.
0389   const RegisterBank **RegBanks;
0390 
0391   /// Total number of register banks.
0392   unsigned NumRegBanks;
0393 
0394   /// Hold the sizes of the register banks for all HwModes.
0395   const unsigned *Sizes;
0396 
0397   /// Current HwMode for the target.
0398   unsigned HwMode;
0399 
0400   /// Keep dynamically allocated PartialMapping in a separate map.
0401   /// This shouldn't be needed when everything gets TableGen'ed.
0402   mutable DenseMap<hash_code, std::unique_ptr<const PartialMapping>>
0403       MapOfPartialMappings;
0404 
0405   /// Keep dynamically allocated ValueMapping in a separate map.
0406   /// This shouldn't be needed when everything gets TableGen'ed.
0407   mutable DenseMap<hash_code, std::unique_ptr<const ValueMapping>>
0408       MapOfValueMappings;
0409 
0410   /// Keep dynamically allocated array of ValueMapping in a separate map.
0411   /// This shouldn't be needed when everything gets TableGen'ed.
0412   mutable DenseMap<hash_code, std::unique_ptr<ValueMapping[]>>
0413       MapOfOperandsMappings;
0414 
0415   /// Keep dynamically allocated InstructionMapping in a separate map.
0416   /// This shouldn't be needed when everything gets TableGen'ed.
0417   mutable DenseMap<hash_code, std::unique_ptr<const InstructionMapping>>
0418       MapOfInstructionMappings;
0419 
0420   /// Getting the minimal register class of a physreg is expensive.
0421   /// Cache this information as we get it.
0422   mutable DenseMap<unsigned, const TargetRegisterClass *> PhysRegMinimalRCs;
0423 
0424   /// Create a RegisterBankInfo that can accommodate up to \p NumRegBanks
0425   /// RegisterBank instances.
0426   RegisterBankInfo(const RegisterBank **RegBanks, unsigned NumRegBanks,
0427                    const unsigned *Sizes, unsigned HwMode);
0428 
0429   /// This constructor is meaningless.
0430   /// It just provides a default constructor that can be used at link time
0431   /// when GlobalISel is not built.
0432   /// That way, targets can still inherit from this class without doing
0433   /// crazy gymnastic to avoid link time failures.
0434   /// \note That works because the constructor is inlined.
0435   RegisterBankInfo() {
0436     llvm_unreachable("This constructor should not be executed");
0437   }
0438 
0439   /// Get the register bank identified by \p ID.
0440   const RegisterBank &getRegBank(unsigned ID) {
0441     assert(ID < getNumRegBanks() && "Accessing an unknown register bank");
0442     return *RegBanks[ID];
0443   }
0444 
0445   /// Get the MinimalPhysRegClass for Reg.
0446   /// \pre Reg is a physical register.
0447   const TargetRegisterClass *
0448   getMinimalPhysRegClass(Register Reg, const TargetRegisterInfo &TRI) const;
0449 
0450   /// Try to get the mapping of \p MI.
0451   /// See getInstrMapping for more details on what a mapping represents.
0452   ///
0453   /// Unlike getInstrMapping the returned InstructionMapping may be invalid
0454   /// (isValid() == false).
0455   /// This means that the target independent code is not smart enough
0456   /// to get the mapping of \p MI and thus, the target has to provide the
0457   /// information for \p MI.
0458   ///
0459   /// This implementation is able to get the mapping of:
0460   /// - Target specific instructions by looking at the encoding constraints.
0461   /// - Any instruction if all the register operands have already been assigned
0462   ///   a register, a register class, or a register bank.
0463   /// - Copies and phis if at least one of the operands has been assigned a
0464   ///   register, a register class, or a register bank.
0465   /// In other words, this method will likely fail to find a mapping for
0466   /// any generic opcode that has not been lowered by target specific code.
0467   const InstructionMapping &getInstrMappingImpl(const MachineInstr &MI) const;
0468 
0469   /// Get the uniquely generated PartialMapping for the
0470   /// given arguments.
0471   const PartialMapping &getPartialMapping(unsigned StartIdx, unsigned Length,
0472                                           const RegisterBank &RegBank) const;
0473 
0474   /// \name Methods to get a uniquely generated ValueMapping.
0475   /// @{
0476 
0477   /// The most common ValueMapping consists of a single PartialMapping.
0478   /// Feature a method for that.
0479   const ValueMapping &getValueMapping(unsigned StartIdx, unsigned Length,
0480                                       const RegisterBank &RegBank) const;
0481 
0482   /// Get the ValueMapping for the given arguments.
0483   const ValueMapping &getValueMapping(const PartialMapping *BreakDown,
0484                                       unsigned NumBreakDowns) const;
0485   /// @}
0486 
0487   /// \name Methods to get a uniquely generated array of ValueMapping.
0488   /// @{
0489 
0490   /// Get the uniquely generated array of ValueMapping for the
0491   /// elements of between \p Begin and \p End.
0492   ///
0493   /// Elements that are nullptr will be replaced by
0494   /// invalid ValueMapping (ValueMapping::isValid == false).
0495   ///
0496   /// \pre The pointers on ValueMapping between \p Begin and \p End
0497   /// must uniquely identify a ValueMapping. Otherwise, there is no
0498   /// guarantee that the return instance will be unique, i.e., another
0499   /// OperandsMapping could have the same content.
0500   template <typename Iterator>
0501   const ValueMapping *getOperandsMapping(Iterator Begin, Iterator End) const;
0502 
0503   /// Get the uniquely generated array of ValueMapping for the
0504   /// elements of \p OpdsMapping.
0505   ///
0506   /// Elements of \p OpdsMapping that are nullptr will be replaced by
0507   /// invalid ValueMapping (ValueMapping::isValid == false).
0508   const ValueMapping *getOperandsMapping(
0509       const SmallVectorImpl<const ValueMapping *> &OpdsMapping) const;
0510 
0511   /// Get the uniquely generated array of ValueMapping for the
0512   /// given arguments.
0513   ///
0514   /// Arguments that are nullptr will be replaced by invalid
0515   /// ValueMapping (ValueMapping::isValid == false).
0516   const ValueMapping *getOperandsMapping(
0517       std::initializer_list<const ValueMapping *> OpdsMapping) const;
0518   /// @}
0519 
0520   /// \name Methods to get a uniquely generated InstructionMapping.
0521   /// @{
0522 
0523 private:
0524   /// Method to get a uniquely generated InstructionMapping.
0525   const InstructionMapping &
0526   getInstructionMappingImpl(bool IsInvalid, unsigned ID = InvalidMappingID,
0527                             unsigned Cost = 0,
0528                             const ValueMapping *OperandsMapping = nullptr,
0529                             unsigned NumOperands = 0) const;
0530 
0531 public:
0532   /// Method to get a uniquely generated InstructionMapping.
0533   const InstructionMapping &
0534   getInstructionMapping(unsigned ID, unsigned Cost,
0535                         const ValueMapping *OperandsMapping,
0536                         unsigned NumOperands) const {
0537     return getInstructionMappingImpl(/*IsInvalid*/ false, ID, Cost,
0538                                      OperandsMapping, NumOperands);
0539   }
0540 
0541   /// Method to get a uniquely generated invalid InstructionMapping.
0542   const InstructionMapping &getInvalidInstructionMapping() const {
0543     return getInstructionMappingImpl(/*IsInvalid*/ true);
0544   }
0545   /// @}
0546 
0547   /// Get the register bank for the \p OpIdx-th operand of \p MI form
0548   /// the encoding constraints, if any.
0549   ///
0550   /// \return A register bank that covers the register class of the
0551   /// related encoding constraints or nullptr if \p MI did not provide
0552   /// enough information to deduce it.
0553   const RegisterBank *
0554   getRegBankFromConstraints(const MachineInstr &MI, unsigned OpIdx,
0555                             const TargetInstrInfo &TII,
0556                             const MachineRegisterInfo &MRI) const;
0557 
0558   /// Helper method to apply something that is like the default mapping.
0559   /// Basically, that means that \p OpdMapper.getMI() is left untouched
0560   /// aside from the reassignment of the register operand that have been
0561   /// remapped.
0562   ///
0563   /// The type of all the new registers that have been created by the
0564   /// mapper are properly remapped to the type of the original registers
0565   /// they replace. In other words, the semantic of the instruction does
0566   /// not change, only the register banks.
0567   ///
0568   /// If the mapping of one of the operand spans several registers, this
0569   /// method will abort as this is not like a default mapping anymore.
0570   ///
0571   /// \pre For OpIdx in {0..\p OpdMapper.getMI().getNumOperands())
0572   ///        the range OpdMapper.getVRegs(OpIdx) is empty or of size 1.
0573   static void applyDefaultMapping(const OperandsMapper &OpdMapper);
0574 
0575   /// See ::applyMapping.
0576   virtual void applyMappingImpl(MachineIRBuilder &Builder,
0577                                 const OperandsMapper &OpdMapper) const {
0578     llvm_unreachable("The target has to implement this");
0579   }
0580 
0581 public:
0582   virtual ~RegisterBankInfo() = default;
0583 
0584   /// Get the register bank identified by \p ID.
0585   const RegisterBank &getRegBank(unsigned ID) const {
0586     return const_cast<RegisterBankInfo *>(this)->getRegBank(ID);
0587   }
0588 
0589   /// Get the maximum size in bits that fits in the given register bank.
0590   unsigned getMaximumSize(unsigned RegBankID) const {
0591     return Sizes[RegBankID + HwMode * NumRegBanks];
0592   }
0593 
0594   /// Get the register bank of \p Reg.
0595   /// If Reg has not been assigned a register, a register class,
0596   /// or a register bank, then this returns nullptr.
0597   ///
0598   /// \pre Reg != 0 (NoRegister)
0599   const RegisterBank *getRegBank(Register Reg, const MachineRegisterInfo &MRI,
0600                                  const TargetRegisterInfo &TRI) const;
0601 
0602   /// Get the total number of register banks.
0603   unsigned getNumRegBanks() const { return NumRegBanks; }
0604 
0605   /// Returns true if the register bank is considered divergent.
0606   virtual bool isDivergentRegBank(const RegisterBank *RB) const {
0607     return false;
0608   }
0609 
0610   /// Get a register bank that covers \p RC.
0611   ///
0612   /// \pre \p RC is a user-defined register class (as opposed as one
0613   /// generated by TableGen).
0614   ///
0615   /// \note The mapping RC -> RegBank could be built while adding the
0616   /// coverage for the register banks. However, we do not do it, because,
0617   /// at least for now, we only need this information for register classes
0618   /// that are used in the description of instruction. In other words,
0619   /// there are just a handful of them and we do not want to waste space.
0620   ///
0621   /// \todo This should be TableGen'ed.
0622   virtual const RegisterBank &
0623   getRegBankFromRegClass(const TargetRegisterClass &RC, LLT Ty) const {
0624     llvm_unreachable("The target must override this method");
0625   }
0626 
0627   /// Get the cost of a copy from \p B to \p A, or put differently,
0628   /// get the cost of A = COPY B. Since register banks may cover
0629   /// different size, \p Size specifies what will be the size in bits
0630   /// that will be copied around.
0631   ///
0632   /// \note Since this is a copy, both registers have the same size.
0633   virtual unsigned copyCost(const RegisterBank &A, const RegisterBank &B,
0634                             TypeSize Size) const {
0635     // Optimistically assume that copies are coalesced. I.e., when
0636     // they are on the same bank, they are free.
0637     // Otherwise assume a non-zero cost of 1. The targets are supposed
0638     // to override that properly anyway if they care.
0639     return &A != &B;
0640   }
0641 
0642   /// \returns true if emitting a copy from \p Src to \p Dst is impossible.
0643   bool cannotCopy(const RegisterBank &Dst, const RegisterBank &Src,
0644                   TypeSize Size) const {
0645     return copyCost(Dst, Src, Size) == std::numeric_limits<unsigned>::max();
0646   }
0647 
0648   /// Get the cost of using \p ValMapping to decompose a register. This is
0649   /// similar to ::copyCost, except for cases where multiple copy-like
0650   /// operations need to be inserted. If the register is used as a source
0651   /// operand and already has a bank assigned, \p CurBank is non-null.
0652   virtual unsigned
0653   getBreakDownCost(const ValueMapping &ValMapping,
0654                    const RegisterBank *CurBank = nullptr) const {
0655     return std::numeric_limits<unsigned>::max();
0656   }
0657 
0658   /// Constrain the (possibly generic) virtual register \p Reg to \p RC.
0659   ///
0660   /// \pre \p Reg is a virtual register that either has a bank or a class.
0661   /// \returns The constrained register class, or nullptr if there is none.
0662   /// \note This is a generic variant of MachineRegisterInfo::constrainRegClass
0663   /// \note Use MachineRegisterInfo::constrainRegAttrs instead for any non-isel
0664   /// purpose, including non-select passes of GlobalISel
0665   static const TargetRegisterClass *
0666   constrainGenericRegister(Register Reg, const TargetRegisterClass &RC,
0667                            MachineRegisterInfo &MRI);
0668 
0669   /// Identifier used when the related instruction mapping instance
0670   /// is generated by target independent code.
0671   /// Make sure not to use that identifier to avoid possible collision.
0672   static const unsigned DefaultMappingID;
0673 
0674   /// Identifier used when the related instruction mapping instance
0675   /// is generated by the default constructor.
0676   /// Make sure not to use that identifier.
0677   static const unsigned InvalidMappingID;
0678 
0679   /// Get the mapping of the different operands of \p MI
0680   /// on the register bank.
0681   /// This mapping should be the direct translation of \p MI.
0682   /// In other words, when \p MI is mapped with the returned mapping,
0683   /// only the register banks of the operands of \p MI need to be updated.
0684   /// In particular, neither the opcode nor the type of \p MI needs to be
0685   /// updated for this direct mapping.
0686   ///
0687   /// The target independent implementation gives a mapping based on
0688   /// the register classes for the target specific opcode.
0689   /// It uses the ID RegisterBankInfo::DefaultMappingID for that mapping.
0690   /// Make sure you do not use that ID for the alternative mapping
0691   /// for MI. See getInstrAlternativeMappings for the alternative
0692   /// mappings.
0693   ///
0694   /// For instance, if \p MI is a vector add, the mapping should
0695   /// not be a scalarization of the add.
0696   ///
0697   /// \post returnedVal.verify(MI).
0698   ///
0699   /// \note If returnedVal does not verify MI, this would probably mean
0700   /// that the target does not support that instruction.
0701   virtual const InstructionMapping &
0702   getInstrMapping(const MachineInstr &MI) const;
0703 
0704   /// Get the alternative mappings for \p MI.
0705   /// Alternative in the sense different from getInstrMapping.
0706   virtual InstructionMappings
0707   getInstrAlternativeMappings(const MachineInstr &MI) const;
0708 
0709   /// Get the possible mapping for \p MI.
0710   /// A mapping defines where the different operands may live and at what cost.
0711   /// For instance, let us consider:
0712   /// v0(16) = G_ADD <2 x i8> v1, v2
0713   /// The possible mapping could be:
0714   ///
0715   /// {/*ID*/VectorAdd, /*Cost*/1, /*v0*/{(0xFFFF, VPR)}, /*v1*/{(0xFFFF, VPR)},
0716   ///                              /*v2*/{(0xFFFF, VPR)}}
0717   /// {/*ID*/ScalarAddx2, /*Cost*/2, /*v0*/{(0x00FF, GPR),(0xFF00, GPR)},
0718   ///                                /*v1*/{(0x00FF, GPR),(0xFF00, GPR)},
0719   ///                                /*v2*/{(0x00FF, GPR),(0xFF00, GPR)}}
0720   ///
0721   /// \note The first alternative of the returned mapping should be the
0722   /// direct translation of \p MI current form.
0723   ///
0724   /// \post !returnedVal.empty().
0725   InstructionMappings getInstrPossibleMappings(const MachineInstr &MI) const;
0726 
0727   /// Apply \p OpdMapper.getInstrMapping() to \p OpdMapper.getMI().
0728   /// After this call \p OpdMapper.getMI() may not be valid anymore.
0729   /// \p OpdMapper.getInstrMapping().getID() carries the information of
0730   /// what has been chosen to map \p OpdMapper.getMI(). This ID is set
0731   /// by the various getInstrXXXMapping method.
0732   ///
0733   /// Therefore, getting the mapping and applying it should be kept in
0734   /// sync.
0735   void applyMapping(MachineIRBuilder &Builder,
0736                     const OperandsMapper &OpdMapper) const {
0737     // The only mapping we know how to handle is the default mapping.
0738     if (OpdMapper.getInstrMapping().getID() == DefaultMappingID)
0739       return applyDefaultMapping(OpdMapper);
0740     // For other mapping, the target needs to do the right thing.
0741     // If that means calling applyDefaultMapping, fine, but this
0742     // must be explicitly stated.
0743     applyMappingImpl(Builder, OpdMapper);
0744   }
0745 
0746   /// Get the size in bits of \p Reg.
0747   /// Utility method to get the size of any registers. Unlike
0748   /// MachineRegisterInfo::getSize, the register does not need to be a
0749   /// virtual register.
0750   ///
0751   /// \pre \p Reg != 0 (NoRegister).
0752   TypeSize getSizeInBits(Register Reg, const MachineRegisterInfo &MRI,
0753                          const TargetRegisterInfo &TRI) const;
0754 
0755   /// Check that information hold by this instance make sense for the
0756   /// given \p TRI.
0757   ///
0758   /// \note This method does not check anything when assertions are disabled.
0759   ///
0760   /// \return True is the check was successful.
0761   bool verify(const TargetRegisterInfo &TRI) const;
0762 };
0763 
0764 inline raw_ostream &
0765 operator<<(raw_ostream &OS,
0766            const RegisterBankInfo::PartialMapping &PartMapping) {
0767   PartMapping.print(OS);
0768   return OS;
0769 }
0770 
0771 inline raw_ostream &
0772 operator<<(raw_ostream &OS, const RegisterBankInfo::ValueMapping &ValMapping) {
0773   ValMapping.print(OS);
0774   return OS;
0775 }
0776 
0777 inline raw_ostream &
0778 operator<<(raw_ostream &OS,
0779            const RegisterBankInfo::InstructionMapping &InstrMapping) {
0780   InstrMapping.print(OS);
0781   return OS;
0782 }
0783 
0784 inline raw_ostream &
0785 operator<<(raw_ostream &OS, const RegisterBankInfo::OperandsMapper &OpdMapper) {
0786   OpdMapper.print(OS, /*ForDebug*/ false);
0787   return OS;
0788 }
0789 
0790 /// Hashing function for PartialMapping.
0791 /// It is required for the hashing of ValueMapping.
0792 hash_code hash_value(const RegisterBankInfo::PartialMapping &PartMapping);
0793 
0794 } // end namespace llvm
0795 
0796 #endif // LLVM_CODEGEN_REGISTERBANKINFO_H