1 //===- CodeGenRegisters.h - Register and RegisterClass Info -----*- 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 defines structures to encapsulate information gleaned from the
10 // target register and register class definitions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_UTILS_TABLEGEN_CODEGENREGISTERS_H
15 #define LLVM_UTILS_TABLEGEN_CODEGENREGISTERS_H
16 
17 #include "InfoByHwMode.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/SparseBitVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/MC/LaneBitmask.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MachineValueType.h"
31 #include "llvm/TableGen/Record.h"
32 #include "llvm/TableGen/SetTheory.h"
33 #include <cassert>
34 #include <cstdint>
35 #include <deque>
36 #include <list>
37 #include <map>
38 #include <string>
39 #include <utility>
40 #include <vector>
41 
42 namespace llvm {
43 
44   class CodeGenRegBank;
45   template <typename T, typename Vector, typename Set> class SetVector;
46 
47   /// Used to encode a step in a register lane mask transformation.
48   /// Mask the bits specified in Mask, then rotate them Rol bits to the left
49   /// assuming a wraparound at 32bits.
50   struct MaskRolPair {
51     LaneBitmask Mask;
52     uint8_t RotateLeft;
53 
54     bool operator==(const MaskRolPair Other) const {
55       return Mask == Other.Mask && RotateLeft == Other.RotateLeft;
56     }
57     bool operator!=(const MaskRolPair Other) const {
58       return Mask != Other.Mask || RotateLeft != Other.RotateLeft;
59     }
60   };
61 
62   /// CodeGenSubRegIndex - Represents a sub-register index.
63   class CodeGenSubRegIndex {
64     Record *const TheDef;
65     std::string Name;
66     std::string Namespace;
67 
68   public:
69     uint16_t Size;
70     uint16_t Offset;
71     const unsigned EnumValue;
72     mutable LaneBitmask LaneMask;
73     mutable SmallVector<MaskRolPair,1> CompositionLaneMaskTransform;
74 
75     /// A list of subregister indexes concatenated resulting in this
76     /// subregister index. This is the reverse of CodeGenRegBank::ConcatIdx.
77     SmallVector<CodeGenSubRegIndex*,4> ConcatenationOf;
78 
79     // Are all super-registers containing this SubRegIndex covered by their
80     // sub-registers?
81     bool AllSuperRegsCovered;
82     // A subregister index is "artificial" if every subregister obtained
83     // from applying this index is artificial. Artificial subregister
84     // indexes are not used to create new register classes.
85     bool Artificial;
86 
87     CodeGenSubRegIndex(Record *R, unsigned Enum);
88     CodeGenSubRegIndex(StringRef N, StringRef Nspace, unsigned Enum);
89     CodeGenSubRegIndex(CodeGenSubRegIndex&) = delete;
90 
91     const std::string &getName() const { return Name; }
92     const std::string &getNamespace() const { return Namespace; }
93     std::string getQualifiedName() const;
94 
95     // Map of composite subreg indices.
96     typedef std::map<CodeGenSubRegIndex *, CodeGenSubRegIndex *,
97                      deref<std::less<>>>
98         CompMap;
99 
100     // Returns the subreg index that results from composing this with Idx.
101     // Returns NULL if this and Idx don't compose.
102     CodeGenSubRegIndex *compose(CodeGenSubRegIndex *Idx) const {
103       CompMap::const_iterator I = Composed.find(Idx);
104       return I == Composed.end() ? nullptr : I->second;
105     }
106 
107     // Add a composite subreg index: this+A = B.
108     // Return a conflicting composite, or NULL
109     CodeGenSubRegIndex *addComposite(CodeGenSubRegIndex *A,
110                                      CodeGenSubRegIndex *B) {
111       assert(A && B);
112       std::pair<CompMap::iterator, bool> Ins =
113         Composed.insert(std::make_pair(A, B));
114       // Synthetic subreg indices that aren't contiguous (for instance ARM
115       // register tuples) don't have a bit range, so it's OK to let
116       // B->Offset == -1. For the other cases, accumulate the offset and set
117       // the size here. Only do so if there is no offset yet though.
118       if ((Offset != (uint16_t)-1 && A->Offset != (uint16_t)-1) &&
119           (B->Offset == (uint16_t)-1)) {
120         B->Offset = Offset + A->Offset;
121         B->Size = A->Size;
122       }
123       return (Ins.second || Ins.first->second == B) ? nullptr
124                                                     : Ins.first->second;
125     }
126 
127     // Update the composite maps of components specified in 'ComposedOf'.
128     void updateComponents(CodeGenRegBank&);
129 
130     // Return the map of composites.
131     const CompMap &getComposites() const { return Composed; }
132 
133     // Compute LaneMask from Composed. Return LaneMask.
134     LaneBitmask computeLaneMask() const;
135 
136     void setConcatenationOf(ArrayRef<CodeGenSubRegIndex*> Parts);
137 
138     /// Replaces subregister indexes in the `ConcatenationOf` list with
139     /// list of subregisters they are composed of (if any). Do this recursively.
140     void computeConcatTransitiveClosure();
141 
142     bool operator<(const CodeGenSubRegIndex &RHS) const {
143       return this->EnumValue < RHS.EnumValue;
144     }
145 
146   private:
147     CompMap Composed;
148   };
149 
150   /// CodeGenRegister - Represents a register definition.
151   struct CodeGenRegister {
152     Record *TheDef;
153     unsigned EnumValue;
154     std::vector<int64_t> CostPerUse;
155     bool CoveredBySubRegs;
156     bool HasDisjunctSubRegs;
157     bool Artificial;
158 
159     // Map SubRegIndex -> Register.
160     typedef std::map<CodeGenSubRegIndex *, CodeGenRegister *,
161                      deref<std::less<>>>
162         SubRegMap;
163 
164     CodeGenRegister(Record *R, unsigned Enum);
165 
166     StringRef getName() const;
167 
168     // Extract more information from TheDef. This is used to build an object
169     // graph after all CodeGenRegister objects have been created.
170     void buildObjectGraph(CodeGenRegBank&);
171 
172     // Lazily compute a map of all sub-registers.
173     // This includes unique entries for all sub-sub-registers.
174     const SubRegMap &computeSubRegs(CodeGenRegBank&);
175 
176     // Compute extra sub-registers by combining the existing sub-registers.
177     void computeSecondarySubRegs(CodeGenRegBank&);
178 
179     // Add this as a super-register to all sub-registers after the sub-register
180     // graph has been built.
181     void computeSuperRegs(CodeGenRegBank&);
182 
183     const SubRegMap &getSubRegs() const {
184       assert(SubRegsComplete && "Must precompute sub-registers");
185       return SubRegs;
186     }
187 
188     // Add sub-registers to OSet following a pre-order defined by the .td file.
189     void addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
190                             CodeGenRegBank&) const;
191 
192     // Return the sub-register index naming Reg as a sub-register of this
193     // register. Returns NULL if Reg is not a sub-register.
194     CodeGenSubRegIndex *getSubRegIndex(const CodeGenRegister *Reg) const {
195       return SubReg2Idx.lookup(Reg);
196     }
197 
198     typedef std::vector<const CodeGenRegister*> SuperRegList;
199 
200     // Get the list of super-registers in topological order, small to large.
201     // This is valid after computeSubRegs visits all registers during RegBank
202     // construction.
203     const SuperRegList &getSuperRegs() const {
204       assert(SubRegsComplete && "Must precompute sub-registers");
205       return SuperRegs;
206     }
207 
208     // Get the list of ad hoc aliases. The graph is symmetric, so the list
209     // contains all registers in 'Aliases', and all registers that mention this
210     // register in 'Aliases'.
211     ArrayRef<CodeGenRegister*> getExplicitAliases() const {
212       return ExplicitAliases;
213     }
214 
215     // Get the topological signature of this register. This is a small integer
216     // less than RegBank.getNumTopoSigs(). Registers with the same TopoSig have
217     // identical sub-register structure. That is, they support the same set of
218     // sub-register indices mapping to the same kind of sub-registers
219     // (TopoSig-wise).
220     unsigned getTopoSig() const {
221       assert(SuperRegsComplete && "TopoSigs haven't been computed yet.");
222       return TopoSig;
223     }
224 
225     // List of register units in ascending order.
226     typedef SparseBitVector<> RegUnitList;
227     typedef SmallVector<LaneBitmask, 16> RegUnitLaneMaskList;
228 
229     // How many entries in RegUnitList are native?
230     RegUnitList NativeRegUnits;
231 
232     // Get the list of register units.
233     // This is only valid after computeSubRegs() completes.
234     const RegUnitList &getRegUnits() const { return RegUnits; }
235 
236     ArrayRef<LaneBitmask> getRegUnitLaneMasks() const {
237       return makeArrayRef(RegUnitLaneMasks).slice(0, NativeRegUnits.count());
238     }
239 
240     // Get the native register units. This is a prefix of getRegUnits().
241     RegUnitList getNativeRegUnits() const {
242       return NativeRegUnits;
243     }
244 
245     void setRegUnitLaneMasks(const RegUnitLaneMaskList &LaneMasks) {
246       RegUnitLaneMasks = LaneMasks;
247     }
248 
249     // Inherit register units from subregisters.
250     // Return true if the RegUnits changed.
251     bool inheritRegUnits(CodeGenRegBank &RegBank);
252 
253     // Adopt a register unit for pressure tracking.
254     // A unit is adopted iff its unit number is >= NativeRegUnits.count().
255     void adoptRegUnit(unsigned RUID) { RegUnits.set(RUID); }
256 
257     // Get the sum of this register's register unit weights.
258     unsigned getWeight(const CodeGenRegBank &RegBank) const;
259 
260     // Canonically ordered set.
261     typedef std::vector<const CodeGenRegister*> Vec;
262 
263   private:
264     bool SubRegsComplete;
265     bool SuperRegsComplete;
266     unsigned TopoSig;
267 
268     // The sub-registers explicit in the .td file form a tree.
269     SmallVector<CodeGenSubRegIndex*, 8> ExplicitSubRegIndices;
270     SmallVector<CodeGenRegister*, 8> ExplicitSubRegs;
271 
272     // Explicit ad hoc aliases, symmetrized to form an undirected graph.
273     SmallVector<CodeGenRegister*, 8> ExplicitAliases;
274 
275     // Super-registers where this is the first explicit sub-register.
276     SuperRegList LeadingSuperRegs;
277 
278     SubRegMap SubRegs;
279     SuperRegList SuperRegs;
280     DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*> SubReg2Idx;
281     RegUnitList RegUnits;
282     RegUnitLaneMaskList RegUnitLaneMasks;
283   };
284 
285   inline bool operator<(const CodeGenRegister &A, const CodeGenRegister &B) {
286     return A.EnumValue < B.EnumValue;
287   }
288 
289   inline bool operator==(const CodeGenRegister &A, const CodeGenRegister &B) {
290     return A.EnumValue == B.EnumValue;
291   }
292 
293   class CodeGenRegisterClass {
294     CodeGenRegister::Vec Members;
295     // Allocation orders. Order[0] always contains all registers in Members.
296     std::vector<SmallVector<Record*, 16>> Orders;
297     // Bit mask of sub-classes including this, indexed by their EnumValue.
298     BitVector SubClasses;
299     // List of super-classes, topologocally ordered to have the larger classes
300     // first.  This is the same as sorting by EnumValue.
301     SmallVector<CodeGenRegisterClass*, 4> SuperClasses;
302     Record *TheDef;
303     std::string Name;
304 
305     // For a synthesized class, inherit missing properties from the nearest
306     // super-class.
307     void inheritProperties(CodeGenRegBank&);
308 
309     // Map SubRegIndex -> sub-class.  This is the largest sub-class where all
310     // registers have a SubRegIndex sub-register.
311     DenseMap<const CodeGenSubRegIndex *, CodeGenRegisterClass *>
312         SubClassWithSubReg;
313 
314     // Map SubRegIndex -> set of super-reg classes.  This is all register
315     // classes SuperRC such that:
316     //
317     //   R:SubRegIndex in this RC for all R in SuperRC.
318     //
319     DenseMap<const CodeGenSubRegIndex *, SmallPtrSet<CodeGenRegisterClass *, 8>>
320         SuperRegClasses;
321 
322     // Bit vector of TopoSigs for the registers in this class. This will be
323     // very sparse on regular architectures.
324     BitVector TopoSigs;
325 
326   public:
327     unsigned EnumValue;
328     StringRef Namespace;
329     SmallVector<ValueTypeByHwMode, 4> VTs;
330     RegSizeInfoByHwMode RSI;
331     int CopyCost;
332     bool Allocatable;
333     StringRef AltOrderSelect;
334     uint8_t AllocationPriority;
335     uint8_t TSFlags;
336     /// Contains the combination of the lane masks of all subregisters.
337     LaneBitmask LaneMask;
338     /// True if there are at least 2 subregisters which do not interfere.
339     bool HasDisjunctSubRegs;
340     bool CoveredBySubRegs;
341     /// A register class is artificial if all its members are artificial.
342     bool Artificial;
343     /// Generate register pressure set for this register class and any class
344     /// synthesized from it.
345     bool GeneratePressureSet;
346 
347     // Return the Record that defined this class, or NULL if the class was
348     // created by TableGen.
349     Record *getDef() const { return TheDef; }
350 
351     const std::string &getName() const { return Name; }
352     std::string getQualifiedName() const;
353     ArrayRef<ValueTypeByHwMode> getValueTypes() const { return VTs; }
354     unsigned getNumValueTypes() const { return VTs.size(); }
355 
356     bool hasType(const ValueTypeByHwMode &VT) const {
357       return llvm::is_contained(VTs, VT);
358     }
359 
360     const ValueTypeByHwMode &getValueTypeNum(unsigned VTNum) const {
361       if (VTNum < VTs.size())
362         return VTs[VTNum];
363       llvm_unreachable("VTNum greater than number of ValueTypes in RegClass!");
364     }
365 
366     // Return true if this this class contains the register.
367     bool contains(const CodeGenRegister*) const;
368 
369     // Returns true if RC is a subclass.
370     // RC is a sub-class of this class if it is a valid replacement for any
371     // instruction operand where a register of this classis required. It must
372     // satisfy these conditions:
373     //
374     // 1. All RC registers are also in this.
375     // 2. The RC spill size must not be smaller than our spill size.
376     // 3. RC spill alignment must be compatible with ours.
377     //
378     bool hasSubClass(const CodeGenRegisterClass *RC) const {
379       return SubClasses.test(RC->EnumValue);
380     }
381 
382     // getSubClassWithSubReg - Returns the largest sub-class where all
383     // registers have a SubIdx sub-register.
384     CodeGenRegisterClass *
385     getSubClassWithSubReg(const CodeGenSubRegIndex *SubIdx) const {
386       return SubClassWithSubReg.lookup(SubIdx);
387     }
388 
389     /// Find largest subclass where all registers have SubIdx subregisters in
390     /// SubRegClass and the largest subregister class that contains those
391     /// subregisters without (as far as possible) also containing additional registers.
392     ///
393     /// This can be used to find a suitable pair of classes for subregister copies.
394     /// \return std::pair<SubClass, SubRegClass> where SubClass is a SubClass is
395     /// a class where every register has SubIdx and SubRegClass is a class where
396     /// every register is covered by the SubIdx subregister of SubClass.
397     Optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
398     getMatchingSubClassWithSubRegs(CodeGenRegBank &RegBank,
399                                    const CodeGenSubRegIndex *SubIdx) const;
400 
401     void setSubClassWithSubReg(const CodeGenSubRegIndex *SubIdx,
402                                CodeGenRegisterClass *SubRC) {
403       SubClassWithSubReg[SubIdx] = SubRC;
404     }
405 
406     // getSuperRegClasses - Returns a bit vector of all register classes
407     // containing only SubIdx super-registers of this class.
408     void getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
409                             BitVector &Out) const;
410 
411     // addSuperRegClass - Add a class containing only SubIdx super-registers.
412     void addSuperRegClass(CodeGenSubRegIndex *SubIdx,
413                           CodeGenRegisterClass *SuperRC) {
414       SuperRegClasses[SubIdx].insert(SuperRC);
415     }
416 
417     // getSubClasses - Returns a constant BitVector of subclasses indexed by
418     // EnumValue.
419     // The SubClasses vector includes an entry for this class.
420     const BitVector &getSubClasses() const { return SubClasses; }
421 
422     // getSuperClasses - Returns a list of super classes ordered by EnumValue.
423     // The array does not include an entry for this class.
424     ArrayRef<CodeGenRegisterClass*> getSuperClasses() const {
425       return SuperClasses;
426     }
427 
428     // Returns an ordered list of class members.
429     // The order of registers is the same as in the .td file.
430     // No = 0 is the default allocation order, No = 1 is the first alternative.
431     ArrayRef<Record*> getOrder(unsigned No = 0) const {
432         return Orders[No];
433     }
434 
435     // Return the total number of allocation orders available.
436     unsigned getNumOrders() const { return Orders.size(); }
437 
438     // Get the set of registers.  This set contains the same registers as
439     // getOrder(0).
440     const CodeGenRegister::Vec &getMembers() const { return Members; }
441 
442     // Get a bit vector of TopoSigs present in this register class.
443     const BitVector &getTopoSigs() const { return TopoSigs; }
444 
445     // Get a weight of this register class.
446     unsigned getWeight(const CodeGenRegBank&) const;
447 
448     // Populate a unique sorted list of units from a register set.
449     void buildRegUnitSet(const CodeGenRegBank &RegBank,
450                          std::vector<unsigned> &RegUnits) const;
451 
452     CodeGenRegisterClass(CodeGenRegBank&, Record *R);
453     CodeGenRegisterClass(CodeGenRegisterClass&) = delete;
454 
455     // A key representing the parts of a register class used for forming
456     // sub-classes.  Note the ordering provided by this key is not the same as
457     // the topological order used for the EnumValues.
458     struct Key {
459       const CodeGenRegister::Vec *Members;
460       RegSizeInfoByHwMode RSI;
461 
462       Key(const CodeGenRegister::Vec *M, const RegSizeInfoByHwMode &I)
463         : Members(M), RSI(I) {}
464 
465       Key(const CodeGenRegisterClass &RC)
466         : Members(&RC.getMembers()), RSI(RC.RSI) {}
467 
468       // Lexicographical order of (Members, RegSizeInfoByHwMode).
469       bool operator<(const Key&) const;
470     };
471 
472     // Create a non-user defined register class.
473     CodeGenRegisterClass(CodeGenRegBank&, StringRef Name, Key Props);
474 
475     // Called by CodeGenRegBank::CodeGenRegBank().
476     static void computeSubClasses(CodeGenRegBank&);
477   };
478 
479   // Register categories are used when we need to deterine the category a
480   // register falls into (GPR, vector, fixed, etc.) without having to know
481   // specific information about the target architecture.
482   class CodeGenRegisterCategory {
483     Record *TheDef;
484     std::string Name;
485     std::list<CodeGenRegisterClass *> Classes;
486 
487   public:
488     CodeGenRegisterCategory(CodeGenRegBank &, Record *R);
489     CodeGenRegisterCategory(CodeGenRegisterCategory &) = delete;
490 
491     // Return the Record that defined this class, or NULL if the class was
492     // created by TableGen.
493     Record *getDef() const { return TheDef; }
494 
495     std::string getName() const { return Name; }
496     std::list<CodeGenRegisterClass *> getClasses() const { return Classes; }
497   };
498 
499   // Register units are used to model interference and register pressure.
500   // Every register is assigned one or more register units such that two
501   // registers overlap if and only if they have a register unit in common.
502   //
503   // Normally, one register unit is created per leaf register. Non-leaf
504   // registers inherit the units of their sub-registers.
505   struct RegUnit {
506     // Weight assigned to this RegUnit for estimating register pressure.
507     // This is useful when equalizing weights in register classes with mixed
508     // register topologies.
509     unsigned Weight;
510 
511     // Each native RegUnit corresponds to one or two root registers. The full
512     // set of registers containing this unit can be computed as the union of
513     // these two registers and their super-registers.
514     const CodeGenRegister *Roots[2];
515 
516     // Index into RegClassUnitSets where we can find the list of UnitSets that
517     // contain this unit.
518     unsigned RegClassUnitSetsIdx;
519     // A register unit is artificial if at least one of its roots is
520     // artificial.
521     bool Artificial;
522 
523     RegUnit() : Weight(0), RegClassUnitSetsIdx(0), Artificial(false) {
524       Roots[0] = Roots[1] = nullptr;
525     }
526 
527     ArrayRef<const CodeGenRegister*> getRoots() const {
528       assert(!(Roots[1] && !Roots[0]) && "Invalid roots array");
529       return makeArrayRef(Roots, !!Roots[0] + !!Roots[1]);
530     }
531   };
532 
533   // Each RegUnitSet is a sorted vector with a name.
534   struct RegUnitSet {
535     typedef std::vector<unsigned>::const_iterator iterator;
536 
537     std::string Name;
538     std::vector<unsigned> Units;
539     unsigned Weight = 0; // Cache the sum of all unit weights.
540     unsigned Order = 0;  // Cache the sort key.
541 
542     RegUnitSet() = default;
543   };
544 
545   // Base vector for identifying TopoSigs. The contents uniquely identify a
546   // TopoSig, only computeSuperRegs needs to know how.
547   typedef SmallVector<unsigned, 16> TopoSigId;
548 
549   // CodeGenRegBank - Represent a target's registers and the relations between
550   // them.
551   class CodeGenRegBank {
552     SetTheory Sets;
553 
554     const CodeGenHwModes &CGH;
555 
556     std::deque<CodeGenSubRegIndex> SubRegIndices;
557     DenseMap<Record*, CodeGenSubRegIndex*> Def2SubRegIdx;
558 
559     CodeGenSubRegIndex *createSubRegIndex(StringRef Name, StringRef NameSpace);
560 
561     typedef std::map<SmallVector<CodeGenSubRegIndex*, 8>,
562                      CodeGenSubRegIndex*> ConcatIdxMap;
563     ConcatIdxMap ConcatIdx;
564 
565     // Registers.
566     std::deque<CodeGenRegister> Registers;
567     StringMap<CodeGenRegister*> RegistersByName;
568     DenseMap<Record*, CodeGenRegister*> Def2Reg;
569     unsigned NumNativeRegUnits;
570 
571     std::map<TopoSigId, unsigned> TopoSigs;
572 
573     // Includes native (0..NumNativeRegUnits-1) and adopted register units.
574     SmallVector<RegUnit, 8> RegUnits;
575 
576     // Register classes.
577     std::list<CodeGenRegisterClass> RegClasses;
578     DenseMap<Record*, CodeGenRegisterClass*> Def2RC;
579     typedef std::map<CodeGenRegisterClass::Key, CodeGenRegisterClass*> RCKeyMap;
580     RCKeyMap Key2RC;
581 
582     // Register categories.
583     std::list<CodeGenRegisterCategory> RegCategories;
584     DenseMap<Record *, CodeGenRegisterCategory *> Def2RCat;
585     using RCatKeyMap =
586         std::map<CodeGenRegisterClass::Key, CodeGenRegisterCategory *>;
587     RCatKeyMap Key2RCat;
588 
589     // Remember each unique set of register units. Initially, this contains a
590     // unique set for each register class. Simliar sets are coalesced with
591     // pruneUnitSets and new supersets are inferred during computeRegUnitSets.
592     std::vector<RegUnitSet> RegUnitSets;
593 
594     // Map RegisterClass index to the index of the RegUnitSet that contains the
595     // class's units and any inferred RegUnit supersets.
596     //
597     // NOTE: This could grow beyond the number of register classes when we map
598     // register units to lists of unit sets. If the list of unit sets does not
599     // already exist for a register class, we create a new entry in this vector.
600     std::vector<std::vector<unsigned>> RegClassUnitSets;
601 
602     // Give each register unit set an order based on sorting criteria.
603     std::vector<unsigned> RegUnitSetOrder;
604 
605     // Keep track of synthesized definitions generated in TupleExpander.
606     std::vector<std::unique_ptr<Record>> SynthDefs;
607 
608     // Add RC to *2RC maps.
609     void addToMaps(CodeGenRegisterClass*);
610 
611     // Create a synthetic sub-class if it is missing.
612     CodeGenRegisterClass *getOrCreateSubClass(const CodeGenRegisterClass *RC,
613                                               const CodeGenRegister::Vec *Membs,
614                                               StringRef Name);
615 
616     // Infer missing register classes.
617     void computeInferredRegisterClasses();
618     void inferCommonSubClass(CodeGenRegisterClass *RC);
619     void inferSubClassWithSubReg(CodeGenRegisterClass *RC);
620 
621     void inferMatchingSuperRegClass(CodeGenRegisterClass *RC) {
622       inferMatchingSuperRegClass(RC, RegClasses.begin());
623     }
624 
625     void inferMatchingSuperRegClass(
626         CodeGenRegisterClass *RC,
627         std::list<CodeGenRegisterClass>::iterator FirstSubRegRC);
628 
629     // Iteratively prune unit sets.
630     void pruneUnitSets();
631 
632     // Compute a weight for each register unit created during getSubRegs.
633     void computeRegUnitWeights();
634 
635     // Create a RegUnitSet for each RegClass and infer superclasses.
636     void computeRegUnitSets();
637 
638     // Populate the Composite map from sub-register relationships.
639     void computeComposites();
640 
641     // Compute a lane mask for each sub-register index.
642     void computeSubRegLaneMasks();
643 
644     /// Computes a lane mask for each register unit enumerated by a physical
645     /// register.
646     void computeRegUnitLaneMasks();
647 
648   public:
649     CodeGenRegBank(RecordKeeper&, const CodeGenHwModes&);
650     CodeGenRegBank(CodeGenRegBank&) = delete;
651 
652     SetTheory &getSets() { return Sets; }
653 
654     const CodeGenHwModes &getHwModes() const { return CGH; }
655 
656     // Sub-register indices. The first NumNamedIndices are defined by the user
657     // in the .td files. The rest are synthesized such that all sub-registers
658     // have a unique name.
659     const std::deque<CodeGenSubRegIndex> &getSubRegIndices() const {
660       return SubRegIndices;
661     }
662 
663     // Find a SubRegIndex from its Record def or add to the list if it does
664     // not exist there yet.
665     CodeGenSubRegIndex *getSubRegIdx(Record*);
666 
667     // Find a SubRegIndex from its Record def.
668     const CodeGenSubRegIndex *findSubRegIdx(const Record* Def) const;
669 
670     // Find or create a sub-register index representing the A+B composition.
671     CodeGenSubRegIndex *getCompositeSubRegIndex(CodeGenSubRegIndex *A,
672                                                 CodeGenSubRegIndex *B);
673 
674     // Find or create a sub-register index representing the concatenation of
675     // non-overlapping sibling indices.
676     CodeGenSubRegIndex *
677       getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8>&);
678 
679     const std::deque<CodeGenRegister> &getRegisters() const {
680       return Registers;
681     }
682 
683     const StringMap<CodeGenRegister *> &getRegistersByName() const {
684       return RegistersByName;
685     }
686 
687     // Find a register from its Record def.
688     CodeGenRegister *getReg(Record*);
689 
690     // Get a Register's index into the Registers array.
691     unsigned getRegIndex(const CodeGenRegister *Reg) const {
692       return Reg->EnumValue - 1;
693     }
694 
695     // Return the number of allocated TopoSigs. The first TopoSig representing
696     // leaf registers is allocated number 0.
697     unsigned getNumTopoSigs() const {
698       return TopoSigs.size();
699     }
700 
701     // Find or create a TopoSig for the given TopoSigId.
702     // This function is only for use by CodeGenRegister::computeSuperRegs().
703     // Others should simply use Reg->getTopoSig().
704     unsigned getTopoSig(const TopoSigId &Id) {
705       return TopoSigs.insert(std::make_pair(Id, TopoSigs.size())).first->second;
706     }
707 
708     // Create a native register unit that is associated with one or two root
709     // registers.
710     unsigned newRegUnit(CodeGenRegister *R0, CodeGenRegister *R1 = nullptr) {
711       RegUnits.resize(RegUnits.size() + 1);
712       RegUnit &RU = RegUnits.back();
713       RU.Roots[0] = R0;
714       RU.Roots[1] = R1;
715       RU.Artificial = R0->Artificial;
716       if (R1)
717         RU.Artificial |= R1->Artificial;
718       return RegUnits.size() - 1;
719     }
720 
721     // Create a new non-native register unit that can be adopted by a register
722     // to increase its pressure. Note that NumNativeRegUnits is not increased.
723     unsigned newRegUnit(unsigned Weight) {
724       RegUnits.resize(RegUnits.size() + 1);
725       RegUnits.back().Weight = Weight;
726       return RegUnits.size() - 1;
727     }
728 
729     // Native units are the singular unit of a leaf register. Register aliasing
730     // is completely characterized by native units. Adopted units exist to give
731     // register additional weight but don't affect aliasing.
732     bool isNativeUnit(unsigned RUID) const {
733       return RUID < NumNativeRegUnits;
734     }
735 
736     unsigned getNumNativeRegUnits() const {
737       return NumNativeRegUnits;
738     }
739 
740     RegUnit &getRegUnit(unsigned RUID) { return RegUnits[RUID]; }
741     const RegUnit &getRegUnit(unsigned RUID) const { return RegUnits[RUID]; }
742 
743     std::list<CodeGenRegisterClass> &getRegClasses() { return RegClasses; }
744 
745     const std::list<CodeGenRegisterClass> &getRegClasses() const {
746       return RegClasses;
747     }
748 
749     std::list<CodeGenRegisterCategory> &getRegCategories() {
750       return RegCategories;
751     }
752 
753     const std::list<CodeGenRegisterCategory> &getRegCategories() const {
754       return RegCategories;
755     }
756 
757     // Find a register class from its def.
758     CodeGenRegisterClass *getRegClass(const Record *) const;
759 
760     /// getRegisterClassForRegister - Find the register class that contains the
761     /// specified physical register.  If the register is not in a register
762     /// class, return null. If the register is in multiple classes, and the
763     /// classes have a superset-subset relationship and the same set of types,
764     /// return the superclass.  Otherwise return null.
765     const CodeGenRegisterClass* getRegClassForRegister(Record *R);
766 
767     // Analog of TargetRegisterInfo::getMinimalPhysRegClass. Unlike
768     // getRegClassForRegister, this tries to find the smallest class containing
769     // the physical register. If \p VT is specified, it will only find classes
770     // with a matching type
771     const CodeGenRegisterClass *
772     getMinimalPhysRegClass(Record *RegRecord, ValueTypeByHwMode *VT = nullptr);
773 
774     // Get the sum of unit weights.
775     unsigned getRegUnitSetWeight(const std::vector<unsigned> &Units) const {
776       unsigned Weight = 0;
777       for (unsigned Unit : Units)
778         Weight += getRegUnit(Unit).Weight;
779       return Weight;
780     }
781 
782     unsigned getRegSetIDAt(unsigned Order) const {
783       return RegUnitSetOrder[Order];
784     }
785 
786     const RegUnitSet &getRegSetAt(unsigned Order) const {
787       return RegUnitSets[RegUnitSetOrder[Order]];
788     }
789 
790     // Increase a RegUnitWeight.
791     void increaseRegUnitWeight(unsigned RUID, unsigned Inc) {
792       getRegUnit(RUID).Weight += Inc;
793     }
794 
795     // Get the number of register pressure dimensions.
796     unsigned getNumRegPressureSets() const { return RegUnitSets.size(); }
797 
798     // Get a set of register unit IDs for a given dimension of pressure.
799     const RegUnitSet &getRegPressureSet(unsigned Idx) const {
800       return RegUnitSets[Idx];
801     }
802 
803     // The number of pressure set lists may be larget than the number of
804     // register classes if some register units appeared in a list of sets that
805     // did not correspond to an existing register class.
806     unsigned getNumRegClassPressureSetLists() const {
807       return RegClassUnitSets.size();
808     }
809 
810     // Get a list of pressure set IDs for a register class. Liveness of a
811     // register in this class impacts each pressure set in this list by the
812     // weight of the register. An exact solution requires all registers in a
813     // class to have the same class, but it is not strictly guaranteed.
814     ArrayRef<unsigned> getRCPressureSetIDs(unsigned RCIdx) const {
815       return RegClassUnitSets[RCIdx];
816     }
817 
818     // Computed derived records such as missing sub-register indices.
819     void computeDerivedInfo();
820 
821     // Compute the set of registers completely covered by the registers in Regs.
822     // The returned BitVector will have a bit set for each register in Regs,
823     // all sub-registers, and all super-registers that are covered by the
824     // registers in Regs.
825     //
826     // This is used to compute the mask of call-preserved registers from a list
827     // of callee-saves.
828     BitVector computeCoveredRegisters(ArrayRef<Record*> Regs);
829 
830     // Bit mask of lanes that cover their registers. A sub-register index whose
831     // LaneMask is contained in CoveringLanes will be completely covered by
832     // another sub-register with the same or larger lane mask.
833     LaneBitmask CoveringLanes;
834 
835     // Helper function for printing debug information. Handles artificial
836     // (non-native) reg units.
837     void printRegUnitName(unsigned Unit) const;
838   };
839 
840 } // end namespace llvm
841 
842 #endif // LLVM_UTILS_TABLEGEN_CODEGENREGISTERS_H
843