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