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
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               | SIGNEXT { $$ = ParamAttr::SExt;      }
1229               | INREG   { $$ = ParamAttr::InReg;     }
1230               | SRET    { $$ = ParamAttr::StructRet; }
1231               | NOALIAS { $$ = ParamAttr::NoAlias;   }
1232               | BYVAL   { $$ = ParamAttr::ByVal;   }
1233               ;
1234
1235 OptParamAttrs : /* empty */  { $$ = ParamAttr::None; }
1236               | OptParamAttrs ParamAttr {
1237                 $$ = $1 | $2;
1238               }
1239               ;
1240
1241 FuncAttr      : NORETURN { $$ = ParamAttr::NoReturn; }
1242               | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1243               | ZEROEXT  { $$ = ParamAttr::ZExt;     }
1244               | SIGNEXT  { $$ = ParamAttr::SExt;     }
1245               ;
1246
1247 OptFuncAttrs  : /* empty */ { $$ = ParamAttr::None; }
1248               | OptFuncAttrs FuncAttr {
1249                 $$ = $1 | $2;
1250               }
1251               ;
1252
1253 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1254 // a comma before it.
1255 OptAlign : /*empty*/        { $$ = 0; } |
1256            ALIGN EUINT64VAL {
1257   $$ = $2;
1258   if ($$ != 0 && !isPowerOf2_32($$))
1259     GEN_ERROR("Alignment must be a power of two");
1260   CHECK_FOR_ERROR
1261 };
1262 OptCAlign : /*empty*/            { $$ = 0; } |
1263             ',' ALIGN EUINT64VAL {
1264   $$ = $3;
1265   if ($$ != 0 && !isPowerOf2_32($$))
1266     GEN_ERROR("Alignment must be a power of two");
1267   CHECK_FOR_ERROR
1268 };
1269
1270
1271 SectionString : SECTION STRINGCONSTANT {
1272   for (unsigned i = 0, e = $2->length(); i != e; ++i)
1273     if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1274       GEN_ERROR("Invalid character in section name");
1275   $$ = $2;
1276   CHECK_FOR_ERROR
1277 };
1278
1279 OptSection : /*empty*/ { $$ = 0; } |
1280              SectionString { $$ = $1; };
1281
1282 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1283 // is set to be the global we are processing.
1284 //
1285 GlobalVarAttributes : /* empty */ {} |
1286                      ',' GlobalVarAttribute GlobalVarAttributes {};
1287 GlobalVarAttribute : SectionString {
1288     CurGV->setSection(*$1);
1289     delete $1;
1290     CHECK_FOR_ERROR
1291   } 
1292   | ALIGN EUINT64VAL {
1293     if ($2 != 0 && !isPowerOf2_32($2))
1294       GEN_ERROR("Alignment must be a power of two");
1295     CurGV->setAlignment($2);
1296     CHECK_FOR_ERROR
1297   };
1298
1299 //===----------------------------------------------------------------------===//
1300 // Types includes all predefined types... except void, because it can only be
1301 // used in specific contexts (function returning void for example).  
1302
1303 // Derived types are added later...
1304 //
1305 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1306
1307 Types 
1308   : OPAQUE {
1309     $$ = new PATypeHolder(OpaqueType::get());
1310     CHECK_FOR_ERROR
1311   }
1312   | PrimType {
1313     $$ = new PATypeHolder($1);
1314     CHECK_FOR_ERROR
1315   }
1316   | Types '*' {                             // Pointer type?
1317     if (*$1 == Type::LabelTy)
1318       GEN_ERROR("Cannot form a pointer to a basic block");
1319     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1320     delete $1;
1321     CHECK_FOR_ERROR
1322   }
1323   | SymbolicValueRef {            // Named types are also simple types...
1324     const Type* tmp = getTypeVal($1);
1325     CHECK_FOR_ERROR
1326     $$ = new PATypeHolder(tmp);
1327   }
1328   | '\\' EUINT64VAL {                   // Type UpReference
1329     if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1330     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1331     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1332     $$ = new PATypeHolder(OT);
1333     UR_OUT("New Upreference!\n");
1334     CHECK_FOR_ERROR
1335   }
1336   | Types '(' ArgTypeListI ')' OptFuncAttrs {
1337     std::vector<const Type*> Params;
1338     ParamAttrsVector Attrs;
1339     if ($5 != ParamAttr::None) {
1340       ParamAttrsWithIndex X; X.index = 0; X.attrs = $5;
1341       Attrs.push_back(X);
1342     }
1343     unsigned index = 1;
1344     TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1345     for (; I != E; ++I, ++index) {
1346       const Type *Ty = I->Ty->get();
1347       Params.push_back(Ty);
1348       if (Ty != Type::VoidTy)
1349         if (I->Attrs != ParamAttr::None) {
1350           ParamAttrsWithIndex X; X.index = index; X.attrs = I->Attrs;
1351           Attrs.push_back(X);
1352         }
1353     }
1354     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1355     if (isVarArg) Params.pop_back();
1356
1357     ParamAttrsList *ActualAttrs = 0;
1358     if (!Attrs.empty())
1359       ActualAttrs = ParamAttrsList::get(Attrs);
1360     FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, ActualAttrs);
1361     delete $3;   // Delete the argument list
1362     delete $1;   // Delete the return type handle
1363     $$ = new PATypeHolder(HandleUpRefs(FT)); 
1364     CHECK_FOR_ERROR
1365   }
1366   | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1367     std::vector<const Type*> Params;
1368     ParamAttrsVector Attrs;
1369     if ($5 != ParamAttr::None) {
1370       ParamAttrsWithIndex X; X.index = 0; X.attrs = $5;
1371       Attrs.push_back(X);
1372     }
1373     TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1374     unsigned index = 1;
1375     for ( ; I != E; ++I, ++index) {
1376       const Type* Ty = I->Ty->get();
1377       Params.push_back(Ty);
1378       if (Ty != Type::VoidTy)
1379         if (I->Attrs != ParamAttr::None) {
1380           ParamAttrsWithIndex X; X.index = index; X.attrs = I->Attrs;
1381           Attrs.push_back(X);
1382         }
1383     }
1384     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1385     if (isVarArg) Params.pop_back();
1386
1387     ParamAttrsList *ActualAttrs = 0;
1388     if (!Attrs.empty())
1389       ActualAttrs = ParamAttrsList::get(Attrs);
1390
1391     FunctionType *FT = FunctionType::get($1, Params, isVarArg, ActualAttrs);
1392     delete $3;      // Delete the argument list
1393     $$ = new PATypeHolder(HandleUpRefs(FT)); 
1394     CHECK_FOR_ERROR
1395   }
1396
1397   | '[' EUINT64VAL 'x' Types ']' {          // Sized array type?
1398     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1399     delete $4;
1400     CHECK_FOR_ERROR
1401   }
1402   | '<' EUINT64VAL 'x' Types '>' {          // Vector type?
1403      const llvm::Type* ElemTy = $4->get();
1404      if ((unsigned)$2 != $2)
1405         GEN_ERROR("Unsigned result not equal to signed result");
1406      if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1407         GEN_ERROR("Element type of a VectorType must be primitive");
1408      if (!isPowerOf2_32($2))
1409        GEN_ERROR("Vector length should be a power of 2");
1410      $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1411      delete $4;
1412      CHECK_FOR_ERROR
1413   }
1414   | '{' TypeListI '}' {                        // Structure type?
1415     std::vector<const Type*> Elements;
1416     for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1417            E = $2->end(); I != E; ++I)
1418       Elements.push_back(*I);
1419
1420     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1421     delete $2;
1422     CHECK_FOR_ERROR
1423   }
1424   | '{' '}' {                                  // Empty structure type?
1425     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1426     CHECK_FOR_ERROR
1427   }
1428   | '<' '{' TypeListI '}' '>' {
1429     std::vector<const Type*> Elements;
1430     for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1431            E = $3->end(); I != E; ++I)
1432       Elements.push_back(*I);
1433
1434     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1435     delete $3;
1436     CHECK_FOR_ERROR
1437   }
1438   | '<' '{' '}' '>' {                         // Empty structure type?
1439     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1440     CHECK_FOR_ERROR
1441   }
1442   ;
1443
1444 ArgType 
1445   : Types OptParamAttrs { 
1446     $$.Ty = $1; 
1447     $$.Attrs = $2; 
1448   }
1449   ;
1450
1451 ResultTypes
1452   : Types {
1453     if (!UpRefs.empty())
1454       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1455     if (!(*$1)->isFirstClassType())
1456       GEN_ERROR("LLVM functions cannot return aggregate types");
1457     $$ = $1;
1458   }
1459   | VOID {
1460     $$ = new PATypeHolder(Type::VoidTy);
1461   }
1462   ;
1463
1464 ArgTypeList : ArgType {
1465     $$ = new TypeWithAttrsList();
1466     $$->push_back($1);
1467     CHECK_FOR_ERROR
1468   }
1469   | ArgTypeList ',' ArgType {
1470     ($$=$1)->push_back($3);
1471     CHECK_FOR_ERROR
1472   }
1473   ;
1474
1475 ArgTypeListI 
1476   : ArgTypeList
1477   | ArgTypeList ',' DOTDOTDOT {
1478     $$=$1;
1479     TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1480     TWA.Ty = new PATypeHolder(Type::VoidTy);
1481     $$->push_back(TWA);
1482     CHECK_FOR_ERROR
1483   }
1484   | DOTDOTDOT {
1485     $$ = new TypeWithAttrsList;
1486     TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1487     TWA.Ty = new PATypeHolder(Type::VoidTy);
1488     $$->push_back(TWA);
1489     CHECK_FOR_ERROR
1490   }
1491   | /*empty*/ {
1492     $$ = new TypeWithAttrsList();
1493     CHECK_FOR_ERROR
1494   };
1495
1496 // TypeList - Used for struct declarations and as a basis for function type 
1497 // declaration type lists
1498 //
1499 TypeListI : Types {
1500     $$ = new std::list<PATypeHolder>();
1501     $$->push_back(*$1); 
1502     delete $1;
1503     CHECK_FOR_ERROR
1504   }
1505   | TypeListI ',' Types {
1506     ($$=$1)->push_back(*$3); 
1507     delete $3;
1508     CHECK_FOR_ERROR
1509   };
1510
1511 // ConstVal - The various declarations that go into the constant pool.  This
1512 // production is used ONLY to represent constants that show up AFTER a 'const',
1513 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1514 // into other expressions (such as integers and constexprs) are handled by the
1515 // ResolvedVal, ValueRef and ConstValueRef productions.
1516 //
1517 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1518     if (!UpRefs.empty())
1519       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1520     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1521     if (ATy == 0)
1522       GEN_ERROR("Cannot make array constant with type: '" + 
1523                      (*$1)->getDescription() + "'");
1524     const Type *ETy = ATy->getElementType();
1525     int NumElements = ATy->getNumElements();
1526
1527     // Verify that we have the correct size...
1528     if (NumElements != -1 && NumElements != (int)$3->size())
1529       GEN_ERROR("Type mismatch: constant sized array initialized with " +
1530                      utostr($3->size()) +  " arguments, but has size of " + 
1531                      itostr(NumElements) + "");
1532
1533     // Verify all elements are correct type!
1534     for (unsigned i = 0; i < $3->size(); i++) {
1535       if (ETy != (*$3)[i]->getType())
1536         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1537                        ETy->getDescription() +"' as required!\nIt is of type '"+
1538                        (*$3)[i]->getType()->getDescription() + "'.");
1539     }
1540
1541     $$ = ConstantArray::get(ATy, *$3);
1542     delete $1; delete $3;
1543     CHECK_FOR_ERROR
1544   }
1545   | Types '[' ']' {
1546     if (!UpRefs.empty())
1547       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1548     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1549     if (ATy == 0)
1550       GEN_ERROR("Cannot make array constant with type: '" + 
1551                      (*$1)->getDescription() + "'");
1552
1553     int NumElements = ATy->getNumElements();
1554     if (NumElements != -1 && NumElements != 0) 
1555       GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1556                      " arguments, but has size of " + itostr(NumElements) +"");
1557     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1558     delete $1;
1559     CHECK_FOR_ERROR
1560   }
1561   | Types 'c' STRINGCONSTANT {
1562     if (!UpRefs.empty())
1563       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1564     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1565     if (ATy == 0)
1566       GEN_ERROR("Cannot make array constant with type: '" + 
1567                      (*$1)->getDescription() + "'");
1568
1569     int NumElements = ATy->getNumElements();
1570     const Type *ETy = ATy->getElementType();
1571     if (NumElements != -1 && NumElements != int($3->length()))
1572       GEN_ERROR("Can't build string constant of size " + 
1573                      itostr((int)($3->length())) +
1574                      " when array has size " + itostr(NumElements) + "");
1575     std::vector<Constant*> Vals;
1576     if (ETy == Type::Int8Ty) {
1577       for (unsigned i = 0; i < $3->length(); ++i)
1578         Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1579     } else {
1580       delete $3;
1581       GEN_ERROR("Cannot build string arrays of non byte sized elements");
1582     }
1583     delete $3;
1584     $$ = ConstantArray::get(ATy, Vals);
1585     delete $1;
1586     CHECK_FOR_ERROR
1587   }
1588   | Types '<' ConstVector '>' { // Nonempty unsized arr
1589     if (!UpRefs.empty())
1590       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1591     const VectorType *PTy = dyn_cast<VectorType>($1->get());
1592     if (PTy == 0)
1593       GEN_ERROR("Cannot make packed constant with type: '" + 
1594                      (*$1)->getDescription() + "'");
1595     const Type *ETy = PTy->getElementType();
1596     int NumElements = PTy->getNumElements();
1597
1598     // Verify that we have the correct size...
1599     if (NumElements != -1 && NumElements != (int)$3->size())
1600       GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1601                      utostr($3->size()) +  " arguments, but has size of " + 
1602                      itostr(NumElements) + "");
1603
1604     // Verify all elements are correct type!
1605     for (unsigned i = 0; i < $3->size(); i++) {
1606       if (ETy != (*$3)[i]->getType())
1607         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1608            ETy->getDescription() +"' as required!\nIt is of type '"+
1609            (*$3)[i]->getType()->getDescription() + "'.");
1610     }
1611
1612     $$ = ConstantVector::get(PTy, *$3);
1613     delete $1; delete $3;
1614     CHECK_FOR_ERROR
1615   }
1616   | Types '{' ConstVector '}' {
1617     const StructType *STy = dyn_cast<StructType>($1->get());
1618     if (STy == 0)
1619       GEN_ERROR("Cannot make struct constant with type: '" + 
1620                      (*$1)->getDescription() + "'");
1621
1622     if ($3->size() != STy->getNumContainedTypes())
1623       GEN_ERROR("Illegal number of initializers for structure type");
1624
1625     // Check to ensure that constants are compatible with the type initializer!
1626     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1627       if ((*$3)[i]->getType() != STy->getElementType(i))
1628         GEN_ERROR("Expected type '" +
1629                        STy->getElementType(i)->getDescription() +
1630                        "' for element #" + utostr(i) +
1631                        " of structure initializer");
1632
1633     // Check to ensure that Type is not packed
1634     if (STy->isPacked())
1635       GEN_ERROR("Unpacked Initializer to vector type '" +
1636                 STy->getDescription() + "'");
1637
1638     $$ = ConstantStruct::get(STy, *$3);
1639     delete $1; delete $3;
1640     CHECK_FOR_ERROR
1641   }
1642   | Types '{' '}' {
1643     if (!UpRefs.empty())
1644       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1645     const StructType *STy = dyn_cast<StructType>($1->get());
1646     if (STy == 0)
1647       GEN_ERROR("Cannot make struct constant with type: '" + 
1648                      (*$1)->getDescription() + "'");
1649
1650     if (STy->getNumContainedTypes() != 0)
1651       GEN_ERROR("Illegal number of initializers for structure type");
1652
1653     // Check to ensure that Type is not packed
1654     if (STy->isPacked())
1655       GEN_ERROR("Unpacked Initializer to vector type '" +
1656                 STy->getDescription() + "'");
1657
1658     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1659     delete $1;
1660     CHECK_FOR_ERROR
1661   }
1662   | Types '<' '{' ConstVector '}' '>' {
1663     const StructType *STy = dyn_cast<StructType>($1->get());
1664     if (STy == 0)
1665       GEN_ERROR("Cannot make struct constant with type: '" + 
1666                      (*$1)->getDescription() + "'");
1667
1668     if ($4->size() != STy->getNumContainedTypes())
1669       GEN_ERROR("Illegal number of initializers for structure type");
1670
1671     // Check to ensure that constants are compatible with the type initializer!
1672     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1673       if ((*$4)[i]->getType() != STy->getElementType(i))
1674         GEN_ERROR("Expected type '" +
1675                        STy->getElementType(i)->getDescription() +
1676                        "' for element #" + utostr(i) +
1677                        " of structure initializer");
1678
1679     // Check to ensure that Type is packed
1680     if (!STy->isPacked())
1681       GEN_ERROR("Vector initializer to non-vector type '" + 
1682                 STy->getDescription() + "'");
1683
1684     $$ = ConstantStruct::get(STy, *$4);
1685     delete $1; delete $4;
1686     CHECK_FOR_ERROR
1687   }
1688   | Types '<' '{' '}' '>' {
1689     if (!UpRefs.empty())
1690       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1691     const StructType *STy = dyn_cast<StructType>($1->get());
1692     if (STy == 0)
1693       GEN_ERROR("Cannot make struct constant with type: '" + 
1694                      (*$1)->getDescription() + "'");
1695
1696     if (STy->getNumContainedTypes() != 0)
1697       GEN_ERROR("Illegal number of initializers for structure type");
1698
1699     // Check to ensure that Type is packed
1700     if (!STy->isPacked())
1701       GEN_ERROR("Vector initializer to non-vector type '" + 
1702                 STy->getDescription() + "'");
1703
1704     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1705     delete $1;
1706     CHECK_FOR_ERROR
1707   }
1708   | Types NULL_TOK {
1709     if (!UpRefs.empty())
1710       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1711     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1712     if (PTy == 0)
1713       GEN_ERROR("Cannot make null pointer constant with type: '" + 
1714                      (*$1)->getDescription() + "'");
1715
1716     $$ = ConstantPointerNull::get(PTy);
1717     delete $1;
1718     CHECK_FOR_ERROR
1719   }
1720   | Types UNDEF {
1721     if (!UpRefs.empty())
1722       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1723     $$ = UndefValue::get($1->get());
1724     delete $1;
1725     CHECK_FOR_ERROR
1726   }
1727   | Types SymbolicValueRef {
1728     if (!UpRefs.empty())
1729       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1730     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1731     if (Ty == 0)
1732       GEN_ERROR("Global const reference must be a pointer type");
1733
1734     // ConstExprs can exist in the body of a function, thus creating
1735     // GlobalValues whenever they refer to a variable.  Because we are in
1736     // the context of a function, getExistingVal will search the functions
1737     // symbol table instead of the module symbol table for the global symbol,
1738     // which throws things all off.  To get around this, we just tell
1739     // getExistingVal that we are at global scope here.
1740     //
1741     Function *SavedCurFn = CurFun.CurrentFunction;
1742     CurFun.CurrentFunction = 0;
1743
1744     Value *V = getExistingVal(Ty, $2);
1745     CHECK_FOR_ERROR
1746
1747     CurFun.CurrentFunction = SavedCurFn;
1748
1749     // If this is an initializer for a constant pointer, which is referencing a
1750     // (currently) undefined variable, create a stub now that shall be replaced
1751     // in the future with the right type of variable.
1752     //
1753     if (V == 0) {
1754       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1755       const PointerType *PT = cast<PointerType>(Ty);
1756
1757       // First check to see if the forward references value is already created!
1758       PerModuleInfo::GlobalRefsType::iterator I =
1759         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1760     
1761       if (I != CurModule.GlobalRefs.end()) {
1762         V = I->second;             // Placeholder already exists, use it...
1763         $2.destroy();
1764       } else {
1765         std::string Name;
1766         if ($2.Type == ValID::GlobalName)
1767           Name = $2.getName();
1768         else if ($2.Type != ValID::GlobalID)
1769           GEN_ERROR("Invalid reference to global");
1770
1771         // Create the forward referenced global.
1772         GlobalValue *GV;
1773         if (const FunctionType *FTy = 
1774                  dyn_cast<FunctionType>(PT->getElementType())) {
1775           GV = new Function(FTy, GlobalValue::ExternalWeakLinkage, Name,
1776                             CurModule.CurrentModule);
1777         } else {
1778           GV = new GlobalVariable(PT->getElementType(), false,
1779                                   GlobalValue::ExternalWeakLinkage, 0,
1780                                   Name, CurModule.CurrentModule);
1781         }
1782
1783         // Keep track of the fact that we have a forward ref to recycle it
1784         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1785         V = GV;
1786       }
1787     }
1788
1789     $$ = cast<GlobalValue>(V);
1790     delete $1;            // Free the type handle
1791     CHECK_FOR_ERROR
1792   }
1793   | Types ConstExpr {
1794     if (!UpRefs.empty())
1795       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1796     if ($1->get() != $2->getType())
1797       GEN_ERROR("Mismatched types for constant expression: " + 
1798         (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1799     $$ = $2;
1800     delete $1;
1801     CHECK_FOR_ERROR
1802   }
1803   | Types ZEROINITIALIZER {
1804     if (!UpRefs.empty())
1805       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1806     const Type *Ty = $1->get();
1807     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1808       GEN_ERROR("Cannot create a null initialized value of this type");
1809     $$ = Constant::getNullValue(Ty);
1810     delete $1;
1811     CHECK_FOR_ERROR
1812   }
1813   | IntType ESINT64VAL {      // integral constants
1814     if (!ConstantInt::isValueValidForType($1, $2))
1815       GEN_ERROR("Constant value doesn't fit in type");
1816     $$ = ConstantInt::get($1, $2, true);
1817     CHECK_FOR_ERROR
1818   }
1819   | IntType ESAPINTVAL {      // arbitrary precision integer constants
1820     uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1821     if ($2->getBitWidth() > BitWidth) {
1822       GEN_ERROR("Constant value does not fit in type");
1823     }
1824     $2->sextOrTrunc(BitWidth);
1825     $$ = ConstantInt::get(*$2);
1826     delete $2;
1827     CHECK_FOR_ERROR
1828   }
1829   | IntType EUINT64VAL {      // integral constants
1830     if (!ConstantInt::isValueValidForType($1, $2))
1831       GEN_ERROR("Constant value doesn't fit in type");
1832     $$ = ConstantInt::get($1, $2, false);
1833     CHECK_FOR_ERROR
1834   }
1835   | IntType EUAPINTVAL {      // arbitrary precision integer constants
1836     uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1837     if ($2->getBitWidth() > BitWidth) {
1838       GEN_ERROR("Constant value does not fit in type");
1839     } 
1840     $2->zextOrTrunc(BitWidth);
1841     $$ = ConstantInt::get(*$2);
1842     delete $2;
1843     CHECK_FOR_ERROR
1844   }
1845   | INTTYPE TRUETOK {                      // Boolean constants
1846     assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1847     $$ = ConstantInt::getTrue();
1848     CHECK_FOR_ERROR
1849   }
1850   | INTTYPE FALSETOK {                     // Boolean constants
1851     assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1852     $$ = ConstantInt::getFalse();
1853     CHECK_FOR_ERROR
1854   }
1855   | FPType FPVAL {                   // Float & Double constants
1856     if (!ConstantFP::isValueValidForType($1, $2))
1857       GEN_ERROR("Floating point constant invalid for type");
1858     $$ = ConstantFP::get($1, $2);
1859     CHECK_FOR_ERROR
1860   };
1861
1862
1863 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1864     if (!UpRefs.empty())
1865       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1866     Constant *Val = $3;
1867     const Type *DestTy = $5->get();
1868     if (!CastInst::castIsValid($1, $3, DestTy))
1869       GEN_ERROR("invalid cast opcode for cast from '" +
1870                 Val->getType()->getDescription() + "' to '" +
1871                 DestTy->getDescription() + "'"); 
1872     $$ = ConstantExpr::getCast($1, $3, DestTy);
1873     delete $5;
1874   }
1875   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1876     if (!isa<PointerType>($3->getType()))
1877       GEN_ERROR("GetElementPtr requires a pointer operand");
1878
1879     const Type *IdxTy =
1880       GetElementPtrInst::getIndexedType($3->getType(), &(*$4)[0], $4->size(),
1881                                         true);
1882     if (!IdxTy)
1883       GEN_ERROR("Index list invalid for constant getelementptr");
1884
1885     SmallVector<Constant*, 8> IdxVec;
1886     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1887       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1888         IdxVec.push_back(C);
1889       else
1890         GEN_ERROR("Indices to constant getelementptr must be constants");
1891
1892     delete $4;
1893
1894     $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1895     CHECK_FOR_ERROR
1896   }
1897   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1898     if ($3->getType() != Type::Int1Ty)
1899       GEN_ERROR("Select condition must be of boolean type");
1900     if ($5->getType() != $7->getType())
1901       GEN_ERROR("Select operand types must match");
1902     $$ = ConstantExpr::getSelect($3, $5, $7);
1903     CHECK_FOR_ERROR
1904   }
1905   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1906     if ($3->getType() != $5->getType())
1907       GEN_ERROR("Binary operator types must match");
1908     CHECK_FOR_ERROR;
1909     $$ = ConstantExpr::get($1, $3, $5);
1910   }
1911   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1912     if ($3->getType() != $5->getType())
1913       GEN_ERROR("Logical operator types must match");
1914     if (!$3->getType()->isInteger()) {
1915       if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) || 
1916           !cast<VectorType>($3->getType())->getElementType()->isInteger())
1917         GEN_ERROR("Logical operator requires integral operands");
1918     }
1919     $$ = ConstantExpr::get($1, $3, $5);
1920     CHECK_FOR_ERROR
1921   }
1922   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1923     if ($4->getType() != $6->getType())
1924       GEN_ERROR("icmp operand types must match");
1925     $$ = ConstantExpr::getICmp($2, $4, $6);
1926   }
1927   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1928     if ($4->getType() != $6->getType())
1929       GEN_ERROR("fcmp operand types must match");
1930     $$ = ConstantExpr::getFCmp($2, $4, $6);
1931   }
1932   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1933     if (!ExtractElementInst::isValidOperands($3, $5))
1934       GEN_ERROR("Invalid extractelement operands");
1935     $$ = ConstantExpr::getExtractElement($3, $5);
1936     CHECK_FOR_ERROR
1937   }
1938   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1939     if (!InsertElementInst::isValidOperands($3, $5, $7))
1940       GEN_ERROR("Invalid insertelement operands");
1941     $$ = ConstantExpr::getInsertElement($3, $5, $7);
1942     CHECK_FOR_ERROR
1943   }
1944   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1945     if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1946       GEN_ERROR("Invalid shufflevector operands");
1947     $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1948     CHECK_FOR_ERROR
1949   };
1950
1951
1952 // ConstVector - A list of comma separated constants.
1953 ConstVector : ConstVector ',' ConstVal {
1954     ($$ = $1)->push_back($3);
1955     CHECK_FOR_ERROR
1956   }
1957   | ConstVal {
1958     $$ = new std::vector<Constant*>();
1959     $$->push_back($1);
1960     CHECK_FOR_ERROR
1961   };
1962
1963
1964 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1965 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1966
1967 // ThreadLocal 
1968 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1969
1970 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1971 AliaseeRef : ResultTypes SymbolicValueRef {
1972     const Type* VTy = $1->get();
1973     Value *V = getVal(VTy, $2);
1974     GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1975     if (!Aliasee)
1976       GEN_ERROR("Aliases can be created only to global values");
1977
1978     $$ = Aliasee;
1979     CHECK_FOR_ERROR
1980     delete $1;
1981    }
1982    | BITCAST '(' AliaseeRef TO Types ')' {
1983     Constant *Val = $3;
1984     const Type *DestTy = $5->get();
1985     if (!CastInst::castIsValid($1, $3, DestTy))
1986       GEN_ERROR("invalid cast opcode for cast from '" +
1987                 Val->getType()->getDescription() + "' to '" +
1988                 DestTy->getDescription() + "'");
1989     
1990     $$ = ConstantExpr::getCast($1, $3, DestTy);
1991     CHECK_FOR_ERROR
1992     delete $5;
1993    };
1994
1995 //===----------------------------------------------------------------------===//
1996 //                             Rules to match Modules
1997 //===----------------------------------------------------------------------===//
1998
1999 // Module rule: Capture the result of parsing the whole file into a result
2000 // variable...
2001 //
2002 Module 
2003   : DefinitionList {
2004     $$ = ParserResult = CurModule.CurrentModule;
2005     CurModule.ModuleDone();
2006     CHECK_FOR_ERROR;
2007   }
2008   | /*empty*/ {
2009     $$ = ParserResult = CurModule.CurrentModule;
2010     CurModule.ModuleDone();
2011     CHECK_FOR_ERROR;
2012   }
2013   ;
2014
2015 DefinitionList
2016   : Definition
2017   | DefinitionList Definition
2018   ;
2019
2020 Definition 
2021   : DEFINE { CurFun.isDeclare = false; } Function {
2022     CurFun.FunctionDone();
2023     CHECK_FOR_ERROR
2024   }
2025   | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2026     CHECK_FOR_ERROR
2027   }
2028   | MODULE ASM_TOK AsmBlock {
2029     CHECK_FOR_ERROR
2030   }  
2031   | OptLocalAssign TYPE Types {
2032     if (!UpRefs.empty())
2033       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2034     // Eagerly resolve types.  This is not an optimization, this is a
2035     // requirement that is due to the fact that we could have this:
2036     //
2037     // %list = type { %list * }
2038     // %list = type { %list * }    ; repeated type decl
2039     //
2040     // If types are not resolved eagerly, then the two types will not be
2041     // determined to be the same type!
2042     //
2043     ResolveTypeTo($1, *$3);
2044
2045     if (!setTypeName(*$3, $1) && !$1) {
2046       CHECK_FOR_ERROR
2047       // If this is a named type that is not a redefinition, add it to the slot
2048       // table.
2049       CurModule.Types.push_back(*$3);
2050     }
2051
2052     delete $3;
2053     CHECK_FOR_ERROR
2054   }
2055   | OptLocalAssign TYPE VOID {
2056     ResolveTypeTo($1, $3);
2057
2058     if (!setTypeName($3, $1) && !$1) {
2059       CHECK_FOR_ERROR
2060       // If this is a named type that is not a redefinition, add it to the slot
2061       // table.
2062       CurModule.Types.push_back($3);
2063     }
2064     CHECK_FOR_ERROR
2065   }
2066   | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal { 
2067     /* "Externally Visible" Linkage */
2068     if ($5 == 0) 
2069       GEN_ERROR("Global value initializer is not a constant");
2070     CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2071                                 $2, $4, $5->getType(), $5, $3);
2072     CHECK_FOR_ERROR
2073   } GlobalVarAttributes {
2074     CurGV = 0;
2075   }
2076   | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2077     ConstVal {
2078     if ($6 == 0) 
2079       GEN_ERROR("Global value initializer is not a constant");
2080     CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4);
2081     CHECK_FOR_ERROR
2082   } GlobalVarAttributes {
2083     CurGV = 0;
2084   }
2085   | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2086     Types {
2087     if (!UpRefs.empty())
2088       GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2089     CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4);
2090     CHECK_FOR_ERROR
2091     delete $6;
2092   } GlobalVarAttributes {
2093     CurGV = 0;
2094     CHECK_FOR_ERROR
2095   }
2096   | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2097     std::string Name;
2098     if ($1) {
2099       Name = *$1;
2100       delete $1;
2101     }
2102     if (Name.empty())
2103       GEN_ERROR("Alias name cannot be empty");
2104     
2105     Constant* Aliasee = $5;
2106     if (Aliasee == 0)
2107       GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2108
2109     GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2110                                       CurModule.CurrentModule);
2111     GA->setVisibility($2);
2112     InsertValue(GA, CurModule.Values);
2113     CHECK_FOR_ERROR
2114   }
2115   | TARGET TargetDefinition { 
2116     CHECK_FOR_ERROR
2117   }
2118   | DEPLIBS '=' LibrariesDefinition {
2119     CHECK_FOR_ERROR
2120   }
2121   ;
2122
2123
2124 AsmBlock : STRINGCONSTANT {
2125   const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2126   if (AsmSoFar.empty())
2127     CurModule.CurrentModule->setModuleInlineAsm(*$1);
2128   else
2129     CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2130   delete $1;
2131   CHECK_FOR_ERROR
2132 };
2133
2134 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2135     CurModule.CurrentModule->setTargetTriple(*$3);
2136     delete $3;
2137   }
2138   | DATALAYOUT '=' STRINGCONSTANT {
2139     CurModule.CurrentModule->setDataLayout(*$3);
2140     delete $3;
2141   };
2142
2143 LibrariesDefinition : '[' LibList ']';
2144
2145 LibList : LibList ',' STRINGCONSTANT {
2146           CurModule.CurrentModule->addLibrary(*$3);
2147           delete $3;
2148           CHECK_FOR_ERROR
2149         }
2150         | STRINGCONSTANT {
2151           CurModule.CurrentModule->addLibrary(*$1);
2152           delete $1;
2153           CHECK_FOR_ERROR
2154         }
2155         | /* empty: end of list */ {
2156           CHECK_FOR_ERROR
2157         }
2158         ;
2159
2160 //===----------------------------------------------------------------------===//
2161 //                       Rules to match Function Headers
2162 //===----------------------------------------------------------------------===//
2163
2164 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2165     if (!UpRefs.empty())
2166       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2167     if (*$3 == Type::VoidTy)
2168       GEN_ERROR("void typed arguments are invalid");
2169     ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2170     $$ = $1;
2171     $1->push_back(E);
2172     CHECK_FOR_ERROR
2173   }
2174   | Types OptParamAttrs OptLocalName {
2175     if (!UpRefs.empty())
2176       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2177     if (*$1 == Type::VoidTy)
2178       GEN_ERROR("void typed arguments are invalid");
2179     ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2180     $$ = new ArgListType;
2181     $$->push_back(E);
2182     CHECK_FOR_ERROR
2183   };
2184
2185 ArgList : ArgListH {
2186     $$ = $1;
2187     CHECK_FOR_ERROR
2188   }
2189   | ArgListH ',' DOTDOTDOT {
2190     $$ = $1;
2191     struct ArgListEntry E;
2192     E.Ty = new PATypeHolder(Type::VoidTy);
2193     E.Name = 0;
2194     E.Attrs = ParamAttr::None;
2195     $$->push_back(E);
2196     CHECK_FOR_ERROR
2197   }
2198   | DOTDOTDOT {
2199     $$ = new ArgListType;
2200     struct ArgListEntry E;
2201     E.Ty = new PATypeHolder(Type::VoidTy);
2202     E.Name = 0;
2203     E.Attrs = ParamAttr::None;
2204     $$->push_back(E);
2205     CHECK_FOR_ERROR
2206   }
2207   | /* empty */ {
2208     $$ = 0;
2209     CHECK_FOR_ERROR
2210   };
2211
2212 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')' 
2213                   OptFuncAttrs OptSection OptAlign {
2214   std::string FunctionName(*$3);
2215   delete $3;  // Free strdup'd memory!
2216   
2217   // Check the function result for abstractness if this is a define. We should
2218   // have no abstract types at this point
2219   if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2220     GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2221
2222   std::vector<const Type*> ParamTypeList;
2223   ParamAttrsVector Attrs;
2224   if ($7 != ParamAttr::None) {
2225     ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $7;
2226     Attrs.push_back(PAWI);
2227   }
2228   if ($5) {   // If there are arguments...
2229     unsigned index = 1;
2230     for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2231       const Type* Ty = I->Ty->get();
2232       if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2233         GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2234       ParamTypeList.push_back(Ty);
2235       if (Ty != Type::VoidTy)
2236         if (I->Attrs != ParamAttr::None) {
2237           ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = I->Attrs;
2238           Attrs.push_back(PAWI);
2239         }
2240     }
2241   }
2242
2243   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2244   if (isVarArg) ParamTypeList.pop_back();
2245
2246   ParamAttrsList *PAL = 0;
2247   if (!Attrs.empty())
2248     PAL = ParamAttrsList::get(Attrs);
2249
2250   FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg, PAL);
2251   const PointerType *PFT = PointerType::get(FT);
2252   delete $2;
2253
2254   ValID ID;
2255   if (!FunctionName.empty()) {
2256     ID = ValID::createGlobalName((char*)FunctionName.c_str());
2257   } else {
2258     ID = ValID::createGlobalID(CurModule.Values.size());
2259   }
2260
2261   Function *Fn = 0;
2262   // See if this function was forward referenced.  If so, recycle the object.
2263   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2264     // Move the function to the end of the list, from whereever it was 
2265     // previously inserted.
2266     Fn = cast<Function>(FWRef);
2267     CurModule.CurrentModule->getFunctionList().remove(Fn);
2268     CurModule.CurrentModule->getFunctionList().push_back(Fn);
2269   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
2270              (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2271     if (Fn->getFunctionType() != FT) {
2272       // The existing function doesn't have the same type. This is an overload
2273       // error.
2274       GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2275     } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2276       // Neither the existing or the current function is a declaration and they
2277       // have the same name and same type. Clearly this is a redefinition.
2278       GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2279     } if (Fn->isDeclaration()) {
2280       // Make sure to strip off any argument names so we can't get conflicts.
2281       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2282            AI != AE; ++AI)
2283         AI->setName("");
2284     }
2285   } else  {  // Not already defined?
2286     Fn = new Function(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2287                       CurModule.CurrentModule);
2288
2289     InsertValue(Fn, CurModule.Values);
2290   }
2291
2292   CurFun.FunctionStart(Fn);
2293
2294   if (CurFun.isDeclare) {
2295     // If we have declaration, always overwrite linkage.  This will allow us to
2296     // correctly handle cases, when pointer to function is passed as argument to
2297     // another function.
2298     Fn->setLinkage(CurFun.Linkage);
2299     Fn->setVisibility(CurFun.Visibility);
2300   }
2301   Fn->setCallingConv($1);
2302   Fn->setAlignment($9);
2303   if ($8) {
2304     Fn->setSection(*$8);
2305     delete $8;
2306   }
2307
2308   // Add all of the arguments we parsed to the function...
2309   if ($5) {                     // Is null if empty...
2310     if (isVarArg) {  // Nuke the last entry
2311       assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2312              "Not a varargs marker!");
2313       delete $5->back().Ty;
2314       $5->pop_back();  // Delete the last entry
2315     }
2316     Function::arg_iterator ArgIt = Fn->arg_begin();
2317     Function::arg_iterator ArgEnd = Fn->arg_end();
2318     unsigned Idx = 1;
2319     for (ArgListType::iterator I = $5->begin(); 
2320          I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2321       delete I->Ty;                          // Delete the typeholder...
2322       setValueName(ArgIt, I->Name);       // Insert arg into symtab...
2323       CHECK_FOR_ERROR
2324       InsertValue(ArgIt);
2325       Idx++;
2326     }
2327
2328     delete $5;                     // We're now done with the argument list
2329   }
2330   CHECK_FOR_ERROR
2331 };
2332
2333 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
2334
2335 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2336   $$ = CurFun.CurrentFunction;
2337
2338   // Make sure that we keep track of the linkage type even if there was a
2339   // previous "declare".
2340   $$->setLinkage($1);
2341   $$->setVisibility($2);
2342 };
2343
2344 END : ENDTOK | '}';                    // Allow end of '}' to end a function
2345
2346 Function : BasicBlockList END {
2347   $$ = $1;
2348   CHECK_FOR_ERROR
2349 };
2350
2351 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2352     CurFun.CurrentFunction->setLinkage($1);
2353     CurFun.CurrentFunction->setVisibility($2);
2354     $$ = CurFun.CurrentFunction;
2355     CurFun.FunctionDone();
2356     CHECK_FOR_ERROR
2357   };
2358
2359 //===----------------------------------------------------------------------===//
2360 //                        Rules to match Basic Blocks
2361 //===----------------------------------------------------------------------===//
2362
2363 OptSideEffect : /* empty */ {
2364     $$ = false;
2365     CHECK_FOR_ERROR
2366   }
2367   | SIDEEFFECT {
2368     $$ = true;
2369     CHECK_FOR_ERROR
2370   };
2371
2372 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
2373     $$ = ValID::create($1);
2374     CHECK_FOR_ERROR
2375   }
2376   | EUINT64VAL {
2377     $$ = ValID::create($1);
2378     CHECK_FOR_ERROR
2379   }
2380   | FPVAL {                     // Perhaps it's an FP constant?
2381     $$ = ValID::create($1);
2382     CHECK_FOR_ERROR
2383   }
2384   | TRUETOK {
2385     $$ = ValID::create(ConstantInt::getTrue());
2386     CHECK_FOR_ERROR
2387   } 
2388   | FALSETOK {
2389     $$ = ValID::create(ConstantInt::getFalse());
2390     CHECK_FOR_ERROR
2391   }
2392   | NULL_TOK {
2393     $$ = ValID::createNull();
2394     CHECK_FOR_ERROR
2395   }
2396   | UNDEF {
2397     $$ = ValID::createUndef();
2398     CHECK_FOR_ERROR
2399   }
2400   | ZEROINITIALIZER {     // A vector zero constant.
2401     $$ = ValID::createZeroInit();
2402     CHECK_FOR_ERROR
2403   }
2404   | '<' ConstVector '>' { // Nonempty unsized packed vector
2405     const Type *ETy = (*$2)[0]->getType();
2406     int NumElements = $2->size(); 
2407     
2408     VectorType* pt = VectorType::get(ETy, NumElements);
2409     PATypeHolder* PTy = new PATypeHolder(
2410                                          HandleUpRefs(
2411                                             VectorType::get(
2412                                                 ETy, 
2413                                                 NumElements)
2414                                             )
2415                                          );
2416     
2417     // Verify all elements are correct type!
2418     for (unsigned i = 0; i < $2->size(); i++) {
2419       if (ETy != (*$2)[i]->getType())
2420         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
2421                      ETy->getDescription() +"' as required!\nIt is of type '" +
2422                      (*$2)[i]->getType()->getDescription() + "'.");
2423     }
2424
2425     $$ = ValID::create(ConstantVector::get(pt, *$2));
2426     delete PTy; delete $2;
2427     CHECK_FOR_ERROR
2428   }
2429   | ConstExpr {
2430     $$ = ValID::create($1);
2431     CHECK_FOR_ERROR
2432   }
2433   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2434     $$ = ValID::createInlineAsm(*$3, *$5, $2);
2435     delete $3;
2436     delete $5;
2437     CHECK_FOR_ERROR
2438   };
2439
2440 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2441 // another value.
2442 //
2443 SymbolicValueRef : LOCALVAL_ID {  // Is it an integer reference...?
2444     $$ = ValID::createLocalID($1);
2445     CHECK_FOR_ERROR
2446   }
2447   | GLOBALVAL_ID {
2448     $$ = ValID::createGlobalID($1);
2449     CHECK_FOR_ERROR
2450   }
2451   | LocalName {                   // Is it a named reference...?
2452     $$ = ValID::createLocalName(*$1);
2453     delete $1;
2454     CHECK_FOR_ERROR
2455   }
2456   | GlobalName {                   // Is it a named reference...?
2457     $$ = ValID::createGlobalName(*$1);
2458     delete $1;
2459     CHECK_FOR_ERROR
2460   };
2461
2462 // ValueRef - A reference to a definition... either constant or symbolic
2463 ValueRef : SymbolicValueRef | ConstValueRef;
2464
2465
2466 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
2467 // type immediately preceeds the value reference, and allows complex constant
2468 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2469 ResolvedVal : Types ValueRef {
2470     if (!UpRefs.empty())
2471       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2472     $$ = getVal(*$1, $2); 
2473     delete $1;
2474     CHECK_FOR_ERROR
2475   }
2476   ;
2477
2478 BasicBlockList : BasicBlockList BasicBlock {
2479     $$ = $1;
2480     CHECK_FOR_ERROR
2481   }
2482   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
2483     $$ = $1;
2484     CHECK_FOR_ERROR
2485   };
2486
2487
2488 // Basic blocks are terminated by branching instructions: 
2489 // br, br/cc, switch, ret
2490 //
2491 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst  {
2492     setValueName($3, $2);
2493     CHECK_FOR_ERROR
2494     InsertValue($3);
2495     $1->getInstList().push_back($3);
2496     $$ = $1;
2497     CHECK_FOR_ERROR
2498   };
2499
2500 InstructionList : InstructionList Inst {
2501     if (CastInst *CI1 = dyn_cast<CastInst>($2))
2502       if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2503         if (CI2->getParent() == 0)
2504           $1->getInstList().push_back(CI2);
2505     $1->getInstList().push_back($2);
2506     $$ = $1;
2507     CHECK_FOR_ERROR
2508   }
2509   | /* empty */ {          // Empty space between instruction lists
2510     $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2511     CHECK_FOR_ERROR
2512   }
2513   | LABELSTR {             // Labelled (named) basic block
2514     $$ = defineBBVal(ValID::createLocalName(*$1));
2515     delete $1;
2516     CHECK_FOR_ERROR
2517
2518   };
2519
2520 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
2521     $$ = new ReturnInst($2);
2522     CHECK_FOR_ERROR
2523   }
2524   | RET VOID {                                    // Return with no result...
2525     $$ = new ReturnInst();
2526     CHECK_FOR_ERROR
2527   }
2528   | BR LABEL ValueRef {                           // Unconditional Branch...
2529     BasicBlock* tmpBB = getBBVal($3);
2530     CHECK_FOR_ERROR
2531     $$ = new BranchInst(tmpBB);
2532   }                                               // Conditional Branch...
2533   | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
2534     assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2535     BasicBlock* tmpBBA = getBBVal($6);
2536     CHECK_FOR_ERROR
2537     BasicBlock* tmpBBB = getBBVal($9);
2538     CHECK_FOR_ERROR
2539     Value* tmpVal = getVal(Type::Int1Ty, $3);
2540     CHECK_FOR_ERROR
2541     $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2542   }
2543   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2544     Value* tmpVal = getVal($2, $3);
2545     CHECK_FOR_ERROR
2546     BasicBlock* tmpBB = getBBVal($6);
2547     CHECK_FOR_ERROR
2548     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2549     $$ = S;
2550
2551     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2552       E = $8->end();
2553     for (; I != E; ++I) {
2554       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2555           S->addCase(CI, I->second);
2556       else
2557         GEN_ERROR("Switch case is constant, but not a simple integer");
2558     }
2559     delete $8;
2560     CHECK_FOR_ERROR
2561   }
2562   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2563     Value* tmpVal = getVal($2, $3);
2564     CHECK_FOR_ERROR
2565     BasicBlock* tmpBB = getBBVal($6);
2566     CHECK_FOR_ERROR
2567     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2568     $$ = S;
2569     CHECK_FOR_ERROR
2570   }
2571   | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2572     TO LABEL ValueRef UNWIND LABEL ValueRef {
2573
2574     // Handle the short syntax
2575     const PointerType *PFTy = 0;
2576     const FunctionType *Ty = 0;
2577     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2578         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2579       // Pull out the types of all of the arguments...
2580       std::vector<const Type*> ParamTypes;
2581       ParamAttrsVector Attrs;
2582       if ($8 != ParamAttr::None) {
2583         ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2584         Attrs.push_back(PAWI);
2585       }
2586       ValueRefList::iterator I = $6->begin(), E = $6->end();
2587       unsigned index = 1;
2588       for (; I != E; ++I, ++index) {
2589         const Type *Ty = I->Val->getType();
2590         if (Ty == Type::VoidTy)
2591           GEN_ERROR("Short call syntax cannot be used with varargs");
2592         ParamTypes.push_back(Ty);
2593         if (I->Attrs != ParamAttr::None) {
2594           ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = I->Attrs;
2595           Attrs.push_back(PAWI);
2596         }
2597       }
2598
2599       ParamAttrsList *PAL = 0;
2600       if (!Attrs.empty())
2601         PAL = ParamAttrsList::get(Attrs);
2602       Ty = FunctionType::get($3->get(), ParamTypes, false, PAL);
2603       PFTy = PointerType::get(Ty);
2604     }
2605
2606     delete $3;
2607
2608     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2609     CHECK_FOR_ERROR
2610     BasicBlock *Normal = getBBVal($11);
2611     CHECK_FOR_ERROR
2612     BasicBlock *Except = getBBVal($14);
2613     CHECK_FOR_ERROR
2614
2615     // Check the arguments
2616     ValueList Args;
2617     if ($6->empty()) {                                   // Has no arguments?
2618       // Make sure no arguments is a good thing!
2619       if (Ty->getNumParams() != 0)
2620         GEN_ERROR("No arguments passed to a function that "
2621                        "expects arguments");
2622     } else {                                     // Has arguments?
2623       // Loop through FunctionType's arguments and ensure they are specified
2624       // correctly!
2625       FunctionType::param_iterator I = Ty->param_begin();
2626       FunctionType::param_iterator E = Ty->param_end();
2627       ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2628
2629       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2630         if (ArgI->Val->getType() != *I)
2631           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2632                          (*I)->getDescription() + "'");
2633         Args.push_back(ArgI->Val);
2634       }
2635
2636       if (Ty->isVarArg()) {
2637         if (I == E)
2638           for (; ArgI != ArgE; ++ArgI)
2639             Args.push_back(ArgI->Val); // push the remaining varargs
2640       } else if (I != E || ArgI != ArgE)
2641         GEN_ERROR("Invalid number of parameters detected");
2642     }
2643
2644     // Create the InvokeInst
2645     InvokeInst *II = new InvokeInst(V, Normal, Except, &Args[0], Args.size());
2646     II->setCallingConv($2);
2647     $$ = II;
2648     delete $6;
2649     CHECK_FOR_ERROR
2650   }
2651   | UNWIND {
2652     $$ = new UnwindInst();
2653     CHECK_FOR_ERROR
2654   }
2655   | UNREACHABLE {
2656     $$ = new UnreachableInst();
2657     CHECK_FOR_ERROR
2658   };
2659
2660
2661
2662 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2663     $$ = $1;
2664     Constant *V = cast<Constant>(getExistingVal($2, $3));
2665     CHECK_FOR_ERROR
2666     if (V == 0)
2667       GEN_ERROR("May only switch on a constant pool value");
2668
2669     BasicBlock* tmpBB = getBBVal($6);
2670     CHECK_FOR_ERROR
2671     $$->push_back(std::make_pair(V, tmpBB));
2672   }
2673   | IntType ConstValueRef ',' LABEL ValueRef {
2674     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2675     Constant *V = cast<Constant>(getExistingVal($1, $2));
2676     CHECK_FOR_ERROR
2677
2678     if (V == 0)
2679       GEN_ERROR("May only switch on a constant pool value");
2680
2681     BasicBlock* tmpBB = getBBVal($5);
2682     CHECK_FOR_ERROR
2683     $$->push_back(std::make_pair(V, tmpBB)); 
2684   };
2685
2686 Inst : OptLocalAssign InstVal {
2687     // Is this definition named?? if so, assign the name...
2688     setValueName($2, $1);
2689     CHECK_FOR_ERROR
2690     InsertValue($2);
2691     $$ = $2;
2692     CHECK_FOR_ERROR
2693   };
2694
2695
2696 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
2697     if (!UpRefs.empty())
2698       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2699     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2700     Value* tmpVal = getVal(*$1, $3);
2701     CHECK_FOR_ERROR
2702     BasicBlock* tmpBB = getBBVal($5);
2703     CHECK_FOR_ERROR
2704     $$->push_back(std::make_pair(tmpVal, tmpBB));
2705     delete $1;
2706   }
2707   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2708     $$ = $1;
2709     Value* tmpVal = getVal($1->front().first->getType(), $4);
2710     CHECK_FOR_ERROR
2711     BasicBlock* tmpBB = getBBVal($6);
2712     CHECK_FOR_ERROR
2713     $1->push_back(std::make_pair(tmpVal, tmpBB));
2714   };
2715
2716
2717 ValueRefList : Types ValueRef OptParamAttrs {    
2718     if (!UpRefs.empty())
2719       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2720     // Used for call and invoke instructions
2721     $$ = new ValueRefList();
2722     ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2723     $$->push_back(E);
2724     delete $1;
2725   }
2726   | ValueRefList ',' Types ValueRef OptParamAttrs {
2727     if (!UpRefs.empty())
2728       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2729     $$ = $1;
2730     ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2731     $$->push_back(E);
2732     delete $3;
2733     CHECK_FOR_ERROR
2734   }
2735   | /*empty*/ { $$ = new ValueRefList(); };
2736
2737 IndexList       // Used for gep instructions and constant expressions
2738   : /*empty*/ { $$ = new std::vector<Value*>(); }
2739   | IndexList ',' ResolvedVal {
2740     $$ = $1;
2741     $$->push_back($3);
2742     CHECK_FOR_ERROR
2743   }
2744   ;
2745
2746 OptTailCall : TAIL CALL {
2747     $$ = true;
2748     CHECK_FOR_ERROR
2749   }
2750   | CALL {
2751     $$ = false;
2752     CHECK_FOR_ERROR
2753   };
2754
2755 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2756     if (!UpRefs.empty())
2757       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2758     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() && 
2759         !isa<VectorType>((*$2).get()))
2760       GEN_ERROR(
2761         "Arithmetic operator requires integer, FP, or packed operands");
2762     if (isa<VectorType>((*$2).get()) && 
2763         ($1 == Instruction::URem || 
2764          $1 == Instruction::SRem ||
2765          $1 == Instruction::FRem))
2766       GEN_ERROR("Remainder not supported on vector types");
2767     Value* val1 = getVal(*$2, $3); 
2768     CHECK_FOR_ERROR
2769     Value* val2 = getVal(*$2, $5);
2770     CHECK_FOR_ERROR
2771     $$ = BinaryOperator::create($1, val1, val2);
2772     if ($$ == 0)
2773       GEN_ERROR("binary operator returned null");
2774     delete $2;
2775   }
2776   | LogicalOps Types ValueRef ',' ValueRef {
2777     if (!UpRefs.empty())
2778       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2779     if (!(*$2)->isInteger()) {
2780       if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2781           !cast<VectorType>($2->get())->getElementType()->isInteger())
2782         GEN_ERROR("Logical operator requires integral operands");
2783     }
2784     Value* tmpVal1 = getVal(*$2, $3);
2785     CHECK_FOR_ERROR
2786     Value* tmpVal2 = getVal(*$2, $5);
2787     CHECK_FOR_ERROR
2788     $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2789     if ($$ == 0)
2790       GEN_ERROR("binary operator returned null");
2791     delete $2;
2792   }
2793   | ICMP IPredicates Types ValueRef ',' ValueRef  {
2794     if (!UpRefs.empty())
2795       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2796     if (isa<VectorType>((*$3).get()))
2797       GEN_ERROR("Vector types not supported by icmp instruction");
2798     Value* tmpVal1 = getVal(*$3, $4);
2799     CHECK_FOR_ERROR
2800     Value* tmpVal2 = getVal(*$3, $6);
2801     CHECK_FOR_ERROR
2802     $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2803     if ($$ == 0)
2804       GEN_ERROR("icmp operator returned null");
2805     delete $3;
2806   }
2807   | FCMP FPredicates Types ValueRef ',' ValueRef  {
2808     if (!UpRefs.empty())
2809       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2810     if (isa<VectorType>((*$3).get()))
2811       GEN_ERROR("Vector types not supported by fcmp instruction");
2812     Value* tmpVal1 = getVal(*$3, $4);
2813     CHECK_FOR_ERROR
2814     Value* tmpVal2 = getVal(*$3, $6);
2815     CHECK_FOR_ERROR
2816     $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2817     if ($$ == 0)
2818       GEN_ERROR("fcmp operator returned null");
2819     delete $3;
2820   }
2821   | CastOps ResolvedVal TO Types {
2822     if (!UpRefs.empty())
2823       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2824     Value* Val = $2;
2825     const Type* DestTy = $4->get();
2826     if (!CastInst::castIsValid($1, Val, DestTy))
2827       GEN_ERROR("invalid cast opcode for cast from '" +
2828                 Val->getType()->getDescription() + "' to '" +
2829                 DestTy->getDescription() + "'"); 
2830     $$ = CastInst::create($1, Val, DestTy);
2831     delete $4;
2832   }
2833   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2834     if ($2->getType() != Type::Int1Ty)
2835       GEN_ERROR("select condition must be boolean");
2836     if ($4->getType() != $6->getType())
2837       GEN_ERROR("select value types should match");
2838     $$ = new SelectInst($2, $4, $6);
2839     CHECK_FOR_ERROR
2840   }
2841   | VAARG ResolvedVal ',' Types {
2842     if (!UpRefs.empty())
2843       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2844     $$ = new VAArgInst($2, *$4);
2845     delete $4;
2846     CHECK_FOR_ERROR
2847   }
2848   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2849     if (!ExtractElementInst::isValidOperands($2, $4))
2850       GEN_ERROR("Invalid extractelement operands");
2851     $$ = new ExtractElementInst($2, $4);
2852     CHECK_FOR_ERROR
2853   }
2854   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2855     if (!InsertElementInst::isValidOperands($2, $4, $6))
2856       GEN_ERROR("Invalid insertelement operands");
2857     $$ = new InsertElementInst($2, $4, $6);
2858     CHECK_FOR_ERROR
2859   }
2860   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2861     if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2862       GEN_ERROR("Invalid shufflevector operands");
2863     $$ = new ShuffleVectorInst($2, $4, $6);
2864     CHECK_FOR_ERROR
2865   }
2866   | PHI_TOK PHIList {
2867     const Type *Ty = $2->front().first->getType();
2868     if (!Ty->isFirstClassType())
2869       GEN_ERROR("PHI node operands must be of first class type");
2870     $$ = new PHINode(Ty);
2871     ((PHINode*)$$)->reserveOperandSpace($2->size());
2872     while ($2->begin() != $2->end()) {
2873       if ($2->front().first->getType() != Ty) 
2874         GEN_ERROR("All elements of a PHI node must be of the same type");
2875       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2876       $2->pop_front();
2877     }
2878     delete $2;  // Free the list...
2879     CHECK_FOR_ERROR
2880   }
2881   | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' 
2882     OptFuncAttrs {
2883
2884     // Handle the short syntax
2885     const PointerType *PFTy = 0;
2886     const FunctionType *Ty = 0;
2887     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2888         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2889       // Pull out the types of all of the arguments...
2890       std::vector<const Type*> ParamTypes;
2891       ParamAttrsVector Attrs;
2892       if ($8 != ParamAttr::None) {
2893         ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2894         Attrs.push_back(PAWI);
2895       }
2896       unsigned index = 1;
2897       ValueRefList::iterator I = $6->begin(), E = $6->end();
2898       for (; I != E; ++I, ++index) {
2899         const Type *Ty = I->Val->getType();
2900         if (Ty == Type::VoidTy)
2901           GEN_ERROR("Short call syntax cannot be used with varargs");
2902         ParamTypes.push_back(Ty);
2903         if (I->Attrs != ParamAttr::None) {
2904           ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = I->Attrs;
2905           Attrs.push_back(PAWI);
2906         }
2907       }
2908
2909       ParamAttrsList *PAL = 0;
2910       if (!Attrs.empty())
2911         PAL = ParamAttrsList::get(Attrs);
2912
2913       Ty = FunctionType::get($3->get(), ParamTypes, false, PAL);
2914       PFTy = PointerType::get(Ty);
2915     }
2916
2917     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2918     CHECK_FOR_ERROR
2919
2920     // Check for call to invalid intrinsic to avoid crashing later.
2921     if (Function *theF = dyn_cast<Function>(V)) {
2922       if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
2923           (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
2924           !theF->getIntrinsicID(true))
2925         GEN_ERROR("Call to invalid LLVM intrinsic function '" +
2926                   theF->getName() + "'");
2927     }
2928
2929     // Check the arguments 
2930     ValueList Args;
2931     if ($6->empty()) {                                   // Has no arguments?
2932       // Make sure no arguments is a good thing!
2933       if (Ty->getNumParams() != 0)
2934         GEN_ERROR("No arguments passed to a function that "
2935                        "expects arguments");
2936     } else {                                     // Has arguments?
2937       // Loop through FunctionType's arguments and ensure they are specified
2938       // correctly!
2939       //
2940       FunctionType::param_iterator I = Ty->param_begin();
2941       FunctionType::param_iterator E = Ty->param_end();
2942       ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2943
2944       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2945         if (ArgI->Val->getType() != *I)
2946           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2947                          (*I)->getDescription() + "'");
2948         Args.push_back(ArgI->Val);
2949       }
2950       if (Ty->isVarArg()) {
2951         if (I == E)
2952           for (; ArgI != ArgE; ++ArgI)
2953             Args.push_back(ArgI->Val); // push the remaining varargs
2954       } else if (I != E || ArgI != ArgE)
2955         GEN_ERROR("Invalid number of parameters detected");
2956     }
2957     // Create the call node
2958     CallInst *CI = new CallInst(V, &Args[0], Args.size());
2959     CI->setTailCall($1);
2960     CI->setCallingConv($2);
2961     $$ = CI;
2962     delete $6;
2963     delete $3;
2964     CHECK_FOR_ERROR
2965   }
2966   | MemoryInst {
2967     $$ = $1;
2968     CHECK_FOR_ERROR
2969   };
2970
2971 OptVolatile : VOLATILE {
2972     $$ = true;
2973     CHECK_FOR_ERROR
2974   }
2975   | /* empty */ {
2976     $$ = false;
2977     CHECK_FOR_ERROR
2978   };
2979
2980
2981
2982 MemoryInst : MALLOC Types OptCAlign {
2983     if (!UpRefs.empty())
2984       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2985     $$ = new MallocInst(*$2, 0, $3);
2986     delete $2;
2987     CHECK_FOR_ERROR
2988   }
2989   | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2990     if (!UpRefs.empty())
2991       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2992     Value* tmpVal = getVal($4, $5);
2993     CHECK_FOR_ERROR
2994     $$ = new MallocInst(*$2, tmpVal, $6);
2995     delete $2;
2996   }
2997   | ALLOCA Types OptCAlign {
2998     if (!UpRefs.empty())
2999       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3000     $$ = new AllocaInst(*$2, 0, $3);
3001     delete $2;
3002     CHECK_FOR_ERROR
3003   }
3004   | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3005     if (!UpRefs.empty())
3006       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3007     Value* tmpVal = getVal($4, $5);
3008     CHECK_FOR_ERROR
3009     $$ = new AllocaInst(*$2, tmpVal, $6);
3010     delete $2;
3011   }
3012   | FREE ResolvedVal {
3013     if (!isa<PointerType>($2->getType()))
3014       GEN_ERROR("Trying to free nonpointer type " + 
3015                      $2->getType()->getDescription() + "");
3016     $$ = new FreeInst($2);
3017     CHECK_FOR_ERROR
3018   }
3019
3020   | OptVolatile LOAD Types ValueRef OptCAlign {
3021     if (!UpRefs.empty())
3022       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3023     if (!isa<PointerType>($3->get()))
3024       GEN_ERROR("Can't load from nonpointer type: " +
3025                      (*$3)->getDescription());
3026     if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3027       GEN_ERROR("Can't load from pointer of non-first-class type: " +
3028                      (*$3)->getDescription());
3029     Value* tmpVal = getVal(*$3, $4);
3030     CHECK_FOR_ERROR
3031     $$ = new LoadInst(tmpVal, "", $1, $5);
3032     delete $3;
3033   }
3034   | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3035     if (!UpRefs.empty())
3036       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3037     const PointerType *PT = dyn_cast<PointerType>($5->get());
3038     if (!PT)
3039       GEN_ERROR("Can't store to a nonpointer type: " +
3040                      (*$5)->getDescription());
3041     const Type *ElTy = PT->getElementType();
3042     if (ElTy != $3->getType())
3043       GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3044                      "' into space of type '" + ElTy->getDescription() + "'");
3045
3046     Value* tmpVal = getVal(*$5, $6);
3047     CHECK_FOR_ERROR
3048     $$ = new StoreInst($3, tmpVal, $1, $7);
3049     delete $5;
3050   }
3051   | GETELEMENTPTR Types ValueRef IndexList {
3052     if (!UpRefs.empty())
3053       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3054     if (!isa<PointerType>($2->get()))
3055       GEN_ERROR("getelementptr insn requires pointer operand");
3056
3057     if (!GetElementPtrInst::getIndexedType(*$2, &(*$4)[0], $4->size(), true))
3058       GEN_ERROR("Invalid getelementptr indices for type '" +
3059                      (*$2)->getDescription()+ "'");
3060     Value* tmpVal = getVal(*$2, $3);
3061     CHECK_FOR_ERROR
3062     $$ = new GetElementPtrInst(tmpVal, &(*$4)[0], $4->size());
3063     delete $2; 
3064     delete $4;
3065   };
3066
3067
3068 %%
3069
3070 // common code from the two 'RunVMAsmParser' functions
3071 static Module* RunParser(Module * M) {
3072
3073   llvmAsmlineno = 1;      // Reset the current line number...
3074   CurModule.CurrentModule = M;
3075 #if YYDEBUG
3076   yydebug = Debug;
3077 #endif
3078
3079   // Check to make sure the parser succeeded
3080   if (yyparse()) {
3081     if (ParserResult)
3082       delete ParserResult;
3083     return 0;
3084   }
3085
3086   // Emit an error if there are any unresolved types left.
3087   if (!CurModule.LateResolveTypes.empty()) {
3088     const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3089     if (DID.Type == ValID::LocalName) {
3090       GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3091     } else {
3092       GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3093     }
3094     if (ParserResult)
3095       delete ParserResult;
3096     return 0;
3097   }
3098
3099   // Emit an error if there are any unresolved values left.
3100   if (!CurModule.LateResolveValues.empty()) {
3101     Value *V = CurModule.LateResolveValues.back();
3102     std::map<Value*, std::pair<ValID, int> >::iterator I =
3103       CurModule.PlaceHolderInfo.find(V);
3104
3105     if (I != CurModule.PlaceHolderInfo.end()) {
3106       ValID &DID = I->second.first;
3107       if (DID.Type == ValID::LocalName) {
3108         GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3109       } else {
3110         GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3111       }
3112       if (ParserResult)
3113         delete ParserResult;
3114       return 0;
3115     }
3116   }
3117
3118   // Check to make sure that parsing produced a result
3119   if (!ParserResult)
3120     return 0;
3121
3122   // Reset ParserResult variable while saving its value for the result.
3123   Module *Result = ParserResult;
3124   ParserResult = 0;
3125
3126   return Result;
3127 }
3128
3129 void llvm::GenerateError(const std::string &message, int LineNo) {
3130   if (LineNo == -1) LineNo = llvmAsmlineno;
3131   // TODO: column number in exception
3132   if (TheParseError)
3133     TheParseError->setError(CurFilename, message, LineNo);
3134   TriggerError = 1;
3135 }
3136
3137 int yyerror(const char *ErrorMsg) {
3138   std::string where 
3139     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3140                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
3141   std::string errMsg = where + "error: " + std::string(ErrorMsg);
3142   if (yychar != YYEMPTY && yychar != 0)
3143     errMsg += " while reading token: '" + std::string(llvmAsmtext, llvmAsmleng)+
3144               "'";
3145   GenerateError(errMsg);
3146   return 0;
3147 }