What should be the last unnecessary <iostream>s in the library.
[oota-llvm.git] / utils / TableGen / FileParser.y
1 //===-- FileParser.y - Parser for TableGen files ----------------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the bison parser for Table Generator files...
11 //
12 //===----------------------------------------------------------------------===//
13
14 %{
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Streams.h"
18 #include <algorithm>
19 #include <cstdio>
20 #define YYERROR_VERBOSE 1
21
22 int yyerror(const char *ErrorMsg);
23 int yylex();
24
25 namespace llvm {
26   struct MultiClass {
27     Record Rec;  // Placeholder for template args and Name.
28     std::vector<Record*> DefPrototypes;
29     
30     MultiClass(const std::string &Name) : Rec(Name) {}
31   };
32
33   
34 static std::map<std::string, MultiClass*> MultiClasses;
35   
36 extern int Filelineno;
37 static MultiClass *CurMultiClass = 0;    // Set while parsing a multiclass.
38 static std::string *CurDefmPrefix = 0;   // Set while parsing defm.
39 static Record *CurRec = 0;
40 static bool ParsingTemplateArgs = false;
41
42 typedef std::pair<Record*, std::vector<Init*>*> SubClassRefTy;
43
44 struct LetRecord {
45   std::string Name;
46   std::vector<unsigned> Bits;
47   Init *Value;
48   bool HasBits;
49   LetRecord(const std::string &N, std::vector<unsigned> *B, Init *V)
50     : Name(N), Value(V), HasBits(B != 0) {
51     if (HasBits) Bits = *B;
52   }
53 };
54
55 static std::vector<std::vector<LetRecord> > LetStack;
56
57
58 extern std::ostream &err();
59
60 /// getActiveRec - If inside a def/class definition, return the def/class.
61 /// Otherwise, if within a multidef, return it.
62 static Record *getActiveRec() {
63   return CurRec ? CurRec : &CurMultiClass->Rec;
64 }
65
66 static void addValue(const RecordVal &RV) {
67   Record *TheRec = getActiveRec();
68   
69   if (RecordVal *ERV = TheRec->getValue(RV.getName())) {
70     // The value already exists in the class, treat this as a set...
71     if (ERV->setValue(RV.getValue())) {
72       err() << "New definition of '" << RV.getName() << "' of type '"
73             << *RV.getType() << "' is incompatible with previous "
74             << "definition of type '" << *ERV->getType() << "'!\n";
75       exit(1);
76     }
77   } else {
78     TheRec->addValue(RV);
79   }
80 }
81
82 static void addSuperClass(Record *SC) {
83   if (CurRec->isSubClassOf(SC)) {
84     err() << "Already subclass of '" << SC->getName() << "'!\n";
85     exit(1);
86   }
87   CurRec->addSuperClass(SC);
88 }
89
90 static void setValue(const std::string &ValName, 
91                      std::vector<unsigned> *BitList, Init *V) {
92   if (!V) return;
93
94   Record *TheRec = getActiveRec();
95   RecordVal *RV = TheRec->getValue(ValName);
96   if (RV == 0) {
97     err() << "Value '" << ValName << "' unknown!\n";
98     exit(1);
99   }
100
101   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
102   // in the resolution machinery.
103   if (!BitList)
104     if (VarInit *VI = dynamic_cast<VarInit*>(V))
105       if (VI->getName() == ValName)
106         return;
107   
108   // If we are assigning to a subset of the bits in the value... then we must be
109   // assigning to a field of BitsRecTy, which must have a BitsInit
110   // initializer...
111   //
112   if (BitList) {
113     BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
114     if (CurVal == 0) {
115       err() << "Value '" << ValName << "' is not a bits type!\n";
116       exit(1);
117     }
118
119     // Convert the incoming value to a bits type of the appropriate size...
120     Init *BI = V->convertInitializerTo(new BitsRecTy(BitList->size()));
121     if (BI == 0) {
122       V->convertInitializerTo(new BitsRecTy(BitList->size()));
123       err() << "Initializer '" << *V << "' not compatible with bit range!\n";
124       exit(1);
125     }
126
127     // We should have a BitsInit type now...
128     assert(dynamic_cast<BitsInit*>(BI) != 0 || (cerr << *BI).stream() == 0);
129     BitsInit *BInit = (BitsInit*)BI;
130
131     BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
132
133     // Loop over bits, assigning values as appropriate...
134     for (unsigned i = 0, e = BitList->size(); i != e; ++i) {
135       unsigned Bit = (*BitList)[i];
136       if (NewVal->getBit(Bit)) {
137         err() << "Cannot set bit #" << Bit << " of value '" << ValName
138               << "' more than once!\n";
139         exit(1);
140       }
141       NewVal->setBit(Bit, BInit->getBit(i));
142     }
143
144     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
145       if (NewVal->getBit(i) == 0)
146         NewVal->setBit(i, CurVal->getBit(i));
147
148     V = NewVal;
149   }
150
151   if (RV->setValue(V)) {
152     err() << "Value '" << ValName << "' of type '" << *RV->getType()
153           << "' is incompatible with initializer '" << *V << "'!\n";
154     exit(1);
155   }
156 }
157
158 // addSubClass - Add SC as a subclass to CurRec, resolving TemplateArgs as SC's
159 // template arguments.
160 static void addSubClass(Record *SC, const std::vector<Init*> &TemplateArgs) {
161   // Add all of the values in the subclass into the current class...
162   const std::vector<RecordVal> &Vals = SC->getValues();
163   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
164     addValue(Vals[i]);
165
166   const std::vector<std::string> &TArgs = SC->getTemplateArgs();
167
168   // Ensure that an appropriate number of template arguments are specified...
169   if (TArgs.size() < TemplateArgs.size()) {
170     err() << "ERROR: More template args specified than expected!\n";
171     exit(1);
172   }
173   
174   // Loop over all of the template arguments, setting them to the specified
175   // value or leaving them as the default if necessary.
176   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
177     if (i < TemplateArgs.size()) {  // A value is specified for this temp-arg?
178       // Set it now.
179       setValue(TArgs[i], 0, TemplateArgs[i]);
180
181       // Resolve it next.
182       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
183                                   
184       
185       // Now remove it.
186       CurRec->removeValue(TArgs[i]);
187
188     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
189       err() << "ERROR: Value not specified for template argument #"
190             << i << " (" << TArgs[i] << ") of subclass '" << SC->getName()
191             << "'!\n";
192       exit(1);
193     }
194   }
195
196   // Since everything went well, we can now set the "superclass" list for the
197   // current record.
198   const std::vector<Record*> &SCs = SC->getSuperClasses();
199   for (unsigned i = 0, e = SCs.size(); i != e; ++i)
200     addSuperClass(SCs[i]);
201   addSuperClass(SC);
202 }
203
204 } // End llvm namespace
205
206 using namespace llvm;
207
208 %}
209
210 %union {
211   std::string*                StrVal;
212   int                         IntVal;
213   llvm::RecTy*                Ty;
214   llvm::Init*                 Initializer;
215   std::vector<llvm::Init*>*   FieldList;
216   std::vector<unsigned>*      BitList;
217   llvm::Record*               Rec;
218   std::vector<llvm::Record*>* RecList;
219   SubClassRefTy*              SubClassRef;
220   std::vector<SubClassRefTy>* SubClassList;
221   std::vector<std::pair<llvm::Init*, std::string> >* DagValueList;
222 };
223
224 %token INT BIT STRING BITS LIST CODE DAG CLASS DEF MULTICLASS DEFM FIELD LET IN
225 %token SHLTOK SRATOK SRLTOK STRCONCATTOK
226 %token <IntVal>      INTVAL
227 %token <StrVal>      ID VARNAME STRVAL CODEFRAGMENT
228
229 %type <Ty>           Type
230 %type <Rec>          ClassInst DefInst MultiClassDef ObjectBody ClassID
231 %type <RecList>      MultiClassBody
232
233 %type <SubClassRef>  SubClassRef
234 %type <SubClassList> ClassList ClassListNE
235 %type <IntVal>       OptPrefix
236 %type <Initializer>  Value OptValue IDValue
237 %type <DagValueList> DagArgList DagArgListNE
238 %type <FieldList>    ValueList ValueListNE
239 %type <BitList>      BitList OptBitList RBitList
240 %type <StrVal>       Declaration OptID OptVarName ObjectName
241
242 %start File
243
244 %%
245
246 ClassID : ID {
247     if (CurDefmPrefix) {
248       // If CurDefmPrefix is set, we're parsing a defm, which means that this is
249       // actually the name of a multiclass.
250       MultiClass *MC = MultiClasses[*$1];
251       if (MC == 0) {
252         err() << "Couldn't find class '" << *$1 << "'!\n";
253         exit(1);
254       }
255       $$ = &MC->Rec;
256     } else {
257       $$ = Records.getClass(*$1);
258     }
259     if ($$ == 0) {
260       err() << "Couldn't find class '" << *$1 << "'!\n";
261       exit(1);
262     }
263     delete $1;
264   };
265
266
267 // TableGen types...
268 Type : STRING {                       // string type
269     $$ = new StringRecTy();
270   } | BIT {                           // bit type
271     $$ = new BitRecTy();
272   } | BITS '<' INTVAL '>' {           // bits<x> type
273     $$ = new BitsRecTy($3);
274   } | INT {                           // int type
275     $$ = new IntRecTy();
276   } | LIST '<' Type '>'    {          // list<x> type
277     $$ = new ListRecTy($3);
278   } | CODE {                          // code type
279     $$ = new CodeRecTy();
280   } | DAG {                           // dag type
281     $$ = new DagRecTy();
282   } | ClassID {                       // Record Type
283     $$ = new RecordRecTy($1);
284   };
285
286 OptPrefix : /*empty*/ { $$ = 0; } | FIELD { $$ = 1; };
287
288 OptValue : /*empty*/ { $$ = 0; } | '=' Value { $$ = $2; };
289
290 IDValue : ID {
291   if (const RecordVal *RV = (CurRec ? CurRec->getValue(*$1) : 0)) {
292     $$ = new VarInit(*$1, RV->getType());
293   } else if (CurRec && CurRec->isTemplateArg(CurRec->getName()+":"+*$1)) {
294     const RecordVal *RV = CurRec->getValue(CurRec->getName()+":"+*$1);
295     assert(RV && "Template arg doesn't exist??");
296     $$ = new VarInit(CurRec->getName()+":"+*$1, RV->getType());
297   } else if (CurMultiClass &&
298       CurMultiClass->Rec.isTemplateArg(CurMultiClass->Rec.getName()+"::"+*$1)) {
299     std::string Name = CurMultiClass->Rec.getName()+"::"+*$1;
300     const RecordVal *RV = CurMultiClass->Rec.getValue(Name);
301     assert(RV && "Template arg doesn't exist??");
302     $$ = new VarInit(Name, RV->getType());
303   } else if (Record *D = Records.getDef(*$1)) {
304     $$ = new DefInit(D);
305   } else {
306     err() << "Variable not defined: '" << *$1 << "'!\n";
307     exit(1);
308   }
309   
310   delete $1;
311 };
312
313 Value : IDValue {
314     $$ = $1;
315   } | INTVAL {
316     $$ = new IntInit($1);
317   } | STRVAL {
318     $$ = new StringInit(*$1);
319     delete $1;
320   } | CODEFRAGMENT {
321     $$ = new CodeInit(*$1);
322     delete $1;
323   } | '?' {
324     $$ = new UnsetInit();
325   } | '{' ValueList '}' {
326     BitsInit *Init = new BitsInit($2->size());
327     for (unsigned i = 0, e = $2->size(); i != e; ++i) {
328       struct Init *Bit = (*$2)[i]->convertInitializerTo(new BitRecTy());
329       if (Bit == 0) {
330         err() << "Element #" << i << " (" << *(*$2)[i]
331               << ") is not convertable to a bit!\n";
332         exit(1);
333       }
334       Init->setBit($2->size()-i-1, Bit);
335     }
336     $$ = Init;
337     delete $2;
338   } | ID '<' ValueListNE '>' {
339     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
340     // a new anonymous definition, deriving from CLASS<initvalslist> with no
341     // body.
342     Record *Class = Records.getClass(*$1);
343     if (!Class) {
344       err() << "Expected a class, got '" << *$1 << "'!\n";
345       exit(1);
346     }
347     delete $1;
348     
349     static unsigned AnonCounter = 0;
350     Record *OldRec = CurRec;  // Save CurRec.
351     
352     // Create the new record, set it as CurRec temporarily.
353     CurRec = new Record("anonymous.val."+utostr(AnonCounter++));
354     addSubClass(Class, *$3);    // Add info about the subclass to CurRec.
355     delete $3;  // Free up the template args.
356     
357     CurRec->resolveReferences();
358     
359     Records.addDef(CurRec);
360     
361     // The result of the expression is a reference to the new record.
362     $$ = new DefInit(CurRec);
363     
364     // Restore the old CurRec
365     CurRec = OldRec;
366   } | Value '{' BitList '}' {
367     $$ = $1->convertInitializerBitRange(*$3);
368     if ($$ == 0) {
369       err() << "Invalid bit range for value '" << *$1 << "'!\n";
370       exit(1);
371     }
372     delete $3;
373   } | '[' ValueList ']' {
374     $$ = new ListInit(*$2);
375     delete $2;
376   } | Value '.' ID {
377     if (!$1->getFieldType(*$3)) {
378       err() << "Cannot access field '" << *$3 << "' of value '" << *$1 << "!\n";
379       exit(1);
380     }
381     $$ = new FieldInit($1, *$3);
382     delete $3;
383   } | '(' IDValue DagArgList ')' {
384     $$ = new DagInit($2, *$3);
385     delete $3;
386   } | Value '[' BitList ']' {
387     std::reverse($3->begin(), $3->end());
388     $$ = $1->convertInitListSlice(*$3);
389     if ($$ == 0) {
390       err() << "Invalid list slice for value '" << *$1 << "'!\n";
391       exit(1);
392     }
393     delete $3;
394   } | SHLTOK '(' Value ',' Value ')' {
395     $$ = (new BinOpInit(BinOpInit::SHL, $3, $5))->Fold();
396   } | SRATOK '(' Value ',' Value ')' {
397     $$ = (new BinOpInit(BinOpInit::SRA, $3, $5))->Fold();
398   } | SRLTOK '(' Value ',' Value ')' {
399     $$ = (new BinOpInit(BinOpInit::SRL, $3, $5))->Fold();
400   } | STRCONCATTOK '(' Value ',' Value ')' {
401     $$ = (new BinOpInit(BinOpInit::STRCONCAT, $3, $5))->Fold();
402   };
403
404 OptVarName : /* empty */ {
405     $$ = new std::string();
406   }
407   | ':' VARNAME {
408     $$ = $2;
409   };
410
411 DagArgListNE : Value OptVarName {
412     $$ = new std::vector<std::pair<Init*, std::string> >();
413     $$->push_back(std::make_pair($1, *$2));
414     delete $2;
415   }
416   | DagArgListNE ',' Value OptVarName {
417     $1->push_back(std::make_pair($3, *$4));
418     delete $4;
419     $$ = $1;
420   };
421
422 DagArgList : /*empty*/ {
423     $$ = new std::vector<std::pair<Init*, std::string> >();
424   }
425   | DagArgListNE { $$ = $1; };
426
427
428 RBitList : INTVAL {
429     $$ = new std::vector<unsigned>();
430     $$->push_back($1);
431   } | INTVAL '-' INTVAL {
432     if ($1 < 0 || $3 < 0) {
433       err() << "Invalid range: " << $1 << "-" << $3 << "!\n";
434       exit(1);
435     }
436     $$ = new std::vector<unsigned>();
437     if ($1 < $3) {
438       for (int i = $1; i <= $3; ++i)
439         $$->push_back(i);
440     } else {
441       for (int i = $1; i >= $3; --i)
442         $$->push_back(i);
443     }
444   } | INTVAL INTVAL {
445     $2 = -$2;
446     if ($1 < 0 || $2 < 0) {
447       err() << "Invalid range: " << $1 << "-" << $2 << "!\n";
448       exit(1);
449     }
450     $$ = new std::vector<unsigned>();
451     if ($1 < $2) {
452       for (int i = $1; i <= $2; ++i)
453         $$->push_back(i);
454     } else {
455       for (int i = $1; i >= $2; --i)
456         $$->push_back(i);
457     }
458   } | RBitList ',' INTVAL {
459     ($$=$1)->push_back($3);
460   } | RBitList ',' INTVAL '-' INTVAL {
461     if ($3 < 0 || $5 < 0) {
462       err() << "Invalid range: " << $3 << "-" << $5 << "!\n";
463       exit(1);
464     }
465     $$ = $1;
466     if ($3 < $5) {
467       for (int i = $3; i <= $5; ++i)
468         $$->push_back(i);
469     } else {
470       for (int i = $3; i >= $5; --i)
471         $$->push_back(i);
472     }
473   } | RBitList ',' INTVAL INTVAL {
474     $4 = -$4;
475     if ($3 < 0 || $4 < 0) {
476       err() << "Invalid range: " << $3 << "-" << $4 << "!\n";
477       exit(1);
478     }
479     $$ = $1;
480     if ($3 < $4) {
481       for (int i = $3; i <= $4; ++i)
482         $$->push_back(i);
483     } else {
484       for (int i = $3; i >= $4; --i)
485         $$->push_back(i);
486     }
487   };
488
489 BitList : RBitList { $$ = $1; std::reverse($1->begin(), $1->end()); };
490
491 OptBitList : /*empty*/ { $$ = 0; } | '{' BitList '}' { $$ = $2; };
492
493
494
495 ValueList : /*empty*/ {
496     $$ = new std::vector<Init*>();
497   } | ValueListNE {
498     $$ = $1;
499   };
500
501 ValueListNE : Value {
502     $$ = new std::vector<Init*>();
503     $$->push_back($1);
504   } | ValueListNE ',' Value {
505     ($$ = $1)->push_back($3);
506   };
507
508 Declaration : OptPrefix Type ID OptValue {
509   std::string DecName = *$3;
510   if (ParsingTemplateArgs) {
511     if (CurRec) {
512       DecName = CurRec->getName() + ":" + DecName;
513     } else {
514       assert(CurMultiClass);
515     }
516     if (CurMultiClass)
517       DecName = CurMultiClass->Rec.getName() + "::" + DecName;
518   }
519
520   addValue(RecordVal(DecName, $2, $1));
521   setValue(DecName, 0, $4);
522   $$ = new std::string(DecName);
523 };
524
525 BodyItem : Declaration ';' {
526   delete $1;
527 } | LET ID OptBitList '=' Value ';' {
528   setValue(*$2, $3, $5);
529   delete $2;
530   delete $3;
531 };
532
533 BodyList : /*empty*/ | BodyList BodyItem;
534 Body : ';' | '{' BodyList '}';
535
536 SubClassRef : ClassID {
537     $$ = new SubClassRefTy($1, new std::vector<Init*>());
538   } | ClassID '<' ValueListNE '>' {
539     $$ = new SubClassRefTy($1, $3);
540   };
541
542 ClassListNE : SubClassRef {
543     $$ = new std::vector<SubClassRefTy>();
544     $$->push_back(*$1);
545     delete $1;
546   }
547   | ClassListNE ',' SubClassRef {
548     ($$=$1)->push_back(*$3);
549     delete $3;
550   };
551
552 ClassList : /*empty */ {
553     $$ = new std::vector<SubClassRefTy>();
554   }
555   | ':' ClassListNE {
556     $$ = $2;
557   };
558
559 DeclListNE : Declaration {
560   getActiveRec()->addTemplateArg(*$1);
561   delete $1;
562 } | DeclListNE ',' Declaration {
563   getActiveRec()->addTemplateArg(*$3);
564   delete $3;
565 };
566
567 TemplateArgList : '<' DeclListNE '>' {};
568 OptTemplateArgList : /*empty*/ | TemplateArgList;
569
570 OptID : ID { $$ = $1; } | /*empty*/ { $$ = new std::string(); };
571
572 ObjectName : OptID {
573   static unsigned AnonCounter = 0;
574   if ($1->empty())
575     *$1 = "anonymous."+utostr(AnonCounter++);
576   $$ = $1;
577 };
578
579 ClassName : ObjectName {
580   // If a class of this name already exists, it must be a forward ref.
581   if ((CurRec = Records.getClass(*$1))) {
582     // If the body was previously defined, this is an error.
583     if (!CurRec->getValues().empty() ||
584         !CurRec->getSuperClasses().empty() ||
585         !CurRec->getTemplateArgs().empty()) {
586       err() << "Class '" << CurRec->getName() << "' already defined!\n";
587       exit(1);
588     }
589   } else {
590     // If this is the first reference to this class, create and add it.
591     CurRec = new Record(*$1);
592     Records.addClass(CurRec);
593   }
594   delete $1;
595 };
596
597 DefName : ObjectName {
598   CurRec = new Record(*$1);
599   delete $1;
600   
601   if (!CurMultiClass) {
602     // Top-level def definition.
603     
604     // Ensure redefinition doesn't happen.
605     if (Records.getDef(CurRec->getName())) {
606       err() << "def '" << CurRec->getName() << "' already defined!\n";
607       exit(1);
608     }
609     Records.addDef(CurRec);
610   } else {
611     // Otherwise, a def inside a multiclass, add it to the multiclass.
612     for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
613       if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
614         err() << "def '" << CurRec->getName()
615               << "' already defined in this multiclass!\n";
616         exit(1);
617       }
618     CurMultiClass->DefPrototypes.push_back(CurRec);
619   }
620 };
621
622 ObjectBody : ClassList {
623            for (unsigned i = 0, e = $1->size(); i != e; ++i) {
624              addSubClass((*$1)[i].first, *(*$1)[i].second);
625              // Delete the template arg values for the class
626              delete (*$1)[i].second;
627            }
628            delete $1;   // Delete the class list.
629   
630            // Process any variables on the let stack.
631            for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
632              for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
633                setValue(LetStack[i][j].Name,
634                         LetStack[i][j].HasBits ? &LetStack[i][j].Bits : 0,
635                         LetStack[i][j].Value);
636          } Body {
637            $$ = CurRec;
638            CurRec = 0;
639          };
640
641 ClassInst : CLASS ClassName {
642                 ParsingTemplateArgs = true;
643             } OptTemplateArgList {
644                 ParsingTemplateArgs = false;
645             } ObjectBody {
646         $$ = $6;
647      };
648
649 DefInst : DEF DefName ObjectBody {
650   if (CurMultiClass == 0)  // Def's in multiclasses aren't really defs.
651     $3->resolveReferences();
652
653   // If ObjectBody has template arguments, it's an error.
654   assert($3->getTemplateArgs().empty() && "How'd this get template args?");
655   $$ = $3;
656 };
657
658 // MultiClassDef - A def instance specified inside a multiclass.
659 MultiClassDef : DefInst {
660   $$ = $1;
661   // Copy the template arguments for the multiclass into the def.
662   const std::vector<std::string> &TArgs = CurMultiClass->Rec.getTemplateArgs();
663   
664   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
665     const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
666     assert(RV && "Template arg doesn't exist?");
667     $$->addValue(*RV);
668   }
669 };
670
671 // MultiClassBody - Sequence of def's that are instantiated when a multiclass is
672 // used.
673 MultiClassBody : MultiClassDef {
674   $$ = new std::vector<Record*>();
675   $$->push_back($1);
676 } | MultiClassBody MultiClassDef {
677   $$->push_back($2);  
678 };
679
680 MultiClassName : ID {
681   MultiClass *&MCE = MultiClasses[*$1];
682   if (MCE) {
683     err() << "multiclass '" << *$1 << "' already defined!\n";
684     exit(1);
685   }
686   MCE = CurMultiClass = new MultiClass(*$1);
687   delete $1;
688 };
689
690 // MultiClass - Multiple definitions.
691 MultiClassInst : MULTICLASS MultiClassName {
692                                              ParsingTemplateArgs = true;
693                                            } OptTemplateArgList {
694                                              ParsingTemplateArgs = false;
695                                            }'{' MultiClassBody '}' {
696   CurMultiClass = 0;
697 };
698
699 // DefMInst - Instantiate a multiclass.
700 DefMInst : DEFM ID { CurDefmPrefix = $2; } ':' SubClassRef ';' {
701   // To instantiate a multiclass, we need to first get the multiclass, then
702   // instantiate each def contained in the multiclass with the SubClassRef
703   // template parameters.
704   MultiClass *MC = MultiClasses[$5->first->getName()];
705   assert(MC && "Didn't lookup multiclass correctly?");
706   std::vector<Init*> &TemplateVals = *$5->second;
707   delete $5;
708   
709   // Verify that the correct number of template arguments were specified.
710   const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
711   if (TArgs.size() < TemplateVals.size()) {
712     err() << "ERROR: More template args specified than multiclass expects!\n";
713     exit(1);
714   }
715   
716   // Loop over all the def's in the multiclass, instantiating each one.
717   for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
718     Record *DefProto = MC->DefPrototypes[i];
719     
720     // Add the suffix to the defm name to get the new name.
721     assert(CurRec == 0 && "A def is current?");
722     CurRec = new Record(*$2 + DefProto->getName());
723     
724     addSubClass(DefProto, std::vector<Init*>());
725     
726     // Loop over all of the template arguments, setting them to the specified
727     // value or leaving them as the default if necessary.
728     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
729       if (i < TemplateVals.size()) { // A value is specified for this temp-arg?
730         // Set it now.
731         setValue(TArgs[i], 0, TemplateVals[i]);
732         
733         // Resolve it next.
734         CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
735         
736         // Now remove it.
737         CurRec->removeValue(TArgs[i]);
738         
739       } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
740         err() << "ERROR: Value not specified for template argument #"
741         << i << " (" << TArgs[i] << ") of multiclassclass '"
742         << MC->Rec.getName() << "'!\n";
743         exit(1);
744       }
745     }
746     
747     // If the mdef is inside a 'let' expression, add to each def.
748     for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
749       for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
750         setValue(LetStack[i][j].Name,
751                  LetStack[i][j].HasBits ? &LetStack[i][j].Bits : 0,
752                  LetStack[i][j].Value);
753     
754     
755     // Ensure redefinition doesn't happen.
756     if (Records.getDef(CurRec->getName())) {
757       err() << "def '" << CurRec->getName() << "' already defined, "
758             << "instantiating defm '" << *$2 << "' with subdef '"
759             << DefProto->getName() << "'!\n";
760       exit(1);
761     }
762     Records.addDef(CurRec);
763     
764     CurRec->resolveReferences();
765
766     CurRec = 0;
767   }
768   
769   delete &TemplateVals;
770   delete $2;
771   CurDefmPrefix = 0;
772 };
773
774 Object : ClassInst {} | DefInst {};
775 Object : MultiClassInst | DefMInst;
776
777 LETItem : ID OptBitList '=' Value {
778   LetStack.back().push_back(LetRecord(*$1, $2, $4));
779   delete $1; delete $2;
780 };
781
782 LETList : LETItem | LETList ',' LETItem;
783
784 // LETCommand - A 'LET' statement start...
785 LETCommand : LET { LetStack.push_back(std::vector<LetRecord>()); } LETList IN;
786
787 // Support Set commands wrapping objects... both with and without braces.
788 Object : LETCommand '{' ObjectList '}' {
789     LetStack.pop_back();
790   }
791   | LETCommand Object {
792     LetStack.pop_back();
793   };
794
795 ObjectList : Object {} | ObjectList Object {};
796
797 File : ObjectList;
798
799 %%
800
801 int yyerror(const char *ErrorMsg) {
802   err() << "Error parsing: " << ErrorMsg << "\n";
803   exit(1);
804 }