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