]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/include/llvm/TableGen/Record.h
Adjust ENA driver files to latest ena-com changes
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / include / llvm / TableGen / Record.h
1 //===- llvm/TableGen/Record.h - Classes for Table Records -------*- C++ -*-===//
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 // This file defines the main TableGen data structures, including the TableGen
10 // types, values, and high-level data structures.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_TABLEGEN_RECORD_H
15 #define LLVM_TABLEGEN_RECORD_H
16
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/PointerIntPair.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/SMLoc.h"
27 #include "llvm/Support/TrailingObjects.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstddef>
32 #include <cstdint>
33 #include <map>
34 #include <memory>
35 #include <string>
36 #include <utility>
37 #include <vector>
38
39 namespace llvm {
40
41 class ListRecTy;
42 struct MultiClass;
43 class Record;
44 class RecordKeeper;
45 class RecordVal;
46 class Resolver;
47 class StringInit;
48 class TypedInit;
49
50 //===----------------------------------------------------------------------===//
51 //  Type Classes
52 //===----------------------------------------------------------------------===//
53
54 class RecTy {
55 public:
56   /// Subclass discriminator (for dyn_cast<> et al.)
57   enum RecTyKind {
58     BitRecTyKind,
59     BitsRecTyKind,
60     CodeRecTyKind,
61     IntRecTyKind,
62     StringRecTyKind,
63     ListRecTyKind,
64     DagRecTyKind,
65     RecordRecTyKind
66   };
67
68 private:
69   RecTyKind Kind;
70   ListRecTy *ListTy = nullptr;
71
72 public:
73   RecTy(RecTyKind K) : Kind(K) {}
74   virtual ~RecTy() = default;
75
76   RecTyKind getRecTyKind() const { return Kind; }
77
78   virtual std::string getAsString() const = 0;
79   void print(raw_ostream &OS) const { OS << getAsString(); }
80   void dump() const;
81
82   /// Return true if all values of 'this' type can be converted to the specified
83   /// type.
84   virtual bool typeIsConvertibleTo(const RecTy *RHS) const;
85
86   /// Return true if 'this' type is equal to or a subtype of RHS. For example,
87   /// a bit set is not an int, but they are convertible.
88   virtual bool typeIsA(const RecTy *RHS) const;
89
90   /// Returns the type representing list<this>.
91   ListRecTy *getListTy();
92 };
93
94 inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) {
95   Ty.print(OS);
96   return OS;
97 }
98
99 /// 'bit' - Represent a single bit
100 class BitRecTy : public RecTy {
101   static BitRecTy Shared;
102
103   BitRecTy() : RecTy(BitRecTyKind) {}
104
105 public:
106   static bool classof(const RecTy *RT) {
107     return RT->getRecTyKind() == BitRecTyKind;
108   }
109
110   static BitRecTy *get() { return &Shared; }
111
112   std::string getAsString() const override { return "bit"; }
113
114   bool typeIsConvertibleTo(const RecTy *RHS) const override;
115 };
116
117 /// 'bits<n>' - Represent a fixed number of bits
118 class BitsRecTy : public RecTy {
119   unsigned Size;
120
121   explicit BitsRecTy(unsigned Sz) : RecTy(BitsRecTyKind), Size(Sz) {}
122
123 public:
124   static bool classof(const RecTy *RT) {
125     return RT->getRecTyKind() == BitsRecTyKind;
126   }
127
128   static BitsRecTy *get(unsigned Sz);
129
130   unsigned getNumBits() const { return Size; }
131
132   std::string getAsString() const override;
133
134   bool typeIsConvertibleTo(const RecTy *RHS) const override;
135
136   bool typeIsA(const RecTy *RHS) const override;
137 };
138
139 /// 'code' - Represent a code fragment
140 class CodeRecTy : public RecTy {
141   static CodeRecTy Shared;
142
143   CodeRecTy() : RecTy(CodeRecTyKind) {}
144
145 public:
146   static bool classof(const RecTy *RT) {
147     return RT->getRecTyKind() == CodeRecTyKind;
148   }
149
150   static CodeRecTy *get() { return &Shared; }
151
152   std::string getAsString() const override { return "code"; }
153
154   bool typeIsConvertibleTo(const RecTy *RHS) const override;
155 };
156
157 /// 'int' - Represent an integer value of no particular size
158 class IntRecTy : public RecTy {
159   static IntRecTy Shared;
160
161   IntRecTy() : RecTy(IntRecTyKind) {}
162
163 public:
164   static bool classof(const RecTy *RT) {
165     return RT->getRecTyKind() == IntRecTyKind;
166   }
167
168   static IntRecTy *get() { return &Shared; }
169
170   std::string getAsString() const override { return "int"; }
171
172   bool typeIsConvertibleTo(const RecTy *RHS) const override;
173 };
174
175 /// 'string' - Represent an string value
176 class StringRecTy : public RecTy {
177   static StringRecTy Shared;
178
179   StringRecTy() : RecTy(StringRecTyKind) {}
180
181 public:
182   static bool classof(const RecTy *RT) {
183     return RT->getRecTyKind() == StringRecTyKind;
184   }
185
186   static StringRecTy *get() { return &Shared; }
187
188   std::string getAsString() const override;
189
190   bool typeIsConvertibleTo(const RecTy *RHS) const override;
191 };
192
193 /// 'list<Ty>' - Represent a list of values, all of which must be of
194 /// the specified type.
195 class ListRecTy : public RecTy {
196   friend ListRecTy *RecTy::getListTy();
197
198   RecTy *Ty;
199
200   explicit ListRecTy(RecTy *T) : RecTy(ListRecTyKind), Ty(T) {}
201
202 public:
203   static bool classof(const RecTy *RT) {
204     return RT->getRecTyKind() == ListRecTyKind;
205   }
206
207   static ListRecTy *get(RecTy *T) { return T->getListTy(); }
208   RecTy *getElementType() const { return Ty; }
209
210   std::string getAsString() const override;
211
212   bool typeIsConvertibleTo(const RecTy *RHS) const override;
213
214   bool typeIsA(const RecTy *RHS) const override;
215 };
216
217 /// 'dag' - Represent a dag fragment
218 class DagRecTy : public RecTy {
219   static DagRecTy Shared;
220
221   DagRecTy() : RecTy(DagRecTyKind) {}
222
223 public:
224   static bool classof(const RecTy *RT) {
225     return RT->getRecTyKind() == DagRecTyKind;
226   }
227
228   static DagRecTy *get() { return &Shared; }
229
230   std::string getAsString() const override;
231 };
232
233 /// '[classname]' - Type of record values that have zero or more superclasses.
234 ///
235 /// The list of superclasses is non-redundant, i.e. only contains classes that
236 /// are not the superclass of some other listed class.
237 class RecordRecTy final : public RecTy, public FoldingSetNode,
238                           public TrailingObjects<RecordRecTy, Record *> {
239   friend class Record;
240
241   unsigned NumClasses;
242
243   explicit RecordRecTy(unsigned Num)
244       : RecTy(RecordRecTyKind), NumClasses(Num) {}
245
246 public:
247   RecordRecTy(const RecordRecTy &) = delete;
248   RecordRecTy &operator=(const RecordRecTy &) = delete;
249
250   // Do not use sized deallocation due to trailing objects.
251   void operator delete(void *p) { ::operator delete(p); }
252
253   static bool classof(const RecTy *RT) {
254     return RT->getRecTyKind() == RecordRecTyKind;
255   }
256
257   /// Get the record type with the given non-redundant list of superclasses.
258   static RecordRecTy *get(ArrayRef<Record *> Classes);
259
260   void Profile(FoldingSetNodeID &ID) const;
261
262   ArrayRef<Record *> getClasses() const {
263     return makeArrayRef(getTrailingObjects<Record *>(), NumClasses);
264   }
265
266   using const_record_iterator = Record * const *;
267
268   const_record_iterator classes_begin() const { return getClasses().begin(); }
269   const_record_iterator classes_end() const { return getClasses().end(); }
270
271   std::string getAsString() const override;
272
273   bool isSubClassOf(Record *Class) const;
274   bool typeIsConvertibleTo(const RecTy *RHS) const override;
275
276   bool typeIsA(const RecTy *RHS) const override;
277 };
278
279 /// Find a common type that T1 and T2 convert to.
280 /// Return 0 if no such type exists.
281 RecTy *resolveTypes(RecTy *T1, RecTy *T2);
282
283 //===----------------------------------------------------------------------===//
284 //  Initializer Classes
285 //===----------------------------------------------------------------------===//
286
287 class Init {
288 protected:
289   /// Discriminator enum (for isa<>, dyn_cast<>, et al.)
290   ///
291   /// This enum is laid out by a preorder traversal of the inheritance
292   /// hierarchy, and does not contain an entry for abstract classes, as per
293   /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst.
294   ///
295   /// We also explicitly include "first" and "last" values for each
296   /// interior node of the inheritance tree, to make it easier to read the
297   /// corresponding classof().
298   ///
299   /// We could pack these a bit tighter by not having the IK_FirstXXXInit
300   /// and IK_LastXXXInit be their own values, but that would degrade
301   /// readability for really no benefit.
302   enum InitKind : uint8_t {
303     IK_First, // unused; silence a spurious warning
304     IK_FirstTypedInit,
305     IK_BitInit,
306     IK_BitsInit,
307     IK_CodeInit,
308     IK_DagInit,
309     IK_DefInit,
310     IK_FieldInit,
311     IK_IntInit,
312     IK_ListInit,
313     IK_FirstOpInit,
314     IK_BinOpInit,
315     IK_TernOpInit,
316     IK_UnOpInit,
317     IK_LastOpInit,
318     IK_CondOpInit,
319     IK_FoldOpInit,
320     IK_IsAOpInit,
321     IK_StringInit,
322     IK_VarInit,
323     IK_VarListElementInit,
324     IK_VarBitInit,
325     IK_VarDefInit,
326     IK_LastTypedInit,
327     IK_UnsetInit
328   };
329
330 private:
331   const InitKind Kind;
332
333 protected:
334   uint8_t Opc; // Used by UnOpInit, BinOpInit, and TernOpInit
335
336 private:
337   virtual void anchor();
338
339 public:
340   InitKind getKind() const { return Kind; }
341
342 protected:
343   explicit Init(InitKind K, uint8_t Opc = 0) : Kind(K), Opc(Opc) {}
344
345 public:
346   Init(const Init &) = delete;
347   Init &operator=(const Init &) = delete;
348   virtual ~Init() = default;
349
350   /// This virtual method should be overridden by values that may
351   /// not be completely specified yet.
352   virtual bool isComplete() const { return true; }
353
354   /// Is this a concrete and fully resolved value without any references or
355   /// stuck operations? Unset values are concrete.
356   virtual bool isConcrete() const { return false; }
357
358   /// Print out this value.
359   void print(raw_ostream &OS) const { OS << getAsString(); }
360
361   /// Convert this value to a string form.
362   virtual std::string getAsString() const = 0;
363   /// Convert this value to a string form,
364   /// without adding quote markers.  This primaruly affects
365   /// StringInits where we will not surround the string value with
366   /// quotes.
367   virtual std::string getAsUnquotedString() const { return getAsString(); }
368
369   /// Debugging method that may be called through a debugger, just
370   /// invokes print on stderr.
371   void dump() const;
372
373   /// If this initializer is convertible to Ty, return an initializer whose
374   /// type is-a Ty, generating a !cast operation if required. Otherwise, return
375   /// nullptr.
376   virtual Init *getCastTo(RecTy *Ty) const = 0;
377
378   /// Convert to an initializer whose type is-a Ty, or return nullptr if this
379   /// is not possible (this can happen if the initializer's type is convertible
380   /// to Ty, but there are unresolved references).
381   virtual Init *convertInitializerTo(RecTy *Ty) const = 0;
382
383   /// This method is used to implement the bitrange
384   /// selection operator.  Given an initializer, it selects the specified bits
385   /// out, returning them as a new init of bits type.  If it is not legal to use
386   /// the bit subscript operator on this initializer, return null.
387   virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
388     return nullptr;
389   }
390
391   /// This method is used to implement the list slice
392   /// selection operator.  Given an initializer, it selects the specified list
393   /// elements, returning them as a new init of list type.  If it is not legal
394   /// to take a slice of this, return null.
395   virtual Init *convertInitListSlice(ArrayRef<unsigned> Elements) const {
396     return nullptr;
397   }
398
399   /// This method is used to implement the FieldInit class.
400   /// Implementors of this method should return the type of the named field if
401   /// they are of record type.
402   virtual RecTy *getFieldType(StringInit *FieldName) const {
403     return nullptr;
404   }
405
406   /// This method is used by classes that refer to other
407   /// variables which may not be defined at the time the expression is formed.
408   /// If a value is set for the variable later, this method will be called on
409   /// users of the value to allow the value to propagate out.
410   virtual Init *resolveReferences(Resolver &R) const {
411     return const_cast<Init *>(this);
412   }
413
414   /// This method is used to return the initializer for the specified
415   /// bit.
416   virtual Init *getBit(unsigned Bit) const = 0;
417 };
418
419 inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) {
420   I.print(OS); return OS;
421 }
422
423 /// This is the common super-class of types that have a specific,
424 /// explicit, type.
425 class TypedInit : public Init {
426   RecTy *Ty;
427
428 protected:
429   explicit TypedInit(InitKind K, RecTy *T, uint8_t Opc = 0)
430     : Init(K, Opc), Ty(T) {}
431
432 public:
433   TypedInit(const TypedInit &) = delete;
434   TypedInit &operator=(const TypedInit &) = delete;
435
436   static bool classof(const Init *I) {
437     return I->getKind() >= IK_FirstTypedInit &&
438            I->getKind() <= IK_LastTypedInit;
439   }
440
441   RecTy *getType() const { return Ty; }
442
443   Init *getCastTo(RecTy *Ty) const override;
444   Init *convertInitializerTo(RecTy *Ty) const override;
445
446   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
447   Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
448
449   /// This method is used to implement the FieldInit class.
450   /// Implementors of this method should return the type of the named field if
451   /// they are of record type.
452   ///
453   RecTy *getFieldType(StringInit *FieldName) const override;
454 };
455
456 /// '?' - Represents an uninitialized value
457 class UnsetInit : public Init {
458   UnsetInit() : Init(IK_UnsetInit) {}
459
460 public:
461   UnsetInit(const UnsetInit &) = delete;
462   UnsetInit &operator=(const UnsetInit &) = delete;
463
464   static bool classof(const Init *I) {
465     return I->getKind() == IK_UnsetInit;
466   }
467
468   static UnsetInit *get();
469
470   Init *getCastTo(RecTy *Ty) const override;
471   Init *convertInitializerTo(RecTy *Ty) const override;
472
473   Init *getBit(unsigned Bit) const override {
474     return const_cast<UnsetInit*>(this);
475   }
476
477   bool isComplete() const override { return false; }
478   bool isConcrete() const override { return true; }
479   std::string getAsString() const override { return "?"; }
480 };
481
482 /// 'true'/'false' - Represent a concrete initializer for a bit.
483 class BitInit final : public TypedInit {
484   bool Value;
485
486   explicit BitInit(bool V) : TypedInit(IK_BitInit, BitRecTy::get()), Value(V) {}
487
488 public:
489   BitInit(const BitInit &) = delete;
490   BitInit &operator=(BitInit &) = delete;
491
492   static bool classof(const Init *I) {
493     return I->getKind() == IK_BitInit;
494   }
495
496   static BitInit *get(bool V);
497
498   bool getValue() const { return Value; }
499
500   Init *convertInitializerTo(RecTy *Ty) const override;
501
502   Init *getBit(unsigned Bit) const override {
503     assert(Bit < 1 && "Bit index out of range!");
504     return const_cast<BitInit*>(this);
505   }
506
507   bool isConcrete() const override { return true; }
508   std::string getAsString() const override { return Value ? "1" : "0"; }
509 };
510
511 /// '{ a, b, c }' - Represents an initializer for a BitsRecTy value.
512 /// It contains a vector of bits, whose size is determined by the type.
513 class BitsInit final : public TypedInit, public FoldingSetNode,
514                        public TrailingObjects<BitsInit, Init *> {
515   unsigned NumBits;
516
517   BitsInit(unsigned N)
518     : TypedInit(IK_BitsInit, BitsRecTy::get(N)), NumBits(N) {}
519
520 public:
521   BitsInit(const BitsInit &) = delete;
522   BitsInit &operator=(const BitsInit &) = delete;
523
524   // Do not use sized deallocation due to trailing objects.
525   void operator delete(void *p) { ::operator delete(p); }
526
527   static bool classof(const Init *I) {
528     return I->getKind() == IK_BitsInit;
529   }
530
531   static BitsInit *get(ArrayRef<Init *> Range);
532
533   void Profile(FoldingSetNodeID &ID) const;
534
535   unsigned getNumBits() const { return NumBits; }
536
537   Init *convertInitializerTo(RecTy *Ty) const override;
538   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
539
540   bool isComplete() const override {
541     for (unsigned i = 0; i != getNumBits(); ++i)
542       if (!getBit(i)->isComplete()) return false;
543     return true;
544   }
545
546   bool allInComplete() const {
547     for (unsigned i = 0; i != getNumBits(); ++i)
548       if (getBit(i)->isComplete()) return false;
549     return true;
550   }
551
552   bool isConcrete() const override;
553   std::string getAsString() const override;
554
555   Init *resolveReferences(Resolver &R) const override;
556
557   Init *getBit(unsigned Bit) const override {
558     assert(Bit < NumBits && "Bit index out of range!");
559     return getTrailingObjects<Init *>()[Bit];
560   }
561 };
562
563 /// '7' - Represent an initialization by a literal integer value.
564 class IntInit : public TypedInit {
565   int64_t Value;
566
567   explicit IntInit(int64_t V)
568     : TypedInit(IK_IntInit, IntRecTy::get()), Value(V) {}
569
570 public:
571   IntInit(const IntInit &) = delete;
572   IntInit &operator=(const IntInit &) = delete;
573
574   static bool classof(const Init *I) {
575     return I->getKind() == IK_IntInit;
576   }
577
578   static IntInit *get(int64_t V);
579
580   int64_t getValue() const { return Value; }
581
582   Init *convertInitializerTo(RecTy *Ty) const override;
583   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
584
585   bool isConcrete() const override { return true; }
586   std::string getAsString() const override;
587
588   Init *getBit(unsigned Bit) const override {
589     return BitInit::get((Value & (1ULL << Bit)) != 0);
590   }
591 };
592
593 /// "foo" - Represent an initialization by a string value.
594 class StringInit : public TypedInit {
595   StringRef Value;
596
597   explicit StringInit(StringRef V)
598       : TypedInit(IK_StringInit, StringRecTy::get()), Value(V) {}
599
600 public:
601   StringInit(const StringInit &) = delete;
602   StringInit &operator=(const StringInit &) = delete;
603
604   static bool classof(const Init *I) {
605     return I->getKind() == IK_StringInit;
606   }
607
608   static StringInit *get(StringRef);
609
610   StringRef getValue() const { return Value; }
611
612   Init *convertInitializerTo(RecTy *Ty) const override;
613
614   bool isConcrete() const override { return true; }
615   std::string getAsString() const override { return "\"" + Value.str() + "\""; }
616
617   std::string getAsUnquotedString() const override {
618     return std::string(Value);
619   }
620
621   Init *getBit(unsigned Bit) const override {
622     llvm_unreachable("Illegal bit reference off string");
623   }
624 };
625
626 class CodeInit : public TypedInit {
627   StringRef Value;
628   SMLoc Loc;
629
630   explicit CodeInit(StringRef V, const SMLoc &Loc)
631       : TypedInit(IK_CodeInit, static_cast<RecTy *>(CodeRecTy::get())),
632         Value(V), Loc(Loc) {}
633
634 public:
635   CodeInit(const StringInit &) = delete;
636   CodeInit &operator=(const StringInit &) = delete;
637
638   static bool classof(const Init *I) {
639     return I->getKind() == IK_CodeInit;
640   }
641
642   static CodeInit *get(StringRef, const SMLoc &Loc);
643
644   StringRef getValue() const { return Value; }
645   const SMLoc &getLoc() const { return Loc; }
646
647   Init *convertInitializerTo(RecTy *Ty) const override;
648
649   bool isConcrete() const override { return true; }
650   std::string getAsString() const override {
651     return "[{" + Value.str() + "}]";
652   }
653
654   std::string getAsUnquotedString() const override {
655     return std::string(Value);
656   }
657
658   Init *getBit(unsigned Bit) const override {
659     llvm_unreachable("Illegal bit reference off string");
660   }
661 };
662
663 /// [AL, AH, CL] - Represent a list of defs
664 ///
665 class ListInit final : public TypedInit, public FoldingSetNode,
666                        public TrailingObjects<ListInit, Init *> {
667   unsigned NumValues;
668
669 public:
670   using const_iterator = Init *const *;
671
672 private:
673   explicit ListInit(unsigned N, RecTy *EltTy)
674     : TypedInit(IK_ListInit, ListRecTy::get(EltTy)), NumValues(N) {}
675
676 public:
677   ListInit(const ListInit &) = delete;
678   ListInit &operator=(const ListInit &) = delete;
679
680   // Do not use sized deallocation due to trailing objects.
681   void operator delete(void *p) { ::operator delete(p); }
682
683   static bool classof(const Init *I) {
684     return I->getKind() == IK_ListInit;
685   }
686   static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy);
687
688   void Profile(FoldingSetNodeID &ID) const;
689
690   Init *getElement(unsigned i) const {
691     assert(i < NumValues && "List element index out of range!");
692     return getTrailingObjects<Init *>()[i];
693   }
694   RecTy *getElementType() const {
695     return cast<ListRecTy>(getType())->getElementType();
696   }
697
698   Record *getElementAsRecord(unsigned i) const;
699
700   Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
701
702   Init *convertInitializerTo(RecTy *Ty) const override;
703
704   /// This method is used by classes that refer to other
705   /// variables which may not be defined at the time they expression is formed.
706   /// If a value is set for the variable later, this method will be called on
707   /// users of the value to allow the value to propagate out.
708   ///
709   Init *resolveReferences(Resolver &R) const override;
710
711   bool isConcrete() const override;
712   std::string getAsString() const override;
713
714   ArrayRef<Init*> getValues() const {
715     return makeArrayRef(getTrailingObjects<Init *>(), NumValues);
716   }
717
718   const_iterator begin() const { return getTrailingObjects<Init *>(); }
719   const_iterator end  () const { return begin() + NumValues; }
720
721   size_t         size () const { return NumValues;  }
722   bool           empty() const { return NumValues == 0; }
723
724   Init *getBit(unsigned Bit) const override {
725     llvm_unreachable("Illegal bit reference off list");
726   }
727 };
728
729 /// Base class for operators
730 ///
731 class OpInit : public TypedInit {
732 protected:
733   explicit OpInit(InitKind K, RecTy *Type, uint8_t Opc)
734     : TypedInit(K, Type, Opc) {}
735
736 public:
737   OpInit(const OpInit &) = delete;
738   OpInit &operator=(OpInit &) = delete;
739
740   static bool classof(const Init *I) {
741     return I->getKind() >= IK_FirstOpInit &&
742            I->getKind() <= IK_LastOpInit;
743   }
744
745   // Clone - Clone this operator, replacing arguments with the new list
746   virtual OpInit *clone(ArrayRef<Init *> Operands) const = 0;
747
748   virtual unsigned getNumOperands() const = 0;
749   virtual Init *getOperand(unsigned i) const = 0;
750
751   Init *getBit(unsigned Bit) const override;
752 };
753
754 /// !op (X) - Transform an init.
755 ///
756 class UnOpInit : public OpInit, public FoldingSetNode {
757 public:
758   enum UnaryOp : uint8_t { CAST, HEAD, TAIL, SIZE, EMPTY, GETOP };
759
760 private:
761   Init *LHS;
762
763   UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
764     : OpInit(IK_UnOpInit, Type, opc), LHS(lhs) {}
765
766 public:
767   UnOpInit(const UnOpInit &) = delete;
768   UnOpInit &operator=(const UnOpInit &) = delete;
769
770   static bool classof(const Init *I) {
771     return I->getKind() == IK_UnOpInit;
772   }
773
774   static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
775
776   void Profile(FoldingSetNodeID &ID) const;
777
778   // Clone - Clone this operator, replacing arguments with the new list
779   OpInit *clone(ArrayRef<Init *> Operands) const override {
780     assert(Operands.size() == 1 &&
781            "Wrong number of operands for unary operation");
782     return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
783   }
784
785   unsigned getNumOperands() const override { return 1; }
786
787   Init *getOperand(unsigned i) const override {
788     assert(i == 0 && "Invalid operand id for unary operator");
789     return getOperand();
790   }
791
792   UnaryOp getOpcode() const { return (UnaryOp)Opc; }
793   Init *getOperand() const { return LHS; }
794
795   // Fold - If possible, fold this to a simpler init.  Return this if not
796   // possible to fold.
797   Init *Fold(Record *CurRec, bool IsFinal = false) const;
798
799   Init *resolveReferences(Resolver &R) const override;
800
801   std::string getAsString() const override;
802 };
803
804 /// !op (X, Y) - Combine two inits.
805 class BinOpInit : public OpInit, public FoldingSetNode {
806 public:
807   enum BinaryOp : uint8_t { ADD, MUL, AND, OR, SHL, SRA, SRL, LISTCONCAT,
808                             LISTSPLAT, STRCONCAT, CONCAT, EQ, NE, LE, LT, GE,
809                             GT, SETOP };
810
811 private:
812   Init *LHS, *RHS;
813
814   BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) :
815       OpInit(IK_BinOpInit, Type, opc), LHS(lhs), RHS(rhs) {}
816
817 public:
818   BinOpInit(const BinOpInit &) = delete;
819   BinOpInit &operator=(const BinOpInit &) = delete;
820
821   static bool classof(const Init *I) {
822     return I->getKind() == IK_BinOpInit;
823   }
824
825   static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs,
826                         RecTy *Type);
827   static Init *getStrConcat(Init *lhs, Init *rhs);
828   static Init *getListConcat(TypedInit *lhs, Init *rhs);
829   static Init *getListSplat(TypedInit *lhs, Init *rhs);
830
831   void Profile(FoldingSetNodeID &ID) const;
832
833   // Clone - Clone this operator, replacing arguments with the new list
834   OpInit *clone(ArrayRef<Init *> Operands) const override {
835     assert(Operands.size() == 2 &&
836            "Wrong number of operands for binary operation");
837     return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType());
838   }
839
840   unsigned getNumOperands() const override { return 2; }
841   Init *getOperand(unsigned i) const override {
842     switch (i) {
843     default: llvm_unreachable("Invalid operand id for binary operator");
844     case 0: return getLHS();
845     case 1: return getRHS();
846     }
847   }
848
849   BinaryOp getOpcode() const { return (BinaryOp)Opc; }
850   Init *getLHS() const { return LHS; }
851   Init *getRHS() const { return RHS; }
852
853   // Fold - If possible, fold this to a simpler init.  Return this if not
854   // possible to fold.
855   Init *Fold(Record *CurRec) const;
856
857   Init *resolveReferences(Resolver &R) const override;
858
859   std::string getAsString() const override;
860 };
861
862 /// !op (X, Y, Z) - Combine two inits.
863 class TernOpInit : public OpInit, public FoldingSetNode {
864 public:
865   enum TernaryOp : uint8_t { SUBST, FOREACH, IF, DAG };
866
867 private:
868   Init *LHS, *MHS, *RHS;
869
870   TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
871              RecTy *Type) :
872       OpInit(IK_TernOpInit, Type, opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
873
874 public:
875   TernOpInit(const TernOpInit &) = delete;
876   TernOpInit &operator=(const TernOpInit &) = delete;
877
878   static bool classof(const Init *I) {
879     return I->getKind() == IK_TernOpInit;
880   }
881
882   static TernOpInit *get(TernaryOp opc, Init *lhs,
883                          Init *mhs, Init *rhs,
884                          RecTy *Type);
885
886   void Profile(FoldingSetNodeID &ID) const;
887
888   // Clone - Clone this operator, replacing arguments with the new list
889   OpInit *clone(ArrayRef<Init *> Operands) const override {
890     assert(Operands.size() == 3 &&
891            "Wrong number of operands for ternary operation");
892     return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
893                            getType());
894   }
895
896   unsigned getNumOperands() const override { return 3; }
897   Init *getOperand(unsigned i) const override {
898     switch (i) {
899     default: llvm_unreachable("Invalid operand id for ternary operator");
900     case 0: return getLHS();
901     case 1: return getMHS();
902     case 2: return getRHS();
903     }
904   }
905
906   TernaryOp getOpcode() const { return (TernaryOp)Opc; }
907   Init *getLHS() const { return LHS; }
908   Init *getMHS() const { return MHS; }
909   Init *getRHS() const { return RHS; }
910
911   // Fold - If possible, fold this to a simpler init.  Return this if not
912   // possible to fold.
913   Init *Fold(Record *CurRec) const;
914
915   bool isComplete() const override {
916     return LHS->isComplete() && MHS->isComplete() && RHS->isComplete();
917   }
918
919   Init *resolveReferences(Resolver &R) const override;
920
921   std::string getAsString() const override;
922 };
923
924 /// !cond(condition_1: value1, ... , condition_n: value)
925 /// Selects the first value for which condition is true.
926 /// Otherwise reports an error.
927 class CondOpInit final : public TypedInit, public FoldingSetNode,
928                       public TrailingObjects<CondOpInit, Init *> {
929   unsigned NumConds;
930   RecTy *ValType;
931
932   CondOpInit(unsigned NC, RecTy *Type)
933     : TypedInit(IK_CondOpInit, Type),
934       NumConds(NC), ValType(Type) {}
935
936   size_t numTrailingObjects(OverloadToken<Init *>) const {
937     return 2*NumConds;
938   }
939
940 public:
941   CondOpInit(const CondOpInit &) = delete;
942   CondOpInit &operator=(const CondOpInit &) = delete;
943
944   static bool classof(const Init *I) {
945     return I->getKind() == IK_CondOpInit;
946   }
947
948   static CondOpInit *get(ArrayRef<Init*> C, ArrayRef<Init*> V,
949                         RecTy *Type);
950
951   void Profile(FoldingSetNodeID &ID) const;
952
953   RecTy *getValType() const { return ValType; }
954
955   unsigned getNumConds() const { return NumConds; }
956
957   Init *getCond(unsigned Num) const {
958     assert(Num < NumConds && "Condition number out of range!");
959     return getTrailingObjects<Init *>()[Num];
960   }
961
962   Init *getVal(unsigned Num) const {
963     assert(Num < NumConds && "Val number out of range!");
964     return getTrailingObjects<Init *>()[Num+NumConds];
965   }
966
967   ArrayRef<Init *> getConds() const {
968     return makeArrayRef(getTrailingObjects<Init *>(), NumConds);
969   }
970
971   ArrayRef<Init *> getVals() const {
972     return makeArrayRef(getTrailingObjects<Init *>()+NumConds, NumConds);
973   }
974
975   Init *Fold(Record *CurRec) const;
976
977   Init *resolveReferences(Resolver &R) const override;
978
979   bool isConcrete() const override;
980   bool isComplete() const override;
981   std::string getAsString() const override;
982
983   using const_case_iterator = SmallVectorImpl<Init*>::const_iterator;
984   using const_val_iterator = SmallVectorImpl<Init*>::const_iterator;
985
986   inline const_case_iterator  arg_begin() const { return getConds().begin(); }
987   inline const_case_iterator  arg_end  () const { return getConds().end(); }
988
989   inline size_t              case_size () const { return NumConds; }
990   inline bool                case_empty() const { return NumConds == 0; }
991
992   inline const_val_iterator name_begin() const { return getVals().begin();}
993   inline const_val_iterator name_end  () const { return getVals().end(); }
994
995   inline size_t              val_size () const { return NumConds; }
996   inline bool                val_empty() const { return NumConds == 0; }
997
998   Init *getBit(unsigned Bit) const override;
999 };
1000
1001 /// !foldl (a, b, expr, start, lst) - Fold over a list.
1002 class FoldOpInit : public TypedInit, public FoldingSetNode {
1003 private:
1004   Init *Start;
1005   Init *List;
1006   Init *A;
1007   Init *B;
1008   Init *Expr;
1009
1010   FoldOpInit(Init *Start, Init *List, Init *A, Init *B, Init *Expr, RecTy *Type)
1011       : TypedInit(IK_FoldOpInit, Type), Start(Start), List(List), A(A), B(B),
1012         Expr(Expr) {}
1013
1014 public:
1015   FoldOpInit(const FoldOpInit &) = delete;
1016   FoldOpInit &operator=(const FoldOpInit &) = delete;
1017
1018   static bool classof(const Init *I) { return I->getKind() == IK_FoldOpInit; }
1019
1020   static FoldOpInit *get(Init *Start, Init *List, Init *A, Init *B, Init *Expr,
1021                          RecTy *Type);
1022
1023   void Profile(FoldingSetNodeID &ID) const;
1024
1025   // Fold - If possible, fold this to a simpler init.  Return this if not
1026   // possible to fold.
1027   Init *Fold(Record *CurRec) const;
1028
1029   bool isComplete() const override { return false; }
1030
1031   Init *resolveReferences(Resolver &R) const override;
1032
1033   Init *getBit(unsigned Bit) const override;
1034
1035   std::string getAsString() const override;
1036 };
1037
1038 /// !isa<type>(expr) - Dynamically determine the type of an expression.
1039 class IsAOpInit : public TypedInit, public FoldingSetNode {
1040 private:
1041   RecTy *CheckType;
1042   Init *Expr;
1043
1044   IsAOpInit(RecTy *CheckType, Init *Expr)
1045       : TypedInit(IK_IsAOpInit, IntRecTy::get()), CheckType(CheckType),
1046         Expr(Expr) {}
1047
1048 public:
1049   IsAOpInit(const IsAOpInit &) = delete;
1050   IsAOpInit &operator=(const IsAOpInit &) = delete;
1051
1052   static bool classof(const Init *I) { return I->getKind() == IK_IsAOpInit; }
1053
1054   static IsAOpInit *get(RecTy *CheckType, Init *Expr);
1055
1056   void Profile(FoldingSetNodeID &ID) const;
1057
1058   // Fold - If possible, fold this to a simpler init.  Return this if not
1059   // possible to fold.
1060   Init *Fold() const;
1061
1062   bool isComplete() const override { return false; }
1063
1064   Init *resolveReferences(Resolver &R) const override;
1065
1066   Init *getBit(unsigned Bit) const override;
1067
1068   std::string getAsString() const override;
1069 };
1070
1071 /// 'Opcode' - Represent a reference to an entire variable object.
1072 class VarInit : public TypedInit {
1073   Init *VarName;
1074
1075   explicit VarInit(Init *VN, RecTy *T)
1076       : TypedInit(IK_VarInit, T), VarName(VN) {}
1077
1078 public:
1079   VarInit(const VarInit &) = delete;
1080   VarInit &operator=(const VarInit &) = delete;
1081
1082   static bool classof(const Init *I) {
1083     return I->getKind() == IK_VarInit;
1084   }
1085
1086   static VarInit *get(StringRef VN, RecTy *T);
1087   static VarInit *get(Init *VN, RecTy *T);
1088
1089   StringRef getName() const;
1090   Init *getNameInit() const { return VarName; }
1091
1092   std::string getNameInitAsString() const {
1093     return getNameInit()->getAsUnquotedString();
1094   }
1095
1096   /// This method is used by classes that refer to other
1097   /// variables which may not be defined at the time they expression is formed.
1098   /// If a value is set for the variable later, this method will be called on
1099   /// users of the value to allow the value to propagate out.
1100   ///
1101   Init *resolveReferences(Resolver &R) const override;
1102
1103   Init *getBit(unsigned Bit) const override;
1104
1105   std::string getAsString() const override { return std::string(getName()); }
1106 };
1107
1108 /// Opcode{0} - Represent access to one bit of a variable or field.
1109 class VarBitInit final : public TypedInit {
1110   TypedInit *TI;
1111   unsigned Bit;
1112
1113   VarBitInit(TypedInit *T, unsigned B)
1114       : TypedInit(IK_VarBitInit, BitRecTy::get()), TI(T), Bit(B) {
1115     assert(T->getType() &&
1116            (isa<IntRecTy>(T->getType()) ||
1117             (isa<BitsRecTy>(T->getType()) &&
1118              cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&
1119            "Illegal VarBitInit expression!");
1120   }
1121
1122 public:
1123   VarBitInit(const VarBitInit &) = delete;
1124   VarBitInit &operator=(const VarBitInit &) = delete;
1125
1126   static bool classof(const Init *I) {
1127     return I->getKind() == IK_VarBitInit;
1128   }
1129
1130   static VarBitInit *get(TypedInit *T, unsigned B);
1131
1132   Init *getBitVar() const { return TI; }
1133   unsigned getBitNum() const { return Bit; }
1134
1135   std::string getAsString() const override;
1136   Init *resolveReferences(Resolver &R) const override;
1137
1138   Init *getBit(unsigned B) const override {
1139     assert(B < 1 && "Bit index out of range!");
1140     return const_cast<VarBitInit*>(this);
1141   }
1142 };
1143
1144 /// List[4] - Represent access to one element of a var or
1145 /// field.
1146 class VarListElementInit : public TypedInit {
1147   TypedInit *TI;
1148   unsigned Element;
1149
1150   VarListElementInit(TypedInit *T, unsigned E)
1151       : TypedInit(IK_VarListElementInit,
1152                   cast<ListRecTy>(T->getType())->getElementType()),
1153         TI(T), Element(E) {
1154     assert(T->getType() && isa<ListRecTy>(T->getType()) &&
1155            "Illegal VarBitInit expression!");
1156   }
1157
1158 public:
1159   VarListElementInit(const VarListElementInit &) = delete;
1160   VarListElementInit &operator=(const VarListElementInit &) = delete;
1161
1162   static bool classof(const Init *I) {
1163     return I->getKind() == IK_VarListElementInit;
1164   }
1165
1166   static VarListElementInit *get(TypedInit *T, unsigned E);
1167
1168   TypedInit *getVariable() const { return TI; }
1169   unsigned getElementNum() const { return Element; }
1170
1171   std::string getAsString() const override;
1172   Init *resolveReferences(Resolver &R) const override;
1173
1174   Init *getBit(unsigned Bit) const override;
1175 };
1176
1177 /// AL - Represent a reference to a 'def' in the description
1178 class DefInit : public TypedInit {
1179   friend class Record;
1180
1181   Record *Def;
1182
1183   explicit DefInit(Record *D);
1184
1185 public:
1186   DefInit(const DefInit &) = delete;
1187   DefInit &operator=(const DefInit &) = delete;
1188
1189   static bool classof(const Init *I) {
1190     return I->getKind() == IK_DefInit;
1191   }
1192
1193   static DefInit *get(Record*);
1194
1195   Init *convertInitializerTo(RecTy *Ty) const override;
1196
1197   Record *getDef() const { return Def; }
1198
1199   //virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits);
1200
1201   RecTy *getFieldType(StringInit *FieldName) const override;
1202
1203   bool isConcrete() const override { return true; }
1204   std::string getAsString() const override;
1205
1206   Init *getBit(unsigned Bit) const override {
1207     llvm_unreachable("Illegal bit reference off def");
1208   }
1209 };
1210
1211 /// classname<targs...> - Represent an uninstantiated anonymous class
1212 /// instantiation.
1213 class VarDefInit final : public TypedInit, public FoldingSetNode,
1214                          public TrailingObjects<VarDefInit, Init *> {
1215   Record *Class;
1216   DefInit *Def = nullptr; // after instantiation
1217   unsigned NumArgs;
1218
1219   explicit VarDefInit(Record *Class, unsigned N)
1220     : TypedInit(IK_VarDefInit, RecordRecTy::get(Class)), Class(Class), NumArgs(N) {}
1221
1222   DefInit *instantiate();
1223
1224 public:
1225   VarDefInit(const VarDefInit &) = delete;
1226   VarDefInit &operator=(const VarDefInit &) = delete;
1227
1228   // Do not use sized deallocation due to trailing objects.
1229   void operator delete(void *p) { ::operator delete(p); }
1230
1231   static bool classof(const Init *I) {
1232     return I->getKind() == IK_VarDefInit;
1233   }
1234   static VarDefInit *get(Record *Class, ArrayRef<Init *> Args);
1235
1236   void Profile(FoldingSetNodeID &ID) const;
1237
1238   Init *resolveReferences(Resolver &R) const override;
1239   Init *Fold() const;
1240
1241   std::string getAsString() const override;
1242
1243   Init *getArg(unsigned i) const {
1244     assert(i < NumArgs && "Argument index out of range!");
1245     return getTrailingObjects<Init *>()[i];
1246   }
1247
1248   using const_iterator = Init *const *;
1249
1250   const_iterator args_begin() const { return getTrailingObjects<Init *>(); }
1251   const_iterator args_end  () const { return args_begin() + NumArgs; }
1252
1253   size_t         args_size () const { return NumArgs; }
1254   bool           args_empty() const { return NumArgs == 0; }
1255
1256   ArrayRef<Init *> args() const { return makeArrayRef(args_begin(), NumArgs); }
1257
1258   Init *getBit(unsigned Bit) const override {
1259     llvm_unreachable("Illegal bit reference off anonymous def");
1260   }
1261 };
1262
1263 /// X.Y - Represent a reference to a subfield of a variable
1264 class FieldInit : public TypedInit {
1265   Init *Rec;                // Record we are referring to
1266   StringInit *FieldName;    // Field we are accessing
1267
1268   FieldInit(Init *R, StringInit *FN)
1269       : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
1270 #ifndef NDEBUG
1271     if (!getType()) {
1272       llvm::errs() << "In Record = " << Rec->getAsString()
1273                    << ", got FieldName = " << *FieldName
1274                    << " with non-record type!\n";
1275       llvm_unreachable("FieldInit with non-record type!");
1276     }
1277 #endif
1278   }
1279
1280 public:
1281   FieldInit(const FieldInit &) = delete;
1282   FieldInit &operator=(const FieldInit &) = delete;
1283
1284   static bool classof(const Init *I) {
1285     return I->getKind() == IK_FieldInit;
1286   }
1287
1288   static FieldInit *get(Init *R, StringInit *FN);
1289
1290   Init *getRecord() const { return Rec; }
1291   StringInit *getFieldName() const { return FieldName; }
1292
1293   Init *getBit(unsigned Bit) const override;
1294
1295   Init *resolveReferences(Resolver &R) const override;
1296   Init *Fold(Record *CurRec) const;
1297
1298   bool isConcrete() const override;
1299   std::string getAsString() const override {
1300     return Rec->getAsString() + "." + FieldName->getValue().str();
1301   }
1302 };
1303
1304 /// (v a, b) - Represent a DAG tree value.  DAG inits are required
1305 /// to have at least one value then a (possibly empty) list of arguments.  Each
1306 /// argument can have a name associated with it.
1307 class DagInit final : public TypedInit, public FoldingSetNode,
1308                       public TrailingObjects<DagInit, Init *, StringInit *> {
1309   friend TrailingObjects;
1310
1311   Init *Val;
1312   StringInit *ValName;
1313   unsigned NumArgs;
1314   unsigned NumArgNames;
1315
1316   DagInit(Init *V, StringInit *VN, unsigned NumArgs, unsigned NumArgNames)
1317       : TypedInit(IK_DagInit, DagRecTy::get()), Val(V), ValName(VN),
1318         NumArgs(NumArgs), NumArgNames(NumArgNames) {}
1319
1320   size_t numTrailingObjects(OverloadToken<Init *>) const { return NumArgs; }
1321
1322 public:
1323   DagInit(const DagInit &) = delete;
1324   DagInit &operator=(const DagInit &) = delete;
1325
1326   static bool classof(const Init *I) {
1327     return I->getKind() == IK_DagInit;
1328   }
1329
1330   static DagInit *get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1331                       ArrayRef<StringInit*> NameRange);
1332   static DagInit *get(Init *V, StringInit *VN,
1333                       ArrayRef<std::pair<Init*, StringInit*>> Args);
1334
1335   void Profile(FoldingSetNodeID &ID) const;
1336
1337   Init *getOperator() const { return Val; }
1338   Record *getOperatorAsDef(ArrayRef<SMLoc> Loc) const;
1339
1340   StringInit *getName() const { return ValName; }
1341
1342   StringRef getNameStr() const {
1343     return ValName ? ValName->getValue() : StringRef();
1344   }
1345
1346   unsigned getNumArgs() const { return NumArgs; }
1347
1348   Init *getArg(unsigned Num) const {
1349     assert(Num < NumArgs && "Arg number out of range!");
1350     return getTrailingObjects<Init *>()[Num];
1351   }
1352
1353   StringInit *getArgName(unsigned Num) const {
1354     assert(Num < NumArgNames && "Arg number out of range!");
1355     return getTrailingObjects<StringInit *>()[Num];
1356   }
1357
1358   StringRef getArgNameStr(unsigned Num) const {
1359     StringInit *Init = getArgName(Num);
1360     return Init ? Init->getValue() : StringRef();
1361   }
1362
1363   ArrayRef<Init *> getArgs() const {
1364     return makeArrayRef(getTrailingObjects<Init *>(), NumArgs);
1365   }
1366
1367   ArrayRef<StringInit *> getArgNames() const {
1368     return makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames);
1369   }
1370
1371   Init *resolveReferences(Resolver &R) const override;
1372
1373   bool isConcrete() const override;
1374   std::string getAsString() const override;
1375
1376   using const_arg_iterator = SmallVectorImpl<Init*>::const_iterator;
1377   using const_name_iterator = SmallVectorImpl<StringInit*>::const_iterator;
1378
1379   inline const_arg_iterator  arg_begin() const { return getArgs().begin(); }
1380   inline const_arg_iterator  arg_end  () const { return getArgs().end(); }
1381
1382   inline size_t              arg_size () const { return NumArgs; }
1383   inline bool                arg_empty() const { return NumArgs == 0; }
1384
1385   inline const_name_iterator name_begin() const { return getArgNames().begin();}
1386   inline const_name_iterator name_end  () const { return getArgNames().end(); }
1387
1388   inline size_t              name_size () const { return NumArgNames; }
1389   inline bool                name_empty() const { return NumArgNames == 0; }
1390
1391   Init *getBit(unsigned Bit) const override {
1392     llvm_unreachable("Illegal bit reference off dag");
1393   }
1394 };
1395
1396 //===----------------------------------------------------------------------===//
1397 //  High-Level Classes
1398 //===----------------------------------------------------------------------===//
1399
1400 class RecordVal {
1401   friend class Record;
1402
1403   Init *Name;
1404   PointerIntPair<RecTy *, 1, bool> TyAndPrefix;
1405   Init *Value;
1406
1407 public:
1408   RecordVal(Init *N, RecTy *T, bool P);
1409
1410   StringRef getName() const;
1411   Init *getNameInit() const { return Name; }
1412
1413   std::string getNameInitAsString() const {
1414     return getNameInit()->getAsUnquotedString();
1415   }
1416
1417   bool getPrefix() const { return TyAndPrefix.getInt(); }
1418   RecTy *getType() const { return TyAndPrefix.getPointer(); }
1419   Init *getValue() const { return Value; }
1420
1421   bool setValue(Init *V);
1422
1423   void dump() const;
1424   void print(raw_ostream &OS, bool PrintSem = true) const;
1425 };
1426
1427 inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
1428   RV.print(OS << "  ");
1429   return OS;
1430 }
1431
1432 class Record {
1433   static unsigned LastID;
1434
1435   Init *Name;
1436   // Location where record was instantiated, followed by the location of
1437   // multiclass prototypes used.
1438   SmallVector<SMLoc, 4> Locs;
1439   SmallVector<Init *, 0> TemplateArgs;
1440   SmallVector<RecordVal, 0> Values;
1441
1442   // All superclasses in the inheritance forest in reverse preorder (yes, it
1443   // must be a forest; diamond-shaped inheritance is not allowed).
1444   SmallVector<std::pair<Record *, SMRange>, 0> SuperClasses;
1445
1446   // Tracks Record instances. Not owned by Record.
1447   RecordKeeper &TrackedRecords;
1448
1449   DefInit *TheInit = nullptr;
1450
1451   // Unique record ID.
1452   unsigned ID;
1453
1454   bool IsAnonymous;
1455   bool IsClass;
1456
1457   void checkName();
1458
1459 public:
1460   // Constructs a record.
1461   explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1462                   bool Anonymous = false, bool Class = false)
1463     : Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records),
1464       ID(LastID++), IsAnonymous(Anonymous), IsClass(Class) {
1465     checkName();
1466   }
1467
1468   explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1469                   bool Class = false)
1470       : Record(StringInit::get(N), locs, records, false, Class) {}
1471
1472   // When copy-constructing a Record, we must still guarantee a globally unique
1473   // ID number.  Don't copy TheInit either since it's owned by the original
1474   // record. All other fields can be copied normally.
1475   Record(const Record &O)
1476     : Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
1477       Values(O.Values), SuperClasses(O.SuperClasses),
1478       TrackedRecords(O.TrackedRecords), ID(LastID++),
1479       IsAnonymous(O.IsAnonymous), IsClass(O.IsClass) { }
1480
1481   static unsigned getNewUID() { return LastID++; }
1482
1483   unsigned getID() const { return ID; }
1484
1485   StringRef getName() const { return cast<StringInit>(Name)->getValue(); }
1486
1487   Init *getNameInit() const {
1488     return Name;
1489   }
1490
1491   const std::string getNameInitAsString() const {
1492     return getNameInit()->getAsUnquotedString();
1493   }
1494
1495   void setName(Init *Name);      // Also updates RecordKeeper.
1496
1497   ArrayRef<SMLoc> getLoc() const { return Locs; }
1498   void appendLoc(SMLoc Loc) { Locs.push_back(Loc); }
1499
1500   // Make the type that this record should have based on its superclasses.
1501   RecordRecTy *getType();
1502
1503   /// get the corresponding DefInit.
1504   DefInit *getDefInit();
1505
1506   bool isClass() const { return IsClass; }
1507
1508   ArrayRef<Init *> getTemplateArgs() const {
1509     return TemplateArgs;
1510   }
1511
1512   ArrayRef<RecordVal> getValues() const { return Values; }
1513
1514   ArrayRef<std::pair<Record *, SMRange>>  getSuperClasses() const {
1515     return SuperClasses;
1516   }
1517
1518   /// Append the direct super classes of this record to Classes.
1519   void getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const;
1520
1521   bool isTemplateArg(Init *Name) const {
1522     for (Init *TA : TemplateArgs)
1523       if (TA == Name) return true;
1524     return false;
1525   }
1526
1527   const RecordVal *getValue(const Init *Name) const {
1528     for (const RecordVal &Val : Values)
1529       if (Val.Name == Name) return &Val;
1530     return nullptr;
1531   }
1532
1533   const RecordVal *getValue(StringRef Name) const {
1534     return getValue(StringInit::get(Name));
1535   }
1536
1537   RecordVal *getValue(const Init *Name) {
1538     return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1539   }
1540
1541   RecordVal *getValue(StringRef Name) {
1542     return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1543   }
1544
1545   void addTemplateArg(Init *Name) {
1546     assert(!isTemplateArg(Name) && "Template arg already defined!");
1547     TemplateArgs.push_back(Name);
1548   }
1549
1550   void addValue(const RecordVal &RV) {
1551     assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
1552     Values.push_back(RV);
1553   }
1554
1555   void removeValue(Init *Name) {
1556     for (unsigned i = 0, e = Values.size(); i != e; ++i)
1557       if (Values[i].getNameInit() == Name) {
1558         Values.erase(Values.begin()+i);
1559         return;
1560       }
1561     llvm_unreachable("Cannot remove an entry that does not exist!");
1562   }
1563
1564   void removeValue(StringRef Name) {
1565     removeValue(StringInit::get(Name));
1566   }
1567
1568   bool isSubClassOf(const Record *R) const {
1569     for (const auto &SCPair : SuperClasses)
1570       if (SCPair.first == R)
1571         return true;
1572     return false;
1573   }
1574
1575   bool isSubClassOf(StringRef Name) const {
1576     for (const auto &SCPair : SuperClasses) {
1577       if (const auto *SI = dyn_cast<StringInit>(SCPair.first->getNameInit())) {
1578         if (SI->getValue() == Name)
1579           return true;
1580       } else if (SCPair.first->getNameInitAsString() == Name) {
1581         return true;
1582       }
1583     }
1584     return false;
1585   }
1586
1587   void addSuperClass(Record *R, SMRange Range) {
1588     assert(!TheInit && "changing type of record after it has been referenced");
1589     assert(!isSubClassOf(R) && "Already subclassing record!");
1590     SuperClasses.push_back(std::make_pair(R, Range));
1591   }
1592
1593   /// If there are any field references that refer to fields
1594   /// that have been filled in, we can propagate the values now.
1595   ///
1596   /// This is a final resolve: any error messages, e.g. due to undefined
1597   /// !cast references, are generated now.
1598   void resolveReferences();
1599
1600   /// Apply the resolver to the name of the record as well as to the
1601   /// initializers of all fields of the record except SkipVal.
1602   ///
1603   /// The resolver should not resolve any of the fields itself, to avoid
1604   /// recursion / infinite loops.
1605   void resolveReferences(Resolver &R, const RecordVal *SkipVal = nullptr);
1606
1607   RecordKeeper &getRecords() const {
1608     return TrackedRecords;
1609   }
1610
1611   bool isAnonymous() const {
1612     return IsAnonymous;
1613   }
1614
1615   void print(raw_ostream &OS) const;
1616   void dump() const;
1617
1618   //===--------------------------------------------------------------------===//
1619   // High-level methods useful to tablegen back-ends
1620   //
1621
1622   /// Return the initializer for a value with the specified name,
1623   /// or throw an exception if the field does not exist.
1624   Init *getValueInit(StringRef FieldName) const;
1625
1626   /// Return true if the named field is unset.
1627   bool isValueUnset(StringRef FieldName) const {
1628     return isa<UnsetInit>(getValueInit(FieldName));
1629   }
1630
1631   /// This method looks up the specified field and returns
1632   /// its value as a string, throwing an exception if the field does not exist
1633   /// or if the value is not a string.
1634   StringRef getValueAsString(StringRef FieldName) const;
1635
1636   /// This method looks up the specified field and returns
1637   /// its value as a BitsInit, throwing an exception if the field does not exist
1638   /// or if the value is not the right type.
1639   BitsInit *getValueAsBitsInit(StringRef FieldName) const;
1640
1641   /// This method looks up the specified field and returns
1642   /// its value as a ListInit, throwing an exception if the field does not exist
1643   /// or if the value is not the right type.
1644   ListInit *getValueAsListInit(StringRef FieldName) const;
1645
1646   /// This method looks up the specified field and
1647   /// returns its value as a vector of records, throwing an exception if the
1648   /// field does not exist or if the value is not the right type.
1649   std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
1650
1651   /// This method looks up the specified field and
1652   /// returns its value as a vector of integers, throwing an exception if the
1653   /// field does not exist or if the value is not the right type.
1654   std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
1655
1656   /// This method looks up the specified field and
1657   /// returns its value as a vector of strings, throwing an exception if the
1658   /// field does not exist or if the value is not the right type.
1659   std::vector<StringRef> getValueAsListOfStrings(StringRef FieldName) const;
1660
1661   /// This method looks up the specified field and returns its
1662   /// value as a Record, throwing an exception if the field does not exist or if
1663   /// the value is not the right type.
1664   Record *getValueAsDef(StringRef FieldName) const;
1665
1666   /// This method looks up the specified field and returns its value as a
1667   /// Record, returning null if the field exists but is "uninitialized"
1668   /// (i.e. set to `?`), and throwing an exception if the field does not
1669   /// exist or if its value is not the right type.
1670   Record *getValueAsOptionalDef(StringRef FieldName) const;
1671
1672   /// This method looks up the specified field and returns its
1673   /// value as a bit, throwing an exception if the field does not exist or if
1674   /// the value is not the right type.
1675   bool getValueAsBit(StringRef FieldName) const;
1676
1677   /// This method looks up the specified field and
1678   /// returns its value as a bit. If the field is unset, sets Unset to true and
1679   /// returns false.
1680   bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
1681
1682   /// This method looks up the specified field and returns its
1683   /// value as an int64_t, throwing an exception if the field does not exist or
1684   /// if the value is not the right type.
1685   int64_t getValueAsInt(StringRef FieldName) const;
1686
1687   /// This method looks up the specified field and returns its
1688   /// value as an Dag, throwing an exception if the field does not exist or if
1689   /// the value is not the right type.
1690   DagInit *getValueAsDag(StringRef FieldName) const;
1691 };
1692
1693 raw_ostream &operator<<(raw_ostream &OS, const Record &R);
1694
1695 class RecordKeeper {
1696   friend class RecordRecTy;
1697   using RecordMap = std::map<std::string, std::unique_ptr<Record>, std::less<>>;
1698   RecordMap Classes, Defs;
1699   FoldingSet<RecordRecTy> RecordTypePool;
1700   std::map<std::string, Init *, std::less<>> ExtraGlobals;
1701   unsigned AnonCounter = 0;
1702
1703 public:
1704   const RecordMap &getClasses() const { return Classes; }
1705   const RecordMap &getDefs() const { return Defs; }
1706
1707   Record *getClass(StringRef Name) const {
1708     auto I = Classes.find(Name);
1709     return I == Classes.end() ? nullptr : I->second.get();
1710   }
1711
1712   Record *getDef(StringRef Name) const {
1713     auto I = Defs.find(Name);
1714     return I == Defs.end() ? nullptr : I->second.get();
1715   }
1716
1717   Init *getGlobal(StringRef Name) const {
1718     if (Record *R = getDef(Name))
1719       return R->getDefInit();
1720     auto It = ExtraGlobals.find(Name);
1721     return It == ExtraGlobals.end() ? nullptr : It->second;
1722   }
1723
1724   void addClass(std::unique_ptr<Record> R) {
1725     bool Ins = Classes.insert(std::make_pair(std::string(R->getName()),
1726                                              std::move(R))).second;
1727     (void)Ins;
1728     assert(Ins && "Class already exists");
1729   }
1730
1731   void addDef(std::unique_ptr<Record> R) {
1732     bool Ins = Defs.insert(std::make_pair(std::string(R->getName()),
1733                                           std::move(R))).second;
1734     (void)Ins;
1735     assert(Ins && "Record already exists");
1736   }
1737
1738   void addExtraGlobal(StringRef Name, Init *I) {
1739     bool Ins = ExtraGlobals.insert(std::make_pair(std::string(Name), I)).second;
1740     (void)Ins;
1741     assert(!getDef(Name));
1742     assert(Ins && "Global already exists");
1743   }
1744
1745   Init *getNewAnonymousName();
1746
1747   //===--------------------------------------------------------------------===//
1748   // High-level helper methods, useful for tablegen backends...
1749
1750   /// This method returns all concrete definitions
1751   /// that derive from the specified class name.  A class with the specified
1752   /// name must exist.
1753   std::vector<Record *> getAllDerivedDefinitions(StringRef ClassName) const;
1754
1755   void dump() const;
1756 };
1757
1758 /// Sorting predicate to sort record pointers by name.
1759 struct LessRecord {
1760   bool operator()(const Record *Rec1, const Record *Rec2) const {
1761     return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
1762   }
1763 };
1764
1765 /// Sorting predicate to sort record pointers by their
1766 /// unique ID. If you just need a deterministic order, use this, since it
1767 /// just compares two `unsigned`; the other sorting predicates require
1768 /// string manipulation.
1769 struct LessRecordByID {
1770   bool operator()(const Record *LHS, const Record *RHS) const {
1771     return LHS->getID() < RHS->getID();
1772   }
1773 };
1774
1775 /// Sorting predicate to sort record pointers by their
1776 /// name field.
1777 struct LessRecordFieldName {
1778   bool operator()(const Record *Rec1, const Record *Rec2) const {
1779     return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
1780   }
1781 };
1782
1783 struct LessRecordRegister {
1784   static bool ascii_isdigit(char x) { return x >= '0' && x <= '9'; }
1785
1786   struct RecordParts {
1787     SmallVector<std::pair< bool, StringRef>, 4> Parts;
1788
1789     RecordParts(StringRef Rec) {
1790       if (Rec.empty())
1791         return;
1792
1793       size_t Len = 0;
1794       const char *Start = Rec.data();
1795       const char *Curr = Start;
1796       bool isDigitPart = ascii_isdigit(Curr[0]);
1797       for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
1798         bool isDigit = ascii_isdigit(Curr[I]);
1799         if (isDigit != isDigitPart) {
1800           Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1801           Len = 0;
1802           Start = &Curr[I];
1803           isDigitPart = ascii_isdigit(Curr[I]);
1804         }
1805       }
1806       // Push the last part.
1807       Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1808     }
1809
1810     size_t size() { return Parts.size(); }
1811
1812     std::pair<bool, StringRef> getPart(size_t i) {
1813       assert (i < Parts.size() && "Invalid idx!");
1814       return Parts[i];
1815     }
1816   };
1817
1818   bool operator()(const Record *Rec1, const Record *Rec2) const {
1819     RecordParts LHSParts(StringRef(Rec1->getName()));
1820     RecordParts RHSParts(StringRef(Rec2->getName()));
1821
1822     size_t LHSNumParts = LHSParts.size();
1823     size_t RHSNumParts = RHSParts.size();
1824     assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
1825
1826     if (LHSNumParts != RHSNumParts)
1827       return LHSNumParts < RHSNumParts;
1828
1829     // We expect the registers to be of the form [_a-zA-Z]+([0-9]*[_a-zA-Z]*)*.
1830     for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
1831       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1832       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1833       // Expect even part to always be alpha.
1834       assert (LHSPart.first == false && RHSPart.first == false &&
1835               "Expected both parts to be alpha.");
1836       if (int Res = LHSPart.second.compare(RHSPart.second))
1837         return Res < 0;
1838     }
1839     for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
1840       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1841       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1842       // Expect odd part to always be numeric.
1843       assert (LHSPart.first == true && RHSPart.first == true &&
1844               "Expected both parts to be numeric.");
1845       if (LHSPart.second.size() != RHSPart.second.size())
1846         return LHSPart.second.size() < RHSPart.second.size();
1847
1848       unsigned LHSVal, RHSVal;
1849
1850       bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
1851       assert(!LHSFailed && "Unable to convert LHS to integer.");
1852       bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
1853       assert(!RHSFailed && "Unable to convert RHS to integer.");
1854
1855       if (LHSVal != RHSVal)
1856         return LHSVal < RHSVal;
1857     }
1858     return LHSNumParts < RHSNumParts;
1859   }
1860 };
1861
1862 raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
1863
1864 //===----------------------------------------------------------------------===//
1865 //  Resolvers
1866 //===----------------------------------------------------------------------===//
1867
1868 /// Interface for looking up the initializer for a variable name, used by
1869 /// Init::resolveReferences.
1870 class Resolver {
1871   Record *CurRec;
1872   bool IsFinal = false;
1873
1874 public:
1875   explicit Resolver(Record *CurRec) : CurRec(CurRec) {}
1876   virtual ~Resolver() {}
1877
1878   Record *getCurrentRecord() const { return CurRec; }
1879
1880   /// Return the initializer for the given variable name (should normally be a
1881   /// StringInit), or nullptr if the name could not be resolved.
1882   virtual Init *resolve(Init *VarName) = 0;
1883
1884   // Whether bits in a BitsInit should stay unresolved if resolving them would
1885   // result in a ? (UnsetInit). This behavior is used to represent instruction
1886   // encodings by keeping references to unset variables within a record.
1887   virtual bool keepUnsetBits() const { return false; }
1888
1889   // Whether this is the final resolve step before adding a record to the
1890   // RecordKeeper. Error reporting during resolve and related constant folding
1891   // should only happen when this is true.
1892   bool isFinal() const { return IsFinal; }
1893
1894   void setFinal(bool Final) { IsFinal = Final; }
1895 };
1896
1897 /// Resolve arbitrary mappings.
1898 class MapResolver final : public Resolver {
1899   struct MappedValue {
1900     Init *V;
1901     bool Resolved;
1902
1903     MappedValue() : V(nullptr), Resolved(false) {}
1904     MappedValue(Init *V, bool Resolved) : V(V), Resolved(Resolved) {}
1905   };
1906
1907   DenseMap<Init *, MappedValue> Map;
1908
1909 public:
1910   explicit MapResolver(Record *CurRec = nullptr) : Resolver(CurRec) {}
1911
1912   void set(Init *Key, Init *Value) { Map[Key] = {Value, false}; }
1913
1914   Init *resolve(Init *VarName) override;
1915 };
1916
1917 /// Resolve all variables from a record except for unset variables.
1918 class RecordResolver final : public Resolver {
1919   DenseMap<Init *, Init *> Cache;
1920   SmallVector<Init *, 4> Stack;
1921
1922 public:
1923   explicit RecordResolver(Record &R) : Resolver(&R) {}
1924
1925   Init *resolve(Init *VarName) override;
1926
1927   bool keepUnsetBits() const override { return true; }
1928 };
1929
1930 /// Resolve all references to a specific RecordVal.
1931 //
1932 // TODO: This is used for resolving references to template arguments, in a
1933 //       rather inefficient way. Change those uses to resolve all template
1934 //       arguments simultaneously and get rid of this class.
1935 class RecordValResolver final : public Resolver {
1936   const RecordVal *RV;
1937
1938 public:
1939   explicit RecordValResolver(Record &R, const RecordVal *RV)
1940       : Resolver(&R), RV(RV) {}
1941
1942   Init *resolve(Init *VarName) override {
1943     if (VarName == RV->getNameInit())
1944       return RV->getValue();
1945     return nullptr;
1946   }
1947 };
1948
1949 /// Delegate resolving to a sub-resolver, but shadow some variable names.
1950 class ShadowResolver final : public Resolver {
1951   Resolver &R;
1952   DenseSet<Init *> Shadowed;
1953
1954 public:
1955   explicit ShadowResolver(Resolver &R)
1956       : Resolver(R.getCurrentRecord()), R(R) {
1957     setFinal(R.isFinal());
1958   }
1959
1960   void addShadow(Init *Key) { Shadowed.insert(Key); }
1961
1962   Init *resolve(Init *VarName) override {
1963     if (Shadowed.count(VarName))
1964       return nullptr;
1965     return R.resolve(VarName);
1966   }
1967 };
1968
1969 /// (Optionally) delegate resolving to a sub-resolver, and keep track whether
1970 /// there were unresolved references.
1971 class TrackUnresolvedResolver final : public Resolver {
1972   Resolver *R;
1973   bool FoundUnresolved = false;
1974
1975 public:
1976   explicit TrackUnresolvedResolver(Resolver *R = nullptr)
1977       : Resolver(R ? R->getCurrentRecord() : nullptr), R(R) {}
1978
1979   bool foundUnresolved() const { return FoundUnresolved; }
1980
1981   Init *resolve(Init *VarName) override;
1982 };
1983
1984 /// Do not resolve anything, but keep track of whether a given variable was
1985 /// referenced.
1986 class HasReferenceResolver final : public Resolver {
1987   Init *VarNameToTrack;
1988   bool Found = false;
1989
1990 public:
1991   explicit HasReferenceResolver(Init *VarNameToTrack)
1992       : Resolver(nullptr), VarNameToTrack(VarNameToTrack) {}
1993
1994   bool found() const { return Found; }
1995
1996   Init *resolve(Init *VarName) override;
1997 };
1998
1999 void EmitJSON(RecordKeeper &RK, raw_ostream &OS);
2000
2001 } // end namespace llvm
2002
2003 #endif // LLVM_TABLEGEN_RECORD_H