Compute topological signatures of registers.
[oota-llvm.git] / utils / TableGen / CodeGenRegisters.h
1 //===- CodeGenRegisters.h - Register and RegisterClass Info -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines structures to encapsulate information gleaned from the
11 // target register and register class definitions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef CODEGEN_REGISTERS_H
16 #define CODEGEN_REGISTERS_H
17
18 #include "SetTheory.h"
19 #include "llvm/TableGen/Record.h"
20 #include "llvm/CodeGen/ValueTypes.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include <cstdlib>
27 #include <map>
28 #include <string>
29 #include <set>
30 #include <vector>
31
32 namespace llvm {
33   class CodeGenRegBank;
34
35   /// CodeGenSubRegIndex - Represents a sub-register index.
36   class CodeGenSubRegIndex {
37     Record *const TheDef;
38
39   public:
40     const unsigned EnumValue;
41
42     CodeGenSubRegIndex(Record *R, unsigned Enum);
43
44     const std::string &getName() const;
45     std::string getNamespace() const;
46     std::string getQualifiedName() const;
47
48     // Order CodeGenSubRegIndex pointers by EnumValue.
49     struct Less {
50       bool operator()(const CodeGenSubRegIndex *A,
51                       const CodeGenSubRegIndex *B) const {
52         assert(A && B);
53         return A->EnumValue < B->EnumValue;
54       }
55     };
56
57     // Map of composite subreg indices.
58     typedef std::map<CodeGenSubRegIndex*, CodeGenSubRegIndex*, Less> CompMap;
59
60     // Returns the subreg index that results from composing this with Idx.
61     // Returns NULL if this and Idx don't compose.
62     CodeGenSubRegIndex *compose(CodeGenSubRegIndex *Idx) const {
63       CompMap::const_iterator I = Composed.find(Idx);
64       return I == Composed.end() ? 0 : I->second;
65     }
66
67     // Add a composite subreg index: this+A = B.
68     // Return a conflicting composite, or NULL
69     CodeGenSubRegIndex *addComposite(CodeGenSubRegIndex *A,
70                                      CodeGenSubRegIndex *B) {
71       assert(A && B);
72       std::pair<CompMap::iterator, bool> Ins =
73         Composed.insert(std::make_pair(A, B));
74       return (Ins.second || Ins.first->second == B) ? 0 : Ins.first->second;
75     }
76
77     // Update the composite maps of components specified in 'ComposedOf'.
78     void updateComponents(CodeGenRegBank&);
79
80     // Clean out redundant composite mappings.
81     void cleanComposites();
82
83     // Return the map of composites.
84     const CompMap &getComposites() const { return Composed; }
85
86   private:
87     CompMap Composed;
88   };
89
90   /// CodeGenRegister - Represents a register definition.
91   struct CodeGenRegister {
92     Record *TheDef;
93     unsigned EnumValue;
94     unsigned CostPerUse;
95     bool CoveredBySubRegs;
96
97     // Map SubRegIndex -> Register.
98     typedef std::map<CodeGenSubRegIndex*, CodeGenRegister*,
99                      CodeGenSubRegIndex::Less> SubRegMap;
100
101     CodeGenRegister(Record *R, unsigned Enum);
102
103     const std::string &getName() const;
104
105     // Extract more information from TheDef. This is used to build an object
106     // graph after all CodeGenRegister objects have been created.
107     void buildObjectGraph(CodeGenRegBank&);
108
109     // Lazily compute a map of all sub-registers.
110     // This includes unique entries for all sub-sub-registers.
111     const SubRegMap &computeSubRegs(CodeGenRegBank&);
112
113     // Compute extra sub-registers by combining the existing sub-registers.
114     void computeSecondarySubRegs(CodeGenRegBank&);
115
116     // Add this as a super-register to all sub-registers after the sub-register
117     // graph has been built.
118     void computeSuperRegs(CodeGenRegBank&);
119
120     const SubRegMap &getSubRegs() const {
121       assert(SubRegsComplete && "Must precompute sub-registers");
122       return SubRegs;
123     }
124
125     // Add sub-registers to OSet following a pre-order defined by the .td file.
126     void addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
127                             CodeGenRegBank&) const;
128
129     // Return the sub-register index naming Reg as a sub-register of this
130     // register. Returns NULL if Reg is not a sub-register.
131     CodeGenSubRegIndex *getSubRegIndex(const CodeGenRegister *Reg) const {
132       return SubReg2Idx.lookup(Reg);
133     }
134
135     typedef std::vector<const CodeGenRegister*> SuperRegList;
136
137     // Get the list of super-registers in topological order, small to large.
138     // This is valid after computeSubRegs visits all registers during RegBank
139     // construction.
140     const SuperRegList &getSuperRegs() const {
141       assert(SubRegsComplete && "Must precompute sub-registers");
142       return SuperRegs;
143     }
144
145     // Get the topological signature of this register. This is a small integer
146     // less than RegBank.getNumTopoSigs(). Registers with the same TopoSig have
147     // identical sub-register structure. That is, they support the same set of
148     // sub-register indices mapping to the same kind of sub-registers
149     // (TopoSig-wise).
150     unsigned getTopoSig() const {
151       assert(SuperRegsComplete && "TopoSigs haven't been computed yet.");
152       return TopoSig;
153     }
154
155     // List of register units in ascending order.
156     typedef SmallVector<unsigned, 16> RegUnitList;
157
158     // Get the list of register units.
159     // This is only valid after getSubRegs() completes.
160     const RegUnitList &getRegUnits() const { return RegUnits; }
161
162     // Inherit register units from subregisters.
163     // Return true if the RegUnits changed.
164     bool inheritRegUnits(CodeGenRegBank &RegBank);
165
166     // Adopt a register unit for pressure tracking.
167     // A unit is adopted iff its unit number is >= NumNativeRegUnits.
168     void adoptRegUnit(unsigned RUID) { RegUnits.push_back(RUID); }
169
170     // Get the sum of this register's register unit weights.
171     unsigned getWeight(const CodeGenRegBank &RegBank) const;
172
173     // Order CodeGenRegister pointers by EnumValue.
174     struct Less {
175       bool operator()(const CodeGenRegister *A,
176                       const CodeGenRegister *B) const {
177         assert(A && B);
178         return A->EnumValue < B->EnumValue;
179       }
180     };
181
182     // Canonically ordered set.
183     typedef std::set<const CodeGenRegister*, Less> Set;
184
185   private:
186     bool SubRegsComplete;
187     bool SuperRegsComplete;
188     unsigned TopoSig;
189
190     // The sub-registers explicit in the .td file form a tree.
191     SmallVector<CodeGenSubRegIndex*, 8> ExplicitSubRegIndices;
192     SmallVector<CodeGenRegister*, 8> ExplicitSubRegs;
193
194     // Super-registers where this is the first explicit sub-register.
195     SuperRegList LeadingSuperRegs;
196
197     SubRegMap SubRegs;
198     SuperRegList SuperRegs;
199     DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*> SubReg2Idx;
200     RegUnitList RegUnits;
201   };
202
203
204   class CodeGenRegisterClass {
205     CodeGenRegister::Set Members;
206     // Allocation orders. Order[0] always contains all registers in Members.
207     std::vector<SmallVector<Record*, 16> > Orders;
208     // Bit mask of sub-classes including this, indexed by their EnumValue.
209     BitVector SubClasses;
210     // List of super-classes, topologocally ordered to have the larger classes
211     // first.  This is the same as sorting by EnumValue.
212     SmallVector<CodeGenRegisterClass*, 4> SuperClasses;
213     Record *TheDef;
214     std::string Name;
215
216     // For a synthesized class, inherit missing properties from the nearest
217     // super-class.
218     void inheritProperties(CodeGenRegBank&);
219
220     // Map SubRegIndex -> sub-class.  This is the largest sub-class where all
221     // registers have a SubRegIndex sub-register.
222     DenseMap<CodeGenSubRegIndex*, CodeGenRegisterClass*> SubClassWithSubReg;
223
224     // Map SubRegIndex -> set of super-reg classes.  This is all register
225     // classes SuperRC such that:
226     //
227     //   R:SubRegIndex in this RC for all R in SuperRC.
228     //
229     DenseMap<CodeGenSubRegIndex*,
230              SmallPtrSet<CodeGenRegisterClass*, 8> > SuperRegClasses;
231
232     // Bit vector of TopoSigs for the registers in this class. This will be
233     // very sparse on regular architectures.
234     BitVector TopoSigs;
235
236   public:
237     unsigned EnumValue;
238     std::string Namespace;
239     std::vector<MVT::SimpleValueType> VTs;
240     unsigned SpillSize;
241     unsigned SpillAlignment;
242     int CopyCost;
243     bool Allocatable;
244     std::string AltOrderSelect;
245
246     // Return the Record that defined this class, or NULL if the class was
247     // created by TableGen.
248     Record *getDef() const { return TheDef; }
249
250     const std::string &getName() const { return Name; }
251     std::string getQualifiedName() const;
252     const std::vector<MVT::SimpleValueType> &getValueTypes() const {return VTs;}
253     unsigned getNumValueTypes() const { return VTs.size(); }
254
255     MVT::SimpleValueType getValueTypeNum(unsigned VTNum) const {
256       if (VTNum < VTs.size())
257         return VTs[VTNum];
258       llvm_unreachable("VTNum greater than number of ValueTypes in RegClass!");
259     }
260
261     // Return true if this this class contains the register.
262     bool contains(const CodeGenRegister*) const;
263
264     // Returns true if RC is a subclass.
265     // RC is a sub-class of this class if it is a valid replacement for any
266     // instruction operand where a register of this classis required. It must
267     // satisfy these conditions:
268     //
269     // 1. All RC registers are also in this.
270     // 2. The RC spill size must not be smaller than our spill size.
271     // 3. RC spill alignment must be compatible with ours.
272     //
273     bool hasSubClass(const CodeGenRegisterClass *RC) const {
274       return SubClasses.test(RC->EnumValue);
275     }
276
277     // getSubClassWithSubReg - Returns the largest sub-class where all
278     // registers have a SubIdx sub-register.
279     CodeGenRegisterClass*
280     getSubClassWithSubReg(CodeGenSubRegIndex *SubIdx) const {
281       return SubClassWithSubReg.lookup(SubIdx);
282     }
283
284     void setSubClassWithSubReg(CodeGenSubRegIndex *SubIdx,
285                                CodeGenRegisterClass *SubRC) {
286       SubClassWithSubReg[SubIdx] = SubRC;
287     }
288
289     // getSuperRegClasses - Returns a bit vector of all register classes
290     // containing only SubIdx super-registers of this class.
291     void getSuperRegClasses(CodeGenSubRegIndex *SubIdx, BitVector &Out) const;
292
293     // addSuperRegClass - Add a class containing only SudIdx super-registers.
294     void addSuperRegClass(CodeGenSubRegIndex *SubIdx,
295                           CodeGenRegisterClass *SuperRC) {
296       SuperRegClasses[SubIdx].insert(SuperRC);
297     }
298
299     // getSubClasses - Returns a constant BitVector of subclasses indexed by
300     // EnumValue.
301     // The SubClasses vector includs an entry for this class.
302     const BitVector &getSubClasses() const { return SubClasses; }
303
304     // getSuperClasses - Returns a list of super classes ordered by EnumValue.
305     // The array does not include an entry for this class.
306     ArrayRef<CodeGenRegisterClass*> getSuperClasses() const {
307       return SuperClasses;
308     }
309
310     // Returns an ordered list of class members.
311     // The order of registers is the same as in the .td file.
312     // No = 0 is the default allocation order, No = 1 is the first alternative.
313     ArrayRef<Record*> getOrder(unsigned No = 0) const {
314         return Orders[No];
315     }
316
317     // Return the total number of allocation orders available.
318     unsigned getNumOrders() const { return Orders.size(); }
319
320     // Get the set of registers.  This set contains the same registers as
321     // getOrder(0).
322     const CodeGenRegister::Set &getMembers() const { return Members; }
323
324     // Get a bit vector of TopoSigs present in this register class.
325     const BitVector &getTopoSigs() const { return TopoSigs; }
326
327     // Populate a unique sorted list of units from a register set.
328     void buildRegUnitSet(std::vector<unsigned> &RegUnits) const;
329
330     CodeGenRegisterClass(CodeGenRegBank&, Record *R);
331
332     // A key representing the parts of a register class used for forming
333     // sub-classes.  Note the ordering provided by this key is not the same as
334     // the topological order used for the EnumValues.
335     struct Key {
336       const CodeGenRegister::Set *Members;
337       unsigned SpillSize;
338       unsigned SpillAlignment;
339
340       Key(const Key &O)
341         : Members(O.Members),
342           SpillSize(O.SpillSize),
343           SpillAlignment(O.SpillAlignment) {}
344
345       Key(const CodeGenRegister::Set *M, unsigned S = 0, unsigned A = 0)
346         : Members(M), SpillSize(S), SpillAlignment(A) {}
347
348       Key(const CodeGenRegisterClass &RC)
349         : Members(&RC.getMembers()),
350           SpillSize(RC.SpillSize),
351           SpillAlignment(RC.SpillAlignment) {}
352
353       // Lexicographical order of (Members, SpillSize, SpillAlignment).
354       bool operator<(const Key&) const;
355     };
356
357     // Create a non-user defined register class.
358     CodeGenRegisterClass(StringRef Name, Key Props);
359
360     // Called by CodeGenRegBank::CodeGenRegBank().
361     static void computeSubClasses(CodeGenRegBank&);
362   };
363
364   // Each RegUnitSet is a sorted vector with a name.
365   struct RegUnitSet {
366     typedef std::vector<unsigned>::const_iterator iterator;
367
368     std::string Name;
369     std::vector<unsigned> Units;
370   };
371
372   // Base vector for identifying TopoSigs. The contents uniquely identify a
373   // TopoSig, only computeSuperRegs needs to know how.
374   typedef SmallVector<unsigned, 16> TopoSigId;
375
376   // CodeGenRegBank - Represent a target's registers and the relations between
377   // them.
378   class CodeGenRegBank {
379     RecordKeeper &Records;
380     SetTheory Sets;
381
382     // SubRegIndices.
383     std::vector<CodeGenSubRegIndex*> SubRegIndices;
384     DenseMap<Record*, CodeGenSubRegIndex*> Def2SubRegIdx;
385     unsigned NumNamedIndices;
386
387     typedef std::map<SmallVector<CodeGenSubRegIndex*, 8>,
388                      CodeGenSubRegIndex*> ConcatIdxMap;
389     ConcatIdxMap ConcatIdx;
390
391     // Registers.
392     std::vector<CodeGenRegister*> Registers;
393     DenseMap<Record*, CodeGenRegister*> Def2Reg;
394     unsigned NumNativeRegUnits;
395     unsigned NumRegUnits; // # native + adopted register units.
396
397     std::map<TopoSigId, unsigned> TopoSigs;
398
399     // Map each register unit to a weight (for register pressure).
400     // Includes native and adopted register units.
401     std::vector<unsigned> RegUnitWeights;
402
403     // Register classes.
404     std::vector<CodeGenRegisterClass*> RegClasses;
405     DenseMap<Record*, CodeGenRegisterClass*> Def2RC;
406     typedef std::map<CodeGenRegisterClass::Key, CodeGenRegisterClass*> RCKeyMap;
407     RCKeyMap Key2RC;
408
409     // Remember each unique set of register units. Initially, this contains a
410     // unique set for each register class. Simliar sets are coalesced with
411     // pruneUnitSets and new supersets are inferred during computeRegUnitSets.
412     std::vector<RegUnitSet> RegUnitSets;
413
414     // Map RegisterClass index to the index of the RegUnitSet that contains the
415     // class's units and any inferred RegUnit supersets.
416     std::vector<std::vector<unsigned> > RegClassUnitSets;
417
418     // Add RC to *2RC maps.
419     void addToMaps(CodeGenRegisterClass*);
420
421     // Create a synthetic sub-class if it is missing.
422     CodeGenRegisterClass *getOrCreateSubClass(const CodeGenRegisterClass *RC,
423                                               const CodeGenRegister::Set *Membs,
424                                               StringRef Name);
425
426     // Infer missing register classes.
427     void computeInferredRegisterClasses();
428     void inferCommonSubClass(CodeGenRegisterClass *RC);
429     void inferSubClassWithSubReg(CodeGenRegisterClass *RC);
430     void inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
431                                     unsigned FirstSubRegRC = 0);
432
433     // Iteratively prune unit sets.
434     void pruneUnitSets();
435
436     // Compute a weight for each register unit created during getSubRegs.
437     void computeRegUnitWeights();
438
439     // Create a RegUnitSet for each RegClass and infer superclasses.
440     void computeRegUnitSets();
441
442     // Populate the Composite map from sub-register relationships.
443     void computeComposites();
444
445   public:
446     CodeGenRegBank(RecordKeeper&);
447
448     SetTheory &getSets() { return Sets; }
449
450     // Sub-register indices. The first NumNamedIndices are defined by the user
451     // in the .td files. The rest are synthesized such that all sub-registers
452     // have a unique name.
453     ArrayRef<CodeGenSubRegIndex*> getSubRegIndices() { return SubRegIndices; }
454     unsigned getNumNamedIndices() { return NumNamedIndices; }
455
456     // Find a SubRegIndex form its Record def.
457     CodeGenSubRegIndex *getSubRegIdx(Record*);
458
459     // Find or create a sub-register index representing the A+B composition.
460     CodeGenSubRegIndex *getCompositeSubRegIndex(CodeGenSubRegIndex *A,
461                                                 CodeGenSubRegIndex *B);
462
463     // Find or create a sub-register index representing the concatenation of
464     // non-overlapping sibling indices.
465     CodeGenSubRegIndex *
466       getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex*, 8>&);
467
468     void
469     addConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex*, 8> &Parts,
470                          CodeGenSubRegIndex *Idx) {
471       ConcatIdx.insert(std::make_pair(Parts, Idx));
472     }
473
474     const std::vector<CodeGenRegister*> &getRegisters() { return Registers; }
475
476     // Find a register from its Record def.
477     CodeGenRegister *getReg(Record*);
478
479     // Get a Register's index into the Registers array.
480     unsigned getRegIndex(const CodeGenRegister *Reg) const {
481       return Reg->EnumValue - 1;
482     }
483
484     // Return the number of allocated TopoSigs. The first TopoSig representing
485     // leaf registers is allocated number 0.
486     unsigned getNumTopoSigs() const {
487       return TopoSigs.size();
488     }
489
490     // Find or create a TopoSig for the given TopoSigId.
491     // This function is only for use by CodeGenRegister::computeSuperRegs().
492     // Others should simply use Reg->getTopoSig().
493     unsigned getTopoSig(const TopoSigId &Id) {
494       return TopoSigs.insert(std::make_pair(Id, TopoSigs.size())).first->second;
495     }
496
497     // Create a new non-native register unit that can be adopted by a register
498     // to increase its pressure. Note that NumNativeRegUnits is not increased.
499     unsigned newRegUnit(unsigned Weight) {
500       if (!RegUnitWeights.empty()) {
501         assert(Weight && "should only add allocatable units");
502         RegUnitWeights.resize(NumRegUnits+1);
503         RegUnitWeights[NumRegUnits] = Weight;
504       }
505       return NumRegUnits++;
506     }
507
508     // Native units are the singular unit of a leaf register. Register aliasing
509     // is completely characterized by native units. Adopted units exist to give
510     // register additional weight but don't affect aliasing.
511     bool isNativeUnit(unsigned RUID) {
512       return RUID < NumNativeRegUnits;
513     }
514
515     ArrayRef<CodeGenRegisterClass*> getRegClasses() const {
516       return RegClasses;
517     }
518
519     // Find a register class from its def.
520     CodeGenRegisterClass *getRegClass(Record*);
521
522     /// getRegisterClassForRegister - Find the register class that contains the
523     /// specified physical register.  If the register is not in a register
524     /// class, return null. If the register is in multiple classes, and the
525     /// classes have a superset-subset relationship and the same set of types,
526     /// return the superclass.  Otherwise return null.
527     const CodeGenRegisterClass* getRegClassForRegister(Record *R);
528
529     // Get a register unit's weight. Zero for unallocatable registers.
530     unsigned getRegUnitWeight(unsigned RUID) const {
531       return RegUnitWeights[RUID];
532     }
533
534     // Get the sum of unit weights.
535     unsigned getRegUnitSetWeight(const std::vector<unsigned> &Units) const {
536       unsigned Weight = 0;
537       for (std::vector<unsigned>::const_iterator
538              I = Units.begin(), E = Units.end(); I != E; ++I)
539         Weight += getRegUnitWeight(*I);
540       return Weight;
541     }
542
543     // Increase a RegUnitWeight.
544     void increaseRegUnitWeight(unsigned RUID, unsigned Inc) {
545       RegUnitWeights[RUID] += Inc;
546     }
547
548     // Get the number of register pressure dimensions.
549     unsigned getNumRegPressureSets() const { return RegUnitSets.size(); }
550
551     // Get a set of register unit IDs for a given dimension of pressure.
552     RegUnitSet getRegPressureSet(unsigned Idx) const {
553       return RegUnitSets[Idx];
554     }
555
556     // Get a list of pressure set IDs for a register class. Liveness of a
557     // register in this class impacts each pressure set in this list by the
558     // weight of the register. An exact solution requires all registers in a
559     // class to have the same class, but it is not strictly guaranteed.
560     ArrayRef<unsigned> getRCPressureSetIDs(unsigned RCIdx) const {
561       return RegClassUnitSets[RCIdx];
562     }
563
564     // Computed derived records such as missing sub-register indices.
565     void computeDerivedInfo();
566
567     // Compute full overlap sets for every register. These sets include the
568     // rarely used aliases that are neither sub nor super-registers.
569     //
570     // Map[R1].count(R2) is reflexive and symmetric, but not transitive.
571     //
572     // If R1 is a sub-register of R2, Map[R1] is a subset of Map[R2].
573     void computeOverlaps(std::map<const CodeGenRegister*,
574                                   CodeGenRegister::Set> &Map);
575
576     // Compute the set of registers completely covered by the registers in Regs.
577     // The returned BitVector will have a bit set for each register in Regs,
578     // all sub-registers, and all super-registers that are covered by the
579     // registers in Regs.
580     //
581     // This is used to compute the mask of call-preserved registers from a list
582     // of callee-saves.
583     BitVector computeCoveredRegisters(ArrayRef<Record*> Regs);
584   };
585 }
586
587 #endif