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