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