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