186a93f5b4e0a50173fa71b2303138c55c0301d7
[oota-llvm.git] / lib / AsmParser / llvmAsmParser.y
1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the bison parser for LLVM assembly languages files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 %{
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Streams.h"
27 #include <algorithm>
28 #include <list>
29 #include <utility>
30 #ifndef NDEBUG
31 #define YYDEBUG 1
32 #endif
33
34 // The following is a gross hack. In order to rid the libAsmParser library of
35 // exceptions, we have to have a way of getting the yyparse function to go into
36 // an error situation. So, whenever we want an error to occur, the GenerateError
37 // function (see bottom of file) sets TriggerError. Then, at the end of each 
38 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR 
39 // (a goto) to put YACC in error state. Furthermore, several calls to 
40 // GenerateError are made from inside productions and they must simulate the
41 // previous exception behavior by exiting the production immediately. We have
42 // replaced these with the GEN_ERROR macro which calls GeneratError and then
43 // immediately invokes YYERROR. This would be so much cleaner if it was a 
44 // recursive descent parser.
45 static bool TriggerError = false;
46 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
47 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
48
49 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
50 int yylex();                       // declaration" of xxx warnings.
51 int yyparse();
52
53 namespace llvm {
54   std::string CurFilename;
55 #if YYDEBUG
56 static cl::opt<bool>
57 Debug("debug-yacc", cl::desc("Print yacc debug state changes"), 
58       cl::Hidden, cl::init(false));
59 #endif
60 }
61 using namespace llvm;
62
63 static Module *ParserResult;
64
65 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
66 // relating to upreferences in the input stream.
67 //
68 //#define DEBUG_UPREFS 1
69 #ifdef DEBUG_UPREFS
70 #define UR_OUT(X) cerr << X
71 #else
72 #define UR_OUT(X)
73 #endif
74
75 #define YYERROR_VERBOSE 1
76
77 static GlobalVariable *CurGV;
78
79
80 // This contains info used when building the body of a function.  It is
81 // destroyed when the function is completed.
82 //
83 typedef std::vector<Value *> ValueList;           // Numbered defs
84
85 static void 
86 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
87                    std::map<const Type *,ValueList> *FutureLateResolvers = 0);
88
89 static struct PerModuleInfo {
90   Module *CurrentModule;
91   std::map<const Type *, ValueList> Values; // Module level numbered definitions
92   std::map<const Type *,ValueList> LateResolveValues;
93   std::vector<PATypeHolder>    Types;
94   std::map<ValID, PATypeHolder> LateResolveTypes;
95
96   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
97   /// how they were referenced and on which line of the input they came from so
98   /// that we can resolve them later and print error messages as appropriate.
99   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
100
101   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
102   // references to global values.  Global values may be referenced before they
103   // are defined, and if so, the temporary object that they represent is held
104   // here.  This is used for forward references of GlobalValues.
105   //
106   typedef std::map<std::pair<const PointerType *,
107                              ValID>, GlobalValue*> GlobalRefsType;
108   GlobalRefsType GlobalRefs;
109
110   void ModuleDone() {
111     // If we could not resolve some functions at function compilation time
112     // (calls to functions before they are defined), resolve them now...  Types
113     // are resolved when the constant pool has been completely parsed.
114     //
115     ResolveDefinitions(LateResolveValues);
116     if (TriggerError)
117       return;
118
119     // Check to make sure that all global value forward references have been
120     // resolved!
121     //
122     if (!GlobalRefs.empty()) {
123       std::string UndefinedReferences = "Unresolved global references exist:\n";
124
125       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
126            I != E; ++I) {
127         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
128                                I->first.second.getName() + "\n";
129       }
130       GenerateError(UndefinedReferences);
131       return;
132     }
133
134     Values.clear();         // Clear out function local definitions
135     Types.clear();
136     CurrentModule = 0;
137   }
138
139   // GetForwardRefForGlobal - Check to see if there is a forward reference
140   // for this global.  If so, remove it from the GlobalRefs map and return it.
141   // If not, just return null.
142   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
143     // Check to see if there is a forward reference to this global variable...
144     // if there is, eliminate it and patch the reference to use the new def'n.
145     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
146     GlobalValue *Ret = 0;
147     if (I != GlobalRefs.end()) {
148       Ret = I->second;
149       GlobalRefs.erase(I);
150     }
151     return Ret;
152   }
153
154   bool TypeIsUnresolved(PATypeHolder* PATy) {
155     // If it isn't abstract, its resolved
156     const Type* Ty = PATy->get();
157     if (!Ty->isAbstract())
158       return false;
159     // Traverse the type looking for abstract types. If it isn't abstract then
160     // we don't need to traverse that leg of the type. 
161     std::vector<const Type*> WorkList, SeenList;
162     WorkList.push_back(Ty);
163     while (!WorkList.empty()) {
164       const Type* Ty = WorkList.back();
165       SeenList.push_back(Ty);
166       WorkList.pop_back();
167       if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
168         // Check to see if this is an unresolved type
169         std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
170         std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
171         for ( ; I != E; ++I) {
172           if (I->second.get() == OpTy)
173             return true;
174         }
175       } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
176         const Type* TheTy = SeqTy->getElementType();
177         if (TheTy->isAbstract() && TheTy != Ty) {
178           std::vector<const Type*>::iterator I = SeenList.begin(), 
179                                              E = SeenList.end();
180           for ( ; I != E; ++I)
181             if (*I == TheTy)
182               break;
183           if (I == E)
184             WorkList.push_back(TheTy);
185         }
186       } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
187         for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
188           const Type* TheTy = StrTy->getElementType(i);
189           if (TheTy->isAbstract() && TheTy != Ty) {
190             std::vector<const Type*>::iterator I = SeenList.begin(), 
191                                                E = SeenList.end();
192             for ( ; I != E; ++I)
193               if (*I == TheTy)
194                 break;
195             if (I == E)
196               WorkList.push_back(TheTy);
197           }
198         }
199       }
200     }
201     return false;
202   }
203
204
205 } CurModule;
206
207 static struct PerFunctionInfo {
208   Function *CurrentFunction;     // Pointer to current function being created
209
210   std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
211   std::map<const Type*, ValueList> LateResolveValues;
212   bool isDeclare;                    // Is this function a forward declararation?
213   GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
214   GlobalValue::VisibilityTypes Visibility;
215
216   /// BBForwardRefs - When we see forward references to basic blocks, keep
217   /// track of them here.
218   std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
219   std::vector<BasicBlock*> NumberedBlocks;
220   unsigned NextBBNum;
221
222   inline PerFunctionInfo() {
223     CurrentFunction = 0;
224     isDeclare = false;
225     Linkage = GlobalValue::ExternalLinkage;
226     Visibility = GlobalValue::DefaultVisibility;
227   }
228
229   inline void FunctionStart(Function *M) {
230     CurrentFunction = M;
231     NextBBNum = 0;
232   }
233
234   void FunctionDone() {
235     NumberedBlocks.clear();
236
237     // Any forward referenced blocks left?
238     if (!BBForwardRefs.empty()) {
239       GenerateError("Undefined reference to label " +
240                      BBForwardRefs.begin()->first->getName());
241       return;
242     }
243
244     // Resolve all forward references now.
245     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
246
247     Values.clear();         // Clear out function local definitions
248     CurrentFunction = 0;
249     isDeclare = false;
250     Linkage = GlobalValue::ExternalLinkage;
251     Visibility = GlobalValue::DefaultVisibility;
252   }
253 } CurFun;  // Info for the current function...
254
255 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
256
257
258 //===----------------------------------------------------------------------===//
259 //               Code to handle definitions of all the types
260 //===----------------------------------------------------------------------===//
261
262 static int InsertValue(Value *V,
263                   std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
264   if (V->hasName()) return -1;           // Is this a numbered definition?
265
266   // Yes, insert the value into the value table...
267   ValueList &List = ValueTab[V->getType()];
268   List.push_back(V);
269   return List.size()-1;
270 }
271
272 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
273   switch (D.Type) {
274   case ValID::LocalID:               // Is it a numbered definition?
275     // Module constants occupy the lowest numbered slots...
276     if (D.Num < CurModule.Types.size())
277       return CurModule.Types[D.Num];
278     break;
279   case ValID::LocalName:                 // Is it a named definition?
280     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
281       D.destroy();  // Free old strdup'd memory...
282       return N;
283     }
284     break;
285   default:
286     GenerateError("Internal parser error: Invalid symbol type reference");
287     return 0;
288   }
289
290   // If we reached here, we referenced either a symbol that we don't know about
291   // or an id number that hasn't been read yet.  We may be referencing something
292   // forward, so just create an entry to be resolved later and get to it...
293   //
294   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
295
296
297   if (inFunctionScope()) {
298     if (D.Type == ValID::LocalName) {
299       GenerateError("Reference to an undefined type: '" + D.getName() + "'");
300       return 0;
301     } else {
302       GenerateError("Reference to an undefined type: #" + utostr(D.Num));
303       return 0;
304     }
305   }
306
307   std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
308   if (I != CurModule.LateResolveTypes.end())
309     return I->second;
310
311   Type *Typ = OpaqueType::get();
312   CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
313   return Typ;
314  }
315
316 // getValNonImprovising - Look up the value specified by the provided type and
317 // the provided ValID.  If the value exists and has already been defined, return
318 // it.  Otherwise return null.
319 //
320 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
321   if (isa<FunctionType>(Ty)) {
322     GenerateError("Functions are not values and "
323                    "must be referenced as pointers");
324     return 0;
325   }
326
327   switch (D.Type) {
328   case ValID::LocalID: {                 // Is it a numbered definition?
329     // Module constants occupy the lowest numbered slots.
330     std::map<const Type*,ValueList>::iterator VI = CurFun.Values.find(Ty);
331     // Make sure that our type is within bounds.
332     if (VI == CurFun.Values.end()) return 0;
333
334     // Check that the number is within bounds.
335     if (D.Num >= VI->second.size()) return 0;
336
337     return VI->second[D.Num];
338   }
339   case ValID::GlobalID: {                 // Is it a numbered definition?
340     unsigned Num = D.Num;
341     
342     // Module constants occupy the lowest numbered slots...
343     std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
344     if (VI == CurModule.Values.end()) return 0;
345     if (D.Num >= VI->second.size()) return 0;
346     return VI->second[Num];
347   }
348     
349   case ValID::LocalName: {                // Is it a named definition?
350     if (!inFunctionScope()) return 0;
351     SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
352     Value *N = SymTab.lookup(Ty, D.Name);
353     if (N == 0) return 0;
354     
355     D.destroy();  // Free old strdup'd memory...
356     return N;
357   }
358   case ValID::GlobalName: {                // Is it a named definition?
359     SymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
360     Value *N = SymTab.lookup(Ty, D.Name);
361     if (N == 0) return 0;
362
363     D.destroy();  // Free old strdup'd memory...
364     return N;
365   }
366
367   // Check to make sure that "Ty" is an integral type, and that our
368   // value will fit into the specified type...
369   case ValID::ConstSIntVal:    // Is it a constant pool reference??
370     if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
371       GenerateError("Signed integral constant '" +
372                      itostr(D.ConstPool64) + "' is invalid for type '" +
373                      Ty->getDescription() + "'");
374       return 0;
375     }
376     return ConstantInt::get(Ty, D.ConstPool64);
377
378   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
379     if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
380       if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
381         GenerateError("Integral constant '" + utostr(D.UConstPool64) +
382                        "' is invalid or out of range");
383         return 0;
384       } else {     // This is really a signed reference.  Transmogrify.
385         return ConstantInt::get(Ty, D.ConstPool64);
386       }
387     } else {
388       return ConstantInt::get(Ty, D.UConstPool64);
389     }
390
391   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
392     if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
393       GenerateError("FP constant invalid for type");
394       return 0;
395     }
396     return ConstantFP::get(Ty, D.ConstPoolFP);
397
398   case ValID::ConstNullVal:      // Is it a null value?
399     if (!isa<PointerType>(Ty)) {
400       GenerateError("Cannot create a a non pointer null");
401       return 0;
402     }
403     return ConstantPointerNull::get(cast<PointerType>(Ty));
404
405   case ValID::ConstUndefVal:      // Is it an undef value?
406     return UndefValue::get(Ty);
407
408   case ValID::ConstZeroVal:      // Is it a zero value?
409     return Constant::getNullValue(Ty);
410     
411   case ValID::ConstantVal:       // Fully resolved constant?
412     if (D.ConstantValue->getType() != Ty) {
413       GenerateError("Constant expression type different from required type");
414       return 0;
415     }
416     return D.ConstantValue;
417
418   case ValID::InlineAsmVal: {    // Inline asm expression
419     const PointerType *PTy = dyn_cast<PointerType>(Ty);
420     const FunctionType *FTy =
421       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
422     if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
423       GenerateError("Invalid type for asm constraint string");
424       return 0;
425     }
426     InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
427                                    D.IAD->HasSideEffects);
428     D.destroy();   // Free InlineAsmDescriptor.
429     return IA;
430   }
431   default:
432     assert(0 && "Unhandled case!");
433     return 0;
434   }   // End of switch
435
436   assert(0 && "Unhandled case!");
437   return 0;
438 }
439
440 // getVal - This function is identical to getValNonImprovising, except that if a
441 // value is not already defined, it "improvises" by creating a placeholder var
442 // that looks and acts just like the requested variable.  When the value is
443 // defined later, all uses of the placeholder variable are replaced with the
444 // real thing.
445 //
446 static Value *getVal(const Type *Ty, const ValID &ID) {
447   if (Ty == Type::LabelTy) {
448     GenerateError("Cannot use a basic block here");
449     return 0;
450   }
451
452   // See if the value has already been defined.
453   Value *V = getValNonImprovising(Ty, ID);
454   if (V) return V;
455   if (TriggerError) return 0;
456
457   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
458     GenerateError("Invalid use of a composite type");
459     return 0;
460   }
461
462   // If we reached here, we referenced either a symbol that we don't know about
463   // or an id number that hasn't been read yet.  We may be referencing something
464   // forward, so just create an entry to be resolved later and get to it...
465   //
466   V = new Argument(Ty);
467
468   // Remember where this forward reference came from.  FIXME, shouldn't we try
469   // to recycle these things??
470   CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
471                                                                llvmAsmlineno)));
472
473   if (inFunctionScope())
474     InsertValue(V, CurFun.LateResolveValues);
475   else
476     InsertValue(V, CurModule.LateResolveValues);
477   return V;
478 }
479
480 /// getBBVal - This is used for two purposes:
481 ///  * If isDefinition is true, a new basic block with the specified ID is being
482 ///    defined.
483 ///  * If isDefinition is true, this is a reference to a basic block, which may
484 ///    or may not be a forward reference.
485 ///
486 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
487   assert(inFunctionScope() && "Can't get basic block at global scope!");
488
489   std::string Name;
490   BasicBlock *BB = 0;
491   switch (ID.Type) {
492   default: 
493     GenerateError("Illegal label reference " + ID.getName());
494     return 0;
495   case ValID::LocalID:                // Is it a numbered definition?
496     if (ID.Num >= CurFun.NumberedBlocks.size())
497       CurFun.NumberedBlocks.resize(ID.Num+1);
498     BB = CurFun.NumberedBlocks[ID.Num];
499     break;
500   case ValID::LocalName:                  // Is it a named definition?
501     Name = ID.Name;
502     if (Value *N = CurFun.CurrentFunction->
503                    getValueSymbolTable().lookup(Type::LabelTy, Name))
504       BB = cast<BasicBlock>(N);
505     break;
506   }
507
508   // See if the block has already been defined.
509   if (BB) {
510     // If this is the definition of the block, make sure the existing value was
511     // just a forward reference.  If it was a forward reference, there will be
512     // an entry for it in the PlaceHolderInfo map.
513     if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
514       // The existing value was a definition, not a forward reference.
515       GenerateError("Redefinition of label " + ID.getName());
516       return 0;
517     }
518
519     ID.destroy();                       // Free strdup'd memory.
520     return BB;
521   }
522
523   // Otherwise this block has not been seen before.
524   BB = new BasicBlock("", CurFun.CurrentFunction);
525   if (ID.Type == ValID::LocalName) {
526     BB->setName(ID.Name);
527   } else {
528     CurFun.NumberedBlocks[ID.Num] = BB;
529   }
530
531   // If this is not a definition, keep track of it so we can use it as a forward
532   // reference.
533   if (!isDefinition) {
534     // Remember where this forward reference came from.
535     CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
536   } else {
537     // The forward declaration could have been inserted anywhere in the
538     // function: insert it into the correct place now.
539     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
540     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
541   }
542   ID.destroy();
543   return BB;
544 }
545
546
547 //===----------------------------------------------------------------------===//
548 //              Code to handle forward references in instructions
549 //===----------------------------------------------------------------------===//
550 //
551 // This code handles the late binding needed with statements that reference
552 // values not defined yet... for example, a forward branch, or the PHI node for
553 // a loop body.
554 //
555 // This keeps a table (CurFun.LateResolveValues) of all such forward references
556 // and back patchs after we are done.
557 //
558
559 // ResolveDefinitions - If we could not resolve some defs at parsing
560 // time (forward branches, phi functions for loops, etc...) resolve the
561 // defs now...
562 //
563 static void 
564 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
565                    std::map<const Type*,ValueList> *FutureLateResolvers) {
566   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
567   for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
568          E = LateResolvers.end(); LRI != E; ++LRI) {
569     ValueList &List = LRI->second;
570     while (!List.empty()) {
571       Value *V = List.back();
572       List.pop_back();
573
574       std::map<Value*, std::pair<ValID, int> >::iterator PHI =
575         CurModule.PlaceHolderInfo.find(V);
576       assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
577
578       ValID &DID = PHI->second.first;
579
580       Value *TheRealValue = getValNonImprovising(LRI->first, DID);
581       if (TriggerError)
582         return;
583       if (TheRealValue) {
584         V->replaceAllUsesWith(TheRealValue);
585         delete V;
586         CurModule.PlaceHolderInfo.erase(PHI);
587       } else if (FutureLateResolvers) {
588         // Functions have their unresolved items forwarded to the module late
589         // resolver table
590         InsertValue(V, *FutureLateResolvers);
591       } else {
592         if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
593           GenerateError("Reference to an invalid definition: '" +DID.getName()+
594                          "' of type '" + V->getType()->getDescription() + "'",
595                          PHI->second.second);
596           return;
597         } else {
598           GenerateError("Reference to an invalid definition: #" +
599                          itostr(DID.Num) + " of type '" +
600                          V->getType()->getDescription() + "'",
601                          PHI->second.second);
602           return;
603         }
604       }
605     }
606   }
607
608   LateResolvers.clear();
609 }
610
611 // ResolveTypeTo - A brand new type was just declared.  This means that (if
612 // name is not null) things referencing Name can be resolved.  Otherwise, things
613 // refering to the number can be resolved.  Do this now.
614 //
615 static void ResolveTypeTo(char *Name, const Type *ToTy) {
616   ValID D;
617   if (Name) D = ValID::createLocalName(Name);
618   else      D = ValID::createLocalID(CurModule.Types.size());
619
620   std::map<ValID, PATypeHolder>::iterator I =
621     CurModule.LateResolveTypes.find(D);
622   if (I != CurModule.LateResolveTypes.end()) {
623     ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
624     CurModule.LateResolveTypes.erase(I);
625   }
626 }
627
628 // setValueName - Set the specified value to the name given.  The name may be
629 // null potentially, in which case this is a noop.  The string passed in is
630 // assumed to be a malloc'd string buffer, and is free'd by this function.
631 //
632 static void setValueName(Value *V, char *NameStr) {
633   if (!NameStr) return;
634   std::string Name(NameStr);      // Copy string
635   free(NameStr);                  // Free old string
636
637   if (V->getType() == Type::VoidTy) {
638     GenerateError("Can't assign name '" + Name+"' to value with void type");
639     return;
640   }
641
642   assert(inFunctionScope() && "Must be in function scope!");
643   SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
644   if (ST.lookup(V->getType(), Name)) {
645     GenerateError("Redefinition of value '" + Name + "' of type '" +
646                    V->getType()->getDescription() + "'");
647     return;
648   }
649
650   // Set the name.
651   V->setName(Name);
652 }
653
654 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
655 /// this is a declaration, otherwise it is a definition.
656 static GlobalVariable *
657 ParseGlobalVariable(char *NameStr,
658                     GlobalValue::LinkageTypes Linkage,
659                     GlobalValue::VisibilityTypes Visibility,
660                     bool isConstantGlobal, const Type *Ty,
661                     Constant *Initializer) {
662   if (isa<FunctionType>(Ty)) {
663     GenerateError("Cannot declare global vars of function type");
664     return 0;
665   }
666
667   const PointerType *PTy = PointerType::get(Ty);
668
669   std::string Name;
670   if (NameStr) {
671     Name = NameStr;      // Copy string
672     free(NameStr);       // Free old string
673   }
674
675   // See if this global value was forward referenced.  If so, recycle the
676   // object.
677   ValID ID;
678   if (!Name.empty()) {
679     ID = ValID::createGlobalName((char*)Name.c_str());
680   } else {
681     ID = ValID::createGlobalID(CurModule.Values[PTy].size());
682   }
683
684   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
685     // Move the global to the end of the list, from whereever it was
686     // previously inserted.
687     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
688     CurModule.CurrentModule->getGlobalList().remove(GV);
689     CurModule.CurrentModule->getGlobalList().push_back(GV);
690     GV->setInitializer(Initializer);
691     GV->setLinkage(Linkage);
692     GV->setVisibility(Visibility);
693     GV->setConstant(isConstantGlobal);
694     InsertValue(GV, CurModule.Values);
695     return GV;
696   }
697
698   // If this global has a name, check to see if there is already a definition
699   // of this global in the module.  If so, it is an error.
700   if (!Name.empty()) {
701     // We are a simple redefinition of a value, check to see if it is defined
702     // the same as the old one.
703     if (CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
704       GenerateError("Redefinition of global variable named '" + Name +
705                      "' of type '" + Ty->getDescription() + "'");
706       return 0;
707     }
708   }
709
710   // Otherwise there is no existing GV to use, create one now.
711   GlobalVariable *GV =
712     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
713                        CurModule.CurrentModule);
714   GV->setVisibility(Visibility);
715   InsertValue(GV, CurModule.Values);
716   return GV;
717 }
718
719 // setTypeName - Set the specified type to the name given.  The name may be
720 // null potentially, in which case this is a noop.  The string passed in is
721 // assumed to be a malloc'd string buffer, and is freed by this function.
722 //
723 // This function returns true if the type has already been defined, but is
724 // allowed to be redefined in the specified context.  If the name is a new name
725 // for the type plane, it is inserted and false is returned.
726 static bool setTypeName(const Type *T, char *NameStr) {
727   assert(!inFunctionScope() && "Can't give types function-local names!");
728   if (NameStr == 0) return false;
729  
730   std::string Name(NameStr);      // Copy string
731   free(NameStr);                  // Free old string
732
733   // We don't allow assigning names to void type
734   if (T == Type::VoidTy) {
735     GenerateError("Can't assign name '" + Name + "' to the void type");
736     return false;
737   }
738
739   // Set the type name, checking for conflicts as we do so.
740   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
741
742   if (AlreadyExists) {   // Inserting a name that is already defined???
743     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
744     assert(Existing && "Conflict but no matching type?!");
745
746     // There is only one case where this is allowed: when we are refining an
747     // opaque type.  In this case, Existing will be an opaque type.
748     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
749       // We ARE replacing an opaque type!
750       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
751       return true;
752     }
753
754     // Otherwise, this is an attempt to redefine a type. That's okay if
755     // the redefinition is identical to the original. This will be so if
756     // Existing and T point to the same Type object. In this one case we
757     // allow the equivalent redefinition.
758     if (Existing == T) return true;  // Yes, it's equal.
759
760     // Any other kind of (non-equivalent) redefinition is an error.
761     GenerateError("Redefinition of type named '" + Name + "' of type '" +
762                    T->getDescription() + "'");
763   }
764
765   return false;
766 }
767
768 //===----------------------------------------------------------------------===//
769 // Code for handling upreferences in type names...
770 //
771
772 // TypeContains - Returns true if Ty directly contains E in it.
773 //
774 static bool TypeContains(const Type *Ty, const Type *E) {
775   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
776                    E) != Ty->subtype_end();
777 }
778
779 namespace {
780   struct UpRefRecord {
781     // NestingLevel - The number of nesting levels that need to be popped before
782     // this type is resolved.
783     unsigned NestingLevel;
784
785     // LastContainedTy - This is the type at the current binding level for the
786     // type.  Every time we reduce the nesting level, this gets updated.
787     const Type *LastContainedTy;
788
789     // UpRefTy - This is the actual opaque type that the upreference is
790     // represented with.
791     OpaqueType *UpRefTy;
792
793     UpRefRecord(unsigned NL, OpaqueType *URTy)
794       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
795   };
796 }
797
798 // UpRefs - A list of the outstanding upreferences that need to be resolved.
799 static std::vector<UpRefRecord> UpRefs;
800
801 /// HandleUpRefs - Every time we finish a new layer of types, this function is
802 /// called.  It loops through the UpRefs vector, which is a list of the
803 /// currently active types.  For each type, if the up reference is contained in
804 /// the newly completed type, we decrement the level count.  When the level
805 /// count reaches zero, the upreferenced type is the type that is passed in:
806 /// thus we can complete the cycle.
807 ///
808 static PATypeHolder HandleUpRefs(const Type *ty) {
809   // If Ty isn't abstract, or if there are no up-references in it, then there is
810   // nothing to resolve here.
811   if (!ty->isAbstract() || UpRefs.empty()) return ty;
812   
813   PATypeHolder Ty(ty);
814   UR_OUT("Type '" << Ty->getDescription() <<
815          "' newly formed.  Resolving upreferences.\n" <<
816          UpRefs.size() << " upreferences active!\n");
817
818   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
819   // to zero), we resolve them all together before we resolve them to Ty.  At
820   // the end of the loop, if there is anything to resolve to Ty, it will be in
821   // this variable.
822   OpaqueType *TypeToResolve = 0;
823
824   for (unsigned i = 0; i != UpRefs.size(); ++i) {
825     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
826            << UpRefs[i].second->getDescription() << ") = "
827            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
828     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
829       // Decrement level of upreference
830       unsigned Level = --UpRefs[i].NestingLevel;
831       UpRefs[i].LastContainedTy = Ty;
832       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
833       if (Level == 0) {                     // Upreference should be resolved!
834         if (!TypeToResolve) {
835           TypeToResolve = UpRefs[i].UpRefTy;
836         } else {
837           UR_OUT("  * Resolving upreference for "
838                  << UpRefs[i].second->getDescription() << "\n";
839                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
840           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
841           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
842                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
843         }
844         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
845         --i;                                // Do not skip the next element...
846       }
847     }
848   }
849
850   if (TypeToResolve) {
851     UR_OUT("  * Resolving upreference for "
852            << UpRefs[i].second->getDescription() << "\n";
853            std::string OldName = TypeToResolve->getDescription());
854     TypeToResolve->refineAbstractTypeTo(Ty);
855   }
856
857   return Ty;
858 }
859
860 //===----------------------------------------------------------------------===//
861 //            RunVMAsmParser - Define an interface to this parser
862 //===----------------------------------------------------------------------===//
863 //
864 static Module* RunParser(Module * M);
865
866 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
867   set_scan_file(F);
868
869   CurFilename = Filename;
870   return RunParser(new Module(CurFilename));
871 }
872
873 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
874   set_scan_string(AsmString);
875
876   CurFilename = "from_memory";
877   if (M == NULL) {
878     return RunParser(new Module (CurFilename));
879   } else {
880     return RunParser(M);
881   }
882 }
883
884 %}
885
886 %union {
887   llvm::Module                           *ModuleVal;
888   llvm::Function                         *FunctionVal;
889   llvm::BasicBlock                       *BasicBlockVal;
890   llvm::TerminatorInst                   *TermInstVal;
891   llvm::Instruction                      *InstVal;
892   llvm::Constant                         *ConstVal;
893
894   const llvm::Type                       *PrimType;
895   std::list<llvm::PATypeHolder>          *TypeList;
896   llvm::PATypeHolder                     *TypeVal;
897   llvm::Value                            *ValueVal;
898   std::vector<llvm::Value*>              *ValueList;
899   llvm::ArgListType                      *ArgList;
900   llvm::TypeWithAttrs                     TypeWithAttrs;
901   llvm::TypeWithAttrsList                *TypeWithAttrsList;
902   llvm::ValueRefList                     *ValueRefList;
903
904   // Represent the RHS of PHI node
905   std::list<std::pair<llvm::Value*,
906                       llvm::BasicBlock*> > *PHIList;
907   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
908   std::vector<llvm::Constant*>           *ConstVector;
909
910   llvm::GlobalValue::LinkageTypes         Linkage;
911   llvm::GlobalValue::VisibilityTypes      Visibility;
912   llvm::FunctionType::ParameterAttributes ParamAttrs;
913   int64_t                           SInt64Val;
914   uint64_t                          UInt64Val;
915   int                               SIntVal;
916   unsigned                          UIntVal;
917   double                            FPVal;
918   bool                              BoolVal;
919
920   char                             *StrVal;   // This memory is strdup'd!
921   llvm::ValID                       ValIDVal; // strdup'd memory maybe!
922
923   llvm::Instruction::BinaryOps      BinaryOpVal;
924   llvm::Instruction::TermOps        TermOpVal;
925   llvm::Instruction::MemoryOps      MemOpVal;
926   llvm::Instruction::CastOps        CastOpVal;
927   llvm::Instruction::OtherOps       OtherOpVal;
928   llvm::ICmpInst::Predicate         IPredicate;
929   llvm::FCmpInst::Predicate         FPredicate;
930 }
931
932 %type <ModuleVal>     Module 
933 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
934 %type <BasicBlockVal> BasicBlock InstructionList
935 %type <TermInstVal>   BBTerminatorInst
936 %type <InstVal>       Inst InstVal MemoryInst
937 %type <ConstVal>      ConstVal ConstExpr
938 %type <ConstVector>   ConstVector
939 %type <ArgList>       ArgList ArgListH
940 %type <PHIList>       PHIList
941 %type <ValueRefList>  ValueRefList      // For call param lists & GEP indices
942 %type <ValueList>     IndexList         // For GEP indices
943 %type <TypeList>      TypeListI 
944 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
945 %type <TypeWithAttrs> ArgType
946 %type <JumpTable>     JumpTable
947 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
948 %type <BoolVal>       OptVolatile                 // 'volatile' or not
949 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
950 %type <BoolVal>       OptSideEffect               // 'sideeffect' or not.
951 %type <Linkage>       GVInternalLinkage GVExternalLinkage
952 %type <Linkage>       FunctionDefineLinkage FunctionDeclareLinkage
953 %type <Visibility>    GVVisibilityStyle
954
955 // ValueRef - Unresolved reference to a definition or BB
956 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
957 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
958 // Tokens and types for handling constant integer values
959 //
960 // ESINT64VAL - A negative number within long long range
961 %token <SInt64Val> ESINT64VAL
962
963 // EUINT64VAL - A positive number within uns. long long range
964 %token <UInt64Val> EUINT64VAL
965
966 %token  <UIntVal>   LOCALVAL_ID GLOBALVAL_ID  // %123 @123
967 %token  <FPVal>     FPVAL     // Float or Double constant
968
969 // Built in types...
970 %type  <TypeVal> Types ResultTypes
971 %type  <PrimType> IntType FPType PrimType           // Classifications
972 %token <PrimType> VOID INTTYPE 
973 %token <PrimType> FLOAT DOUBLE LABEL
974 %token TYPE
975
976 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR STRINGCONSTANT ATSTRINGCONSTANT
977 %type <StrVal> LocalName OptLocalName OptLocalAssign
978 %type <StrVal> GlobalName OptGlobalAssign
979 %type <UIntVal> OptAlign OptCAlign
980 %type <StrVal> OptSection SectionString
981
982 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
983 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
984 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
985 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
986 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
987 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
988 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
989 %token DATALAYOUT
990 %type <UIntVal> OptCallingConv
991 %type <ParamAttrs> OptParamAttrs ParamAttr 
992 %type <ParamAttrs> OptFuncAttrs  FuncAttr
993
994 // Basic Block Terminating Operators
995 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
996
997 // Binary Operators
998 %type  <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
999 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1000 %token <BinaryOpVal> SHL LSHR ASHR
1001
1002 %token <OtherOpVal> ICMP FCMP
1003 %type  <IPredicate> IPredicates
1004 %type  <FPredicate> FPredicates
1005 %token  EQ NE SLT SGT SLE SGE ULT UGT ULE UGE 
1006 %token  OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1007
1008 // Memory Instructions
1009 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1010
1011 // Cast Operators
1012 %type <CastOpVal> CastOps
1013 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1014 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1015
1016 // Other Operators
1017 %token <OtherOpVal> PHI_TOK SELECT VAARG
1018 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1019
1020 // Function Attributes
1021 %token NORETURN INREG SRET
1022
1023 // Visibility Styles
1024 %token DEFAULT HIDDEN
1025
1026 %start Module
1027 %%
1028
1029
1030 // Operations that are notably excluded from this list include:
1031 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1032 //
1033 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1034 LogicalOps   : SHL | LSHR | ASHR | AND | OR | XOR;
1035 CastOps      : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST | 
1036                UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1037
1038 IPredicates  
1039   : EQ   { $$ = ICmpInst::ICMP_EQ; }  | NE   { $$ = ICmpInst::ICMP_NE; }
1040   | SLT  { $$ = ICmpInst::ICMP_SLT; } | SGT  { $$ = ICmpInst::ICMP_SGT; }
1041   | SLE  { $$ = ICmpInst::ICMP_SLE; } | SGE  { $$ = ICmpInst::ICMP_SGE; }
1042   | ULT  { $$ = ICmpInst::ICMP_ULT; } | UGT  { $$ = ICmpInst::ICMP_UGT; }
1043   | ULE  { $$ = ICmpInst::ICMP_ULE; } | UGE  { $$ = ICmpInst::ICMP_UGE; } 
1044   ;
1045
1046 FPredicates  
1047   : OEQ  { $$ = FCmpInst::FCMP_OEQ; } | ONE  { $$ = FCmpInst::FCMP_ONE; }
1048   | OLT  { $$ = FCmpInst::FCMP_OLT; } | OGT  { $$ = FCmpInst::FCMP_OGT; }
1049   | OLE  { $$ = FCmpInst::FCMP_OLE; } | OGE  { $$ = FCmpInst::FCMP_OGE; }
1050   | ORD  { $$ = FCmpInst::FCMP_ORD; } | UNO  { $$ = FCmpInst::FCMP_UNO; }
1051   | UEQ  { $$ = FCmpInst::FCMP_UEQ; } | UNE  { $$ = FCmpInst::FCMP_UNE; }
1052   | ULT  { $$ = FCmpInst::FCMP_ULT; } | UGT  { $$ = FCmpInst::FCMP_UGT; }
1053   | ULE  { $$ = FCmpInst::FCMP_ULE; } | UGE  { $$ = FCmpInst::FCMP_UGE; }
1054   | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1055   | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1056   ;
1057
1058 // These are some types that allow classification if we only want a particular 
1059 // thing... for example, only a signed, unsigned, or integral type.
1060 IntType :  INTTYPE;
1061 FPType   : FLOAT | DOUBLE;
1062
1063 LocalName : LOCALVAR | STRINGCONSTANT;
1064 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1065
1066 /// OptLocalAssign - Value producing statements have an optional assignment
1067 /// component.
1068 OptLocalAssign : LocalName '=' {
1069     $$ = $1;
1070     CHECK_FOR_ERROR
1071   }
1072   | /*empty*/ {
1073     $$ = 0;
1074     CHECK_FOR_ERROR
1075   };
1076
1077 GlobalName : GLOBALVAR | ATSTRINGCONSTANT;
1078
1079 OptGlobalAssign : GlobalName '=' {
1080     $$ = $1;
1081     CHECK_FOR_ERROR
1082   }
1083   | /*empty*/ {
1084     $$ = 0;
1085     CHECK_FOR_ERROR
1086   };
1087
1088 GVInternalLinkage 
1089   : INTERNAL    { $$ = GlobalValue::InternalLinkage; } 
1090   | WEAK        { $$ = GlobalValue::WeakLinkage; } 
1091   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; }
1092   | APPENDING   { $$ = GlobalValue::AppendingLinkage; }
1093   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1094   ;
1095
1096 GVExternalLinkage
1097   : DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; }
1098   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1099   | EXTERNAL    { $$ = GlobalValue::ExternalLinkage; }
1100   ;
1101
1102 GVVisibilityStyle
1103   : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1104   | HIDDEN    { $$ = GlobalValue::HiddenVisibility;  }
1105   ;
1106
1107 FunctionDeclareLinkage
1108   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1109   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } 
1110   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1111   ;
1112   
1113 FunctionDefineLinkage 
1114   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1115   | INTERNAL    { $$ = GlobalValue::InternalLinkage; }
1116   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; }
1117   | WEAK        { $$ = GlobalValue::WeakLinkage; }
1118   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1119   ; 
1120
1121 OptCallingConv : /*empty*/          { $$ = CallingConv::C; } |
1122                  CCC_TOK            { $$ = CallingConv::C; } |
1123                  FASTCC_TOK         { $$ = CallingConv::Fast; } |
1124                  COLDCC_TOK         { $$ = CallingConv::Cold; } |
1125                  X86_STDCALLCC_TOK  { $$ = CallingConv::X86_StdCall; } |
1126                  X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1127                  CC_TOK EUINT64VAL  {
1128                    if ((unsigned)$2 != $2)
1129                      GEN_ERROR("Calling conv too large");
1130                    $$ = $2;
1131                   CHECK_FOR_ERROR
1132                  };
1133
1134 ParamAttr     : ZEXT  { $$ = FunctionType::ZExtAttribute;      }
1135               | SEXT  { $$ = FunctionType::SExtAttribute;      }
1136               | INREG { $$ = FunctionType::InRegAttribute;     }
1137               | SRET  { $$ = FunctionType::StructRetAttribute; }
1138               ;
1139
1140 OptParamAttrs : /* empty */  { $$ = FunctionType::NoAttributeSet; }
1141               | OptParamAttrs ParamAttr {
1142                 $$ = FunctionType::ParameterAttributes($1 | $2);
1143               }
1144               ;
1145
1146 FuncAttr      : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1147               | ParamAttr
1148               ;
1149
1150 OptFuncAttrs  : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1151               | OptFuncAttrs FuncAttr {
1152                 $$ = FunctionType::ParameterAttributes($1 | $2);
1153               }
1154               ;
1155
1156 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1157 // a comma before it.
1158 OptAlign : /*empty*/        { $$ = 0; } |
1159            ALIGN EUINT64VAL {
1160   $$ = $2;
1161   if ($$ != 0 && !isPowerOf2_32($$))
1162     GEN_ERROR("Alignment must be a power of two");
1163   CHECK_FOR_ERROR
1164 };
1165 OptCAlign : /*empty*/            { $$ = 0; } |
1166             ',' ALIGN EUINT64VAL {
1167   $$ = $3;
1168   if ($$ != 0 && !isPowerOf2_32($$))
1169     GEN_ERROR("Alignment must be a power of two");
1170   CHECK_FOR_ERROR
1171 };
1172
1173
1174 SectionString : SECTION STRINGCONSTANT {
1175   for (unsigned i = 0, e = strlen($2); i != e; ++i)
1176     if ($2[i] == '"' || $2[i] == '\\')
1177       GEN_ERROR("Invalid character in section name");
1178   $$ = $2;
1179   CHECK_FOR_ERROR
1180 };
1181
1182 OptSection : /*empty*/ { $$ = 0; } |
1183              SectionString { $$ = $1; };
1184
1185 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1186 // is set to be the global we are processing.
1187 //
1188 GlobalVarAttributes : /* empty */ {} |
1189                      ',' GlobalVarAttribute GlobalVarAttributes {};
1190 GlobalVarAttribute : SectionString {
1191     CurGV->setSection($1);
1192     free($1);
1193     CHECK_FOR_ERROR
1194   } 
1195   | ALIGN EUINT64VAL {
1196     if ($2 != 0 && !isPowerOf2_32($2))
1197       GEN_ERROR("Alignment must be a power of two");
1198     CurGV->setAlignment($2);
1199     CHECK_FOR_ERROR
1200   };
1201
1202 //===----------------------------------------------------------------------===//
1203 // Types includes all predefined types... except void, because it can only be
1204 // used in specific contexts (function returning void for example).  
1205
1206 // Derived types are added later...
1207 //
1208 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1209
1210 Types 
1211   : OPAQUE {
1212     $$ = new PATypeHolder(OpaqueType::get());
1213     CHECK_FOR_ERROR
1214   }
1215   | PrimType {
1216     $$ = new PATypeHolder($1);
1217     CHECK_FOR_ERROR
1218   }
1219   | Types '*' {                             // Pointer type?
1220     if (*$1 == Type::LabelTy)
1221       GEN_ERROR("Cannot form a pointer to a basic block");
1222     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1223     delete $1;
1224     CHECK_FOR_ERROR
1225   }
1226   | SymbolicValueRef {            // Named types are also simple types...
1227     const Type* tmp = getTypeVal($1);
1228     CHECK_FOR_ERROR
1229     $$ = new PATypeHolder(tmp);
1230   }
1231   | '\\' EUINT64VAL {                   // Type UpReference
1232     if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1233     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1234     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1235     $$ = new PATypeHolder(OT);
1236     UR_OUT("New Upreference!\n");
1237     CHECK_FOR_ERROR
1238   }
1239   | Types '(' ArgTypeListI ')' OptFuncAttrs {
1240     std::vector<const Type*> Params;
1241     std::vector<FunctionType::ParameterAttributes> Attrs;
1242     Attrs.push_back($5);
1243     for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1244       Params.push_back(I->Ty->get());
1245       if (I->Ty->get() != Type::VoidTy)
1246         Attrs.push_back(I->Attrs);
1247     }
1248     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1249     if (isVarArg) Params.pop_back();
1250
1251     FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1252     delete $3;   // Delete the argument list
1253     delete $1;   // Delete the return type handle
1254     $$ = new PATypeHolder(HandleUpRefs(FT)); 
1255     CHECK_FOR_ERROR
1256   }
1257   | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1258     std::vector<const Type*> Params;
1259     std::vector<FunctionType::ParameterAttributes> Attrs;
1260     Attrs.push_back($5);
1261     for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1262       Params.push_back(I->Ty->get());
1263       if (I->Ty->get() != Type::VoidTy)
1264         Attrs.push_back(I->Attrs);
1265     }
1266     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1267     if (isVarArg) Params.pop_back();
1268
1269     FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1270     delete $3;      // Delete the argument list
1271     $$ = new PATypeHolder(HandleUpRefs(FT)); 
1272     CHECK_FOR_ERROR
1273   }
1274
1275   | '[' EUINT64VAL 'x' Types ']' {          // Sized array type?
1276     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1277     delete $4;
1278     CHECK_FOR_ERROR
1279   }
1280   | '<' EUINT64VAL 'x' Types '>' {          // Packed array type?
1281      const llvm::Type* ElemTy = $4->get();
1282      if ((unsigned)$2 != $2)
1283         GEN_ERROR("Unsigned result not equal to signed result");
1284      if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1285         GEN_ERROR("Element type of a PackedType must be primitive");
1286      if (!isPowerOf2_32($2))
1287        GEN_ERROR("Vector length should be a power of 2");
1288      $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1289      delete $4;
1290      CHECK_FOR_ERROR
1291   }
1292   | '{' TypeListI '}' {                        // Structure type?
1293     std::vector<const Type*> Elements;
1294     for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1295            E = $2->end(); I != E; ++I)
1296       Elements.push_back(*I);
1297
1298     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1299     delete $2;
1300     CHECK_FOR_ERROR
1301   }
1302   | '{' '}' {                                  // Empty structure type?
1303     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1304     CHECK_FOR_ERROR
1305   }
1306   | '<' '{' TypeListI '}' '>' {
1307     std::vector<const Type*> Elements;
1308     for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1309            E = $3->end(); I != E; ++I)
1310       Elements.push_back(*I);
1311
1312     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1313     delete $3;
1314     CHECK_FOR_ERROR
1315   }
1316   | '<' '{' '}' '>' {                         // Empty structure type?
1317     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1318     CHECK_FOR_ERROR
1319   }
1320   ;
1321
1322 ArgType 
1323   : Types OptParamAttrs { 
1324     $$.Ty = $1; 
1325     $$.Attrs = $2; 
1326   }
1327   ;
1328
1329 ResultTypes
1330   : Types {
1331     if (!UpRefs.empty())
1332       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1333     if (!(*$1)->isFirstClassType())
1334       GEN_ERROR("LLVM functions cannot return aggregate types");
1335     $$ = $1;
1336   }
1337   | VOID {
1338     $$ = new PATypeHolder(Type::VoidTy);
1339   }
1340   ;
1341
1342 ArgTypeList : ArgType {
1343     $$ = new TypeWithAttrsList();
1344     $$->push_back($1);
1345     CHECK_FOR_ERROR
1346   }
1347   | ArgTypeList ',' ArgType {
1348     ($$=$1)->push_back($3);
1349     CHECK_FOR_ERROR
1350   }
1351   ;
1352
1353 ArgTypeListI 
1354   : ArgTypeList
1355   | ArgTypeList ',' DOTDOTDOT {
1356     $$=$1;
1357     TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1358     TWA.Ty = new PATypeHolder(Type::VoidTy);
1359     $$->push_back(TWA);
1360     CHECK_FOR_ERROR
1361   }
1362   | DOTDOTDOT {
1363     $$ = new TypeWithAttrsList;
1364     TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1365     TWA.Ty = new PATypeHolder(Type::VoidTy);
1366     $$->push_back(TWA);
1367     CHECK_FOR_ERROR
1368   }
1369   | /*empty*/ {
1370     $$ = new TypeWithAttrsList();
1371     CHECK_FOR_ERROR
1372   };
1373
1374 // TypeList - Used for struct declarations and as a basis for function type 
1375 // declaration type lists
1376 //
1377 TypeListI : Types {
1378     $$ = new std::list<PATypeHolder>();
1379     $$->push_back(*$1); delete $1;
1380     CHECK_FOR_ERROR
1381   }
1382   | TypeListI ',' Types {
1383     ($$=$1)->push_back(*$3); delete $3;
1384     CHECK_FOR_ERROR
1385   };
1386
1387 // ConstVal - The various declarations that go into the constant pool.  This
1388 // production is used ONLY to represent constants that show up AFTER a 'const',
1389 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1390 // into other expressions (such as integers and constexprs) are handled by the
1391 // ResolvedVal, ValueRef and ConstValueRef productions.
1392 //
1393 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1394     if (!UpRefs.empty())
1395       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1396     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1397     if (ATy == 0)
1398       GEN_ERROR("Cannot make array constant with type: '" + 
1399                      (*$1)->getDescription() + "'");
1400     const Type *ETy = ATy->getElementType();
1401     int NumElements = ATy->getNumElements();
1402
1403     // Verify that we have the correct size...
1404     if (NumElements != -1 && NumElements != (int)$3->size())
1405       GEN_ERROR("Type mismatch: constant sized array initialized with " +
1406                      utostr($3->size()) +  " arguments, but has size of " + 
1407                      itostr(NumElements) + "");
1408
1409     // Verify all elements are correct type!
1410     for (unsigned i = 0; i < $3->size(); i++) {
1411       if (ETy != (*$3)[i]->getType())
1412         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1413                        ETy->getDescription() +"' as required!\nIt is of type '"+
1414                        (*$3)[i]->getType()->getDescription() + "'.");
1415     }
1416
1417     $$ = ConstantArray::get(ATy, *$3);
1418     delete $1; delete $3;
1419     CHECK_FOR_ERROR
1420   }
1421   | Types '[' ']' {
1422     if (!UpRefs.empty())
1423       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1424     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1425     if (ATy == 0)
1426       GEN_ERROR("Cannot make array constant with type: '" + 
1427                      (*$1)->getDescription() + "'");
1428
1429     int NumElements = ATy->getNumElements();
1430     if (NumElements != -1 && NumElements != 0) 
1431       GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1432                      " arguments, but has size of " + itostr(NumElements) +"");
1433     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1434     delete $1;
1435     CHECK_FOR_ERROR
1436   }
1437   | Types 'c' STRINGCONSTANT {
1438     if (!UpRefs.empty())
1439       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1440     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1441     if (ATy == 0)
1442       GEN_ERROR("Cannot make array constant with type: '" + 
1443                      (*$1)->getDescription() + "'");
1444
1445     int NumElements = ATy->getNumElements();
1446     const Type *ETy = ATy->getElementType();
1447     char *EndStr = UnEscapeLexed($3, true);
1448     if (NumElements != -1 && NumElements != (EndStr-$3))
1449       GEN_ERROR("Can't build string constant of size " + 
1450                      itostr((int)(EndStr-$3)) +
1451                      " when array has size " + itostr(NumElements) + "");
1452     std::vector<Constant*> Vals;
1453     if (ETy == Type::Int8Ty) {
1454       for (unsigned char *C = (unsigned char *)$3; 
1455         C != (unsigned char*)EndStr; ++C)
1456       Vals.push_back(ConstantInt::get(ETy, *C));
1457     } else {
1458       free($3);
1459       GEN_ERROR("Cannot build string arrays of non byte sized elements");
1460     }
1461     free($3);
1462     $$ = ConstantArray::get(ATy, Vals);
1463     delete $1;
1464     CHECK_FOR_ERROR
1465   }
1466   | Types '<' ConstVector '>' { // Nonempty unsized arr
1467     if (!UpRefs.empty())
1468       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1469     const PackedType *PTy = dyn_cast<PackedType>($1->get());
1470     if (PTy == 0)
1471       GEN_ERROR("Cannot make packed constant with type: '" + 
1472                      (*$1)->getDescription() + "'");
1473     const Type *ETy = PTy->getElementType();
1474     int NumElements = PTy->getNumElements();
1475
1476     // Verify that we have the correct size...
1477     if (NumElements != -1 && NumElements != (int)$3->size())
1478       GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1479                      utostr($3->size()) +  " arguments, but has size of " + 
1480                      itostr(NumElements) + "");
1481
1482     // Verify all elements are correct type!
1483     for (unsigned i = 0; i < $3->size(); i++) {
1484       if (ETy != (*$3)[i]->getType())
1485         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1486            ETy->getDescription() +"' as required!\nIt is of type '"+
1487            (*$3)[i]->getType()->getDescription() + "'.");
1488     }
1489
1490     $$ = ConstantPacked::get(PTy, *$3);
1491     delete $1; delete $3;
1492     CHECK_FOR_ERROR
1493   }
1494   | Types '{' ConstVector '}' {
1495     const StructType *STy = dyn_cast<StructType>($1->get());
1496     if (STy == 0)
1497       GEN_ERROR("Cannot make struct constant with type: '" + 
1498                      (*$1)->getDescription() + "'");
1499
1500     if ($3->size() != STy->getNumContainedTypes())
1501       GEN_ERROR("Illegal number of initializers for structure type");
1502
1503     // Check to ensure that constants are compatible with the type initializer!
1504     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1505       if ((*$3)[i]->getType() != STy->getElementType(i))
1506         GEN_ERROR("Expected type '" +
1507                        STy->getElementType(i)->getDescription() +
1508                        "' for element #" + utostr(i) +
1509                        " of structure initializer");
1510
1511     // Check to ensure that Type is not packed
1512     if (STy->isPacked())
1513       GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1514
1515     $$ = ConstantStruct::get(STy, *$3);
1516     delete $1; delete $3;
1517     CHECK_FOR_ERROR
1518   }
1519   | Types '{' '}' {
1520     if (!UpRefs.empty())
1521       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1522     const StructType *STy = dyn_cast<StructType>($1->get());
1523     if (STy == 0)
1524       GEN_ERROR("Cannot make struct constant with type: '" + 
1525                      (*$1)->getDescription() + "'");
1526
1527     if (STy->getNumContainedTypes() != 0)
1528       GEN_ERROR("Illegal number of initializers for structure type");
1529
1530     // Check to ensure that Type is not packed
1531     if (STy->isPacked())
1532       GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1533
1534     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1535     delete $1;
1536     CHECK_FOR_ERROR
1537   }
1538   | Types '<' '{' ConstVector '}' '>' {
1539     const StructType *STy = dyn_cast<StructType>($1->get());
1540     if (STy == 0)
1541       GEN_ERROR("Cannot make struct constant with type: '" + 
1542                      (*$1)->getDescription() + "'");
1543
1544     if ($4->size() != STy->getNumContainedTypes())
1545       GEN_ERROR("Illegal number of initializers for structure type");
1546
1547     // Check to ensure that constants are compatible with the type initializer!
1548     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1549       if ((*$4)[i]->getType() != STy->getElementType(i))
1550         GEN_ERROR("Expected type '" +
1551                        STy->getElementType(i)->getDescription() +
1552                        "' for element #" + utostr(i) +
1553                        " of structure initializer");
1554
1555     // Check to ensure that Type is packed
1556     if (!STy->isPacked())
1557       GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1558
1559     $$ = ConstantStruct::get(STy, *$4);
1560     delete $1; delete $4;
1561     CHECK_FOR_ERROR
1562   }
1563   | Types '<' '{' '}' '>' {
1564     if (!UpRefs.empty())
1565       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1566     const StructType *STy = dyn_cast<StructType>($1->get());
1567     if (STy == 0)
1568       GEN_ERROR("Cannot make struct constant with type: '" + 
1569                      (*$1)->getDescription() + "'");
1570
1571     if (STy->getNumContainedTypes() != 0)
1572       GEN_ERROR("Illegal number of initializers for structure type");
1573
1574     // Check to ensure that Type is packed
1575     if (!STy->isPacked())
1576       GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1577
1578     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1579     delete $1;
1580     CHECK_FOR_ERROR
1581   }
1582   | Types NULL_TOK {
1583     if (!UpRefs.empty())
1584       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1585     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1586     if (PTy == 0)
1587       GEN_ERROR("Cannot make null pointer constant with type: '" + 
1588                      (*$1)->getDescription() + "'");
1589
1590     $$ = ConstantPointerNull::get(PTy);
1591     delete $1;
1592     CHECK_FOR_ERROR
1593   }
1594   | Types UNDEF {
1595     if (!UpRefs.empty())
1596       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1597     $$ = UndefValue::get($1->get());
1598     delete $1;
1599     CHECK_FOR_ERROR
1600   }
1601   | Types SymbolicValueRef {
1602     if (!UpRefs.empty())
1603       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1604     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1605     if (Ty == 0)
1606       GEN_ERROR("Global const reference must be a pointer type");
1607
1608     // ConstExprs can exist in the body of a function, thus creating
1609     // GlobalValues whenever they refer to a variable.  Because we are in
1610     // the context of a function, getValNonImprovising will search the functions
1611     // symbol table instead of the module symbol table for the global symbol,
1612     // which throws things all off.  To get around this, we just tell
1613     // getValNonImprovising that we are at global scope here.
1614     //
1615     Function *SavedCurFn = CurFun.CurrentFunction;
1616     CurFun.CurrentFunction = 0;
1617
1618     Value *V = getValNonImprovising(Ty, $2);
1619     CHECK_FOR_ERROR
1620
1621     CurFun.CurrentFunction = SavedCurFn;
1622
1623     // If this is an initializer for a constant pointer, which is referencing a
1624     // (currently) undefined variable, create a stub now that shall be replaced
1625     // in the future with the right type of variable.
1626     //
1627     if (V == 0) {
1628       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1629       const PointerType *PT = cast<PointerType>(Ty);
1630
1631       // First check to see if the forward references value is already created!
1632       PerModuleInfo::GlobalRefsType::iterator I =
1633         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1634     
1635       if (I != CurModule.GlobalRefs.end()) {
1636         V = I->second;             // Placeholder already exists, use it...
1637         $2.destroy();
1638       } else {
1639         std::string Name;
1640         if ($2.Type == ValID::GlobalName)
1641           Name = $2.Name;
1642         else if ($2.Type != ValID::GlobalID)
1643           GEN_ERROR("Invalid reference to global");
1644
1645         // Create the forward referenced global.
1646         GlobalValue *GV;
1647         if (const FunctionType *FTy = 
1648                  dyn_cast<FunctionType>(PT->getElementType())) {
1649           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1650                             CurModule.CurrentModule);
1651         } else {
1652           GV = new GlobalVariable(PT->getElementType(), false,
1653                                   GlobalValue::ExternalLinkage, 0,
1654                                   Name, CurModule.CurrentModule);
1655         }
1656
1657         // Keep track of the fact that we have a forward ref to recycle it
1658         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1659         V = GV;
1660       }
1661     }
1662
1663     $$ = cast<GlobalValue>(V);
1664     delete $1;            // Free the type handle
1665     CHECK_FOR_ERROR
1666   }
1667   | Types ConstExpr {
1668     if (!UpRefs.empty())
1669       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1670     if ($1->get() != $2->getType())
1671       GEN_ERROR("Mismatched types for constant expression: " + 
1672         (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1673     $$ = $2;
1674     delete $1;
1675     CHECK_FOR_ERROR
1676   }
1677   | Types ZEROINITIALIZER {
1678     if (!UpRefs.empty())
1679       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1680     const Type *Ty = $1->get();
1681     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1682       GEN_ERROR("Cannot create a null initialized value of this type");
1683     $$ = Constant::getNullValue(Ty);
1684     delete $1;
1685     CHECK_FOR_ERROR
1686   }
1687   | IntType ESINT64VAL {      // integral constants
1688     if (!ConstantInt::isValueValidForType($1, $2))
1689       GEN_ERROR("Constant value doesn't fit in type");
1690     $$ = ConstantInt::get($1, $2);
1691     CHECK_FOR_ERROR
1692   }
1693   | IntType EUINT64VAL {      // integral constants
1694     if (!ConstantInt::isValueValidForType($1, $2))
1695       GEN_ERROR("Constant value doesn't fit in type");
1696     $$ = ConstantInt::get($1, $2);
1697     CHECK_FOR_ERROR
1698   }
1699   | INTTYPE TRUETOK {                      // Boolean constants
1700     assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1701     $$ = ConstantInt::getTrue();
1702     CHECK_FOR_ERROR
1703   }
1704   | INTTYPE FALSETOK {                     // Boolean constants
1705     assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1706     $$ = ConstantInt::getFalse();
1707     CHECK_FOR_ERROR
1708   }
1709   | FPType FPVAL {                   // Float & Double constants
1710     if (!ConstantFP::isValueValidForType($1, $2))
1711       GEN_ERROR("Floating point constant invalid for type");
1712     $$ = ConstantFP::get($1, $2);
1713     CHECK_FOR_ERROR
1714   };
1715
1716
1717 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1718     if (!UpRefs.empty())
1719       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1720     Constant *Val = $3;
1721     const Type *DestTy = $5->get();
1722     if (!CastInst::castIsValid($1, $3, DestTy))
1723       GEN_ERROR("invalid cast opcode for cast from '" +
1724                 Val->getType()->getDescription() + "' to '" +
1725                 DestTy->getDescription() + "'"); 
1726     $$ = ConstantExpr::getCast($1, $3, DestTy);
1727     delete $5;
1728   }
1729   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1730     if (!isa<PointerType>($3->getType()))
1731       GEN_ERROR("GetElementPtr requires a pointer operand");
1732
1733     const Type *IdxTy =
1734       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1735     if (!IdxTy)
1736       GEN_ERROR("Index list invalid for constant getelementptr");
1737
1738     SmallVector<Constant*, 8> IdxVec;
1739     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1740       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1741         IdxVec.push_back(C);
1742       else
1743         GEN_ERROR("Indices to constant getelementptr must be constants");
1744
1745     delete $4;
1746
1747     $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1748     CHECK_FOR_ERROR
1749   }
1750   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1751     if ($3->getType() != Type::Int1Ty)
1752       GEN_ERROR("Select condition must be of boolean type");
1753     if ($5->getType() != $7->getType())
1754       GEN_ERROR("Select operand types must match");
1755     $$ = ConstantExpr::getSelect($3, $5, $7);
1756     CHECK_FOR_ERROR
1757   }
1758   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1759     if ($3->getType() != $5->getType())
1760       GEN_ERROR("Binary operator types must match");
1761     CHECK_FOR_ERROR;
1762     $$ = ConstantExpr::get($1, $3, $5);
1763   }
1764   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1765     if ($3->getType() != $5->getType())
1766       GEN_ERROR("Logical operator types must match");
1767     if (!$3->getType()->isInteger()) {
1768       if (Instruction::isShift($1) || !isa<PackedType>($3->getType()) || 
1769           !cast<PackedType>($3->getType())->getElementType()->isInteger())
1770         GEN_ERROR("Logical operator requires integral operands");
1771     }
1772     $$ = ConstantExpr::get($1, $3, $5);
1773     CHECK_FOR_ERROR
1774   }
1775   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1776     if ($4->getType() != $6->getType())
1777       GEN_ERROR("icmp operand types must match");
1778     $$ = ConstantExpr::getICmp($2, $4, $6);
1779   }
1780   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1781     if ($4->getType() != $6->getType())
1782       GEN_ERROR("fcmp operand types must match");
1783     $$ = ConstantExpr::getFCmp($2, $4, $6);
1784   }
1785   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1786     if (!ExtractElementInst::isValidOperands($3, $5))
1787       GEN_ERROR("Invalid extractelement operands");
1788     $$ = ConstantExpr::getExtractElement($3, $5);
1789     CHECK_FOR_ERROR
1790   }
1791   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1792     if (!InsertElementInst::isValidOperands($3, $5, $7))
1793       GEN_ERROR("Invalid insertelement operands");
1794     $$ = ConstantExpr::getInsertElement($3, $5, $7);
1795     CHECK_FOR_ERROR
1796   }
1797   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1798     if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1799       GEN_ERROR("Invalid shufflevector operands");
1800     $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1801     CHECK_FOR_ERROR
1802   };
1803
1804
1805 // ConstVector - A list of comma separated constants.
1806 ConstVector : ConstVector ',' ConstVal {
1807     ($$ = $1)->push_back($3);
1808     CHECK_FOR_ERROR
1809   }
1810   | ConstVal {
1811     $$ = new std::vector<Constant*>();
1812     $$->push_back($1);
1813     CHECK_FOR_ERROR
1814   };
1815
1816
1817 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1818 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1819
1820
1821 //===----------------------------------------------------------------------===//
1822 //                             Rules to match Modules
1823 //===----------------------------------------------------------------------===//
1824
1825 // Module rule: Capture the result of parsing the whole file into a result
1826 // variable...
1827 //
1828 Module 
1829   : DefinitionList {
1830     $$ = ParserResult = CurModule.CurrentModule;
1831     CurModule.ModuleDone();
1832     CHECK_FOR_ERROR;
1833   }
1834   | /*empty*/ {
1835     $$ = ParserResult = CurModule.CurrentModule;
1836     CurModule.ModuleDone();
1837     CHECK_FOR_ERROR;
1838   }
1839   ;
1840
1841 DefinitionList
1842   : Definition
1843   | DefinitionList Definition
1844   ;
1845
1846 Definition 
1847   : DEFINE { CurFun.isDeclare = false; } Function {
1848     CurFun.FunctionDone();
1849     CHECK_FOR_ERROR
1850   }
1851   | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1852     CHECK_FOR_ERROR
1853   }
1854   | MODULE ASM_TOK AsmBlock {
1855     CHECK_FOR_ERROR
1856   }  
1857   | IMPLEMENTATION {
1858     // Emit an error if there are any unresolved types left.
1859     if (!CurModule.LateResolveTypes.empty()) {
1860       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1861       if (DID.Type == ValID::LocalName) {
1862         GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1863       } else {
1864         GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1865       }
1866     }
1867     CHECK_FOR_ERROR
1868   }
1869   | OptLocalAssign TYPE Types {
1870     if (!UpRefs.empty())
1871       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1872     // Eagerly resolve types.  This is not an optimization, this is a
1873     // requirement that is due to the fact that we could have this:
1874     //
1875     // %list = type { %list * }
1876     // %list = type { %list * }    ; repeated type decl
1877     //
1878     // If types are not resolved eagerly, then the two types will not be
1879     // determined to be the same type!
1880     //
1881     ResolveTypeTo($1, *$3);
1882
1883     if (!setTypeName(*$3, $1) && !$1) {
1884       CHECK_FOR_ERROR
1885       // If this is a named type that is not a redefinition, add it to the slot
1886       // table.
1887       CurModule.Types.push_back(*$3);
1888     }
1889
1890     delete $3;
1891     CHECK_FOR_ERROR
1892   }
1893   | OptLocalAssign TYPE VOID {
1894     ResolveTypeTo($1, $3);
1895
1896     if (!setTypeName($3, $1) && !$1) {
1897       CHECK_FOR_ERROR
1898       // If this is a named type that is not a redefinition, add it to the slot
1899       // table.
1900       CurModule.Types.push_back($3);
1901     }
1902     CHECK_FOR_ERROR
1903   }
1904   | OptGlobalAssign GVVisibilityStyle GlobalType ConstVal { 
1905     /* "Externally Visible" Linkage */
1906     if ($4 == 0) 
1907       GEN_ERROR("Global value initializer is not a constant");
1908     CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
1909                                 $2, $3, $4->getType(), $4);
1910     CHECK_FOR_ERROR
1911   } GlobalVarAttributes {
1912     CurGV = 0;
1913   }
1914   | OptGlobalAssign GVInternalLinkage GVVisibilityStyle GlobalType ConstVal {
1915     if ($5 == 0) 
1916       GEN_ERROR("Global value initializer is not a constant");
1917     CurGV = ParseGlobalVariable($1, $2, $3, $4, $5->getType(), $5);
1918     CHECK_FOR_ERROR
1919   } GlobalVarAttributes {
1920     CurGV = 0;
1921   }
1922   | OptGlobalAssign GVExternalLinkage GVVisibilityStyle GlobalType Types {
1923     if (!UpRefs.empty())
1924       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1925     CurGV = ParseGlobalVariable($1, $2, $3, $4, *$5, 0);
1926     CHECK_FOR_ERROR
1927     delete $5;
1928   } GlobalVarAttributes {
1929     CurGV = 0;
1930     CHECK_FOR_ERROR
1931   }
1932   | TARGET TargetDefinition { 
1933     CHECK_FOR_ERROR
1934   }
1935   | DEPLIBS '=' LibrariesDefinition {
1936     CHECK_FOR_ERROR
1937   }
1938   ;
1939
1940
1941 AsmBlock : STRINGCONSTANT {
1942   const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1943   char *EndStr = UnEscapeLexed($1, true);
1944   std::string NewAsm($1, EndStr);
1945   free($1);
1946
1947   if (AsmSoFar.empty())
1948     CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1949   else
1950     CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1951   CHECK_FOR_ERROR
1952 };
1953
1954 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
1955     CurModule.CurrentModule->setTargetTriple($3);
1956     free($3);
1957   }
1958   | DATALAYOUT '=' STRINGCONSTANT {
1959     CurModule.CurrentModule->setDataLayout($3);
1960     free($3);
1961   };
1962
1963 LibrariesDefinition : '[' LibList ']';
1964
1965 LibList : LibList ',' STRINGCONSTANT {
1966           CurModule.CurrentModule->addLibrary($3);
1967           free($3);
1968           CHECK_FOR_ERROR
1969         }
1970         | STRINGCONSTANT {
1971           CurModule.CurrentModule->addLibrary($1);
1972           free($1);
1973           CHECK_FOR_ERROR
1974         }
1975         | /* empty: end of list */ {
1976           CHECK_FOR_ERROR
1977         }
1978         ;
1979
1980 //===----------------------------------------------------------------------===//
1981 //                       Rules to match Function Headers
1982 //===----------------------------------------------------------------------===//
1983
1984 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
1985     if (!UpRefs.empty())
1986       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1987     if (*$3 == Type::VoidTy)
1988       GEN_ERROR("void typed arguments are invalid");
1989     ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
1990     $$ = $1;
1991     $1->push_back(E);
1992     CHECK_FOR_ERROR
1993   }
1994   | Types OptParamAttrs OptLocalName {
1995     if (!UpRefs.empty())
1996       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1997     if (*$1 == Type::VoidTy)
1998       GEN_ERROR("void typed arguments are invalid");
1999     ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2000     $$ = new ArgListType;
2001     $$->push_back(E);
2002     CHECK_FOR_ERROR
2003   };
2004
2005 ArgList : ArgListH {
2006     $$ = $1;
2007     CHECK_FOR_ERROR
2008   }
2009   | ArgListH ',' DOTDOTDOT {
2010     $$ = $1;
2011     struct ArgListEntry E;
2012     E.Ty = new PATypeHolder(Type::VoidTy);
2013     E.Name = 0;
2014     E.Attrs = FunctionType::NoAttributeSet;
2015     $$->push_back(E);
2016     CHECK_FOR_ERROR
2017   }
2018   | DOTDOTDOT {
2019     $$ = new ArgListType;
2020     struct ArgListEntry E;
2021     E.Ty = new PATypeHolder(Type::VoidTy);
2022     E.Name = 0;
2023     E.Attrs = FunctionType::NoAttributeSet;
2024     $$->push_back(E);
2025     CHECK_FOR_ERROR
2026   }
2027   | /* empty */ {
2028     $$ = 0;
2029     CHECK_FOR_ERROR
2030   };
2031
2032 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')' 
2033                   OptFuncAttrs OptSection OptAlign {
2034   UnEscapeLexed($3);
2035   std::string FunctionName($3);
2036   free($3);  // Free strdup'd memory!
2037   
2038   // Check the function result for abstractness if this is a define. We should
2039   // have no abstract types at this point
2040   if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2041     GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2042
2043   std::vector<const Type*> ParamTypeList;
2044   std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2045   ParamAttrs.push_back($7);
2046   if ($5) {   // If there are arguments...
2047     for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2048       const Type* Ty = I->Ty->get();
2049       if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2050         GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2051       ParamTypeList.push_back(Ty);
2052       if (Ty != Type::VoidTy)
2053         ParamAttrs.push_back(I->Attrs);
2054     }
2055   }
2056
2057   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2058   if (isVarArg) ParamTypeList.pop_back();
2059
2060   FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2061                                        ParamAttrs);
2062   const PointerType *PFT = PointerType::get(FT);
2063   delete $2;
2064
2065   ValID ID;
2066   if (!FunctionName.empty()) {
2067     ID = ValID::createGlobalName((char*)FunctionName.c_str());
2068   } else {
2069     ID = ValID::createGlobalID(CurModule.Values[PFT].size());
2070   }
2071
2072   Function *Fn = 0;
2073   // See if this function was forward referenced.  If so, recycle the object.
2074   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2075     // Move the function to the end of the list, from whereever it was 
2076     // previously inserted.
2077     Fn = cast<Function>(FWRef);
2078     CurModule.CurrentModule->getFunctionList().remove(Fn);
2079     CurModule.CurrentModule->getFunctionList().push_back(Fn);
2080   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
2081              (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2082     // If this is the case, either we need to be a forward decl, or it needs 
2083     // to be.
2084     if (!CurFun.isDeclare && !Fn->isDeclaration())
2085       GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2086     
2087     // Make sure to strip off any argument names so we can't get conflicts.
2088     if (Fn->isDeclaration())
2089       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2090            AI != AE; ++AI)
2091         AI->setName("");
2092   } else  {  // Not already defined?
2093     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2094                       CurModule.CurrentModule);
2095
2096     InsertValue(Fn, CurModule.Values);
2097   }
2098
2099   CurFun.FunctionStart(Fn);
2100
2101   if (CurFun.isDeclare) {
2102     // If we have declaration, always overwrite linkage.  This will allow us to
2103     // correctly handle cases, when pointer to function is passed as argument to
2104     // another function.
2105     Fn->setLinkage(CurFun.Linkage);
2106     Fn->setVisibility(CurFun.Visibility);
2107   }
2108   Fn->setCallingConv($1);
2109   Fn->setAlignment($9);
2110   if ($8) {
2111     Fn->setSection($8);
2112     free($8);
2113   }
2114
2115   // Add all of the arguments we parsed to the function...
2116   if ($5) {                     // Is null if empty...
2117     if (isVarArg) {  // Nuke the last entry
2118       assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0&&
2119              "Not a varargs marker!");
2120       delete $5->back().Ty;
2121       $5->pop_back();  // Delete the last entry
2122     }
2123     Function::arg_iterator ArgIt = Fn->arg_begin();
2124     unsigned Idx = 1;
2125     for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++ArgIt) {
2126       delete I->Ty;                          // Delete the typeholder...
2127       setValueName(ArgIt, I->Name);           // Insert arg into symtab...
2128       CHECK_FOR_ERROR
2129       InsertValue(ArgIt);
2130       Idx++;
2131     }
2132
2133     delete $5;                     // We're now done with the argument list
2134   }
2135   CHECK_FOR_ERROR
2136 };
2137
2138 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
2139
2140 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2141   $$ = CurFun.CurrentFunction;
2142
2143   // Make sure that we keep track of the linkage type even if there was a
2144   // previous "declare".
2145   $$->setLinkage($1);
2146   $$->setVisibility($2);
2147 };
2148
2149 END : ENDTOK | '}';                    // Allow end of '}' to end a function
2150
2151 Function : BasicBlockList END {
2152   $$ = $1;
2153   CHECK_FOR_ERROR
2154 };
2155
2156 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2157     CurFun.CurrentFunction->setLinkage($1);
2158     CurFun.CurrentFunction->setVisibility($2);
2159     $$ = CurFun.CurrentFunction;
2160     CurFun.FunctionDone();
2161     CHECK_FOR_ERROR
2162   };
2163
2164 //===----------------------------------------------------------------------===//
2165 //                        Rules to match Basic Blocks
2166 //===----------------------------------------------------------------------===//
2167
2168 OptSideEffect : /* empty */ {
2169     $$ = false;
2170     CHECK_FOR_ERROR
2171   }
2172   | SIDEEFFECT {
2173     $$ = true;
2174     CHECK_FOR_ERROR
2175   };
2176
2177 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
2178     $$ = ValID::create($1);
2179     CHECK_FOR_ERROR
2180   }
2181   | EUINT64VAL {
2182     $$ = ValID::create($1);
2183     CHECK_FOR_ERROR
2184   }
2185   | FPVAL {                     // Perhaps it's an FP constant?
2186     $$ = ValID::create($1);
2187     CHECK_FOR_ERROR
2188   }
2189   | TRUETOK {
2190     $$ = ValID::create(ConstantInt::getTrue());
2191     CHECK_FOR_ERROR
2192   } 
2193   | FALSETOK {
2194     $$ = ValID::create(ConstantInt::getFalse());
2195     CHECK_FOR_ERROR
2196   }
2197   | NULL_TOK {
2198     $$ = ValID::createNull();
2199     CHECK_FOR_ERROR
2200   }
2201   | UNDEF {
2202     $$ = ValID::createUndef();
2203     CHECK_FOR_ERROR
2204   }
2205   | ZEROINITIALIZER {     // A vector zero constant.
2206     $$ = ValID::createZeroInit();
2207     CHECK_FOR_ERROR
2208   }
2209   | '<' ConstVector '>' { // Nonempty unsized packed vector
2210     const Type *ETy = (*$2)[0]->getType();
2211     int NumElements = $2->size(); 
2212     
2213     PackedType* pt = PackedType::get(ETy, NumElements);
2214     PATypeHolder* PTy = new PATypeHolder(
2215                                          HandleUpRefs(
2216                                             PackedType::get(
2217                                                 ETy, 
2218                                                 NumElements)
2219                                             )
2220                                          );
2221     
2222     // Verify all elements are correct type!
2223     for (unsigned i = 0; i < $2->size(); i++) {
2224       if (ETy != (*$2)[i]->getType())
2225         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
2226                      ETy->getDescription() +"' as required!\nIt is of type '" +
2227                      (*$2)[i]->getType()->getDescription() + "'.");
2228     }
2229
2230     $$ = ValID::create(ConstantPacked::get(pt, *$2));
2231     delete PTy; delete $2;
2232     CHECK_FOR_ERROR
2233   }
2234   | ConstExpr {
2235     $$ = ValID::create($1);
2236     CHECK_FOR_ERROR
2237   }
2238   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2239     char *End = UnEscapeLexed($3, true);
2240     std::string AsmStr = std::string($3, End);
2241     End = UnEscapeLexed($5, true);
2242     std::string Constraints = std::string($5, End);
2243     $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2244     free($3);
2245     free($5);
2246     CHECK_FOR_ERROR
2247   };
2248
2249 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2250 // another value.
2251 //
2252 SymbolicValueRef : LOCALVAL_ID {  // Is it an integer reference...?
2253     $$ = ValID::createLocalID($1);
2254     CHECK_FOR_ERROR
2255   }
2256   | GLOBALVAL_ID {
2257     $$ = ValID::createGlobalID($1);
2258     CHECK_FOR_ERROR
2259   }
2260   | LocalName {                   // Is it a named reference...?
2261     $$ = ValID::createLocalName($1);
2262     CHECK_FOR_ERROR
2263   }
2264   | GlobalName {                   // Is it a named reference...?
2265     $$ = ValID::createGlobalName($1);
2266     CHECK_FOR_ERROR
2267   };
2268
2269 // ValueRef - A reference to a definition... either constant or symbolic
2270 ValueRef : SymbolicValueRef | ConstValueRef;
2271
2272
2273 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
2274 // type immediately preceeds the value reference, and allows complex constant
2275 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2276 ResolvedVal : Types ValueRef {
2277     if (!UpRefs.empty())
2278       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2279     $$ = getVal(*$1, $2); 
2280     delete $1;
2281     CHECK_FOR_ERROR
2282   }
2283   ;
2284
2285 BasicBlockList : BasicBlockList BasicBlock {
2286     $$ = $1;
2287     CHECK_FOR_ERROR
2288   }
2289   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
2290     $$ = $1;
2291     CHECK_FOR_ERROR
2292   };
2293
2294
2295 // Basic blocks are terminated by branching instructions: 
2296 // br, br/cc, switch, ret
2297 //
2298 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst  {
2299     setValueName($3, $2);
2300     CHECK_FOR_ERROR
2301     InsertValue($3);
2302
2303     $1->getInstList().push_back($3);
2304     InsertValue($1);
2305     $$ = $1;
2306     CHECK_FOR_ERROR
2307   };
2308
2309 InstructionList : InstructionList Inst {
2310     if (CastInst *CI1 = dyn_cast<CastInst>($2))
2311       if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2312         if (CI2->getParent() == 0)
2313           $1->getInstList().push_back(CI2);
2314     $1->getInstList().push_back($2);
2315     $$ = $1;
2316     CHECK_FOR_ERROR
2317   }
2318   | /* empty */ {
2319     $$ = getBBVal(ValID::createLocalID(CurFun.NextBBNum++), true);
2320     CHECK_FOR_ERROR
2321
2322     // Make sure to move the basic block to the correct location in the
2323     // function, instead of leaving it inserted wherever it was first
2324     // referenced.
2325     Function::BasicBlockListType &BBL = 
2326       CurFun.CurrentFunction->getBasicBlockList();
2327     BBL.splice(BBL.end(), BBL, $$);
2328     CHECK_FOR_ERROR
2329   }
2330   | LABELSTR {
2331     $$ = getBBVal(ValID::createLocalName($1), true);
2332     CHECK_FOR_ERROR
2333
2334     // Make sure to move the basic block to the correct location in the
2335     // function, instead of leaving it inserted wherever it was first
2336     // referenced.
2337     Function::BasicBlockListType &BBL = 
2338       CurFun.CurrentFunction->getBasicBlockList();
2339     BBL.splice(BBL.end(), BBL, $$);
2340     CHECK_FOR_ERROR
2341   };
2342
2343 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
2344     $$ = new ReturnInst($2);
2345     CHECK_FOR_ERROR
2346   }
2347   | RET VOID {                                       // Return with no result...
2348     $$ = new ReturnInst();
2349     CHECK_FOR_ERROR
2350   }
2351   | BR LABEL ValueRef {                         // Unconditional Branch...
2352     BasicBlock* tmpBB = getBBVal($3);
2353     CHECK_FOR_ERROR
2354     $$ = new BranchInst(tmpBB);
2355   }                                                  // Conditional Branch...
2356   | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
2357     assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2358     BasicBlock* tmpBBA = getBBVal($6);
2359     CHECK_FOR_ERROR
2360     BasicBlock* tmpBBB = getBBVal($9);
2361     CHECK_FOR_ERROR
2362     Value* tmpVal = getVal(Type::Int1Ty, $3);
2363     CHECK_FOR_ERROR
2364     $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2365   }
2366   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2367     Value* tmpVal = getVal($2, $3);
2368     CHECK_FOR_ERROR
2369     BasicBlock* tmpBB = getBBVal($6);
2370     CHECK_FOR_ERROR
2371     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2372     $$ = S;
2373
2374     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2375       E = $8->end();
2376     for (; I != E; ++I) {
2377       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2378           S->addCase(CI, I->second);
2379       else
2380         GEN_ERROR("Switch case is constant, but not a simple integer");
2381     }
2382     delete $8;
2383     CHECK_FOR_ERROR
2384   }
2385   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2386     Value* tmpVal = getVal($2, $3);
2387     CHECK_FOR_ERROR
2388     BasicBlock* tmpBB = getBBVal($6);
2389     CHECK_FOR_ERROR
2390     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2391     $$ = S;
2392     CHECK_FOR_ERROR
2393   }
2394   | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2395     TO LABEL ValueRef UNWIND LABEL ValueRef {
2396
2397     // Handle the short syntax
2398     const PointerType *PFTy = 0;
2399     const FunctionType *Ty = 0;
2400     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2401         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2402       // Pull out the types of all of the arguments...
2403       std::vector<const Type*> ParamTypes;
2404       FunctionType::ParamAttrsList ParamAttrs;
2405       ParamAttrs.push_back($8);
2406       for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2407         const Type *Ty = I->Val->getType();
2408         if (Ty == Type::VoidTy)
2409           GEN_ERROR("Short call syntax cannot be used with varargs");
2410         ParamTypes.push_back(Ty);
2411         ParamAttrs.push_back(I->Attrs);
2412       }
2413
2414       Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2415       PFTy = PointerType::get(Ty);
2416     }
2417
2418     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2419     CHECK_FOR_ERROR
2420     BasicBlock *Normal = getBBVal($11);
2421     CHECK_FOR_ERROR
2422     BasicBlock *Except = getBBVal($14);
2423     CHECK_FOR_ERROR
2424
2425     // Check the arguments
2426     ValueList Args;
2427     if ($6->empty()) {                                   // Has no arguments?
2428       // Make sure no arguments is a good thing!
2429       if (Ty->getNumParams() != 0)
2430         GEN_ERROR("No arguments passed to a function that "
2431                        "expects arguments");
2432     } else {                                     // Has arguments?
2433       // Loop through FunctionType's arguments and ensure they are specified
2434       // correctly!
2435       FunctionType::param_iterator I = Ty->param_begin();
2436       FunctionType::param_iterator E = Ty->param_end();
2437       ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2438
2439       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2440         if (ArgI->Val->getType() != *I)
2441           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2442                          (*I)->getDescription() + "'");
2443         Args.push_back(ArgI->Val);
2444       }
2445
2446       if (Ty->isVarArg()) {
2447         if (I == E)
2448           for (; ArgI != ArgE; ++ArgI)
2449             Args.push_back(ArgI->Val); // push the remaining varargs
2450       } else if (I != E || ArgI != ArgE)
2451         GEN_ERROR("Invalid number of parameters detected");
2452     }
2453
2454     // Create the InvokeInst
2455     InvokeInst *II = new InvokeInst(V, Normal, Except, Args);
2456     II->setCallingConv($2);
2457     $$ = II;
2458     delete $6;
2459     CHECK_FOR_ERROR
2460   }
2461   | UNWIND {
2462     $$ = new UnwindInst();
2463     CHECK_FOR_ERROR
2464   }
2465   | UNREACHABLE {
2466     $$ = new UnreachableInst();
2467     CHECK_FOR_ERROR
2468   };
2469
2470
2471
2472 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2473     $$ = $1;
2474     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2475     CHECK_FOR_ERROR
2476     if (V == 0)
2477       GEN_ERROR("May only switch on a constant pool value");
2478
2479     BasicBlock* tmpBB = getBBVal($6);
2480     CHECK_FOR_ERROR
2481     $$->push_back(std::make_pair(V, tmpBB));
2482   }
2483   | IntType ConstValueRef ',' LABEL ValueRef {
2484     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2485     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2486     CHECK_FOR_ERROR
2487
2488     if (V == 0)
2489       GEN_ERROR("May only switch on a constant pool value");
2490
2491     BasicBlock* tmpBB = getBBVal($5);
2492     CHECK_FOR_ERROR
2493     $$->push_back(std::make_pair(V, tmpBB)); 
2494   };
2495
2496 Inst : OptLocalAssign InstVal {
2497   // Is this definition named?? if so, assign the name...
2498   setValueName($2, $1);
2499   CHECK_FOR_ERROR
2500   InsertValue($2);
2501   $$ = $2;
2502   CHECK_FOR_ERROR
2503 };
2504
2505 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
2506     if (!UpRefs.empty())
2507       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2508     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2509     Value* tmpVal = getVal(*$1, $3);
2510     CHECK_FOR_ERROR
2511     BasicBlock* tmpBB = getBBVal($5);
2512     CHECK_FOR_ERROR
2513     $$->push_back(std::make_pair(tmpVal, tmpBB));
2514     delete $1;
2515   }
2516   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2517     $$ = $1;
2518     Value* tmpVal = getVal($1->front().first->getType(), $4);
2519     CHECK_FOR_ERROR
2520     BasicBlock* tmpBB = getBBVal($6);
2521     CHECK_FOR_ERROR
2522     $1->push_back(std::make_pair(tmpVal, tmpBB));
2523   };
2524
2525
2526 ValueRefList : Types ValueRef OptParamAttrs {    
2527     if (!UpRefs.empty())
2528       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2529     // Used for call and invoke instructions
2530     $$ = new ValueRefList();
2531     ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2532     $$->push_back(E);
2533   }
2534   | ValueRefList ',' Types ValueRef OptParamAttrs {
2535     if (!UpRefs.empty())
2536       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2537     $$ = $1;
2538     ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2539     $$->push_back(E);
2540     CHECK_FOR_ERROR
2541   }
2542   | /*empty*/ { $$ = new ValueRefList(); };
2543
2544 IndexList       // Used for gep instructions and constant expressions
2545   : /*empty*/ { $$ = new std::vector<Value*>(); }
2546   | IndexList ',' ResolvedVal {
2547     $$ = $1;
2548     $$->push_back($3);
2549     CHECK_FOR_ERROR
2550   }
2551   ;
2552
2553 OptTailCall : TAIL CALL {
2554     $$ = true;
2555     CHECK_FOR_ERROR
2556   }
2557   | CALL {
2558     $$ = false;
2559     CHECK_FOR_ERROR
2560   };
2561
2562 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2563     if (!UpRefs.empty())
2564       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2565     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() && 
2566         !isa<PackedType>((*$2).get()))
2567       GEN_ERROR(
2568         "Arithmetic operator requires integer, FP, or packed operands");
2569     if (isa<PackedType>((*$2).get()) && 
2570         ($1 == Instruction::URem || 
2571          $1 == Instruction::SRem ||
2572          $1 == Instruction::FRem))
2573       GEN_ERROR("U/S/FRem not supported on packed types");
2574     Value* val1 = getVal(*$2, $3); 
2575     CHECK_FOR_ERROR
2576     Value* val2 = getVal(*$2, $5);
2577     CHECK_FOR_ERROR
2578     $$ = BinaryOperator::create($1, val1, val2);
2579     if ($$ == 0)
2580       GEN_ERROR("binary operator returned null");
2581     delete $2;
2582   }
2583   | LogicalOps Types ValueRef ',' ValueRef {
2584     if (!UpRefs.empty())
2585       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2586     if (!(*$2)->isInteger()) {
2587       if (Instruction::isShift($1) || !isa<PackedType>($2->get()) ||
2588           !cast<PackedType>($2->get())->getElementType()->isInteger())
2589         GEN_ERROR("Logical operator requires integral operands");
2590     }
2591     Value* tmpVal1 = getVal(*$2, $3);
2592     CHECK_FOR_ERROR
2593     Value* tmpVal2 = getVal(*$2, $5);
2594     CHECK_FOR_ERROR
2595     $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2596     if ($$ == 0)
2597       GEN_ERROR("binary operator returned null");
2598     delete $2;
2599   }
2600   | ICMP IPredicates Types ValueRef ',' ValueRef  {
2601     if (!UpRefs.empty())
2602       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2603     if (isa<PackedType>((*$3).get()))
2604       GEN_ERROR("Packed types not supported by icmp instruction");
2605     Value* tmpVal1 = getVal(*$3, $4);
2606     CHECK_FOR_ERROR
2607     Value* tmpVal2 = getVal(*$3, $6);
2608     CHECK_FOR_ERROR
2609     $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2610     if ($$ == 0)
2611       GEN_ERROR("icmp operator returned null");
2612   }
2613   | FCMP FPredicates Types ValueRef ',' ValueRef  {
2614     if (!UpRefs.empty())
2615       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2616     if (isa<PackedType>((*$3).get()))
2617       GEN_ERROR("Packed types not supported by fcmp instruction");
2618     Value* tmpVal1 = getVal(*$3, $4);
2619     CHECK_FOR_ERROR
2620     Value* tmpVal2 = getVal(*$3, $6);
2621     CHECK_FOR_ERROR
2622     $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2623     if ($$ == 0)
2624       GEN_ERROR("fcmp operator returned null");
2625   }
2626   | CastOps ResolvedVal TO Types {
2627     if (!UpRefs.empty())
2628       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2629     Value* Val = $2;
2630     const Type* DestTy = $4->get();
2631     if (!CastInst::castIsValid($1, Val, DestTy))
2632       GEN_ERROR("invalid cast opcode for cast from '" +
2633                 Val->getType()->getDescription() + "' to '" +
2634                 DestTy->getDescription() + "'"); 
2635     $$ = CastInst::create($1, Val, DestTy);
2636     delete $4;
2637   }
2638   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2639     if ($2->getType() != Type::Int1Ty)
2640       GEN_ERROR("select condition must be boolean");
2641     if ($4->getType() != $6->getType())
2642       GEN_ERROR("select value types should match");
2643     $$ = new SelectInst($2, $4, $6);
2644     CHECK_FOR_ERROR
2645   }
2646   | VAARG ResolvedVal ',' Types {
2647     if (!UpRefs.empty())
2648       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2649     $$ = new VAArgInst($2, *$4);
2650     delete $4;
2651     CHECK_FOR_ERROR
2652   }
2653   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2654     if (!ExtractElementInst::isValidOperands($2, $4))
2655       GEN_ERROR("Invalid extractelement operands");
2656     $$ = new ExtractElementInst($2, $4);
2657     CHECK_FOR_ERROR
2658   }
2659   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2660     if (!InsertElementInst::isValidOperands($2, $4, $6))
2661       GEN_ERROR("Invalid insertelement operands");
2662     $$ = new InsertElementInst($2, $4, $6);
2663     CHECK_FOR_ERROR
2664   }
2665   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2666     if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2667       GEN_ERROR("Invalid shufflevector operands");
2668     $$ = new ShuffleVectorInst($2, $4, $6);
2669     CHECK_FOR_ERROR
2670   }
2671   | PHI_TOK PHIList {
2672     const Type *Ty = $2->front().first->getType();
2673     if (!Ty->isFirstClassType())
2674       GEN_ERROR("PHI node operands must be of first class type");
2675     $$ = new PHINode(Ty);
2676     ((PHINode*)$$)->reserveOperandSpace($2->size());
2677     while ($2->begin() != $2->end()) {
2678       if ($2->front().first->getType() != Ty) 
2679         GEN_ERROR("All elements of a PHI node must be of the same type");
2680       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2681       $2->pop_front();
2682     }
2683     delete $2;  // Free the list...
2684     CHECK_FOR_ERROR
2685   }
2686   | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' 
2687     OptFuncAttrs {
2688
2689     // Handle the short syntax
2690     const PointerType *PFTy = 0;
2691     const FunctionType *Ty = 0;
2692     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2693         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2694       // Pull out the types of all of the arguments...
2695       std::vector<const Type*> ParamTypes;
2696       FunctionType::ParamAttrsList ParamAttrs;
2697       ParamAttrs.push_back($8);
2698       for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2699         const Type *Ty = I->Val->getType();
2700         if (Ty == Type::VoidTy)
2701           GEN_ERROR("Short call syntax cannot be used with varargs");
2702         ParamTypes.push_back(Ty);
2703         ParamAttrs.push_back(I->Attrs);
2704       }
2705
2706       Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2707       PFTy = PointerType::get(Ty);
2708     }
2709
2710     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2711     CHECK_FOR_ERROR
2712
2713     // Check the arguments 
2714     ValueList Args;
2715     if ($6->empty()) {                                   // Has no arguments?
2716       // Make sure no arguments is a good thing!
2717       if (Ty->getNumParams() != 0)
2718         GEN_ERROR("No arguments passed to a function that "
2719                        "expects arguments");
2720     } else {                                     // Has arguments?
2721       // Loop through FunctionType's arguments and ensure they are specified
2722       // correctly!
2723       //
2724       FunctionType::param_iterator I = Ty->param_begin();
2725       FunctionType::param_iterator E = Ty->param_end();
2726       ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2727
2728       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2729         if (ArgI->Val->getType() != *I)
2730           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2731                          (*I)->getDescription() + "'");
2732         Args.push_back(ArgI->Val);
2733       }
2734       if (Ty->isVarArg()) {
2735         if (I == E)
2736           for (; ArgI != ArgE; ++ArgI)
2737             Args.push_back(ArgI->Val); // push the remaining varargs
2738       } else if (I != E || ArgI != ArgE)
2739         GEN_ERROR("Invalid number of parameters detected");
2740     }
2741     // Create the call node
2742     CallInst *CI = new CallInst(V, Args);
2743     CI->setTailCall($1);
2744     CI->setCallingConv($2);
2745     $$ = CI;
2746     delete $6;
2747     delete $3;
2748     CHECK_FOR_ERROR
2749   }
2750   | MemoryInst {
2751     $$ = $1;
2752     CHECK_FOR_ERROR
2753   };
2754
2755 OptVolatile : VOLATILE {
2756     $$ = true;
2757     CHECK_FOR_ERROR
2758   }
2759   | /* empty */ {
2760     $$ = false;
2761     CHECK_FOR_ERROR
2762   };
2763
2764
2765
2766 MemoryInst : MALLOC Types OptCAlign {
2767     if (!UpRefs.empty())
2768       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2769     $$ = new MallocInst(*$2, 0, $3);
2770     delete $2;
2771     CHECK_FOR_ERROR
2772   }
2773   | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2774     if (!UpRefs.empty())
2775       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2776     Value* tmpVal = getVal($4, $5);
2777     CHECK_FOR_ERROR
2778     $$ = new MallocInst(*$2, tmpVal, $6);
2779     delete $2;
2780   }
2781   | ALLOCA Types OptCAlign {
2782     if (!UpRefs.empty())
2783       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2784     $$ = new AllocaInst(*$2, 0, $3);
2785     delete $2;
2786     CHECK_FOR_ERROR
2787   }
2788   | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
2789     if (!UpRefs.empty())
2790       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2791     Value* tmpVal = getVal($4, $5);
2792     CHECK_FOR_ERROR
2793     $$ = new AllocaInst(*$2, tmpVal, $6);
2794     delete $2;
2795   }
2796   | FREE ResolvedVal {
2797     if (!isa<PointerType>($2->getType()))
2798       GEN_ERROR("Trying to free nonpointer type " + 
2799                      $2->getType()->getDescription() + "");
2800     $$ = new FreeInst($2);
2801     CHECK_FOR_ERROR
2802   }
2803
2804   | OptVolatile LOAD Types ValueRef {
2805     if (!UpRefs.empty())
2806       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2807     if (!isa<PointerType>($3->get()))
2808       GEN_ERROR("Can't load from nonpointer type: " +
2809                      (*$3)->getDescription());
2810     if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2811       GEN_ERROR("Can't load from pointer of non-first-class type: " +
2812                      (*$3)->getDescription());
2813     Value* tmpVal = getVal(*$3, $4);
2814     CHECK_FOR_ERROR
2815     $$ = new LoadInst(tmpVal, "", $1);
2816     delete $3;
2817   }
2818   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2819     if (!UpRefs.empty())
2820       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2821     const PointerType *PT = dyn_cast<PointerType>($5->get());
2822     if (!PT)
2823       GEN_ERROR("Can't store to a nonpointer type: " +
2824                      (*$5)->getDescription());
2825     const Type *ElTy = PT->getElementType();
2826     if (ElTy != $3->getType())
2827       GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2828                      "' into space of type '" + ElTy->getDescription() + "'");
2829
2830     Value* tmpVal = getVal(*$5, $6);
2831     CHECK_FOR_ERROR
2832     $$ = new StoreInst($3, tmpVal, $1);
2833     delete $5;
2834   }
2835   | GETELEMENTPTR Types ValueRef IndexList {
2836     if (!UpRefs.empty())
2837       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2838     if (!isa<PointerType>($2->get()))
2839       GEN_ERROR("getelementptr insn requires pointer operand");
2840
2841     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2842       GEN_ERROR("Invalid getelementptr indices for type '" +
2843                      (*$2)->getDescription()+ "'");
2844     Value* tmpVal = getVal(*$2, $3);
2845     CHECK_FOR_ERROR
2846     $$ = new GetElementPtrInst(tmpVal, *$4);
2847     delete $2; 
2848     delete $4;
2849   };
2850
2851
2852 %%
2853
2854 // common code from the two 'RunVMAsmParser' functions
2855 static Module* RunParser(Module * M) {
2856
2857   llvmAsmlineno = 1;      // Reset the current line number...
2858   CurModule.CurrentModule = M;
2859 #if YYDEBUG
2860   yydebug = Debug;
2861 #endif
2862
2863   // Check to make sure the parser succeeded
2864   if (yyparse()) {
2865     if (ParserResult)
2866       delete ParserResult;
2867     return 0;
2868   }
2869
2870   // Check to make sure that parsing produced a result
2871   if (!ParserResult)
2872     return 0;
2873
2874   // Reset ParserResult variable while saving its value for the result.
2875   Module *Result = ParserResult;
2876   ParserResult = 0;
2877
2878   return Result;
2879 }
2880
2881 void llvm::GenerateError(const std::string &message, int LineNo) {
2882   if (LineNo == -1) LineNo = llvmAsmlineno;
2883   // TODO: column number in exception
2884   if (TheParseError)
2885     TheParseError->setError(CurFilename, message, LineNo);
2886   TriggerError = 1;
2887 }
2888
2889 int yyerror(const char *ErrorMsg) {
2890   std::string where 
2891     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2892                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2893   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2894   if (yychar == YYEMPTY || yychar == 0)
2895     errMsg += "end-of-file.";
2896   else
2897     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2898   GenerateError(errMsg);
2899   return 0;
2900 }