• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- llvm/CodeGen/GlobalISel/RegisterBankInfo.h ---------------*- 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 /// \file This file declares the API for the register bank info.
10 /// This API is responsible for handling the register banks.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CODEGEN_GLOBALISEL_REGISTERBANKINFO_H
15 #define LLVM_CODEGEN_GLOBALISEL_REGISTERBANKINFO_H
16 
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/CodeGen/Register.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/LowLevelTypeImpl.h"
24 #include <cassert>
25 #include <initializer_list>
26 #include <memory>
27 
28 namespace llvm {
29 
30 class MachineInstr;
31 class MachineRegisterInfo;
32 class raw_ostream;
33 class RegisterBank;
34 class TargetInstrInfo;
35 class TargetRegisterClass;
36 class TargetRegisterInfo;
37 
38 /// Holds all the information related to register banks.
39 class RegisterBankInfo {
40 public:
41   /// Helper struct that represents how a value is partially mapped
42   /// into a register.
43   /// The StartIdx and Length represent what region of the orginal
44   /// value this partial mapping covers.
45   /// This can be represented as a Mask of contiguous bit starting
46   /// at StartIdx bit and spanning Length bits.
47   /// StartIdx is the number of bits from the less significant bits.
48   struct PartialMapping {
49     /// Number of bits at which this partial mapping starts in the
50     /// original value.  The bits are counted from less significant
51     /// bits to most significant bits.
52     unsigned StartIdx;
53 
54     /// Length of this mapping in bits. This is how many bits this
55     /// partial mapping covers in the original value:
56     /// from StartIdx to StartIdx + Length -1.
57     unsigned Length;
58 
59     /// Register bank where the partial value lives.
60     const RegisterBank *RegBank;
61 
62     PartialMapping() = default;
63 
64     /// Provide a shortcut for quickly building PartialMapping.
PartialMappingPartialMapping65     PartialMapping(unsigned StartIdx, unsigned Length,
66                    const RegisterBank &RegBank)
67         : StartIdx(StartIdx), Length(Length), RegBank(&RegBank) {}
68 
69     /// \return the index of in the original value of the most
70     /// significant bit that this partial mapping covers.
getHighBitIdxPartialMapping71     unsigned getHighBitIdx() const { return StartIdx + Length - 1; }
72 
73     /// Print this partial mapping on dbgs() stream.
74     void dump() const;
75 
76     /// Print this partial mapping on \p OS;
77     void print(raw_ostream &OS) const;
78 
79     /// Check that the Mask is compatible with the RegBank.
80     /// Indeed, if the RegBank cannot accomadate the "active bits" of the mask,
81     /// there is no way this mapping is valid.
82     ///
83     /// \note This method does not check anything when assertions are disabled.
84     ///
85     /// \return True is the check was successful.
86     bool verify() const;
87   };
88 
89   /// Helper struct that represents how a value is mapped through
90   /// different register banks.
91   ///
92   /// \note: So far we do not have any users of the complex mappings
93   /// (mappings with more than one partial mapping), but when we do,
94   /// we would have needed to duplicate partial mappings.
95   /// The alternative could be to use an array of pointers of partial
96   /// mapping (i.e., PartialMapping **BreakDown) and duplicate the
97   /// pointers instead.
98   ///
99   /// E.g.,
100   /// Let say we have a 32-bit add and a <2 x 32-bit> vadd. We
101   /// can expand the
102   /// <2 x 32-bit> add into 2 x 32-bit add.
103   ///
104   /// Currently the TableGen-like file would look like:
105   /// \code
106   /// PartialMapping[] = {
107   /// /*32-bit add*/    {0, 32, GPR}, // Scalar entry repeated for first vec elt.
108   /// /*2x32-bit add*/  {0, 32, GPR}, {32, 32, GPR},
109   /// /*<2x32-bit> vadd {0, 64, VPR}
110   /// }; // PartialMapping duplicated.
111   ///
112   /// ValueMapping[] {
113   ///   /*plain 32-bit add*/ {&PartialMapping[0], 1},
114   ///   /*expanded vadd on 2xadd*/ {&PartialMapping[1], 2},
115   ///   /*plain <2x32-bit> vadd*/ {&PartialMapping[3], 1}
116   /// };
117   /// \endcode
118   ///
119   /// With the array of pointer, we would have:
120   /// \code
121   /// PartialMapping[] = {
122   /// /*32-bit add lower */ {0, 32, GPR},
123   /// /*32-bit add upper */ {32, 32, GPR},
124   /// /*<2x32-bit> vadd {0, 64, VPR}
125   /// }; // No more duplication.
126   ///
127   /// BreakDowns[] = {
128   /// /*AddBreakDown*/ &PartialMapping[0],
129   /// /*2xAddBreakDown*/ &PartialMapping[0], &PartialMapping[1],
130   /// /*VAddBreakDown*/ &PartialMapping[2]
131   /// }; // Addresses of PartialMapping duplicated (smaller).
132   ///
133   /// ValueMapping[] {
134   ///   /*plain 32-bit add*/ {&BreakDowns[0], 1},
135   ///   /*expanded vadd on 2xadd*/ {&BreakDowns[1], 2},
136   ///   /*plain <2x32-bit> vadd*/ {&BreakDowns[3], 1}
137   /// };
138   /// \endcode
139   ///
140   /// Given that a PartialMapping is actually small, the code size
141   /// impact is actually a degradation. Moreover the compile time will
142   /// be hit by the additional indirection.
143   /// If PartialMapping gets bigger we may reconsider.
144   struct ValueMapping {
145     /// How the value is broken down between the different register banks.
146     const PartialMapping *BreakDown;
147 
148     /// Number of partial mapping to break down this value.
149     unsigned NumBreakDowns;
150 
151     /// The default constructor creates an invalid (isValid() == false)
152     /// instance.
ValueMappingValueMapping153     ValueMapping() : ValueMapping(nullptr, 0) {}
154 
155     /// Initialize a ValueMapping with the given parameter.
156     /// \p BreakDown needs to have a life time at least as long
157     /// as this instance.
ValueMappingValueMapping158     ValueMapping(const PartialMapping *BreakDown, unsigned NumBreakDowns)
159         : BreakDown(BreakDown), NumBreakDowns(NumBreakDowns) {}
160 
161     /// Iterators through the PartialMappings.
beginValueMapping162     const PartialMapping *begin() const { return BreakDown; }
endValueMapping163     const PartialMapping *end() const { return BreakDown + NumBreakDowns; }
164 
165     /// \return true if all partial mappings are the same size and register
166     /// bank.
167     bool partsAllUniform() const;
168 
169     /// Check if this ValueMapping is valid.
isValidValueMapping170     bool isValid() const { return BreakDown && NumBreakDowns; }
171 
172     /// Verify that this mapping makes sense for a value of
173     /// \p MeaningfulBitWidth.
174     /// \note This method does not check anything when assertions are disabled.
175     ///
176     /// \return True is the check was successful.
177     bool verify(unsigned MeaningfulBitWidth) const;
178 
179     /// Print this on dbgs() stream.
180     void dump() const;
181 
182     /// Print this on \p OS;
183     void print(raw_ostream &OS) const;
184   };
185 
186   /// Helper class that represents how the value of an instruction may be
187   /// mapped and what is the related cost of such mapping.
188   class InstructionMapping {
189     /// Identifier of the mapping.
190     /// This is used to communicate between the target and the optimizers
191     /// which mapping should be realized.
192     unsigned ID = InvalidMappingID;
193 
194     /// Cost of this mapping.
195     unsigned Cost = 0;
196 
197     /// Mapping of all the operands.
198     const ValueMapping *OperandsMapping = nullptr;
199 
200     /// Number of operands.
201     unsigned NumOperands = 0;
202 
getOperandMapping(unsigned i)203     const ValueMapping &getOperandMapping(unsigned i) {
204       assert(i < getNumOperands() && "Out of bound operand");
205       return OperandsMapping[i];
206     }
207 
208   public:
209     /// Constructor for the mapping of an instruction.
210     /// \p NumOperands must be equal to number of all the operands of
211     /// the related instruction.
212     /// The rationale is that it is more efficient for the optimizers
213     /// to be able to assume that the mapping of the ith operand is
214     /// at the index i.
InstructionMapping(unsigned ID,unsigned Cost,const ValueMapping * OperandsMapping,unsigned NumOperands)215     InstructionMapping(unsigned ID, unsigned Cost,
216                        const ValueMapping *OperandsMapping,
217                        unsigned NumOperands)
218         : ID(ID), Cost(Cost), OperandsMapping(OperandsMapping),
219           NumOperands(NumOperands) {
220     }
221 
222     /// Default constructor.
223     /// Use this constructor to express that the mapping is invalid.
224     InstructionMapping() = default;
225 
226     /// Get the cost.
getCost()227     unsigned getCost() const { return Cost; }
228 
229     /// Get the ID.
getID()230     unsigned getID() const { return ID; }
231 
232     /// Get the number of operands.
getNumOperands()233     unsigned getNumOperands() const { return NumOperands; }
234 
235     /// Get the value mapping of the ith operand.
236     /// \pre The mapping for the ith operand has been set.
237     /// \pre The ith operand is a register.
getOperandMapping(unsigned i)238     const ValueMapping &getOperandMapping(unsigned i) const {
239       const ValueMapping &ValMapping =
240           const_cast<InstructionMapping *>(this)->getOperandMapping(i);
241       return ValMapping;
242     }
243 
244     /// Set the mapping for all the operands.
245     /// In other words, OpdsMapping should hold at least getNumOperands
246     /// ValueMapping.
setOperandsMapping(const ValueMapping * OpdsMapping)247     void setOperandsMapping(const ValueMapping *OpdsMapping) {
248       OperandsMapping = OpdsMapping;
249     }
250 
251     /// Check whether this object is valid.
252     /// This is a lightweight check for obvious wrong instance.
isValid()253     bool isValid() const {
254       return getID() != InvalidMappingID && OperandsMapping;
255     }
256 
257     /// Verifiy that this mapping makes sense for \p MI.
258     /// \pre \p MI must be connected to a MachineFunction.
259     ///
260     /// \note This method does not check anything when assertions are disabled.
261     ///
262     /// \return True is the check was successful.
263     bool verify(const MachineInstr &MI) const;
264 
265     /// Print this on dbgs() stream.
266     void dump() const;
267 
268     /// Print this on \p OS;
269     void print(raw_ostream &OS) const;
270   };
271 
272   /// Convenient type to represent the alternatives for mapping an
273   /// instruction.
274   /// \todo When we move to TableGen this should be an array ref.
275   using InstructionMappings = SmallVector<const InstructionMapping *, 4>;
276 
277   /// Helper class used to get/create the virtual registers that will be used
278   /// to replace the MachineOperand when applying a mapping.
279   class OperandsMapper {
280     /// The OpIdx-th cell contains the index in NewVRegs where the VRegs of the
281     /// OpIdx-th operand starts. -1 means we do not have such mapping yet.
282     /// Note: We use a SmallVector to avoid heap allocation for most cases.
283     SmallVector<int, 8> OpToNewVRegIdx;
284 
285     /// Hold the registers that will be used to map MI with InstrMapping.
286     SmallVector<Register, 8> NewVRegs;
287 
288     /// Current MachineRegisterInfo, used to create new virtual registers.
289     MachineRegisterInfo &MRI;
290 
291     /// Instruction being remapped.
292     MachineInstr &MI;
293 
294     /// New mapping of the instruction.
295     const InstructionMapping &InstrMapping;
296 
297     /// Constant value identifying that the index in OpToNewVRegIdx
298     /// for an operand has not been set yet.
299     static const int DontKnowIdx;
300 
301     /// Get the range in NewVRegs to store all the partial
302     /// values for the \p OpIdx-th operand.
303     ///
304     /// \return The iterator range for the space created.
305     //
306     /// \pre getMI().getOperand(OpIdx).isReg()
307     iterator_range<SmallVectorImpl<Register>::iterator>
308     getVRegsMem(unsigned OpIdx);
309 
310     /// Get the end iterator for a range starting at \p StartIdx and
311     /// spannig \p NumVal in NewVRegs.
312     /// \pre StartIdx + NumVal <= NewVRegs.size()
313     SmallVectorImpl<Register>::const_iterator
314     getNewVRegsEnd(unsigned StartIdx, unsigned NumVal) const;
315     SmallVectorImpl<Register>::iterator getNewVRegsEnd(unsigned StartIdx,
316                                                        unsigned NumVal);
317 
318   public:
319     /// Create an OperandsMapper that will hold the information to apply \p
320     /// InstrMapping to \p MI.
321     /// \pre InstrMapping.verify(MI)
322     OperandsMapper(MachineInstr &MI, const InstructionMapping &InstrMapping,
323                    MachineRegisterInfo &MRI);
324 
325     /// \name Getters.
326     /// @{
327     /// The MachineInstr being remapped.
getMI()328     MachineInstr &getMI() const { return MI; }
329 
330     /// The final mapping of the instruction.
getInstrMapping()331     const InstructionMapping &getInstrMapping() const { return InstrMapping; }
332 
333     /// The MachineRegisterInfo we used to realize the mapping.
getMRI()334     MachineRegisterInfo &getMRI() const { return MRI; }
335     /// @}
336 
337     /// Create as many new virtual registers as needed for the mapping of the \p
338     /// OpIdx-th operand.
339     /// The number of registers is determined by the number of breakdown for the
340     /// related operand in the instruction mapping.
341     /// The type of the new registers is a plain scalar of the right size.
342     /// The proper type is expected to be set when the mapping is applied to
343     /// the instruction(s) that realizes the mapping.
344     ///
345     /// \pre getMI().getOperand(OpIdx).isReg()
346     ///
347     /// \post All the partial mapping of the \p OpIdx-th operand have been
348     /// assigned a new virtual register.
349     void createVRegs(unsigned OpIdx);
350 
351     /// Set the virtual register of the \p PartialMapIdx-th partial mapping of
352     /// the OpIdx-th operand to \p NewVReg.
353     ///
354     /// \pre getMI().getOperand(OpIdx).isReg()
355     /// \pre getInstrMapping().getOperandMapping(OpIdx).BreakDown.size() >
356     /// PartialMapIdx
357     /// \pre NewReg != 0
358     ///
359     /// \post the \p PartialMapIdx-th register of the value mapping of the \p
360     /// OpIdx-th operand has been set.
361     void setVRegs(unsigned OpIdx, unsigned PartialMapIdx, Register NewVReg);
362 
363     /// Get all the virtual registers required to map the \p OpIdx-th operand of
364     /// the instruction.
365     ///
366     /// This return an empty range when createVRegs or setVRegs has not been
367     /// called.
368     /// The iterator may be invalidated by a call to setVRegs or createVRegs.
369     ///
370     /// When \p ForDebug is true, we will not check that the list of new virtual
371     /// registers does not contain uninitialized values.
372     ///
373     /// \pre getMI().getOperand(OpIdx).isReg()
374     /// \pre ForDebug || All partial mappings have been set a register
375     iterator_range<SmallVectorImpl<Register>::const_iterator>
376     getVRegs(unsigned OpIdx, bool ForDebug = false) const;
377 
378     /// Print this operands mapper on dbgs() stream.
379     void dump() const;
380 
381     /// Print this operands mapper on \p OS stream.
382     void print(raw_ostream &OS, bool ForDebug = false) const;
383   };
384 
385 protected:
386   /// Hold the set of supported register banks.
387   RegisterBank **RegBanks;
388 
389   /// Total number of register banks.
390   unsigned NumRegBanks;
391 
392   /// Keep dynamically allocated PartialMapping in a separate map.
393   /// This shouldn't be needed when everything gets TableGen'ed.
394   mutable DenseMap<unsigned, std::unique_ptr<const PartialMapping>>
395       MapOfPartialMappings;
396 
397   /// Keep dynamically allocated ValueMapping in a separate map.
398   /// This shouldn't be needed when everything gets TableGen'ed.
399   mutable DenseMap<unsigned, std::unique_ptr<const ValueMapping>>
400       MapOfValueMappings;
401 
402   /// Keep dynamically allocated array of ValueMapping in a separate map.
403   /// This shouldn't be needed when everything gets TableGen'ed.
404   mutable DenseMap<unsigned, std::unique_ptr<ValueMapping[]>>
405       MapOfOperandsMappings;
406 
407   /// Keep dynamically allocated InstructionMapping in a separate map.
408   /// This shouldn't be needed when everything gets TableGen'ed.
409   mutable DenseMap<unsigned, std::unique_ptr<const InstructionMapping>>
410       MapOfInstructionMappings;
411 
412   /// Getting the minimal register class of a physreg is expensive.
413   /// Cache this information as we get it.
414   mutable DenseMap<unsigned, const TargetRegisterClass *> PhysRegMinimalRCs;
415 
416   /// Create a RegisterBankInfo that can accommodate up to \p NumRegBanks
417   /// RegisterBank instances.
418   RegisterBankInfo(RegisterBank **RegBanks, unsigned NumRegBanks);
419 
420   /// This constructor is meaningless.
421   /// It just provides a default constructor that can be used at link time
422   /// when GlobalISel is not built.
423   /// That way, targets can still inherit from this class without doing
424   /// crazy gymnastic to avoid link time failures.
425   /// \note That works because the constructor is inlined.
RegisterBankInfo()426   RegisterBankInfo() {
427     llvm_unreachable("This constructor should not be executed");
428   }
429 
430   /// Get the register bank identified by \p ID.
getRegBank(unsigned ID)431   RegisterBank &getRegBank(unsigned ID) {
432     assert(ID < getNumRegBanks() && "Accessing an unknown register bank");
433     return *RegBanks[ID];
434   }
435 
436   /// Get the MinimalPhysRegClass for Reg.
437   /// \pre Reg is a physical register.
438   const TargetRegisterClass &
439   getMinimalPhysRegClass(Register Reg, const TargetRegisterInfo &TRI) const;
440 
441   /// Try to get the mapping of \p MI.
442   /// See getInstrMapping for more details on what a mapping represents.
443   ///
444   /// Unlike getInstrMapping the returned InstructionMapping may be invalid
445   /// (isValid() == false).
446   /// This means that the target independent code is not smart enough
447   /// to get the mapping of \p MI and thus, the target has to provide the
448   /// information for \p MI.
449   ///
450   /// This implementation is able to get the mapping of:
451   /// - Target specific instructions by looking at the encoding constraints.
452   /// - Any instruction if all the register operands have already been assigned
453   ///   a register, a register class, or a register bank.
454   /// - Copies and phis if at least one of the operands has been assigned a
455   ///   register, a register class, or a register bank.
456   /// In other words, this method will likely fail to find a mapping for
457   /// any generic opcode that has not been lowered by target specific code.
458   const InstructionMapping &getInstrMappingImpl(const MachineInstr &MI) const;
459 
460   /// Get the uniquely generated PartialMapping for the
461   /// given arguments.
462   const PartialMapping &getPartialMapping(unsigned StartIdx, unsigned Length,
463                                           const RegisterBank &RegBank) const;
464 
465   /// \name Methods to get a uniquely generated ValueMapping.
466   /// @{
467 
468   /// The most common ValueMapping consists of a single PartialMapping.
469   /// Feature a method for that.
470   const ValueMapping &getValueMapping(unsigned StartIdx, unsigned Length,
471                                       const RegisterBank &RegBank) const;
472 
473   /// Get the ValueMapping for the given arguments.
474   const ValueMapping &getValueMapping(const PartialMapping *BreakDown,
475                                       unsigned NumBreakDowns) const;
476   /// @}
477 
478   /// \name Methods to get a uniquely generated array of ValueMapping.
479   /// @{
480 
481   /// Get the uniquely generated array of ValueMapping for the
482   /// elements of between \p Begin and \p End.
483   ///
484   /// Elements that are nullptr will be replaced by
485   /// invalid ValueMapping (ValueMapping::isValid == false).
486   ///
487   /// \pre The pointers on ValueMapping between \p Begin and \p End
488   /// must uniquely identify a ValueMapping. Otherwise, there is no
489   /// guarantee that the return instance will be unique, i.e., another
490   /// OperandsMapping could have the same content.
491   template <typename Iterator>
492   const ValueMapping *getOperandsMapping(Iterator Begin, Iterator End) const;
493 
494   /// Get the uniquely generated array of ValueMapping for the
495   /// elements of \p OpdsMapping.
496   ///
497   /// Elements of \p OpdsMapping that are nullptr will be replaced by
498   /// invalid ValueMapping (ValueMapping::isValid == false).
499   const ValueMapping *getOperandsMapping(
500       const SmallVectorImpl<const ValueMapping *> &OpdsMapping) const;
501 
502   /// Get the uniquely generated array of ValueMapping for the
503   /// given arguments.
504   ///
505   /// Arguments that are nullptr will be replaced by invalid
506   /// ValueMapping (ValueMapping::isValid == false).
507   const ValueMapping *getOperandsMapping(
508       std::initializer_list<const ValueMapping *> OpdsMapping) const;
509   /// @}
510 
511   /// \name Methods to get a uniquely generated InstructionMapping.
512   /// @{
513 
514 private:
515   /// Method to get a uniquely generated InstructionMapping.
516   const InstructionMapping &
517   getInstructionMappingImpl(bool IsInvalid, unsigned ID = InvalidMappingID,
518                             unsigned Cost = 0,
519                             const ValueMapping *OperandsMapping = nullptr,
520                             unsigned NumOperands = 0) const;
521 
522 public:
523   /// Method to get a uniquely generated InstructionMapping.
524   const InstructionMapping &
getInstructionMapping(unsigned ID,unsigned Cost,const ValueMapping * OperandsMapping,unsigned NumOperands)525   getInstructionMapping(unsigned ID, unsigned Cost,
526                         const ValueMapping *OperandsMapping,
527                         unsigned NumOperands) const {
528     return getInstructionMappingImpl(/*IsInvalid*/ false, ID, Cost,
529                                      OperandsMapping, NumOperands);
530   }
531 
532   /// Method to get a uniquely generated invalid InstructionMapping.
getInvalidInstructionMapping()533   const InstructionMapping &getInvalidInstructionMapping() const {
534     return getInstructionMappingImpl(/*IsInvalid*/ true);
535   }
536   /// @}
537 
538   /// Get the register bank for the \p OpIdx-th operand of \p MI form
539   /// the encoding constraints, if any.
540   ///
541   /// \return A register bank that covers the register class of the
542   /// related encoding constraints or nullptr if \p MI did not provide
543   /// enough information to deduce it.
544   const RegisterBank *
545   getRegBankFromConstraints(const MachineInstr &MI, unsigned OpIdx,
546                             const TargetInstrInfo &TII,
547                             const MachineRegisterInfo &MRI) const;
548 
549   /// Helper method to apply something that is like the default mapping.
550   /// Basically, that means that \p OpdMapper.getMI() is left untouched
551   /// aside from the reassignment of the register operand that have been
552   /// remapped.
553   ///
554   /// The type of all the new registers that have been created by the
555   /// mapper are properly remapped to the type of the original registers
556   /// they replace. In other words, the semantic of the instruction does
557   /// not change, only the register banks.
558   ///
559   /// If the mapping of one of the operand spans several registers, this
560   /// method will abort as this is not like a default mapping anymore.
561   ///
562   /// \pre For OpIdx in {0..\p OpdMapper.getMI().getNumOperands())
563   ///        the range OpdMapper.getVRegs(OpIdx) is empty or of size 1.
564   static void applyDefaultMapping(const OperandsMapper &OpdMapper);
565 
566   /// See ::applyMapping.
applyMappingImpl(const OperandsMapper & OpdMapper)567   virtual void applyMappingImpl(const OperandsMapper &OpdMapper) const {
568     llvm_unreachable("The target has to implement that part");
569   }
570 
571 public:
572   virtual ~RegisterBankInfo() = default;
573 
574   /// Get the register bank identified by \p ID.
getRegBank(unsigned ID)575   const RegisterBank &getRegBank(unsigned ID) const {
576     return const_cast<RegisterBankInfo *>(this)->getRegBank(ID);
577   }
578 
579   /// Get the register bank of \p Reg.
580   /// If Reg has not been assigned a register, a register class,
581   /// or a register bank, then this returns nullptr.
582   ///
583   /// \pre Reg != 0 (NoRegister)
584   const RegisterBank *getRegBank(Register Reg, const MachineRegisterInfo &MRI,
585                                  const TargetRegisterInfo &TRI) const;
586 
587   /// Get the total number of register banks.
getNumRegBanks()588   unsigned getNumRegBanks() const { return NumRegBanks; }
589 
590   /// Get a register bank that covers \p RC.
591   ///
592   /// \pre \p RC is a user-defined register class (as opposed as one
593   /// generated by TableGen).
594   ///
595   /// \note The mapping RC -> RegBank could be built while adding the
596   /// coverage for the register banks. However, we do not do it, because,
597   /// at least for now, we only need this information for register classes
598   /// that are used in the description of instruction. In other words,
599   /// there are just a handful of them and we do not want to waste space.
600   ///
601   /// \todo This should be TableGen'ed.
602   virtual const RegisterBank &
getRegBankFromRegClass(const TargetRegisterClass & RC,LLT Ty)603   getRegBankFromRegClass(const TargetRegisterClass &RC, LLT Ty) const {
604     llvm_unreachable("The target must override this method");
605   }
606 
607   /// Get the cost of a copy from \p B to \p A, or put differently,
608   /// get the cost of A = COPY B. Since register banks may cover
609   /// different size, \p Size specifies what will be the size in bits
610   /// that will be copied around.
611   ///
612   /// \note Since this is a copy, both registers have the same size.
copyCost(const RegisterBank & A,const RegisterBank & B,unsigned Size)613   virtual unsigned copyCost(const RegisterBank &A, const RegisterBank &B,
614                             unsigned Size) const {
615     // Optimistically assume that copies are coalesced. I.e., when
616     // they are on the same bank, they are free.
617     // Otherwise assume a non-zero cost of 1. The targets are supposed
618     // to override that properly anyway if they care.
619     return &A != &B;
620   }
621 
622   /// \returns true if emitting a copy from \p Src to \p Dst is impossible.
cannotCopy(const RegisterBank & Dst,const RegisterBank & Src,unsigned Size)623   bool cannotCopy(const RegisterBank &Dst, const RegisterBank &Src,
624                   unsigned Size) const {
625     return copyCost(Dst, Src, Size) == std::numeric_limits<unsigned>::max();
626   }
627 
628   /// Get the cost of using \p ValMapping to decompose a register. This is
629   /// similar to ::copyCost, except for cases where multiple copy-like
630   /// operations need to be inserted. If the register is used as a source
631   /// operand and already has a bank assigned, \p CurBank is non-null.
632   virtual unsigned getBreakDownCost(const ValueMapping &ValMapping,
633                                     const RegisterBank *CurBank = nullptr) const {
634     return std::numeric_limits<unsigned>::max();
635   }
636 
637   /// Constrain the (possibly generic) virtual register \p Reg to \p RC.
638   ///
639   /// \pre \p Reg is a virtual register that either has a bank or a class.
640   /// \returns The constrained register class, or nullptr if there is none.
641   /// \note This is a generic variant of MachineRegisterInfo::constrainRegClass
642   /// \note Use MachineRegisterInfo::constrainRegAttrs instead for any non-isel
643   /// purpose, including non-select passes of GlobalISel
644   static const TargetRegisterClass *
645   constrainGenericRegister(Register Reg, const TargetRegisterClass &RC,
646                            MachineRegisterInfo &MRI);
647 
648   /// Identifier used when the related instruction mapping instance
649   /// is generated by target independent code.
650   /// Make sure not to use that identifier to avoid possible collision.
651   static const unsigned DefaultMappingID;
652 
653   /// Identifier used when the related instruction mapping instance
654   /// is generated by the default constructor.
655   /// Make sure not to use that identifier.
656   static const unsigned InvalidMappingID;
657 
658   /// Get the mapping of the different operands of \p MI
659   /// on the register bank.
660   /// This mapping should be the direct translation of \p MI.
661   /// In other words, when \p MI is mapped with the returned mapping,
662   /// only the register banks of the operands of \p MI need to be updated.
663   /// In particular, neither the opcode nor the type of \p MI needs to be
664   /// updated for this direct mapping.
665   ///
666   /// The target independent implementation gives a mapping based on
667   /// the register classes for the target specific opcode.
668   /// It uses the ID RegisterBankInfo::DefaultMappingID for that mapping.
669   /// Make sure you do not use that ID for the alternative mapping
670   /// for MI. See getInstrAlternativeMappings for the alternative
671   /// mappings.
672   ///
673   /// For instance, if \p MI is a vector add, the mapping should
674   /// not be a scalarization of the add.
675   ///
676   /// \post returnedVal.verify(MI).
677   ///
678   /// \note If returnedVal does not verify MI, this would probably mean
679   /// that the target does not support that instruction.
680   virtual const InstructionMapping &
681   getInstrMapping(const MachineInstr &MI) const;
682 
683   /// Get the alternative mappings for \p MI.
684   /// Alternative in the sense different from getInstrMapping.
685   virtual InstructionMappings
686   getInstrAlternativeMappings(const MachineInstr &MI) const;
687 
688   /// Get the possible mapping for \p MI.
689   /// A mapping defines where the different operands may live and at what cost.
690   /// For instance, let us consider:
691   /// v0(16) = G_ADD <2 x i8> v1, v2
692   /// The possible mapping could be:
693   ///
694   /// {/*ID*/VectorAdd, /*Cost*/1, /*v0*/{(0xFFFF, VPR)}, /*v1*/{(0xFFFF, VPR)},
695   ///                              /*v2*/{(0xFFFF, VPR)}}
696   /// {/*ID*/ScalarAddx2, /*Cost*/2, /*v0*/{(0x00FF, GPR),(0xFF00, GPR)},
697   ///                                /*v1*/{(0x00FF, GPR),(0xFF00, GPR)},
698   ///                                /*v2*/{(0x00FF, GPR),(0xFF00, GPR)}}
699   ///
700   /// \note The first alternative of the returned mapping should be the
701   /// direct translation of \p MI current form.
702   ///
703   /// \post !returnedVal.empty().
704   InstructionMappings getInstrPossibleMappings(const MachineInstr &MI) const;
705 
706   /// Apply \p OpdMapper.getInstrMapping() to \p OpdMapper.getMI().
707   /// After this call \p OpdMapper.getMI() may not be valid anymore.
708   /// \p OpdMapper.getInstrMapping().getID() carries the information of
709   /// what has been chosen to map \p OpdMapper.getMI(). This ID is set
710   /// by the various getInstrXXXMapping method.
711   ///
712   /// Therefore, getting the mapping and applying it should be kept in
713   /// sync.
applyMapping(const OperandsMapper & OpdMapper)714   void applyMapping(const OperandsMapper &OpdMapper) const {
715     // The only mapping we know how to handle is the default mapping.
716     if (OpdMapper.getInstrMapping().getID() == DefaultMappingID)
717       return applyDefaultMapping(OpdMapper);
718     // For other mapping, the target needs to do the right thing.
719     // If that means calling applyDefaultMapping, fine, but this
720     // must be explicitly stated.
721     applyMappingImpl(OpdMapper);
722   }
723 
724   /// Get the size in bits of \p Reg.
725   /// Utility method to get the size of any registers. Unlike
726   /// MachineRegisterInfo::getSize, the register does not need to be a
727   /// virtual register.
728   ///
729   /// \pre \p Reg != 0 (NoRegister).
730   unsigned getSizeInBits(Register Reg, const MachineRegisterInfo &MRI,
731                          const TargetRegisterInfo &TRI) const;
732 
733   /// Check that information hold by this instance make sense for the
734   /// given \p TRI.
735   ///
736   /// \note This method does not check anything when assertions are disabled.
737   ///
738   /// \return True is the check was successful.
739   bool verify(const TargetRegisterInfo &TRI) const;
740 };
741 
742 inline raw_ostream &
743 operator<<(raw_ostream &OS,
744            const RegisterBankInfo::PartialMapping &PartMapping) {
745   PartMapping.print(OS);
746   return OS;
747 }
748 
749 inline raw_ostream &
750 operator<<(raw_ostream &OS, const RegisterBankInfo::ValueMapping &ValMapping) {
751   ValMapping.print(OS);
752   return OS;
753 }
754 
755 inline raw_ostream &
756 operator<<(raw_ostream &OS,
757            const RegisterBankInfo::InstructionMapping &InstrMapping) {
758   InstrMapping.print(OS);
759   return OS;
760 }
761 
762 inline raw_ostream &
763 operator<<(raw_ostream &OS, const RegisterBankInfo::OperandsMapper &OpdMapper) {
764   OpdMapper.print(OS, /*ForDebug*/ false);
765   return OS;
766 }
767 
768 /// Hashing function for PartialMapping.
769 /// It is required for the hashing of ValueMapping.
770 hash_code hash_value(const RegisterBankInfo::PartialMapping &PartMapping);
771 
772 } // end namespace llvm
773 
774 #endif // LLVM_CODEGEN_GLOBALISEL_REGISTERBANKINFO_H
775