[TableGen] Remove unnecessary include. NFC.
[oota-llvm.git] / include / llvm / TableGen / Record.h
1 //===- llvm/TableGen/Record.h - Classes for Table Records -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the main TableGen data structures, including the TableGen
11 // types, values, and high-level data structures.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_TABLEGEN_RECORD_H
16 #define LLVM_TABLEGEN_RECORD_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/DataTypes.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <map>
26
27 namespace llvm {
28
29 class ListRecTy;
30 struct MultiClass;
31 class Record;
32 class RecordVal;
33 class RecordKeeper;
34
35 //===----------------------------------------------------------------------===//
36 //  Type Classes
37 //===----------------------------------------------------------------------===//
38
39 class RecTy {
40 public:
41   /// \brief Subclass discriminator (for dyn_cast<> et al.)
42   enum RecTyKind {
43     BitRecTyKind,
44     BitsRecTyKind,
45     IntRecTyKind,
46     StringRecTyKind,
47     ListRecTyKind,
48     DagRecTyKind,
49     RecordRecTyKind
50   };
51
52 private:
53   RecTyKind Kind;
54   std::unique_ptr<ListRecTy> ListTy;
55
56 public:
57   RecTyKind getRecTyKind() const { return Kind; }
58
59   RecTy(RecTyKind K) : Kind(K) {}
60   virtual ~RecTy() {}
61
62   virtual std::string getAsString() const = 0;
63   void print(raw_ostream &OS) const { OS << getAsString(); }
64   void dump() const;
65
66   /// typeIsConvertibleTo - Return true if all values of 'this' type can be
67   /// converted to the specified type.
68   virtual bool typeIsConvertibleTo(const RecTy *RHS) const;
69
70   /// getListTy - Returns the type representing list<this>.
71   ListRecTy *getListTy();
72 };
73
74 inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) {
75   Ty.print(OS);
76   return OS;
77 }
78
79 /// BitRecTy - 'bit' - Represent a single bit
80 ///
81 class BitRecTy : public RecTy {
82   static BitRecTy Shared;
83   BitRecTy() : RecTy(BitRecTyKind) {}
84
85 public:
86   static bool classof(const RecTy *RT) {
87     return RT->getRecTyKind() == BitRecTyKind;
88   }
89
90   static BitRecTy *get() { return &Shared; }
91
92   std::string getAsString() const override { return "bit"; }
93
94   bool typeIsConvertibleTo(const RecTy *RHS) const override;
95 };
96
97 /// BitsRecTy - 'bits<n>' - Represent a fixed number of bits
98 ///
99 class BitsRecTy : public RecTy {
100   unsigned Size;
101   explicit BitsRecTy(unsigned Sz) : RecTy(BitsRecTyKind), Size(Sz) {}
102
103 public:
104   static bool classof(const RecTy *RT) {
105     return RT->getRecTyKind() == BitsRecTyKind;
106   }
107
108   static BitsRecTy *get(unsigned Sz);
109
110   unsigned getNumBits() const { return Size; }
111
112   std::string getAsString() const override;
113
114   bool typeIsConvertibleTo(const RecTy *RHS) const override;
115 };
116
117 /// IntRecTy - 'int' - Represent an integer value of no particular size
118 ///
119 class IntRecTy : public RecTy {
120   static IntRecTy Shared;
121   IntRecTy() : RecTy(IntRecTyKind) {}
122
123 public:
124   static bool classof(const RecTy *RT) {
125     return RT->getRecTyKind() == IntRecTyKind;
126   }
127
128   static IntRecTy *get() { return &Shared; }
129
130   std::string getAsString() const override { return "int"; }
131
132   bool typeIsConvertibleTo(const RecTy *RHS) const override;
133 };
134
135 /// StringRecTy - 'string' - Represent an string value
136 ///
137 class StringRecTy : public RecTy {
138   static StringRecTy Shared;
139   StringRecTy() : RecTy(StringRecTyKind) {}
140
141 public:
142   static bool classof(const RecTy *RT) {
143     return RT->getRecTyKind() == StringRecTyKind;
144   }
145
146   static StringRecTy *get() { return &Shared; }
147
148   std::string getAsString() const override;
149 };
150
151 /// ListRecTy - 'list<Ty>' - Represent a list of values, all of which must be of
152 /// the specified type.
153 ///
154 class ListRecTy : public RecTy {
155   RecTy *Ty;
156   explicit ListRecTy(RecTy *T) : RecTy(ListRecTyKind), Ty(T) {}
157   friend ListRecTy *RecTy::getListTy();
158
159 public:
160   static bool classof(const RecTy *RT) {
161     return RT->getRecTyKind() == ListRecTyKind;
162   }
163
164   static ListRecTy *get(RecTy *T) { return T->getListTy(); }
165   RecTy *getElementType() const { return Ty; }
166
167   std::string getAsString() const override;
168
169   bool typeIsConvertibleTo(const RecTy *RHS) const override;
170 };
171
172 /// DagRecTy - 'dag' - Represent a dag fragment
173 ///
174 class DagRecTy : public RecTy {
175   static DagRecTy Shared;
176   DagRecTy() : RecTy(DagRecTyKind) {}
177
178 public:
179   static bool classof(const RecTy *RT) {
180     return RT->getRecTyKind() == DagRecTyKind;
181   }
182
183   static DagRecTy *get() { return &Shared; }
184
185   std::string getAsString() const override;
186 };
187
188 /// RecordRecTy - '[classname]' - Represent an instance of a class, such as:
189 /// (R32 X = EAX).
190 ///
191 class RecordRecTy : public RecTy {
192   Record *Rec;
193   explicit RecordRecTy(Record *R) : RecTy(RecordRecTyKind), Rec(R) {}
194   friend class Record;
195
196 public:
197   static bool classof(const RecTy *RT) {
198     return RT->getRecTyKind() == RecordRecTyKind;
199   }
200
201   static RecordRecTy *get(Record *R);
202
203   Record *getRecord() const { return Rec; }
204
205   std::string getAsString() const override;
206
207   bool typeIsConvertibleTo(const RecTy *RHS) const override;
208 };
209
210 /// resolveTypes - Find a common type that T1 and T2 convert to.
211 /// Return 0 if no such type exists.
212 ///
213 RecTy *resolveTypes(RecTy *T1, RecTy *T2);
214
215 //===----------------------------------------------------------------------===//
216 //  Initializer Classes
217 //===----------------------------------------------------------------------===//
218
219 class Init {
220 protected:
221   /// \brief Discriminator enum (for isa<>, dyn_cast<>, et al.)
222   ///
223   /// This enum is laid out by a preorder traversal of the inheritance
224   /// hierarchy, and does not contain an entry for abstract classes, as per
225   /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst.
226   ///
227   /// We also explicitly include "first" and "last" values for each
228   /// interior node of the inheritance tree, to make it easier to read the
229   /// corresponding classof().
230   ///
231   /// We could pack these a bit tighter by not having the IK_FirstXXXInit
232   /// and IK_LastXXXInit be their own values, but that would degrade
233   /// readability for really no benefit.
234   enum InitKind {
235     IK_BitInit,
236     IK_FirstTypedInit,
237     IK_BitsInit,
238     IK_DagInit,
239     IK_DefInit,
240     IK_FieldInit,
241     IK_IntInit,
242     IK_ListInit,
243     IK_FirstOpInit,
244     IK_BinOpInit,
245     IK_TernOpInit,
246     IK_UnOpInit,
247     IK_LastOpInit,
248     IK_StringInit,
249     IK_VarInit,
250     IK_VarListElementInit,
251     IK_LastTypedInit,
252     IK_UnsetInit,
253     IK_VarBitInit
254   };
255
256 private:
257   const InitKind Kind;
258   Init(const Init &) = delete;
259   Init &operator=(const Init &) = delete;
260   virtual void anchor();
261
262 public:
263   InitKind getKind() const { return Kind; }
264
265 protected:
266   explicit Init(InitKind K) : Kind(K) {}
267
268 public:
269   virtual ~Init() {}
270
271   /// isComplete - This virtual method should be overridden by values that may
272   /// not be completely specified yet.
273   virtual bool isComplete() const { return true; }
274
275   /// print - Print out this value.
276   void print(raw_ostream &OS) const { OS << getAsString(); }
277
278   /// getAsString - Convert this value to a string form.
279   virtual std::string getAsString() const = 0;
280   /// getAsUnquotedString - Convert this value to a string form,
281   /// without adding quote markers.  This primaruly affects
282   /// StringInits where we will not surround the string value with
283   /// quotes.
284   virtual std::string getAsUnquotedString() const { return getAsString(); }
285
286   /// dump - Debugging method that may be called through a debugger, just
287   /// invokes print on stderr.
288   void dump() const;
289
290   /// convertInitializerTo - This virtual function converts to the appropriate
291   /// Init based on the passed in type.
292   virtual Init *convertInitializerTo(RecTy *Ty) const = 0;
293
294   /// convertInitializerBitRange - This method is used to implement the bitrange
295   /// selection operator.  Given an initializer, it selects the specified bits
296   /// out, returning them as a new init of bits type.  If it is not legal to use
297   /// the bit subscript operator on this initializer, return null.
298   ///
299   virtual Init *
300   convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
301     return nullptr;
302   }
303
304   /// convertInitListSlice - This method is used to implement the list slice
305   /// selection operator.  Given an initializer, it selects the specified list
306   /// elements, returning them as a new init of list type.  If it is not legal
307   /// to take a slice of this, return null.
308   ///
309   virtual Init *
310   convertInitListSlice(const std::vector<unsigned> &Elements) const {
311     return nullptr;
312   }
313
314   /// getFieldType - This method is used to implement the FieldInit class.
315   /// Implementors of this method should return the type of the named field if
316   /// they are of record type.
317   ///
318   virtual RecTy *getFieldType(const std::string &FieldName) const {
319     return nullptr;
320   }
321
322   /// getFieldInit - This method complements getFieldType to return the
323   /// initializer for the specified field.  If getFieldType returns non-null
324   /// this method should return non-null, otherwise it returns null.
325   ///
326   virtual Init *getFieldInit(Record &R, const RecordVal *RV,
327                              const std::string &FieldName) const {
328     return nullptr;
329   }
330
331   /// resolveReferences - This method is used by classes that refer to other
332   /// variables which may not be defined at the time the expression is formed.
333   /// If a value is set for the variable later, this method will be called on
334   /// users of the value to allow the value to propagate out.
335   ///
336   virtual Init *resolveReferences(Record &R, const RecordVal *RV) const {
337     return const_cast<Init *>(this);
338   }
339
340   /// getBit - This method is used to return the initializer for the specified
341   /// bit.
342   virtual Init *getBit(unsigned Bit) const = 0;
343
344   /// getBitVar - This method is used to retrieve the initializer for bit
345   /// reference. For non-VarBitInit, it simply returns itself.
346   virtual Init *getBitVar() const { return const_cast<Init*>(this); }
347
348   /// getBitNum - This method is used to retrieve the bit number of a bit
349   /// reference. For non-VarBitInit, it simply returns 0.
350   virtual unsigned getBitNum() const { return 0; }
351 };
352
353 inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) {
354   I.print(OS); return OS;
355 }
356
357 /// TypedInit - This is the common super-class of types that have a specific,
358 /// explicit, type.
359 ///
360 class TypedInit : public Init {
361   RecTy *Ty;
362
363   TypedInit(const TypedInit &Other) = delete;
364   TypedInit &operator=(const TypedInit &Other) = delete;
365
366 protected:
367   explicit TypedInit(InitKind K, RecTy *T) : Init(K), Ty(T) {}
368   ~TypedInit() {
369     // If this is a DefInit we need to delete the RecordRecTy.
370     if (getKind() == IK_DefInit)
371       delete Ty;
372   }
373
374 public:
375   static bool classof(const Init *I) {
376     return I->getKind() >= IK_FirstTypedInit &&
377            I->getKind() <= IK_LastTypedInit;
378   }
379   RecTy *getType() const { return Ty; }
380
381   Init *convertInitializerTo(RecTy *Ty) const override;
382
383   Init *
384   convertInitializerBitRange(const std::vector<unsigned> &Bits) const override;
385   Init *
386   convertInitListSlice(const std::vector<unsigned> &Elements) const override;
387
388   /// getFieldType - This method is used to implement the FieldInit class.
389   /// Implementors of this method should return the type of the named field if
390   /// they are of record type.
391   ///
392   RecTy *getFieldType(const std::string &FieldName) const override;
393
394   /// resolveListElementReference - This method is used to implement
395   /// VarListElementInit::resolveReferences.  If the list element is resolvable
396   /// now, we return the resolved value, otherwise we return null.
397   virtual Init *resolveListElementReference(Record &R, const RecordVal *RV,
398                                             unsigned Elt) const = 0;
399 };
400
401 /// UnsetInit - ? - Represents an uninitialized value
402 ///
403 class UnsetInit : public Init {
404   UnsetInit() : Init(IK_UnsetInit) {}
405   UnsetInit(const UnsetInit &) = delete;
406   UnsetInit &operator=(const UnsetInit &Other) = delete;
407
408 public:
409   static bool classof(const Init *I) {
410     return I->getKind() == IK_UnsetInit;
411   }
412   static UnsetInit *get();
413
414   Init *convertInitializerTo(RecTy *Ty) const override;
415
416   Init *getBit(unsigned Bit) const override {
417     return const_cast<UnsetInit*>(this);
418   }
419
420   bool isComplete() const override { return false; }
421   std::string getAsString() const override { return "?"; }
422 };
423
424 /// BitInit - true/false - Represent a concrete initializer for a bit.
425 ///
426 class BitInit : public Init {
427   bool Value;
428
429   explicit BitInit(bool V) : Init(IK_BitInit), Value(V) {}
430   BitInit(const BitInit &Other) = delete;
431   BitInit &operator=(BitInit &Other) = delete;
432
433 public:
434   static bool classof(const Init *I) {
435     return I->getKind() == IK_BitInit;
436   }
437   static BitInit *get(bool V);
438
439   bool getValue() const { return Value; }
440
441   Init *convertInitializerTo(RecTy *Ty) const override;
442
443   Init *getBit(unsigned Bit) const override {
444     assert(Bit < 1 && "Bit index out of range!");
445     return const_cast<BitInit*>(this);
446   }
447
448   std::string getAsString() const override { return Value ? "1" : "0"; }
449 };
450
451 /// BitsInit - { a, b, c } - Represents an initializer for a BitsRecTy value.
452 /// It contains a vector of bits, whose size is determined by the type.
453 ///
454 class BitsInit : public TypedInit, public FoldingSetNode {
455   std::vector<Init*> Bits;
456
457   BitsInit(ArrayRef<Init *> Range)
458     : TypedInit(IK_BitsInit, BitsRecTy::get(Range.size())),
459       Bits(Range.begin(), Range.end()) {}
460
461   BitsInit(const BitsInit &Other) = delete;
462   BitsInit &operator=(const BitsInit &Other) = delete;
463
464 public:
465   static bool classof(const Init *I) {
466     return I->getKind() == IK_BitsInit;
467   }
468   static BitsInit *get(ArrayRef<Init *> Range);
469
470   void Profile(FoldingSetNodeID &ID) const;
471
472   unsigned getNumBits() const { return Bits.size(); }
473
474   Init *convertInitializerTo(RecTy *Ty) const override;
475   Init *
476   convertInitializerBitRange(const std::vector<unsigned> &Bits) const override;
477
478   bool isComplete() const override {
479     for (unsigned i = 0; i != getNumBits(); ++i)
480       if (!getBit(i)->isComplete()) return false;
481     return true;
482   }
483   bool allInComplete() const {
484     for (unsigned i = 0; i != getNumBits(); ++i)
485       if (getBit(i)->isComplete()) return false;
486     return true;
487   }
488   std::string getAsString() const override;
489
490   /// resolveListElementReference - This method is used to implement
491   /// VarListElementInit::resolveReferences.  If the list element is resolvable
492   /// now, we return the resolved value, otherwise we return null.
493   Init *resolveListElementReference(Record &R, const RecordVal *RV,
494                                     unsigned Elt) const override {
495     llvm_unreachable("Illegal element reference off bits<n>");
496   }
497
498   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
499
500   Init *getBit(unsigned Bit) const override {
501     assert(Bit < Bits.size() && "Bit index out of range!");
502     return Bits[Bit];
503   }
504 };
505
506 /// IntInit - 7 - Represent an initialization by a literal integer value.
507 ///
508 class IntInit : public TypedInit {
509   int64_t Value;
510
511   explicit IntInit(int64_t V)
512     : TypedInit(IK_IntInit, IntRecTy::get()), Value(V) {}
513
514   IntInit(const IntInit &Other) = delete;
515   IntInit &operator=(const IntInit &Other) = delete;
516
517 public:
518   static bool classof(const Init *I) {
519     return I->getKind() == IK_IntInit;
520   }
521   static IntInit *get(int64_t V);
522
523   int64_t getValue() const { return Value; }
524
525   Init *convertInitializerTo(RecTy *Ty) const override;
526   Init *
527   convertInitializerBitRange(const std::vector<unsigned> &Bits) const override;
528
529   std::string getAsString() const override;
530
531   /// resolveListElementReference - This method is used to implement
532   /// VarListElementInit::resolveReferences.  If the list element is resolvable
533   /// now, we return the resolved value, otherwise we return null.
534   Init *resolveListElementReference(Record &R, const RecordVal *RV,
535                                     unsigned Elt) const override {
536     llvm_unreachable("Illegal element reference off int");
537   }
538
539   Init *getBit(unsigned Bit) const override {
540     return BitInit::get((Value & (1ULL << Bit)) != 0);
541   }
542 };
543
544 /// StringInit - "foo" - Represent an initialization by a string value.
545 ///
546 class StringInit : public TypedInit {
547   std::string Value;
548
549   explicit StringInit(const std::string &V)
550     : TypedInit(IK_StringInit, StringRecTy::get()), Value(V) {}
551
552   StringInit(const StringInit &Other) = delete;
553   StringInit &operator=(const StringInit &Other) = delete;
554
555 public:
556   static bool classof(const Init *I) {
557     return I->getKind() == IK_StringInit;
558   }
559   static StringInit *get(StringRef);
560
561   const std::string &getValue() const { return Value; }
562
563   Init *convertInitializerTo(RecTy *Ty) const override;
564
565   std::string getAsString() const override { return "\"" + Value + "\""; }
566   std::string getAsUnquotedString() const override { return Value; }
567
568   /// resolveListElementReference - This method is used to implement
569   /// VarListElementInit::resolveReferences.  If the list element is resolvable
570   /// now, we return the resolved value, otherwise we return null.
571   Init *resolveListElementReference(Record &R, const RecordVal *RV,
572                                     unsigned Elt) const override {
573     llvm_unreachable("Illegal element reference off string");
574   }
575
576   Init *getBit(unsigned Bit) const override {
577     llvm_unreachable("Illegal bit reference off string");
578   }
579 };
580
581 /// ListInit - [AL, AH, CL] - Represent a list of defs
582 ///
583 class ListInit : public TypedInit, public FoldingSetNode {
584   std::vector<Init*> Values;
585
586 public:
587   typedef std::vector<Init*>::const_iterator const_iterator;
588
589 private:
590   explicit ListInit(ArrayRef<Init *> Range, RecTy *EltTy)
591     : TypedInit(IK_ListInit, ListRecTy::get(EltTy)),
592       Values(Range.begin(), Range.end()) {}
593
594   ListInit(const ListInit &Other) = delete;
595   ListInit &operator=(const ListInit &Other) = delete;
596
597 public:
598   static bool classof(const Init *I) {
599     return I->getKind() == IK_ListInit;
600   }
601   static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy);
602
603   void Profile(FoldingSetNodeID &ID) const;
604
605   Init *getElement(unsigned i) const {
606     assert(i < Values.size() && "List element index out of range!");
607     return Values[i];
608   }
609
610   Record *getElementAsRecord(unsigned i) const;
611
612   Init *
613     convertInitListSlice(const std::vector<unsigned> &Elements) const override;
614
615   Init *convertInitializerTo(RecTy *Ty) const override;
616
617   /// resolveReferences - This method is used by classes that refer to other
618   /// variables which may not be defined at the time they expression is formed.
619   /// If a value is set for the variable later, this method will be called on
620   /// users of the value to allow the value to propagate out.
621   ///
622   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
623
624   std::string getAsString() const override;
625
626   ArrayRef<Init*> getValues() const { return Values; }
627
628   const_iterator begin() const { return Values.begin(); }
629   const_iterator end  () const { return Values.end();   }
630
631   size_t         size () const { return Values.size();  }
632   bool           empty() const { return Values.empty(); }
633
634   /// resolveListElementReference - This method is used to implement
635   /// VarListElementInit::resolveReferences.  If the list element is resolvable
636   /// now, we return the resolved value, otherwise we return null.
637   Init *resolveListElementReference(Record &R, const RecordVal *RV,
638                                     unsigned Elt) const override;
639
640   Init *getBit(unsigned Bit) const override {
641     llvm_unreachable("Illegal bit reference off list");
642   }
643 };
644
645 /// OpInit - Base class for operators
646 ///
647 class OpInit : public TypedInit {
648   OpInit(const OpInit &Other) = delete;
649   OpInit &operator=(OpInit &Other) = delete;
650
651 protected:
652   explicit OpInit(InitKind K, RecTy *Type) : TypedInit(K, Type) {}
653
654 public:
655   static bool classof(const Init *I) {
656     return I->getKind() >= IK_FirstOpInit &&
657            I->getKind() <= IK_LastOpInit;
658   }
659   // Clone - Clone this operator, replacing arguments with the new list
660   virtual OpInit *clone(std::vector<Init *> &Operands) const = 0;
661
662   virtual unsigned getNumOperands() const = 0;
663   virtual Init *getOperand(unsigned i) const = 0;
664
665   // Fold - If possible, fold this to a simpler init.  Return this if not
666   // possible to fold.
667   virtual Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const = 0;
668
669   Init *resolveListElementReference(Record &R, const RecordVal *RV,
670                                     unsigned Elt) const override;
671
672   Init *getBit(unsigned Bit) const override;
673 };
674
675 /// UnOpInit - !op (X) - Transform an init.
676 ///
677 class UnOpInit : public OpInit {
678 public:
679   enum UnaryOp { CAST, HEAD, TAIL, EMPTY };
680
681 private:
682   UnaryOp Opc;
683   Init *LHS;
684
685   UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
686     : OpInit(IK_UnOpInit, Type), Opc(opc), LHS(lhs) {}
687
688   UnOpInit(const UnOpInit &Other) = delete;
689   UnOpInit &operator=(const UnOpInit &Other) = delete;
690
691 public:
692   static bool classof(const Init *I) {
693     return I->getKind() == IK_UnOpInit;
694   }
695   static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
696
697   // Clone - Clone this operator, replacing arguments with the new list
698   OpInit *clone(std::vector<Init *> &Operands) const override {
699     assert(Operands.size() == 1 &&
700            "Wrong number of operands for unary operation");
701     return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
702   }
703
704   unsigned getNumOperands() const override { return 1; }
705   Init *getOperand(unsigned i) const override {
706     assert(i == 0 && "Invalid operand id for unary operator");
707     return getOperand();
708   }
709
710   UnaryOp getOpcode() const { return Opc; }
711   Init *getOperand() const { return LHS; }
712
713   // Fold - If possible, fold this to a simpler init.  Return this if not
714   // possible to fold.
715   Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
716
717   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
718
719   std::string getAsString() const override;
720 };
721
722 /// BinOpInit - !op (X, Y) - Combine two inits.
723 ///
724 class BinOpInit : public OpInit {
725 public:
726   enum BinaryOp { ADD, AND, SHL, SRA, SRL, LISTCONCAT, STRCONCAT, CONCAT, EQ };
727
728 private:
729   BinaryOp Opc;
730   Init *LHS, *RHS;
731
732   BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) :
733       OpInit(IK_BinOpInit, Type), Opc(opc), LHS(lhs), RHS(rhs) {}
734
735   BinOpInit(const BinOpInit &Other) = delete;
736   BinOpInit &operator=(const BinOpInit &Other) = delete;
737
738 public:
739   static bool classof(const Init *I) {
740     return I->getKind() == IK_BinOpInit;
741   }
742   static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs,
743                         RecTy *Type);
744
745   // Clone - Clone this operator, replacing arguments with the new list
746   OpInit *clone(std::vector<Init *> &Operands) const override {
747     assert(Operands.size() == 2 &&
748            "Wrong number of operands for binary operation");
749     return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType());
750   }
751
752   unsigned getNumOperands() const override { return 2; }
753   Init *getOperand(unsigned i) const override {
754     switch (i) {
755     default: llvm_unreachable("Invalid operand id for binary operator");
756     case 0: return getLHS();
757     case 1: return getRHS();
758     }
759   }
760
761   BinaryOp getOpcode() const { return Opc; }
762   Init *getLHS() const { return LHS; }
763   Init *getRHS() const { return RHS; }
764
765   // Fold - If possible, fold this to a simpler init.  Return this if not
766   // possible to fold.
767   Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
768
769   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
770
771   std::string getAsString() const override;
772 };
773
774 /// TernOpInit - !op (X, Y, Z) - Combine two inits.
775 ///
776 class TernOpInit : public OpInit {
777 public:
778   enum TernaryOp { SUBST, FOREACH, IF };
779
780 private:
781   TernaryOp Opc;
782   Init *LHS, *MHS, *RHS;
783
784   TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
785              RecTy *Type) :
786       OpInit(IK_TernOpInit, Type), Opc(opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
787
788   TernOpInit(const TernOpInit &Other) = delete;
789   TernOpInit &operator=(const TernOpInit &Other) = delete;
790
791 public:
792   static bool classof(const Init *I) {
793     return I->getKind() == IK_TernOpInit;
794   }
795   static TernOpInit *get(TernaryOp opc, Init *lhs,
796                          Init *mhs, Init *rhs,
797                          RecTy *Type);
798
799   // Clone - Clone this operator, replacing arguments with the new list
800   OpInit *clone(std::vector<Init *> &Operands) const override {
801     assert(Operands.size() == 3 &&
802            "Wrong number of operands for ternary operation");
803     return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
804                            getType());
805   }
806
807   unsigned getNumOperands() const override { return 3; }
808   Init *getOperand(unsigned i) const override {
809     switch (i) {
810     default: llvm_unreachable("Invalid operand id for ternary operator");
811     case 0: return getLHS();
812     case 1: return getMHS();
813     case 2: return getRHS();
814     }
815   }
816
817   TernaryOp getOpcode() const { return Opc; }
818   Init *getLHS() const { return LHS; }
819   Init *getMHS() const { return MHS; }
820   Init *getRHS() const { return RHS; }
821
822   // Fold - If possible, fold this to a simpler init.  Return this if not
823   // possible to fold.
824   Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
825
826   bool isComplete() const override { return false; }
827
828   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
829
830   std::string getAsString() const override;
831 };
832
833 /// VarInit - 'Opcode' - Represent a reference to an entire variable object.
834 ///
835 class VarInit : public TypedInit {
836   Init *VarName;
837
838   explicit VarInit(const std::string &VN, RecTy *T)
839       : TypedInit(IK_VarInit, T), VarName(StringInit::get(VN)) {}
840   explicit VarInit(Init *VN, RecTy *T)
841       : TypedInit(IK_VarInit, T), VarName(VN) {}
842
843   VarInit(const VarInit &Other) = delete;
844   VarInit &operator=(const VarInit &Other) = delete;
845
846 public:
847   static bool classof(const Init *I) {
848     return I->getKind() == IK_VarInit;
849   }
850   static VarInit *get(const std::string &VN, RecTy *T);
851   static VarInit *get(Init *VN, RecTy *T);
852
853   const std::string &getName() const;
854   Init *getNameInit() const { return VarName; }
855   std::string getNameInitAsString() const {
856     return getNameInit()->getAsUnquotedString();
857   }
858
859   Init *resolveListElementReference(Record &R, const RecordVal *RV,
860                                     unsigned Elt) const override;
861
862   RecTy *getFieldType(const std::string &FieldName) const override;
863   Init *getFieldInit(Record &R, const RecordVal *RV,
864                      const std::string &FieldName) const override;
865
866   /// resolveReferences - This method is used by classes that refer to other
867   /// variables which may not be defined at the time they expression is formed.
868   /// If a value is set for the variable later, this method will be called on
869   /// users of the value to allow the value to propagate out.
870   ///
871   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
872
873   Init *getBit(unsigned Bit) const override;
874
875   std::string getAsString() const override { return getName(); }
876 };
877
878 /// VarBitInit - Opcode{0} - Represent access to one bit of a variable or field.
879 ///
880 class VarBitInit : public Init {
881   TypedInit *TI;
882   unsigned Bit;
883
884   VarBitInit(TypedInit *T, unsigned B) : Init(IK_VarBitInit), TI(T), Bit(B) {
885     assert(T->getType() &&
886            (isa<IntRecTy>(T->getType()) ||
887             (isa<BitsRecTy>(T->getType()) &&
888              cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&
889            "Illegal VarBitInit expression!");
890   }
891
892   VarBitInit(const VarBitInit &Other) = delete;
893   VarBitInit &operator=(const VarBitInit &Other) = delete;
894
895 public:
896   static bool classof(const Init *I) {
897     return I->getKind() == IK_VarBitInit;
898   }
899   static VarBitInit *get(TypedInit *T, unsigned B);
900
901   Init *convertInitializerTo(RecTy *Ty) const override;
902
903   Init *getBitVar() const override { return TI; }
904   unsigned getBitNum() const override { return Bit; }
905
906   std::string getAsString() const override;
907   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
908
909   Init *getBit(unsigned B) const override {
910     assert(B < 1 && "Bit index out of range!");
911     return const_cast<VarBitInit*>(this);
912   }
913 };
914
915 /// VarListElementInit - List[4] - Represent access to one element of a var or
916 /// field.
917 class VarListElementInit : public TypedInit {
918   TypedInit *TI;
919   unsigned Element;
920
921   VarListElementInit(TypedInit *T, unsigned E)
922       : TypedInit(IK_VarListElementInit,
923                   cast<ListRecTy>(T->getType())->getElementType()),
924         TI(T), Element(E) {
925     assert(T->getType() && isa<ListRecTy>(T->getType()) &&
926            "Illegal VarBitInit expression!");
927   }
928
929   VarListElementInit(const VarListElementInit &Other) = delete;
930   void operator=(const VarListElementInit &Other) = delete;
931
932 public:
933   static bool classof(const Init *I) {
934     return I->getKind() == IK_VarListElementInit;
935   }
936   static VarListElementInit *get(TypedInit *T, unsigned E);
937
938   TypedInit *getVariable() const { return TI; }
939   unsigned getElementNum() const { return Element; }
940
941   /// resolveListElementReference - This method is used to implement
942   /// VarListElementInit::resolveReferences.  If the list element is resolvable
943   /// now, we return the resolved value, otherwise we return null.
944   Init *resolveListElementReference(Record &R, const RecordVal *RV,
945                                     unsigned Elt) const override;
946
947   std::string getAsString() const override;
948   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
949
950   Init *getBit(unsigned Bit) const override;
951 };
952
953 /// DefInit - AL - Represent a reference to a 'def' in the description
954 ///
955 class DefInit : public TypedInit {
956   Record *Def;
957
958   DefInit(Record *D, RecordRecTy *T) : TypedInit(IK_DefInit, T), Def(D) {}
959   friend class Record;
960
961   DefInit(const DefInit &Other) = delete;
962   DefInit &operator=(const DefInit &Other) = delete;
963
964 public:
965   static bool classof(const Init *I) {
966     return I->getKind() == IK_DefInit;
967   }
968   static DefInit *get(Record*);
969
970   Init *convertInitializerTo(RecTy *Ty) const override;
971
972   Record *getDef() const { return Def; }
973
974   //virtual Init *convertInitializerBitRange(const std::vector<unsigned> &Bits);
975
976   RecTy *getFieldType(const std::string &FieldName) const override;
977   Init *getFieldInit(Record &R, const RecordVal *RV,
978                      const std::string &FieldName) const override;
979
980   std::string getAsString() const override;
981
982   Init *getBit(unsigned Bit) const override {
983     llvm_unreachable("Illegal bit reference off def");
984   }
985
986   /// resolveListElementReference - This method is used to implement
987   /// VarListElementInit::resolveReferences.  If the list element is resolvable
988   /// now, we return the resolved value, otherwise we return null.
989   Init *resolveListElementReference(Record &R, const RecordVal *RV,
990                                     unsigned Elt) const override {
991     llvm_unreachable("Illegal element reference off def");
992   }
993 };
994
995 /// FieldInit - X.Y - Represent a reference to a subfield of a variable
996 ///
997 class FieldInit : public TypedInit {
998   Init *Rec;                // Record we are referring to
999   std::string FieldName;    // Field we are accessing
1000
1001   FieldInit(Init *R, const std::string &FN)
1002       : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
1003     assert(getType() && "FieldInit with non-record type!");
1004   }
1005
1006   FieldInit(const FieldInit &Other) = delete;
1007   FieldInit &operator=(const FieldInit &Other) = delete;
1008
1009 public:
1010   static bool classof(const Init *I) {
1011     return I->getKind() == IK_FieldInit;
1012   }
1013   static FieldInit *get(Init *R, const std::string &FN);
1014   static FieldInit *get(Init *R, const Init *FN);
1015
1016   Init *getBit(unsigned Bit) const override;
1017
1018   Init *resolveListElementReference(Record &R, const RecordVal *RV,
1019                                     unsigned Elt) const override;
1020
1021   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1022
1023   std::string getAsString() const override {
1024     return Rec->getAsString() + "." + FieldName;
1025   }
1026 };
1027
1028 /// DagInit - (v a, b) - Represent a DAG tree value.  DAG inits are required
1029 /// to have at least one value then a (possibly empty) list of arguments.  Each
1030 /// argument can have a name associated with it.
1031 ///
1032 class DagInit : public TypedInit, public FoldingSetNode {
1033   Init *Val;
1034   std::string ValName;
1035   std::vector<Init*> Args;
1036   std::vector<std::string> ArgNames;
1037
1038   DagInit(Init *V, const std::string &VN,
1039           ArrayRef<Init *> ArgRange,
1040           ArrayRef<std::string> NameRange)
1041       : TypedInit(IK_DagInit, DagRecTy::get()), Val(V), ValName(VN),
1042           Args(ArgRange.begin(), ArgRange.end()),
1043           ArgNames(NameRange.begin(), NameRange.end()) {}
1044
1045   DagInit(const DagInit &Other) = delete;
1046   DagInit &operator=(const DagInit &Other) = delete;
1047
1048 public:
1049   static bool classof(const Init *I) {
1050     return I->getKind() == IK_DagInit;
1051   }
1052   static DagInit *get(Init *V, const std::string &VN,
1053                       ArrayRef<Init *> ArgRange,
1054                       ArrayRef<std::string> NameRange);
1055   static DagInit *get(Init *V, const std::string &VN,
1056                       const std::vector<
1057                         std::pair<Init*, std::string> > &args);
1058
1059   void Profile(FoldingSetNodeID &ID) const;
1060
1061   Init *convertInitializerTo(RecTy *Ty) const override;
1062
1063   Init *getOperator() const { return Val; }
1064
1065   const std::string &getName() const { return ValName; }
1066
1067   unsigned getNumArgs() const { return Args.size(); }
1068   Init *getArg(unsigned Num) const {
1069     assert(Num < Args.size() && "Arg number out of range!");
1070     return Args[Num];
1071   }
1072   const std::string &getArgName(unsigned Num) const {
1073     assert(Num < ArgNames.size() && "Arg number out of range!");
1074     return ArgNames[Num];
1075   }
1076
1077   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1078
1079   std::string getAsString() const override;
1080
1081   typedef std::vector<Init*>::const_iterator       const_arg_iterator;
1082   typedef std::vector<std::string>::const_iterator const_name_iterator;
1083
1084   inline const_arg_iterator  arg_begin() const { return Args.begin(); }
1085   inline const_arg_iterator  arg_end  () const { return Args.end();   }
1086
1087   inline size_t              arg_size () const { return Args.size();  }
1088   inline bool                arg_empty() const { return Args.empty(); }
1089
1090   inline const_name_iterator name_begin() const { return ArgNames.begin(); }
1091   inline const_name_iterator name_end  () const { return ArgNames.end();   }
1092
1093   inline size_t              name_size () const { return ArgNames.size();  }
1094   inline bool                name_empty() const { return ArgNames.empty(); }
1095
1096   Init *getBit(unsigned Bit) const override {
1097     llvm_unreachable("Illegal bit reference off dag");
1098   }
1099
1100   Init *resolveListElementReference(Record &R, const RecordVal *RV,
1101                                     unsigned Elt) const override {
1102     llvm_unreachable("Illegal element reference off dag");
1103   }
1104 };
1105
1106 //===----------------------------------------------------------------------===//
1107 //  High-Level Classes
1108 //===----------------------------------------------------------------------===//
1109
1110 class RecordVal {
1111   PointerIntPair<Init *, 1, bool> NameAndPrefix;
1112   RecTy *Ty;
1113   Init *Value;
1114
1115 public:
1116   RecordVal(Init *N, RecTy *T, bool P);
1117   RecordVal(const std::string &N, RecTy *T, bool P);
1118
1119   const std::string &getName() const;
1120   const Init *getNameInit() const { return NameAndPrefix.getPointer(); }
1121   std::string getNameInitAsString() const {
1122     return getNameInit()->getAsUnquotedString();
1123   }
1124
1125   bool getPrefix() const { return NameAndPrefix.getInt(); }
1126   RecTy *getType() const { return Ty; }
1127   Init *getValue() const { return Value; }
1128
1129   bool setValue(Init *V) {
1130     if (V) {
1131       Value = V->convertInitializerTo(Ty);
1132       return Value == nullptr;
1133     }
1134     Value = nullptr;
1135     return false;
1136   }
1137
1138   void dump() const;
1139   void print(raw_ostream &OS, bool PrintSem = true) const;
1140 };
1141
1142 inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
1143   RV.print(OS << "  ");
1144   return OS;
1145 }
1146
1147 class Record {
1148   static unsigned LastID;
1149
1150   // Unique record ID.
1151   unsigned ID;
1152   Init *Name;
1153   // Location where record was instantiated, followed by the location of
1154   // multiclass prototypes used.
1155   SmallVector<SMLoc, 4> Locs;
1156   std::vector<Init *> TemplateArgs;
1157   std::vector<RecordVal> Values;
1158   std::vector<Record *> SuperClasses;
1159   std::vector<SMRange> SuperClassRanges;
1160
1161   // Tracks Record instances. Not owned by Record.
1162   RecordKeeper &TrackedRecords;
1163
1164   DefInit *TheInit;
1165   bool IsAnonymous;
1166
1167   // Class-instance values can be used by other defs.  For example, Struct<i>
1168   // is used here as a template argument to another class:
1169   //
1170   //   multiclass MultiClass<int i> {
1171   //     def Def : Class<Struct<i>>;
1172   //
1173   // These need to get fully resolved before instantiating any other
1174   // definitions that use them (e.g. Def).  However, inside a multiclass they
1175   // can't be immediately resolved so we mark them ResolveFirst to fully
1176   // resolve them later as soon as the multiclass is instantiated.
1177   bool ResolveFirst;
1178
1179   void init();
1180   void checkName();
1181
1182 public:
1183   // Constructs a record.
1184   explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1185                   bool Anonymous = false) :
1186     ID(LastID++), Name(N), Locs(locs.begin(), locs.end()),
1187     TrackedRecords(records), TheInit(nullptr), IsAnonymous(Anonymous),
1188     ResolveFirst(false) {
1189     init();
1190   }
1191   explicit Record(const std::string &N, ArrayRef<SMLoc> locs,
1192                   RecordKeeper &records, bool Anonymous = false)
1193     : Record(StringInit::get(N), locs, records, Anonymous) {}
1194
1195
1196   // When copy-constructing a Record, we must still guarantee a globally unique
1197   // ID number.  All other fields can be copied normally.
1198   Record(const Record &O) :
1199     ID(LastID++), Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
1200     Values(O.Values), SuperClasses(O.SuperClasses),
1201     SuperClassRanges(O.SuperClassRanges), TrackedRecords(O.TrackedRecords),
1202     TheInit(O.TheInit), IsAnonymous(O.IsAnonymous),
1203     ResolveFirst(O.ResolveFirst) { }
1204
1205   static unsigned getNewUID() { return LastID++; }
1206
1207   unsigned getID() const { return ID; }
1208
1209   const std::string &getName() const;
1210   Init *getNameInit() const {
1211     return Name;
1212   }
1213   const std::string getNameInitAsString() const {
1214     return getNameInit()->getAsUnquotedString();
1215   }
1216
1217   void setName(Init *Name);               // Also updates RecordKeeper.
1218   void setName(const std::string &Name);  // Also updates RecordKeeper.
1219
1220   ArrayRef<SMLoc> getLoc() const { return Locs; }
1221
1222   /// get the corresponding DefInit.
1223   DefInit *getDefInit();
1224
1225   const std::vector<Init *> &getTemplateArgs() const {
1226     return TemplateArgs;
1227   }
1228   const std::vector<RecordVal> &getValues() const { return Values; }
1229   const std::vector<Record*>   &getSuperClasses() const { return SuperClasses; }
1230   ArrayRef<SMRange> getSuperClassRanges() const { return SuperClassRanges; }
1231
1232   bool isTemplateArg(Init *Name) const {
1233     for (Init *TA : TemplateArgs)
1234       if (TA == Name) return true;
1235     return false;
1236   }
1237   bool isTemplateArg(StringRef Name) const {
1238     return isTemplateArg(StringInit::get(Name));
1239   }
1240
1241   const RecordVal *getValue(const Init *Name) const {
1242     for (const RecordVal &Val : Values)
1243       if (Val.getNameInit() == Name) return &Val;
1244     return nullptr;
1245   }
1246   const RecordVal *getValue(StringRef Name) const {
1247     return getValue(StringInit::get(Name));
1248   }
1249   RecordVal *getValue(const Init *Name) {
1250     for (RecordVal &Val : Values)
1251       if (Val.getNameInit() == Name) return &Val;
1252     return nullptr;
1253   }
1254   RecordVal *getValue(StringRef Name) {
1255     return getValue(StringInit::get(Name));
1256   }
1257
1258   void addTemplateArg(Init *Name) {
1259     assert(!isTemplateArg(Name) && "Template arg already defined!");
1260     TemplateArgs.push_back(Name);
1261   }
1262   void addTemplateArg(StringRef Name) {
1263     addTemplateArg(StringInit::get(Name));
1264   }
1265
1266   void addValue(const RecordVal &RV) {
1267     assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
1268     Values.push_back(RV);
1269     if (Values.size() > 1)
1270       // Keep NAME at the end of the list.  It makes record dumps a
1271       // bit prettier and allows TableGen tests to be written more
1272       // naturally.  Tests can use CHECK-NEXT to look for Record
1273       // fields they expect to see after a def.  They can't do that if
1274       // NAME is the first Record field.
1275       std::swap(Values[Values.size() - 2], Values[Values.size() - 1]);
1276   }
1277
1278   void removeValue(Init *Name) {
1279     for (unsigned i = 0, e = Values.size(); i != e; ++i)
1280       if (Values[i].getNameInit() == Name) {
1281         Values.erase(Values.begin()+i);
1282         return;
1283       }
1284     llvm_unreachable("Cannot remove an entry that does not exist!");
1285   }
1286
1287   void removeValue(StringRef Name) {
1288     removeValue(StringInit::get(Name));
1289   }
1290
1291   bool isSubClassOf(const Record *R) const {
1292     for (const Record *SC : SuperClasses)
1293       if (SC == R)
1294         return true;
1295     return false;
1296   }
1297
1298   bool isSubClassOf(StringRef Name) const {
1299     for (const Record *SC : SuperClasses)
1300       if (SC->getNameInitAsString() == Name)
1301         return true;
1302     return false;
1303   }
1304
1305   void addSuperClass(Record *R, SMRange Range) {
1306     assert(!isSubClassOf(R) && "Already subclassing record!");
1307     SuperClasses.push_back(R);
1308     SuperClassRanges.push_back(Range);
1309   }
1310
1311   /// resolveReferences - If there are any field references that refer to fields
1312   /// that have been filled in, we can propagate the values now.
1313   ///
1314   void resolveReferences() { resolveReferencesTo(nullptr); }
1315
1316   /// resolveReferencesTo - If anything in this record refers to RV, replace the
1317   /// reference to RV with the RHS of RV.  If RV is null, we resolve all
1318   /// possible references.
1319   void resolveReferencesTo(const RecordVal *RV);
1320
1321   RecordKeeper &getRecords() const {
1322     return TrackedRecords;
1323   }
1324
1325   bool isAnonymous() const {
1326     return IsAnonymous;
1327   }
1328
1329   bool isResolveFirst() const {
1330     return ResolveFirst;
1331   }
1332
1333   void setResolveFirst(bool b) {
1334     ResolveFirst = b;
1335   }
1336
1337   void dump() const;
1338
1339   //===--------------------------------------------------------------------===//
1340   // High-level methods useful to tablegen back-ends
1341   //
1342
1343   /// getValueInit - Return the initializer for a value with the specified name,
1344   /// or throw an exception if the field does not exist.
1345   ///
1346   Init *getValueInit(StringRef FieldName) const;
1347
1348   /// Return true if the named field is unset.
1349   bool isValueUnset(StringRef FieldName) const {
1350     return isa<UnsetInit>(getValueInit(FieldName));
1351   }
1352
1353   /// getValueAsString - This method looks up the specified field and returns
1354   /// its value as a string, throwing an exception if the field does not exist
1355   /// or if the value is not a string.
1356   ///
1357   std::string getValueAsString(StringRef FieldName) const;
1358
1359   /// getValueAsBitsInit - This method looks up the specified field and returns
1360   /// its value as a BitsInit, throwing an exception if the field does not exist
1361   /// or if the value is not the right type.
1362   ///
1363   BitsInit *getValueAsBitsInit(StringRef FieldName) const;
1364
1365   /// getValueAsListInit - This method looks up the specified field and returns
1366   /// its value as a ListInit, throwing an exception if the field does not exist
1367   /// or if the value is not the right type.
1368   ///
1369   ListInit *getValueAsListInit(StringRef FieldName) const;
1370
1371   /// getValueAsListOfDefs - This method looks up the specified field and
1372   /// returns its value as a vector of records, throwing an exception if the
1373   /// field does not exist or if the value is not the right type.
1374   ///
1375   std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
1376
1377   /// getValueAsListOfInts - This method looks up the specified field and
1378   /// returns its value as a vector of integers, throwing an exception if the
1379   /// field does not exist or if the value is not the right type.
1380   ///
1381   std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
1382
1383   /// getValueAsListOfStrings - This method looks up the specified field and
1384   /// returns its value as a vector of strings, throwing an exception if the
1385   /// field does not exist or if the value is not the right type.
1386   ///
1387   std::vector<std::string> getValueAsListOfStrings(StringRef FieldName) const;
1388
1389   /// getValueAsDef - This method looks up the specified field and returns its
1390   /// value as a Record, throwing an exception if the field does not exist or if
1391   /// the value is not the right type.
1392   ///
1393   Record *getValueAsDef(StringRef FieldName) const;
1394
1395   /// getValueAsBit - This method looks up the specified field and returns its
1396   /// value as a bit, throwing an exception if the field does not exist or if
1397   /// the value is not the right type.
1398   ///
1399   bool getValueAsBit(StringRef FieldName) const;
1400
1401   /// getValueAsBitOrUnset - This method looks up the specified field and
1402   /// returns its value as a bit. If the field is unset, sets Unset to true and
1403   /// returns false.
1404   ///
1405   bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
1406
1407   /// getValueAsInt - This method looks up the specified field and returns its
1408   /// value as an int64_t, throwing an exception if the field does not exist or
1409   /// if the value is not the right type.
1410   ///
1411   int64_t getValueAsInt(StringRef FieldName) const;
1412
1413   /// getValueAsDag - This method looks up the specified field and returns its
1414   /// value as an Dag, throwing an exception if the field does not exist or if
1415   /// the value is not the right type.
1416   ///
1417   DagInit *getValueAsDag(StringRef FieldName) const;
1418 };
1419
1420 raw_ostream &operator<<(raw_ostream &OS, const Record &R);
1421
1422 struct MultiClass {
1423   Record Rec;  // Placeholder for template args and Name.
1424   typedef std::vector<std::unique_ptr<Record>> RecordVector;
1425   RecordVector DefPrototypes;
1426
1427   void dump() const;
1428
1429   MultiClass(const std::string &Name, SMLoc Loc, RecordKeeper &Records) :
1430     Rec(Name, Loc, Records) {}
1431 };
1432
1433 class RecordKeeper {
1434   typedef std::map<std::string, std::unique_ptr<Record>> RecordMap;
1435   RecordMap Classes, Defs;
1436
1437 public:
1438   const RecordMap &getClasses() const { return Classes; }
1439   const RecordMap &getDefs() const { return Defs; }
1440
1441   Record *getClass(const std::string &Name) const {
1442     auto I = Classes.find(Name);
1443     return I == Classes.end() ? nullptr : I->second.get();
1444   }
1445   Record *getDef(const std::string &Name) const {
1446     auto I = Defs.find(Name);
1447     return I == Defs.end() ? nullptr : I->second.get();
1448   }
1449   void addClass(std::unique_ptr<Record> R) {
1450     bool Ins = Classes.insert(std::make_pair(R->getName(),
1451                                              std::move(R))).second;
1452     (void)Ins;
1453     assert(Ins && "Class already exists");
1454   }
1455   void addDef(std::unique_ptr<Record> R) {
1456     bool Ins = Defs.insert(std::make_pair(R->getName(),
1457                                           std::move(R))).second;
1458     (void)Ins;
1459     assert(Ins && "Record already exists");
1460   }
1461
1462   //===--------------------------------------------------------------------===//
1463   // High-level helper methods, useful for tablegen backends...
1464
1465   /// getAllDerivedDefinitions - This method returns all concrete definitions
1466   /// that derive from the specified class name.  If a class with the specified
1467   /// name does not exist, an exception is thrown.
1468   std::vector<Record*>
1469   getAllDerivedDefinitions(const std::string &ClassName) const;
1470
1471   void dump() const;
1472 };
1473
1474 /// LessRecord - Sorting predicate to sort record pointers by name.
1475 ///
1476 struct LessRecord {
1477   bool operator()(const Record *Rec1, const Record *Rec2) const {
1478     return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
1479   }
1480 };
1481
1482 /// LessRecordByID - Sorting predicate to sort record pointers by their
1483 /// unique ID. If you just need a deterministic order, use this, since it
1484 /// just compares two `unsigned`; the other sorting predicates require
1485 /// string manipulation.
1486 struct LessRecordByID {
1487   bool operator()(const Record *LHS, const Record *RHS) const {
1488     return LHS->getID() < RHS->getID();
1489   }
1490 };
1491
1492 /// LessRecordFieldName - Sorting predicate to sort record pointers by their
1493 /// name field.
1494 ///
1495 struct LessRecordFieldName {
1496   bool operator()(const Record *Rec1, const Record *Rec2) const {
1497     return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
1498   }
1499 };
1500
1501 struct LessRecordRegister {
1502   static bool ascii_isdigit(char x) { return x >= '0' && x <= '9'; }
1503
1504   struct RecordParts {
1505     SmallVector<std::pair< bool, StringRef>, 4> Parts;
1506
1507     RecordParts(StringRef Rec) {
1508       if (Rec.empty())
1509         return;
1510
1511       size_t Len = 0;
1512       const char *Start = Rec.data();
1513       const char *Curr = Start;
1514       bool isDigitPart = ascii_isdigit(Curr[0]);
1515       for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
1516         bool isDigit = ascii_isdigit(Curr[I]);
1517         if (isDigit != isDigitPart) {
1518           Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1519           Len = 0;
1520           Start = &Curr[I];
1521           isDigitPart = ascii_isdigit(Curr[I]);
1522         }
1523       }
1524       // Push the last part.
1525       Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1526     }
1527
1528     size_t size() { return Parts.size(); }
1529
1530     std::pair<bool, StringRef> getPart(size_t i) {
1531       assert (i < Parts.size() && "Invalid idx!");
1532       return Parts[i];
1533     }
1534   };
1535
1536   bool operator()(const Record *Rec1, const Record *Rec2) const {
1537     RecordParts LHSParts(StringRef(Rec1->getName()));
1538     RecordParts RHSParts(StringRef(Rec2->getName()));
1539
1540     size_t LHSNumParts = LHSParts.size();
1541     size_t RHSNumParts = RHSParts.size();
1542     assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
1543
1544     if (LHSNumParts != RHSNumParts)
1545       return LHSNumParts < RHSNumParts;
1546
1547     // We expect the registers to be of the form [_a-zA-z]+([0-9]*[_a-zA-Z]*)*.
1548     for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
1549       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1550       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1551       // Expect even part to always be alpha.
1552       assert (LHSPart.first == false && RHSPart.first == false &&
1553               "Expected both parts to be alpha.");
1554       if (int Res = LHSPart.second.compare(RHSPart.second))
1555         return Res < 0;
1556     }
1557     for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
1558       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1559       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1560       // Expect odd part to always be numeric.
1561       assert (LHSPart.first == true && RHSPart.first == true &&
1562               "Expected both parts to be numeric.");
1563       if (LHSPart.second.size() != RHSPart.second.size())
1564         return LHSPart.second.size() < RHSPart.second.size();
1565
1566       unsigned LHSVal, RHSVal;
1567
1568       bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
1569       assert(!LHSFailed && "Unable to convert LHS to integer.");
1570       bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
1571       assert(!RHSFailed && "Unable to convert RHS to integer.");
1572
1573       if (LHSVal != RHSVal)
1574         return LHSVal < RHSVal;
1575     }
1576     return LHSNumParts < RHSNumParts;
1577   }
1578 };
1579
1580 raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
1581
1582 /// QualifyName - Return an Init with a qualifier prefix referring
1583 /// to CurRec's name.
1584 Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1585                   Init *Name, const std::string &Scoper);
1586
1587 /// QualifyName - Return an Init with a qualifier prefix referring
1588 /// to CurRec's name.
1589 Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1590                   const std::string &Name, const std::string &Scoper);
1591
1592 } // End llvm namespace
1593
1594 #endif