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