rename TGLoc -> SMLoc.
[oota-llvm.git] / utils / TableGen / TGParser.cpp
1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
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 // Implement the Parser for TableGen.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include <algorithm>
15 #include <sstream>
16
17 #include "TGParser.h"
18 #include "Record.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/Streams.h"
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
26
27 namespace llvm {
28 struct SubClassReference {
29   SMLoc RefLoc;
30   Record *Rec;
31   std::vector<Init*> TemplateArgs;
32   SubClassReference() : Rec(0) {}
33
34   bool isInvalid() const { return Rec == 0; }
35 };
36
37 struct SubMultiClassReference {
38   SMLoc RefLoc;
39   MultiClass *MC;
40   std::vector<Init*> TemplateArgs;
41   SubMultiClassReference() : MC(0) {}
42
43   bool isInvalid() const { return MC == 0; }
44   void dump() const;
45 };
46
47 void SubMultiClassReference::dump() const {
48   cerr << "Multiclass:\n";
49  
50   MC->dump();
51  
52   cerr << "Template args:\n";
53   for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
54          iend = TemplateArgs.end();
55        i != iend;
56        ++i) {
57     (*i)->dump();
58   }
59 }
60
61 } // end namespace llvm
62
63 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
64   if (CurRec == 0)
65     CurRec = &CurMultiClass->Rec;
66   
67   if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
68     // The value already exists in the class, treat this as a set.
69     if (ERV->setValue(RV.getValue()))
70       return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71                    RV.getType()->getAsString() + "' is incompatible with " +
72                    "previous definition of type '" + 
73                    ERV->getType()->getAsString() + "'");
74   } else {
75     CurRec->addValue(RV);
76   }
77   return false;
78 }
79
80 /// SetValue -
81 /// Return true on error, false on success.
82 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, const std::string &ValName, 
83                         const std::vector<unsigned> &BitList, Init *V) {
84   if (!V) return false;
85
86   if (CurRec == 0) CurRec = &CurMultiClass->Rec;
87
88   RecordVal *RV = CurRec->getValue(ValName);
89   if (RV == 0)
90     return Error(Loc, "Value '" + ValName + "' unknown!");
91
92   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
93   // in the resolution machinery.
94   if (BitList.empty())
95     if (VarInit *VI = dynamic_cast<VarInit*>(V))
96       if (VI->getName() == ValName)
97         return false;
98   
99   // If we are assigning to a subset of the bits in the value... then we must be
100   // assigning to a field of BitsRecTy, which must have a BitsInit
101   // initializer.
102   //
103   if (!BitList.empty()) {
104     BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
105     if (CurVal == 0)
106       return Error(Loc, "Value '" + ValName + "' is not a bits type");
107
108     // Convert the incoming value to a bits type of the appropriate size...
109     Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
110     if (BI == 0) {
111       V->convertInitializerTo(new BitsRecTy(BitList.size()));
112       return Error(Loc, "Initializer is not compatible with bit range");
113     }
114                    
115     // We should have a BitsInit type now.
116     BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
117     assert(BInit != 0);
118
119     BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
120
121     // Loop over bits, assigning values as appropriate.
122     for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
123       unsigned Bit = BitList[i];
124       if (NewVal->getBit(Bit))
125         return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
126                      ValName + "' more than once");
127       NewVal->setBit(Bit, BInit->getBit(i));
128     }
129
130     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
131       if (NewVal->getBit(i) == 0)
132         NewVal->setBit(i, CurVal->getBit(i));
133
134     V = NewVal;
135   }
136
137   if (RV->setValue(V))
138    return Error(Loc, "Value '" + ValName + "' of type '" + 
139                 RV->getType()->getAsString() + 
140                 "' is incompatible with initializer '" + V->getAsString() +"'");
141   return false;
142 }
143
144 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
145 /// args as SubClass's template arguments.
146 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
147   Record *SC = SubClass.Rec;
148   // Add all of the values in the subclass into the current class.
149   const std::vector<RecordVal> &Vals = SC->getValues();
150   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
151     if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
152       return true;
153
154   const std::vector<std::string> &TArgs = SC->getTemplateArgs();
155
156   // Ensure that an appropriate number of template arguments are specified.
157   if (TArgs.size() < SubClass.TemplateArgs.size())
158     return Error(SubClass.RefLoc, "More template args specified than expected");
159   
160   // Loop over all of the template arguments, setting them to the specified
161   // value or leaving them as the default if necessary.
162   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
163     if (i < SubClass.TemplateArgs.size()) {
164       // If a value is specified for this template arg, set it now.
165       if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(), 
166                    SubClass.TemplateArgs[i]))
167         return true;
168       
169       // Resolve it next.
170       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
171       
172       // Now remove it.
173       CurRec->removeValue(TArgs[i]);
174
175     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
176       return Error(SubClass.RefLoc,"Value not specified for template argument #"
177                    + utostr(i) + " (" + TArgs[i] + ") of subclass '" + 
178                    SC->getName() + "'!");
179     }
180   }
181
182   // Since everything went well, we can now set the "superclass" list for the
183   // current record.
184   const std::vector<Record*> &SCs = SC->getSuperClasses();
185   for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
186     if (CurRec->isSubClassOf(SCs[i]))
187       return Error(SubClass.RefLoc,
188                    "Already subclass of '" + SCs[i]->getName() + "'!\n");
189     CurRec->addSuperClass(SCs[i]);
190   }
191   
192   if (CurRec->isSubClassOf(SC))
193     return Error(SubClass.RefLoc,
194                  "Already subclass of '" + SC->getName() + "'!\n");
195   CurRec->addSuperClass(SC);
196   return false;
197 }
198
199 /// AddSubMultiClass - Add SubMultiClass as a subclass to
200 /// CurMC, resolving its template args as SubMultiClass's
201 /// template arguments.
202 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
203                                 SubMultiClassReference &SubMultiClass) {
204   MultiClass *SMC = SubMultiClass.MC;
205   Record *CurRec = &CurMC->Rec;
206
207   const std::vector<RecordVal> &MCVals = CurRec->getValues();
208
209   // Add all of the values in the subclass into the current class.
210   const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
211   for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
212     if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
213       return true;
214
215   int newDefStart = CurMC->DefPrototypes.size();
216
217   // Add all of the defs in the subclass into the current multiclass.
218   for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
219          iend = SMC->DefPrototypes.end();
220        i != iend;
221        ++i) {
222     // Clone the def and add it to the current multiclass
223     Record *NewDef = new Record(**i);
224
225     // Add all of the values in the superclass into the current def.
226     for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
227       if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
228         return true;
229
230     CurMC->DefPrototypes.push_back(NewDef);
231   }
232
233   const std::vector<std::string> &SMCTArgs = SMC->Rec.getTemplateArgs();
234
235   // Ensure that an appropriate number of template arguments are
236   // specified.
237   if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
238     return Error(SubMultiClass.RefLoc,
239                  "More template args specified than expected");
240
241   // Loop over all of the template arguments, setting them to the specified
242   // value or leaving them as the default if necessary.
243   for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
244     if (i < SubMultiClass.TemplateArgs.size()) {
245       // If a value is specified for this template arg, set it in the
246       // superclass now.
247       if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
248                    std::vector<unsigned>(),
249                    SubMultiClass.TemplateArgs[i]))
250         return true;
251
252       // Resolve it next.
253       CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
254
255       // Now remove it.
256       CurRec->removeValue(SMCTArgs[i]);
257
258       // If a value is specified for this template arg, set it in the
259       // new defs now.
260       for (MultiClass::RecordVector::iterator j =
261              CurMC->DefPrototypes.begin() + newDefStart,
262              jend = CurMC->DefPrototypes.end();
263            j != jend;
264            ++j) {
265         Record *Def = *j;
266
267         if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
268                      std::vector<unsigned>(),
269                      SubMultiClass.TemplateArgs[i]))
270           return true;
271
272         // Resolve it next.
273         Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
274
275         // Now remove it
276         Def->removeValue(SMCTArgs[i]);
277       }
278     } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
279       return Error(SubMultiClass.RefLoc,
280                    "Value not specified for template argument #"
281                    + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
282                    SMC->Rec.getName() + "'!");
283     }
284   }
285
286   return false;
287 }
288
289 //===----------------------------------------------------------------------===//
290 // Parser Code
291 //===----------------------------------------------------------------------===//
292
293 /// isObjectStart - Return true if this is a valid first token for an Object.
294 static bool isObjectStart(tgtok::TokKind K) {
295   return K == tgtok::Class || K == tgtok::Def ||
296          K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass; 
297 }
298
299 /// ParseObjectName - If an object name is specified, return it.  Otherwise,
300 /// return an anonymous name.
301 ///   ObjectName ::= ID
302 ///   ObjectName ::= /*empty*/
303 ///
304 std::string TGParser::ParseObjectName() {
305   if (Lex.getCode() == tgtok::Id) {
306     std::string Ret = Lex.getCurStrVal();
307     Lex.Lex();
308     return Ret;
309   }
310   
311   static unsigned AnonCounter = 0;
312   return "anonymous."+utostr(AnonCounter++);
313 }
314
315
316 /// ParseClassID - Parse and resolve a reference to a class name.  This returns
317 /// null on error.
318 ///
319 ///    ClassID ::= ID
320 ///
321 Record *TGParser::ParseClassID() {
322   if (Lex.getCode() != tgtok::Id) {
323     TokError("expected name for ClassID");
324     return 0;
325   }
326   
327   Record *Result = Records.getClass(Lex.getCurStrVal());
328   if (Result == 0)
329     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
330   
331   Lex.Lex();
332   return Result;
333 }
334
335 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
336 /// This returns null on error.
337 ///
338 ///    MultiClassID ::= ID
339 ///
340 MultiClass *TGParser::ParseMultiClassID() {
341   if (Lex.getCode() != tgtok::Id) {
342     TokError("expected name for ClassID");
343     return 0;
344   }
345
346   MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
347   if (Result == 0)
348     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
349
350   Lex.Lex();
351   return Result;
352 }
353
354 Record *TGParser::ParseDefmID() {
355   if (Lex.getCode() != tgtok::Id) {
356     TokError("expected multiclass name");
357     return 0;
358   }
359   
360   MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
361   if (MC == 0) {
362     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
363     return 0;
364   }
365   
366   Lex.Lex();
367   return &MC->Rec;
368 }  
369
370
371
372 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
373 /// subclass.  This returns a SubClassRefTy with a null Record* on error.
374 ///
375 ///  SubClassRef ::= ClassID
376 ///  SubClassRef ::= ClassID '<' ValueList '>'
377 ///
378 SubClassReference TGParser::
379 ParseSubClassReference(Record *CurRec, bool isDefm) {
380   SubClassReference Result;
381   Result.RefLoc = Lex.getLoc();
382   
383   if (isDefm)
384     Result.Rec = ParseDefmID();
385   else
386     Result.Rec = ParseClassID();
387   if (Result.Rec == 0) return Result;
388   
389   // If there is no template arg list, we're done.
390   if (Lex.getCode() != tgtok::less)
391     return Result;
392   Lex.Lex();  // Eat the '<'
393   
394   if (Lex.getCode() == tgtok::greater) {
395     TokError("subclass reference requires a non-empty list of template values");
396     Result.Rec = 0;
397     return Result;
398   }
399   
400   Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
401   if (Result.TemplateArgs.empty()) {
402     Result.Rec = 0;   // Error parsing value list.
403     return Result;
404   }
405     
406   if (Lex.getCode() != tgtok::greater) {
407     TokError("expected '>' in template value list");
408     Result.Rec = 0;
409     return Result;
410   }
411   Lex.Lex();
412   
413   return Result;
414 }
415
416 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
417 /// templated submulticlass.  This returns a SubMultiClassRefTy with a null
418 /// Record* on error.
419 ///
420 ///  SubMultiClassRef ::= MultiClassID
421 ///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
422 ///
423 SubMultiClassReference TGParser::
424 ParseSubMultiClassReference(MultiClass *CurMC) {
425   SubMultiClassReference Result;
426   Result.RefLoc = Lex.getLoc();
427
428   Result.MC = ParseMultiClassID();
429   if (Result.MC == 0) return Result;
430
431   // If there is no template arg list, we're done.
432   if (Lex.getCode() != tgtok::less)
433     return Result;
434   Lex.Lex();  // Eat the '<'
435
436   if (Lex.getCode() == tgtok::greater) {
437     TokError("subclass reference requires a non-empty list of template values");
438     Result.MC = 0;
439     return Result;
440   }
441
442   Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
443   if (Result.TemplateArgs.empty()) {
444     Result.MC = 0;   // Error parsing value list.
445     return Result;
446   }
447
448   if (Lex.getCode() != tgtok::greater) {
449     TokError("expected '>' in template value list");
450     Result.MC = 0;
451     return Result;
452   }
453   Lex.Lex();
454
455   return Result;
456 }
457
458 /// ParseRangePiece - Parse a bit/value range.
459 ///   RangePiece ::= INTVAL
460 ///   RangePiece ::= INTVAL '-' INTVAL
461 ///   RangePiece ::= INTVAL INTVAL
462 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
463   if (Lex.getCode() != tgtok::IntVal) {
464     TokError("expected integer or bitrange");
465     return true;
466   }
467   int64_t Start = Lex.getCurIntVal();
468   int64_t End;
469   
470   if (Start < 0)
471     return TokError("invalid range, cannot be negative");
472   
473   switch (Lex.Lex()) {  // eat first character.
474   default: 
475     Ranges.push_back(Start);
476     return false;
477   case tgtok::minus:
478     if (Lex.Lex() != tgtok::IntVal) {
479       TokError("expected integer value as end of range");
480       return true;
481     }
482     End = Lex.getCurIntVal();
483     break;
484   case tgtok::IntVal:
485     End = -Lex.getCurIntVal();
486     break;
487   }
488   if (End < 0) 
489     return TokError("invalid range, cannot be negative");
490   Lex.Lex();
491   
492   // Add to the range.
493   if (Start < End) {
494     for (; Start <= End; ++Start)
495       Ranges.push_back(Start);
496   } else {
497     for (; Start >= End; --Start)
498       Ranges.push_back(Start);
499   }
500   return false;
501 }
502
503 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
504 ///
505 ///   RangeList ::= RangePiece (',' RangePiece)*
506 ///
507 std::vector<unsigned> TGParser::ParseRangeList() {
508   std::vector<unsigned> Result;
509   
510   // Parse the first piece.
511   if (ParseRangePiece(Result))
512     return std::vector<unsigned>();
513   while (Lex.getCode() == tgtok::comma) {
514     Lex.Lex();  // Eat the comma.
515
516     // Parse the next range piece.
517     if (ParseRangePiece(Result))
518       return std::vector<unsigned>();
519   }
520   return Result;
521 }
522
523 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
524 ///   OptionalRangeList ::= '<' RangeList '>'
525 ///   OptionalRangeList ::= /*empty*/
526 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
527   if (Lex.getCode() != tgtok::less)
528     return false;
529   
530   SMLoc StartLoc = Lex.getLoc();
531   Lex.Lex(); // eat the '<'
532   
533   // Parse the range list.
534   Ranges = ParseRangeList();
535   if (Ranges.empty()) return true;
536   
537   if (Lex.getCode() != tgtok::greater) {
538     TokError("expected '>' at end of range list");
539     return Error(StartLoc, "to match this '<'");
540   }
541   Lex.Lex();   // eat the '>'.
542   return false;
543 }
544
545 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
546 ///   OptionalBitList ::= '{' RangeList '}'
547 ///   OptionalBitList ::= /*empty*/
548 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
549   if (Lex.getCode() != tgtok::l_brace)
550     return false;
551   
552   SMLoc StartLoc = Lex.getLoc();
553   Lex.Lex(); // eat the '{'
554   
555   // Parse the range list.
556   Ranges = ParseRangeList();
557   if (Ranges.empty()) return true;
558   
559   if (Lex.getCode() != tgtok::r_brace) {
560     TokError("expected '}' at end of bit list");
561     return Error(StartLoc, "to match this '{'");
562   }
563   Lex.Lex();   // eat the '}'.
564   return false;
565 }
566
567
568 /// ParseType - Parse and return a tblgen type.  This returns null on error.
569 ///
570 ///   Type ::= STRING                       // string type
571 ///   Type ::= BIT                          // bit type
572 ///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
573 ///   Type ::= INT                          // int type
574 ///   Type ::= LIST '<' Type '>'            // list<x> type
575 ///   Type ::= CODE                         // code type
576 ///   Type ::= DAG                          // dag type
577 ///   Type ::= ClassID                      // Record Type
578 ///
579 RecTy *TGParser::ParseType() {
580   switch (Lex.getCode()) {
581   default: TokError("Unknown token when expecting a type"); return 0;
582   case tgtok::String: Lex.Lex(); return new StringRecTy();
583   case tgtok::Bit:    Lex.Lex(); return new BitRecTy();
584   case tgtok::Int:    Lex.Lex(); return new IntRecTy();
585   case tgtok::Code:   Lex.Lex(); return new CodeRecTy();
586   case tgtok::Dag:    Lex.Lex(); return new DagRecTy();
587   case tgtok::Id:
588     if (Record *R = ParseClassID()) return new RecordRecTy(R);
589     return 0;
590   case tgtok::Bits: {
591     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
592       TokError("expected '<' after bits type");
593       return 0;
594     }
595     if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
596       TokError("expected integer in bits<n> type");
597       return 0;
598     }
599     uint64_t Val = Lex.getCurIntVal();
600     if (Lex.Lex() != tgtok::greater) {  // Eat count.
601       TokError("expected '>' at end of bits<n> type");
602       return 0;
603     }
604     Lex.Lex();  // Eat '>'
605     return new BitsRecTy(Val);
606   }
607   case tgtok::List: {
608     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
609       TokError("expected '<' after list type");
610       return 0;
611     }
612     Lex.Lex();  // Eat '<'
613     RecTy *SubType = ParseType();
614     if (SubType == 0) return 0;
615     
616     if (Lex.getCode() != tgtok::greater) {
617       TokError("expected '>' at end of list<ty> type");
618       return 0;
619     }
620     Lex.Lex();  // Eat '>'
621     return new ListRecTy(SubType);
622   }
623   }      
624 }
625
626 /// ParseIDValue - Parse an ID as a value and decode what it means.
627 ///
628 ///  IDValue ::= ID [def local value]
629 ///  IDValue ::= ID [def template arg]
630 ///  IDValue ::= ID [multiclass local value]
631 ///  IDValue ::= ID [multiclass template argument]
632 ///  IDValue ::= ID [def name]
633 ///
634 Init *TGParser::ParseIDValue(Record *CurRec) {
635   assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
636   std::string Name = Lex.getCurStrVal();
637   SMLoc Loc = Lex.getLoc();
638   Lex.Lex();
639   return ParseIDValue(CurRec, Name, Loc);
640 }
641
642 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
643 /// has already been read.
644 Init *TGParser::ParseIDValue(Record *CurRec, 
645                              const std::string &Name, SMLoc NameLoc) {
646   if (CurRec) {
647     if (const RecordVal *RV = CurRec->getValue(Name))
648       return new VarInit(Name, RV->getType());
649     
650     std::string TemplateArgName = CurRec->getName()+":"+Name;
651     if (CurRec->isTemplateArg(TemplateArgName)) {
652       const RecordVal *RV = CurRec->getValue(TemplateArgName);
653       assert(RV && "Template arg doesn't exist??");
654       return new VarInit(TemplateArgName, RV->getType());
655     }
656   }
657   
658   if (CurMultiClass) {
659     std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
660     if (CurMultiClass->Rec.isTemplateArg(MCName)) {
661       const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
662       assert(RV && "Template arg doesn't exist??");
663       return new VarInit(MCName, RV->getType());
664     }
665   }
666   
667   if (Record *D = Records.getDef(Name))
668     return new DefInit(D);
669
670   Error(NameLoc, "Variable not defined: '" + Name + "'");
671   return 0;
672 }
673
674 /// ParseOperation - Parse an operator.  This returns null on error.
675 ///
676 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
677 ///
678 Init *TGParser::ParseOperation(Record *CurRec) {
679   switch (Lex.getCode()) {
680   default:
681     TokError("unknown operation");
682     return 0;
683     break;
684   case tgtok::XCar:
685   case tgtok::XCdr:
686   case tgtok::XNull:
687   case tgtok::XCast: {  // Value ::= !unop '(' Value ')'
688     UnOpInit::UnaryOp Code;
689     RecTy *Type = 0;
690
691     switch (Lex.getCode()) {
692     default: assert(0 && "Unhandled code!");
693     case tgtok::XCast:
694       Lex.Lex();  // eat the operation
695       Code = UnOpInit::CAST;
696
697       Type = ParseOperatorType();
698
699       if (Type == 0) {
700         TokError("did not get type for unary operator");
701         return 0;
702       }
703
704       break;
705     case tgtok::XCar:
706       Lex.Lex();  // eat the operation
707       Code = UnOpInit::CAR;
708       break;
709     case tgtok::XCdr:
710       Lex.Lex();  // eat the operation
711       Code = UnOpInit::CDR;
712       break;
713     case tgtok::XNull:
714       Lex.Lex();  // eat the operation
715       Code = UnOpInit::LNULL;
716       Type = new IntRecTy;
717       break;
718     }
719     if (Lex.getCode() != tgtok::l_paren) {
720       TokError("expected '(' after unary operator");
721       return 0;
722     }
723     Lex.Lex();  // eat the '('
724
725     Init *LHS = ParseValue(CurRec);
726     if (LHS == 0) return 0;
727
728     if (Code == UnOpInit::CAR
729         || Code == UnOpInit::CDR
730         || Code == UnOpInit::LNULL) {
731       ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
732       StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
733       TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
734       if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
735         TokError("expected list or string type argument in unary operator");
736         return 0;
737       }
738       if (LHSt) {
739         ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
740         StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
741         if (LType == 0 && SType == 0) {
742           TokError("expected list or string type argumnet in unary operator");
743           return 0;
744         }
745       }
746
747       if (Code == UnOpInit::CAR
748           || Code == UnOpInit::CDR) {
749         if (LHSl == 0 && LHSt == 0) {
750           TokError("expected list type argumnet in unary operator");
751           return 0;
752         }
753         
754         if (LHSl && LHSl->getSize() == 0) {
755           TokError("empty list argument in unary operator");
756           return 0;
757         }
758         if (LHSl) {
759           Init *Item = LHSl->getElement(0);
760           TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
761           if (Itemt == 0) {
762             TokError("untyped list element in unary operator");
763             return 0;
764           }
765           if (Code == UnOpInit::CAR) {
766             Type = Itemt->getType();
767           }
768           else {
769             Type = new ListRecTy(Itemt->getType());
770           }
771         }
772         else {
773           assert(LHSt && "expected list type argument in unary operator");
774           ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
775           if (LType == 0) {
776             TokError("expected list type argumnet in unary operator");
777             return 0;
778           }
779           if (Code == UnOpInit::CAR) {
780             Type = LType->getElementType();
781           }
782           else {
783             Type = LType;
784           }
785         }
786       }
787     }
788
789     if (Lex.getCode() != tgtok::r_paren) {
790       TokError("expected ')' in unary operator");
791       return 0;
792     }
793     Lex.Lex();  // eat the ')'
794     return (new UnOpInit(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
795   }
796
797   case tgtok::XConcat:
798   case tgtok::XSRA: 
799   case tgtok::XSRL:
800   case tgtok::XSHL:
801   case tgtok::XStrConcat:
802   case tgtok::XNameConcat: {  // Value ::= !binop '(' Value ',' Value ')'
803     BinOpInit::BinaryOp Code;
804     RecTy *Type = 0;
805
806
807     switch (Lex.getCode()) {
808     default: assert(0 && "Unhandled code!");
809     case tgtok::XConcat:     
810       Lex.Lex();  // eat the operation
811       Code = BinOpInit::CONCAT;
812       Type = new DagRecTy();
813       break;
814     case tgtok::XSRA:        
815       Lex.Lex();  // eat the operation
816       Code = BinOpInit::SRA;
817       Type = new IntRecTy();
818       break;
819     case tgtok::XSRL:        
820       Lex.Lex();  // eat the operation
821       Code = BinOpInit::SRL;
822       Type = new IntRecTy();
823       break;
824     case tgtok::XSHL:        
825       Lex.Lex();  // eat the operation
826       Code = BinOpInit::SHL;
827       Type = new IntRecTy();
828       break;
829     case tgtok::XStrConcat:  
830       Lex.Lex();  // eat the operation
831       Code = BinOpInit::STRCONCAT;
832       Type = new StringRecTy();
833       break;
834     case tgtok::XNameConcat: 
835       Lex.Lex();  // eat the operation
836       Code = BinOpInit::NAMECONCAT;
837
838       Type = ParseOperatorType();
839
840       if (Type == 0) {
841         TokError("did not get type for binary operator");
842         return 0;
843       }
844
845       break;
846     }
847     if (Lex.getCode() != tgtok::l_paren) {
848       TokError("expected '(' after binary operator");
849       return 0;
850     }
851     Lex.Lex();  // eat the '('
852
853     Init *LHS = ParseValue(CurRec);
854     if (LHS == 0) return 0;
855
856     if (Lex.getCode() != tgtok::comma) {
857       TokError("expected ',' in binary operator");
858       return 0;
859     }
860     Lex.Lex();  // eat the ','
861     
862     Init *RHS = ParseValue(CurRec);
863     if (RHS == 0) return 0;
864
865     if (Lex.getCode() != tgtok::r_paren) {
866       TokError("expected ')' in binary operator");
867       return 0;
868     }
869     Lex.Lex();  // eat the ')'
870     return (new BinOpInit(Code, LHS, RHS, Type))->Fold(CurRec, CurMultiClass);
871   }
872
873   case tgtok::XIf:
874   case tgtok::XForEach:
875   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
876     TernOpInit::TernaryOp Code;
877     RecTy *Type = 0;
878
879
880     tgtok::TokKind LexCode = Lex.getCode();
881     Lex.Lex();  // eat the operation
882     switch (LexCode) {
883     default: assert(0 && "Unhandled code!");
884     case tgtok::XIf:
885       Code = TernOpInit::IF;
886       break;
887     case tgtok::XForEach:
888       Code = TernOpInit::FOREACH;
889       break;
890     case tgtok::XSubst:
891       Code = TernOpInit::SUBST;
892       break;
893     }
894     if (Lex.getCode() != tgtok::l_paren) {
895       TokError("expected '(' after ternary operator");
896       return 0;
897     }
898     Lex.Lex();  // eat the '('
899
900     Init *LHS = ParseValue(CurRec);
901     if (LHS == 0) return 0;
902
903     if (Lex.getCode() != tgtok::comma) {
904       TokError("expected ',' in ternary operator");
905       return 0;
906     }
907     Lex.Lex();  // eat the ','
908     
909     Init *MHS = ParseValue(CurRec);
910     if (MHS == 0) return 0;
911
912     if (Lex.getCode() != tgtok::comma) {
913       TokError("expected ',' in ternary operator");
914       return 0;
915     }
916     Lex.Lex();  // eat the ','
917     
918     Init *RHS = ParseValue(CurRec);
919     if (RHS == 0) return 0;
920
921     if (Lex.getCode() != tgtok::r_paren) {
922       TokError("expected ')' in binary operator");
923       return 0;
924     }
925     Lex.Lex();  // eat the ')'
926
927     switch (LexCode) {
928     default: assert(0 && "Unhandled code!");
929     case tgtok::XIf: {
930       TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
931       TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
932       if (MHSt == 0 || RHSt == 0) {
933         TokError("could not get type for !if");
934         return 0;
935       }
936       if (MHSt->getType()->typeIsConvertibleTo(RHSt->getType())) {
937         Type = RHSt->getType();
938       }
939       else if (RHSt->getType()->typeIsConvertibleTo(MHSt->getType())) {
940         Type = MHSt->getType();
941       }
942       else {
943         TokError("inconsistent types for !if");
944         return 0;
945       }
946       break;
947     }
948     case tgtok::XForEach: {
949       TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
950       if (MHSt == 0) {
951         TokError("could not get type for !foreach");
952         return 0;
953       }
954       Type = MHSt->getType();
955       break;
956     }
957     case tgtok::XSubst: {
958       TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
959       if (RHSt == 0) {
960         TokError("could not get type for !subst");
961         return 0;
962       }
963       Type = RHSt->getType();
964       break;
965     }
966     }
967     return (new TernOpInit(Code, LHS, MHS, RHS, Type))->Fold(CurRec, CurMultiClass);
968   }
969   }
970   TokError("could not parse operation");
971   return 0;
972 }
973
974 /// ParseOperatorType - Parse a type for an operator.  This returns
975 /// null on error.
976 ///
977 /// OperatorType ::= '<' Type '>'
978 ///
979 RecTy *TGParser::ParseOperatorType(void) {
980   RecTy *Type = 0;
981
982   if (Lex.getCode() != tgtok::less) {
983     TokError("expected type name for operator");
984     return 0;
985   }
986   Lex.Lex();  // eat the <
987
988   Type = ParseType();
989
990   if (Type == 0) {
991     TokError("expected type name for operator");
992     return 0;
993   }
994
995   if (Lex.getCode() != tgtok::greater) {
996     TokError("expected type name for operator");
997     return 0;
998   }
999   Lex.Lex();  // eat the >
1000
1001   return Type;
1002 }
1003
1004
1005 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1006 ///
1007 ///   SimpleValue ::= IDValue
1008 ///   SimpleValue ::= INTVAL
1009 ///   SimpleValue ::= STRVAL+
1010 ///   SimpleValue ::= CODEFRAGMENT
1011 ///   SimpleValue ::= '?'
1012 ///   SimpleValue ::= '{' ValueList '}'
1013 ///   SimpleValue ::= ID '<' ValueListNE '>'
1014 ///   SimpleValue ::= '[' ValueList ']'
1015 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1016 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1017 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1018 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1019 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1020 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1021 ///
1022 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType) {
1023   Init *R = 0;
1024   switch (Lex.getCode()) {
1025   default: TokError("Unknown token when parsing a value"); break;
1026   case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
1027   case tgtok::StrVal: {
1028     std::string Val = Lex.getCurStrVal();
1029     Lex.Lex();
1030     
1031     // Handle multiple consecutive concatenated strings.
1032     while (Lex.getCode() == tgtok::StrVal) {
1033       Val += Lex.getCurStrVal();
1034       Lex.Lex();
1035     }
1036     
1037     R = new StringInit(Val);
1038     break;
1039   }
1040   case tgtok::CodeFragment:
1041       R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
1042   case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
1043   case tgtok::Id: {
1044     SMLoc NameLoc = Lex.getLoc();
1045     std::string Name = Lex.getCurStrVal();
1046     if (Lex.Lex() != tgtok::less)  // consume the Id.
1047       return ParseIDValue(CurRec, Name, NameLoc);    // Value ::= IDValue
1048     
1049     // Value ::= ID '<' ValueListNE '>'
1050     if (Lex.Lex() == tgtok::greater) {
1051       TokError("expected non-empty value list");
1052       return 0;
1053     }
1054
1055     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1056     // a new anonymous definition, deriving from CLASS<initvalslist> with no
1057     // body.
1058     Record *Class = Records.getClass(Name);
1059     if (!Class) {
1060       Error(NameLoc, "Expected a class name, got '" + Name + "'");
1061       return 0;
1062     }
1063
1064     std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1065     if (ValueList.empty()) return 0;
1066     
1067     if (Lex.getCode() != tgtok::greater) {
1068       TokError("expected '>' at end of value list");
1069       return 0;
1070     }
1071     Lex.Lex();  // eat the '>'
1072     
1073     // Create the new record, set it as CurRec temporarily.
1074     static unsigned AnonCounter = 0;
1075     Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),NameLoc);
1076     SubClassReference SCRef;
1077     SCRef.RefLoc = NameLoc;
1078     SCRef.Rec = Class;
1079     SCRef.TemplateArgs = ValueList;
1080     // Add info about the subclass to NewRec.
1081     if (AddSubClass(NewRec, SCRef))
1082       return 0;
1083     NewRec->resolveReferences();
1084     Records.addDef(NewRec);
1085     
1086     // The result of the expression is a reference to the new record.
1087     return new DefInit(NewRec);
1088   }    
1089   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1090     SMLoc BraceLoc = Lex.getLoc();
1091     Lex.Lex(); // eat the '{'
1092     std::vector<Init*> Vals;
1093     
1094     if (Lex.getCode() != tgtok::r_brace) {
1095       Vals = ParseValueList(CurRec);
1096       if (Vals.empty()) return 0;
1097     }
1098     if (Lex.getCode() != tgtok::r_brace) {
1099       TokError("expected '}' at end of bit list value");
1100       return 0;
1101     }
1102     Lex.Lex();  // eat the '}'
1103     
1104     BitsInit *Result = new BitsInit(Vals.size());
1105     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1106       Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
1107       if (Bit == 0) {
1108         Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1109               ") is not convertable to a bit");
1110         return 0;
1111       }
1112       Result->setBit(Vals.size()-i-1, Bit);
1113     }
1114     return Result;
1115   }
1116   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1117     Lex.Lex(); // eat the '['
1118     std::vector<Init*> Vals;
1119     
1120     RecTy *DeducedEltTy = 0;
1121     ListRecTy *GivenListTy = 0;
1122     
1123     if (ItemType != 0) {
1124       ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1125       if (ListType == 0) {
1126         std::stringstream s;
1127         s << "Type mismatch for list, expected list type, got " 
1128           << ItemType->getAsString();
1129         TokError(s.str());
1130       }
1131       GivenListTy = ListType;
1132     }    
1133
1134     if (Lex.getCode() != tgtok::r_square) {
1135       Vals = ParseValueList(CurRec, 0, GivenListTy ? GivenListTy->getElementType() : 0);
1136       if (Vals.empty()) return 0;
1137     }
1138     if (Lex.getCode() != tgtok::r_square) {
1139       TokError("expected ']' at end of list value");
1140       return 0;
1141     }
1142     Lex.Lex();  // eat the ']'
1143
1144     RecTy *GivenEltTy = 0;
1145     if (Lex.getCode() == tgtok::less) {
1146       // Optional list element type
1147       Lex.Lex();  // eat the '<'
1148
1149       GivenEltTy = ParseType();
1150       if (GivenEltTy == 0) {
1151         // Couldn't parse element type
1152         return 0;
1153       }
1154
1155       if (Lex.getCode() != tgtok::greater) {
1156         TokError("expected '>' at end of list element type");
1157         return 0;
1158       }
1159       Lex.Lex();  // eat the '>'
1160     }
1161
1162     // Check elements
1163     RecTy *EltTy = 0;
1164     for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1165          i != ie;
1166          ++i) {
1167       TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1168       if (TArg == 0) {
1169         TokError("Untyped list element");
1170         return 0;
1171       }
1172       if (EltTy != 0) {
1173         EltTy = resolveTypes(EltTy, TArg->getType());
1174         if (EltTy == 0) {
1175           TokError("Incompatible types in list elements");
1176           return 0;
1177         }
1178       }
1179       else {
1180         EltTy = TArg->getType();
1181       }
1182     }
1183
1184     if (GivenEltTy != 0) {
1185       if (EltTy != 0) {
1186         // Verify consistency
1187         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1188           TokError("Incompatible types in list elements");
1189           return 0;
1190         }
1191       }
1192       EltTy = GivenEltTy;
1193     }
1194
1195     if (EltTy == 0) {
1196       if (ItemType == 0) {
1197         TokError("No type for list");
1198         return 0;
1199       }
1200       DeducedEltTy = GivenListTy->getElementType();
1201    }
1202     else {
1203       // Make sure the deduced type is compatible with the given type
1204       if (GivenListTy) {
1205         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1206           TokError("Element type mismatch for list");
1207           return 0;
1208         }
1209       }
1210       DeducedEltTy = EltTy;
1211     }
1212     
1213     return new ListInit(Vals, DeducedEltTy);
1214   }
1215   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
1216     Lex.Lex();   // eat the '('
1217     if (Lex.getCode() != tgtok::Id
1218         && Lex.getCode() != tgtok::XCast
1219         && Lex.getCode() != tgtok::XNameConcat) {
1220       TokError("expected identifier in dag init");
1221       return 0;
1222     }
1223     
1224     Init *Operator = 0;
1225     if (Lex.getCode() == tgtok::Id) {
1226       Operator = ParseIDValue(CurRec);
1227       if (Operator == 0) return 0;
1228     }
1229     else {
1230       Operator = ParseOperation(CurRec);
1231       if (Operator == 0) return 0;
1232     }
1233
1234     // If the operator name is present, parse it.
1235     std::string OperatorName;
1236     if (Lex.getCode() == tgtok::colon) {
1237       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1238         TokError("expected variable name in dag operator");
1239         return 0;
1240       }
1241       OperatorName = Lex.getCurStrVal();
1242       Lex.Lex();  // eat the VarName.
1243     }
1244     
1245     std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1246     if (Lex.getCode() != tgtok::r_paren) {
1247       DagArgs = ParseDagArgList(CurRec);
1248       if (DagArgs.empty()) return 0;
1249     }
1250     
1251     if (Lex.getCode() != tgtok::r_paren) {
1252       TokError("expected ')' in dag init");
1253       return 0;
1254     }
1255     Lex.Lex();  // eat the ')'
1256     
1257     return new DagInit(Operator, OperatorName, DagArgs);
1258     break;
1259   }
1260  
1261   case tgtok::XCar:
1262   case tgtok::XCdr:
1263   case tgtok::XNull:
1264   case tgtok::XCast:  // Value ::= !unop '(' Value ')'
1265   case tgtok::XConcat:
1266   case tgtok::XSRA: 
1267   case tgtok::XSRL:
1268   case tgtok::XSHL:
1269   case tgtok::XStrConcat:
1270   case tgtok::XNameConcat:  // Value ::= !binop '(' Value ',' Value ')'
1271   case tgtok::XIf:
1272   case tgtok::XForEach:
1273   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1274     return ParseOperation(CurRec);
1275     break;
1276   }
1277   }
1278   
1279   return R;
1280 }
1281
1282 /// ParseValue - Parse a tblgen value.  This returns null on error.
1283 ///
1284 ///   Value       ::= SimpleValue ValueSuffix*
1285 ///   ValueSuffix ::= '{' BitList '}'
1286 ///   ValueSuffix ::= '[' BitList ']'
1287 ///   ValueSuffix ::= '.' ID
1288 ///
1289 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType) {
1290   Init *Result = ParseSimpleValue(CurRec, ItemType);
1291   if (Result == 0) return 0;
1292   
1293   // Parse the suffixes now if present.
1294   while (1) {
1295     switch (Lex.getCode()) {
1296     default: return Result;
1297     case tgtok::l_brace: {
1298       SMLoc CurlyLoc = Lex.getLoc();
1299       Lex.Lex(); // eat the '{'
1300       std::vector<unsigned> Ranges = ParseRangeList();
1301       if (Ranges.empty()) return 0;
1302       
1303       // Reverse the bitlist.
1304       std::reverse(Ranges.begin(), Ranges.end());
1305       Result = Result->convertInitializerBitRange(Ranges);
1306       if (Result == 0) {
1307         Error(CurlyLoc, "Invalid bit range for value");
1308         return 0;
1309       }
1310       
1311       // Eat the '}'.
1312       if (Lex.getCode() != tgtok::r_brace) {
1313         TokError("expected '}' at end of bit range list");
1314         return 0;
1315       }
1316       Lex.Lex();
1317       break;
1318     }
1319     case tgtok::l_square: {
1320       SMLoc SquareLoc = Lex.getLoc();
1321       Lex.Lex(); // eat the '['
1322       std::vector<unsigned> Ranges = ParseRangeList();
1323       if (Ranges.empty()) return 0;
1324       
1325       Result = Result->convertInitListSlice(Ranges);
1326       if (Result == 0) {
1327         Error(SquareLoc, "Invalid range for list slice");
1328         return 0;
1329       }
1330       
1331       // Eat the ']'.
1332       if (Lex.getCode() != tgtok::r_square) {
1333         TokError("expected ']' at end of list slice");
1334         return 0;
1335       }
1336       Lex.Lex();
1337       break;
1338     }
1339     case tgtok::period:
1340       if (Lex.Lex() != tgtok::Id) {  // eat the .
1341         TokError("expected field identifier after '.'");
1342         return 0;
1343       }
1344       if (!Result->getFieldType(Lex.getCurStrVal())) {
1345         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1346                  Result->getAsString() + "'");
1347         return 0;
1348       }
1349       Result = new FieldInit(Result, Lex.getCurStrVal());
1350       Lex.Lex();  // eat field name
1351       break;
1352     }
1353   }
1354 }
1355
1356 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1357 ///
1358 ///    ParseDagArgList ::= Value (':' VARNAME)?
1359 ///    ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1360 std::vector<std::pair<llvm::Init*, std::string> > 
1361 TGParser::ParseDagArgList(Record *CurRec) {
1362   std::vector<std::pair<llvm::Init*, std::string> > Result;
1363   
1364   while (1) {
1365     Init *Val = ParseValue(CurRec);
1366     if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1367     
1368     // If the variable name is present, add it.
1369     std::string VarName;
1370     if (Lex.getCode() == tgtok::colon) {
1371       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1372         TokError("expected variable name in dag literal");
1373         return std::vector<std::pair<llvm::Init*, std::string> >();
1374       }
1375       VarName = Lex.getCurStrVal();
1376       Lex.Lex();  // eat the VarName.
1377     }
1378     
1379     Result.push_back(std::make_pair(Val, VarName));
1380     
1381     if (Lex.getCode() != tgtok::comma) break;
1382     Lex.Lex(); // eat the ','    
1383   }
1384   
1385   return Result;
1386 }
1387
1388
1389 /// ParseValueList - Parse a comma separated list of values, returning them as a
1390 /// vector.  Note that this always expects to be able to parse at least one
1391 /// value.  It returns an empty list if this is not possible.
1392 ///
1393 ///   ValueList ::= Value (',' Value)
1394 ///
1395 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec, RecTy *EltTy) {
1396   std::vector<Init*> Result;
1397   RecTy *ItemType = EltTy;
1398   int ArgN = 0;
1399   if (ArgsRec != 0 && EltTy == 0) {
1400     const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1401     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1402     assert(RV && "Template argument record not found??");
1403     ItemType = RV->getType();
1404     ++ArgN;
1405   }
1406   Result.push_back(ParseValue(CurRec, ItemType));
1407   if (Result.back() == 0) return std::vector<Init*>();
1408   
1409   while (Lex.getCode() == tgtok::comma) {
1410     Lex.Lex();  // Eat the comma
1411     
1412     if (ArgsRec != 0 && EltTy == 0) {
1413       const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1414       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1415       assert(RV && "Template argument record not found??");
1416       ItemType = RV->getType();
1417       ++ArgN;
1418     }
1419     Result.push_back(ParseValue(CurRec, ItemType));
1420     if (Result.back() == 0) return std::vector<Init*>();
1421   }
1422   
1423   return Result;
1424 }
1425
1426
1427
1428 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1429 /// empty string on error.  This can happen in a number of different context's,
1430 /// including within a def or in the template args for a def (which which case
1431 /// CurRec will be non-null) and within the template args for a multiclass (in
1432 /// which case CurRec will be null, but CurMultiClass will be set).  This can
1433 /// also happen within a def that is within a multiclass, which will set both
1434 /// CurRec and CurMultiClass.
1435 ///
1436 ///  Declaration ::= FIELD? Type ID ('=' Value)?
1437 ///
1438 std::string TGParser::ParseDeclaration(Record *CurRec, 
1439                                        bool ParsingTemplateArgs) {
1440   // Read the field prefix if present.
1441   bool HasField = Lex.getCode() == tgtok::Field;
1442   if (HasField) Lex.Lex();
1443   
1444   RecTy *Type = ParseType();
1445   if (Type == 0) return "";
1446   
1447   if (Lex.getCode() != tgtok::Id) {
1448     TokError("Expected identifier in declaration");
1449     return "";
1450   }
1451   
1452   SMLoc IdLoc = Lex.getLoc();
1453   std::string DeclName = Lex.getCurStrVal();
1454   Lex.Lex();
1455   
1456   if (ParsingTemplateArgs) {
1457     if (CurRec) {
1458       DeclName = CurRec->getName() + ":" + DeclName;
1459     } else {
1460       assert(CurMultiClass);
1461     }
1462     if (CurMultiClass)
1463       DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1464   }
1465   
1466   // Add the value.
1467   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1468     return "";
1469   
1470   // If a value is present, parse it.
1471   if (Lex.getCode() == tgtok::equal) {
1472     Lex.Lex();
1473     SMLoc ValLoc = Lex.getLoc();
1474     Init *Val = ParseValue(CurRec, Type);
1475     if (Val == 0 ||
1476         SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1477       return "";
1478   }
1479   
1480   return DeclName;
1481 }
1482
1483 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1484 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
1485 /// template args for a def, which may or may not be in a multiclass.  If null,
1486 /// these are the template args for a multiclass.
1487 ///
1488 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1489 /// 
1490 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1491   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1492   Lex.Lex(); // eat the '<'
1493   
1494   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1495   
1496   // Read the first declaration.
1497   std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1498   if (TemplArg.empty())
1499     return true;
1500   
1501   TheRecToAddTo->addTemplateArg(TemplArg);
1502   
1503   while (Lex.getCode() == tgtok::comma) {
1504     Lex.Lex(); // eat the ','
1505     
1506     // Read the following declarations.
1507     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1508     if (TemplArg.empty())
1509       return true;
1510     TheRecToAddTo->addTemplateArg(TemplArg);
1511   }
1512   
1513   if (Lex.getCode() != tgtok::greater)
1514     return TokError("expected '>' at end of template argument list");
1515   Lex.Lex(); // eat the '>'.
1516   return false;
1517 }
1518
1519
1520 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1521 ///
1522 ///   BodyItem ::= Declaration ';'
1523 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
1524 bool TGParser::ParseBodyItem(Record *CurRec) {
1525   if (Lex.getCode() != tgtok::Let) {
1526     if (ParseDeclaration(CurRec, false).empty()) 
1527       return true;
1528     
1529     if (Lex.getCode() != tgtok::semi)
1530       return TokError("expected ';' after declaration");
1531     Lex.Lex();
1532     return false;
1533   }
1534
1535   // LET ID OptionalRangeList '=' Value ';'
1536   if (Lex.Lex() != tgtok::Id)
1537     return TokError("expected field identifier after let");
1538   
1539   SMLoc IdLoc = Lex.getLoc();
1540   std::string FieldName = Lex.getCurStrVal();
1541   Lex.Lex();  // eat the field name.
1542   
1543   std::vector<unsigned> BitList;
1544   if (ParseOptionalBitList(BitList)) 
1545     return true;
1546   std::reverse(BitList.begin(), BitList.end());
1547   
1548   if (Lex.getCode() != tgtok::equal)
1549     return TokError("expected '=' in let expression");
1550   Lex.Lex();  // eat the '='.
1551   
1552   RecordVal *Field = CurRec->getValue(FieldName);
1553   if (Field == 0)
1554     return TokError("Value '" + FieldName + "' unknown!");
1555
1556   RecTy *Type = Field->getType();
1557   
1558   Init *Val = ParseValue(CurRec, Type);
1559   if (Val == 0) return true;
1560   
1561   if (Lex.getCode() != tgtok::semi)
1562     return TokError("expected ';' after let expression");
1563   Lex.Lex();
1564   
1565   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1566 }
1567
1568 /// ParseBody - Read the body of a class or def.  Return true on error, false on
1569 /// success.
1570 ///
1571 ///   Body     ::= ';'
1572 ///   Body     ::= '{' BodyList '}'
1573 ///   BodyList BodyItem*
1574 ///
1575 bool TGParser::ParseBody(Record *CurRec) {
1576   // If this is a null definition, just eat the semi and return.
1577   if (Lex.getCode() == tgtok::semi) {
1578     Lex.Lex();
1579     return false;
1580   }
1581   
1582   if (Lex.getCode() != tgtok::l_brace)
1583     return TokError("Expected ';' or '{' to start body");
1584   // Eat the '{'.
1585   Lex.Lex();
1586   
1587   while (Lex.getCode() != tgtok::r_brace)
1588     if (ParseBodyItem(CurRec))
1589       return true;
1590
1591   // Eat the '}'.
1592   Lex.Lex();
1593   return false;
1594 }
1595
1596 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
1597 /// optional ClassList followed by a Body.  CurRec is the current def or class
1598 /// that is being parsed.
1599 ///
1600 ///   ObjectBody      ::= BaseClassList Body
1601 ///   BaseClassList   ::= /*empty*/
1602 ///   BaseClassList   ::= ':' BaseClassListNE
1603 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1604 ///
1605 bool TGParser::ParseObjectBody(Record *CurRec) {
1606   // If there is a baseclass list, read it.
1607   if (Lex.getCode() == tgtok::colon) {
1608     Lex.Lex();
1609     
1610     // Read all of the subclasses.
1611     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1612     while (1) {
1613       // Check for error.
1614       if (SubClass.Rec == 0) return true;
1615      
1616       // Add it.
1617       if (AddSubClass(CurRec, SubClass))
1618         return true;
1619       
1620       if (Lex.getCode() != tgtok::comma) break;
1621       Lex.Lex(); // eat ','.
1622       SubClass = ParseSubClassReference(CurRec, false);
1623     }
1624   }
1625
1626   // Process any variables on the let stack.
1627   for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1628     for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1629       if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1630                    LetStack[i][j].Bits, LetStack[i][j].Value))
1631         return true;
1632   
1633   return ParseBody(CurRec);
1634 }
1635
1636
1637 /// ParseDef - Parse and return a top level or multiclass def, return the record
1638 /// corresponding to it.  This returns null on error.
1639 ///
1640 ///   DefInst ::= DEF ObjectName ObjectBody
1641 ///
1642 llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
1643   SMLoc DefLoc = Lex.getLoc();
1644   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1645   Lex.Lex();  // Eat the 'def' token.  
1646
1647   // Parse ObjectName and make a record for it.
1648   Record *CurRec = new Record(ParseObjectName(), DefLoc);
1649   
1650   if (!CurMultiClass) {
1651     // Top-level def definition.
1652     
1653     // Ensure redefinition doesn't happen.
1654     if (Records.getDef(CurRec->getName())) {
1655       Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1656       return 0;
1657     }
1658     Records.addDef(CurRec);
1659   } else {
1660     // Otherwise, a def inside a multiclass, add it to the multiclass.
1661     for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1662       if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1663         Error(DefLoc, "def '" + CurRec->getName() +
1664               "' already defined in this multiclass!");
1665         return 0;
1666       }
1667     CurMultiClass->DefPrototypes.push_back(CurRec);
1668   }
1669   
1670   if (ParseObjectBody(CurRec))
1671     return 0;
1672   
1673   if (CurMultiClass == 0)  // Def's in multiclasses aren't really defs.
1674     CurRec->resolveReferences();
1675   
1676   // If ObjectBody has template arguments, it's an error.
1677   assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1678   return CurRec;
1679 }
1680
1681
1682 /// ParseClass - Parse a tblgen class definition.
1683 ///
1684 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1685 ///
1686 bool TGParser::ParseClass() {
1687   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1688   Lex.Lex();
1689   
1690   if (Lex.getCode() != tgtok::Id)
1691     return TokError("expected class name after 'class' keyword");
1692   
1693   Record *CurRec = Records.getClass(Lex.getCurStrVal());
1694   if (CurRec) {
1695     // If the body was previously defined, this is an error.
1696     if (!CurRec->getValues().empty() ||
1697         !CurRec->getSuperClasses().empty() ||
1698         !CurRec->getTemplateArgs().empty())
1699       return TokError("Class '" + CurRec->getName() + "' already defined");
1700   } else {
1701     // If this is the first reference to this class, create and add it.
1702     CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
1703     Records.addClass(CurRec);
1704   }
1705   Lex.Lex(); // eat the name.
1706   
1707   // If there are template args, parse them.
1708   if (Lex.getCode() == tgtok::less)
1709     if (ParseTemplateArgList(CurRec))
1710       return true;
1711
1712   // Finally, parse the object body.
1713   return ParseObjectBody(CurRec);
1714 }
1715
1716 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1717 /// of LetRecords.
1718 ///
1719 ///   LetList ::= LetItem (',' LetItem)*
1720 ///   LetItem ::= ID OptionalRangeList '=' Value
1721 ///
1722 std::vector<LetRecord> TGParser::ParseLetList() {
1723   std::vector<LetRecord> Result;
1724   
1725   while (1) {
1726     if (Lex.getCode() != tgtok::Id) {
1727       TokError("expected identifier in let definition");
1728       return std::vector<LetRecord>();
1729     }
1730     std::string Name = Lex.getCurStrVal();
1731     SMLoc NameLoc = Lex.getLoc();
1732     Lex.Lex();  // Eat the identifier. 
1733
1734     // Check for an optional RangeList.
1735     std::vector<unsigned> Bits;
1736     if (ParseOptionalRangeList(Bits)) 
1737       return std::vector<LetRecord>();
1738     std::reverse(Bits.begin(), Bits.end());
1739     
1740     if (Lex.getCode() != tgtok::equal) {
1741       TokError("expected '=' in let expression");
1742       return std::vector<LetRecord>();
1743     }
1744     Lex.Lex();  // eat the '='.
1745     
1746     Init *Val = ParseValue(0);
1747     if (Val == 0) return std::vector<LetRecord>();
1748     
1749     // Now that we have everything, add the record.
1750     Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1751     
1752     if (Lex.getCode() != tgtok::comma)
1753       return Result;
1754     Lex.Lex();  // eat the comma.    
1755   }
1756 }
1757
1758 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
1759 /// different related productions.
1760 ///
1761 ///   Object ::= LET LetList IN '{' ObjectList '}'
1762 ///   Object ::= LET LetList IN Object
1763 ///
1764 bool TGParser::ParseTopLevelLet() {
1765   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1766   Lex.Lex();
1767   
1768   // Add this entry to the let stack.
1769   std::vector<LetRecord> LetInfo = ParseLetList();
1770   if (LetInfo.empty()) return true;
1771   LetStack.push_back(LetInfo);
1772
1773   if (Lex.getCode() != tgtok::In)
1774     return TokError("expected 'in' at end of top-level 'let'");
1775   Lex.Lex();
1776   
1777   // If this is a scalar let, just handle it now
1778   if (Lex.getCode() != tgtok::l_brace) {
1779     // LET LetList IN Object
1780     if (ParseObject())
1781       return true;
1782   } else {   // Object ::= LETCommand '{' ObjectList '}'
1783     SMLoc BraceLoc = Lex.getLoc();
1784     // Otherwise, this is a group let.
1785     Lex.Lex();  // eat the '{'.
1786     
1787     // Parse the object list.
1788     if (ParseObjectList())
1789       return true;
1790     
1791     if (Lex.getCode() != tgtok::r_brace) {
1792       TokError("expected '}' at end of top level let command");
1793       return Error(BraceLoc, "to match this '{'");
1794     }
1795     Lex.Lex();
1796   }
1797   
1798   // Outside this let scope, this let block is not active.
1799   LetStack.pop_back();
1800   return false;
1801 }
1802
1803 /// ParseMultiClassDef - Parse a def in a multiclass context.
1804 ///
1805 ///  MultiClassDef ::= DefInst
1806 ///
1807 bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1808   if (Lex.getCode() != tgtok::Def) 
1809     return TokError("expected 'def' in multiclass body");
1810
1811   Record *D = ParseDef(CurMC);
1812   if (D == 0) return true;
1813   
1814   // Copy the template arguments for the multiclass into the def.
1815   const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1816   
1817   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1818     const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1819     assert(RV && "Template arg doesn't exist?");
1820     D->addValue(*RV);
1821   }
1822
1823   return false;
1824 }
1825
1826 /// ParseMultiClass - Parse a multiclass definition.
1827 ///
1828 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
1829 ///                     ':' BaseMultiClassList '{' MultiClassDef+ '}'
1830 ///
1831 bool TGParser::ParseMultiClass() {
1832   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1833   Lex.Lex();  // Eat the multiclass token.
1834
1835   if (Lex.getCode() != tgtok::Id)
1836     return TokError("expected identifier after multiclass for name");
1837   std::string Name = Lex.getCurStrVal();
1838   
1839   if (MultiClasses.count(Name))
1840     return TokError("multiclass '" + Name + "' already defined");
1841   
1842   CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
1843   Lex.Lex();  // Eat the identifier.
1844   
1845   // If there are template args, parse them.
1846   if (Lex.getCode() == tgtok::less)
1847     if (ParseTemplateArgList(0))
1848       return true;
1849
1850   bool inherits = false;
1851
1852   // If there are submulticlasses, parse them.
1853   if (Lex.getCode() == tgtok::colon) {
1854     inherits = true;
1855
1856     Lex.Lex();
1857
1858     // Read all of the submulticlasses.
1859     SubMultiClassReference SubMultiClass =
1860       ParseSubMultiClassReference(CurMultiClass);
1861     while (1) {
1862       // Check for error.
1863       if (SubMultiClass.MC == 0) return true;
1864
1865       // Add it.
1866       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1867         return true;
1868
1869       if (Lex.getCode() != tgtok::comma) break;
1870       Lex.Lex(); // eat ','.
1871       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1872     }
1873   }
1874
1875   if (Lex.getCode() != tgtok::l_brace) {
1876     if (!inherits)
1877       return TokError("expected '{' in multiclass definition");
1878     else
1879       if (Lex.getCode() != tgtok::semi)
1880         return TokError("expected ';' in multiclass definition");
1881       else
1882         Lex.Lex();  // eat the ';'.
1883   }
1884   else {
1885     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
1886       return TokError("multiclass must contain at least one def");
1887   
1888     while (Lex.getCode() != tgtok::r_brace)
1889       if (ParseMultiClassDef(CurMultiClass))
1890         return true;
1891   
1892     Lex.Lex();  // eat the '}'.
1893   }
1894   
1895   CurMultiClass = 0;
1896   return false;
1897 }
1898
1899 /// ParseDefm - Parse the instantiation of a multiclass.
1900 ///
1901 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1902 ///
1903 bool TGParser::ParseDefm() {
1904   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1905   if (Lex.Lex() != tgtok::Id)  // eat the defm.
1906     return TokError("expected identifier after defm");
1907   
1908   SMLoc DefmPrefixLoc = Lex.getLoc();
1909   std::string DefmPrefix = Lex.getCurStrVal();
1910   if (Lex.Lex() != tgtok::colon)
1911     return TokError("expected ':' after defm identifier");
1912   
1913   // eat the colon.
1914   Lex.Lex();
1915
1916   SMLoc SubClassLoc = Lex.getLoc();
1917   SubClassReference Ref = ParseSubClassReference(0, true);
1918
1919   while (1) {
1920     if (Ref.Rec == 0) return true;
1921
1922     // To instantiate a multiclass, we need to first get the multiclass, then
1923     // instantiate each def contained in the multiclass with the SubClassRef
1924     // template parameters.
1925     MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1926     assert(MC && "Didn't lookup multiclass correctly?");
1927     std::vector<Init*> &TemplateVals = Ref.TemplateArgs;   
1928
1929     // Verify that the correct number of template arguments were specified.
1930     const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1931     if (TArgs.size() < TemplateVals.size())
1932       return Error(SubClassLoc,
1933                    "more template args specified than multiclass expects");
1934
1935     // Loop over all the def's in the multiclass, instantiating each one.
1936     for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1937       Record *DefProto = MC->DefPrototypes[i];
1938
1939       // Add in the defm name
1940       std::string DefName = DefProto->getName();
1941       std::string::size_type idx = DefName.find("#NAME#");
1942       if (idx != std::string::npos) {
1943         DefName.replace(idx, 6, DefmPrefix);
1944       }
1945       else {
1946         // Add the suffix to the defm name to get the new name.
1947         DefName = DefmPrefix + DefName;
1948       }
1949
1950       Record *CurRec = new Record(DefName, DefmPrefixLoc);
1951
1952       SubClassReference Ref;
1953       Ref.RefLoc = DefmPrefixLoc;
1954       Ref.Rec = DefProto;
1955       AddSubClass(CurRec, Ref);
1956
1957       // Loop over all of the template arguments, setting them to the specified
1958       // value or leaving them as the default if necessary.
1959       for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1960         // Check if a value is specified for this temp-arg.
1961         if (i < TemplateVals.size()) {
1962           // Set it now.
1963           if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1964                        TemplateVals[i]))
1965             return true;
1966
1967           // Resolve it next.
1968           CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1969
1970           // Now remove it.
1971           CurRec->removeValue(TArgs[i]);
1972
1973         } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1974           return Error(SubClassLoc,
1975                        "value not specified for template argument #"+
1976                        utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1977                        MC->Rec.getName() + "'");
1978         }
1979       }
1980
1981       // If the mdef is inside a 'let' expression, add to each def.
1982       for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1983         for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1984           if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1985                        LetStack[i][j].Bits, LetStack[i][j].Value)) {
1986             Error(DefmPrefixLoc, "when instantiating this defm");
1987             return true;
1988           }
1989
1990       // Ensure redefinition doesn't happen.
1991       if (Records.getDef(CurRec->getName()))
1992         return Error(DefmPrefixLoc, "def '" + CurRec->getName() + 
1993                      "' already defined, instantiating defm with subdef '" + 
1994                      DefProto->getName() + "'");
1995       Records.addDef(CurRec);
1996       CurRec->resolveReferences();
1997     }
1998
1999     if (Lex.getCode() != tgtok::comma) break;
2000     Lex.Lex(); // eat ','.
2001
2002     SubClassLoc = Lex.getLoc();
2003     Ref = ParseSubClassReference(0, true);
2004   }
2005
2006   if (Lex.getCode() != tgtok::semi)
2007     return TokError("expected ';' at end of defm");
2008   Lex.Lex();
2009   
2010   return false;
2011 }
2012
2013 /// ParseObject
2014 ///   Object ::= ClassInst
2015 ///   Object ::= DefInst
2016 ///   Object ::= MultiClassInst
2017 ///   Object ::= DefMInst
2018 ///   Object ::= LETCommand '{' ObjectList '}'
2019 ///   Object ::= LETCommand Object
2020 bool TGParser::ParseObject() {
2021   switch (Lex.getCode()) {
2022   default: assert(0 && "This is not an object");
2023   case tgtok::Let:   return ParseTopLevelLet();
2024   case tgtok::Def:   return ParseDef(0) == 0;
2025   case tgtok::Defm:  return ParseDefm();
2026   case tgtok::Class: return ParseClass();
2027   case tgtok::MultiClass: return ParseMultiClass();
2028   }
2029 }
2030
2031 /// ParseObjectList
2032 ///   ObjectList :== Object*
2033 bool TGParser::ParseObjectList() {
2034   while (isObjectStart(Lex.getCode())) {
2035     if (ParseObject())
2036       return true;
2037   }
2038   return false;
2039 }
2040
2041
2042 bool TGParser::ParseFile() {
2043   Lex.Lex(); // Prime the lexer.
2044   if (ParseObjectList()) return true;
2045   
2046   // If we have unread input at the end of the file, report it.
2047   if (Lex.getCode() == tgtok::Eof)
2048     return false;
2049   
2050   return TokError("Unexpected input at top level");
2051 }
2052