1 //===- Record.cpp - Record implementation ---------------------------------===//
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 // Implement the tablegen record classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Support/Allocator.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/SMLoc.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/TableGen/Error.h"
29 #include "llvm/TableGen/Record.h"
30 #include <cassert>
31 #include <cstdint>
32 #include <memory>
33 #include <string>
34 #include <utility>
35 #include <vector>
36 
37 using namespace llvm;
38 
39 static BumpPtrAllocator Allocator;
40 
41 //===----------------------------------------------------------------------===//
42 //    Type implementations
43 //===----------------------------------------------------------------------===//
44 
45 BitRecTy BitRecTy::Shared;
46 CodeRecTy CodeRecTy::Shared;
47 IntRecTy IntRecTy::Shared;
48 StringRecTy StringRecTy::Shared;
49 DagRecTy DagRecTy::Shared;
50 
51 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
52 LLVM_DUMP_METHOD void RecTy::dump() const { print(errs()); }
53 #endif
54 
55 ListRecTy *RecTy::getListTy() {
56   if (!ListTy)
57     ListTy = new(Allocator) ListRecTy(this);
58   return ListTy;
59 }
60 
61 bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
62   assert(RHS && "NULL pointer");
63   return Kind == RHS->getRecTyKind();
64 }
65 
66 bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
67 
68 bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
69   if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
70     return true;
71   if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
72     return BitsTy->getNumBits() == 1;
73   return false;
74 }
75 
76 BitsRecTy *BitsRecTy::get(unsigned Sz) {
77   static std::vector<BitsRecTy*> Shared;
78   if (Sz >= Shared.size())
79     Shared.resize(Sz + 1);
80   BitsRecTy *&Ty = Shared[Sz];
81   if (!Ty)
82     Ty = new(Allocator) BitsRecTy(Sz);
83   return Ty;
84 }
85 
86 std::string BitsRecTy::getAsString() const {
87   return "bits<" + utostr(Size) + ">";
88 }
89 
90 bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
91   if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
92     return cast<BitsRecTy>(RHS)->Size == Size;
93   RecTyKind kind = RHS->getRecTyKind();
94   return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
95 }
96 
97 bool BitsRecTy::typeIsA(const RecTy *RHS) const {
98   if (const BitsRecTy *RHSb = dyn_cast<BitsRecTy>(RHS))
99     return RHSb->Size == Size;
100   return false;
101 }
102 
103 bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
104   RecTyKind kind = RHS->getRecTyKind();
105   return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
106 }
107 
108 bool CodeRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
109   RecTyKind Kind = RHS->getRecTyKind();
110   return Kind == CodeRecTyKind || Kind == StringRecTyKind;
111 }
112 
113 std::string StringRecTy::getAsString() const {
114   return "string";
115 }
116 
117 bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
118   RecTyKind Kind = RHS->getRecTyKind();
119   return Kind == StringRecTyKind || Kind == CodeRecTyKind;
120 }
121 
122 std::string ListRecTy::getAsString() const {
123   return "list<" + Ty->getAsString() + ">";
124 }
125 
126 bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
127   if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
128     return Ty->typeIsConvertibleTo(ListTy->getElementType());
129   return false;
130 }
131 
132 bool ListRecTy::typeIsA(const RecTy *RHS) const {
133   if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS))
134     return getElementType()->typeIsA(RHSl->getElementType());
135   return false;
136 }
137 
138 std::string DagRecTy::getAsString() const {
139   return "dag";
140 }
141 
142 static void ProfileRecordRecTy(FoldingSetNodeID &ID,
143                                ArrayRef<Record *> Classes) {
144   ID.AddInteger(Classes.size());
145   for (Record *R : Classes)
146     ID.AddPointer(R);
147 }
148 
149 RecordRecTy *RecordRecTy::get(ArrayRef<Record *> UnsortedClasses) {
150   if (UnsortedClasses.empty()) {
151     static RecordRecTy AnyRecord(0);
152     return &AnyRecord;
153   }
154 
155   FoldingSet<RecordRecTy> &ThePool =
156       UnsortedClasses[0]->getRecords().RecordTypePool;
157 
158   SmallVector<Record *, 4> Classes(UnsortedClasses.begin(),
159                                    UnsortedClasses.end());
160   std::sort(Classes.begin(), Classes.end(),
161             [](Record *LHS, Record *RHS) {
162               return LHS->getNameInitAsString() < RHS->getNameInitAsString();
163             });
164 
165   FoldingSetNodeID ID;
166   ProfileRecordRecTy(ID, Classes);
167 
168   void *IP = nullptr;
169   if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP))
170     return Ty;
171 
172 #ifndef NDEBUG
173   // Check for redundancy.
174   for (unsigned i = 0; i < Classes.size(); ++i) {
175     for (unsigned j = 0; j < Classes.size(); ++j) {
176       assert(i == j || !Classes[i]->isSubClassOf(Classes[j]));
177     }
178     assert(&Classes[0]->getRecords() == &Classes[i]->getRecords());
179   }
180 #endif
181 
182   void *Mem = Allocator.Allocate(totalSizeToAlloc<Record *>(Classes.size()),
183                                  alignof(RecordRecTy));
184   RecordRecTy *Ty = new(Mem) RecordRecTy(Classes.size());
185   std::uninitialized_copy(Classes.begin(), Classes.end(),
186                           Ty->getTrailingObjects<Record *>());
187   ThePool.InsertNode(Ty, IP);
188   return Ty;
189 }
190 
191 void RecordRecTy::Profile(FoldingSetNodeID &ID) const {
192   ProfileRecordRecTy(ID, getClasses());
193 }
194 
195 std::string RecordRecTy::getAsString() const {
196   if (NumClasses == 1)
197     return getClasses()[0]->getName();
198 
199   std::string Str = "{";
200   bool First = true;
201   for (Record *R : getClasses()) {
202     if (!First)
203       Str += ", ";
204     First = false;
205     Str += R->getName();
206   }
207   Str += "}";
208   return Str;
209 }
210 
211 bool RecordRecTy::isSubClassOf(Record *Class) const {
212   return llvm::any_of(getClasses(), [Class](Record *MySuperClass) {
213                                       return MySuperClass == Class ||
214                                              MySuperClass->isSubClassOf(Class);
215                                     });
216 }
217 
218 bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
219   if (this == RHS)
220     return true;
221 
222   const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
223   if (!RTy)
224     return false;
225 
226   return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) {
227                                            return isSubClassOf(TargetClass);
228                                          });
229 }
230 
231 bool RecordRecTy::typeIsA(const RecTy *RHS) const {
232   return typeIsConvertibleTo(RHS);
233 }
234 
235 static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) {
236   SmallVector<Record *, 4> CommonSuperClasses;
237   SmallVector<Record *, 4> Stack;
238 
239   Stack.insert(Stack.end(), T1->classes_begin(), T1->classes_end());
240 
241   while (!Stack.empty()) {
242     Record *R = Stack.back();
243     Stack.pop_back();
244 
245     if (T2->isSubClassOf(R)) {
246       CommonSuperClasses.push_back(R);
247     } else {
248       R->getDirectSuperClasses(Stack);
249     }
250   }
251 
252   return RecordRecTy::get(CommonSuperClasses);
253 }
254 
255 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
256   if (T1 == T2)
257     return T1;
258 
259   if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
260     if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2))
261       return resolveRecordTypes(RecTy1, RecTy2);
262   }
263 
264   if (T1->typeIsConvertibleTo(T2))
265     return T2;
266   if (T2->typeIsConvertibleTo(T1))
267     return T1;
268 
269   if (ListRecTy *ListTy1 = dyn_cast<ListRecTy>(T1)) {
270     if (ListRecTy *ListTy2 = dyn_cast<ListRecTy>(T2)) {
271       RecTy* NewType = resolveTypes(ListTy1->getElementType(),
272                                     ListTy2->getElementType());
273       if (NewType)
274         return NewType->getListTy();
275     }
276   }
277 
278   return nullptr;
279 }
280 
281 //===----------------------------------------------------------------------===//
282 //    Initializer implementations
283 //===----------------------------------------------------------------------===//
284 
285 void Init::anchor() {}
286 
287 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
288 LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); }
289 #endif
290 
291 UnsetInit *UnsetInit::get() {
292   static UnsetInit TheInit;
293   return &TheInit;
294 }
295 
296 Init *UnsetInit::getCastTo(RecTy *Ty) const {
297   return const_cast<UnsetInit *>(this);
298 }
299 
300 Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
301   return const_cast<UnsetInit *>(this);
302 }
303 
304 BitInit *BitInit::get(bool V) {
305   static BitInit True(true);
306   static BitInit False(false);
307 
308   return V ? &True : &False;
309 }
310 
311 Init *BitInit::convertInitializerTo(RecTy *Ty) const {
312   if (isa<BitRecTy>(Ty))
313     return const_cast<BitInit *>(this);
314 
315   if (isa<IntRecTy>(Ty))
316     return IntInit::get(getValue());
317 
318   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
319     // Can only convert single bit.
320     if (BRT->getNumBits() == 1)
321       return BitsInit::get(const_cast<BitInit *>(this));
322   }
323 
324   return nullptr;
325 }
326 
327 static void
328 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
329   ID.AddInteger(Range.size());
330 
331   for (Init *I : Range)
332     ID.AddPointer(I);
333 }
334 
335 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
336   static FoldingSet<BitsInit> ThePool;
337 
338   FoldingSetNodeID ID;
339   ProfileBitsInit(ID, Range);
340 
341   void *IP = nullptr;
342   if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
343     return I;
344 
345   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
346                                  alignof(BitsInit));
347   BitsInit *I = new(Mem) BitsInit(Range.size());
348   std::uninitialized_copy(Range.begin(), Range.end(),
349                           I->getTrailingObjects<Init *>());
350   ThePool.InsertNode(I, IP);
351   return I;
352 }
353 
354 void BitsInit::Profile(FoldingSetNodeID &ID) const {
355   ProfileBitsInit(ID, makeArrayRef(getTrailingObjects<Init *>(), NumBits));
356 }
357 
358 Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
359   if (isa<BitRecTy>(Ty)) {
360     if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
361     return getBit(0);
362   }
363 
364   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
365     // If the number of bits is right, return it.  Otherwise we need to expand
366     // or truncate.
367     if (getNumBits() != BRT->getNumBits()) return nullptr;
368     return const_cast<BitsInit *>(this);
369   }
370 
371   if (isa<IntRecTy>(Ty)) {
372     int64_t Result = 0;
373     for (unsigned i = 0, e = getNumBits(); i != e; ++i)
374       if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
375         Result |= static_cast<int64_t>(Bit->getValue()) << i;
376       else
377         return nullptr;
378     return IntInit::get(Result);
379   }
380 
381   return nullptr;
382 }
383 
384 Init *
385 BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
386   SmallVector<Init *, 16> NewBits(Bits.size());
387 
388   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
389     if (Bits[i] >= getNumBits())
390       return nullptr;
391     NewBits[i] = getBit(Bits[i]);
392   }
393   return BitsInit::get(NewBits);
394 }
395 
396 bool BitsInit::isConcrete() const {
397   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
398     if (!getBit(i)->isConcrete())
399       return false;
400   }
401   return true;
402 }
403 
404 std::string BitsInit::getAsString() const {
405   std::string Result = "{ ";
406   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
407     if (i) Result += ", ";
408     if (Init *Bit = getBit(e-i-1))
409       Result += Bit->getAsString();
410     else
411       Result += "*";
412   }
413   return Result + " }";
414 }
415 
416 // resolveReferences - If there are any field references that refer to fields
417 // that have been filled in, we can propagate the values now.
418 Init *BitsInit::resolveReferences(Resolver &R) const {
419   bool Changed = false;
420   SmallVector<Init *, 16> NewBits(getNumBits());
421 
422   Init *CachedBitVarRef = nullptr;
423   Init *CachedBitVarResolved = nullptr;
424 
425   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
426     Init *CurBit = getBit(i);
427     Init *NewBit = CurBit;
428 
429     if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
430       if (CurBitVar->getBitVar() != CachedBitVarRef) {
431         CachedBitVarRef = CurBitVar->getBitVar();
432         CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
433       }
434 
435       NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());
436     } else {
437       // getBit(0) implicitly converts int and bits<1> values to bit.
438       NewBit = CurBit->resolveReferences(R)->getBit(0);
439     }
440 
441     if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
442       NewBit = CurBit;
443     NewBits[i] = NewBit;
444     Changed |= CurBit != NewBit;
445   }
446 
447   if (Changed)
448     return BitsInit::get(NewBits);
449 
450   return const_cast<BitsInit *>(this);
451 }
452 
453 IntInit *IntInit::get(int64_t V) {
454   static DenseMap<int64_t, IntInit*> ThePool;
455 
456   IntInit *&I = ThePool[V];
457   if (!I) I = new(Allocator) IntInit(V);
458   return I;
459 }
460 
461 std::string IntInit::getAsString() const {
462   return itostr(Value);
463 }
464 
465 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
466   // For example, with NumBits == 4, we permit Values from [-7 .. 15].
467   return (NumBits >= sizeof(Value) * 8) ||
468          (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
469 }
470 
471 Init *IntInit::convertInitializerTo(RecTy *Ty) const {
472   if (isa<IntRecTy>(Ty))
473     return const_cast<IntInit *>(this);
474 
475   if (isa<BitRecTy>(Ty)) {
476     int64_t Val = getValue();
477     if (Val != 0 && Val != 1) return nullptr;  // Only accept 0 or 1 for a bit!
478     return BitInit::get(Val != 0);
479   }
480 
481   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
482     int64_t Value = getValue();
483     // Make sure this bitfield is large enough to hold the integer value.
484     if (!canFitInBitfield(Value, BRT->getNumBits()))
485       return nullptr;
486 
487     SmallVector<Init *, 16> NewBits(BRT->getNumBits());
488     for (unsigned i = 0; i != BRT->getNumBits(); ++i)
489       NewBits[i] = BitInit::get(Value & (1LL << i));
490 
491     return BitsInit::get(NewBits);
492   }
493 
494   return nullptr;
495 }
496 
497 Init *
498 IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
499   SmallVector<Init *, 16> NewBits(Bits.size());
500 
501   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
502     if (Bits[i] >= 64)
503       return nullptr;
504 
505     NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
506   }
507   return BitsInit::get(NewBits);
508 }
509 
510 CodeInit *CodeInit::get(StringRef V) {
511   static StringMap<CodeInit*, BumpPtrAllocator &> ThePool(Allocator);
512 
513   auto &Entry = *ThePool.insert(std::make_pair(V, nullptr)).first;
514   if (!Entry.second)
515     Entry.second = new(Allocator) CodeInit(Entry.getKey());
516   return Entry.second;
517 }
518 
519 StringInit *StringInit::get(StringRef V) {
520   static StringMap<StringInit*, BumpPtrAllocator &> ThePool(Allocator);
521 
522   auto &Entry = *ThePool.insert(std::make_pair(V, nullptr)).first;
523   if (!Entry.second)
524     Entry.second = new(Allocator) StringInit(Entry.getKey());
525   return Entry.second;
526 }
527 
528 Init *StringInit::convertInitializerTo(RecTy *Ty) const {
529   if (isa<StringRecTy>(Ty))
530     return const_cast<StringInit *>(this);
531   if (isa<CodeRecTy>(Ty))
532     return CodeInit::get(getValue());
533 
534   return nullptr;
535 }
536 
537 Init *CodeInit::convertInitializerTo(RecTy *Ty) const {
538   if (isa<CodeRecTy>(Ty))
539     return const_cast<CodeInit *>(this);
540   if (isa<StringRecTy>(Ty))
541     return StringInit::get(getValue());
542 
543   return nullptr;
544 }
545 
546 static void ProfileListInit(FoldingSetNodeID &ID,
547                             ArrayRef<Init *> Range,
548                             RecTy *EltTy) {
549   ID.AddInteger(Range.size());
550   ID.AddPointer(EltTy);
551 
552   for (Init *I : Range)
553     ID.AddPointer(I);
554 }
555 
556 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
557   static FoldingSet<ListInit> ThePool;
558 
559   FoldingSetNodeID ID;
560   ProfileListInit(ID, Range, EltTy);
561 
562   void *IP = nullptr;
563   if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
564     return I;
565 
566   assert(Range.empty() || !isa<TypedInit>(Range[0]) ||
567          cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy));
568 
569   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
570                                  alignof(ListInit));
571   ListInit *I = new(Mem) ListInit(Range.size(), EltTy);
572   std::uninitialized_copy(Range.begin(), Range.end(),
573                           I->getTrailingObjects<Init *>());
574   ThePool.InsertNode(I, IP);
575   return I;
576 }
577 
578 void ListInit::Profile(FoldingSetNodeID &ID) const {
579   RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
580 
581   ProfileListInit(ID, getValues(), EltTy);
582 }
583 
584 Init *ListInit::convertInitializerTo(RecTy *Ty) const {
585   if (getType() == Ty)
586     return const_cast<ListInit*>(this);
587 
588   if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
589     SmallVector<Init*, 8> Elements;
590     Elements.reserve(getValues().size());
591 
592     // Verify that all of the elements of the list are subclasses of the
593     // appropriate class!
594     bool Changed = false;
595     RecTy *ElementType = LRT->getElementType();
596     for (Init *I : getValues())
597       if (Init *CI = I->convertInitializerTo(ElementType)) {
598         Elements.push_back(CI);
599         if (CI != I)
600           Changed = true;
601       } else
602         return nullptr;
603 
604     if (!Changed)
605       return const_cast<ListInit*>(this);
606     return ListInit::get(Elements, ElementType);
607   }
608 
609   return nullptr;
610 }
611 
612 Init *ListInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
613   SmallVector<Init*, 8> Vals;
614   Vals.reserve(Elements.size());
615   for (unsigned Element : Elements) {
616     if (Element >= size())
617       return nullptr;
618     Vals.push_back(getElement(Element));
619   }
620   return ListInit::get(Vals, getElementType());
621 }
622 
623 Record *ListInit::getElementAsRecord(unsigned i) const {
624   assert(i < NumValues && "List element index out of range!");
625   DefInit *DI = dyn_cast<DefInit>(getElement(i));
626   if (!DI)
627     PrintFatalError("Expected record in list!");
628   return DI->getDef();
629 }
630 
631 Init *ListInit::resolveReferences(Resolver &R) const {
632   SmallVector<Init*, 8> Resolved;
633   Resolved.reserve(size());
634   bool Changed = false;
635 
636   for (Init *CurElt : getValues()) {
637     Init *E;
638 
639     do {
640       E = CurElt;
641       CurElt = CurElt->resolveReferences(R);
642       Changed |= E != CurElt;
643     } while (E != CurElt);
644     Resolved.push_back(E);
645   }
646 
647   if (Changed)
648     return ListInit::get(Resolved, getElementType());
649   return const_cast<ListInit *>(this);
650 }
651 
652 bool ListInit::isConcrete() const {
653   for (Init *Element : *this) {
654     if (!Element->isConcrete())
655       return false;
656   }
657   return true;
658 }
659 
660 std::string ListInit::getAsString() const {
661   std::string Result = "[";
662   const char *sep = "";
663   for (Init *Element : *this) {
664     Result += sep;
665     sep = ", ";
666     Result += Element->getAsString();
667   }
668   return Result + "]";
669 }
670 
671 Init *OpInit::getBit(unsigned Bit) const {
672   if (getType() == BitRecTy::get())
673     return const_cast<OpInit*>(this);
674   return VarBitInit::get(const_cast<OpInit*>(this), Bit);
675 }
676 
677 static void
678 ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {
679   ID.AddInteger(Opcode);
680   ID.AddPointer(Op);
681   ID.AddPointer(Type);
682 }
683 
684 UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {
685   static FoldingSet<UnOpInit> ThePool;
686 
687   FoldingSetNodeID ID;
688   ProfileUnOpInit(ID, Opc, LHS, Type);
689 
690   void *IP = nullptr;
691   if (UnOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
692     return I;
693 
694   UnOpInit *I = new(Allocator) UnOpInit(Opc, LHS, Type);
695   ThePool.InsertNode(I, IP);
696   return I;
697 }
698 
699 void UnOpInit::Profile(FoldingSetNodeID &ID) const {
700   ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());
701 }
702 
703 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
704   switch (getOpcode()) {
705   case CAST:
706     if (isa<StringRecTy>(getType())) {
707       if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
708         return LHSs;
709 
710       if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
711         return StringInit::get(LHSd->getAsString());
712 
713       if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
714         return StringInit::get(LHSi->getAsString());
715     } else if (isa<RecordRecTy>(getType())) {
716       if (StringInit *Name = dyn_cast<StringInit>(LHS)) {
717         // From TGParser::ParseIDValue
718         if (CurRec) {
719           if (const RecordVal *RV = CurRec->getValue(Name)) {
720             if (RV->getType() != getType())
721               PrintFatalError("type mismatch in cast");
722             return VarInit::get(Name, RV->getType());
723           }
724 
725           Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
726                                               ":");
727 
728           if (CurRec->isTemplateArg(TemplateArgName)) {
729             const RecordVal *RV = CurRec->getValue(TemplateArgName);
730             assert(RV && "Template arg doesn't exist??");
731 
732             if (RV->getType() != getType())
733               PrintFatalError("type mismatch in cast");
734 
735             return VarInit::get(TemplateArgName, RV->getType());
736           }
737         }
738 
739         if (CurMultiClass) {
740           Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
741                                      "::");
742 
743           if (CurMultiClass->Rec.isTemplateArg(MCName)) {
744             const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
745             assert(RV && "Template arg doesn't exist??");
746 
747             if (RV->getType() != getType())
748               PrintFatalError("type mismatch in cast");
749 
750             return VarInit::get(MCName, RV->getType());
751           }
752         }
753         assert(CurRec && "NULL pointer");
754         if (Record *D = (CurRec->getRecords()).getDef(Name->getValue()))
755           return DefInit::get(D);
756 
757         PrintFatalError(CurRec->getLoc(),
758                         "Undefined reference:'" + Name->getValue() + "'\n");
759       }
760     }
761 
762     if (Init *NewInit = LHS->convertInitializerTo(getType()))
763       return NewInit;
764     break;
765 
766   case HEAD:
767     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
768       assert(!LHSl->empty() && "Empty list in head");
769       return LHSl->getElement(0);
770     }
771     break;
772 
773   case TAIL:
774     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
775       assert(!LHSl->empty() && "Empty list in tail");
776       // Note the +1.  We can't just pass the result of getValues()
777       // directly.
778       return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType());
779     }
780     break;
781 
782   case SIZE:
783     if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
784       return IntInit::get(LHSl->size());
785     break;
786 
787   case EMPTY:
788     if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
789       return IntInit::get(LHSl->empty());
790     if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
791       return IntInit::get(LHSs->getValue().empty());
792     break;
793   }
794   return const_cast<UnOpInit *>(this);
795 }
796 
797 Init *UnOpInit::resolveReferences(Resolver &R) const {
798   Init *lhs = LHS->resolveReferences(R);
799 
800   if (LHS != lhs)
801     return (UnOpInit::get(getOpcode(), lhs, getType()))
802         ->Fold(R.getCurrentRecord(), nullptr);
803   return Fold(R.getCurrentRecord(), nullptr);
804 }
805 
806 std::string UnOpInit::getAsString() const {
807   std::string Result;
808   switch (getOpcode()) {
809   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
810   case HEAD: Result = "!head"; break;
811   case TAIL: Result = "!tail"; break;
812   case SIZE: Result = "!size"; break;
813   case EMPTY: Result = "!empty"; break;
814   }
815   return Result + "(" + LHS->getAsString() + ")";
816 }
817 
818 static void
819 ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
820                  RecTy *Type) {
821   ID.AddInteger(Opcode);
822   ID.AddPointer(LHS);
823   ID.AddPointer(RHS);
824   ID.AddPointer(Type);
825 }
826 
827 BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS,
828                           Init *RHS, RecTy *Type) {
829   static FoldingSet<BinOpInit> ThePool;
830 
831   FoldingSetNodeID ID;
832   ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
833 
834   void *IP = nullptr;
835   if (BinOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
836     return I;
837 
838   BinOpInit *I = new(Allocator) BinOpInit(Opc, LHS, RHS, Type);
839   ThePool.InsertNode(I, IP);
840   return I;
841 }
842 
843 void BinOpInit::Profile(FoldingSetNodeID &ID) const {
844   ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
845 }
846 
847 static StringInit *ConcatStringInits(const StringInit *I0,
848                                      const StringInit *I1) {
849   SmallString<80> Concat(I0->getValue());
850   Concat.append(I1->getValue());
851   return StringInit::get(Concat);
852 }
853 
854 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
855   switch (getOpcode()) {
856   case CONCAT: {
857     DagInit *LHSs = dyn_cast<DagInit>(LHS);
858     DagInit *RHSs = dyn_cast<DagInit>(RHS);
859     if (LHSs && RHSs) {
860       DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
861       DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
862       if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
863         PrintFatalError("Concated Dag operators do not match!");
864       SmallVector<Init*, 8> Args;
865       SmallVector<StringInit*, 8> ArgNames;
866       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
867         Args.push_back(LHSs->getArg(i));
868         ArgNames.push_back(LHSs->getArgName(i));
869       }
870       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
871         Args.push_back(RHSs->getArg(i));
872         ArgNames.push_back(RHSs->getArgName(i));
873       }
874       return DagInit::get(LHSs->getOperator(), nullptr, Args, ArgNames);
875     }
876     break;
877   }
878   case LISTCONCAT: {
879     ListInit *LHSs = dyn_cast<ListInit>(LHS);
880     ListInit *RHSs = dyn_cast<ListInit>(RHS);
881     if (LHSs && RHSs) {
882       SmallVector<Init *, 8> Args;
883       Args.insert(Args.end(), LHSs->begin(), LHSs->end());
884       Args.insert(Args.end(), RHSs->begin(), RHSs->end());
885       return ListInit::get(Args, LHSs->getElementType());
886     }
887     break;
888   }
889   case STRCONCAT: {
890     StringInit *LHSs = dyn_cast<StringInit>(LHS);
891     StringInit *RHSs = dyn_cast<StringInit>(RHS);
892     if (LHSs && RHSs)
893       return ConcatStringInits(LHSs, RHSs);
894     break;
895   }
896   case EQ: {
897     // try to fold eq comparison for 'bit' and 'int', otherwise fallback
898     // to string objects.
899     IntInit *L =
900       dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
901     IntInit *R =
902       dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
903 
904     if (L && R)
905       return IntInit::get(L->getValue() == R->getValue());
906 
907     StringInit *LHSs = dyn_cast<StringInit>(LHS);
908     StringInit *RHSs = dyn_cast<StringInit>(RHS);
909 
910     // Make sure we've resolved
911     if (LHSs && RHSs)
912       return IntInit::get(LHSs->getValue() == RHSs->getValue());
913 
914     break;
915   }
916   case ADD:
917   case AND:
918   case OR:
919   case SHL:
920   case SRA:
921   case SRL: {
922     IntInit *LHSi =
923       dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
924     IntInit *RHSi =
925       dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
926     if (LHSi && RHSi) {
927       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
928       int64_t Result;
929       switch (getOpcode()) {
930       default: llvm_unreachable("Bad opcode!");
931       case ADD: Result = LHSv +  RHSv; break;
932       case AND: Result = LHSv &  RHSv; break;
933       case OR: Result = LHSv | RHSv; break;
934       case SHL: Result = LHSv << RHSv; break;
935       case SRA: Result = LHSv >> RHSv; break;
936       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
937       }
938       return IntInit::get(Result);
939     }
940     break;
941   }
942   }
943   return const_cast<BinOpInit *>(this);
944 }
945 
946 Init *BinOpInit::resolveReferences(Resolver &R) const {
947   Init *lhs = LHS->resolveReferences(R);
948   Init *rhs = RHS->resolveReferences(R);
949 
950   if (LHS != lhs || RHS != rhs)
951     return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
952         ->Fold(R.getCurrentRecord(), nullptr);
953   return Fold(R.getCurrentRecord(), nullptr);
954 }
955 
956 std::string BinOpInit::getAsString() const {
957   std::string Result;
958   switch (getOpcode()) {
959   case CONCAT: Result = "!con"; break;
960   case ADD: Result = "!add"; break;
961   case AND: Result = "!and"; break;
962   case OR: Result = "!or"; break;
963   case SHL: Result = "!shl"; break;
964   case SRA: Result = "!sra"; break;
965   case SRL: Result = "!srl"; break;
966   case EQ: Result = "!eq"; break;
967   case LISTCONCAT: Result = "!listconcat"; break;
968   case STRCONCAT: Result = "!strconcat"; break;
969   }
970   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
971 }
972 
973 static void
974 ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
975                   Init *RHS, RecTy *Type) {
976   ID.AddInteger(Opcode);
977   ID.AddPointer(LHS);
978   ID.AddPointer(MHS);
979   ID.AddPointer(RHS);
980   ID.AddPointer(Type);
981 }
982 
983 TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
984                             RecTy *Type) {
985   static FoldingSet<TernOpInit> ThePool;
986 
987   FoldingSetNodeID ID;
988   ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
989 
990   void *IP = nullptr;
991   if (TernOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
992     return I;
993 
994   TernOpInit *I = new(Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
995   ThePool.InsertNode(I, IP);
996   return I;
997 }
998 
999 void TernOpInit::Profile(FoldingSetNodeID &ID) const {
1000   ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
1001 }
1002 
1003 static Init *ForeachApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {
1004   MapResolver R(CurRec);
1005   R.set(LHS, MHSe);
1006   return RHS->resolveReferences(R);
1007 }
1008 
1009 static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,
1010                              Record *CurRec) {
1011   bool Change = false;
1012   Init *Val = ForeachApply(LHS, MHSd->getOperator(), RHS, CurRec);
1013   if (Val != MHSd->getOperator())
1014     Change = true;
1015 
1016   SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;
1017   for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1018     Init *Arg = MHSd->getArg(i);
1019     Init *NewArg;
1020     StringInit *ArgName = MHSd->getArgName(i);
1021 
1022     if (DagInit *Argd = dyn_cast<DagInit>(Arg))
1023       NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
1024     else
1025       NewArg = ForeachApply(LHS, Arg, RHS, CurRec);
1026 
1027     NewArgs.push_back(std::make_pair(NewArg, ArgName));
1028     if (Arg != NewArg)
1029       Change = true;
1030   }
1031 
1032   if (Change)
1033     return DagInit::get(Val, nullptr, NewArgs);
1034   return MHSd;
1035 }
1036 
1037 // Applies RHS to all elements of MHS, using LHS as a temp variable.
1038 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1039                            Record *CurRec) {
1040   if (DagInit *MHSd = dyn_cast<DagInit>(MHS))
1041     return ForeachDagApply(LHS, MHSd, RHS, CurRec);
1042 
1043   if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1044     SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());
1045 
1046     for (Init *&Item : NewList) {
1047       Init *NewItem = ForeachApply(LHS, Item, RHS, CurRec);
1048       if (NewItem != Item)
1049         Item = NewItem;
1050     }
1051     return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1052   }
1053 
1054   return nullptr;
1055 }
1056 
1057 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1058   switch (getOpcode()) {
1059   case SUBST: {
1060     DefInit *LHSd = dyn_cast<DefInit>(LHS);
1061     VarInit *LHSv = dyn_cast<VarInit>(LHS);
1062     StringInit *LHSs = dyn_cast<StringInit>(LHS);
1063 
1064     DefInit *MHSd = dyn_cast<DefInit>(MHS);
1065     VarInit *MHSv = dyn_cast<VarInit>(MHS);
1066     StringInit *MHSs = dyn_cast<StringInit>(MHS);
1067 
1068     DefInit *RHSd = dyn_cast<DefInit>(RHS);
1069     VarInit *RHSv = dyn_cast<VarInit>(RHS);
1070     StringInit *RHSs = dyn_cast<StringInit>(RHS);
1071 
1072     if (LHSd && MHSd && RHSd) {
1073       Record *Val = RHSd->getDef();
1074       if (LHSd->getAsString() == RHSd->getAsString())
1075         Val = MHSd->getDef();
1076       return DefInit::get(Val);
1077     }
1078     if (LHSv && MHSv && RHSv) {
1079       std::string Val = RHSv->getName();
1080       if (LHSv->getAsString() == RHSv->getAsString())
1081         Val = MHSv->getName();
1082       return VarInit::get(Val, getType());
1083     }
1084     if (LHSs && MHSs && RHSs) {
1085       std::string Val = RHSs->getValue();
1086 
1087       std::string::size_type found;
1088       std::string::size_type idx = 0;
1089       while (true) {
1090         found = Val.find(LHSs->getValue(), idx);
1091         if (found == std::string::npos)
1092           break;
1093         Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1094         idx = found + MHSs->getValue().size();
1095       }
1096 
1097       return StringInit::get(Val);
1098     }
1099     break;
1100   }
1101 
1102   case FOREACH: {
1103     if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
1104       return Result;
1105     break;
1106   }
1107 
1108   case IF: {
1109     if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
1110                             LHS->convertInitializerTo(IntRecTy::get()))) {
1111       if (LHSi->getValue())
1112         return MHS;
1113       return RHS;
1114     }
1115     break;
1116   }
1117   }
1118 
1119   return const_cast<TernOpInit *>(this);
1120 }
1121 
1122 Init *TernOpInit::resolveReferences(Resolver &R) const {
1123   Init *lhs = LHS->resolveReferences(R);
1124 
1125   if (getOpcode() == IF && lhs != LHS) {
1126     if (IntInit *Value = dyn_cast_or_null<IntInit>(
1127                              lhs->convertInitializerTo(IntRecTy::get()))) {
1128       // Short-circuit
1129       if (Value->getValue())
1130         return MHS->resolveReferences(R);
1131       return RHS->resolveReferences(R);
1132     }
1133   }
1134 
1135   Init *mhs = MHS->resolveReferences(R);
1136   Init *rhs;
1137 
1138   if (getOpcode() == FOREACH) {
1139     ShadowResolver SR(R);
1140     SR.addShadow(lhs);
1141     rhs = RHS->resolveReferences(SR);
1142   } else {
1143     rhs = RHS->resolveReferences(R);
1144   }
1145 
1146   if (LHS != lhs || MHS != mhs || RHS != rhs)
1147     return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
1148         ->Fold(R.getCurrentRecord(), nullptr);
1149   return Fold(R.getCurrentRecord(), nullptr);
1150 }
1151 
1152 std::string TernOpInit::getAsString() const {
1153   std::string Result;
1154   switch (getOpcode()) {
1155   case SUBST: Result = "!subst"; break;
1156   case FOREACH: Result = "!foreach"; break;
1157   case IF: Result = "!if"; break;
1158   }
1159   return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " +
1160          RHS->getAsString() + ")";
1161 }
1162 
1163 static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *A, Init *B,
1164                               Init *Start, Init *List, Init *Expr,
1165                               RecTy *Type) {
1166   ID.AddPointer(Start);
1167   ID.AddPointer(List);
1168   ID.AddPointer(A);
1169   ID.AddPointer(B);
1170   ID.AddPointer(Expr);
1171   ID.AddPointer(Type);
1172 }
1173 
1174 FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,
1175                             Init *Expr, RecTy *Type) {
1176   static FoldingSet<FoldOpInit> ThePool;
1177 
1178   FoldingSetNodeID ID;
1179   ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
1180 
1181   void *IP = nullptr;
1182   if (FoldOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1183     return I;
1184 
1185   FoldOpInit *I = new (Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
1186   ThePool.InsertNode(I, IP);
1187   return I;
1188 }
1189 
1190 void FoldOpInit::Profile(FoldingSetNodeID &ID) const {
1191   ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
1192 }
1193 
1194 Init *FoldOpInit::Fold(Record *CurRec) const {
1195   if (ListInit *LI = dyn_cast<ListInit>(List)) {
1196     Init *Accum = Start;
1197     for (Init *Elt : *LI) {
1198       MapResolver R(CurRec);
1199       R.set(A, Accum);
1200       R.set(B, Elt);
1201       Accum = Expr->resolveReferences(R);
1202     }
1203     return Accum;
1204   }
1205   return const_cast<FoldOpInit *>(this);
1206 }
1207 
1208 Init *FoldOpInit::resolveReferences(Resolver &R) const {
1209   Init *NewStart = Start->resolveReferences(R);
1210   Init *NewList = List->resolveReferences(R);
1211   ShadowResolver SR(R);
1212   SR.addShadow(A);
1213   SR.addShadow(B);
1214   Init *NewExpr = Expr->resolveReferences(SR);
1215 
1216   if (Start == NewStart && List == NewList && Expr == NewExpr)
1217     return const_cast<FoldOpInit *>(this);
1218 
1219   return get(NewStart, NewList, A, B, NewExpr, getType())
1220       ->Fold(R.getCurrentRecord());
1221 }
1222 
1223 Init *FoldOpInit::getBit(unsigned Bit) const {
1224   return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);
1225 }
1226 
1227 std::string FoldOpInit::getAsString() const {
1228   return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
1229           ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
1230           ", " + Expr->getAsString() + ")")
1231       .str();
1232 }
1233 
1234 RecTy *TypedInit::getFieldType(StringInit *FieldName) const {
1235   if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {
1236     for (Record *Rec : RecordType->getClasses()) {
1237       if (RecordVal *Field = Rec->getValue(FieldName))
1238         return Field->getType();
1239     }
1240   }
1241   return nullptr;
1242 }
1243 
1244 Init *
1245 TypedInit::convertInitializerTo(RecTy *Ty) const {
1246   if (getType() == Ty || getType()->typeIsA(Ty))
1247     return const_cast<TypedInit *>(this);
1248 
1249   if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
1250       cast<BitsRecTy>(Ty)->getNumBits() == 1)
1251     return BitsInit::get({const_cast<TypedInit *>(this)});
1252 
1253   return nullptr;
1254 }
1255 
1256 Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
1257   BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1258   if (!T) return nullptr;  // Cannot subscript a non-bits variable.
1259   unsigned NumBits = T->getNumBits();
1260 
1261   SmallVector<Init *, 16> NewBits;
1262   NewBits.reserve(Bits.size());
1263   for (unsigned Bit : Bits) {
1264     if (Bit >= NumBits)
1265       return nullptr;
1266 
1267     NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));
1268   }
1269   return BitsInit::get(NewBits);
1270 }
1271 
1272 Init *TypedInit::getCastTo(RecTy *Ty) const {
1273   // Handle the common case quickly
1274   if (getType() == Ty || getType()->typeIsA(Ty))
1275     return const_cast<TypedInit *>(this);
1276 
1277   if (Init *Converted = convertInitializerTo(Ty)) {
1278     assert(!isa<TypedInit>(Converted) ||
1279            cast<TypedInit>(Converted)->getType()->typeIsA(Ty));
1280     return Converted;
1281   }
1282 
1283   if (!getType()->typeIsConvertibleTo(Ty))
1284     return nullptr;
1285 
1286   return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)
1287              ->Fold(nullptr, nullptr);
1288 }
1289 
1290 Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
1291   ListRecTy *T = dyn_cast<ListRecTy>(getType());
1292   if (!T) return nullptr;  // Cannot subscript a non-list variable.
1293 
1294   if (Elements.size() == 1)
1295     return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1296 
1297   SmallVector<Init*, 8> ListInits;
1298   ListInits.reserve(Elements.size());
1299   for (unsigned Element : Elements)
1300     ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1301                                                 Element));
1302   return ListInit::get(ListInits, T->getElementType());
1303 }
1304 
1305 
1306 VarInit *VarInit::get(StringRef VN, RecTy *T) {
1307   Init *Value = StringInit::get(VN);
1308   return VarInit::get(Value, T);
1309 }
1310 
1311 VarInit *VarInit::get(Init *VN, RecTy *T) {
1312   using Key = std::pair<RecTy *, Init *>;
1313   static DenseMap<Key, VarInit*> ThePool;
1314 
1315   Key TheKey(std::make_pair(T, VN));
1316 
1317   VarInit *&I = ThePool[TheKey];
1318   if (!I)
1319     I = new(Allocator) VarInit(VN, T);
1320   return I;
1321 }
1322 
1323 StringRef VarInit::getName() const {
1324   StringInit *NameString = cast<StringInit>(getNameInit());
1325   return NameString->getValue();
1326 }
1327 
1328 Init *VarInit::getBit(unsigned Bit) const {
1329   if (getType() == BitRecTy::get())
1330     return const_cast<VarInit*>(this);
1331   return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1332 }
1333 
1334 Init *VarInit::resolveReferences(Resolver &R) const {
1335   if (Init *Val = R.resolve(VarName))
1336     return Val;
1337   return const_cast<VarInit *>(this);
1338 }
1339 
1340 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1341   using Key = std::pair<TypedInit *, unsigned>;
1342   static DenseMap<Key, VarBitInit*> ThePool;
1343 
1344   Key TheKey(std::make_pair(T, B));
1345 
1346   VarBitInit *&I = ThePool[TheKey];
1347   if (!I)
1348     I = new(Allocator) VarBitInit(T, B);
1349   return I;
1350 }
1351 
1352 std::string VarBitInit::getAsString() const {
1353   return TI->getAsString() + "{" + utostr(Bit) + "}";
1354 }
1355 
1356 Init *VarBitInit::resolveReferences(Resolver &R) const {
1357   Init *I = TI->resolveReferences(R);
1358   if (TI != I)
1359     return I->getBit(getBitNum());
1360 
1361   return const_cast<VarBitInit*>(this);
1362 }
1363 
1364 VarListElementInit *VarListElementInit::get(TypedInit *T,
1365                                             unsigned E) {
1366   using Key = std::pair<TypedInit *, unsigned>;
1367   static DenseMap<Key, VarListElementInit*> ThePool;
1368 
1369   Key TheKey(std::make_pair(T, E));
1370 
1371   VarListElementInit *&I = ThePool[TheKey];
1372   if (!I) I = new(Allocator) VarListElementInit(T, E);
1373   return I;
1374 }
1375 
1376 std::string VarListElementInit::getAsString() const {
1377   return TI->getAsString() + "[" + utostr(Element) + "]";
1378 }
1379 
1380 Init *VarListElementInit::resolveReferences(Resolver &R) const {
1381   Init *NewTI = TI->resolveReferences(R);
1382   if (ListInit *List = dyn_cast<ListInit>(NewTI)) {
1383     // Leave out-of-bounds array references as-is. This can happen without
1384     // being an error, e.g. in the untaken "branch" of an !if expression.
1385     if (getElementNum() < List->size())
1386       return List->getElement(getElementNum());
1387   }
1388   if (NewTI != TI && isa<TypedInit>(NewTI))
1389     return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum());
1390   return const_cast<VarListElementInit *>(this);
1391 }
1392 
1393 Init *VarListElementInit::getBit(unsigned Bit) const {
1394   if (getType() == BitRecTy::get())
1395     return const_cast<VarListElementInit*>(this);
1396   return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1397 }
1398 
1399 static RecordRecTy *makeDefInitType(Record *Rec) {
1400   SmallVector<Record *, 4> SuperClasses;
1401   Rec->getDirectSuperClasses(SuperClasses);
1402   return RecordRecTy::get(SuperClasses);
1403 }
1404 
1405 DefInit::DefInit(Record *D)
1406     : TypedInit(IK_DefInit, makeDefInitType(D)), Def(D) {}
1407 
1408 DefInit *DefInit::get(Record *R) {
1409   return R->getDefInit();
1410 }
1411 
1412 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1413   if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1414     if (getType()->typeIsConvertibleTo(RRT))
1415       return const_cast<DefInit *>(this);
1416   return nullptr;
1417 }
1418 
1419 RecTy *DefInit::getFieldType(StringInit *FieldName) const {
1420   if (const RecordVal *RV = Def->getValue(FieldName))
1421     return RV->getType();
1422   return nullptr;
1423 }
1424 
1425 std::string DefInit::getAsString() const {
1426   return Def->getName();
1427 }
1428 
1429 static void ProfileVarDefInit(FoldingSetNodeID &ID,
1430                               Record *Class,
1431                               ArrayRef<Init *> Args) {
1432   ID.AddInteger(Args.size());
1433   ID.AddPointer(Class);
1434 
1435   for (Init *I : Args)
1436     ID.AddPointer(I);
1437 }
1438 
1439 VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) {
1440   static FoldingSet<VarDefInit> ThePool;
1441 
1442   FoldingSetNodeID ID;
1443   ProfileVarDefInit(ID, Class, Args);
1444 
1445   void *IP = nullptr;
1446   if (VarDefInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1447     return I;
1448 
1449   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()),
1450                                  alignof(VarDefInit));
1451   VarDefInit *I = new(Mem) VarDefInit(Class, Args.size());
1452   std::uninitialized_copy(Args.begin(), Args.end(),
1453                           I->getTrailingObjects<Init *>());
1454   ThePool.InsertNode(I, IP);
1455   return I;
1456 }
1457 
1458 void VarDefInit::Profile(FoldingSetNodeID &ID) const {
1459   ProfileVarDefInit(ID, Class, args());
1460 }
1461 
1462 DefInit *VarDefInit::instantiate() {
1463   if (!Def) {
1464     RecordKeeper &Records = Class->getRecords();
1465     auto NewRecOwner = make_unique<Record>(Records.getNewAnonymousName(),
1466                                            Class->getLoc(), Records,
1467                                            /*IsAnonymous=*/true);
1468     Record *NewRec = NewRecOwner.get();
1469 
1470     // Copy values from class to instance
1471     for (const RecordVal &Val : Class->getValues()) {
1472       if (Val.getName() != "NAME")
1473         NewRec->addValue(Val);
1474     }
1475 
1476     // Substitute and resolve template arguments
1477     ArrayRef<Init *> TArgs = Class->getTemplateArgs();
1478     MapResolver R(NewRec);
1479 
1480     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1481       if (i < args_size())
1482         R.set(TArgs[i], getArg(i));
1483       else
1484         R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue());
1485 
1486       NewRec->removeValue(TArgs[i]);
1487     }
1488 
1489     NewRec->resolveReferences(R);
1490 
1491     // Add superclasses.
1492     ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();
1493     for (const auto &SCPair : SCs)
1494       NewRec->addSuperClass(SCPair.first, SCPair.second);
1495 
1496     NewRec->addSuperClass(Class,
1497                           SMRange(Class->getLoc().back(),
1498                                   Class->getLoc().back()));
1499 
1500     // Resolve internal references and store in record keeper
1501     NewRec->resolveReferences();
1502     Records.addDef(std::move(NewRecOwner));
1503 
1504     Def = DefInit::get(NewRec);
1505   }
1506 
1507   return Def;
1508 }
1509 
1510 Init *VarDefInit::resolveReferences(Resolver &R) const {
1511   TrackUnresolvedResolver UR(&R);
1512   bool Changed = false;
1513   SmallVector<Init *, 8> NewArgs;
1514   NewArgs.reserve(args_size());
1515 
1516   for (Init *Arg : args()) {
1517     Init *NewArg = Arg->resolveReferences(UR);
1518     NewArgs.push_back(NewArg);
1519     Changed |= NewArg != Arg;
1520   }
1521 
1522   if (Changed) {
1523     auto New = VarDefInit::get(Class, NewArgs);
1524     if (!UR.foundUnresolved())
1525       return New->instantiate();
1526     return New;
1527   }
1528   return const_cast<VarDefInit *>(this);
1529 }
1530 
1531 Init *VarDefInit::Fold() const {
1532   if (Def)
1533     return Def;
1534 
1535   TrackUnresolvedResolver R;
1536   for (Init *Arg : args())
1537     Arg->resolveReferences(R);
1538 
1539   if (!R.foundUnresolved())
1540     return const_cast<VarDefInit *>(this)->instantiate();
1541   return const_cast<VarDefInit *>(this);
1542 }
1543 
1544 std::string VarDefInit::getAsString() const {
1545   std::string Result = Class->getNameInitAsString() + "<";
1546   const char *sep = "";
1547   for (Init *Arg : args()) {
1548     Result += sep;
1549     sep = ", ";
1550     Result += Arg->getAsString();
1551   }
1552   return Result + ">";
1553 }
1554 
1555 FieldInit *FieldInit::get(Init *R, StringInit *FN) {
1556   using Key = std::pair<Init *, StringInit *>;
1557   static DenseMap<Key, FieldInit*> ThePool;
1558 
1559   Key TheKey(std::make_pair(R, FN));
1560 
1561   FieldInit *&I = ThePool[TheKey];
1562   if (!I) I = new(Allocator) FieldInit(R, FN);
1563   return I;
1564 }
1565 
1566 Init *FieldInit::getBit(unsigned Bit) const {
1567   if (getType() == BitRecTy::get())
1568     return const_cast<FieldInit*>(this);
1569   return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1570 }
1571 
1572 Init *FieldInit::resolveReferences(Resolver &R) const {
1573   Init *NewRec = Rec->resolveReferences(R);
1574 
1575   if (DefInit *DI = dyn_cast<DefInit>(NewRec)) {
1576     Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue();
1577     Init *BVR = FieldVal->resolveReferences(R);
1578     if (BVR->isComplete())
1579       return BVR;
1580   }
1581 
1582   if (NewRec != Rec)
1583     return FieldInit::get(NewRec, FieldName);
1584   return const_cast<FieldInit *>(this);
1585 }
1586 
1587 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,
1588                            ArrayRef<Init *> ArgRange,
1589                            ArrayRef<StringInit *> NameRange) {
1590   ID.AddPointer(V);
1591   ID.AddPointer(VN);
1592 
1593   ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1594   ArrayRef<StringInit *>::iterator Name = NameRange.begin();
1595   while (Arg != ArgRange.end()) {
1596     assert(Name != NameRange.end() && "Arg name underflow!");
1597     ID.AddPointer(*Arg++);
1598     ID.AddPointer(*Name++);
1599   }
1600   assert(Name == NameRange.end() && "Arg name overflow!");
1601 }
1602 
1603 DagInit *
1604 DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1605              ArrayRef<StringInit *> NameRange) {
1606   static FoldingSet<DagInit> ThePool;
1607 
1608   FoldingSetNodeID ID;
1609   ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1610 
1611   void *IP = nullptr;
1612   if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1613     return I;
1614 
1615   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()), alignof(BitsInit));
1616   DagInit *I = new(Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());
1617   std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),
1618                           I->getTrailingObjects<Init *>());
1619   std::uninitialized_copy(NameRange.begin(), NameRange.end(),
1620                           I->getTrailingObjects<StringInit *>());
1621   ThePool.InsertNode(I, IP);
1622   return I;
1623 }
1624 
1625 DagInit *
1626 DagInit::get(Init *V, StringInit *VN,
1627              ArrayRef<std::pair<Init*, StringInit*>> args) {
1628   SmallVector<Init *, 8> Args;
1629   SmallVector<StringInit *, 8> Names;
1630 
1631   for (const auto &Arg : args) {
1632     Args.push_back(Arg.first);
1633     Names.push_back(Arg.second);
1634   }
1635 
1636   return DagInit::get(V, VN, Args, Names);
1637 }
1638 
1639 void DagInit::Profile(FoldingSetNodeID &ID) const {
1640   ProfileDagInit(ID, Val, ValName, makeArrayRef(getTrailingObjects<Init *>(), NumArgs), makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));
1641 }
1642 
1643 Init *DagInit::resolveReferences(Resolver &R) const {
1644   SmallVector<Init*, 8> NewArgs;
1645   NewArgs.reserve(arg_size());
1646   bool ArgsChanged = false;
1647   for (const Init *Arg : getArgs()) {
1648     Init *NewArg = Arg->resolveReferences(R);
1649     NewArgs.push_back(NewArg);
1650     ArgsChanged |= NewArg != Arg;
1651   }
1652 
1653   Init *Op = Val->resolveReferences(R);
1654   if (Op != Val || ArgsChanged)
1655     return DagInit::get(Op, ValName, NewArgs, getArgNames());
1656 
1657   return const_cast<DagInit *>(this);
1658 }
1659 
1660 bool DagInit::isConcrete() const {
1661   if (!Val->isConcrete())
1662     return false;
1663   for (const Init *Elt : getArgs()) {
1664     if (!Elt->isConcrete())
1665       return false;
1666   }
1667   return true;
1668 }
1669 
1670 std::string DagInit::getAsString() const {
1671   std::string Result = "(" + Val->getAsString();
1672   if (ValName)
1673     Result += ":" + ValName->getAsUnquotedString();
1674   if (!arg_empty()) {
1675     Result += " " + getArg(0)->getAsString();
1676     if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();
1677     for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {
1678       Result += ", " + getArg(i)->getAsString();
1679       if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();
1680     }
1681   }
1682   return Result + ")";
1683 }
1684 
1685 //===----------------------------------------------------------------------===//
1686 //    Other implementations
1687 //===----------------------------------------------------------------------===//
1688 
1689 RecordVal::RecordVal(Init *N, RecTy *T, bool P)
1690   : Name(N), TyAndPrefix(T, P) {
1691   setValue(UnsetInit::get());
1692   assert(Value && "Cannot create unset value for current type!");
1693 }
1694 
1695 StringRef RecordVal::getName() const {
1696   return cast<StringInit>(getNameInit())->getValue();
1697 }
1698 
1699 bool RecordVal::setValue(Init *V) {
1700   if (V) {
1701     Value = V->getCastTo(getType());
1702     if (Value) {
1703       assert(!isa<TypedInit>(Value) ||
1704              cast<TypedInit>(Value)->getType()->typeIsA(getType()));
1705       if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
1706         if (!isa<BitsInit>(Value)) {
1707           SmallVector<Init *, 64> Bits;
1708           Bits.reserve(BTy->getNumBits());
1709           for (unsigned i = 0, e = BTy->getNumBits(); i < e; ++i)
1710             Bits.push_back(Value->getBit(i));
1711           Value = BitsInit::get(Bits);
1712         }
1713       }
1714     }
1715     return Value == nullptr;
1716   }
1717   Value = nullptr;
1718   return false;
1719 }
1720 
1721 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1722 LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }
1723 #endif
1724 
1725 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1726   if (getPrefix()) OS << "field ";
1727   OS << *getType() << " " << getNameInitAsString();
1728 
1729   if (getValue())
1730     OS << " = " << *getValue();
1731 
1732   if (PrintSem) OS << ";\n";
1733 }
1734 
1735 unsigned Record::LastID = 0;
1736 
1737 void Record::init() {
1738   checkName();
1739 
1740   // Every record potentially has a def at the top.  This value is
1741   // replaced with the top-level def name at instantiation time.
1742   addValue(RecordVal(StringInit::get("NAME"), StringRecTy::get(), false));
1743 }
1744 
1745 void Record::checkName() {
1746   // Ensure the record name has string type.
1747   const TypedInit *TypedName = cast<const TypedInit>(Name);
1748   if (!isa<StringRecTy>(TypedName->getType()))
1749     PrintFatalError(getLoc(), "Record name is not a string!");
1750 }
1751 
1752 DefInit *Record::getDefInit() {
1753   if (!TheInit)
1754     TheInit = new(Allocator) DefInit(this);
1755   return TheInit;
1756 }
1757 
1758 void Record::setName(Init *NewName) {
1759   Name = NewName;
1760   checkName();
1761   // DO NOT resolve record values to the name at this point because
1762   // there might be default values for arguments of this def.  Those
1763   // arguments might not have been resolved yet so we don't want to
1764   // prematurely assume values for those arguments were not passed to
1765   // this def.
1766   //
1767   // Nonetheless, it may be that some of this Record's values
1768   // reference the record name.  Indeed, the reason for having the
1769   // record name be an Init is to provide this flexibility.  The extra
1770   // resolve steps after completely instantiating defs takes care of
1771   // this.  See TGParser::ParseDef and TGParser::ParseDefm.
1772 }
1773 
1774 void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {
1775   ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
1776   while (!SCs.empty()) {
1777     // Superclasses are in reverse preorder, so 'back' is a direct superclass,
1778     // and its transitive superclasses are directly preceding it.
1779     Record *SC = SCs.back().first;
1780     SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
1781     Classes.push_back(SC);
1782   }
1783 }
1784 
1785 void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {
1786   for (RecordVal &Value : Values) {
1787     if (SkipVal == &Value) // Skip resolve the same field as the given one
1788       continue;
1789     if (Init *V = Value.getValue()) {
1790       Init *VR = V->resolveReferences(R);
1791       if (Value.setValue(VR))
1792         PrintFatalError(getLoc(), "Invalid value is found when setting '" +
1793                                       Value.getNameInitAsString() +
1794                                       "' after resolving references: " +
1795                                       VR->getAsUnquotedString() + "\n");
1796     }
1797   }
1798   Init *OldName = getNameInit();
1799   Init *NewName = Name->resolveReferences(R);
1800   if (NewName != OldName) {
1801     // Re-register with RecordKeeper.
1802     setName(NewName);
1803   }
1804 }
1805 
1806 void Record::resolveReferences() {
1807   RecordResolver R(*this);
1808   resolveReferences(R);
1809 }
1810 
1811 void Record::resolveReferencesTo(const RecordVal *RV) {
1812   RecordValResolver R(*this, RV);
1813   resolveReferences(R, RV);
1814 }
1815 
1816 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1817 LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }
1818 #endif
1819 
1820 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1821   OS << R.getNameInitAsString();
1822 
1823   ArrayRef<Init *> TArgs = R.getTemplateArgs();
1824   if (!TArgs.empty()) {
1825     OS << "<";
1826     bool NeedComma = false;
1827     for (const Init *TA : TArgs) {
1828       if (NeedComma) OS << ", ";
1829       NeedComma = true;
1830       const RecordVal *RV = R.getValue(TA);
1831       assert(RV && "Template argument record not found??");
1832       RV->print(OS, false);
1833     }
1834     OS << ">";
1835   }
1836 
1837   OS << " {";
1838   ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
1839   if (!SC.empty()) {
1840     OS << "\t//";
1841     for (const auto &SuperPair : SC)
1842       OS << " " << SuperPair.first->getNameInitAsString();
1843   }
1844   OS << "\n";
1845 
1846   for (const RecordVal &Val : R.getValues())
1847     if (Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
1848       OS << Val;
1849   for (const RecordVal &Val : R.getValues())
1850     if (!Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
1851       OS << Val;
1852 
1853   return OS << "}\n";
1854 }
1855 
1856 Init *Record::getValueInit(StringRef FieldName) const {
1857   const RecordVal *R = getValue(FieldName);
1858   if (!R || !R->getValue())
1859     PrintFatalError(getLoc(), "Record `" + getName() +
1860       "' does not have a field named `" + FieldName + "'!\n");
1861   return R->getValue();
1862 }
1863 
1864 StringRef Record::getValueAsString(StringRef FieldName) const {
1865   const RecordVal *R = getValue(FieldName);
1866   if (!R || !R->getValue())
1867     PrintFatalError(getLoc(), "Record `" + getName() +
1868       "' does not have a field named `" + FieldName + "'!\n");
1869 
1870   if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1871     return SI->getValue();
1872   if (CodeInit *CI = dyn_cast<CodeInit>(R->getValue()))
1873     return CI->getValue();
1874 
1875   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1876     FieldName + "' does not have a string initializer!");
1877 }
1878 
1879 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1880   const RecordVal *R = getValue(FieldName);
1881   if (!R || !R->getValue())
1882     PrintFatalError(getLoc(), "Record `" + getName() +
1883       "' does not have a field named `" + FieldName + "'!\n");
1884 
1885   if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1886     return BI;
1887   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1888     FieldName + "' does not have a BitsInit initializer!");
1889 }
1890 
1891 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1892   const RecordVal *R = getValue(FieldName);
1893   if (!R || !R->getValue())
1894     PrintFatalError(getLoc(), "Record `" + getName() +
1895       "' does not have a field named `" + FieldName + "'!\n");
1896 
1897   if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1898     return LI;
1899   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1900     FieldName + "' does not have a list initializer!");
1901 }
1902 
1903 std::vector<Record*>
1904 Record::getValueAsListOfDefs(StringRef FieldName) const {
1905   ListInit *List = getValueAsListInit(FieldName);
1906   std::vector<Record*> Defs;
1907   for (Init *I : List->getValues()) {
1908     if (DefInit *DI = dyn_cast<DefInit>(I))
1909       Defs.push_back(DI->getDef());
1910     else
1911       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1912         FieldName + "' list is not entirely DefInit!");
1913   }
1914   return Defs;
1915 }
1916 
1917 int64_t Record::getValueAsInt(StringRef FieldName) const {
1918   const RecordVal *R = getValue(FieldName);
1919   if (!R || !R->getValue())
1920     PrintFatalError(getLoc(), "Record `" + getName() +
1921       "' does not have a field named `" + FieldName + "'!\n");
1922 
1923   if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1924     return II->getValue();
1925   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1926     FieldName + "' does not have an int initializer!");
1927 }
1928 
1929 std::vector<int64_t>
1930 Record::getValueAsListOfInts(StringRef FieldName) const {
1931   ListInit *List = getValueAsListInit(FieldName);
1932   std::vector<int64_t> Ints;
1933   for (Init *I : List->getValues()) {
1934     if (IntInit *II = dyn_cast<IntInit>(I))
1935       Ints.push_back(II->getValue());
1936     else
1937       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1938         FieldName + "' does not have a list of ints initializer!");
1939   }
1940   return Ints;
1941 }
1942 
1943 std::vector<StringRef>
1944 Record::getValueAsListOfStrings(StringRef FieldName) const {
1945   ListInit *List = getValueAsListInit(FieldName);
1946   std::vector<StringRef> Strings;
1947   for (Init *I : List->getValues()) {
1948     if (StringInit *SI = dyn_cast<StringInit>(I))
1949       Strings.push_back(SI->getValue());
1950     else
1951       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1952         FieldName + "' does not have a list of strings initializer!");
1953   }
1954   return Strings;
1955 }
1956 
1957 Record *Record::getValueAsDef(StringRef FieldName) const {
1958   const RecordVal *R = getValue(FieldName);
1959   if (!R || !R->getValue())
1960     PrintFatalError(getLoc(), "Record `" + getName() +
1961       "' does not have a field named `" + FieldName + "'!\n");
1962 
1963   if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1964     return DI->getDef();
1965   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1966     FieldName + "' does not have a def initializer!");
1967 }
1968 
1969 bool Record::getValueAsBit(StringRef FieldName) const {
1970   const RecordVal *R = getValue(FieldName);
1971   if (!R || !R->getValue())
1972     PrintFatalError(getLoc(), "Record `" + getName() +
1973       "' does not have a field named `" + FieldName + "'!\n");
1974 
1975   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1976     return BI->getValue();
1977   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1978     FieldName + "' does not have a bit initializer!");
1979 }
1980 
1981 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1982   const RecordVal *R = getValue(FieldName);
1983   if (!R || !R->getValue())
1984     PrintFatalError(getLoc(), "Record `" + getName() +
1985       "' does not have a field named `" + FieldName.str() + "'!\n");
1986 
1987   if (isa<UnsetInit>(R->getValue())) {
1988     Unset = true;
1989     return false;
1990   }
1991   Unset = false;
1992   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1993     return BI->getValue();
1994   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1995     FieldName + "' does not have a bit initializer!");
1996 }
1997 
1998 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1999   const RecordVal *R = getValue(FieldName);
2000   if (!R || !R->getValue())
2001     PrintFatalError(getLoc(), "Record `" + getName() +
2002       "' does not have a field named `" + FieldName + "'!\n");
2003 
2004   if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
2005     return DI;
2006   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2007     FieldName + "' does not have a dag initializer!");
2008 }
2009 
2010 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2011 LLVM_DUMP_METHOD void MultiClass::dump() const {
2012   errs() << "Record:\n";
2013   Rec.dump();
2014 
2015   errs() << "Defs:\n";
2016   for (const auto &Proto : DefPrototypes)
2017     Proto->dump();
2018 }
2019 
2020 LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }
2021 #endif
2022 
2023 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2024   OS << "------------- Classes -----------------\n";
2025   for (const auto &C : RK.getClasses())
2026     OS << "class " << *C.second;
2027 
2028   OS << "------------- Defs -----------------\n";
2029   for (const auto &D : RK.getDefs())
2030     OS << "def " << *D.second;
2031   return OS;
2032 }
2033 
2034 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
2035 /// an identifier.
2036 Init *RecordKeeper::getNewAnonymousName() {
2037   return StringInit::get("anonymous_" + utostr(AnonCounter++));
2038 }
2039 
2040 std::vector<Record *>
2041 RecordKeeper::getAllDerivedDefinitions(StringRef ClassName) const {
2042   Record *Class = getClass(ClassName);
2043   if (!Class)
2044     PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
2045 
2046   std::vector<Record*> Defs;
2047   for (const auto &D : getDefs())
2048     if (D.second->isSubClassOf(Class))
2049       Defs.push_back(D.second.get());
2050 
2051   return Defs;
2052 }
2053 
2054 static Init *GetStrConcat(Init *I0, Init *I1) {
2055   // Shortcut for the common case of concatenating two strings.
2056   if (const StringInit *I0s = dyn_cast<StringInit>(I0))
2057     if (const StringInit *I1s = dyn_cast<StringInit>(I1))
2058       return ConcatStringInits(I0s, I1s);
2059   return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1, StringRecTy::get());
2060 }
2061 
2062 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2063                         Init *Name, StringRef Scoper) {
2064   Init *NewName = GetStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
2065   NewName = GetStrConcat(NewName, Name);
2066   if (CurMultiClass && Scoper != "::") {
2067     Init *Prefix = GetStrConcat(CurMultiClass->Rec.getNameInit(),
2068                                 StringInit::get("::"));
2069     NewName = GetStrConcat(Prefix, NewName);
2070   }
2071 
2072   if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
2073     NewName = BinOp->Fold(&CurRec, CurMultiClass);
2074   return NewName;
2075 }
2076 
2077 Init *MapResolver::resolve(Init *VarName) {
2078   auto It = Map.find(VarName);
2079   if (It == Map.end())
2080     return nullptr;
2081 
2082   Init *I = It->second.V;
2083 
2084   if (!It->second.Resolved && Map.size() > 1) {
2085     // Resolve mutual references among the mapped variables, but prevent
2086     // infinite recursion.
2087     Map.erase(It);
2088     I = I->resolveReferences(*this);
2089     Map[VarName] = {I, true};
2090   }
2091 
2092   return I;
2093 }
2094 
2095 Init *RecordResolver::resolve(Init *VarName) {
2096   Init *Val = Cache.lookup(VarName);
2097   if (Val)
2098     return Val;
2099 
2100   for (Init *S : Stack) {
2101     if (S == VarName)
2102       return nullptr; // prevent infinite recursion
2103   }
2104 
2105   if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
2106     if (!isa<UnsetInit>(RV->getValue())) {
2107       Val = RV->getValue();
2108       Stack.push_back(VarName);
2109       Val = Val->resolveReferences(*this);
2110       Stack.pop_back();
2111     }
2112   }
2113 
2114   Cache[VarName] = Val;
2115   return Val;
2116 }
2117 
2118 Init *TrackUnresolvedResolver::resolve(Init *VarName) {
2119   Init *I = nullptr;
2120 
2121   if (R) {
2122     I = R->resolve(VarName);
2123     if (I && !FoundUnresolved) {
2124       // Do not recurse into the resolved initializer, as that would change
2125       // the behavior of the resolver we're delegating, but do check to see
2126       // if there are unresolved variables remaining.
2127       TrackUnresolvedResolver Sub;
2128       I->resolveReferences(Sub);
2129       FoundUnresolved |= Sub.FoundUnresolved;
2130     }
2131   }
2132 
2133   if (!I)
2134     FoundUnresolved = true;
2135   return I;
2136 }
2137