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