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