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