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