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