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