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