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