Add TGParser files to VStudio project files. Removed generated files section from...
[oota-llvm.git] / utils / TableGen / TGParser.cpp
1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implement the Parser for TableGen.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include <algorithm>
15
16 #include "TGParser.h"
17 #include "Record.h"
18 #include "llvm/ADT/StringExtras.h"
19 using namespace llvm;
20
21 //===----------------------------------------------------------------------===//
22 // Support Code for the Semantic Actions.
23 //===----------------------------------------------------------------------===//
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 struct SubClassReference {
34   TGParser::LocTy RefLoc;
35   Record *Rec;
36   std::vector<Init*> TemplateArgs;
37   SubClassReference() : RefLoc(0), Rec(0) {}
38   
39   bool isInvalid() const { return Rec == 0; }
40 };
41   
42 } // end namespace llvm
43
44 bool TGParser::AddValue(Record *CurRec, LocTy Loc, const RecordVal &RV) {
45   if (CurRec == 0)
46     CurRec = &CurMultiClass->Rec;
47   
48   if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
49     // The value already exists in the class, treat this as a set.
50     if (ERV->setValue(RV.getValue()))
51       return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
52                    RV.getType()->getAsString() + "' is incompatible with " +
53                    "previous definition of type '" + 
54                    ERV->getType()->getAsString() + "'");
55   } else {
56     CurRec->addValue(RV);
57   }
58   return false;
59 }
60
61 /// SetValue -
62 /// Return true on error, false on success.
63 bool TGParser::SetValue(Record *CurRec, LocTy Loc, const std::string &ValName, 
64                         const std::vector<unsigned> &BitList, Init *V) {
65   if (!V) return false;
66
67   if (CurRec == 0) CurRec = &CurMultiClass->Rec;
68
69   RecordVal *RV = CurRec->getValue(ValName);
70   if (RV == 0)
71     return Error(Loc, "Value '" + ValName + "' unknown!");
72
73   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
74   // in the resolution machinery.
75   if (BitList.empty())
76     if (VarInit *VI = dynamic_cast<VarInit*>(V))
77       if (VI->getName() == ValName)
78         return false;
79   
80   // If we are assigning to a subset of the bits in the value... then we must be
81   // assigning to a field of BitsRecTy, which must have a BitsInit
82   // initializer.
83   //
84   if (!BitList.empty()) {
85     BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
86     if (CurVal == 0)
87       return Error(Loc, "Value '" + ValName + "' is not a bits type");
88
89     // Convert the incoming value to a bits type of the appropriate size...
90     Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
91     if (BI == 0) {
92       V->convertInitializerTo(new BitsRecTy(BitList.size()));
93       return Error(Loc, "Initializer is not compatible with bit range");
94     }
95                    
96     // We should have a BitsInit type now.
97     BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
98     assert(BInit != 0);
99
100     BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
101
102     // Loop over bits, assigning values as appropriate.
103     for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
104       unsigned Bit = BitList[i];
105       if (NewVal->getBit(Bit))
106         return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
107                      ValName + "' more than once");
108       NewVal->setBit(Bit, BInit->getBit(i));
109     }
110
111     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
112       if (NewVal->getBit(i) == 0)
113         NewVal->setBit(i, CurVal->getBit(i));
114
115     V = NewVal;
116   }
117
118   if (RV->setValue(V))
119    return Error(Loc, "Value '" + ValName + "' of type '" + 
120                 RV->getType()->getAsString() + 
121                 "' is incompatible with initializer '" + V->getAsString() +"'");
122   return false;
123 }
124
125 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
126 /// args as SubClass's template arguments.
127 bool TGParser::AddSubClass(Record *CurRec, class SubClassReference &SubClass) {
128   Record *SC = SubClass.Rec;
129   // Add all of the values in the subclass into the current class.
130   const std::vector<RecordVal> &Vals = SC->getValues();
131   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
132     if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
133       return true;
134
135   const std::vector<std::string> &TArgs = SC->getTemplateArgs();
136
137   // Ensure that an appropriate number of template arguments are specified.
138   if (TArgs.size() < SubClass.TemplateArgs.size())
139     return Error(SubClass.RefLoc, "More template args specified than expected");
140   
141   // Loop over all of the template arguments, setting them to the specified
142   // value or leaving them as the default if necessary.
143   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
144     if (i < SubClass.TemplateArgs.size()) {
145       // If a value is specified for this template arg, set it now.
146       if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(), 
147                    SubClass.TemplateArgs[i]))
148         return true;
149       
150       // Resolve it next.
151       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
152       
153       // Now remove it.
154       CurRec->removeValue(TArgs[i]);
155
156     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
157       return Error(SubClass.RefLoc,"Value not specified for template argument #"
158                    + utostr(i) + " (" + TArgs[i] + ") of subclass '" + 
159                    SC->getName() + "'!");
160     }
161   }
162
163   // Since everything went well, we can now set the "superclass" list for the
164   // current record.
165   const std::vector<Record*> &SCs = SC->getSuperClasses();
166   for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
167     if (CurRec->isSubClassOf(SCs[i]))
168       return Error(SubClass.RefLoc,
169                    "Already subclass of '" + SCs[i]->getName() + "'!\n");
170     CurRec->addSuperClass(SCs[i]);
171   }
172   
173   if (CurRec->isSubClassOf(SC))
174     return Error(SubClass.RefLoc,
175                  "Already subclass of '" + SC->getName() + "'!\n");
176   CurRec->addSuperClass(SC);
177   return false;
178 }
179
180 //===----------------------------------------------------------------------===//
181 // Parser Code
182 //===----------------------------------------------------------------------===//
183
184 /// isObjectStart - Return true if this is a valid first token for an Object.
185 static bool isObjectStart(tgtok::TokKind K) {
186   return K == tgtok::Class || K == tgtok::Def ||
187          K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass; 
188 }
189
190 /// ParseObjectName - If an object name is specified, return it.  Otherwise,
191 /// return an anonymous name.
192 ///   ObjectName ::= ID
193 ///   ObjectName ::= /*empty*/
194 ///
195 std::string TGParser::ParseObjectName() {
196   if (Lex.getCode() == tgtok::Id) {
197     std::string Ret = Lex.getCurStrVal();
198     Lex.Lex();
199     return Ret;
200   }
201   
202   static unsigned AnonCounter = 0;
203   return "anonymous."+utostr(AnonCounter++);
204 }
205
206
207 /// ParseClassID - Parse and resolve a reference to a class name.  This returns
208 /// null on error.
209 ///
210 ///    ClassID ::= ID
211 ///
212 Record *TGParser::ParseClassID() {
213   if (Lex.getCode() != tgtok::Id) {
214     TokError("expected name for ClassID");
215     return 0;
216   }
217   
218   Record *Result = Records.getClass(Lex.getCurStrVal());
219   if (Result == 0)
220     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
221   
222   Lex.Lex();
223   return Result;
224 }
225
226 Record *TGParser::ParseDefmID() {
227   if (Lex.getCode() != tgtok::Id) {
228     TokError("expected multiclass name");
229     return 0;
230   }
231   
232   MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
233   if (MC == 0) {
234     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
235     return 0;
236   }
237   
238   Lex.Lex();
239   return &MC->Rec;
240 }  
241
242
243
244 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
245 /// subclass.  This returns a SubClassRefTy with a null Record* on error.
246 ///
247 ///  SubClassRef ::= ClassID
248 ///  SubClassRef ::= ClassID '<' ValueList '>'
249 ///
250 SubClassReference TGParser::
251 ParseSubClassReference(Record *CurRec, bool isDefm) {
252   SubClassReference Result;
253   Result.RefLoc = Lex.getLoc();
254   
255   if (isDefm)
256     Result.Rec = ParseDefmID();
257   else
258     Result.Rec = ParseClassID();
259   if (Result.Rec == 0) return Result;
260   
261   // If there is no template arg list, we're done.
262   if (Lex.getCode() != tgtok::less)
263     return Result;
264   Lex.Lex();  // Eat the '<'
265   
266   if (Lex.getCode() == tgtok::greater) {
267     TokError("subclass reference requires a non-empty list of template values");
268     Result.Rec = 0;
269     return Result;
270   }
271   
272   Result.TemplateArgs = ParseValueList(CurRec);
273   if (Result.TemplateArgs.empty()) {
274     Result.Rec = 0;   // Error parsing value list.
275     return Result;
276   }
277     
278   if (Lex.getCode() != tgtok::greater) {
279     TokError("expected '>' in template value list");
280     Result.Rec = 0;
281     return Result;
282   }
283   Lex.Lex();
284   
285   return Result;
286 }
287
288 /// ParseRangePiece - Parse a bit/value range.
289 ///   RangePiece ::= INTVAL
290 ///   RangePiece ::= INTVAL '-' INTVAL
291 ///   RangePiece ::= INTVAL INTVAL
292 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
293   assert(Lex.getCode() == tgtok::IntVal && "Invalid range");
294   int Start = Lex.getCurIntVal();
295   int End;
296   
297   if (Start < 0)
298     return TokError("invalid range, cannot be negative");
299   
300   switch (Lex.Lex()) {  // eat first character.
301   default: 
302     Ranges.push_back(Start);
303     return false;
304   case tgtok::minus:
305     if (Lex.Lex() != tgtok::IntVal) {
306       TokError("expected integer value as end of range");
307       return true;
308     }
309     End = Lex.getCurIntVal();
310     break;
311   case tgtok::IntVal:
312     End = -Lex.getCurIntVal();
313     break;
314   }
315   if (End < 0) 
316     return TokError("invalid range, cannot be negative");
317   Lex.Lex();
318   
319   // Add to the range.
320   if (Start < End) {
321     for (; Start <= End; ++Start)
322       Ranges.push_back(Start);
323   } else {
324     for (; Start >= End; --Start)
325       Ranges.push_back(Start);
326   }
327   return false;
328 }
329
330 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
331 ///
332 ///   RangeList ::= RangePiece (',' RangePiece)*
333 ///
334 std::vector<unsigned> TGParser::ParseRangeList() {
335   std::vector<unsigned> Result;
336   
337   // Parse the first piece.
338   if (ParseRangePiece(Result))
339     return std::vector<unsigned>();
340   while (Lex.getCode() == tgtok::comma) {
341     Lex.Lex();  // Eat the comma.
342
343     // Parse the next range piece.
344     if (ParseRangePiece(Result))
345       return std::vector<unsigned>();
346   }
347   return Result;
348 }
349
350 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
351 ///   OptionalRangeList ::= '<' RangeList '>'
352 ///   OptionalRangeList ::= /*empty*/
353 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
354   if (Lex.getCode() != tgtok::less)
355     return false;
356   
357   LocTy StartLoc = Lex.getLoc();
358   Lex.Lex(); // eat the '<'
359   
360   // Parse the range list.
361   Ranges = ParseRangeList();
362   if (Ranges.empty()) return true;
363   
364   if (Lex.getCode() != tgtok::greater) {
365     TokError("expected '>' at end of range list");
366     return Error(StartLoc, "to match this '<'");
367   }
368   Lex.Lex();   // eat the '>'.
369   return false;
370 }
371
372 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
373 ///   OptionalBitList ::= '{' RangeList '}'
374 ///   OptionalBitList ::= /*empty*/
375 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
376   if (Lex.getCode() != tgtok::l_brace)
377     return false;
378   
379   LocTy StartLoc = Lex.getLoc();
380   Lex.Lex(); // eat the '{'
381   
382   // Parse the range list.
383   Ranges = ParseRangeList();
384   if (Ranges.empty()) return true;
385   
386   if (Lex.getCode() != tgtok::r_brace) {
387     TokError("expected '}' at end of bit list");
388     return Error(StartLoc, "to match this '{'");
389   }
390   Lex.Lex();   // eat the '}'.
391   return false;
392 }
393
394
395 /// ParseType - Parse and return a tblgen type.  This returns null on error.
396 ///
397 ///   Type ::= STRING                       // string type
398 ///   Type ::= BIT                          // bit type
399 ///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
400 ///   Type ::= INT                          // int type
401 ///   Type ::= LIST '<' Type '>'            // list<x> type
402 ///   Type ::= CODE                         // code type
403 ///   Type ::= DAG                          // dag type
404 ///   Type ::= ClassID                      // Record Type
405 ///
406 RecTy *TGParser::ParseType() {
407   switch (Lex.getCode()) {
408   default: TokError("Unknown token when expecting a type"); return 0;
409   case tgtok::String: Lex.Lex(); return new StringRecTy();
410   case tgtok::Bit:    Lex.Lex(); return new BitRecTy();
411   case tgtok::Int:    Lex.Lex(); return new IntRecTy();
412   case tgtok::Code:   Lex.Lex(); return new CodeRecTy();
413   case tgtok::Dag:    Lex.Lex(); return new DagRecTy();
414   case tgtok::Id:
415     if (Record *R = ParseClassID()) return new RecordRecTy(R);
416     return 0;
417   case tgtok::Bits: {
418     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
419       TokError("expected '<' after bits type");
420       return 0;
421     }
422     if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
423       TokError("expected integer in bits<n> type");
424       return 0;
425     }
426     unsigned Val = Lex.getCurIntVal();
427     if (Lex.Lex() != tgtok::greater) {  // Eat count.
428       TokError("expected '>' at end of bits<n> type");
429       return 0;
430     }
431     Lex.Lex();  // Eat '>'
432     return new BitsRecTy(Val);
433   }
434   case tgtok::List: {
435     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
436       TokError("expected '<' after list type");
437       return 0;
438     }
439     Lex.Lex();  // Eat '<'
440     RecTy *SubType = ParseType();
441     if (SubType == 0) return 0;
442     
443     if (Lex.getCode() != tgtok::greater) {
444       TokError("expected '>' at end of list<ty> type");
445       return 0;
446     }
447     Lex.Lex();  // Eat '>'
448     return new ListRecTy(SubType);
449   }
450   }      
451 }
452
453 /// ParseIDValue - Parse an ID as a value and decode what it means.
454 ///
455 ///  IDValue ::= ID [def local value]
456 ///  IDValue ::= ID [def template arg]
457 ///  IDValue ::= ID [multiclass local value]
458 ///  IDValue ::= ID [multiclass template argument]
459 ///  IDValue ::= ID [def name]
460 ///
461 Init *TGParser::ParseIDValue(Record *CurRec) {
462   assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
463   std::string Name = Lex.getCurStrVal();
464   LocTy Loc = Lex.getLoc();
465   Lex.Lex();
466   return ParseIDValue(CurRec, Name, Loc);
467 }
468
469 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
470 /// has already been read.
471 Init *TGParser::ParseIDValue(Record *CurRec, 
472                              const std::string &Name, LocTy NameLoc) {
473   if (CurRec) {
474     if (const RecordVal *RV = CurRec->getValue(Name))
475       return new VarInit(Name, RV->getType());
476     
477     std::string TemplateArgName = CurRec->getName()+":"+Name;
478     if (CurRec->isTemplateArg(TemplateArgName)) {
479       const RecordVal *RV = CurRec->getValue(TemplateArgName);
480       assert(RV && "Template arg doesn't exist??");
481       return new VarInit(TemplateArgName, RV->getType());
482     }
483   }
484   
485   if (CurMultiClass) {
486     std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
487     if (CurMultiClass->Rec.isTemplateArg(MCName)) {
488       const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
489       assert(RV && "Template arg doesn't exist??");
490       return new VarInit(MCName, RV->getType());
491     }
492   }
493   
494   if (Record *D = Records.getDef(Name))
495     return new DefInit(D);
496
497   Error(NameLoc, "Variable not defined: '" + Name + "'");
498   return 0;
499 }
500
501 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
502 ///
503 ///   SimpleValue ::= IDValue
504 ///   SimpleValue ::= INTVAL
505 ///   SimpleValue ::= STRVAL
506 ///   SimpleValue ::= CODEFRAGMENT
507 ///   SimpleValue ::= '?'
508 ///   SimpleValue ::= '{' ValueList '}'
509 ///   SimpleValue ::= ID '<' ValueListNE '>'
510 ///   SimpleValue ::= '[' ValueList ']'
511 ///   SimpleValue ::= '(' IDValue DagArgList ')'
512 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
513 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
514 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
515 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
516 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
517 ///
518 Init *TGParser::ParseSimpleValue(Record *CurRec) {
519   Init *R = 0;
520   switch (Lex.getCode()) {
521   default: TokError("Unknown token when parsing a value"); break;
522   case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
523   case tgtok::StrVal: R = new StringInit(Lex.getCurStrVal()); Lex.Lex(); break;
524   case tgtok::CodeFragment:
525       R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
526   case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
527   case tgtok::Id: {
528     LocTy NameLoc = Lex.getLoc();
529     std::string Name = Lex.getCurStrVal();
530     if (Lex.Lex() != tgtok::less)  // consume the Id.
531       return ParseIDValue(CurRec, Name, NameLoc);    // Value ::= IDValue
532     
533     // Value ::= ID '<' ValueListNE '>'
534     if (Lex.Lex() == tgtok::greater) {
535       TokError("expected non-empty value list");
536       return 0;
537     }
538     std::vector<Init*> ValueList = ParseValueList(CurRec);
539     if (ValueList.empty()) return 0;
540     
541     if (Lex.getCode() != tgtok::greater) {
542       TokError("expected '>' at end of value list");
543       return 0;
544     }
545     Lex.Lex();  // eat the '>'
546     
547     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
548     // a new anonymous definition, deriving from CLASS<initvalslist> with no
549     // body.
550     Record *Class = Records.getClass(Name);
551     if (!Class) {
552       Error(NameLoc, "Expected a class name, got '" + Name + "'");
553       return 0;
554     }
555     
556     // Create the new record, set it as CurRec temporarily.
557     static unsigned AnonCounter = 0;
558     Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++));
559     SubClassReference SCRef;
560     SCRef.RefLoc = NameLoc;
561     SCRef.Rec = Class;
562     SCRef.TemplateArgs = ValueList;
563     // Add info about the subclass to NewRec.
564     if (AddSubClass(NewRec, SCRef))
565       return 0;
566     NewRec->resolveReferences();
567     Records.addDef(NewRec);
568     
569     // The result of the expression is a reference to the new record.
570     return new DefInit(NewRec);
571   }    
572   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
573     LocTy BraceLoc = Lex.getLoc();
574     Lex.Lex(); // eat the '{'
575     std::vector<Init*> Vals;
576     
577     if (Lex.getCode() != tgtok::r_brace) {
578       Vals = ParseValueList(CurRec);
579       if (Vals.empty()) return 0;
580     }
581     if (Lex.getCode() != tgtok::r_brace) {
582       TokError("expected '}' at end of bit list value");
583       return 0;
584     }
585     Lex.Lex();  // eat the '}'
586     
587     BitsInit *Result = new BitsInit(Vals.size());
588     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
589       Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
590       if (Bit == 0) {
591         Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
592               ") is not convertable to a bit");
593         return 0;
594       }
595       Result->setBit(Vals.size()-i-1, Bit);
596     }
597     return Result;
598   }
599   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
600     Lex.Lex(); // eat the '['
601     std::vector<Init*> Vals;
602     
603     if (Lex.getCode() != tgtok::r_square) {
604       Vals = ParseValueList(CurRec);
605       if (Vals.empty()) return 0;
606     }
607     if (Lex.getCode() != tgtok::r_square) {
608       TokError("expected ']' at end of list value");
609       return 0;
610     }
611     Lex.Lex();  // eat the ']'
612     return new ListInit(Vals);
613   }
614   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
615     Lex.Lex();   // eat the '('
616     Init *Operator = ParseIDValue(CurRec);
617     if (Operator == 0) return 0;
618     
619     std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
620     if (Lex.getCode() != tgtok::r_paren) {
621       DagArgs = ParseDagArgList(CurRec);
622       if (DagArgs.empty()) return 0;
623     }
624     
625     if (Lex.getCode() != tgtok::r_paren) {
626       TokError("expected ')' in dag init");
627       return 0;
628     }
629     Lex.Lex();  // eat the ')'
630     
631     return new DagInit(Operator, DagArgs);
632   }
633   case tgtok::XConcat:
634   case tgtok::XSRA: 
635   case tgtok::XSRL:
636   case tgtok::XSHL:
637   case tgtok::XStrConcat: {  // Value ::= !binop '(' Value ',' Value ')'
638     BinOpInit::BinaryOp Code;
639     switch (Lex.getCode()) {
640     default: assert(0 && "Unhandled code!");
641     case tgtok::XConcat:    Code = BinOpInit::CONCAT; break;
642     case tgtok::XSRA:       Code = BinOpInit::SRA; break;
643     case tgtok::XSRL:       Code = BinOpInit::SRL; break;
644     case tgtok::XSHL:       Code = BinOpInit::SHL; break;
645     case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
646     }
647     Lex.Lex();  // eat the operation
648     if (Lex.getCode() != tgtok::l_paren) {
649       TokError("expected '(' after binary operator");
650       return 0;
651     }
652     Lex.Lex();  // eat the '('
653     
654     Init *LHS = ParseValue(CurRec);
655     if (LHS == 0) return 0;
656
657     if (Lex.getCode() != tgtok::comma) {
658       TokError("expected ',' in binary operator");
659       return 0;
660     }
661     Lex.Lex();  // eat the ','
662     
663     Init *RHS = ParseValue(CurRec);
664     if (RHS == 0) return 0;
665
666     if (Lex.getCode() != tgtok::r_paren) {
667       TokError("expected ')' in binary operator");
668       return 0;
669     }
670     Lex.Lex();  // eat the ')'
671     return (new BinOpInit(Code, LHS, RHS))->Fold();
672   }
673   }
674   
675   return R;
676 }
677
678 /// ParseValue - Parse a tblgen value.  This returns null on error.
679 ///
680 ///   Value       ::= SimpleValue ValueSuffix*
681 ///   ValueSuffix ::= '{' BitList '}'
682 ///   ValueSuffix ::= '[' BitList ']'
683 ///   ValueSuffix ::= '.' ID
684 ///
685 Init *TGParser::ParseValue(Record *CurRec) {
686   Init *Result = ParseSimpleValue(CurRec);
687   if (Result == 0) return 0;
688   
689   // Parse the suffixes now if present.
690   while (1) {
691     switch (Lex.getCode()) {
692     default: return Result;
693     case tgtok::l_brace: {
694       LocTy CurlyLoc = Lex.getLoc();
695       Lex.Lex(); // eat the '{'
696       std::vector<unsigned> Ranges = ParseRangeList();
697       if (Ranges.empty()) return 0;
698       
699       // Reverse the bitlist.
700       std::reverse(Ranges.begin(), Ranges.end());
701       Result = Result->convertInitializerBitRange(Ranges);
702       if (Result == 0) {
703         Error(CurlyLoc, "Invalid bit range for value");
704         return 0;
705       }
706       
707       // Eat the '}'.
708       if (Lex.getCode() != tgtok::r_brace) {
709         TokError("expected '}' at end of bit range list");
710         return 0;
711       }
712       Lex.Lex();
713       break;
714     }
715     case tgtok::l_square: {
716       LocTy SquareLoc = Lex.getLoc();
717       Lex.Lex(); // eat the '['
718       std::vector<unsigned> Ranges = ParseRangeList();
719       if (Ranges.empty()) return 0;
720       
721       Result = Result->convertInitListSlice(Ranges);
722       if (Result == 0) {
723         Error(SquareLoc, "Invalid range for list slice");
724         return 0;
725       }
726       
727       // Eat the ']'.
728       if (Lex.getCode() != tgtok::r_square) {
729         TokError("expected ']' at end of list slice");
730         return 0;
731       }
732       Lex.Lex();
733       break;
734     }
735     case tgtok::period:
736       if (Lex.Lex() != tgtok::Id) {  // eat the .
737         TokError("expected field identifier after '.'");
738         return 0;
739       }
740       if (!Result->getFieldType(Lex.getCurStrVal())) {
741         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
742                  Result->getAsString() + "'");
743         return 0;
744       }
745       Result = new FieldInit(Result, Lex.getCurStrVal());
746       Lex.Lex();  // eat field name
747       break;
748     }
749   }
750 }
751
752 /// ParseDagArgList - Parse the argument list for a dag literal expression.
753 ///
754 ///    ParseDagArgList ::= Value (':' VARNAME)?
755 ///    ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
756 std::vector<std::pair<llvm::Init*, std::string> > 
757 TGParser::ParseDagArgList(Record *CurRec) {
758   std::vector<std::pair<llvm::Init*, std::string> > Result;
759   
760   while (1) {
761     Init *Val = ParseValue(CurRec);
762     if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
763     
764     // If the variable name is present, add it.
765     std::string VarName;
766     if (Lex.getCode() == tgtok::colon) {
767       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
768         TokError("expected variable name in dag literal");
769         return std::vector<std::pair<llvm::Init*, std::string> >();
770       }
771       VarName = Lex.getCurStrVal();
772       Lex.Lex();  // eat the VarName.
773     }
774     
775     Result.push_back(std::make_pair(Val, VarName));
776     
777     if (Lex.getCode() != tgtok::comma) break;
778     Lex.Lex(); // eat the ','    
779   }
780   
781   return Result;
782 }
783
784
785 /// ParseValueList - Parse a comma separated list of values, returning them as a
786 /// vector.  Note that this always expects to be able to parse at least one
787 /// value.  It returns an empty list if this is not possible.
788 ///
789 ///   ValueList ::= Value (',' Value)
790 ///
791 std::vector<Init*> TGParser::ParseValueList(Record *CurRec) {
792   std::vector<Init*> Result;
793   Result.push_back(ParseValue(CurRec));
794   if (Result.back() == 0) return std::vector<Init*>();
795   
796   while (Lex.getCode() == tgtok::comma) {
797     Lex.Lex();  // Eat the comma
798     
799     Result.push_back(ParseValue(CurRec));
800     if (Result.back() == 0) return std::vector<Init*>();
801   }
802   
803   return Result;
804 }
805
806
807
808 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
809 /// empty string on error.  This can happen in a number of different context's,
810 /// including within a def or in the template args for a def (which which case
811 /// CurRec will be non-null) and within the template args for a multiclass (in
812 /// which case CurRec will be null, but CurMultiClass will be set).  This can
813 /// also happen within a def that is within a multiclass, which will set both
814 /// CurRec and CurMultiClass.
815 ///
816 ///  Declaration ::= FIELD? Type ID ('=' Value)?
817 ///
818 std::string TGParser::ParseDeclaration(Record *CurRec, 
819                                        bool ParsingTemplateArgs) {
820   // Read the field prefix if present.
821   bool HasField = Lex.getCode() == tgtok::Field;
822   if (HasField) Lex.Lex();
823   
824   RecTy *Type = ParseType();
825   if (Type == 0) return "";
826   
827   if (Lex.getCode() != tgtok::Id) {
828     TokError("Expected identifier in declaration");
829     return "";
830   }
831   
832   LocTy IdLoc = Lex.getLoc();
833   std::string DeclName = Lex.getCurStrVal();
834   Lex.Lex();
835   
836   if (ParsingTemplateArgs) {
837     if (CurRec) {
838       DeclName = CurRec->getName() + ":" + DeclName;
839     } else {
840       assert(CurMultiClass);
841     }
842     if (CurMultiClass)
843       DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
844   }
845   
846   // Add the value.
847   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
848     return "";
849   
850   // If a value is present, parse it.
851   if (Lex.getCode() == tgtok::equal) {
852     Lex.Lex();
853     LocTy ValLoc = Lex.getLoc();
854     Init *Val = ParseValue(CurRec);
855     if (Val == 0 ||
856         SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
857       return "";
858   }
859   
860   return DeclName;
861 }
862
863 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
864 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
865 /// template args for a def, which may or may not be in a multiclass.  If null,
866 /// these are the template args for a multiclass.
867 ///
868 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
869 /// 
870 bool TGParser::ParseTemplateArgList(Record *CurRec) {
871   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
872   Lex.Lex(); // eat the '<'
873   
874   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
875   
876   // Read the first declaration.
877   std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
878   if (TemplArg.empty())
879     return true;
880   
881   TheRecToAddTo->addTemplateArg(TemplArg);
882   
883   while (Lex.getCode() == tgtok::comma) {
884     Lex.Lex(); // eat the ','
885     
886     // Read the following declarations.
887     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
888     if (TemplArg.empty())
889       return true;
890     TheRecToAddTo->addTemplateArg(TemplArg);
891   }
892   
893   if (Lex.getCode() != tgtok::greater)
894     return TokError("expected '>' at end of template argument list");
895   Lex.Lex(); // eat the '>'.
896   return false;
897 }
898
899
900 /// ParseBodyItem - Parse a single item at within the body of a def or class.
901 ///
902 ///   BodyItem ::= Declaration ';'
903 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
904 bool TGParser::ParseBodyItem(Record *CurRec) {
905   if (Lex.getCode() != tgtok::Let) {
906     if (ParseDeclaration(CurRec, false).empty()) 
907       return true;
908     
909     if (Lex.getCode() != tgtok::semi)
910       return TokError("expected ';' after declaration");
911     Lex.Lex();
912     return false;
913   }
914
915   // LET ID OptionalRangeList '=' Value ';'
916   if (Lex.Lex() != tgtok::Id)
917     return TokError("expected field identifier after let");
918   
919   LocTy IdLoc = Lex.getLoc();
920   std::string FieldName = Lex.getCurStrVal();
921   Lex.Lex();  // eat the field name.
922   
923   std::vector<unsigned> BitList;
924   if (ParseOptionalBitList(BitList)) 
925     return true;
926   std::reverse(BitList.begin(), BitList.end());
927   
928   if (Lex.getCode() != tgtok::equal)
929     return TokError("expected '=' in let expression");
930   Lex.Lex();  // eat the '='.
931   
932   Init *Val = ParseValue(CurRec);
933   if (Val == 0) return true;
934   
935   if (Lex.getCode() != tgtok::semi)
936     return TokError("expected ';' after let expression");
937   Lex.Lex();
938   
939   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
940 }
941
942 /// ParseBody - Read the body of a class or def.  Return true on error, false on
943 /// success.
944 ///
945 ///   Body     ::= ';'
946 ///   Body     ::= '{' BodyList '}'
947 ///   BodyList BodyItem*
948 ///
949 bool TGParser::ParseBody(Record *CurRec) {
950   // If this is a null definition, just eat the semi and return.
951   if (Lex.getCode() == tgtok::semi) {
952     Lex.Lex();
953     return false;
954   }
955   
956   if (Lex.getCode() != tgtok::l_brace)
957     return TokError("Expected ';' or '{' to start body");
958   // Eat the '{'.
959   Lex.Lex();
960   
961   while (Lex.getCode() != tgtok::r_brace)
962     if (ParseBodyItem(CurRec))
963       return true;
964
965   // Eat the '}'.
966   Lex.Lex();
967   return false;
968 }
969
970 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
971 /// optional ClassList followed by a Body.  CurRec is the current def or class
972 /// that is being parsed.
973 ///
974 ///   ObjectBody      ::= BaseClassList Body
975 ///   BaseClassList   ::= /*empty*/
976 ///   BaseClassList   ::= ':' BaseClassListNE
977 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
978 ///
979 bool TGParser::ParseObjectBody(Record *CurRec) {
980   // If there is a baseclass list, read it.
981   if (Lex.getCode() == tgtok::colon) {
982     Lex.Lex();
983     
984     // Read all of the subclasses.
985     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
986     while (1) {
987       // Check for error.
988       if (SubClass.Rec == 0) return true;
989      
990       // Add it.
991       if (AddSubClass(CurRec, SubClass))
992         return true;
993       
994       if (Lex.getCode() != tgtok::comma) break;
995       Lex.Lex(); // eat ','.
996       SubClass = ParseSubClassReference(CurRec, false);
997     }
998   }
999
1000   // Process any variables on the let stack.
1001   for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1002     for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1003       if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1004                    LetStack[i][j].Bits, LetStack[i][j].Value))
1005         return true;
1006   
1007   return ParseBody(CurRec);
1008 }
1009
1010
1011 /// ParseDef - Parse and return a top level or multiclass def, return the record
1012 /// corresponding to it.  This returns null on error.
1013 ///
1014 ///   DefInst ::= DEF ObjectName ObjectBody
1015 ///
1016 llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
1017   LocTy DefLoc = Lex.getLoc();
1018   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1019   Lex.Lex();  // Eat the 'def' token.  
1020
1021   // Parse ObjectName and make a record for it.
1022   Record *CurRec = new Record(ParseObjectName());
1023   
1024   if (!CurMultiClass) {
1025     // Top-level def definition.
1026     
1027     // Ensure redefinition doesn't happen.
1028     if (Records.getDef(CurRec->getName())) {
1029       Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1030       return 0;
1031     }
1032     Records.addDef(CurRec);
1033   } else {
1034     // Otherwise, a def inside a multiclass, add it to the multiclass.
1035     for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1036       if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1037         Error(DefLoc, "def '" + CurRec->getName() +
1038               "' already defined in this multiclass!");
1039         return 0;
1040       }
1041     CurMultiClass->DefPrototypes.push_back(CurRec);
1042   }
1043   
1044   if (ParseObjectBody(CurRec))
1045     return 0;
1046   
1047   if (CurMultiClass == 0)  // Def's in multiclasses aren't really defs.
1048     CurRec->resolveReferences();
1049   
1050   // If ObjectBody has template arguments, it's an error.
1051   assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1052   return CurRec;
1053 }
1054
1055
1056 /// ParseClass - Parse a tblgen class definition.
1057 ///
1058 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1059 ///
1060 bool TGParser::ParseClass() {
1061   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1062   Lex.Lex();
1063   
1064   if (Lex.getCode() != tgtok::Id)
1065     return TokError("expected class name after 'class' keyword");
1066   
1067   Record *CurRec = Records.getClass(Lex.getCurStrVal());
1068   if (CurRec) {
1069     // If the body was previously defined, this is an error.
1070     if (!CurRec->getValues().empty() ||
1071         !CurRec->getSuperClasses().empty() ||
1072         !CurRec->getTemplateArgs().empty())
1073       return TokError("Class '" + CurRec->getName() + "' already defined");
1074   } else {
1075     // If this is the first reference to this class, create and add it.
1076     CurRec = new Record(Lex.getCurStrVal());
1077     Records.addClass(CurRec);
1078   }
1079   Lex.Lex(); // eat the name.
1080   
1081   // If there are template args, parse them.
1082   if (Lex.getCode() == tgtok::less)
1083     if (ParseTemplateArgList(CurRec))
1084       return true;
1085
1086   // Finally, parse the object body.
1087   return ParseObjectBody(CurRec);
1088 }
1089
1090 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1091 /// of LetRecords.
1092 ///
1093 ///   LetList ::= LetItem (',' LetItem)*
1094 ///   LetItem ::= ID OptionalRangeList '=' Value
1095 ///
1096 std::vector<LetRecord> TGParser::ParseLetList() {
1097   std::vector<LetRecord> Result;
1098   
1099   while (1) {
1100     if (Lex.getCode() != tgtok::Id) {
1101       TokError("expected identifier in let definition");
1102       return std::vector<LetRecord>();
1103     }
1104     std::string Name = Lex.getCurStrVal();
1105     LocTy NameLoc = Lex.getLoc();
1106     Lex.Lex();  // Eat the identifier. 
1107
1108     // Check for an optional RangeList.
1109     std::vector<unsigned> Bits;
1110     if (ParseOptionalRangeList(Bits)) 
1111       return std::vector<LetRecord>();
1112     std::reverse(Bits.begin(), Bits.end());
1113     
1114     if (Lex.getCode() != tgtok::equal) {
1115       TokError("expected '=' in let expression");
1116       return std::vector<LetRecord>();
1117     }
1118     Lex.Lex();  // eat the '='.
1119     
1120     Init *Val = ParseValue(0);
1121     if (Val == 0) return std::vector<LetRecord>();
1122     
1123     // Now that we have everything, add the record.
1124     Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1125     
1126     if (Lex.getCode() != tgtok::comma)
1127       return Result;
1128     Lex.Lex();  // eat the comma.    
1129   }
1130 }
1131
1132 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
1133 /// different related productions.
1134 ///
1135 ///   Object ::= LET LetList IN '{' ObjectList '}'
1136 ///   Object ::= LET LetList IN Object
1137 ///
1138 bool TGParser::ParseTopLevelLet() {
1139   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1140   Lex.Lex();
1141   
1142   // Add this entry to the let stack.
1143   std::vector<LetRecord> LetInfo = ParseLetList();
1144   if (LetInfo.empty()) return true;
1145   LetStack.push_back(LetInfo);
1146
1147   if (Lex.getCode() != tgtok::In)
1148     return TokError("expected 'in' at end of top-level 'let'");
1149   Lex.Lex();
1150   
1151   // If this is a scalar let, just handle it now
1152   if (Lex.getCode() != tgtok::l_brace) {
1153     // LET LetList IN Object
1154     if (ParseObject())
1155       return true;
1156   } else {   // Object ::= LETCommand '{' ObjectList '}'
1157     LocTy BraceLoc = Lex.getLoc();
1158     // Otherwise, this is a group let.
1159     Lex.Lex();  // eat the '{'.
1160     
1161     // Parse the object list.
1162     if (ParseObjectList())
1163       return true;
1164     
1165     if (Lex.getCode() != tgtok::r_brace) {
1166       TokError("expected '}' at end of top level let command");
1167       return Error(BraceLoc, "to match this '{'");
1168     }
1169     Lex.Lex();
1170   }
1171   
1172   // Outside this let scope, this let block is not active.
1173   LetStack.pop_back();
1174   return false;
1175 }
1176
1177 /// ParseMultiClassDef - Parse a def in a multiclass context.
1178 ///
1179 ///  MultiClassDef ::= DefInst
1180 ///
1181 bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1182   if (Lex.getCode() != tgtok::Def) 
1183     return TokError("expected 'def' in multiclass body");
1184
1185   Record *D = ParseDef(CurMC);
1186   if (D == 0) return true;
1187   
1188   // Copy the template arguments for the multiclass into the def.
1189   const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1190   
1191   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1192     const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1193     assert(RV && "Template arg doesn't exist?");
1194     D->addValue(*RV);
1195   }
1196
1197   return false;
1198 }
1199
1200 /// ParseMultiClass - Parse a multiclass definition.
1201 ///
1202 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList? '{' MultiClassDef+ '}'
1203 ///
1204 bool TGParser::ParseMultiClass() {
1205   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1206   Lex.Lex();  // Eat the multiclass token.
1207
1208   if (Lex.getCode() != tgtok::Id)
1209     return TokError("expected identifier after multiclass for name");
1210   std::string Name = Lex.getCurStrVal();
1211   
1212   if (MultiClasses.count(Name))
1213     return TokError("multiclass '" + Name + "' already defined");
1214   
1215   CurMultiClass  = MultiClasses[Name] = new MultiClass(Name);
1216   Lex.Lex();  // Eat the identifier.
1217   
1218   // If there are template args, parse them.
1219   if (Lex.getCode() == tgtok::less)
1220     if (ParseTemplateArgList(0))
1221       return true;
1222
1223   if (Lex.getCode() != tgtok::l_brace)
1224     return TokError("expected '{' in multiclass definition");
1225
1226   if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
1227     return TokError("multiclass must contain at least one def");
1228   
1229   while (Lex.getCode() != tgtok::r_brace)
1230     if (ParseMultiClassDef(CurMultiClass))
1231       return true;
1232   
1233   Lex.Lex();  // eat the '}'.
1234   
1235   CurMultiClass = 0;
1236   return false;
1237 }
1238
1239 /// ParseDefm - Parse the instantiation of a multiclass.
1240 ///
1241 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1242 ///
1243 bool TGParser::ParseDefm() {
1244   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1245   if (Lex.Lex() != tgtok::Id)  // eat the defm.
1246     return TokError("expected identifier after defm");
1247   
1248   LocTy DefmPrefixLoc = Lex.getLoc();
1249   std::string DefmPrefix = Lex.getCurStrVal();
1250   if (Lex.Lex() != tgtok::colon)
1251     return TokError("expected ':' after defm identifier");
1252   
1253   // eat the colon.
1254   Lex.Lex();
1255
1256   LocTy SubClassLoc = Lex.getLoc();
1257   SubClassReference Ref = ParseSubClassReference(0, true);
1258   if (Ref.Rec == 0) return true;
1259   
1260   if (Lex.getCode() != tgtok::semi)
1261     return TokError("expected ';' at end of defm");
1262   Lex.Lex();
1263   
1264   // To instantiate a multiclass, we need to first get the multiclass, then
1265   // instantiate each def contained in the multiclass with the SubClassRef
1266   // template parameters.
1267   MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1268   assert(MC && "Didn't lookup multiclass correctly?");
1269   std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1270   
1271   // Verify that the correct number of template arguments were specified.
1272   const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1273   if (TArgs.size() < TemplateVals.size())
1274     return Error(SubClassLoc,
1275                  "more template args specified than multiclass expects");
1276   
1277   // Loop over all the def's in the multiclass, instantiating each one.
1278   for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1279     Record *DefProto = MC->DefPrototypes[i];
1280     
1281     // Add the suffix to the defm name to get the new name.
1282     Record *CurRec = new Record(DefmPrefix + DefProto->getName());
1283     
1284     SubClassReference Ref;
1285     Ref.RefLoc = DefmPrefixLoc;
1286     Ref.Rec = DefProto;
1287     AddSubClass(CurRec, Ref);
1288     
1289     // Loop over all of the template arguments, setting them to the specified
1290     // value or leaving them as the default if necessary.
1291     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1292       if (i < TemplateVals.size()) { // A value is specified for this temp-arg?
1293         // Set it now.
1294         if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1295                      TemplateVals[i]))
1296           return true;
1297         
1298         // Resolve it next.
1299         CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1300         
1301         // Now remove it.
1302         CurRec->removeValue(TArgs[i]);
1303         
1304       } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1305         return Error(SubClassLoc, "value not specified for template argument #"+
1306                      utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1307                      MC->Rec.getName() + "'");
1308       }
1309     }
1310     
1311     // If the mdef is inside a 'let' expression, add to each def.
1312     for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1313       for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1314         if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1315                      LetStack[i][j].Bits, LetStack[i][j].Value)) {
1316           Error(DefmPrefixLoc, "when instantiating this defm");
1317           return true;
1318         }
1319     
1320     
1321     // Ensure redefinition doesn't happen.
1322     if (Records.getDef(CurRec->getName()))
1323       return Error(DefmPrefixLoc, "def '" + CurRec->getName() + 
1324                    "' already defined, instantiating defm with subdef '" + 
1325                    DefProto->getName() + "'");
1326     Records.addDef(CurRec);
1327     CurRec->resolveReferences();
1328   }
1329   
1330   return false;
1331 }
1332
1333 /// ParseObject
1334 ///   Object ::= ClassInst
1335 ///   Object ::= DefInst
1336 ///   Object ::= MultiClassInst
1337 ///   Object ::= DefMInst
1338 ///   Object ::= LETCommand '{' ObjectList '}'
1339 ///   Object ::= LETCommand Object
1340 bool TGParser::ParseObject() {
1341   switch (Lex.getCode()) {
1342   default: assert(0 && "This is not an object");
1343   case tgtok::Let:   return ParseTopLevelLet();
1344   case tgtok::Def:   return ParseDef(0) == 0;
1345   case tgtok::Defm:  return ParseDefm();
1346   case tgtok::Class: return ParseClass();
1347   case tgtok::MultiClass: return ParseMultiClass();
1348   }
1349 }
1350
1351 /// ParseObjectList
1352 ///   ObjectList :== Object*
1353 bool TGParser::ParseObjectList() {
1354   while (isObjectStart(Lex.getCode())) {
1355     if (ParseObject())
1356       return true;
1357   }
1358   return false;
1359 }
1360
1361
1362 bool TGParser::ParseFile() {
1363   Lex.Lex(); // Prime the lexer.
1364   if (ParseObjectList()) return true;
1365   
1366   // If we have unread input at the end of the file, report it.
1367   if (Lex.getCode() == tgtok::Eof)
1368     return false;
1369   
1370   return TokError("Unexpected input at top level");
1371 }
1372