TableGen: Fix register class lane masks being too conservative.
[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/ADT/IntEqClasses.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/TableGen/Error.h"
24
25 using namespace llvm;
26
27 #define DEBUG_TYPE "regalloc-emitter"
28
29 //===----------------------------------------------------------------------===//
30 //                             CodeGenSubRegIndex
31 //===----------------------------------------------------------------------===//
32
33 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
34   : TheDef(R), EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
35   Name = R->getName();
36   if (R->getValue("Namespace"))
37     Namespace = R->getValueAsString("Namespace");
38   Size = R->getValueAsInt("Size");
39   Offset = R->getValueAsInt("Offset");
40 }
41
42 CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
43                                        unsigned Enum)
44   : TheDef(nullptr), Name(N), Namespace(Nspace), Size(-1), Offset(-1),
45     EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
46 }
47
48 std::string CodeGenSubRegIndex::getQualifiedName() const {
49   std::string N = getNamespace();
50   if (!N.empty())
51     N += "::";
52   N += getName();
53   return N;
54 }
55
56 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
57   if (!TheDef)
58     return;
59
60   std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
61   if (!Comps.empty()) {
62     if (Comps.size() != 2)
63       PrintFatalError(TheDef->getLoc(),
64                       "ComposedOf must have exactly two entries");
65     CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
66     CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
67     CodeGenSubRegIndex *X = A->addComposite(B, this);
68     if (X)
69       PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
70   }
71
72   std::vector<Record*> Parts =
73     TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
74   if (!Parts.empty()) {
75     if (Parts.size() < 2)
76       PrintFatalError(TheDef->getLoc(),
77                       "CoveredBySubRegs must have two or more entries");
78     SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
79     for (unsigned i = 0, e = Parts.size(); i != e; ++i)
80       IdxParts.push_back(RegBank.getSubRegIdx(Parts[i]));
81     RegBank.addConcatSubRegIndex(IdxParts, this);
82   }
83 }
84
85 unsigned CodeGenSubRegIndex::computeLaneMask() const {
86   // Already computed?
87   if (LaneMask)
88     return LaneMask;
89
90   // Recursion guard, shouldn't be required.
91   LaneMask = ~0u;
92
93   // The lane mask is simply the union of all sub-indices.
94   unsigned M = 0;
95   for (const auto &C : Composed)
96     M |= C.second->computeLaneMask();
97   assert(M && "Missing lane mask, sub-register cycle?");
98   LaneMask = M;
99   return LaneMask;
100 }
101
102 //===----------------------------------------------------------------------===//
103 //                              CodeGenRegister
104 //===----------------------------------------------------------------------===//
105
106 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
107   : TheDef(R),
108     EnumValue(Enum),
109     CostPerUse(R->getValueAsInt("CostPerUse")),
110     CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
111     SubRegsComplete(false),
112     SuperRegsComplete(false),
113     TopoSig(~0u)
114 {}
115
116 void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
117   std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
118   std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
119
120   if (SRIs.size() != SRs.size())
121     PrintFatalError(TheDef->getLoc(),
122                     "SubRegs and SubRegIndices must have the same size");
123
124   for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
125     ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
126     ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
127   }
128
129   // Also compute leading super-registers. Each register has a list of
130   // covered-by-subregs super-registers where it appears as the first explicit
131   // sub-register.
132   //
133   // This is used by computeSecondarySubRegs() to find candidates.
134   if (CoveredBySubRegs && !ExplicitSubRegs.empty())
135     ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
136
137   // Add ad hoc alias links. This is a symmetric relationship between two
138   // registers, so build a symmetric graph by adding links in both ends.
139   std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
140   for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
141     CodeGenRegister *Reg = RegBank.getReg(Aliases[i]);
142     ExplicitAliases.push_back(Reg);
143     Reg->ExplicitAliases.push_back(this);
144   }
145 }
146
147 const std::string &CodeGenRegister::getName() const {
148   assert(TheDef && "no def");
149   return TheDef->getName();
150 }
151
152 namespace {
153 // Iterate over all register units in a set of registers.
154 class RegUnitIterator {
155   CodeGenRegister::Vec::const_iterator RegI, RegE;
156   CodeGenRegister::RegUnitList::iterator UnitI, UnitE;
157
158 public:
159   RegUnitIterator(const CodeGenRegister::Vec &Regs):
160     RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
161
162     if (RegI != RegE) {
163       UnitI = (*RegI)->getRegUnits().begin();
164       UnitE = (*RegI)->getRegUnits().end();
165       advance();
166     }
167   }
168
169   bool isValid() const { return UnitI != UnitE; }
170
171   unsigned operator* () const { assert(isValid()); return *UnitI; }
172
173   const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
174
175   /// Preincrement.  Move to the next unit.
176   void operator++() {
177     assert(isValid() && "Cannot advance beyond the last operand");
178     ++UnitI;
179     advance();
180   }
181
182 protected:
183   void advance() {
184     while (UnitI == UnitE) {
185       if (++RegI == RegE)
186         break;
187       UnitI = (*RegI)->getRegUnits().begin();
188       UnitE = (*RegI)->getRegUnits().end();
189     }
190   }
191 };
192 } // namespace
193
194 // Return true of this unit appears in RegUnits.
195 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
196   return RegUnits.test(Unit);
197 }
198
199 // Inherit register units from subregisters.
200 // Return true if the RegUnits changed.
201 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
202   bool changed = false;
203   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
204        I != E; ++I) {
205     CodeGenRegister *SR = I->second;
206     // Merge the subregister's units into this register's RegUnits.
207     changed |= (RegUnits |= SR->RegUnits);
208   }
209
210   return changed;
211 }
212
213 const CodeGenRegister::SubRegMap &
214 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
215   // Only compute this map once.
216   if (SubRegsComplete)
217     return SubRegs;
218   SubRegsComplete = true;
219
220   // First insert the explicit subregs and make sure they are fully indexed.
221   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
222     CodeGenRegister *SR = ExplicitSubRegs[i];
223     CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
224     if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
225       PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
226                       " appears twice in Register " + getName());
227     // Map explicit sub-registers first, so the names take precedence.
228     // The inherited sub-registers are mapped below.
229     SubReg2Idx.insert(std::make_pair(SR, Idx));
230   }
231
232   // Keep track of inherited subregs and how they can be reached.
233   SmallPtrSet<CodeGenRegister*, 8> Orphans;
234
235   // Clone inherited subregs and place duplicate entries in Orphans.
236   // Here the order is important - earlier subregs take precedence.
237   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
238     CodeGenRegister *SR = ExplicitSubRegs[i];
239     const SubRegMap &Map = SR->computeSubRegs(RegBank);
240
241     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
242          ++SI) {
243       if (!SubRegs.insert(*SI).second)
244         Orphans.insert(SI->second);
245     }
246   }
247
248   // Expand any composed subreg indices.
249   // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
250   // qsub_1 subreg, add a dsub_2 subreg.  Keep growing Indices and process
251   // expanded subreg indices recursively.
252   SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
253   for (unsigned i = 0; i != Indices.size(); ++i) {
254     CodeGenSubRegIndex *Idx = Indices[i];
255     const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
256     CodeGenRegister *SR = SubRegs[Idx];
257     const SubRegMap &Map = SR->computeSubRegs(RegBank);
258
259     // Look at the possible compositions of Idx.
260     // They may not all be supported by SR.
261     for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
262            E = Comps.end(); I != E; ++I) {
263       SubRegMap::const_iterator SRI = Map.find(I->first);
264       if (SRI == Map.end())
265         continue; // Idx + I->first doesn't exist in SR.
266       // Add I->second as a name for the subreg SRI->second, assuming it is
267       // orphaned, and the name isn't already used for something else.
268       if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
269         continue;
270       // We found a new name for the orphaned sub-register.
271       SubRegs.insert(std::make_pair(I->second, SRI->second));
272       Indices.push_back(I->second);
273     }
274   }
275
276   // Now Orphans contains the inherited subregisters without a direct index.
277   // Create inferred indexes for all missing entries.
278   // Work backwards in the Indices vector in order to compose subregs bottom-up.
279   // Consider this subreg sequence:
280   //
281   //   qsub_1 -> dsub_0 -> ssub_0
282   //
283   // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
284   // can be reached in two different ways:
285   //
286   //   qsub_1 -> ssub_0
287   //   dsub_2 -> ssub_0
288   //
289   // We pick the latter composition because another register may have [dsub_0,
290   // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg.  The
291   // dsub_2 -> ssub_0 composition can be shared.
292   while (!Indices.empty() && !Orphans.empty()) {
293     CodeGenSubRegIndex *Idx = Indices.pop_back_val();
294     CodeGenRegister *SR = SubRegs[Idx];
295     const SubRegMap &Map = SR->computeSubRegs(RegBank);
296     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
297          ++SI)
298       if (Orphans.erase(SI->second))
299         SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
300   }
301
302   // Compute the inverse SubReg -> Idx map.
303   for (SubRegMap::const_iterator SI = SubRegs.begin(), SE = SubRegs.end();
304        SI != SE; ++SI) {
305     if (SI->second == this) {
306       ArrayRef<SMLoc> Loc;
307       if (TheDef)
308         Loc = TheDef->getLoc();
309       PrintFatalError(Loc, "Register " + getName() +
310                       " has itself as a sub-register");
311     }
312
313     // Compute AllSuperRegsCovered.
314     if (!CoveredBySubRegs)
315       SI->first->AllSuperRegsCovered = false;
316
317     // Ensure that every sub-register has a unique name.
318     DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
319       SubReg2Idx.insert(std::make_pair(SI->second, SI->first)).first;
320     if (Ins->second == SI->first)
321       continue;
322     // Trouble: Two different names for SI->second.
323     ArrayRef<SMLoc> Loc;
324     if (TheDef)
325       Loc = TheDef->getLoc();
326     PrintFatalError(Loc, "Sub-register can't have two names: " +
327                   SI->second->getName() + " available as " +
328                   SI->first->getName() + " and " + Ins->second->getName());
329   }
330
331   // Derive possible names for sub-register concatenations from any explicit
332   // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
333   // that getConcatSubRegIndex() won't invent any concatenated indices that the
334   // user already specified.
335   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
336     CodeGenRegister *SR = ExplicitSubRegs[i];
337     if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1)
338       continue;
339
340     // SR is composed of multiple sub-regs. Find their names in this register.
341     SmallVector<CodeGenSubRegIndex*, 8> Parts;
342     for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j)
343       Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
344
345     // Offer this as an existing spelling for the concatenation of Parts.
346     RegBank.addConcatSubRegIndex(Parts, ExplicitSubRegIndices[i]);
347   }
348
349   // Initialize RegUnitList. Because getSubRegs is called recursively, this
350   // processes the register hierarchy in postorder.
351   //
352   // Inherit all sub-register units. It is good enough to look at the explicit
353   // sub-registers, the other registers won't contribute any more units.
354   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
355     CodeGenRegister *SR = ExplicitSubRegs[i];
356     RegUnits |= SR->RegUnits;
357   }
358
359   // Absent any ad hoc aliasing, we create one register unit per leaf register.
360   // These units correspond to the maximal cliques in the register overlap
361   // graph which is optimal.
362   //
363   // When there is ad hoc aliasing, we simply create one unit per edge in the
364   // undirected ad hoc aliasing graph. Technically, we could do better by
365   // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
366   // are extremely rare anyway (I've never seen one), so we don't bother with
367   // the added complexity.
368   for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
369     CodeGenRegister *AR = ExplicitAliases[i];
370     // Only visit each edge once.
371     if (AR->SubRegsComplete)
372       continue;
373     // Create a RegUnit representing this alias edge, and add it to both
374     // registers.
375     unsigned Unit = RegBank.newRegUnit(this, AR);
376     RegUnits.set(Unit);
377     AR->RegUnits.set(Unit);
378   }
379
380   // Finally, create units for leaf registers without ad hoc aliases. Note that
381   // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
382   // necessary. This means the aliasing leaf registers can share a single unit.
383   if (RegUnits.empty())
384     RegUnits.set(RegBank.newRegUnit(this));
385
386   // We have now computed the native register units. More may be adopted later
387   // for balancing purposes.
388   NativeRegUnits = RegUnits;
389
390   return SubRegs;
391 }
392
393 // In a register that is covered by its sub-registers, try to find redundant
394 // sub-registers. For example:
395 //
396 //   QQ0 = {Q0, Q1}
397 //   Q0 = {D0, D1}
398 //   Q1 = {D2, D3}
399 //
400 // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
401 // the register definition.
402 //
403 // The explicitly specified registers form a tree. This function discovers
404 // sub-register relationships that would force a DAG.
405 //
406 void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
407   // Collect new sub-registers first, add them later.
408   SmallVector<SubRegMap::value_type, 8> NewSubRegs;
409
410   // Look at the leading super-registers of each sub-register. Those are the
411   // candidates for new sub-registers, assuming they are fully contained in
412   // this register.
413   for (SubRegMap::iterator I = SubRegs.begin(), E = SubRegs.end(); I != E; ++I){
414     const CodeGenRegister *SubReg = I->second;
415     const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
416     for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
417       CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
418       // Already got this sub-register?
419       if (Cand == this || getSubRegIndex(Cand))
420         continue;
421       // Check if each component of Cand is already a sub-register.
422       // We know that the first component is I->second, and is present with the
423       // name I->first.
424       SmallVector<CodeGenSubRegIndex*, 8> Parts(1, I->first);
425       assert(!Cand->ExplicitSubRegs.empty() &&
426              "Super-register has no sub-registers");
427       for (unsigned j = 1, e = Cand->ExplicitSubRegs.size(); j != e; ++j) {
428         if (CodeGenSubRegIndex *Idx = getSubRegIndex(Cand->ExplicitSubRegs[j]))
429           Parts.push_back(Idx);
430         else {
431           // Sub-register doesn't exist.
432           Parts.clear();
433           break;
434         }
435       }
436       // If some Cand sub-register is not part of this register, or if Cand only
437       // has one sub-register, there is nothing to do.
438       if (Parts.size() <= 1)
439         continue;
440
441       // Each part of Cand is a sub-register of this. Make the full Cand also
442       // a sub-register with a concatenated sub-register index.
443       CodeGenSubRegIndex *Concat= RegBank.getConcatSubRegIndex(Parts);
444       NewSubRegs.push_back(std::make_pair(Concat, Cand));
445     }
446   }
447
448   // Now add all the new sub-registers.
449   for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
450     // Don't add Cand if another sub-register is already using the index.
451     if (!SubRegs.insert(NewSubRegs[i]).second)
452       continue;
453
454     CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
455     CodeGenRegister *NewSubReg = NewSubRegs[i].second;
456     SubReg2Idx.insert(std::make_pair(NewSubReg, NewIdx));
457   }
458
459   // Create sub-register index composition maps for the synthesized indices.
460   for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
461     CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
462     CodeGenRegister *NewSubReg = NewSubRegs[i].second;
463     for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
464            SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
465       CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
466       if (!SubIdx)
467         PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
468                         SI->second->getName() + " in " + getName());
469       NewIdx->addComposite(SI->first, SubIdx);
470     }
471   }
472 }
473
474 void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
475   // Only visit each register once.
476   if (SuperRegsComplete)
477     return;
478   SuperRegsComplete = true;
479
480   // Make sure all sub-registers have been visited first, so the super-reg
481   // lists will be topologically ordered.
482   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
483        I != E; ++I)
484     I->second->computeSuperRegs(RegBank);
485
486   // Now add this as a super-register on all sub-registers.
487   // Also compute the TopoSigId in post-order.
488   TopoSigId Id;
489   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
490        I != E; ++I) {
491     // Topological signature computed from SubIdx, TopoId(SubReg).
492     // Loops and idempotent indices have TopoSig = ~0u.
493     Id.push_back(I->first->EnumValue);
494     Id.push_back(I->second->TopoSig);
495
496     // Don't add duplicate entries.
497     if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
498       continue;
499     I->second->SuperRegs.push_back(this);
500   }
501   TopoSig = RegBank.getTopoSig(Id);
502 }
503
504 void
505 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
506                                     CodeGenRegBank &RegBank) const {
507   assert(SubRegsComplete && "Must precompute sub-registers");
508   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
509     CodeGenRegister *SR = ExplicitSubRegs[i];
510     if (OSet.insert(SR))
511       SR->addSubRegsPreOrder(OSet, RegBank);
512   }
513   // Add any secondary sub-registers that weren't part of the explicit tree.
514   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
515        I != E; ++I)
516     OSet.insert(I->second);
517 }
518
519 // Get the sum of this register's unit weights.
520 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
521   unsigned Weight = 0;
522   for (RegUnitList::iterator I = RegUnits.begin(), E = RegUnits.end();
523        I != E; ++I) {
524     Weight += RegBank.getRegUnit(*I).Weight;
525   }
526   return Weight;
527 }
528
529 //===----------------------------------------------------------------------===//
530 //                               RegisterTuples
531 //===----------------------------------------------------------------------===//
532
533 // A RegisterTuples def is used to generate pseudo-registers from lists of
534 // sub-registers. We provide a SetTheory expander class that returns the new
535 // registers.
536 namespace {
537 struct TupleExpander : SetTheory::Expander {
538   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
539     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
540     unsigned Dim = Indices.size();
541     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
542     if (Dim != SubRegs->getSize())
543       PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
544     if (Dim < 2)
545       PrintFatalError(Def->getLoc(),
546                       "Tuples must have at least 2 sub-registers");
547
548     // Evaluate the sub-register lists to be zipped.
549     unsigned Length = ~0u;
550     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
551     for (unsigned i = 0; i != Dim; ++i) {
552       ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
553       Length = std::min(Length, unsigned(Lists[i].size()));
554     }
555
556     if (Length == 0)
557       return;
558
559     // Precompute some types.
560     Record *RegisterCl = Def->getRecords().getClass("Register");
561     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
562     StringInit *BlankName = StringInit::get("");
563
564     // Zip them up.
565     for (unsigned n = 0; n != Length; ++n) {
566       std::string Name;
567       Record *Proto = Lists[0][n];
568       std::vector<Init*> Tuple;
569       unsigned CostPerUse = 0;
570       for (unsigned i = 0; i != Dim; ++i) {
571         Record *Reg = Lists[i][n];
572         if (i) Name += '_';
573         Name += Reg->getName();
574         Tuple.push_back(DefInit::get(Reg));
575         CostPerUse = std::max(CostPerUse,
576                               unsigned(Reg->getValueAsInt("CostPerUse")));
577       }
578
579       // Create a new Record representing the synthesized register. This record
580       // is only for consumption by CodeGenRegister, it is not added to the
581       // RecordKeeper.
582       Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
583       Elts.insert(NewReg);
584
585       // Copy Proto super-classes.
586       ArrayRef<Record *> Supers = Proto->getSuperClasses();
587       ArrayRef<SMRange> Ranges = Proto->getSuperClassRanges();
588       for (unsigned i = 0, e = Supers.size(); i != e; ++i)
589         NewReg->addSuperClass(Supers[i], Ranges[i]);
590
591       // Copy Proto fields.
592       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
593         RecordVal RV = Proto->getValues()[i];
594
595         // Skip existing fields, like NAME.
596         if (NewReg->getValue(RV.getNameInit()))
597           continue;
598
599         StringRef Field = RV.getName();
600
601         // Replace the sub-register list with Tuple.
602         if (Field == "SubRegs")
603           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
604
605         // Provide a blank AsmName. MC hacks are required anyway.
606         if (Field == "AsmName")
607           RV.setValue(BlankName);
608
609         // CostPerUse is aggregated from all Tuple members.
610         if (Field == "CostPerUse")
611           RV.setValue(IntInit::get(CostPerUse));
612
613         // Composite registers are always covered by sub-registers.
614         if (Field == "CoveredBySubRegs")
615           RV.setValue(BitInit::get(true));
616
617         // Copy fields from the RegisterTuples def.
618         if (Field == "SubRegIndices" ||
619             Field == "CompositeIndices") {
620           NewReg->addValue(*Def->getValue(Field));
621           continue;
622         }
623
624         // Some fields get their default uninitialized value.
625         if (Field == "DwarfNumbers" ||
626             Field == "DwarfAlias" ||
627             Field == "Aliases") {
628           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
629             NewReg->addValue(*DefRV);
630           continue;
631         }
632
633         // Everything else is copied from Proto.
634         NewReg->addValue(RV);
635       }
636     }
637   }
638 };
639 }
640
641 //===----------------------------------------------------------------------===//
642 //                            CodeGenRegisterClass
643 //===----------------------------------------------------------------------===//
644
645 static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
646   std::sort(M.begin(), M.end(), deref<llvm::less>());
647   M.erase(std::unique(M.begin(), M.end(), deref<llvm::equal>()), M.end());
648 }
649
650 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
651   : TheDef(R),
652     Name(R->getName()),
653     TopoSigs(RegBank.getNumTopoSigs()),
654     EnumValue(-1),
655     LaneMask(0) {
656   // Rename anonymous register classes.
657   if (R->getName().size() > 9 && R->getName()[9] == '.') {
658     static unsigned AnonCounter = 0;
659     R->setName("AnonRegClass_" + utostr(AnonCounter++));
660   }
661
662   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
663   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
664     Record *Type = TypeList[i];
665     if (!Type->isSubClassOf("ValueType"))
666       PrintFatalError("RegTypes list member '" + Type->getName() +
667         "' does not derive from the ValueType class!");
668     VTs.push_back(getValueType(Type));
669   }
670   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
671
672   // Allocation order 0 is the full set. AltOrders provides others.
673   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
674   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
675   Orders.resize(1 + AltOrders->size());
676
677   // Default allocation order always contains all registers.
678   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
679     Orders[0].push_back((*Elements)[i]);
680     const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
681     Members.push_back(Reg);
682     TopoSigs.set(Reg->getTopoSig());
683   }
684   sortAndUniqueRegisters(Members);
685
686   // Alternative allocation orders may be subsets.
687   SetTheory::RecSet Order;
688   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
689     RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
690     Orders[1 + i].append(Order.begin(), Order.end());
691     // Verify that all altorder members are regclass members.
692     while (!Order.empty()) {
693       CodeGenRegister *Reg = RegBank.getReg(Order.back());
694       Order.pop_back();
695       if (!contains(Reg))
696         PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
697                       " is not a class member");
698     }
699   }
700
701   // Allow targets to override the size in bits of the RegisterClass.
702   unsigned Size = R->getValueAsInt("Size");
703
704   Namespace = R->getValueAsString("Namespace");
705   SpillSize = Size ? Size : MVT(VTs[0]).getSizeInBits();
706   SpillAlignment = R->getValueAsInt("Alignment");
707   CopyCost = R->getValueAsInt("CopyCost");
708   Allocatable = R->getValueAsBit("isAllocatable");
709   AltOrderSelect = R->getValueAsString("AltOrderSelect");
710 }
711
712 // Create an inferred register class that was missing from the .td files.
713 // Most properties will be inherited from the closest super-class after the
714 // class structure has been computed.
715 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
716                                            StringRef Name, Key Props)
717   : Members(*Props.Members),
718     TheDef(nullptr),
719     Name(Name),
720     TopoSigs(RegBank.getNumTopoSigs()),
721     EnumValue(-1),
722     SpillSize(Props.SpillSize),
723     SpillAlignment(Props.SpillAlignment),
724     CopyCost(0),
725     Allocatable(true) {
726   for (const auto R : Members)
727     TopoSigs.set(R->getTopoSig());
728 }
729
730 // Compute inherited propertied for a synthesized register class.
731 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
732   assert(!getDef() && "Only synthesized classes can inherit properties");
733   assert(!SuperClasses.empty() && "Synthesized class without super class");
734
735   // The last super-class is the smallest one.
736   CodeGenRegisterClass &Super = *SuperClasses.back();
737
738   // Most properties are copied directly.
739   // Exceptions are members, size, and alignment
740   Namespace = Super.Namespace;
741   VTs = Super.VTs;
742   CopyCost = Super.CopyCost;
743   Allocatable = Super.Allocatable;
744   AltOrderSelect = Super.AltOrderSelect;
745
746   // Copy all allocation orders, filter out foreign registers from the larger
747   // super-class.
748   Orders.resize(Super.Orders.size());
749   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
750     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
751       if (contains(RegBank.getReg(Super.Orders[i][j])))
752         Orders[i].push_back(Super.Orders[i][j]);
753 }
754
755 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
756   return std::binary_search(Members.begin(), Members.end(), Reg,
757                             deref<llvm::less>());
758 }
759
760 namespace llvm {
761   raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
762     OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
763     for (const auto R : *K.Members)
764       OS << ", " << R->getName();
765     return OS << " }";
766   }
767 }
768
769 // This is a simple lexicographical order that can be used to search for sets.
770 // It is not the same as the topological order provided by TopoOrderRC.
771 bool CodeGenRegisterClass::Key::
772 operator<(const CodeGenRegisterClass::Key &B) const {
773   assert(Members && B.Members);
774   return std::tie(*Members, SpillSize, SpillAlignment) <
775          std::tie(*B.Members, B.SpillSize, B.SpillAlignment);
776 }
777
778 // Returns true if RC is a strict subclass.
779 // RC is a sub-class of this class if it is a valid replacement for any
780 // instruction operand where a register of this classis required. It must
781 // satisfy these conditions:
782 //
783 // 1. All RC registers are also in this.
784 // 2. The RC spill size must not be smaller than our spill size.
785 // 3. RC spill alignment must be compatible with ours.
786 //
787 static bool testSubClass(const CodeGenRegisterClass *A,
788                          const CodeGenRegisterClass *B) {
789   return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
790          A->SpillSize <= B->SpillSize &&
791          std::includes(A->getMembers().begin(), A->getMembers().end(),
792                        B->getMembers().begin(), B->getMembers().end(),
793                        deref<llvm::less>());
794 }
795
796 /// Sorting predicate for register classes.  This provides a topological
797 /// ordering that arranges all register classes before their sub-classes.
798 ///
799 /// Register classes with the same registers, spill size, and alignment form a
800 /// clique.  They will be ordered alphabetically.
801 ///
802 static bool TopoOrderRC(const CodeGenRegisterClass &PA,
803                         const CodeGenRegisterClass &PB) {
804   auto *A = &PA;
805   auto *B = &PB;
806   if (A == B)
807     return 0;
808
809   // Order by ascending spill size.
810   if (A->SpillSize < B->SpillSize)
811     return true;
812   if (A->SpillSize > B->SpillSize)
813     return false;
814
815   // Order by ascending spill alignment.
816   if (A->SpillAlignment < B->SpillAlignment)
817     return true;
818   if (A->SpillAlignment > B->SpillAlignment)
819     return false;
820
821   // Order by descending set size.  Note that the classes' allocation order may
822   // not have been computed yet.  The Members set is always vaild.
823   if (A->getMembers().size() > B->getMembers().size())
824     return true;
825   if (A->getMembers().size() < B->getMembers().size())
826     return false;
827
828   // Finally order by name as a tie breaker.
829   return StringRef(A->getName()) < B->getName();
830 }
831
832 std::string CodeGenRegisterClass::getQualifiedName() const {
833   if (Namespace.empty())
834     return getName();
835   else
836     return Namespace + "::" + getName();
837 }
838
839 // Compute sub-classes of all register classes.
840 // Assume the classes are ordered topologically.
841 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
842   auto &RegClasses = RegBank.getRegClasses();
843
844   // Visit backwards so sub-classes are seen first.
845   for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
846     CodeGenRegisterClass &RC = *I;
847     RC.SubClasses.resize(RegClasses.size());
848     RC.SubClasses.set(RC.EnumValue);
849
850     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
851     for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
852       CodeGenRegisterClass &SubRC = *I2;
853       if (RC.SubClasses.test(SubRC.EnumValue))
854         continue;
855       if (!testSubClass(&RC, &SubRC))
856         continue;
857       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
858       // check them again.
859       RC.SubClasses |= SubRC.SubClasses;
860     }
861
862     // Sweep up missed clique members.  They will be immediately preceding RC.
863     for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
864       RC.SubClasses.set(I2->EnumValue);
865   }
866
867   // Compute the SuperClasses lists from the SubClasses vectors.
868   for (auto &RC : RegClasses) {
869     const BitVector &SC = RC.getSubClasses();
870     auto I = RegClasses.begin();
871     for (int s = 0, next_s = SC.find_first(); next_s != -1;
872          next_s = SC.find_next(s)) {
873       std::advance(I, next_s - s);
874       s = next_s;
875       if (&*I == &RC)
876         continue;
877       I->SuperClasses.push_back(&RC);
878     }
879   }
880
881   // With the class hierarchy in place, let synthesized register classes inherit
882   // properties from their closest super-class. The iteration order here can
883   // propagate properties down multiple levels.
884   for (auto &RC : RegClasses)
885     if (!RC.getDef())
886       RC.inheritProperties(RegBank);
887 }
888
889 void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
890                                               BitVector &Out) const {
891   auto FindI = SuperRegClasses.find(SubIdx);
892   if (FindI == SuperRegClasses.end())
893     return;
894   for (CodeGenRegisterClass *RC : FindI->second)
895     Out.set(RC->EnumValue);
896 }
897
898 // Populate a unique sorted list of units from a register set.
899 void CodeGenRegisterClass::buildRegUnitSet(
900   std::vector<unsigned> &RegUnits) const {
901   std::vector<unsigned> TmpUnits;
902   for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
903     TmpUnits.push_back(*UnitI);
904   std::sort(TmpUnits.begin(), TmpUnits.end());
905   std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
906                    std::back_inserter(RegUnits));
907 }
908
909 //===----------------------------------------------------------------------===//
910 //                               CodeGenRegBank
911 //===----------------------------------------------------------------------===//
912
913 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) {
914   // Configure register Sets to understand register classes and tuples.
915   Sets.addFieldExpander("RegisterClass", "MemberList");
916   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
917   Sets.addExpander("RegisterTuples", new TupleExpander());
918
919   // Read in the user-defined (named) sub-register indices.
920   // More indices will be synthesized later.
921   std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
922   std::sort(SRIs.begin(), SRIs.end(), LessRecord());
923   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
924     getSubRegIdx(SRIs[i]);
925   // Build composite maps from ComposedOf fields.
926   for (auto &Idx : SubRegIndices)
927     Idx.updateComponents(*this);
928
929   // Read in the register definitions.
930   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
931   std::sort(Regs.begin(), Regs.end(), LessRecordRegister());
932   // Assign the enumeration values.
933   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
934     getReg(Regs[i]);
935
936   // Expand tuples and number the new registers.
937   std::vector<Record*> Tups =
938     Records.getAllDerivedDefinitions("RegisterTuples");
939
940   for (Record *R : Tups) {
941     std::vector<Record *> TupRegs = *Sets.expand(R);
942     std::sort(TupRegs.begin(), TupRegs.end(), LessRecordRegister());
943     for (Record *RC : TupRegs)
944       getReg(RC);
945   }
946
947   // Now all the registers are known. Build the object graph of explicit
948   // register-register references.
949   for (auto &Reg : Registers)
950     Reg.buildObjectGraph(*this);
951
952   // Compute register name map.
953   for (auto &Reg : Registers)
954     // FIXME: This could just be RegistersByName[name] = register, except that
955     // causes some failures in MIPS - perhaps they have duplicate register name
956     // entries? (or maybe there's a reason for it - I don't know much about this
957     // code, just drive-by refactoring)
958     RegistersByName.insert(
959         std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
960
961   // Precompute all sub-register maps.
962   // This will create Composite entries for all inferred sub-register indices.
963   for (auto &Reg : Registers)
964     Reg.computeSubRegs(*this);
965
966   // Infer even more sub-registers by combining leading super-registers.
967   for (auto &Reg : Registers)
968     if (Reg.CoveredBySubRegs)
969       Reg.computeSecondarySubRegs(*this);
970
971   // After the sub-register graph is complete, compute the topologically
972   // ordered SuperRegs list.
973   for (auto &Reg : Registers)
974     Reg.computeSuperRegs(*this);
975
976   // Native register units are associated with a leaf register. They've all been
977   // discovered now.
978   NumNativeRegUnits = RegUnits.size();
979
980   // Read in register class definitions.
981   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
982   if (RCs.empty())
983     PrintFatalError("No 'RegisterClass' subclasses defined!");
984
985   // Allocate user-defined register classes.
986   for (auto *RC : RCs) {
987     RegClasses.push_back(CodeGenRegisterClass(*this, RC));
988     addToMaps(&RegClasses.back());
989   }
990
991   // Infer missing classes to create a full algebra.
992   computeInferredRegisterClasses();
993
994   // Order register classes topologically and assign enum values.
995   RegClasses.sort(TopoOrderRC);
996   unsigned i = 0;
997   for (auto &RC : RegClasses)
998     RC.EnumValue = i++;
999   CodeGenRegisterClass::computeSubClasses(*this);
1000 }
1001
1002 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1003 CodeGenSubRegIndex*
1004 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1005   SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
1006   return &SubRegIndices.back();
1007 }
1008
1009 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1010   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1011   if (Idx)
1012     return Idx;
1013   SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
1014   Idx = &SubRegIndices.back();
1015   return Idx;
1016 }
1017
1018 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1019   CodeGenRegister *&Reg = Def2Reg[Def];
1020   if (Reg)
1021     return Reg;
1022   Registers.emplace_back(Def, Registers.size() + 1);
1023   Reg = &Registers.back();
1024   return Reg;
1025 }
1026
1027 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1028   if (Record *Def = RC->getDef())
1029     Def2RC.insert(std::make_pair(Def, RC));
1030
1031   // Duplicate classes are rejected by insert().
1032   // That's OK, we only care about the properties handled by CGRC::Key.
1033   CodeGenRegisterClass::Key K(*RC);
1034   Key2RC.insert(std::make_pair(K, RC));
1035 }
1036
1037 // Create a synthetic sub-class if it is missing.
1038 CodeGenRegisterClass*
1039 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1040                                     const CodeGenRegister::Vec *Members,
1041                                     StringRef Name) {
1042   // Synthetic sub-class has the same size and alignment as RC.
1043   CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
1044   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1045   if (FoundI != Key2RC.end())
1046     return FoundI->second;
1047
1048   // Sub-class doesn't exist, create a new one.
1049   RegClasses.push_back(CodeGenRegisterClass(*this, Name, K));
1050   addToMaps(&RegClasses.back());
1051   return &RegClasses.back();
1052 }
1053
1054 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1055   if (CodeGenRegisterClass *RC = Def2RC[Def])
1056     return RC;
1057
1058   PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1059 }
1060
1061 CodeGenSubRegIndex*
1062 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1063                                         CodeGenSubRegIndex *B) {
1064   // Look for an existing entry.
1065   CodeGenSubRegIndex *Comp = A->compose(B);
1066   if (Comp)
1067     return Comp;
1068
1069   // None exists, synthesize one.
1070   std::string Name = A->getName() + "_then_" + B->getName();
1071   Comp = createSubRegIndex(Name, A->getNamespace());
1072   A->addComposite(B, Comp);
1073   return Comp;
1074 }
1075
1076 CodeGenSubRegIndex *CodeGenRegBank::
1077 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
1078   assert(Parts.size() > 1 && "Need two parts to concatenate");
1079
1080   // Look for an existing entry.
1081   CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1082   if (Idx)
1083     return Idx;
1084
1085   // None exists, synthesize one.
1086   std::string Name = Parts.front()->getName();
1087   // Determine whether all parts are contiguous.
1088   bool isContinuous = true;
1089   unsigned Size = Parts.front()->Size;
1090   unsigned LastOffset = Parts.front()->Offset;
1091   unsigned LastSize = Parts.front()->Size;
1092   for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1093     Name += '_';
1094     Name += Parts[i]->getName();
1095     Size += Parts[i]->Size;
1096     if (Parts[i]->Offset != (LastOffset + LastSize))
1097       isContinuous = false;
1098     LastOffset = Parts[i]->Offset;
1099     LastSize = Parts[i]->Size;
1100   }
1101   Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1102   Idx->Size = Size;
1103   Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
1104   return Idx;
1105 }
1106
1107 void CodeGenRegBank::computeComposites() {
1108   // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1109   // and many registers will share TopoSigs on regular architectures.
1110   BitVector TopoSigs(getNumTopoSigs());
1111
1112   for (const auto &Reg1 : Registers) {
1113     // Skip identical subreg structures already processed.
1114     if (TopoSigs.test(Reg1.getTopoSig()))
1115       continue;
1116     TopoSigs.set(Reg1.getTopoSig());
1117
1118     const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1119     for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1120          e1 = SRM1.end(); i1 != e1; ++i1) {
1121       CodeGenSubRegIndex *Idx1 = i1->first;
1122       CodeGenRegister *Reg2 = i1->second;
1123       // Ignore identity compositions.
1124       if (&Reg1 == Reg2)
1125         continue;
1126       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1127       // Try composing Idx1 with another SubRegIndex.
1128       for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1129            e2 = SRM2.end(); i2 != e2; ++i2) {
1130         CodeGenSubRegIndex *Idx2 = i2->first;
1131         CodeGenRegister *Reg3 = i2->second;
1132         // Ignore identity compositions.
1133         if (Reg2 == Reg3)
1134           continue;
1135         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1136         CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
1137         assert(Idx3 && "Sub-register doesn't have an index");
1138
1139         // Conflicting composition? Emit a warning but allow it.
1140         if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3))
1141           PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1142                        " and " + Idx2->getQualifiedName() +
1143                        " compose ambiguously as " + Prev->getQualifiedName() +
1144                        " or " + Idx3->getQualifiedName());
1145       }
1146     }
1147   }
1148 }
1149
1150 // Compute lane masks. This is similar to register units, but at the
1151 // sub-register index level. Each bit in the lane mask is like a register unit
1152 // class, and two lane masks will have a bit in common if two sub-register
1153 // indices overlap in some register.
1154 //
1155 // Conservatively share a lane mask bit if two sub-register indices overlap in
1156 // some registers, but not in others. That shouldn't happen a lot.
1157 void CodeGenRegBank::computeSubRegLaneMasks() {
1158   // First assign individual bits to all the leaf indices.
1159   unsigned Bit = 0;
1160   // Determine mask of lanes that cover their registers.
1161   CoveringLanes = ~0u;
1162   for (auto &Idx : SubRegIndices) {
1163     if (Idx.getComposites().empty()) {
1164       Idx.LaneMask = 1u << Bit;
1165       // Share bit 31 in the unlikely case there are more than 32 leafs.
1166       //
1167       // Sharing bits is harmless; it allows graceful degradation in targets
1168       // with more than 32 vector lanes. They simply get a limited resolution
1169       // view of lanes beyond the 32nd.
1170       //
1171       // See also the comment for getSubRegIndexLaneMask().
1172       if (Bit < 31)
1173         ++Bit;
1174       else
1175         // Once bit 31 is shared among multiple leafs, the 'lane' it represents
1176         // is no longer covering its registers.
1177         CoveringLanes &= ~(1u << Bit);
1178     } else {
1179       Idx.LaneMask = 0;
1180     }
1181   }
1182
1183   // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
1184   // here is that for each possible target subregister we look at the leafs
1185   // in the subregister graph that compose for this target and create
1186   // transformation sequences for the lanemasks. Each step in the sequence
1187   // consists of a bitmask and a bitrotate operation. As the rotation amounts
1188   // are usually the same for many subregisters we can easily combine the steps
1189   // by combining the masks.
1190   for (const auto &Idx : SubRegIndices) {
1191     const auto &Composites = Idx.getComposites();
1192     auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
1193     // Go through all leaf subregisters and find the ones that compose with Idx.
1194     // These make out all possible valid bits in the lane mask we want to
1195     // transform. Looking only at the leafs ensure that only a single bit in
1196     // the mask is set.
1197     unsigned NextBit = 0;
1198     for (auto &Idx2 : SubRegIndices) {
1199       // Skip non-leaf subregisters.
1200       if (!Idx2.getComposites().empty())
1201         continue;
1202       // Replicate the behaviour from the lane mask generation loop above.
1203       unsigned SrcBit = NextBit;
1204       unsigned SrcMask = 1u << SrcBit;
1205       if (NextBit < 31)
1206         ++NextBit;
1207       assert(Idx2.LaneMask == SrcMask);
1208
1209       // Get the composed subregister if there is any.
1210       auto C = Composites.find(&Idx2);
1211       if (C == Composites.end())
1212         continue;
1213       const CodeGenSubRegIndex *Composite = C->second;
1214       // The Composed subreg should be a leaf subreg too
1215       assert(Composite->getComposites().empty());
1216
1217       // Create Mask+Rotate operation and merge with existing ops if possible.
1218       unsigned DstBit = Log2_32(Composite->LaneMask);
1219       int Shift = DstBit - SrcBit;
1220       uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift : 32+Shift;
1221       for (auto &I : LaneTransforms) {
1222         if (I.RotateLeft == RotateLeft) {
1223           I.Mask |= SrcMask;
1224           SrcMask = 0;
1225         }
1226       }
1227       if (SrcMask != 0) {
1228         MaskRolPair MaskRol = { SrcMask, RotateLeft };
1229         LaneTransforms.push_back(MaskRol);
1230       }
1231     }
1232     // Optimize if the transformation consists of one step only: Set mask to
1233     // 0xffffffff (including some irrelevant invalid bits) so that it should
1234     // merge with more entries later while compressing the table.
1235     if (LaneTransforms.size() == 1)
1236       LaneTransforms[0].Mask = ~0u;
1237
1238     // Further compression optimization: For invalid compositions resulting
1239     // in a sequence with 0 entries we can just pick any other. Choose
1240     // Mask 0xffffffff with Rotation 0.
1241     if (LaneTransforms.size() == 0) {
1242       MaskRolPair P = { ~0u, 0 };
1243       LaneTransforms.push_back(P);
1244     }
1245   }
1246
1247   // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1248   // by the sub-register graph? This doesn't occur in any known targets.
1249
1250   // Inherit lanes from composites.
1251   for (const auto &Idx : SubRegIndices) {
1252     unsigned Mask = Idx.computeLaneMask();
1253     // If some super-registers without CoveredBySubRegs use this index, we can
1254     // no longer assume that the lanes are covering their registers.
1255     if (!Idx.AllSuperRegsCovered)
1256       CoveringLanes &= ~Mask;
1257   }
1258
1259   // Compute lane mask combinations for register classes.
1260   for (auto &RegClass : RegClasses) {
1261     unsigned LaneMask = 0;
1262     for (const auto &SubRegIndex : SubRegIndices) {
1263       if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr)
1264         continue;
1265       LaneMask |= SubRegIndex.LaneMask;
1266     }
1267     RegClass.LaneMask = LaneMask;
1268   }
1269 }
1270
1271 namespace {
1272 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1273 // the transitive closure of the union of overlapping register
1274 // classes. Together, the UberRegSets form a partition of the registers. If we
1275 // consider overlapping register classes to be connected, then each UberRegSet
1276 // is a set of connected components.
1277 //
1278 // An UberRegSet will likely be a horizontal slice of register names of
1279 // the same width. Nontrivial subregisters should then be in a separate
1280 // UberRegSet. But this property isn't required for valid computation of
1281 // register unit weights.
1282 //
1283 // A Weight field caches the max per-register unit weight in each UberRegSet.
1284 //
1285 // A set of SingularDeterminants flags single units of some register in this set
1286 // for which the unit weight equals the set weight. These units should not have
1287 // their weight increased.
1288 struct UberRegSet {
1289   CodeGenRegister::Vec Regs;
1290   unsigned Weight;
1291   CodeGenRegister::RegUnitList SingularDeterminants;
1292
1293   UberRegSet(): Weight(0) {}
1294 };
1295 } // namespace
1296
1297 // Partition registers into UberRegSets, where each set is the transitive
1298 // closure of the union of overlapping register classes.
1299 //
1300 // UberRegSets[0] is a special non-allocatable set.
1301 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1302                             std::vector<UberRegSet*> &RegSets,
1303                             CodeGenRegBank &RegBank) {
1304
1305   const auto &Registers = RegBank.getRegisters();
1306
1307   // The Register EnumValue is one greater than its index into Registers.
1308   assert(Registers.size() == Registers.back().EnumValue &&
1309          "register enum value mismatch");
1310
1311   // For simplicitly make the SetID the same as EnumValue.
1312   IntEqClasses UberSetIDs(Registers.size()+1);
1313   std::set<unsigned> AllocatableRegs;
1314   for (auto &RegClass : RegBank.getRegClasses()) {
1315     if (!RegClass.Allocatable)
1316       continue;
1317
1318     const CodeGenRegister::Vec &Regs = RegClass.getMembers();
1319     if (Regs.empty())
1320       continue;
1321
1322     unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1323     assert(USetID && "register number 0 is invalid");
1324
1325     AllocatableRegs.insert((*Regs.begin())->EnumValue);
1326     for (auto I = std::next(Regs.begin()), E = Regs.end(); I != E; ++I) {
1327       AllocatableRegs.insert((*I)->EnumValue);
1328       UberSetIDs.join(USetID, (*I)->EnumValue);
1329     }
1330   }
1331   // Combine non-allocatable regs.
1332   for (const auto &Reg : Registers) {
1333     unsigned RegNum = Reg.EnumValue;
1334     if (AllocatableRegs.count(RegNum))
1335       continue;
1336
1337     UberSetIDs.join(0, RegNum);
1338   }
1339   UberSetIDs.compress();
1340
1341   // Make the first UberSet a special unallocatable set.
1342   unsigned ZeroID = UberSetIDs[0];
1343
1344   // Insert Registers into the UberSets formed by union-find.
1345   // Do not resize after this.
1346   UberSets.resize(UberSetIDs.getNumClasses());
1347   unsigned i = 0;
1348   for (const CodeGenRegister &Reg : Registers) {
1349     unsigned USetID = UberSetIDs[Reg.EnumValue];
1350     if (!USetID)
1351       USetID = ZeroID;
1352     else if (USetID == ZeroID)
1353       USetID = 0;
1354
1355     UberRegSet *USet = &UberSets[USetID];
1356     USet->Regs.push_back(&Reg);
1357     sortAndUniqueRegisters(USet->Regs);
1358     RegSets[i++] = USet;
1359   }
1360 }
1361
1362 // Recompute each UberSet weight after changing unit weights.
1363 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1364                                CodeGenRegBank &RegBank) {
1365   // Skip the first unallocatable set.
1366   for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1367          E = UberSets.end(); I != E; ++I) {
1368
1369     // Initialize all unit weights in this set, and remember the max units/reg.
1370     const CodeGenRegister *Reg = nullptr;
1371     unsigned MaxWeight = 0, Weight = 0;
1372     for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1373       if (Reg != UnitI.getReg()) {
1374         if (Weight > MaxWeight)
1375           MaxWeight = Weight;
1376         Reg = UnitI.getReg();
1377         Weight = 0;
1378       }
1379       unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1380       if (!UWeight) {
1381         UWeight = 1;
1382         RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1383       }
1384       Weight += UWeight;
1385     }
1386     if (Weight > MaxWeight)
1387       MaxWeight = Weight;
1388     if (I->Weight != MaxWeight) {
1389       DEBUG(
1390         dbgs() << "UberSet " << I - UberSets.begin() << " Weight " << MaxWeight;
1391         for (auto &Unit : I->Regs)
1392           dbgs() << " " << Unit->getName();
1393         dbgs() << "\n");
1394       // Update the set weight.
1395       I->Weight = MaxWeight;
1396     }
1397
1398     // Find singular determinants.
1399     for (const auto R : I->Regs) {
1400       if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
1401         I->SingularDeterminants |= R->getRegUnits();
1402       }
1403     }
1404   }
1405 }
1406
1407 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1408 // a register and its subregisters so that they have the same weight as their
1409 // UberSet. Self-recursion processes the subregister tree in postorder so
1410 // subregisters are normalized first.
1411 //
1412 // Side effects:
1413 // - creates new adopted register units
1414 // - causes superregisters to inherit adopted units
1415 // - increases the weight of "singular" units
1416 // - induces recomputation of UberWeights.
1417 static bool normalizeWeight(CodeGenRegister *Reg,
1418                             std::vector<UberRegSet> &UberSets,
1419                             std::vector<UberRegSet*> &RegSets,
1420                             SparseBitVector<> &NormalRegs,
1421                             CodeGenRegister::RegUnitList &NormalUnits,
1422                             CodeGenRegBank &RegBank) {
1423   if (NormalRegs.test(Reg->EnumValue))
1424     return false;
1425   NormalRegs.set(Reg->EnumValue);
1426
1427   bool Changed = false;
1428   const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1429   for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1430          SRE = SRM.end(); SRI != SRE; ++SRI) {
1431     if (SRI->second == Reg)
1432       continue; // self-cycles happen
1433
1434     Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1435                                NormalRegs, NormalUnits, RegBank);
1436   }
1437   // Postorder register normalization.
1438
1439   // Inherit register units newly adopted by subregisters.
1440   if (Reg->inheritRegUnits(RegBank))
1441     computeUberWeights(UberSets, RegBank);
1442
1443   // Check if this register is too skinny for its UberRegSet.
1444   UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1445
1446   unsigned RegWeight = Reg->getWeight(RegBank);
1447   if (UberSet->Weight > RegWeight) {
1448     // A register unit's weight can be adjusted only if it is the singular unit
1449     // for this register, has not been used to normalize a subregister's set,
1450     // and has not already been used to singularly determine this UberRegSet.
1451     unsigned AdjustUnit = *Reg->getRegUnits().begin();
1452     if (Reg->getRegUnits().count() != 1
1453         || hasRegUnit(NormalUnits, AdjustUnit)
1454         || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1455       // We don't have an adjustable unit, so adopt a new one.
1456       AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1457       Reg->adoptRegUnit(AdjustUnit);
1458       // Adopting a unit does not immediately require recomputing set weights.
1459     }
1460     else {
1461       // Adjust the existing single unit.
1462       RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1463       // The unit may be shared among sets and registers within this set.
1464       computeUberWeights(UberSets, RegBank);
1465     }
1466     Changed = true;
1467   }
1468
1469   // Mark these units normalized so superregisters can't change their weights.
1470   NormalUnits |= Reg->getRegUnits();
1471
1472   return Changed;
1473 }
1474
1475 // Compute a weight for each register unit created during getSubRegs.
1476 //
1477 // The goal is that two registers in the same class will have the same weight,
1478 // where each register's weight is defined as sum of its units' weights.
1479 void CodeGenRegBank::computeRegUnitWeights() {
1480   std::vector<UberRegSet> UberSets;
1481   std::vector<UberRegSet*> RegSets(Registers.size());
1482   computeUberSets(UberSets, RegSets, *this);
1483   // UberSets and RegSets are now immutable.
1484
1485   computeUberWeights(UberSets, *this);
1486
1487   // Iterate over each Register, normalizing the unit weights until reaching
1488   // a fix point.
1489   unsigned NumIters = 0;
1490   for (bool Changed = true; Changed; ++NumIters) {
1491     assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1492     Changed = false;
1493     for (auto &Reg : Registers) {
1494       CodeGenRegister::RegUnitList NormalUnits;
1495       SparseBitVector<> NormalRegs;
1496       Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
1497                                  NormalUnits, *this);
1498     }
1499   }
1500 }
1501
1502 // Find a set in UniqueSets with the same elements as Set.
1503 // Return an iterator into UniqueSets.
1504 static std::vector<RegUnitSet>::const_iterator
1505 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1506                const RegUnitSet &Set) {
1507   std::vector<RegUnitSet>::const_iterator
1508     I = UniqueSets.begin(), E = UniqueSets.end();
1509   for(;I != E; ++I) {
1510     if (I->Units == Set.Units)
1511       break;
1512   }
1513   return I;
1514 }
1515
1516 // Return true if the RUSubSet is a subset of RUSuperSet.
1517 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1518                             const std::vector<unsigned> &RUSuperSet) {
1519   return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1520                        RUSubSet.begin(), RUSubSet.end());
1521 }
1522
1523 /// Iteratively prune unit sets. Prune subsets that are close to the superset,
1524 /// but with one or two registers removed. We occasionally have registers like
1525 /// APSR and PC thrown in with the general registers. We also see many
1526 /// special-purpose register subsets, such as tail-call and Thumb
1527 /// encodings. Generating all possible overlapping sets is combinatorial and
1528 /// overkill for modeling pressure. Ideally we could fix this statically in
1529 /// tablegen by (1) having the target define register classes that only include
1530 /// the allocatable registers and marking other classes as non-allocatable and
1531 /// (2) having a way to mark special purpose classes as "don't-care" classes for
1532 /// the purpose of pressure.  However, we make an attempt to handle targets that
1533 /// are not nicely defined by merging nearly identical register unit sets
1534 /// statically. This generates smaller tables. Then, dynamically, we adjust the
1535 /// set limit by filtering the reserved registers.
1536 ///
1537 /// Merge sets only if the units have the same weight. For example, on ARM,
1538 /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1539 /// should not expand the S set to include D regs.
1540 void CodeGenRegBank::pruneUnitSets() {
1541   assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1542
1543   // Form an equivalence class of UnitSets with no significant difference.
1544   std::vector<unsigned> SuperSetIDs;
1545   for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1546        SubIdx != EndIdx; ++SubIdx) {
1547     const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1548     unsigned SuperIdx = 0;
1549     for (; SuperIdx != EndIdx; ++SuperIdx) {
1550       if (SuperIdx == SubIdx)
1551         continue;
1552
1553       unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
1554       const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1555       if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1556           && (SubSet.Units.size() + 3 > SuperSet.Units.size())
1557           && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
1558           && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
1559         DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
1560               << "\n");
1561         break;
1562       }
1563     }
1564     if (SuperIdx == EndIdx)
1565       SuperSetIDs.push_back(SubIdx);
1566   }
1567   // Populate PrunedUnitSets with each equivalence class's superset.
1568   std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1569   for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1570     unsigned SuperIdx = SuperSetIDs[i];
1571     PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1572     PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1573   }
1574   RegUnitSets.swap(PrunedUnitSets);
1575 }
1576
1577 // Create a RegUnitSet for each RegClass that contains all units in the class
1578 // including adopted units that are necessary to model register pressure. Then
1579 // iteratively compute RegUnitSets such that the union of any two overlapping
1580 // RegUnitSets is repreresented.
1581 //
1582 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1583 // RegUnitSet that is a superset of that RegUnitClass.
1584 void CodeGenRegBank::computeRegUnitSets() {
1585   assert(RegUnitSets.empty() && "dirty RegUnitSets");
1586
1587   // Compute a unique RegUnitSet for each RegClass.
1588   auto &RegClasses = getRegClasses();
1589   for (auto &RC : RegClasses) {
1590     if (!RC.Allocatable)
1591       continue;
1592
1593     // Speculatively grow the RegUnitSets to hold the new set.
1594     RegUnitSets.resize(RegUnitSets.size() + 1);
1595     RegUnitSets.back().Name = RC.getName();
1596
1597     // Compute a sorted list of units in this class.
1598     RC.buildRegUnitSet(RegUnitSets.back().Units);
1599
1600     // Find an existing RegUnitSet.
1601     std::vector<RegUnitSet>::const_iterator SetI =
1602       findRegUnitSet(RegUnitSets, RegUnitSets.back());
1603     if (SetI != std::prev(RegUnitSets.end()))
1604       RegUnitSets.pop_back();
1605   }
1606
1607   DEBUG(dbgs() << "\nBefore pruning:\n";
1608         for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1609              USIdx < USEnd; ++USIdx) {
1610           dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1611                  << ":";
1612           for (auto &U : RegUnitSets[USIdx].Units)
1613             dbgs() << " " << RegUnits[U].Roots[0]->getName();
1614           dbgs() << "\n";
1615         });
1616
1617   // Iteratively prune unit sets.
1618   pruneUnitSets();
1619
1620   DEBUG(dbgs() << "\nBefore union:\n";
1621         for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1622              USIdx < USEnd; ++USIdx) {
1623           dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1624                  << ":";
1625           for (auto &U : RegUnitSets[USIdx].Units)
1626             dbgs() << " " << RegUnits[U].Roots[0]->getName();
1627           dbgs() << "\n";
1628         }
1629         dbgs() << "\nUnion sets:\n");
1630
1631   // Iterate over all unit sets, including new ones added by this loop.
1632   unsigned NumRegUnitSubSets = RegUnitSets.size();
1633   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1634     // In theory, this is combinatorial. In practice, it needs to be bounded
1635     // by a small number of sets for regpressure to be efficient.
1636     // If the assert is hit, we need to implement pruning.
1637     assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1638
1639     // Compare new sets with all original classes.
1640     for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1641          SearchIdx != EndIdx; ++SearchIdx) {
1642       std::set<unsigned> Intersection;
1643       std::set_intersection(RegUnitSets[Idx].Units.begin(),
1644                             RegUnitSets[Idx].Units.end(),
1645                             RegUnitSets[SearchIdx].Units.begin(),
1646                             RegUnitSets[SearchIdx].Units.end(),
1647                             std::inserter(Intersection, Intersection.begin()));
1648       if (Intersection.empty())
1649         continue;
1650
1651       // Speculatively grow the RegUnitSets to hold the new set.
1652       RegUnitSets.resize(RegUnitSets.size() + 1);
1653       RegUnitSets.back().Name =
1654         RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1655
1656       std::set_union(RegUnitSets[Idx].Units.begin(),
1657                      RegUnitSets[Idx].Units.end(),
1658                      RegUnitSets[SearchIdx].Units.begin(),
1659                      RegUnitSets[SearchIdx].Units.end(),
1660                      std::inserter(RegUnitSets.back().Units,
1661                                    RegUnitSets.back().Units.begin()));
1662
1663       // Find an existing RegUnitSet, or add the union to the unique sets.
1664       std::vector<RegUnitSet>::const_iterator SetI =
1665         findRegUnitSet(RegUnitSets, RegUnitSets.back());
1666       if (SetI != std::prev(RegUnitSets.end()))
1667         RegUnitSets.pop_back();
1668       else {
1669         DEBUG(dbgs() << "UnitSet " << RegUnitSets.size()-1
1670               << " " << RegUnitSets.back().Name << ":";
1671               for (auto &U : RegUnitSets.back().Units)
1672                 dbgs() << " " << RegUnits[U].Roots[0]->getName();
1673               dbgs() << "\n";);
1674       }
1675     }
1676   }
1677
1678   // Iteratively prune unit sets after inferring supersets.
1679   pruneUnitSets();
1680
1681   DEBUG(dbgs() << "\n";
1682         for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1683              USIdx < USEnd; ++USIdx) {
1684           dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1685                  << ":";
1686           for (auto &U : RegUnitSets[USIdx].Units)
1687             dbgs() << " " << RegUnits[U].Roots[0]->getName();
1688           dbgs() << "\n";
1689         });
1690
1691   // For each register class, list the UnitSets that are supersets.
1692   RegClassUnitSets.resize(RegClasses.size());
1693   int RCIdx = -1;
1694   for (auto &RC : RegClasses) {
1695     ++RCIdx;
1696     if (!RC.Allocatable)
1697       continue;
1698
1699     // Recompute the sorted list of units in this class.
1700     std::vector<unsigned> RCRegUnits;
1701     RC.buildRegUnitSet(RCRegUnits);
1702
1703     // Don't increase pressure for unallocatable regclasses.
1704     if (RCRegUnits.empty())
1705       continue;
1706
1707     DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n";
1708           for (auto &U : RCRegUnits)
1709             dbgs() << RegUnits[U].getRoots()[0]->getName() << " ";
1710           dbgs() << "\n  UnitSetIDs:");
1711
1712     // Find all supersets.
1713     for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1714          USIdx != USEnd; ++USIdx) {
1715       if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
1716         DEBUG(dbgs() << " " << USIdx);
1717         RegClassUnitSets[RCIdx].push_back(USIdx);
1718       }
1719     }
1720     DEBUG(dbgs() << "\n");
1721     assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1722   }
1723
1724   // For each register unit, ensure that we have the list of UnitSets that
1725   // contain the unit. Normally, this matches an existing list of UnitSets for a
1726   // register class. If not, we create a new entry in RegClassUnitSets as a
1727   // "fake" register class.
1728   for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
1729        UnitIdx < UnitEnd; ++UnitIdx) {
1730     std::vector<unsigned> RUSets;
1731     for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
1732       RegUnitSet &RUSet = RegUnitSets[i];
1733       if (std::find(RUSet.Units.begin(), RUSet.Units.end(), UnitIdx)
1734           == RUSet.Units.end())
1735         continue;
1736       RUSets.push_back(i);
1737     }
1738     unsigned RCUnitSetsIdx = 0;
1739     for (unsigned e = RegClassUnitSets.size();
1740          RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
1741       if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
1742         break;
1743       }
1744     }
1745     RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
1746     if (RCUnitSetsIdx == RegClassUnitSets.size()) {
1747       // Create a new list of UnitSets as a "fake" register class.
1748       RegClassUnitSets.resize(RCUnitSetsIdx + 1);
1749       RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
1750     }
1751   }
1752 }
1753
1754 void CodeGenRegBank::computeRegUnitLaneMasks() {
1755   for (auto &Register : Registers) {
1756     // Create an initial lane mask for all register units.
1757     const auto &RegUnits = Register.getRegUnits();
1758     CodeGenRegister::RegUnitLaneMaskList RegUnitLaneMasks(RegUnits.count(), 0);
1759     // Iterate through SubRegisters.
1760     typedef CodeGenRegister::SubRegMap SubRegMap;
1761     const SubRegMap &SubRegs = Register.getSubRegs();
1762     for (SubRegMap::const_iterator S = SubRegs.begin(),
1763          SE = SubRegs.end(); S != SE; ++S) {
1764       CodeGenRegister *SubReg = S->second;
1765       // Ignore non-leaf subregisters, their lane masks are fully covered by
1766       // the leaf subregisters anyway.
1767       if (SubReg->getSubRegs().size() != 0)
1768         continue;
1769       CodeGenSubRegIndex *SubRegIndex = S->first;
1770       const CodeGenRegister *SubRegister = S->second;
1771       unsigned LaneMask = SubRegIndex->LaneMask;
1772       // Distribute LaneMask to Register Units touched.
1773       for (const auto &SUI : SubRegister->getRegUnits()) {
1774         bool Found = false;
1775         unsigned u = 0;
1776         for (unsigned RU : RegUnits) {
1777           if (SUI == RU) {
1778             RegUnitLaneMasks[u] |= LaneMask;
1779             assert(!Found);
1780             Found = true;
1781           }
1782           ++u;
1783         }
1784         (void)Found;
1785         assert(Found);
1786       }
1787     }
1788     Register.setRegUnitLaneMasks(RegUnitLaneMasks);
1789   }
1790 }
1791
1792 void CodeGenRegBank::computeDerivedInfo() {
1793   computeComposites();
1794   computeSubRegLaneMasks();
1795
1796   // Compute a weight for each register unit created during getSubRegs.
1797   // This may create adopted register units (with unit # >= NumNativeRegUnits).
1798   computeRegUnitWeights();
1799
1800   // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1801   // supersets for the union of overlapping sets.
1802   computeRegUnitSets();
1803
1804   computeRegUnitLaneMasks();
1805
1806   // Get the weight of each set.
1807   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1808     RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
1809
1810   // Find the order of each set.
1811   RegUnitSetOrder.reserve(RegUnitSets.size());
1812   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1813     RegUnitSetOrder.push_back(Idx);
1814
1815   std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(),
1816                    [this](unsigned ID1, unsigned ID2) {
1817     return getRegPressureSet(ID1).Units.size() <
1818            getRegPressureSet(ID2).Units.size();
1819   });
1820   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1821     RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
1822   }
1823 }
1824
1825 //
1826 // Synthesize missing register class intersections.
1827 //
1828 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1829 // returns a maximal register class for all X.
1830 //
1831 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1832   assert(!RegClasses.empty());
1833   // Stash the iterator to the last element so that this loop doesn't visit
1834   // elements added by the getOrCreateSubClass call within it.
1835   for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
1836        I != std::next(E); ++I) {
1837     CodeGenRegisterClass *RC1 = RC;
1838     CodeGenRegisterClass *RC2 = &*I;
1839     if (RC1 == RC2)
1840       continue;
1841
1842     // Compute the set intersection of RC1 and RC2.
1843     const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
1844     const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
1845     CodeGenRegister::Vec Intersection;
1846     std::set_intersection(
1847         Memb1.begin(), Memb1.end(), Memb2.begin(), Memb2.end(),
1848         std::inserter(Intersection, Intersection.begin()), deref<llvm::less>());
1849
1850     // Skip disjoint class pairs.
1851     if (Intersection.empty())
1852       continue;
1853
1854     // If RC1 and RC2 have different spill sizes or alignments, use the
1855     // larger size for sub-classing.  If they are equal, prefer RC1.
1856     if (RC2->SpillSize > RC1->SpillSize ||
1857         (RC2->SpillSize == RC1->SpillSize &&
1858          RC2->SpillAlignment > RC1->SpillAlignment))
1859       std::swap(RC1, RC2);
1860
1861     getOrCreateSubClass(RC1, &Intersection,
1862                         RC1->getName() + "_and_" + RC2->getName());
1863   }
1864 }
1865
1866 //
1867 // Synthesize missing sub-classes for getSubClassWithSubReg().
1868 //
1869 // Make sure that the set of registers in RC with a given SubIdx sub-register
1870 // form a register class.  Update RC->SubClassWithSubReg.
1871 //
1872 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
1873   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
1874   typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
1875                    deref<llvm::less>> SubReg2SetMap;
1876
1877   // Compute the set of registers supporting each SubRegIndex.
1878   SubReg2SetMap SRSets;
1879   for (const auto R : RC->getMembers()) {
1880     const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
1881     for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1882          E = SRM.end(); I != E; ++I)
1883       SRSets[I->first].push_back(R);
1884   }
1885
1886   for (auto I : SRSets)
1887     sortAndUniqueRegisters(I.second);
1888
1889   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
1890   // numerical order to visit synthetic indices last.
1891   for (const auto &SubIdx : SubRegIndices) {
1892     SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
1893     // Unsupported SubRegIndex. Skip it.
1894     if (I == SRSets.end())
1895       continue;
1896     // In most cases, all RC registers support the SubRegIndex.
1897     if (I->second.size() == RC->getMembers().size()) {
1898       RC->setSubClassWithSubReg(&SubIdx, RC);
1899       continue;
1900     }
1901     // This is a real subset.  See if we have a matching class.
1902     CodeGenRegisterClass *SubRC =
1903       getOrCreateSubClass(RC, &I->second,
1904                           RC->getName() + "_with_" + I->first->getName());
1905     RC->setSubClassWithSubReg(&SubIdx, SubRC);
1906   }
1907 }
1908
1909 //
1910 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1911 //
1912 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1913 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1914 //
1915
1916 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1917                                                 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
1918   SmallVector<std::pair<const CodeGenRegister*,
1919                         const CodeGenRegister*>, 16> SSPairs;
1920   BitVector TopoSigs(getNumTopoSigs());
1921
1922   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1923   for (auto &SubIdx : SubRegIndices) {
1924     // Skip indexes that aren't fully supported by RC's registers. This was
1925     // computed by inferSubClassWithSubReg() above which should have been
1926     // called first.
1927     if (RC->getSubClassWithSubReg(&SubIdx) != RC)
1928       continue;
1929
1930     // Build list of (Super, Sub) pairs for this SubIdx.
1931     SSPairs.clear();
1932     TopoSigs.reset();
1933     for (const auto Super : RC->getMembers()) {
1934       const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
1935       assert(Sub && "Missing sub-register");
1936       SSPairs.push_back(std::make_pair(Super, Sub));
1937       TopoSigs.set(Sub->getTopoSig());
1938     }
1939
1940     // Iterate over sub-register class candidates.  Ignore classes created by
1941     // this loop. They will never be useful.
1942     // Store an iterator to the last element (not end) so that this loop doesn't
1943     // visit newly inserted elements.
1944     assert(!RegClasses.empty());
1945     for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
1946          I != std::next(E); ++I) {
1947       CodeGenRegisterClass &SubRC = *I;
1948       // Topological shortcut: SubRC members have the wrong shape.
1949       if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
1950         continue;
1951       // Compute the subset of RC that maps into SubRC.
1952       CodeGenRegister::Vec SubSetVec;
1953       for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1954         if (SubRC.contains(SSPairs[i].second))
1955           SubSetVec.push_back(SSPairs[i].first);
1956
1957       if (SubSetVec.empty())
1958         continue;
1959
1960       // RC injects completely into SubRC.
1961       sortAndUniqueRegisters(SubSetVec);
1962       if (SubSetVec.size() == SSPairs.size()) {
1963         SubRC.addSuperRegClass(&SubIdx, RC);
1964         continue;
1965       }
1966
1967       // Only a subset of RC maps into SubRC. Make sure it is represented by a
1968       // class.
1969       getOrCreateSubClass(RC, &SubSetVec, RC->getName() + "_with_" +
1970                                           SubIdx.getName() + "_in_" +
1971                                           SubRC.getName());
1972     }
1973   }
1974 }
1975
1976
1977 //
1978 // Infer missing register classes.
1979 //
1980 void CodeGenRegBank::computeInferredRegisterClasses() {
1981   assert(!RegClasses.empty());
1982   // When this function is called, the register classes have not been sorted
1983   // and assigned EnumValues yet.  That means getSubClasses(),
1984   // getSuperClasses(), and hasSubClass() functions are defunct.
1985
1986   // Use one-before-the-end so it doesn't move forward when new elements are
1987   // added.
1988   auto FirstNewRC = std::prev(RegClasses.end());
1989
1990   // Visit all register classes, including the ones being added by the loop.
1991   // Watch out for iterator invalidation here.
1992   for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
1993     CodeGenRegisterClass *RC = &*I;
1994
1995     // Synthesize answers for getSubClassWithSubReg().
1996     inferSubClassWithSubReg(RC);
1997
1998     // Synthesize answers for getCommonSubClass().
1999     inferCommonSubClass(RC);
2000
2001     // Synthesize answers for getMatchingSuperRegClass().
2002     inferMatchingSuperRegClass(RC);
2003
2004     // New register classes are created while this loop is running, and we need
2005     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
2006     // to match old super-register classes with sub-register classes created
2007     // after inferMatchingSuperRegClass was called.  At this point,
2008     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
2009     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
2010     if (I == FirstNewRC) {
2011       auto NextNewRC = std::prev(RegClasses.end());
2012       for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
2013            ++I2)
2014         inferMatchingSuperRegClass(&*I2, E2);
2015       FirstNewRC = NextNewRC;
2016     }
2017   }
2018 }
2019
2020 /// getRegisterClassForRegister - Find the register class that contains the
2021 /// specified physical register.  If the register is not in a register class,
2022 /// return null. If the register is in multiple classes, and the classes have a
2023 /// superset-subset relationship and the same set of types, return the
2024 /// superclass.  Otherwise return null.
2025 const CodeGenRegisterClass*
2026 CodeGenRegBank::getRegClassForRegister(Record *R) {
2027   const CodeGenRegister *Reg = getReg(R);
2028   const CodeGenRegisterClass *FoundRC = nullptr;
2029   for (const auto &RC : getRegClasses()) {
2030     if (!RC.contains(Reg))
2031       continue;
2032
2033     // If this is the first class that contains the register,
2034     // make a note of it and go on to the next class.
2035     if (!FoundRC) {
2036       FoundRC = &RC;
2037       continue;
2038     }
2039
2040     // If a register's classes have different types, return null.
2041     if (RC.getValueTypes() != FoundRC->getValueTypes())
2042       return nullptr;
2043
2044     // Check to see if the previously found class that contains
2045     // the register is a subclass of the current class. If so,
2046     // prefer the superclass.
2047     if (RC.hasSubClass(FoundRC)) {
2048       FoundRC = &RC;
2049       continue;
2050     }
2051
2052     // Check to see if the previously found class that contains
2053     // the register is a superclass of the current class. If so,
2054     // prefer the superclass.
2055     if (FoundRC->hasSubClass(&RC))
2056       continue;
2057
2058     // Multiple classes, and neither is a superclass of the other.
2059     // Return null.
2060     return nullptr;
2061   }
2062   return FoundRC;
2063 }
2064
2065 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
2066   SetVector<const CodeGenRegister*> Set;
2067
2068   // First add Regs with all sub-registers.
2069   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2070     CodeGenRegister *Reg = getReg(Regs[i]);
2071     if (Set.insert(Reg))
2072       // Reg is new, add all sub-registers.
2073       // The pre-ordering is not important here.
2074       Reg->addSubRegsPreOrder(Set, *this);
2075   }
2076
2077   // Second, find all super-registers that are completely covered by the set.
2078   for (unsigned i = 0; i != Set.size(); ++i) {
2079     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
2080     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
2081       const CodeGenRegister *Super = SR[j];
2082       if (!Super->CoveredBySubRegs || Set.count(Super))
2083         continue;
2084       // This new super-register is covered by its sub-registers.
2085       bool AllSubsInSet = true;
2086       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2087       for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2088              E = SRM.end(); I != E; ++I)
2089         if (!Set.count(I->second)) {
2090           AllSubsInSet = false;
2091           break;
2092         }
2093       // All sub-registers in Set, add Super as well.
2094       // We will visit Super later to recheck its super-registers.
2095       if (AllSubsInSet)
2096         Set.insert(Super);
2097     }
2098   }
2099
2100   // Convert to BitVector.
2101   BitVector BV(Registers.size() + 1);
2102   for (unsigned i = 0, e = Set.size(); i != e; ++i)
2103     BV.set(Set[i]->EnumValue);
2104   return BV;
2105 }