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