89358c8d2fc7289616648e54f71c512f703bf7bc
[oota-llvm.git] / utils / TableGen / CodeGenRegisters.cpp
1 //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
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 #include "CodeGenRegisters.h"
16 #include "CodeGenTarget.h"
17 #include "llvm/TableGen/Error.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringExtras.h"
21
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 //                              CodeGenRegister
26 //===----------------------------------------------------------------------===//
27
28 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
29   : TheDef(R),
30     EnumValue(Enum),
31     CostPerUse(R->getValueAsInt("CostPerUse")),
32     SubRegsComplete(false)
33 {}
34
35 const std::string &CodeGenRegister::getName() const {
36   return TheDef->getName();
37 }
38
39 namespace {
40   struct Orphan {
41     CodeGenRegister *SubReg;
42     Record *First, *Second;
43     Orphan(CodeGenRegister *r, Record *a, Record *b)
44       : SubReg(r), First(a), Second(b) {}
45   };
46 }
47
48 const CodeGenRegister::SubRegMap &
49 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) {
50   // Only compute this map once.
51   if (SubRegsComplete)
52     return SubRegs;
53   SubRegsComplete = true;
54
55   std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
56   std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
57   if (SubList.size() != Indices.size())
58     throw TGError(TheDef->getLoc(), "Register " + getName() +
59                   " SubRegIndices doesn't match SubRegs");
60
61   // First insert the direct subregs and make sure they are fully indexed.
62   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
63     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
64     if (!SubRegs.insert(std::make_pair(Indices[i], SR)).second)
65       throw TGError(TheDef->getLoc(), "SubRegIndex " + Indices[i]->getName() +
66                     " appears twice in Register " + getName());
67   }
68
69   // Keep track of inherited subregs and how they can be reached.
70   SmallVector<Orphan, 8> Orphans;
71
72   // Clone inherited subregs and place duplicate entries on Orphans.
73   // Here the order is important - earlier subregs take precedence.
74   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
75     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
76     const SubRegMap &Map = SR->getSubRegs(RegBank);
77
78     // Add this as a super-register of SR now all sub-registers are in the list.
79     // This creates a topological ordering, the exact order depends on the
80     // order getSubRegs is called on all registers.
81     SR->SuperRegs.push_back(this);
82
83     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
84          ++SI) {
85       if (!SubRegs.insert(*SI).second)
86         Orphans.push_back(Orphan(SI->second, Indices[i], SI->first));
87
88       // Noop sub-register indexes are possible, so avoid duplicates.
89       if (SI->second != SR)
90         SI->second->SuperRegs.push_back(this);
91     }
92   }
93
94   // Process the composites.
95   ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
96   for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
97     DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
98     if (!Pat)
99       throw TGError(TheDef->getLoc(), "Invalid dag '" +
100                     Comps->getElement(i)->getAsString() +
101                     "' in CompositeIndices");
102     DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
103     if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
104       throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
105                     Pat->getAsString());
106
107     // Resolve list of subreg indices into R2.
108     CodeGenRegister *R2 = this;
109     for (DagInit::const_arg_iterator di = Pat->arg_begin(),
110          de = Pat->arg_end(); di != de; ++di) {
111       DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
112       if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
113         throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
114                       Pat->getAsString());
115       const SubRegMap &R2Subs = R2->getSubRegs(RegBank);
116       SubRegMap::const_iterator ni = R2Subs.find(IdxInit->getDef());
117       if (ni == R2Subs.end())
118         throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
119                       " refers to bad index in " + R2->getName());
120       R2 = ni->second;
121     }
122
123     // Insert composite index. Allow overriding inherited indices etc.
124     SubRegs[BaseIdxInit->getDef()] = R2;
125
126     // R2 is no longer an orphan.
127     for (unsigned j = 0, je = Orphans.size(); j != je; ++j)
128       if (Orphans[j].SubReg == R2)
129           Orphans[j].SubReg = 0;
130   }
131
132   // Now Orphans contains the inherited subregisters without a direct index.
133   // Create inferred indexes for all missing entries.
134   for (unsigned i = 0, e = Orphans.size(); i != e; ++i) {
135     Orphan &O = Orphans[i];
136     if (!O.SubReg)
137       continue;
138     SubRegs[RegBank.getCompositeSubRegIndex(O.First, O.Second, true)] =
139       O.SubReg;
140   }
141   return SubRegs;
142 }
143
144 void
145 CodeGenRegister::addSubRegsPreOrder(SetVector<CodeGenRegister*> &OSet) const {
146   assert(SubRegsComplete && "Must precompute sub-registers");
147   std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
148   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
149     CodeGenRegister *SR = SubRegs.find(Indices[i])->second;
150     if (OSet.insert(SR))
151       SR->addSubRegsPreOrder(OSet);
152   }
153 }
154
155 //===----------------------------------------------------------------------===//
156 //                               RegisterTuples
157 //===----------------------------------------------------------------------===//
158
159 // A RegisterTuples def is used to generate pseudo-registers from lists of
160 // sub-registers. We provide a SetTheory expander class that returns the new
161 // registers.
162 namespace {
163 struct TupleExpander : SetTheory::Expander {
164   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
165     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
166     unsigned Dim = Indices.size();
167     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
168     if (Dim != SubRegs->getSize())
169       throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
170     if (Dim < 2)
171       throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers");
172
173     // Evaluate the sub-register lists to be zipped.
174     unsigned Length = ~0u;
175     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
176     for (unsigned i = 0; i != Dim; ++i) {
177       ST.evaluate(SubRegs->getElement(i), Lists[i]);
178       Length = std::min(Length, unsigned(Lists[i].size()));
179     }
180
181     if (Length == 0)
182       return;
183
184     // Precompute some types.
185     Record *RegisterCl = Def->getRecords().getClass("Register");
186     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
187     StringInit *BlankName = StringInit::get("");
188
189     // Zip them up.
190     for (unsigned n = 0; n != Length; ++n) {
191       std::string Name;
192       Record *Proto = Lists[0][n];
193       std::vector<Init*> Tuple;
194       unsigned CostPerUse = 0;
195       for (unsigned i = 0; i != Dim; ++i) {
196         Record *Reg = Lists[i][n];
197         if (i) Name += '_';
198         Name += Reg->getName();
199         Tuple.push_back(DefInit::get(Reg));
200         CostPerUse = std::max(CostPerUse,
201                               unsigned(Reg->getValueAsInt("CostPerUse")));
202       }
203
204       // Create a new Record representing the synthesized register. This record
205       // is only for consumption by CodeGenRegister, it is not added to the
206       // RecordKeeper.
207       Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
208       Elts.insert(NewReg);
209
210       // Copy Proto super-classes.
211       for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i)
212         NewReg->addSuperClass(Proto->getSuperClasses()[i]);
213
214       // Copy Proto fields.
215       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
216         RecordVal RV = Proto->getValues()[i];
217
218         if (RV.getName() == "NAME")
219           continue;
220
221         // Replace the sub-register list with Tuple.
222         if (RV.getName() == "SubRegs")
223           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
224
225         // Provide a blank AsmName. MC hacks are required anyway.
226         if (RV.getName() == "AsmName")
227           RV.setValue(BlankName);
228
229         // CostPerUse is aggregated from all Tuple members.
230         if (RV.getName() == "CostPerUse")
231           RV.setValue(IntInit::get(CostPerUse));
232
233         // Copy fields from the RegisterTuples def.
234         if (RV.getName() == "SubRegIndices" ||
235             RV.getName() == "CompositeIndices") {
236           NewReg->addValue(*Def->getValue(RV.getName()));
237           continue;
238         }
239
240         // Some fields get their default uninitialized value.
241         if (RV.getName() == "DwarfNumbers" ||
242             RV.getName() == "DwarfAlias" ||
243             RV.getName() == "Aliases") {
244           if (const RecordVal *DefRV = RegisterCl->getValue(RV.getName()))
245             NewReg->addValue(*DefRV);
246           continue;
247         }
248
249         // Everything else is copied from Proto.
250         NewReg->addValue(RV);
251       }
252     }
253   }
254 };
255 }
256
257 //===----------------------------------------------------------------------===//
258 //                            CodeGenRegisterClass
259 //===----------------------------------------------------------------------===//
260
261 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
262   : TheDef(R), Name(R->getName()), EnumValue(-1) {
263   // Rename anonymous register classes.
264   if (R->getName().size() > 9 && R->getName()[9] == '.') {
265     static unsigned AnonCounter = 0;
266     R->setName("AnonRegClass_"+utostr(AnonCounter++));
267   }
268
269   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
270   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
271     Record *Type = TypeList[i];
272     if (!Type->isSubClassOf("ValueType"))
273       throw "RegTypes list member '" + Type->getName() +
274         "' does not derive from the ValueType class!";
275     VTs.push_back(getValueType(Type));
276   }
277   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
278
279   // Allocation order 0 is the full set. AltOrders provides others.
280   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
281   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
282   Orders.resize(1 + AltOrders->size());
283
284   // Default allocation order always contains all registers.
285   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
286     Orders[0].push_back((*Elements)[i]);
287     Members.insert(RegBank.getReg((*Elements)[i]));
288   }
289
290   // Alternative allocation orders may be subsets.
291   SetTheory::RecSet Order;
292   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
293     RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
294     Orders[1 + i].append(Order.begin(), Order.end());
295     // Verify that all altorder members are regclass members.
296     while (!Order.empty()) {
297       CodeGenRegister *Reg = RegBank.getReg(Order.back());
298       Order.pop_back();
299       if (!contains(Reg))
300         throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
301                       " is not a class member");
302     }
303   }
304
305   // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
306   ListInit *SRC = R->getValueAsListInit("SubRegClasses");
307   for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
308     DagInit *DAG = dynamic_cast<DagInit*>(*i);
309     if (!DAG) throw "SubRegClasses must contain DAGs";
310     DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
311     Record *RCRec;
312     if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
313       throw "Operator '" + DAG->getOperator()->getAsString() +
314         "' in SubRegClasses is not a RegisterClass";
315     // Iterate over args, all SubRegIndex instances.
316     for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
317          ai != ae; ++ai) {
318       DefInit *Idx = dynamic_cast<DefInit*>(*ai);
319       Record *IdxRec;
320       if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
321         throw "Argument '" + (*ai)->getAsString() +
322           "' in SubRegClasses is not a SubRegIndex";
323       if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
324         throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
325     }
326   }
327
328   // Allow targets to override the size in bits of the RegisterClass.
329   unsigned Size = R->getValueAsInt("Size");
330
331   Namespace = R->getValueAsString("Namespace");
332   SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
333   SpillAlignment = R->getValueAsInt("Alignment");
334   CopyCost = R->getValueAsInt("CopyCost");
335   Allocatable = R->getValueAsBit("isAllocatable");
336   AltOrderSelect = R->getValueAsString("AltOrderSelect");
337 }
338
339 // Create an inferred register class that was missing from the .td files.
340 // Most properties will be inherited from the closest super-class after the
341 // class structure has been computed.
342 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props)
343   : Members(*Props.Members),
344     TheDef(0),
345     Name(Name),
346     EnumValue(-1),
347     SpillSize(Props.SpillSize),
348     SpillAlignment(Props.SpillAlignment),
349     CopyCost(0),
350     Allocatable(true) {
351 }
352
353 // Compute inherited propertied for a synthesized register class.
354 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
355   assert(!getDef() && "Only synthesized classes can inherit properties");
356   assert(!SuperClasses.empty() && "Synthesized class without super class");
357
358   // The last super-class is the smallest one.
359   CodeGenRegisterClass &Super = *SuperClasses.back();
360
361   // Most properties are copied directly.
362   // Exceptions are members, size, and alignment
363   Namespace = Super.Namespace;
364   VTs = Super.VTs;
365   CopyCost = Super.CopyCost;
366   Allocatable = Super.Allocatable;
367   AltOrderSelect = Super.AltOrderSelect;
368
369   // Copy all allocation orders, filter out foreign registers from the larger
370   // super-class.
371   Orders.resize(Super.Orders.size());
372   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
373     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
374       if (contains(RegBank.getReg(Super.Orders[i][j])))
375         Orders[i].push_back(Super.Orders[i][j]);
376 }
377
378 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
379   return Members.count(Reg);
380 }
381
382 namespace llvm {
383   raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
384     OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
385     for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
386          E = K.Members->end(); I != E; ++I)
387       OS << ", " << (*I)->getName();
388     return OS << " }";
389   }
390 }
391
392 // This is a simple lexicographical order that can be used to search for sets.
393 // It is not the same as the topological order provided by TopoOrderRC.
394 bool CodeGenRegisterClass::Key::
395 operator<(const CodeGenRegisterClass::Key &B) const {
396   assert(Members && B.Members);
397   if (*Members != *B.Members)
398     return *Members < *B.Members;
399   if (SpillSize != B.SpillSize)
400     return SpillSize < B.SpillSize;
401   return SpillAlignment < B.SpillAlignment;
402 }
403
404 // Returns true if RC is a strict subclass.
405 // RC is a sub-class of this class if it is a valid replacement for any
406 // instruction operand where a register of this classis required. It must
407 // satisfy these conditions:
408 //
409 // 1. All RC registers are also in this.
410 // 2. The RC spill size must not be smaller than our spill size.
411 // 3. RC spill alignment must be compatible with ours.
412 //
413 static bool testSubClass(const CodeGenRegisterClass *A,
414                          const CodeGenRegisterClass *B) {
415   return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
416     A->SpillSize <= B->SpillSize &&
417     std::includes(A->getMembers().begin(), A->getMembers().end(),
418                   B->getMembers().begin(), B->getMembers().end(),
419                   CodeGenRegister::Less());
420 }
421
422 /// Sorting predicate for register classes.  This provides a topological
423 /// ordering that arranges all register classes before their sub-classes.
424 ///
425 /// Register classes with the same registers, spill size, and alignment form a
426 /// clique.  They will be ordered alphabetically.
427 ///
428 static int TopoOrderRC(const void *PA, const void *PB) {
429   const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
430   const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
431   if (A == B)
432     return 0;
433
434   // Order by descending set size.  Note that the classes' allocation order may
435   // not have been computed yet.  The Members set is always vaild.
436   if (A->getMembers().size() > B->getMembers().size())
437     return -1;
438   if (A->getMembers().size() < B->getMembers().size())
439     return 1;
440
441   // Order by ascending spill size.
442   if (A->SpillSize < B->SpillSize)
443     return -1;
444   if (A->SpillSize > B->SpillSize)
445     return 1;
446
447   // Order by ascending spill alignment.
448   if (A->SpillAlignment < B->SpillAlignment)
449     return -1;
450   if (A->SpillAlignment > B->SpillAlignment)
451     return 1;
452
453   // Finally order by name as a tie breaker.
454   return A->getName() < B->getName();
455 }
456
457 std::string CodeGenRegisterClass::getQualifiedName() const {
458   if (Namespace.empty())
459     return getName();
460   else
461     return Namespace + "::" + getName();
462 }
463
464 // Compute sub-classes of all register classes.
465 // Assume the classes are ordered topologically.
466 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
467   ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
468
469   // Visit backwards so sub-classes are seen first.
470   for (unsigned rci = RegClasses.size(); rci; --rci) {
471     CodeGenRegisterClass &RC = *RegClasses[rci - 1];
472     RC.SubClasses.resize(RegClasses.size());
473     RC.SubClasses.set(RC.EnumValue);
474
475     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
476     for (unsigned s = rci; s != RegClasses.size(); ++s) {
477       if (RC.SubClasses.test(s))
478         continue;
479       CodeGenRegisterClass *SubRC = RegClasses[s];
480       if (!testSubClass(&RC, SubRC))
481         continue;
482       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
483       // check them again.
484       RC.SubClasses |= SubRC->SubClasses;
485     }
486
487     // Sweep up missed clique members.  They will be immediately preceeding RC.
488     for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
489       RC.SubClasses.set(s - 1);
490   }
491
492   // Compute the SuperClasses lists from the SubClasses vectors.
493   for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
494     const BitVector &SC = RegClasses[rci]->getSubClasses();
495     for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
496       if (unsigned(s) == rci)
497         continue;
498       RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
499     }
500   }
501
502   // With the class hierarchy in place, let synthesized register classes inherit
503   // properties from their closest super-class. The iteration order here can
504   // propagate properties down multiple levels.
505   for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
506     if (!RegClasses[rci]->getDef())
507       RegClasses[rci]->inheritProperties(RegBank);
508 }
509
510 void
511 CodeGenRegisterClass::getSuperRegClasses(Record *SubIdx, BitVector &Out) const {
512   DenseMap<Record*, SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
513     FindI = SuperRegClasses.find(SubIdx);
514   if (FindI == SuperRegClasses.end())
515     return;
516   for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
517        FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
518     Out.set((*I)->EnumValue);
519 }
520
521
522 //===----------------------------------------------------------------------===//
523 //                               CodeGenRegBank
524 //===----------------------------------------------------------------------===//
525
526 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
527   // Configure register Sets to understand register classes and tuples.
528   Sets.addFieldExpander("RegisterClass", "MemberList");
529   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
530   Sets.addExpander("RegisterTuples", new TupleExpander());
531
532   // Read in the user-defined (named) sub-register indices.
533   // More indices will be synthesized later.
534   SubRegIndices = Records.getAllDerivedDefinitions("SubRegIndex");
535   std::sort(SubRegIndices.begin(), SubRegIndices.end(), LessRecord());
536   NumNamedIndices = SubRegIndices.size();
537
538   // Read in the register definitions.
539   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
540   std::sort(Regs.begin(), Regs.end(), LessRecord());
541   Registers.reserve(Regs.size());
542   // Assign the enumeration values.
543   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
544     getReg(Regs[i]);
545
546   // Expand tuples and number the new registers.
547   std::vector<Record*> Tups =
548     Records.getAllDerivedDefinitions("RegisterTuples");
549   for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
550     const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
551     for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
552       getReg((*TupRegs)[j]);
553   }
554
555   // Precompute all sub-register maps now all the registers are known.
556   // This will create Composite entries for all inferred sub-register indices.
557   for (unsigned i = 0, e = Registers.size(); i != e; ++i)
558     Registers[i]->getSubRegs(*this);
559
560   // Read in register class definitions.
561   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
562   if (RCs.empty())
563     throw std::string("No 'RegisterClass' subclasses defined!");
564
565   // Allocate user-defined register classes.
566   RegClasses.reserve(RCs.size());
567   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
568     addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
569
570   // Infer missing classes to create a full algebra.
571   computeInferredRegisterClasses();
572
573   // Order register classes topologically and assign enum values.
574   array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
575   for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
576     RegClasses[i]->EnumValue = i;
577   CodeGenRegisterClass::computeSubClasses(*this);
578 }
579
580 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
581   CodeGenRegister *&Reg = Def2Reg[Def];
582   if (Reg)
583     return Reg;
584   Reg = new CodeGenRegister(Def, Registers.size() + 1);
585   Registers.push_back(Reg);
586   return Reg;
587 }
588
589 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
590   RegClasses.push_back(RC);
591
592   if (Record *Def = RC->getDef())
593     Def2RC.insert(std::make_pair(Def, RC));
594
595   // Duplicate classes are rejected by insert().
596   // That's OK, we only care about the properties handled by CGRC::Key.
597   CodeGenRegisterClass::Key K(*RC);
598   Key2RC.insert(std::make_pair(K, RC));
599 }
600
601 // Create a synthetic sub-class if it is missing.
602 CodeGenRegisterClass*
603 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
604                                     const CodeGenRegister::Set *Members,
605                                     StringRef Name) {
606   // Synthetic sub-class has the same size and alignment as RC.
607   CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
608   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
609   if (FoundI != Key2RC.end())
610     return FoundI->second;
611
612   // Sub-class doesn't exist, create a new one.
613   CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(Name, K);
614   addToMaps(NewRC);
615   return NewRC;
616 }
617
618 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
619   if (CodeGenRegisterClass *RC = Def2RC[Def])
620     return RC;
621
622   throw TGError(Def->getLoc(), "Not a known RegisterClass!");
623 }
624
625 Record *CodeGenRegBank::getCompositeSubRegIndex(Record *A, Record *B,
626                                                 bool create) {
627   // Look for an existing entry.
628   Record *&Comp = Composite[std::make_pair(A, B)];
629   if (Comp || !create)
630     return Comp;
631
632   // None exists, synthesize one.
633   std::string Name = A->getName() + "_then_" + B->getName();
634   Comp = new Record(Name, SMLoc(), Records);
635   SubRegIndices.push_back(Comp);
636   return Comp;
637 }
638
639 unsigned CodeGenRegBank::getSubRegIndexNo(Record *idx) {
640   std::vector<Record*>::const_iterator i =
641     std::find(SubRegIndices.begin(), SubRegIndices.end(), idx);
642   assert(i != SubRegIndices.end() && "Not a SubRegIndex");
643   return (i - SubRegIndices.begin()) + 1;
644 }
645
646 void CodeGenRegBank::computeComposites() {
647   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
648     CodeGenRegister *Reg1 = Registers[i];
649     const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
650     for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
651          e1 = SRM1.end(); i1 != e1; ++i1) {
652       Record *Idx1 = i1->first;
653       CodeGenRegister *Reg2 = i1->second;
654       // Ignore identity compositions.
655       if (Reg1 == Reg2)
656         continue;
657       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
658       // Try composing Idx1 with another SubRegIndex.
659       for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
660            e2 = SRM2.end(); i2 != e2; ++i2) {
661         std::pair<Record*, Record*> IdxPair(Idx1, i2->first);
662         CodeGenRegister *Reg3 = i2->second;
663         // Ignore identity compositions.
664         if (Reg2 == Reg3)
665           continue;
666         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
667         for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
668              e1d = SRM1.end(); i1d != e1d; ++i1d) {
669           if (i1d->second == Reg3) {
670             std::pair<CompositeMap::iterator, bool> Ins =
671               Composite.insert(std::make_pair(IdxPair, i1d->first));
672             // Conflicting composition? Emit a warning but allow it.
673             if (!Ins.second && Ins.first->second != i1d->first) {
674               errs() << "Warning: SubRegIndex " << getQualifiedName(Idx1)
675                      << " and " << getQualifiedName(IdxPair.second)
676                      << " compose ambiguously as "
677                      << getQualifiedName(Ins.first->second) << " or "
678                      << getQualifiedName(i1d->first) << "\n";
679             }
680           }
681         }
682       }
683     }
684   }
685
686   // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
687   // compositions, so remove any mappings of that form.
688   for (CompositeMap::iterator i = Composite.begin(), e = Composite.end();
689        i != e;) {
690     CompositeMap::iterator j = i;
691     ++i;
692     if (j->first.second == j->second)
693       Composite.erase(j);
694   }
695 }
696
697 // Compute sets of overlapping registers.
698 //
699 // The standard set is all super-registers and all sub-registers, but the
700 // target description can add arbitrary overlapping registers via the 'Aliases'
701 // field. This complicates things, but we can compute overlapping sets using
702 // the following rules:
703 //
704 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
705 //
706 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
707 //
708 // Alternatively:
709 //
710 //    overlap(A, B) iff there exists:
711 //    A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
712 //    A' = B' or A' in aliases(B') or B' in aliases(A').
713 //
714 // Here subregs(A) is the full flattened sub-register set returned by
715 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
716 // description of register A.
717 //
718 // This also implies that registers with a common sub-register are considered
719 // overlapping. This can happen when forming register pairs:
720 //
721 //    P0 = (R0, R1)
722 //    P1 = (R1, R2)
723 //    P2 = (R2, R3)
724 //
725 // In this case, we will infer an overlap between P0 and P1 because of the
726 // shared sub-register R1. There is no overlap between P0 and P2.
727 //
728 void CodeGenRegBank::
729 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
730   assert(Map.empty());
731
732   // Collect overlaps that don't follow from rule 2.
733   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
734     CodeGenRegister *Reg = Registers[i];
735     CodeGenRegister::Set &Overlaps = Map[Reg];
736
737     // Reg overlaps itself.
738     Overlaps.insert(Reg);
739
740     // All super-registers overlap.
741     const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
742     Overlaps.insert(Supers.begin(), Supers.end());
743
744     // Form symmetrical relations from the special Aliases[] lists.
745     std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
746     for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
747       CodeGenRegister *Reg2 = getReg(RegList[i2]);
748       CodeGenRegister::Set &Overlaps2 = Map[Reg2];
749       const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
750       // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
751       Overlaps.insert(Reg2);
752       Overlaps.insert(Supers2.begin(), Supers2.end());
753       Overlaps2.insert(Reg);
754       Overlaps2.insert(Supers.begin(), Supers.end());
755     }
756   }
757
758   // Apply rule 2. and inherit all sub-register overlaps.
759   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
760     CodeGenRegister *Reg = Registers[i];
761     CodeGenRegister::Set &Overlaps = Map[Reg];
762     const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
763     for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
764          e2 = SRM.end(); i2 != e2; ++i2) {
765       CodeGenRegister::Set &Overlaps2 = Map[i2->second];
766       Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
767     }
768   }
769 }
770
771 void CodeGenRegBank::computeDerivedInfo() {
772   computeComposites();
773 }
774
775 //
776 // Synthesize missing register class intersections.
777 //
778 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
779 // returns a maximal register class for all X.
780 //
781 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
782   for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
783     CodeGenRegisterClass *RC1 = RC;
784     CodeGenRegisterClass *RC2 = RegClasses[rci];
785     if (RC1 == RC2)
786       continue;
787
788     // Compute the set intersection of RC1 and RC2.
789     const CodeGenRegister::Set &Memb1 = RC1->getMembers();
790     const CodeGenRegister::Set &Memb2 = RC2->getMembers();
791     CodeGenRegister::Set Intersection;
792     std::set_intersection(Memb1.begin(), Memb1.end(),
793                           Memb2.begin(), Memb2.end(),
794                           std::inserter(Intersection, Intersection.begin()),
795                           CodeGenRegister::Less());
796
797     // Skip disjoint class pairs.
798     if (Intersection.empty())
799       continue;
800
801     // If RC1 and RC2 have different spill sizes or alignments, use the
802     // larger size for sub-classing.  If they are equal, prefer RC1.
803     if (RC2->SpillSize > RC1->SpillSize ||
804         (RC2->SpillSize == RC1->SpillSize &&
805          RC2->SpillAlignment > RC1->SpillAlignment))
806       std::swap(RC1, RC2);
807
808     getOrCreateSubClass(RC1, &Intersection,
809                         RC1->getName() + "_and_" + RC2->getName());
810   }
811 }
812
813 //
814 // Synthesize missing sub-classes for getSubClassWithSubReg().
815 //
816 // Make sure that the set of registers in RC with a given SubIdx sub-register
817 // form a register class.  Update RC->SubClassWithSubReg.
818 //
819 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
820   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
821   typedef std::map<Record*, CodeGenRegister::Set, LessRecord> SubReg2SetMap;
822
823   // Compute the set of registers supporting each SubRegIndex.
824   SubReg2SetMap SRSets;
825   for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
826        RE = RC->getMembers().end(); RI != RE; ++RI) {
827     const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
828     for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
829          E = SRM.end(); I != E; ++I)
830       SRSets[I->first].insert(*RI);
831   }
832
833   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
834   // numerical order to visit synthetic indices last.
835   for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
836     Record *SubIdx = SubRegIndices[sri];
837     SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
838     // Unsupported SubRegIndex. Skip it.
839     if (I == SRSets.end())
840       continue;
841     // In most cases, all RC registers support the SubRegIndex.
842     if (I->second.size() == RC->getMembers().size()) {
843       RC->setSubClassWithSubReg(SubIdx, RC);
844       continue;
845     }
846     // This is a real subset.  See if we have a matching class.
847     CodeGenRegisterClass *SubRC =
848       getOrCreateSubClass(RC, &I->second,
849                           RC->getName() + "_with_" + I->first->getName());
850     RC->setSubClassWithSubReg(SubIdx, SubRC);
851   }
852 }
853
854 //
855 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
856 //
857 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
858 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
859 //
860
861 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
862                                                 unsigned FirstSubRegRC) {
863   SmallVector<std::pair<const CodeGenRegister*,
864                         const CodeGenRegister*>, 16> SSPairs;
865
866   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
867   for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
868     Record *SubIdx = SubRegIndices[sri];
869     // Skip indexes that aren't fully supported by RC's registers. This was
870     // computed by inferSubClassWithSubReg() above which should have been
871     // called first.
872     if (RC->getSubClassWithSubReg(SubIdx) != RC)
873       continue;
874
875     // Build list of (Super, Sub) pairs for this SubIdx.
876     SSPairs.clear();
877     for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
878          RE = RC->getMembers().end(); RI != RE; ++RI) {
879       const CodeGenRegister *Super = *RI;
880       const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
881       assert(Sub && "Missing sub-register");
882       SSPairs.push_back(std::make_pair(Super, Sub));
883     }
884
885     // Iterate over sub-register class candidates.  Ignore classes created by
886     // this loop. They will never be useful.
887     for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
888          ++rci) {
889       CodeGenRegisterClass *SubRC = RegClasses[rci];
890       // Compute the subset of RC that maps into SubRC.
891       CodeGenRegister::Set SubSet;
892       for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
893         if (SubRC->contains(SSPairs[i].second))
894           SubSet.insert(SSPairs[i].first);
895       if (SubSet.empty())
896         continue;
897       // RC injects completely into SubRC.
898       if (SubSet.size() == SSPairs.size()) {
899         SubRC->addSuperRegClass(SubIdx, RC);
900         continue;
901       }
902       // Only a subset of RC maps into SubRC. Make sure it is represented by a
903       // class.
904       getOrCreateSubClass(RC, &SubSet, RC->getName() +
905                           "_with_" + SubIdx->getName() +
906                           "_in_" + SubRC->getName());
907     }
908   }
909 }
910
911
912 //
913 // Infer missing register classes.
914 //
915 void CodeGenRegBank::computeInferredRegisterClasses() {
916   // When this function is called, the register classes have not been sorted
917   // and assigned EnumValues yet.  That means getSubClasses(),
918   // getSuperClasses(), and hasSubClass() functions are defunct.
919   unsigned FirstNewRC = RegClasses.size();
920
921   // Visit all register classes, including the ones being added by the loop.
922   for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
923     CodeGenRegisterClass *RC = RegClasses[rci];
924
925     // Synthesize answers for getSubClassWithSubReg().
926     inferSubClassWithSubReg(RC);
927
928     // Synthesize answers for getCommonSubClass().
929     inferCommonSubClass(RC);
930
931     // Synthesize answers for getMatchingSuperRegClass().
932     inferMatchingSuperRegClass(RC);
933
934     // New register classes are created while this loop is running, and we need
935     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
936     // to match old super-register classes with sub-register classes created
937     // after inferMatchingSuperRegClass was called.  At this point,
938     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
939     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
940     if (rci + 1 == FirstNewRC) {
941       unsigned NextNewRC = RegClasses.size();
942       for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
943         inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
944       FirstNewRC = NextNewRC;
945     }
946   }
947 }
948
949 /// getRegisterClassForRegister - Find the register class that contains the
950 /// specified physical register.  If the register is not in a register class,
951 /// return null. If the register is in multiple classes, and the classes have a
952 /// superset-subset relationship and the same set of types, return the
953 /// superclass.  Otherwise return null.
954 const CodeGenRegisterClass*
955 CodeGenRegBank::getRegClassForRegister(Record *R) {
956   const CodeGenRegister *Reg = getReg(R);
957   ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
958   const CodeGenRegisterClass *FoundRC = 0;
959   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
960     const CodeGenRegisterClass &RC = *RCs[i];
961     if (!RC.contains(Reg))
962       continue;
963
964     // If this is the first class that contains the register,
965     // make a note of it and go on to the next class.
966     if (!FoundRC) {
967       FoundRC = &RC;
968       continue;
969     }
970
971     // If a register's classes have different types, return null.
972     if (RC.getValueTypes() != FoundRC->getValueTypes())
973       return 0;
974
975     // Check to see if the previously found class that contains
976     // the register is a subclass of the current class. If so,
977     // prefer the superclass.
978     if (RC.hasSubClass(FoundRC)) {
979       FoundRC = &RC;
980       continue;
981     }
982
983     // Check to see if the previously found class that contains
984     // the register is a superclass of the current class. If so,
985     // prefer the superclass.
986     if (FoundRC->hasSubClass(&RC))
987       continue;
988
989     // Multiple classes, and neither is a superclass of the other.
990     // Return null.
991     return 0;
992   }
993   return FoundRC;
994 }
995
996 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
997   SetVector<CodeGenRegister*> Set;
998
999   // First add Regs with all sub-registers.
1000   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1001     CodeGenRegister *Reg = getReg(Regs[i]);
1002     if (Set.insert(Reg))
1003       // Reg is new, add all sub-registers.
1004       // The pre-ordering is not important here.
1005       Reg->addSubRegsPreOrder(Set);
1006   }
1007
1008   // Second, find all super-registers that are completely covered by the set.
1009   // FIXME: Implement CoveredBySubRegs bit.
1010
1011   // Convert to BitVector.
1012   BitVector BV(Registers.size() + 1);
1013   for (unsigned i = 0, e = Set.size(); i != e; ++i)
1014     BV.set(Set[i]->EnumValue);
1015   return BV;
1016 }