rename indbr -> indirectbr to appease the residents of #llvm.
[oota-llvm.git] / lib / AsmParser / LLParser.cpp
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLParser.h"
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/Module.h"
24 #include "llvm/Operator.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm;
31
32 namespace llvm {
33   /// ValID - Represents a reference of a definition of some sort with no type.
34   /// There are several cases where we have to parse the value but where the
35   /// type can depend on later context.  This may either be a numeric reference
36   /// or a symbolic (%var) reference.  This is just a discriminated union.
37   struct ValID {
38     enum {
39       t_LocalID, t_GlobalID,      // ID in UIntVal.
40       t_LocalName, t_GlobalName,  // Name in StrVal.
41       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
42       t_Null, t_Undef, t_Zero,    // No value.
43       t_EmptyArray,               // No value:  []
44       t_Constant,                 // Value in ConstantVal.
45       t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
46       t_Metadata                  // Value in MetadataVal.
47     } Kind;
48
49     LLParser::LocTy Loc;
50     unsigned UIntVal;
51     std::string StrVal, StrVal2;
52     APSInt APSIntVal;
53     APFloat APFloatVal;
54     Constant *ConstantVal;
55     MetadataBase *MetadataVal;
56     ValID() : APFloatVal(0.0) {}
57   };
58 }
59
60 /// Run: module ::= toplevelentity*
61 bool LLParser::Run() {
62   // Prime the lexer.
63   Lex.Lex();
64
65   return ParseTopLevelEntities() ||
66          ValidateEndOfModule();
67 }
68
69 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
70 /// module.
71 bool LLParser::ValidateEndOfModule() {
72   // Update auto-upgraded malloc calls to "malloc".
73   // FIXME: Remove in LLVM 3.0.
74   if (MallocF) {
75     MallocF->setName("malloc");
76     // If setName() does not set the name to "malloc", then there is already a 
77     // declaration of "malloc".  In that case, iterate over all calls to MallocF
78     // and get them to call the declared "malloc" instead.
79     if (MallocF->getName() != "malloc") {
80       Constant* RealMallocF = M->getFunction("malloc");
81       if (RealMallocF->getType() != MallocF->getType())
82         RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
83       MallocF->replaceAllUsesWith(RealMallocF);
84       MallocF->eraseFromParent();
85       MallocF = NULL;
86     }
87   }
88
89   if (!ForwardRefTypes.empty())
90     return Error(ForwardRefTypes.begin()->second.second,
91                  "use of undefined type named '" +
92                  ForwardRefTypes.begin()->first + "'");
93   if (!ForwardRefTypeIDs.empty())
94     return Error(ForwardRefTypeIDs.begin()->second.second,
95                  "use of undefined type '%" +
96                  utostr(ForwardRefTypeIDs.begin()->first) + "'");
97
98   if (!ForwardRefVals.empty())
99     return Error(ForwardRefVals.begin()->second.second,
100                  "use of undefined value '@" + ForwardRefVals.begin()->first +
101                  "'");
102
103   if (!ForwardRefValIDs.empty())
104     return Error(ForwardRefValIDs.begin()->second.second,
105                  "use of undefined value '@" +
106                  utostr(ForwardRefValIDs.begin()->first) + "'");
107
108   if (!ForwardRefMDNodes.empty())
109     return Error(ForwardRefMDNodes.begin()->second.second,
110                  "use of undefined metadata '!" +
111                  utostr(ForwardRefMDNodes.begin()->first) + "'");
112
113
114   // Look for intrinsic functions and CallInst that need to be upgraded
115   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
116     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
117
118   // Check debug info intrinsics.
119   CheckDebugInfoIntrinsics(M);
120   return false;
121 }
122
123 //===----------------------------------------------------------------------===//
124 // Top-Level Entities
125 //===----------------------------------------------------------------------===//
126
127 bool LLParser::ParseTopLevelEntities() {
128   while (1) {
129     switch (Lex.getKind()) {
130     default:         return TokError("expected top-level entity");
131     case lltok::Eof: return false;
132     //case lltok::kw_define:
133     case lltok::kw_declare: if (ParseDeclare()) return true; break;
134     case lltok::kw_define:  if (ParseDefine()) return true; break;
135     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
136     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
137     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
138     case lltok::kw_type:    if (ParseUnnamedType()) return true; break;
139     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
140     case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
141     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
142     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
143     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
144     case lltok::Metadata:   if (ParseStandaloneMetadata()) return true; break;
145     case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break;
146
147     // The Global variable production with no name can have many different
148     // optional leading prefixes, the production is:
149     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
150     //               OptionalAddrSpace ('constant'|'global') ...
151     case lltok::kw_private :       // OptionalLinkage
152     case lltok::kw_linker_private: // OptionalLinkage
153     case lltok::kw_internal:       // OptionalLinkage
154     case lltok::kw_weak:           // OptionalLinkage
155     case lltok::kw_weak_odr:       // OptionalLinkage
156     case lltok::kw_linkonce:       // OptionalLinkage
157     case lltok::kw_linkonce_odr:   // OptionalLinkage
158     case lltok::kw_appending:      // OptionalLinkage
159     case lltok::kw_dllexport:      // OptionalLinkage
160     case lltok::kw_common:         // OptionalLinkage
161     case lltok::kw_dllimport:      // OptionalLinkage
162     case lltok::kw_extern_weak:    // OptionalLinkage
163     case lltok::kw_external: {     // OptionalLinkage
164       unsigned Linkage, Visibility;
165       if (ParseOptionalLinkage(Linkage) ||
166           ParseOptionalVisibility(Visibility) ||
167           ParseGlobal("", SMLoc(), Linkage, true, Visibility))
168         return true;
169       break;
170     }
171     case lltok::kw_default:       // OptionalVisibility
172     case lltok::kw_hidden:        // OptionalVisibility
173     case lltok::kw_protected: {   // OptionalVisibility
174       unsigned Visibility;
175       if (ParseOptionalVisibility(Visibility) ||
176           ParseGlobal("", SMLoc(), 0, false, Visibility))
177         return true;
178       break;
179     }
180
181     case lltok::kw_thread_local:  // OptionalThreadLocal
182     case lltok::kw_addrspace:     // OptionalAddrSpace
183     case lltok::kw_constant:      // GlobalType
184     case lltok::kw_global:        // GlobalType
185       if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
186       break;
187     }
188   }
189 }
190
191
192 /// toplevelentity
193 ///   ::= 'module' 'asm' STRINGCONSTANT
194 bool LLParser::ParseModuleAsm() {
195   assert(Lex.getKind() == lltok::kw_module);
196   Lex.Lex();
197
198   std::string AsmStr;
199   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
200       ParseStringConstant(AsmStr)) return true;
201
202   const std::string &AsmSoFar = M->getModuleInlineAsm();
203   if (AsmSoFar.empty())
204     M->setModuleInlineAsm(AsmStr);
205   else
206     M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
207   return false;
208 }
209
210 /// toplevelentity
211 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
212 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
213 bool LLParser::ParseTargetDefinition() {
214   assert(Lex.getKind() == lltok::kw_target);
215   std::string Str;
216   switch (Lex.Lex()) {
217   default: return TokError("unknown target property");
218   case lltok::kw_triple:
219     Lex.Lex();
220     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
221         ParseStringConstant(Str))
222       return true;
223     M->setTargetTriple(Str);
224     return false;
225   case lltok::kw_datalayout:
226     Lex.Lex();
227     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
228         ParseStringConstant(Str))
229       return true;
230     M->setDataLayout(Str);
231     return false;
232   }
233 }
234
235 /// toplevelentity
236 ///   ::= 'deplibs' '=' '[' ']'
237 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
238 bool LLParser::ParseDepLibs() {
239   assert(Lex.getKind() == lltok::kw_deplibs);
240   Lex.Lex();
241   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
242       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
243     return true;
244
245   if (EatIfPresent(lltok::rsquare))
246     return false;
247
248   std::string Str;
249   if (ParseStringConstant(Str)) return true;
250   M->addLibrary(Str);
251
252   while (EatIfPresent(lltok::comma)) {
253     if (ParseStringConstant(Str)) return true;
254     M->addLibrary(Str);
255   }
256
257   return ParseToken(lltok::rsquare, "expected ']' at end of list");
258 }
259
260 /// ParseUnnamedType:
261 ///   ::= 'type' type
262 ///   ::= LocalVarID '=' 'type' type
263 bool LLParser::ParseUnnamedType() {
264   unsigned TypeID = NumberedTypes.size();
265
266   // Handle the LocalVarID form.
267   if (Lex.getKind() == lltok::LocalVarID) {
268     if (Lex.getUIntVal() != TypeID)
269       return Error(Lex.getLoc(), "type expected to be numbered '%" +
270                    utostr(TypeID) + "'");
271     Lex.Lex(); // eat LocalVarID;
272
273     if (ParseToken(lltok::equal, "expected '=' after name"))
274       return true;
275   }
276
277   assert(Lex.getKind() == lltok::kw_type);
278   LocTy TypeLoc = Lex.getLoc();
279   Lex.Lex(); // eat kw_type
280
281   PATypeHolder Ty(Type::getVoidTy(Context));
282   if (ParseType(Ty)) return true;
283
284   // See if this type was previously referenced.
285   std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
286     FI = ForwardRefTypeIDs.find(TypeID);
287   if (FI != ForwardRefTypeIDs.end()) {
288     if (FI->second.first.get() == Ty)
289       return Error(TypeLoc, "self referential type is invalid");
290
291     cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
292     Ty = FI->second.first.get();
293     ForwardRefTypeIDs.erase(FI);
294   }
295
296   NumberedTypes.push_back(Ty);
297
298   return false;
299 }
300
301 /// toplevelentity
302 ///   ::= LocalVar '=' 'type' type
303 bool LLParser::ParseNamedType() {
304   std::string Name = Lex.getStrVal();
305   LocTy NameLoc = Lex.getLoc();
306   Lex.Lex();  // eat LocalVar.
307
308   PATypeHolder Ty(Type::getVoidTy(Context));
309
310   if (ParseToken(lltok::equal, "expected '=' after name") ||
311       ParseToken(lltok::kw_type, "expected 'type' after name") ||
312       ParseType(Ty))
313     return true;
314
315   // Set the type name, checking for conflicts as we do so.
316   bool AlreadyExists = M->addTypeName(Name, Ty);
317   if (!AlreadyExists) return false;
318
319   // See if this type is a forward reference.  We need to eagerly resolve
320   // types to allow recursive type redefinitions below.
321   std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
322   FI = ForwardRefTypes.find(Name);
323   if (FI != ForwardRefTypes.end()) {
324     if (FI->second.first.get() == Ty)
325       return Error(NameLoc, "self referential type is invalid");
326
327     cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
328     Ty = FI->second.first.get();
329     ForwardRefTypes.erase(FI);
330   }
331
332   // Inserting a name that is already defined, get the existing name.
333   const Type *Existing = M->getTypeByName(Name);
334   assert(Existing && "Conflict but no matching type?!");
335
336   // Otherwise, this is an attempt to redefine a type. That's okay if
337   // the redefinition is identical to the original.
338   // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
339   if (Existing == Ty) return false;
340
341   // Any other kind of (non-equivalent) redefinition is an error.
342   return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
343                Ty->getDescription() + "'");
344 }
345
346
347 /// toplevelentity
348 ///   ::= 'declare' FunctionHeader
349 bool LLParser::ParseDeclare() {
350   assert(Lex.getKind() == lltok::kw_declare);
351   Lex.Lex();
352
353   Function *F;
354   return ParseFunctionHeader(F, false);
355 }
356
357 /// toplevelentity
358 ///   ::= 'define' FunctionHeader '{' ...
359 bool LLParser::ParseDefine() {
360   assert(Lex.getKind() == lltok::kw_define);
361   Lex.Lex();
362
363   Function *F;
364   return ParseFunctionHeader(F, true) ||
365          ParseFunctionBody(*F);
366 }
367
368 /// ParseGlobalType
369 ///   ::= 'constant'
370 ///   ::= 'global'
371 bool LLParser::ParseGlobalType(bool &IsConstant) {
372   if (Lex.getKind() == lltok::kw_constant)
373     IsConstant = true;
374   else if (Lex.getKind() == lltok::kw_global)
375     IsConstant = false;
376   else {
377     IsConstant = false;
378     return TokError("expected 'global' or 'constant'");
379   }
380   Lex.Lex();
381   return false;
382 }
383
384 /// ParseUnnamedGlobal:
385 ///   OptionalVisibility ALIAS ...
386 ///   OptionalLinkage OptionalVisibility ...   -> global variable
387 ///   GlobalID '=' OptionalVisibility ALIAS ...
388 ///   GlobalID '=' OptionalLinkage OptionalVisibility ...   -> global variable
389 bool LLParser::ParseUnnamedGlobal() {
390   unsigned VarID = NumberedVals.size();
391   std::string Name;
392   LocTy NameLoc = Lex.getLoc();
393
394   // Handle the GlobalID form.
395   if (Lex.getKind() == lltok::GlobalID) {
396     if (Lex.getUIntVal() != VarID)
397       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
398                    utostr(VarID) + "'");
399     Lex.Lex(); // eat GlobalID;
400
401     if (ParseToken(lltok::equal, "expected '=' after name"))
402       return true;
403   }
404
405   bool HasLinkage;
406   unsigned Linkage, Visibility;
407   if (ParseOptionalLinkage(Linkage, HasLinkage) ||
408       ParseOptionalVisibility(Visibility))
409     return true;
410
411   if (HasLinkage || Lex.getKind() != lltok::kw_alias)
412     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
413   return ParseAlias(Name, NameLoc, Visibility);
414 }
415
416 /// ParseNamedGlobal:
417 ///   GlobalVar '=' OptionalVisibility ALIAS ...
418 ///   GlobalVar '=' OptionalLinkage OptionalVisibility ...   -> global variable
419 bool LLParser::ParseNamedGlobal() {
420   assert(Lex.getKind() == lltok::GlobalVar);
421   LocTy NameLoc = Lex.getLoc();
422   std::string Name = Lex.getStrVal();
423   Lex.Lex();
424
425   bool HasLinkage;
426   unsigned Linkage, Visibility;
427   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
428       ParseOptionalLinkage(Linkage, HasLinkage) ||
429       ParseOptionalVisibility(Visibility))
430     return true;
431
432   if (HasLinkage || Lex.getKind() != lltok::kw_alias)
433     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
434   return ParseAlias(Name, NameLoc, Visibility);
435 }
436
437 // MDString:
438 //   ::= '!' STRINGCONSTANT
439 bool LLParser::ParseMDString(MetadataBase *&MDS) {
440   std::string Str;
441   if (ParseStringConstant(Str)) return true;
442   MDS = MDString::get(Context, Str);
443   return false;
444 }
445
446 // MDNode:
447 //   ::= '!' MDNodeNumber
448 bool LLParser::ParseMDNode(MetadataBase *&Node) {
449   // !{ ..., !42, ... }
450   unsigned MID = 0;
451   if (ParseUInt32(MID))  return true;
452
453   // Check existing MDNode.
454   std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
455   if (I != MetadataCache.end()) {
456     Node = I->second;
457     return false;
458   }
459
460   // Check known forward references.
461   std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
462     FI = ForwardRefMDNodes.find(MID);
463   if (FI != ForwardRefMDNodes.end()) {
464     Node = FI->second.first;
465     return false;
466   }
467
468   // Create MDNode forward reference
469   SmallVector<Value *, 1> Elts;
470   std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
471   Elts.push_back(MDString::get(Context, FwdRefName));
472   MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
473   ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
474   Node = FwdNode;
475   return false;
476 }
477
478 ///ParseNamedMetadata:
479 ///   !foo = !{ !1, !2 }
480 bool LLParser::ParseNamedMetadata() {
481   assert(Lex.getKind() == lltok::NamedOrCustomMD);
482   Lex.Lex();
483   std::string Name = Lex.getStrVal();
484
485   if (ParseToken(lltok::equal, "expected '=' here"))
486     return true;
487
488   if (Lex.getKind() != lltok::Metadata)
489     return TokError("Expected '!' here");
490   Lex.Lex();
491
492   if (Lex.getKind() != lltok::lbrace)
493     return TokError("Expected '{' here");
494   Lex.Lex();
495   SmallVector<MetadataBase *, 8> Elts;
496   do {
497     if (Lex.getKind() != lltok::Metadata)
498       return TokError("Expected '!' here");
499     Lex.Lex();
500     MetadataBase *N = 0;
501     if (ParseMDNode(N)) return true;
502     Elts.push_back(N);
503   } while (EatIfPresent(lltok::comma));
504
505   if (ParseToken(lltok::rbrace, "expected end of metadata node"))
506     return true;
507
508   NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
509   return false;
510 }
511
512 /// ParseStandaloneMetadata:
513 ///   !42 = !{...}
514 bool LLParser::ParseStandaloneMetadata() {
515   assert(Lex.getKind() == lltok::Metadata);
516   Lex.Lex();
517   unsigned MetadataID = 0;
518   if (ParseUInt32(MetadataID))
519     return true;
520   if (MetadataCache.find(MetadataID) != MetadataCache.end())
521     return TokError("Metadata id is already used");
522   if (ParseToken(lltok::equal, "expected '=' here"))
523     return true;
524
525   LocTy TyLoc;
526   PATypeHolder Ty(Type::getVoidTy(Context));
527   if (ParseType(Ty, TyLoc))
528     return true;
529
530   if (Lex.getKind() != lltok::Metadata)
531     return TokError("Expected metadata here");
532
533   Lex.Lex();
534   if (Lex.getKind() != lltok::lbrace)
535     return TokError("Expected '{' here");
536
537   SmallVector<Value *, 16> Elts;
538   if (ParseMDNodeVector(Elts)
539       || ParseToken(lltok::rbrace, "expected end of metadata node"))
540     return true;
541
542   MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
543   MetadataCache[MetadataID] = Init;
544   std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
545     FI = ForwardRefMDNodes.find(MetadataID);
546   if (FI != ForwardRefMDNodes.end()) {
547     MDNode *FwdNode = cast<MDNode>(FI->second.first);
548     FwdNode->replaceAllUsesWith(Init);
549     ForwardRefMDNodes.erase(FI);
550   }
551
552   return false;
553 }
554
555 /// ParseAlias:
556 ///   ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
557 /// Aliasee
558 ///   ::= TypeAndValue
559 ///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
560 ///   ::= 'getelementptr' 'inbounds'? '(' ... ')'
561 ///
562 /// Everything through visibility has already been parsed.
563 ///
564 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
565                           unsigned Visibility) {
566   assert(Lex.getKind() == lltok::kw_alias);
567   Lex.Lex();
568   unsigned Linkage;
569   LocTy LinkageLoc = Lex.getLoc();
570   if (ParseOptionalLinkage(Linkage))
571     return true;
572
573   if (Linkage != GlobalValue::ExternalLinkage &&
574       Linkage != GlobalValue::WeakAnyLinkage &&
575       Linkage != GlobalValue::WeakODRLinkage &&
576       Linkage != GlobalValue::InternalLinkage &&
577       Linkage != GlobalValue::PrivateLinkage &&
578       Linkage != GlobalValue::LinkerPrivateLinkage)
579     return Error(LinkageLoc, "invalid linkage type for alias");
580
581   Constant *Aliasee;
582   LocTy AliaseeLoc = Lex.getLoc();
583   if (Lex.getKind() != lltok::kw_bitcast &&
584       Lex.getKind() != lltok::kw_getelementptr) {
585     if (ParseGlobalTypeAndValue(Aliasee)) return true;
586   } else {
587     // The bitcast dest type is not present, it is implied by the dest type.
588     ValID ID;
589     if (ParseValID(ID)) return true;
590     if (ID.Kind != ValID::t_Constant)
591       return Error(AliaseeLoc, "invalid aliasee");
592     Aliasee = ID.ConstantVal;
593   }
594
595   if (!isa<PointerType>(Aliasee->getType()))
596     return Error(AliaseeLoc, "alias must have pointer type");
597
598   // Okay, create the alias but do not insert it into the module yet.
599   GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
600                                     (GlobalValue::LinkageTypes)Linkage, Name,
601                                     Aliasee);
602   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
603
604   // See if this value already exists in the symbol table.  If so, it is either
605   // a redefinition or a definition of a forward reference.
606   if (GlobalValue *Val = M->getNamedValue(Name)) {
607     // See if this was a redefinition.  If so, there is no entry in
608     // ForwardRefVals.
609     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
610       I = ForwardRefVals.find(Name);
611     if (I == ForwardRefVals.end())
612       return Error(NameLoc, "redefinition of global named '@" + Name + "'");
613
614     // Otherwise, this was a definition of forward ref.  Verify that types
615     // agree.
616     if (Val->getType() != GA->getType())
617       return Error(NameLoc,
618               "forward reference and definition of alias have different types");
619
620     // If they agree, just RAUW the old value with the alias and remove the
621     // forward ref info.
622     Val->replaceAllUsesWith(GA);
623     Val->eraseFromParent();
624     ForwardRefVals.erase(I);
625   }
626
627   // Insert into the module, we know its name won't collide now.
628   M->getAliasList().push_back(GA);
629   assert(GA->getNameStr() == Name && "Should not be a name conflict!");
630
631   return false;
632 }
633
634 /// ParseGlobal
635 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
636 ///       OptionalAddrSpace GlobalType Type Const
637 ///   ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
638 ///       OptionalAddrSpace GlobalType Type Const
639 ///
640 /// Everything through visibility has been parsed already.
641 ///
642 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
643                            unsigned Linkage, bool HasLinkage,
644                            unsigned Visibility) {
645   unsigned AddrSpace;
646   bool ThreadLocal, IsConstant;
647   LocTy TyLoc;
648
649   PATypeHolder Ty(Type::getVoidTy(Context));
650   if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
651       ParseOptionalAddrSpace(AddrSpace) ||
652       ParseGlobalType(IsConstant) ||
653       ParseType(Ty, TyLoc))
654     return true;
655
656   // If the linkage is specified and is external, then no initializer is
657   // present.
658   Constant *Init = 0;
659   if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
660                       Linkage != GlobalValue::ExternalWeakLinkage &&
661                       Linkage != GlobalValue::ExternalLinkage)) {
662     if (ParseGlobalValue(Ty, Init))
663       return true;
664   }
665
666   if (isa<FunctionType>(Ty) || Ty->isLabelTy())
667     return Error(TyLoc, "invalid type for global variable");
668
669   GlobalVariable *GV = 0;
670
671   // See if the global was forward referenced, if so, use the global.
672   if (!Name.empty()) {
673     if (GlobalValue *GVal = M->getNamedValue(Name)) {
674       if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
675         return Error(NameLoc, "redefinition of global '@" + Name + "'");
676       GV = cast<GlobalVariable>(GVal);
677     }
678   } else {
679     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
680       I = ForwardRefValIDs.find(NumberedVals.size());
681     if (I != ForwardRefValIDs.end()) {
682       GV = cast<GlobalVariable>(I->second.first);
683       ForwardRefValIDs.erase(I);
684     }
685   }
686
687   if (GV == 0) {
688     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
689                             Name, 0, false, AddrSpace);
690   } else {
691     if (GV->getType()->getElementType() != Ty)
692       return Error(TyLoc,
693             "forward reference and definition of global have different types");
694
695     // Move the forward-reference to the correct spot in the module.
696     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
697   }
698
699   if (Name.empty())
700     NumberedVals.push_back(GV);
701
702   // Set the parsed properties on the global.
703   if (Init)
704     GV->setInitializer(Init);
705   GV->setConstant(IsConstant);
706   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
707   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
708   GV->setThreadLocal(ThreadLocal);
709
710   // Parse attributes on the global.
711   while (Lex.getKind() == lltok::comma) {
712     Lex.Lex();
713
714     if (Lex.getKind() == lltok::kw_section) {
715       Lex.Lex();
716       GV->setSection(Lex.getStrVal());
717       if (ParseToken(lltok::StringConstant, "expected global section string"))
718         return true;
719     } else if (Lex.getKind() == lltok::kw_align) {
720       unsigned Alignment;
721       if (ParseOptionalAlignment(Alignment)) return true;
722       GV->setAlignment(Alignment);
723     } else {
724       TokError("unknown global variable property!");
725     }
726   }
727
728   return false;
729 }
730
731
732 //===----------------------------------------------------------------------===//
733 // GlobalValue Reference/Resolution Routines.
734 //===----------------------------------------------------------------------===//
735
736 /// GetGlobalVal - Get a value with the specified name or ID, creating a
737 /// forward reference record if needed.  This can return null if the value
738 /// exists but does not have the right type.
739 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
740                                     LocTy Loc) {
741   const PointerType *PTy = dyn_cast<PointerType>(Ty);
742   if (PTy == 0) {
743     Error(Loc, "global variable reference must have pointer type");
744     return 0;
745   }
746
747   // Look this name up in the normal function symbol table.
748   GlobalValue *Val =
749     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
750
751   // If this is a forward reference for the value, see if we already created a
752   // forward ref record.
753   if (Val == 0) {
754     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
755       I = ForwardRefVals.find(Name);
756     if (I != ForwardRefVals.end())
757       Val = I->second.first;
758   }
759
760   // If we have the value in the symbol table or fwd-ref table, return it.
761   if (Val) {
762     if (Val->getType() == Ty) return Val;
763     Error(Loc, "'@" + Name + "' defined with type '" +
764           Val->getType()->getDescription() + "'");
765     return 0;
766   }
767
768   // Otherwise, create a new forward reference for this value and remember it.
769   GlobalValue *FwdVal;
770   if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
771     // Function types can return opaque but functions can't.
772     if (isa<OpaqueType>(FT->getReturnType())) {
773       Error(Loc, "function may not return opaque type");
774       return 0;
775     }
776
777     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
778   } else {
779     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
780                                 GlobalValue::ExternalWeakLinkage, 0, Name);
781   }
782
783   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
784   return FwdVal;
785 }
786
787 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
788   const PointerType *PTy = dyn_cast<PointerType>(Ty);
789   if (PTy == 0) {
790     Error(Loc, "global variable reference must have pointer type");
791     return 0;
792   }
793
794   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
795
796   // If this is a forward reference for the value, see if we already created a
797   // forward ref record.
798   if (Val == 0) {
799     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
800       I = ForwardRefValIDs.find(ID);
801     if (I != ForwardRefValIDs.end())
802       Val = I->second.first;
803   }
804
805   // If we have the value in the symbol table or fwd-ref table, return it.
806   if (Val) {
807     if (Val->getType() == Ty) return Val;
808     Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
809           Val->getType()->getDescription() + "'");
810     return 0;
811   }
812
813   // Otherwise, create a new forward reference for this value and remember it.
814   GlobalValue *FwdVal;
815   if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
816     // Function types can return opaque but functions can't.
817     if (isa<OpaqueType>(FT->getReturnType())) {
818       Error(Loc, "function may not return opaque type");
819       return 0;
820     }
821     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
822   } else {
823     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
824                                 GlobalValue::ExternalWeakLinkage, 0, "");
825   }
826
827   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
828   return FwdVal;
829 }
830
831
832 //===----------------------------------------------------------------------===//
833 // Helper Routines.
834 //===----------------------------------------------------------------------===//
835
836 /// ParseToken - If the current token has the specified kind, eat it and return
837 /// success.  Otherwise, emit the specified error and return failure.
838 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
839   if (Lex.getKind() != T)
840     return TokError(ErrMsg);
841   Lex.Lex();
842   return false;
843 }
844
845 /// ParseStringConstant
846 ///   ::= StringConstant
847 bool LLParser::ParseStringConstant(std::string &Result) {
848   if (Lex.getKind() != lltok::StringConstant)
849     return TokError("expected string constant");
850   Result = Lex.getStrVal();
851   Lex.Lex();
852   return false;
853 }
854
855 /// ParseUInt32
856 ///   ::= uint32
857 bool LLParser::ParseUInt32(unsigned &Val) {
858   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
859     return TokError("expected integer");
860   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
861   if (Val64 != unsigned(Val64))
862     return TokError("expected 32-bit integer (too large)");
863   Val = Val64;
864   Lex.Lex();
865   return false;
866 }
867
868
869 /// ParseOptionalAddrSpace
870 ///   := /*empty*/
871 ///   := 'addrspace' '(' uint32 ')'
872 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
873   AddrSpace = 0;
874   if (!EatIfPresent(lltok::kw_addrspace))
875     return false;
876   return ParseToken(lltok::lparen, "expected '(' in address space") ||
877          ParseUInt32(AddrSpace) ||
878          ParseToken(lltok::rparen, "expected ')' in address space");
879 }
880
881 /// ParseOptionalAttrs - Parse a potentially empty attribute list.  AttrKind
882 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
883 /// 2: function attr.
884 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
885 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
886   Attrs = Attribute::None;
887   LocTy AttrLoc = Lex.getLoc();
888
889   while (1) {
890     switch (Lex.getKind()) {
891     case lltok::kw_sext:
892     case lltok::kw_zext:
893       // Treat these as signext/zeroext if they occur in the argument list after
894       // the value, as in "call i8 @foo(i8 10 sext)".  If they occur before the
895       // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
896       // expr.
897       // FIXME: REMOVE THIS IN LLVM 3.0
898       if (AttrKind == 3) {
899         if (Lex.getKind() == lltok::kw_sext)
900           Attrs |= Attribute::SExt;
901         else
902           Attrs |= Attribute::ZExt;
903         break;
904       }
905       // FALL THROUGH.
906     default:  // End of attributes.
907       if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
908         return Error(AttrLoc, "invalid use of function-only attribute");
909
910       if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
911         return Error(AttrLoc, "invalid use of parameter-only attribute");
912
913       return false;
914     case lltok::kw_zeroext:         Attrs |= Attribute::ZExt; break;
915     case lltok::kw_signext:         Attrs |= Attribute::SExt; break;
916     case lltok::kw_inreg:           Attrs |= Attribute::InReg; break;
917     case lltok::kw_sret:            Attrs |= Attribute::StructRet; break;
918     case lltok::kw_noalias:         Attrs |= Attribute::NoAlias; break;
919     case lltok::kw_nocapture:       Attrs |= Attribute::NoCapture; break;
920     case lltok::kw_byval:           Attrs |= Attribute::ByVal; break;
921     case lltok::kw_nest:            Attrs |= Attribute::Nest; break;
922
923     case lltok::kw_noreturn:        Attrs |= Attribute::NoReturn; break;
924     case lltok::kw_nounwind:        Attrs |= Attribute::NoUnwind; break;
925     case lltok::kw_noinline:        Attrs |= Attribute::NoInline; break;
926     case lltok::kw_readnone:        Attrs |= Attribute::ReadNone; break;
927     case lltok::kw_readonly:        Attrs |= Attribute::ReadOnly; break;
928     case lltok::kw_inlinehint:      Attrs |= Attribute::InlineHint; break;
929     case lltok::kw_alwaysinline:    Attrs |= Attribute::AlwaysInline; break;
930     case lltok::kw_optsize:         Attrs |= Attribute::OptimizeForSize; break;
931     case lltok::kw_ssp:             Attrs |= Attribute::StackProtect; break;
932     case lltok::kw_sspreq:          Attrs |= Attribute::StackProtectReq; break;
933     case lltok::kw_noredzone:       Attrs |= Attribute::NoRedZone; break;
934     case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
935     case lltok::kw_naked:           Attrs |= Attribute::Naked; break;
936
937     case lltok::kw_align: {
938       unsigned Alignment;
939       if (ParseOptionalAlignment(Alignment))
940         return true;
941       Attrs |= Attribute::constructAlignmentFromInt(Alignment);
942       continue;
943     }
944     }
945     Lex.Lex();
946   }
947 }
948
949 /// ParseOptionalLinkage
950 ///   ::= /*empty*/
951 ///   ::= 'private'
952 ///   ::= 'linker_private'
953 ///   ::= 'internal'
954 ///   ::= 'weak'
955 ///   ::= 'weak_odr'
956 ///   ::= 'linkonce'
957 ///   ::= 'linkonce_odr'
958 ///   ::= 'appending'
959 ///   ::= 'dllexport'
960 ///   ::= 'common'
961 ///   ::= 'dllimport'
962 ///   ::= 'extern_weak'
963 ///   ::= 'external'
964 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
965   HasLinkage = false;
966   switch (Lex.getKind()) {
967   default:                       Res=GlobalValue::ExternalLinkage; return false;
968   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
969   case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
970   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
971   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
972   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
973   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
974   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
975   case lltok::kw_available_externally:
976     Res = GlobalValue::AvailableExternallyLinkage;
977     break;
978   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
979   case lltok::kw_dllexport:      Res = GlobalValue::DLLExportLinkage;     break;
980   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
981   case lltok::kw_dllimport:      Res = GlobalValue::DLLImportLinkage;     break;
982   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
983   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
984   }
985   Lex.Lex();
986   HasLinkage = true;
987   return false;
988 }
989
990 /// ParseOptionalVisibility
991 ///   ::= /*empty*/
992 ///   ::= 'default'
993 ///   ::= 'hidden'
994 ///   ::= 'protected'
995 ///
996 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
997   switch (Lex.getKind()) {
998   default:                  Res = GlobalValue::DefaultVisibility; return false;
999   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
1000   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
1001   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1002   }
1003   Lex.Lex();
1004   return false;
1005 }
1006
1007 /// ParseOptionalCallingConv
1008 ///   ::= /*empty*/
1009 ///   ::= 'ccc'
1010 ///   ::= 'fastcc'
1011 ///   ::= 'coldcc'
1012 ///   ::= 'x86_stdcallcc'
1013 ///   ::= 'x86_fastcallcc'
1014 ///   ::= 'arm_apcscc'
1015 ///   ::= 'arm_aapcscc'
1016 ///   ::= 'arm_aapcs_vfpcc'
1017 ///   ::= 'cc' UINT
1018 ///
1019 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1020   switch (Lex.getKind()) {
1021   default:                       CC = CallingConv::C; return false;
1022   case lltok::kw_ccc:            CC = CallingConv::C; break;
1023   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1024   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1025   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1026   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1027   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1028   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1029   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1030   case lltok::kw_cc: {
1031       unsigned ArbitraryCC;
1032       Lex.Lex();
1033       if (ParseUInt32(ArbitraryCC)) {
1034         return true;
1035       } else
1036         CC = static_cast<CallingConv::ID>(ArbitraryCC);
1037         return false;
1038     }
1039     break;
1040   }
1041
1042   Lex.Lex();
1043   return false;
1044 }
1045
1046 /// ParseOptionalCustomMetadata
1047 ///   ::= /* empty */
1048 ///   ::= !dbg !42
1049 bool LLParser::ParseOptionalCustomMetadata() {
1050   if (Lex.getKind() != lltok::NamedOrCustomMD)
1051     return false;
1052
1053   std::string Name = Lex.getStrVal();
1054   Lex.Lex();
1055
1056   if (Lex.getKind() != lltok::Metadata)
1057     return TokError("Expected '!' here");
1058   Lex.Lex();
1059
1060   MetadataBase *Node;
1061   if (ParseMDNode(Node)) return true;
1062
1063   MetadataContext &TheMetadata = M->getContext().getMetadata();
1064   unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1065   if (!MDK)
1066     MDK = TheMetadata.registerMDKind(Name.c_str());
1067   MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
1068
1069   return false;
1070 }
1071
1072 /// ParseOptionalAlignment
1073 ///   ::= /* empty */
1074 ///   ::= 'align' 4
1075 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1076   Alignment = 0;
1077   if (!EatIfPresent(lltok::kw_align))
1078     return false;
1079   LocTy AlignLoc = Lex.getLoc();
1080   if (ParseUInt32(Alignment)) return true;
1081   if (!isPowerOf2_32(Alignment))
1082     return Error(AlignLoc, "alignment is not a power of two");
1083   return false;
1084 }
1085
1086 /// ParseOptionalInfo
1087 ///   ::= OptionalInfo (',' OptionalInfo)+
1088 bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1089
1090   // FIXME: Handle customized metadata info attached with an instruction.
1091   do {
1092       if (Lex.getKind() == lltok::NamedOrCustomMD) {
1093       if (ParseOptionalCustomMetadata()) return true;
1094     } else if (Lex.getKind() == lltok::kw_align) {
1095       if (ParseOptionalAlignment(Alignment)) return true;
1096     } else
1097       return true;
1098   } while (EatIfPresent(lltok::comma));
1099
1100   return false;
1101 }
1102
1103
1104 /// ParseIndexList
1105 ///    ::=  (',' uint32)+
1106 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1107   if (Lex.getKind() != lltok::comma)
1108     return TokError("expected ',' as start of index list");
1109
1110   while (EatIfPresent(lltok::comma)) {
1111     unsigned Idx;
1112     if (ParseUInt32(Idx)) return true;
1113     Indices.push_back(Idx);
1114   }
1115
1116   return false;
1117 }
1118
1119 //===----------------------------------------------------------------------===//
1120 // Type Parsing.
1121 //===----------------------------------------------------------------------===//
1122
1123 /// ParseType - Parse and resolve a full type.
1124 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1125   LocTy TypeLoc = Lex.getLoc();
1126   if (ParseTypeRec(Result)) return true;
1127
1128   // Verify no unresolved uprefs.
1129   if (!UpRefs.empty())
1130     return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1131
1132   if (!AllowVoid && Result.get()->isVoidTy())
1133     return Error(TypeLoc, "void type only allowed for function results");
1134
1135   return false;
1136 }
1137
1138 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1139 /// called.  It loops through the UpRefs vector, which is a list of the
1140 /// currently active types.  For each type, if the up-reference is contained in
1141 /// the newly completed type, we decrement the level count.  When the level
1142 /// count reaches zero, the up-referenced type is the type that is passed in:
1143 /// thus we can complete the cycle.
1144 ///
1145 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1146   // If Ty isn't abstract, or if there are no up-references in it, then there is
1147   // nothing to resolve here.
1148   if (!ty->isAbstract() || UpRefs.empty()) return ty;
1149
1150   PATypeHolder Ty(ty);
1151 #if 0
1152   errs() << "Type '" << Ty->getDescription()
1153          << "' newly formed.  Resolving upreferences.\n"
1154          << UpRefs.size() << " upreferences active!\n";
1155 #endif
1156
1157   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1158   // to zero), we resolve them all together before we resolve them to Ty.  At
1159   // the end of the loop, if there is anything to resolve to Ty, it will be in
1160   // this variable.
1161   OpaqueType *TypeToResolve = 0;
1162
1163   for (unsigned i = 0; i != UpRefs.size(); ++i) {
1164     // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1165     bool ContainsType =
1166       std::find(Ty->subtype_begin(), Ty->subtype_end(),
1167                 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1168
1169 #if 0
1170     errs() << "  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1171            << UpRefs[i].LastContainedTy->getDescription() << ") = "
1172            << (ContainsType ? "true" : "false")
1173            << " level=" << UpRefs[i].NestingLevel << "\n";
1174 #endif
1175     if (!ContainsType)
1176       continue;
1177
1178     // Decrement level of upreference
1179     unsigned Level = --UpRefs[i].NestingLevel;
1180     UpRefs[i].LastContainedTy = Ty;
1181
1182     // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1183     if (Level != 0)
1184       continue;
1185
1186 #if 0
1187     errs() << "  * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1188 #endif
1189     if (!TypeToResolve)
1190       TypeToResolve = UpRefs[i].UpRefTy;
1191     else
1192       UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1193     UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list.
1194     --i;                                // Do not skip the next element.
1195   }
1196
1197   if (TypeToResolve)
1198     TypeToResolve->refineAbstractTypeTo(Ty);
1199
1200   return Ty;
1201 }
1202
1203
1204 /// ParseTypeRec - The recursive function used to process the internal
1205 /// implementation details of types.
1206 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1207   switch (Lex.getKind()) {
1208   default:
1209     return TokError("expected type");
1210   case lltok::Type:
1211     // TypeRec ::= 'float' | 'void' (etc)
1212     Result = Lex.getTyVal();
1213     Lex.Lex();
1214     break;
1215   case lltok::kw_opaque:
1216     // TypeRec ::= 'opaque'
1217     Result = OpaqueType::get(Context);
1218     Lex.Lex();
1219     break;
1220   case lltok::lbrace:
1221     // TypeRec ::= '{' ... '}'
1222     if (ParseStructType(Result, false))
1223       return true;
1224     break;
1225   case lltok::lsquare:
1226     // TypeRec ::= '[' ... ']'
1227     Lex.Lex(); // eat the lsquare.
1228     if (ParseArrayVectorType(Result, false))
1229       return true;
1230     break;
1231   case lltok::less: // Either vector or packed struct.
1232     // TypeRec ::= '<' ... '>'
1233     Lex.Lex();
1234     if (Lex.getKind() == lltok::lbrace) {
1235       if (ParseStructType(Result, true) ||
1236           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1237         return true;
1238     } else if (ParseArrayVectorType(Result, true))
1239       return true;
1240     break;
1241   case lltok::LocalVar:
1242   case lltok::StringConstant:  // FIXME: REMOVE IN LLVM 3.0
1243     // TypeRec ::= %foo
1244     if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1245       Result = T;
1246     } else {
1247       Result = OpaqueType::get(Context);
1248       ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1249                                             std::make_pair(Result,
1250                                                            Lex.getLoc())));
1251       M->addTypeName(Lex.getStrVal(), Result.get());
1252     }
1253     Lex.Lex();
1254     break;
1255
1256   case lltok::LocalVarID:
1257     // TypeRec ::= %4
1258     if (Lex.getUIntVal() < NumberedTypes.size())
1259       Result = NumberedTypes[Lex.getUIntVal()];
1260     else {
1261       std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1262         I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1263       if (I != ForwardRefTypeIDs.end())
1264         Result = I->second.first;
1265       else {
1266         Result = OpaqueType::get(Context);
1267         ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1268                                                 std::make_pair(Result,
1269                                                                Lex.getLoc())));
1270       }
1271     }
1272     Lex.Lex();
1273     break;
1274   case lltok::backslash: {
1275     // TypeRec ::= '\' 4
1276     Lex.Lex();
1277     unsigned Val;
1278     if (ParseUInt32(Val)) return true;
1279     OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1280     UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1281     Result = OT;
1282     break;
1283   }
1284   }
1285
1286   // Parse the type suffixes.
1287   while (1) {
1288     switch (Lex.getKind()) {
1289     // End of type.
1290     default: return false;
1291
1292     // TypeRec ::= TypeRec '*'
1293     case lltok::star:
1294       if (Result.get()->isLabelTy())
1295         return TokError("basic block pointers are invalid");
1296       if (Result.get()->isVoidTy())
1297         return TokError("pointers to void are invalid; use i8* instead");
1298       if (!PointerType::isValidElementType(Result.get()))
1299         return TokError("pointer to this type is invalid");
1300       Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1301       Lex.Lex();
1302       break;
1303
1304     // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1305     case lltok::kw_addrspace: {
1306       if (Result.get()->isLabelTy())
1307         return TokError("basic block pointers are invalid");
1308       if (Result.get()->isVoidTy())
1309         return TokError("pointers to void are invalid; use i8* instead");
1310       if (!PointerType::isValidElementType(Result.get()))
1311         return TokError("pointer to this type is invalid");
1312       unsigned AddrSpace;
1313       if (ParseOptionalAddrSpace(AddrSpace) ||
1314           ParseToken(lltok::star, "expected '*' in address space"))
1315         return true;
1316
1317       Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1318       break;
1319     }
1320
1321     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1322     case lltok::lparen:
1323       if (ParseFunctionType(Result))
1324         return true;
1325       break;
1326     }
1327   }
1328 }
1329
1330 /// ParseParameterList
1331 ///    ::= '(' ')'
1332 ///    ::= '(' Arg (',' Arg)* ')'
1333 ///  Arg
1334 ///    ::= Type OptionalAttributes Value OptionalAttributes
1335 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1336                                   PerFunctionState &PFS) {
1337   if (ParseToken(lltok::lparen, "expected '(' in call"))
1338     return true;
1339
1340   while (Lex.getKind() != lltok::rparen) {
1341     // If this isn't the first argument, we need a comma.
1342     if (!ArgList.empty() &&
1343         ParseToken(lltok::comma, "expected ',' in argument list"))
1344       return true;
1345
1346     // Parse the argument.
1347     LocTy ArgLoc;
1348     PATypeHolder ArgTy(Type::getVoidTy(Context));
1349     unsigned ArgAttrs1, ArgAttrs2;
1350     Value *V;
1351     if (ParseType(ArgTy, ArgLoc) ||
1352         ParseOptionalAttrs(ArgAttrs1, 0) ||
1353         ParseValue(ArgTy, V, PFS) ||
1354         // FIXME: Should not allow attributes after the argument, remove this in
1355         // LLVM 3.0.
1356         ParseOptionalAttrs(ArgAttrs2, 3))
1357       return true;
1358     ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1359   }
1360
1361   Lex.Lex();  // Lex the ')'.
1362   return false;
1363 }
1364
1365
1366
1367 /// ParseArgumentList - Parse the argument list for a function type or function
1368 /// prototype.  If 'inType' is true then we are parsing a FunctionType.
1369 ///   ::= '(' ArgTypeListI ')'
1370 /// ArgTypeListI
1371 ///   ::= /*empty*/
1372 ///   ::= '...'
1373 ///   ::= ArgTypeList ',' '...'
1374 ///   ::= ArgType (',' ArgType)*
1375 ///
1376 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1377                                  bool &isVarArg, bool inType) {
1378   isVarArg = false;
1379   assert(Lex.getKind() == lltok::lparen);
1380   Lex.Lex(); // eat the (.
1381
1382   if (Lex.getKind() == lltok::rparen) {
1383     // empty
1384   } else if (Lex.getKind() == lltok::dotdotdot) {
1385     isVarArg = true;
1386     Lex.Lex();
1387   } else {
1388     LocTy TypeLoc = Lex.getLoc();
1389     PATypeHolder ArgTy(Type::getVoidTy(Context));
1390     unsigned Attrs;
1391     std::string Name;
1392
1393     // If we're parsing a type, use ParseTypeRec, because we allow recursive
1394     // types (such as a function returning a pointer to itself).  If parsing a
1395     // function prototype, we require fully resolved types.
1396     if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1397         ParseOptionalAttrs(Attrs, 0)) return true;
1398
1399     if (ArgTy->isVoidTy())
1400       return Error(TypeLoc, "argument can not have void type");
1401
1402     if (Lex.getKind() == lltok::LocalVar ||
1403         Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1404       Name = Lex.getStrVal();
1405       Lex.Lex();
1406     }
1407
1408     if (!FunctionType::isValidArgumentType(ArgTy))
1409       return Error(TypeLoc, "invalid type for function argument");
1410
1411     ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1412
1413     while (EatIfPresent(lltok::comma)) {
1414       // Handle ... at end of arg list.
1415       if (EatIfPresent(lltok::dotdotdot)) {
1416         isVarArg = true;
1417         break;
1418       }
1419
1420       // Otherwise must be an argument type.
1421       TypeLoc = Lex.getLoc();
1422       if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1423           ParseOptionalAttrs(Attrs, 0)) return true;
1424
1425       if (ArgTy->isVoidTy())
1426         return Error(TypeLoc, "argument can not have void type");
1427
1428       if (Lex.getKind() == lltok::LocalVar ||
1429           Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1430         Name = Lex.getStrVal();
1431         Lex.Lex();
1432       } else {
1433         Name = "";
1434       }
1435
1436       if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1437         return Error(TypeLoc, "invalid type for function argument");
1438
1439       ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1440     }
1441   }
1442
1443   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1444 }
1445
1446 /// ParseFunctionType
1447 ///  ::= Type ArgumentList OptionalAttrs
1448 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1449   assert(Lex.getKind() == lltok::lparen);
1450
1451   if (!FunctionType::isValidReturnType(Result))
1452     return TokError("invalid function return type");
1453
1454   std::vector<ArgInfo> ArgList;
1455   bool isVarArg;
1456   unsigned Attrs;
1457   if (ParseArgumentList(ArgList, isVarArg, true) ||
1458       // FIXME: Allow, but ignore attributes on function types!
1459       // FIXME: Remove in LLVM 3.0
1460       ParseOptionalAttrs(Attrs, 2))
1461     return true;
1462
1463   // Reject names on the arguments lists.
1464   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1465     if (!ArgList[i].Name.empty())
1466       return Error(ArgList[i].Loc, "argument name invalid in function type");
1467     if (!ArgList[i].Attrs != 0) {
1468       // Allow but ignore attributes on function types; this permits
1469       // auto-upgrade.
1470       // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1471     }
1472   }
1473
1474   std::vector<const Type*> ArgListTy;
1475   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1476     ArgListTy.push_back(ArgList[i].Type);
1477
1478   Result = HandleUpRefs(FunctionType::get(Result.get(),
1479                                                 ArgListTy, isVarArg));
1480   return false;
1481 }
1482
1483 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1484 ///   TypeRec
1485 ///     ::= '{' '}'
1486 ///     ::= '{' TypeRec (',' TypeRec)* '}'
1487 ///     ::= '<' '{' '}' '>'
1488 ///     ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1489 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1490   assert(Lex.getKind() == lltok::lbrace);
1491   Lex.Lex(); // Consume the '{'
1492
1493   if (EatIfPresent(lltok::rbrace)) {
1494     Result = StructType::get(Context, Packed);
1495     return false;
1496   }
1497
1498   std::vector<PATypeHolder> ParamsList;
1499   LocTy EltTyLoc = Lex.getLoc();
1500   if (ParseTypeRec(Result)) return true;
1501   ParamsList.push_back(Result);
1502
1503   if (Result->isVoidTy())
1504     return Error(EltTyLoc, "struct element can not have void type");
1505   if (!StructType::isValidElementType(Result))
1506     return Error(EltTyLoc, "invalid element type for struct");
1507
1508   while (EatIfPresent(lltok::comma)) {
1509     EltTyLoc = Lex.getLoc();
1510     if (ParseTypeRec(Result)) return true;
1511
1512     if (Result->isVoidTy())
1513       return Error(EltTyLoc, "struct element can not have void type");
1514     if (!StructType::isValidElementType(Result))
1515       return Error(EltTyLoc, "invalid element type for struct");
1516
1517     ParamsList.push_back(Result);
1518   }
1519
1520   if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1521     return true;
1522
1523   std::vector<const Type*> ParamsListTy;
1524   for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1525     ParamsListTy.push_back(ParamsList[i].get());
1526   Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1527   return false;
1528 }
1529
1530 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1531 /// token has already been consumed.
1532 ///   TypeRec
1533 ///     ::= '[' APSINTVAL 'x' Types ']'
1534 ///     ::= '<' APSINTVAL 'x' Types '>'
1535 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1536   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1537       Lex.getAPSIntVal().getBitWidth() > 64)
1538     return TokError("expected number in address space");
1539
1540   LocTy SizeLoc = Lex.getLoc();
1541   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1542   Lex.Lex();
1543
1544   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1545       return true;
1546
1547   LocTy TypeLoc = Lex.getLoc();
1548   PATypeHolder EltTy(Type::getVoidTy(Context));
1549   if (ParseTypeRec(EltTy)) return true;
1550
1551   if (EltTy->isVoidTy())
1552     return Error(TypeLoc, "array and vector element type cannot be void");
1553
1554   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1555                  "expected end of sequential type"))
1556     return true;
1557
1558   if (isVector) {
1559     if (Size == 0)
1560       return Error(SizeLoc, "zero element vector is illegal");
1561     if ((unsigned)Size != Size)
1562       return Error(SizeLoc, "size too large for vector");
1563     if (!VectorType::isValidElementType(EltTy))
1564       return Error(TypeLoc, "vector element type must be fp or integer");
1565     Result = VectorType::get(EltTy, unsigned(Size));
1566   } else {
1567     if (!ArrayType::isValidElementType(EltTy))
1568       return Error(TypeLoc, "invalid array element type");
1569     Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1570   }
1571   return false;
1572 }
1573
1574 //===----------------------------------------------------------------------===//
1575 // Function Semantic Analysis.
1576 //===----------------------------------------------------------------------===//
1577
1578 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1579   : P(p), F(f) {
1580
1581   // Insert unnamed arguments into the NumberedVals list.
1582   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1583        AI != E; ++AI)
1584     if (!AI->hasName())
1585       NumberedVals.push_back(AI);
1586 }
1587
1588 LLParser::PerFunctionState::~PerFunctionState() {
1589   // If there were any forward referenced non-basicblock values, delete them.
1590   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1591        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1592     if (!isa<BasicBlock>(I->second.first)) {
1593       I->second.first->replaceAllUsesWith(
1594                            UndefValue::get(I->second.first->getType()));
1595       delete I->second.first;
1596       I->second.first = 0;
1597     }
1598
1599   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1600        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1601     if (!isa<BasicBlock>(I->second.first)) {
1602       I->second.first->replaceAllUsesWith(
1603                            UndefValue::get(I->second.first->getType()));
1604       delete I->second.first;
1605       I->second.first = 0;
1606     }
1607 }
1608
1609 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1610   if (!ForwardRefVals.empty())
1611     return P.Error(ForwardRefVals.begin()->second.second,
1612                    "use of undefined value '%" + ForwardRefVals.begin()->first +
1613                    "'");
1614   if (!ForwardRefValIDs.empty())
1615     return P.Error(ForwardRefValIDs.begin()->second.second,
1616                    "use of undefined value '%" +
1617                    utostr(ForwardRefValIDs.begin()->first) + "'");
1618   return false;
1619 }
1620
1621
1622 /// GetVal - Get a value with the specified name or ID, creating a
1623 /// forward reference record if needed.  This can return null if the value
1624 /// exists but does not have the right type.
1625 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1626                                           const Type *Ty, LocTy Loc) {
1627   // Look this name up in the normal function symbol table.
1628   Value *Val = F.getValueSymbolTable().lookup(Name);
1629
1630   // If this is a forward reference for the value, see if we already created a
1631   // forward ref record.
1632   if (Val == 0) {
1633     std::map<std::string, std::pair<Value*, LocTy> >::iterator
1634       I = ForwardRefVals.find(Name);
1635     if (I != ForwardRefVals.end())
1636       Val = I->second.first;
1637   }
1638
1639   // If we have the value in the symbol table or fwd-ref table, return it.
1640   if (Val) {
1641     if (Val->getType() == Ty) return Val;
1642     if (Ty->isLabelTy())
1643       P.Error(Loc, "'%" + Name + "' is not a basic block");
1644     else
1645       P.Error(Loc, "'%" + Name + "' defined with type '" +
1646               Val->getType()->getDescription() + "'");
1647     return 0;
1648   }
1649
1650   // Don't make placeholders with invalid type.
1651   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1652       Ty != Type::getLabelTy(F.getContext())) {
1653     P.Error(Loc, "invalid use of a non-first-class type");
1654     return 0;
1655   }
1656
1657   // Otherwise, create a new forward reference for this value and remember it.
1658   Value *FwdVal;
1659   if (Ty->isLabelTy())
1660     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1661   else
1662     FwdVal = new Argument(Ty, Name);
1663
1664   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1665   return FwdVal;
1666 }
1667
1668 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1669                                           LocTy Loc) {
1670   // Look this name up in the normal function symbol table.
1671   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1672
1673   // If this is a forward reference for the value, see if we already created a
1674   // forward ref record.
1675   if (Val == 0) {
1676     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1677       I = ForwardRefValIDs.find(ID);
1678     if (I != ForwardRefValIDs.end())
1679       Val = I->second.first;
1680   }
1681
1682   // If we have the value in the symbol table or fwd-ref table, return it.
1683   if (Val) {
1684     if (Val->getType() == Ty) return Val;
1685     if (Ty->isLabelTy())
1686       P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1687     else
1688       P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1689               Val->getType()->getDescription() + "'");
1690     return 0;
1691   }
1692
1693   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1694       Ty != Type::getLabelTy(F.getContext())) {
1695     P.Error(Loc, "invalid use of a non-first-class type");
1696     return 0;
1697   }
1698
1699   // Otherwise, create a new forward reference for this value and remember it.
1700   Value *FwdVal;
1701   if (Ty->isLabelTy())
1702     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1703   else
1704     FwdVal = new Argument(Ty);
1705
1706   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1707   return FwdVal;
1708 }
1709
1710 /// SetInstName - After an instruction is parsed and inserted into its
1711 /// basic block, this installs its name.
1712 bool LLParser::PerFunctionState::SetInstName(int NameID,
1713                                              const std::string &NameStr,
1714                                              LocTy NameLoc, Instruction *Inst) {
1715   // If this instruction has void type, it cannot have a name or ID specified.
1716   if (Inst->getType()->isVoidTy()) {
1717     if (NameID != -1 || !NameStr.empty())
1718       return P.Error(NameLoc, "instructions returning void cannot have a name");
1719     return false;
1720   }
1721
1722   // If this was a numbered instruction, verify that the instruction is the
1723   // expected value and resolve any forward references.
1724   if (NameStr.empty()) {
1725     // If neither a name nor an ID was specified, just use the next ID.
1726     if (NameID == -1)
1727       NameID = NumberedVals.size();
1728
1729     if (unsigned(NameID) != NumberedVals.size())
1730       return P.Error(NameLoc, "instruction expected to be numbered '%" +
1731                      utostr(NumberedVals.size()) + "'");
1732
1733     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1734       ForwardRefValIDs.find(NameID);
1735     if (FI != ForwardRefValIDs.end()) {
1736       if (FI->second.first->getType() != Inst->getType())
1737         return P.Error(NameLoc, "instruction forward referenced with type '" +
1738                        FI->second.first->getType()->getDescription() + "'");
1739       FI->second.first->replaceAllUsesWith(Inst);
1740       delete FI->second.first;
1741       ForwardRefValIDs.erase(FI);
1742     }
1743
1744     NumberedVals.push_back(Inst);
1745     return false;
1746   }
1747
1748   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
1749   std::map<std::string, std::pair<Value*, LocTy> >::iterator
1750     FI = ForwardRefVals.find(NameStr);
1751   if (FI != ForwardRefVals.end()) {
1752     if (FI->second.first->getType() != Inst->getType())
1753       return P.Error(NameLoc, "instruction forward referenced with type '" +
1754                      FI->second.first->getType()->getDescription() + "'");
1755     FI->second.first->replaceAllUsesWith(Inst);
1756     delete FI->second.first;
1757     ForwardRefVals.erase(FI);
1758   }
1759
1760   // Set the name on the instruction.
1761   Inst->setName(NameStr);
1762
1763   if (Inst->getNameStr() != NameStr)
1764     return P.Error(NameLoc, "multiple definition of local value named '" +
1765                    NameStr + "'");
1766   return false;
1767 }
1768
1769 /// GetBB - Get a basic block with the specified name or ID, creating a
1770 /// forward reference record if needed.
1771 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1772                                               LocTy Loc) {
1773   return cast_or_null<BasicBlock>(GetVal(Name,
1774                                         Type::getLabelTy(F.getContext()), Loc));
1775 }
1776
1777 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1778   return cast_or_null<BasicBlock>(GetVal(ID,
1779                                         Type::getLabelTy(F.getContext()), Loc));
1780 }
1781
1782 /// DefineBB - Define the specified basic block, which is either named or
1783 /// unnamed.  If there is an error, this returns null otherwise it returns
1784 /// the block being defined.
1785 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1786                                                  LocTy Loc) {
1787   BasicBlock *BB;
1788   if (Name.empty())
1789     BB = GetBB(NumberedVals.size(), Loc);
1790   else
1791     BB = GetBB(Name, Loc);
1792   if (BB == 0) return 0; // Already diagnosed error.
1793
1794   // Move the block to the end of the function.  Forward ref'd blocks are
1795   // inserted wherever they happen to be referenced.
1796   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1797
1798   // Remove the block from forward ref sets.
1799   if (Name.empty()) {
1800     ForwardRefValIDs.erase(NumberedVals.size());
1801     NumberedVals.push_back(BB);
1802   } else {
1803     // BB forward references are already in the function symbol table.
1804     ForwardRefVals.erase(Name);
1805   }
1806
1807   return BB;
1808 }
1809
1810 //===----------------------------------------------------------------------===//
1811 // Constants.
1812 //===----------------------------------------------------------------------===//
1813
1814 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1815 /// type implied.  For example, if we parse "4" we don't know what integer type
1816 /// it has.  The value will later be combined with its type and checked for
1817 /// sanity.
1818 bool LLParser::ParseValID(ValID &ID) {
1819   ID.Loc = Lex.getLoc();
1820   switch (Lex.getKind()) {
1821   default: return TokError("expected value token");
1822   case lltok::GlobalID:  // @42
1823     ID.UIntVal = Lex.getUIntVal();
1824     ID.Kind = ValID::t_GlobalID;
1825     break;
1826   case lltok::GlobalVar:  // @foo
1827     ID.StrVal = Lex.getStrVal();
1828     ID.Kind = ValID::t_GlobalName;
1829     break;
1830   case lltok::LocalVarID:  // %42
1831     ID.UIntVal = Lex.getUIntVal();
1832     ID.Kind = ValID::t_LocalID;
1833     break;
1834   case lltok::LocalVar:  // %foo
1835   case lltok::StringConstant:  // "foo" - FIXME: REMOVE IN LLVM 3.0
1836     ID.StrVal = Lex.getStrVal();
1837     ID.Kind = ValID::t_LocalName;
1838     break;
1839   case lltok::Metadata: {  // !{...} MDNode, !"foo" MDString
1840     ID.Kind = ValID::t_Metadata;
1841     Lex.Lex();
1842     if (Lex.getKind() == lltok::lbrace) {
1843       SmallVector<Value*, 16> Elts;
1844       if (ParseMDNodeVector(Elts) ||
1845           ParseToken(lltok::rbrace, "expected end of metadata node"))
1846         return true;
1847
1848       ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
1849       return false;
1850     }
1851
1852     // Standalone metadata reference
1853     // !{ ..., !42, ... }
1854     if (!ParseMDNode(ID.MetadataVal))
1855       return false;
1856
1857     // MDString:
1858     //   ::= '!' STRINGCONSTANT
1859     if (ParseMDString(ID.MetadataVal)) return true;
1860     ID.Kind = ValID::t_Metadata;
1861     return false;
1862   }
1863   case lltok::APSInt:
1864     ID.APSIntVal = Lex.getAPSIntVal();
1865     ID.Kind = ValID::t_APSInt;
1866     break;
1867   case lltok::APFloat:
1868     ID.APFloatVal = Lex.getAPFloatVal();
1869     ID.Kind = ValID::t_APFloat;
1870     break;
1871   case lltok::kw_true:
1872     ID.ConstantVal = ConstantInt::getTrue(Context);
1873     ID.Kind = ValID::t_Constant;
1874     break;
1875   case lltok::kw_false:
1876     ID.ConstantVal = ConstantInt::getFalse(Context);
1877     ID.Kind = ValID::t_Constant;
1878     break;
1879   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1880   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1881   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1882
1883   case lltok::lbrace: {
1884     // ValID ::= '{' ConstVector '}'
1885     Lex.Lex();
1886     SmallVector<Constant*, 16> Elts;
1887     if (ParseGlobalValueVector(Elts) ||
1888         ParseToken(lltok::rbrace, "expected end of struct constant"))
1889       return true;
1890
1891     ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1892                                          Elts.size(), false);
1893     ID.Kind = ValID::t_Constant;
1894     return false;
1895   }
1896   case lltok::less: {
1897     // ValID ::= '<' ConstVector '>'         --> Vector.
1898     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1899     Lex.Lex();
1900     bool isPackedStruct = EatIfPresent(lltok::lbrace);
1901
1902     SmallVector<Constant*, 16> Elts;
1903     LocTy FirstEltLoc = Lex.getLoc();
1904     if (ParseGlobalValueVector(Elts) ||
1905         (isPackedStruct &&
1906          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1907         ParseToken(lltok::greater, "expected end of constant"))
1908       return true;
1909
1910     if (isPackedStruct) {
1911       ID.ConstantVal =
1912         ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
1913       ID.Kind = ValID::t_Constant;
1914       return false;
1915     }
1916
1917     if (Elts.empty())
1918       return Error(ID.Loc, "constant vector must not be empty");
1919
1920     if (!Elts[0]->getType()->isInteger() &&
1921         !Elts[0]->getType()->isFloatingPoint())
1922       return Error(FirstEltLoc,
1923                    "vector elements must have integer or floating point type");
1924
1925     // Verify that all the vector elements have the same type.
1926     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1927       if (Elts[i]->getType() != Elts[0]->getType())
1928         return Error(FirstEltLoc,
1929                      "vector element #" + utostr(i) +
1930                     " is not of type '" + Elts[0]->getType()->getDescription());
1931
1932     ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1933     ID.Kind = ValID::t_Constant;
1934     return false;
1935   }
1936   case lltok::lsquare: {   // Array Constant
1937     Lex.Lex();
1938     SmallVector<Constant*, 16> Elts;
1939     LocTy FirstEltLoc = Lex.getLoc();
1940     if (ParseGlobalValueVector(Elts) ||
1941         ParseToken(lltok::rsquare, "expected end of array constant"))
1942       return true;
1943
1944     // Handle empty element.
1945     if (Elts.empty()) {
1946       // Use undef instead of an array because it's inconvenient to determine
1947       // the element type at this point, there being no elements to examine.
1948       ID.Kind = ValID::t_EmptyArray;
1949       return false;
1950     }
1951
1952     if (!Elts[0]->getType()->isFirstClassType())
1953       return Error(FirstEltLoc, "invalid array element type: " +
1954                    Elts[0]->getType()->getDescription());
1955
1956     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1957
1958     // Verify all elements are correct type!
1959     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1960       if (Elts[i]->getType() != Elts[0]->getType())
1961         return Error(FirstEltLoc,
1962                      "array element #" + utostr(i) +
1963                      " is not of type '" +Elts[0]->getType()->getDescription());
1964     }
1965
1966     ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1967     ID.Kind = ValID::t_Constant;
1968     return false;
1969   }
1970   case lltok::kw_c:  // c "foo"
1971     Lex.Lex();
1972     ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
1973     if (ParseToken(lltok::StringConstant, "expected string")) return true;
1974     ID.Kind = ValID::t_Constant;
1975     return false;
1976
1977   case lltok::kw_asm: {
1978     // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
1979     bool HasSideEffect, AlignStack;
1980     Lex.Lex();
1981     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1982         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
1983         ParseStringConstant(ID.StrVal) ||
1984         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1985         ParseToken(lltok::StringConstant, "expected constraint string"))
1986       return true;
1987     ID.StrVal2 = Lex.getStrVal();
1988     ID.UIntVal = HasSideEffect | ((unsigned)AlignStack<<1);
1989     ID.Kind = ValID::t_InlineAsm;
1990     return false;
1991   }
1992
1993   case lltok::kw_trunc:
1994   case lltok::kw_zext:
1995   case lltok::kw_sext:
1996   case lltok::kw_fptrunc:
1997   case lltok::kw_fpext:
1998   case lltok::kw_bitcast:
1999   case lltok::kw_uitofp:
2000   case lltok::kw_sitofp:
2001   case lltok::kw_fptoui:
2002   case lltok::kw_fptosi:
2003   case lltok::kw_inttoptr:
2004   case lltok::kw_ptrtoint: {
2005     unsigned Opc = Lex.getUIntVal();
2006     PATypeHolder DestTy(Type::getVoidTy(Context));
2007     Constant *SrcVal;
2008     Lex.Lex();
2009     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2010         ParseGlobalTypeAndValue(SrcVal) ||
2011         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2012         ParseType(DestTy) ||
2013         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2014       return true;
2015     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2016       return Error(ID.Loc, "invalid cast opcode for cast from '" +
2017                    SrcVal->getType()->getDescription() + "' to '" +
2018                    DestTy->getDescription() + "'");
2019     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2020                                                  SrcVal, DestTy);
2021     ID.Kind = ValID::t_Constant;
2022     return false;
2023   }
2024   case lltok::kw_extractvalue: {
2025     Lex.Lex();
2026     Constant *Val;
2027     SmallVector<unsigned, 4> Indices;
2028     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2029         ParseGlobalTypeAndValue(Val) ||
2030         ParseIndexList(Indices) ||
2031         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2032       return true;
2033     if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2034       return Error(ID.Loc, "extractvalue operand must be array or struct");
2035     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2036                                           Indices.end()))
2037       return Error(ID.Loc, "invalid indices for extractvalue");
2038     ID.ConstantVal =
2039       ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2040     ID.Kind = ValID::t_Constant;
2041     return false;
2042   }
2043   case lltok::kw_insertvalue: {
2044     Lex.Lex();
2045     Constant *Val0, *Val1;
2046     SmallVector<unsigned, 4> Indices;
2047     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2048         ParseGlobalTypeAndValue(Val0) ||
2049         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2050         ParseGlobalTypeAndValue(Val1) ||
2051         ParseIndexList(Indices) ||
2052         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2053       return true;
2054     if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2055       return Error(ID.Loc, "extractvalue operand must be array or struct");
2056     if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2057                                           Indices.end()))
2058       return Error(ID.Loc, "invalid indices for insertvalue");
2059     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2060                        Indices.data(), Indices.size());
2061     ID.Kind = ValID::t_Constant;
2062     return false;
2063   }
2064   case lltok::kw_icmp:
2065   case lltok::kw_fcmp: {
2066     unsigned PredVal, Opc = Lex.getUIntVal();
2067     Constant *Val0, *Val1;
2068     Lex.Lex();
2069     if (ParseCmpPredicate(PredVal, Opc) ||
2070         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2071         ParseGlobalTypeAndValue(Val0) ||
2072         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2073         ParseGlobalTypeAndValue(Val1) ||
2074         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2075       return true;
2076
2077     if (Val0->getType() != Val1->getType())
2078       return Error(ID.Loc, "compare operands must have the same type");
2079
2080     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2081
2082     if (Opc == Instruction::FCmp) {
2083       if (!Val0->getType()->isFPOrFPVector())
2084         return Error(ID.Loc, "fcmp requires floating point operands");
2085       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2086     } else {
2087       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2088       if (!Val0->getType()->isIntOrIntVector() &&
2089           !isa<PointerType>(Val0->getType()))
2090         return Error(ID.Loc, "icmp requires pointer or integer operands");
2091       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2092     }
2093     ID.Kind = ValID::t_Constant;
2094     return false;
2095   }
2096
2097   // Binary Operators.
2098   case lltok::kw_add:
2099   case lltok::kw_fadd:
2100   case lltok::kw_sub:
2101   case lltok::kw_fsub:
2102   case lltok::kw_mul:
2103   case lltok::kw_fmul:
2104   case lltok::kw_udiv:
2105   case lltok::kw_sdiv:
2106   case lltok::kw_fdiv:
2107   case lltok::kw_urem:
2108   case lltok::kw_srem:
2109   case lltok::kw_frem: {
2110     bool NUW = false;
2111     bool NSW = false;
2112     bool Exact = false;
2113     unsigned Opc = Lex.getUIntVal();
2114     Constant *Val0, *Val1;
2115     Lex.Lex();
2116     LocTy ModifierLoc = Lex.getLoc();
2117     if (Opc == Instruction::Add ||
2118         Opc == Instruction::Sub ||
2119         Opc == Instruction::Mul) {
2120       if (EatIfPresent(lltok::kw_nuw))
2121         NUW = true;
2122       if (EatIfPresent(lltok::kw_nsw)) {
2123         NSW = true;
2124         if (EatIfPresent(lltok::kw_nuw))
2125           NUW = true;
2126       }
2127     } else if (Opc == Instruction::SDiv) {
2128       if (EatIfPresent(lltok::kw_exact))
2129         Exact = true;
2130     }
2131     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2132         ParseGlobalTypeAndValue(Val0) ||
2133         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2134         ParseGlobalTypeAndValue(Val1) ||
2135         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2136       return true;
2137     if (Val0->getType() != Val1->getType())
2138       return Error(ID.Loc, "operands of constexpr must have same type");
2139     if (!Val0->getType()->isIntOrIntVector()) {
2140       if (NUW)
2141         return Error(ModifierLoc, "nuw only applies to integer operations");
2142       if (NSW)
2143         return Error(ModifierLoc, "nsw only applies to integer operations");
2144     }
2145     // API compatibility: Accept either integer or floating-point types with
2146     // add, sub, and mul.
2147     if (!Val0->getType()->isIntOrIntVector() &&
2148         !Val0->getType()->isFPOrFPVector())
2149       return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2150     unsigned Flags = 0;
2151     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2152     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
2153     if (Exact) Flags |= SDivOperator::IsExact;
2154     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2155     ID.ConstantVal = C;
2156     ID.Kind = ValID::t_Constant;
2157     return false;
2158   }
2159
2160   // Logical Operations
2161   case lltok::kw_shl:
2162   case lltok::kw_lshr:
2163   case lltok::kw_ashr:
2164   case lltok::kw_and:
2165   case lltok::kw_or:
2166   case lltok::kw_xor: {
2167     unsigned Opc = Lex.getUIntVal();
2168     Constant *Val0, *Val1;
2169     Lex.Lex();
2170     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2171         ParseGlobalTypeAndValue(Val0) ||
2172         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2173         ParseGlobalTypeAndValue(Val1) ||
2174         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2175       return true;
2176     if (Val0->getType() != Val1->getType())
2177       return Error(ID.Loc, "operands of constexpr must have same type");
2178     if (!Val0->getType()->isIntOrIntVector())
2179       return Error(ID.Loc,
2180                    "constexpr requires integer or integer vector operands");
2181     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2182     ID.Kind = ValID::t_Constant;
2183     return false;
2184   }
2185
2186   case lltok::kw_getelementptr:
2187   case lltok::kw_shufflevector:
2188   case lltok::kw_insertelement:
2189   case lltok::kw_extractelement:
2190   case lltok::kw_select: {
2191     unsigned Opc = Lex.getUIntVal();
2192     SmallVector<Constant*, 16> Elts;
2193     bool InBounds = false;
2194     Lex.Lex();
2195     if (Opc == Instruction::GetElementPtr)
2196       InBounds = EatIfPresent(lltok::kw_inbounds);
2197     if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2198         ParseGlobalValueVector(Elts) ||
2199         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2200       return true;
2201
2202     if (Opc == Instruction::GetElementPtr) {
2203       if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2204         return Error(ID.Loc, "getelementptr requires pointer operand");
2205
2206       if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2207                                              (Value**)(Elts.data() + 1),
2208                                              Elts.size() - 1))
2209         return Error(ID.Loc, "invalid indices for getelementptr");
2210       ID.ConstantVal = InBounds ?
2211         ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2212                                                Elts.data() + 1,
2213                                                Elts.size() - 1) :
2214         ConstantExpr::getGetElementPtr(Elts[0],
2215                                        Elts.data() + 1, Elts.size() - 1);
2216     } else if (Opc == Instruction::Select) {
2217       if (Elts.size() != 3)
2218         return Error(ID.Loc, "expected three operands to select");
2219       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2220                                                               Elts[2]))
2221         return Error(ID.Loc, Reason);
2222       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2223     } else if (Opc == Instruction::ShuffleVector) {
2224       if (Elts.size() != 3)
2225         return Error(ID.Loc, "expected three operands to shufflevector");
2226       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2227         return Error(ID.Loc, "invalid operands to shufflevector");
2228       ID.ConstantVal =
2229                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2230     } else if (Opc == Instruction::ExtractElement) {
2231       if (Elts.size() != 2)
2232         return Error(ID.Loc, "expected two operands to extractelement");
2233       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2234         return Error(ID.Loc, "invalid extractelement operands");
2235       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2236     } else {
2237       assert(Opc == Instruction::InsertElement && "Unknown opcode");
2238       if (Elts.size() != 3)
2239       return Error(ID.Loc, "expected three operands to insertelement");
2240       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2241         return Error(ID.Loc, "invalid insertelement operands");
2242       ID.ConstantVal =
2243                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2244     }
2245
2246     ID.Kind = ValID::t_Constant;
2247     return false;
2248   }
2249   }
2250
2251   Lex.Lex();
2252   return false;
2253 }
2254
2255 /// ParseGlobalValue - Parse a global value with the specified type.
2256 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2257   V = 0;
2258   ValID ID;
2259   return ParseValID(ID) ||
2260          ConvertGlobalValIDToValue(Ty, ID, V);
2261 }
2262
2263 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2264 /// constant.
2265 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2266                                          Constant *&V) {
2267   if (isa<FunctionType>(Ty))
2268     return Error(ID.Loc, "functions are not values, refer to them as pointers");
2269
2270   switch (ID.Kind) {
2271   default: llvm_unreachable("Unknown ValID!");
2272   case ValID::t_Metadata:
2273     return Error(ID.Loc, "invalid use of metadata");
2274   case ValID::t_LocalID:
2275   case ValID::t_LocalName:
2276     return Error(ID.Loc, "invalid use of function-local name");
2277   case ValID::t_InlineAsm:
2278     return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2279   case ValID::t_GlobalName:
2280     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2281     return V == 0;
2282   case ValID::t_GlobalID:
2283     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2284     return V == 0;
2285   case ValID::t_APSInt:
2286     if (!isa<IntegerType>(Ty))
2287       return Error(ID.Loc, "integer constant must have integer type");
2288     ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2289     V = ConstantInt::get(Context, ID.APSIntVal);
2290     return false;
2291   case ValID::t_APFloat:
2292     if (!Ty->isFloatingPoint() ||
2293         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2294       return Error(ID.Loc, "floating point constant invalid for type");
2295
2296     // The lexer has no type info, so builds all float and double FP constants
2297     // as double.  Fix this here.  Long double does not need this.
2298     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2299         Ty->isFloatTy()) {
2300       bool Ignored;
2301       ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2302                             &Ignored);
2303     }
2304     V = ConstantFP::get(Context, ID.APFloatVal);
2305
2306     if (V->getType() != Ty)
2307       return Error(ID.Loc, "floating point constant does not have type '" +
2308                    Ty->getDescription() + "'");
2309
2310     return false;
2311   case ValID::t_Null:
2312     if (!isa<PointerType>(Ty))
2313       return Error(ID.Loc, "null must be a pointer type");
2314     V = ConstantPointerNull::get(cast<PointerType>(Ty));
2315     return false;
2316   case ValID::t_Undef:
2317     // FIXME: LabelTy should not be a first-class type.
2318     if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2319         !isa<OpaqueType>(Ty))
2320       return Error(ID.Loc, "invalid type for undef constant");
2321     V = UndefValue::get(Ty);
2322     return false;
2323   case ValID::t_EmptyArray:
2324     if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2325       return Error(ID.Loc, "invalid empty array initializer");
2326     V = UndefValue::get(Ty);
2327     return false;
2328   case ValID::t_Zero:
2329     // FIXME: LabelTy should not be a first-class type.
2330     if (!Ty->isFirstClassType() || Ty->isLabelTy())
2331       return Error(ID.Loc, "invalid type for null constant");
2332     V = Constant::getNullValue(Ty);
2333     return false;
2334   case ValID::t_Constant:
2335     if (ID.ConstantVal->getType() != Ty)
2336       return Error(ID.Loc, "constant expression type mismatch");
2337     V = ID.ConstantVal;
2338     return false;
2339   }
2340 }
2341
2342 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2343   PATypeHolder Type(Type::getVoidTy(Context));
2344   return ParseType(Type) ||
2345          ParseGlobalValue(Type, V);
2346 }
2347
2348 /// ParseGlobalValueVector
2349 ///   ::= /*empty*/
2350 ///   ::= TypeAndValue (',' TypeAndValue)*
2351 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2352   // Empty list.
2353   if (Lex.getKind() == lltok::rbrace ||
2354       Lex.getKind() == lltok::rsquare ||
2355       Lex.getKind() == lltok::greater ||
2356       Lex.getKind() == lltok::rparen)
2357     return false;
2358
2359   Constant *C;
2360   if (ParseGlobalTypeAndValue(C)) return true;
2361   Elts.push_back(C);
2362
2363   while (EatIfPresent(lltok::comma)) {
2364     if (ParseGlobalTypeAndValue(C)) return true;
2365     Elts.push_back(C);
2366   }
2367
2368   return false;
2369 }
2370
2371
2372 //===----------------------------------------------------------------------===//
2373 // Function Parsing.
2374 //===----------------------------------------------------------------------===//
2375
2376 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2377                                    PerFunctionState &PFS) {
2378   if (ID.Kind == ValID::t_LocalID)
2379     V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2380   else if (ID.Kind == ValID::t_LocalName)
2381     V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2382   else if (ID.Kind == ValID::t_InlineAsm) {
2383     const PointerType *PTy = dyn_cast<PointerType>(Ty);
2384     const FunctionType *FTy =
2385       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2386     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2387       return Error(ID.Loc, "invalid type for inline asm constraint string");
2388     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2389     return false;
2390   } else if (ID.Kind == ValID::t_Metadata) {
2391     V = ID.MetadataVal;
2392   } else {
2393     Constant *C;
2394     if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2395     V = C;
2396     return false;
2397   }
2398
2399   return V == 0;
2400 }
2401
2402 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2403   V = 0;
2404   ValID ID;
2405   return ParseValID(ID) ||
2406          ConvertValIDToValue(Ty, ID, V, PFS);
2407 }
2408
2409 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2410   PATypeHolder T(Type::getVoidTy(Context));
2411   return ParseType(T) ||
2412          ParseValue(T, V, PFS);
2413 }
2414
2415 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2416                                       PerFunctionState &PFS) {
2417   Value *V;
2418   Loc = Lex.getLoc();
2419   if (ParseTypeAndValue(V, PFS)) return true;
2420   if (!isa<BasicBlock>(V))
2421     return Error(Loc, "expected a basic block");
2422   BB = cast<BasicBlock>(V);
2423   return false;
2424 }
2425
2426
2427 /// FunctionHeader
2428 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2429 ///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2430 ///       OptionalAlign OptGC
2431 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2432   // Parse the linkage.
2433   LocTy LinkageLoc = Lex.getLoc();
2434   unsigned Linkage;
2435
2436   unsigned Visibility, RetAttrs;
2437   CallingConv::ID CC;
2438   PATypeHolder RetType(Type::getVoidTy(Context));
2439   LocTy RetTypeLoc = Lex.getLoc();
2440   if (ParseOptionalLinkage(Linkage) ||
2441       ParseOptionalVisibility(Visibility) ||
2442       ParseOptionalCallingConv(CC) ||
2443       ParseOptionalAttrs(RetAttrs, 1) ||
2444       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2445     return true;
2446
2447   // Verify that the linkage is ok.
2448   switch ((GlobalValue::LinkageTypes)Linkage) {
2449   case GlobalValue::ExternalLinkage:
2450     break; // always ok.
2451   case GlobalValue::DLLImportLinkage:
2452   case GlobalValue::ExternalWeakLinkage:
2453     if (isDefine)
2454       return Error(LinkageLoc, "invalid linkage for function definition");
2455     break;
2456   case GlobalValue::PrivateLinkage:
2457   case GlobalValue::LinkerPrivateLinkage:
2458   case GlobalValue::InternalLinkage:
2459   case GlobalValue::AvailableExternallyLinkage:
2460   case GlobalValue::LinkOnceAnyLinkage:
2461   case GlobalValue::LinkOnceODRLinkage:
2462   case GlobalValue::WeakAnyLinkage:
2463   case GlobalValue::WeakODRLinkage:
2464   case GlobalValue::DLLExportLinkage:
2465     if (!isDefine)
2466       return Error(LinkageLoc, "invalid linkage for function declaration");
2467     break;
2468   case GlobalValue::AppendingLinkage:
2469   case GlobalValue::GhostLinkage:
2470   case GlobalValue::CommonLinkage:
2471     return Error(LinkageLoc, "invalid function linkage type");
2472   }
2473
2474   if (!FunctionType::isValidReturnType(RetType) ||
2475       isa<OpaqueType>(RetType))
2476     return Error(RetTypeLoc, "invalid function return type");
2477
2478   LocTy NameLoc = Lex.getLoc();
2479
2480   std::string FunctionName;
2481   if (Lex.getKind() == lltok::GlobalVar) {
2482     FunctionName = Lex.getStrVal();
2483   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2484     unsigned NameID = Lex.getUIntVal();
2485
2486     if (NameID != NumberedVals.size())
2487       return TokError("function expected to be numbered '%" +
2488                       utostr(NumberedVals.size()) + "'");
2489   } else {
2490     return TokError("expected function name");
2491   }
2492
2493   Lex.Lex();
2494
2495   if (Lex.getKind() != lltok::lparen)
2496     return TokError("expected '(' in function argument list");
2497
2498   std::vector<ArgInfo> ArgList;
2499   bool isVarArg;
2500   unsigned FuncAttrs;
2501   std::string Section;
2502   unsigned Alignment;
2503   std::string GC;
2504
2505   if (ParseArgumentList(ArgList, isVarArg, false) ||
2506       ParseOptionalAttrs(FuncAttrs, 2) ||
2507       (EatIfPresent(lltok::kw_section) &&
2508        ParseStringConstant(Section)) ||
2509       ParseOptionalAlignment(Alignment) ||
2510       (EatIfPresent(lltok::kw_gc) &&
2511        ParseStringConstant(GC)))
2512     return true;
2513
2514   // If the alignment was parsed as an attribute, move to the alignment field.
2515   if (FuncAttrs & Attribute::Alignment) {
2516     Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2517     FuncAttrs &= ~Attribute::Alignment;
2518   }
2519
2520   // Okay, if we got here, the function is syntactically valid.  Convert types
2521   // and do semantic checks.
2522   std::vector<const Type*> ParamTypeList;
2523   SmallVector<AttributeWithIndex, 8> Attrs;
2524   // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2525   // attributes.
2526   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2527   if (FuncAttrs & ObsoleteFuncAttrs) {
2528     RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2529     FuncAttrs &= ~ObsoleteFuncAttrs;
2530   }
2531
2532   if (RetAttrs != Attribute::None)
2533     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2534
2535   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2536     ParamTypeList.push_back(ArgList[i].Type);
2537     if (ArgList[i].Attrs != Attribute::None)
2538       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2539   }
2540
2541   if (FuncAttrs != Attribute::None)
2542     Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2543
2544   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2545
2546   if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2547       RetType != Type::getVoidTy(Context))
2548     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2549
2550   const FunctionType *FT =
2551     FunctionType::get(RetType, ParamTypeList, isVarArg);
2552   const PointerType *PFT = PointerType::getUnqual(FT);
2553
2554   Fn = 0;
2555   if (!FunctionName.empty()) {
2556     // If this was a definition of a forward reference, remove the definition
2557     // from the forward reference table and fill in the forward ref.
2558     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2559       ForwardRefVals.find(FunctionName);
2560     if (FRVI != ForwardRefVals.end()) {
2561       Fn = M->getFunction(FunctionName);
2562       ForwardRefVals.erase(FRVI);
2563     } else if ((Fn = M->getFunction(FunctionName))) {
2564       // If this function already exists in the symbol table, then it is
2565       // multiply defined.  We accept a few cases for old backwards compat.
2566       // FIXME: Remove this stuff for LLVM 3.0.
2567       if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2568           (!Fn->isDeclaration() && isDefine)) {
2569         // If the redefinition has different type or different attributes,
2570         // reject it.  If both have bodies, reject it.
2571         return Error(NameLoc, "invalid redefinition of function '" +
2572                      FunctionName + "'");
2573       } else if (Fn->isDeclaration()) {
2574         // Make sure to strip off any argument names so we can't get conflicts.
2575         for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2576              AI != AE; ++AI)
2577           AI->setName("");
2578       }
2579     } else if (M->getNamedValue(FunctionName)) {
2580       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2581     }
2582
2583   } else {
2584     // If this is a definition of a forward referenced function, make sure the
2585     // types agree.
2586     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2587       = ForwardRefValIDs.find(NumberedVals.size());
2588     if (I != ForwardRefValIDs.end()) {
2589       Fn = cast<Function>(I->second.first);
2590       if (Fn->getType() != PFT)
2591         return Error(NameLoc, "type of definition and forward reference of '@" +
2592                      utostr(NumberedVals.size()) +"' disagree");
2593       ForwardRefValIDs.erase(I);
2594     }
2595   }
2596
2597   if (Fn == 0)
2598     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2599   else // Move the forward-reference to the correct spot in the module.
2600     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2601
2602   if (FunctionName.empty())
2603     NumberedVals.push_back(Fn);
2604
2605   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2606   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2607   Fn->setCallingConv(CC);
2608   Fn->setAttributes(PAL);
2609   Fn->setAlignment(Alignment);
2610   Fn->setSection(Section);
2611   if (!GC.empty()) Fn->setGC(GC.c_str());
2612
2613   // Add all of the arguments we parsed to the function.
2614   Function::arg_iterator ArgIt = Fn->arg_begin();
2615   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2616     // If the argument has a name, insert it into the argument symbol table.
2617     if (ArgList[i].Name.empty()) continue;
2618
2619     // Set the name, if it conflicted, it will be auto-renamed.
2620     ArgIt->setName(ArgList[i].Name);
2621
2622     if (ArgIt->getNameStr() != ArgList[i].Name)
2623       return Error(ArgList[i].Loc, "redefinition of argument '%" +
2624                    ArgList[i].Name + "'");
2625   }
2626
2627   return false;
2628 }
2629
2630
2631 /// ParseFunctionBody
2632 ///   ::= '{' BasicBlock+ '}'
2633 ///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
2634 ///
2635 bool LLParser::ParseFunctionBody(Function &Fn) {
2636   if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2637     return TokError("expected '{' in function body");
2638   Lex.Lex();  // eat the {.
2639
2640   PerFunctionState PFS(*this, Fn);
2641
2642   while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2643     if (ParseBasicBlock(PFS)) return true;
2644
2645   // Eat the }.
2646   Lex.Lex();
2647
2648   // Verify function is ok.
2649   return PFS.VerifyFunctionComplete();
2650 }
2651
2652 /// ParseBasicBlock
2653 ///   ::= LabelStr? Instruction*
2654 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2655   // If this basic block starts out with a name, remember it.
2656   std::string Name;
2657   LocTy NameLoc = Lex.getLoc();
2658   if (Lex.getKind() == lltok::LabelStr) {
2659     Name = Lex.getStrVal();
2660     Lex.Lex();
2661   }
2662
2663   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2664   if (BB == 0) return true;
2665
2666   std::string NameStr;
2667
2668   // Parse the instructions in this block until we get a terminator.
2669   Instruction *Inst;
2670   do {
2671     // This instruction may have three possibilities for a name: a) none
2672     // specified, b) name specified "%foo =", c) number specified: "%4 =".
2673     LocTy NameLoc = Lex.getLoc();
2674     int NameID = -1;
2675     NameStr = "";
2676
2677     if (Lex.getKind() == lltok::LocalVarID) {
2678       NameID = Lex.getUIntVal();
2679       Lex.Lex();
2680       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2681         return true;
2682     } else if (Lex.getKind() == lltok::LocalVar ||
2683                // FIXME: REMOVE IN LLVM 3.0
2684                Lex.getKind() == lltok::StringConstant) {
2685       NameStr = Lex.getStrVal();
2686       Lex.Lex();
2687       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2688         return true;
2689     }
2690
2691     if (ParseInstruction(Inst, BB, PFS)) return true;
2692     if (EatIfPresent(lltok::comma))
2693       ParseOptionalCustomMetadata();
2694
2695     // Set metadata attached with this instruction.
2696     MetadataContext &TheMetadata = M->getContext().getMetadata();
2697     for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
2698            MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
2699       TheMetadata.addMD(MDI->first, MDI->second, Inst);
2700     MDsOnInst.clear();
2701
2702     BB->getInstList().push_back(Inst);
2703
2704     // Set the name on the instruction.
2705     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2706   } while (!isa<TerminatorInst>(Inst));
2707
2708   return false;
2709 }
2710
2711 //===----------------------------------------------------------------------===//
2712 // Instruction Parsing.
2713 //===----------------------------------------------------------------------===//
2714
2715 /// ParseInstruction - Parse one of the many different instructions.
2716 ///
2717 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2718                                 PerFunctionState &PFS) {
2719   lltok::Kind Token = Lex.getKind();
2720   if (Token == lltok::Eof)
2721     return TokError("found end of file when expecting more instructions");
2722   LocTy Loc = Lex.getLoc();
2723   unsigned KeywordVal = Lex.getUIntVal();
2724   Lex.Lex();  // Eat the keyword.
2725
2726   switch (Token) {
2727   default:                    return Error(Loc, "expected instruction opcode");
2728   // Terminator Instructions.
2729   case lltok::kw_unwind:      Inst = new UnwindInst(Context); return false;
2730   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2731   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
2732   case lltok::kw_br:          return ParseBr(Inst, PFS);
2733   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
2734   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
2735   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
2736   // Binary Operators.
2737   case lltok::kw_add:
2738   case lltok::kw_sub:
2739   case lltok::kw_mul: {
2740     bool NUW = false;
2741     bool NSW = false;
2742     LocTy ModifierLoc = Lex.getLoc();
2743     if (EatIfPresent(lltok::kw_nuw))
2744       NUW = true;
2745     if (EatIfPresent(lltok::kw_nsw)) {
2746       NSW = true;
2747       if (EatIfPresent(lltok::kw_nuw))
2748         NUW = true;
2749     }
2750     // API compatibility: Accept either integer or floating-point types.
2751     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2752     if (!Result) {
2753       if (!Inst->getType()->isIntOrIntVector()) {
2754         if (NUW)
2755           return Error(ModifierLoc, "nuw only applies to integer operations");
2756         if (NSW)
2757           return Error(ModifierLoc, "nsw only applies to integer operations");
2758       }
2759       if (NUW)
2760         cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2761       if (NSW)
2762         cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2763     }
2764     return Result;
2765   }
2766   case lltok::kw_fadd:
2767   case lltok::kw_fsub:
2768   case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2769
2770   case lltok::kw_sdiv: {
2771     bool Exact = false;
2772     if (EatIfPresent(lltok::kw_exact))
2773       Exact = true;
2774     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2775     if (!Result)
2776       if (Exact)
2777         cast<BinaryOperator>(Inst)->setIsExact(true);
2778     return Result;
2779   }
2780
2781   case lltok::kw_udiv:
2782   case lltok::kw_urem:
2783   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2784   case lltok::kw_fdiv:
2785   case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2786   case lltok::kw_shl:
2787   case lltok::kw_lshr:
2788   case lltok::kw_ashr:
2789   case lltok::kw_and:
2790   case lltok::kw_or:
2791   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
2792   case lltok::kw_icmp:
2793   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
2794   // Casts.
2795   case lltok::kw_trunc:
2796   case lltok::kw_zext:
2797   case lltok::kw_sext:
2798   case lltok::kw_fptrunc:
2799   case lltok::kw_fpext:
2800   case lltok::kw_bitcast:
2801   case lltok::kw_uitofp:
2802   case lltok::kw_sitofp:
2803   case lltok::kw_fptoui:
2804   case lltok::kw_fptosi:
2805   case lltok::kw_inttoptr:
2806   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
2807   // Other.
2808   case lltok::kw_select:         return ParseSelect(Inst, PFS);
2809   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
2810   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2811   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
2812   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
2813   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
2814   case lltok::kw_call:           return ParseCall(Inst, PFS, false);
2815   case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
2816   // Memory.
2817   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
2818   case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, BB, false);
2819   case lltok::kw_free:           return ParseFree(Inst, PFS, BB);
2820   case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
2821   case lltok::kw_store:          return ParseStore(Inst, PFS, false);
2822   case lltok::kw_volatile:
2823     if (EatIfPresent(lltok::kw_load))
2824       return ParseLoad(Inst, PFS, true);
2825     else if (EatIfPresent(lltok::kw_store))
2826       return ParseStore(Inst, PFS, true);
2827     else
2828       return TokError("expected 'load' or 'store'");
2829   case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
2830   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2831   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
2832   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
2833   }
2834 }
2835
2836 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2837 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2838   if (Opc == Instruction::FCmp) {
2839     switch (Lex.getKind()) {
2840     default: TokError("expected fcmp predicate (e.g. 'oeq')");
2841     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2842     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2843     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2844     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2845     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2846     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2847     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2848     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2849     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2850     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2851     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2852     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2853     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2854     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2855     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2856     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2857     }
2858   } else {
2859     switch (Lex.getKind()) {
2860     default: TokError("expected icmp predicate (e.g. 'eq')");
2861     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
2862     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
2863     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2864     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2865     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2866     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2867     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2868     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2869     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2870     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2871     }
2872   }
2873   Lex.Lex();
2874   return false;
2875 }
2876
2877 //===----------------------------------------------------------------------===//
2878 // Terminator Instructions.
2879 //===----------------------------------------------------------------------===//
2880
2881 /// ParseRet - Parse a return instruction.
2882 ///   ::= 'ret' void (',' !dbg, !1)
2883 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)
2884 ///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  (',' !dbg, !1)
2885 ///         [[obsolete: LLVM 3.0]]
2886 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2887                         PerFunctionState &PFS) {
2888   PATypeHolder Ty(Type::getVoidTy(Context));
2889   if (ParseType(Ty, true /*void allowed*/)) return true;
2890
2891   if (Ty->isVoidTy()) {
2892     Inst = ReturnInst::Create(Context);
2893     return false;
2894   }
2895
2896   Value *RV;
2897   if (ParseValue(Ty, RV, PFS)) return true;
2898
2899   if (EatIfPresent(lltok::comma)) {
2900     // Parse optional custom metadata, e.g. !dbg
2901     if (Lex.getKind() == lltok::NamedOrCustomMD) {
2902       if (ParseOptionalCustomMetadata()) return true;
2903     } else {
2904       // The normal case is one return value.
2905       // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2906       // of 'ret {i32,i32} {i32 1, i32 2}'
2907       SmallVector<Value*, 8> RVs;
2908       RVs.push_back(RV);
2909
2910       do {
2911         // If optional custom metadata, e.g. !dbg is seen then this is the 
2912         // end of MRV.
2913         if (Lex.getKind() == lltok::NamedOrCustomMD)
2914           break;
2915         if (ParseTypeAndValue(RV, PFS)) return true;
2916         RVs.push_back(RV);
2917       } while (EatIfPresent(lltok::comma));
2918
2919       RV = UndefValue::get(PFS.getFunction().getReturnType());
2920       for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2921         Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2922         BB->getInstList().push_back(I);
2923         RV = I;
2924       }
2925     }
2926   }
2927
2928   Inst = ReturnInst::Create(Context, RV);
2929   return false;
2930 }
2931
2932
2933 /// ParseBr
2934 ///   ::= 'br' TypeAndValue
2935 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2936 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2937   LocTy Loc, Loc2;
2938   Value *Op0;
2939   BasicBlock *Op1, *Op2;
2940   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2941
2942   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2943     Inst = BranchInst::Create(BB);
2944     return false;
2945   }
2946
2947   if (Op0->getType() != Type::getInt1Ty(Context))
2948     return Error(Loc, "branch condition must have 'i1' type");
2949
2950   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2951       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
2952       ParseToken(lltok::comma, "expected ',' after true destination") ||
2953       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
2954     return true;
2955
2956   Inst = BranchInst::Create(Op1, Op2, Op0);
2957   return false;
2958 }
2959
2960 /// ParseSwitch
2961 ///  Instruction
2962 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2963 ///  JumpTable
2964 ///    ::= (TypeAndValue ',' TypeAndValue)*
2965 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2966   LocTy CondLoc, BBLoc;
2967   Value *Cond;
2968   BasicBlock *DefaultBB;
2969   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2970       ParseToken(lltok::comma, "expected ',' after switch condition") ||
2971       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
2972       ParseToken(lltok::lsquare, "expected '[' with switch table"))
2973     return true;
2974
2975   if (!isa<IntegerType>(Cond->getType()))
2976     return Error(CondLoc, "switch condition must have integer type");
2977
2978   // Parse the jump table pairs.
2979   SmallPtrSet<Value*, 32> SeenCases;
2980   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2981   while (Lex.getKind() != lltok::rsquare) {
2982     Value *Constant;
2983     BasicBlock *DestBB;
2984
2985     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2986         ParseToken(lltok::comma, "expected ',' after case value") ||
2987         ParseTypeAndBasicBlock(DestBB, PFS))
2988       return true;
2989     
2990     if (!SeenCases.insert(Constant))
2991       return Error(CondLoc, "duplicate case value in switch");
2992     if (!isa<ConstantInt>(Constant))
2993       return Error(CondLoc, "case value is not a constant integer");
2994
2995     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
2996   }
2997
2998   Lex.Lex();  // Eat the ']'.
2999
3000   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3001   for (unsigned i = 0, e = Table.size(); i != e; ++i)
3002     SI->addCase(Table[i].first, Table[i].second);
3003   Inst = SI;
3004   return false;
3005 }
3006
3007 /// ParseIndirectBr
3008 ///  Instruction
3009 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3010 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3011   LocTy AddrLoc;
3012   Value *Address;
3013   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3014       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3015       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3016     return true;
3017   
3018   if (!isa<PointerType>(Address->getType()))
3019     return Error(AddrLoc, "indirectbr address must have pointer type");
3020   
3021   // Parse the destination list.
3022   SmallVector<BasicBlock*, 16> DestList;
3023   
3024   if (Lex.getKind() != lltok::rsquare) {
3025     BasicBlock *DestBB;
3026     if (ParseTypeAndBasicBlock(DestBB, PFS))
3027       return true;
3028     DestList.push_back(DestBB);
3029     
3030     while (EatIfPresent(lltok::comma)) {
3031       if (ParseTypeAndBasicBlock(DestBB, PFS))
3032         return true;
3033       DestList.push_back(DestBB);
3034     }
3035   }
3036   
3037   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3038     return true;
3039
3040   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3041   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3042     IBI->addDestination(DestList[i]);
3043   Inst = IBI;
3044   return false;
3045 }
3046
3047
3048 /// ParseInvoke
3049 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3050 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3051 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3052   LocTy CallLoc = Lex.getLoc();
3053   unsigned RetAttrs, FnAttrs;
3054   CallingConv::ID CC;
3055   PATypeHolder RetType(Type::getVoidTy(Context));
3056   LocTy RetTypeLoc;
3057   ValID CalleeID;
3058   SmallVector<ParamInfo, 16> ArgList;
3059
3060   BasicBlock *NormalBB, *UnwindBB;
3061   if (ParseOptionalCallingConv(CC) ||
3062       ParseOptionalAttrs(RetAttrs, 1) ||
3063       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3064       ParseValID(CalleeID) ||
3065       ParseParameterList(ArgList, PFS) ||
3066       ParseOptionalAttrs(FnAttrs, 2) ||
3067       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3068       ParseTypeAndBasicBlock(NormalBB, PFS) ||
3069       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3070       ParseTypeAndBasicBlock(UnwindBB, PFS))
3071     return true;
3072
3073   // If RetType is a non-function pointer type, then this is the short syntax
3074   // for the call, which means that RetType is just the return type.  Infer the
3075   // rest of the function argument types from the arguments that are present.
3076   const PointerType *PFTy = 0;
3077   const FunctionType *Ty = 0;
3078   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3079       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3080     // Pull out the types of all of the arguments...
3081     std::vector<const Type*> ParamTypes;
3082     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3083       ParamTypes.push_back(ArgList[i].V->getType());
3084
3085     if (!FunctionType::isValidReturnType(RetType))
3086       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3087
3088     Ty = FunctionType::get(RetType, ParamTypes, false);
3089     PFTy = PointerType::getUnqual(Ty);
3090   }
3091
3092   // Look up the callee.
3093   Value *Callee;
3094   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3095
3096   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3097   // function attributes.
3098   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3099   if (FnAttrs & ObsoleteFuncAttrs) {
3100     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3101     FnAttrs &= ~ObsoleteFuncAttrs;
3102   }
3103
3104   // Set up the Attributes for the function.
3105   SmallVector<AttributeWithIndex, 8> Attrs;
3106   if (RetAttrs != Attribute::None)
3107     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3108
3109   SmallVector<Value*, 8> Args;
3110
3111   // Loop through FunctionType's arguments and ensure they are specified
3112   // correctly.  Also, gather any parameter attributes.
3113   FunctionType::param_iterator I = Ty->param_begin();
3114   FunctionType::param_iterator E = Ty->param_end();
3115   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3116     const Type *ExpectedTy = 0;
3117     if (I != E) {
3118       ExpectedTy = *I++;
3119     } else if (!Ty->isVarArg()) {
3120       return Error(ArgList[i].Loc, "too many arguments specified");
3121     }
3122
3123     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3124       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3125                    ExpectedTy->getDescription() + "'");
3126     Args.push_back(ArgList[i].V);
3127     if (ArgList[i].Attrs != Attribute::None)
3128       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3129   }
3130
3131   if (I != E)
3132     return Error(CallLoc, "not enough parameters specified for call");
3133
3134   if (FnAttrs != Attribute::None)
3135     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3136
3137   // Finish off the Attributes and check them
3138   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3139
3140   InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3141                                       Args.begin(), Args.end());
3142   II->setCallingConv(CC);
3143   II->setAttributes(PAL);
3144   Inst = II;
3145   return false;
3146 }
3147
3148
3149
3150 //===----------------------------------------------------------------------===//
3151 // Binary Operators.
3152 //===----------------------------------------------------------------------===//
3153
3154 /// ParseArithmetic
3155 ///  ::= ArithmeticOps TypeAndValue ',' Value
3156 ///
3157 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
3158 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3159 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3160                                unsigned Opc, unsigned OperandType) {
3161   LocTy Loc; Value *LHS, *RHS;
3162   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3163       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3164       ParseValue(LHS->getType(), RHS, PFS))
3165     return true;
3166
3167   bool Valid;
3168   switch (OperandType) {
3169   default: llvm_unreachable("Unknown operand type!");
3170   case 0: // int or FP.
3171     Valid = LHS->getType()->isIntOrIntVector() ||
3172             LHS->getType()->isFPOrFPVector();
3173     break;
3174   case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3175   case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3176   }
3177
3178   if (!Valid)
3179     return Error(Loc, "invalid operand type for instruction");
3180
3181   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3182   return false;
3183 }
3184
3185 /// ParseLogical
3186 ///  ::= ArithmeticOps TypeAndValue ',' Value {
3187 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3188                             unsigned Opc) {
3189   LocTy Loc; Value *LHS, *RHS;
3190   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3191       ParseToken(lltok::comma, "expected ',' in logical operation") ||
3192       ParseValue(LHS->getType(), RHS, PFS))
3193     return true;
3194
3195   if (!LHS->getType()->isIntOrIntVector())
3196     return Error(Loc,"instruction requires integer or integer vector operands");
3197
3198   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3199   return false;
3200 }
3201
3202
3203 /// ParseCompare
3204 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3205 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3206 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3207                             unsigned Opc) {
3208   // Parse the integer/fp comparison predicate.
3209   LocTy Loc;
3210   unsigned Pred;
3211   Value *LHS, *RHS;
3212   if (ParseCmpPredicate(Pred, Opc) ||
3213       ParseTypeAndValue(LHS, Loc, PFS) ||
3214       ParseToken(lltok::comma, "expected ',' after compare value") ||
3215       ParseValue(LHS->getType(), RHS, PFS))
3216     return true;
3217
3218   if (Opc == Instruction::FCmp) {
3219     if (!LHS->getType()->isFPOrFPVector())
3220       return Error(Loc, "fcmp requires floating point operands");
3221     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3222   } else {
3223     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3224     if (!LHS->getType()->isIntOrIntVector() &&
3225         !isa<PointerType>(LHS->getType()))
3226       return Error(Loc, "icmp requires integer operands");
3227     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3228   }
3229   return false;
3230 }
3231
3232 //===----------------------------------------------------------------------===//
3233 // Other Instructions.
3234 //===----------------------------------------------------------------------===//
3235
3236
3237 /// ParseCast
3238 ///   ::= CastOpc TypeAndValue 'to' Type
3239 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3240                          unsigned Opc) {
3241   LocTy Loc;  Value *Op;
3242   PATypeHolder DestTy(Type::getVoidTy(Context));
3243   if (ParseTypeAndValue(Op, Loc, PFS) ||
3244       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3245       ParseType(DestTy))
3246     return true;
3247
3248   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3249     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3250     return Error(Loc, "invalid cast opcode for cast from '" +
3251                  Op->getType()->getDescription() + "' to '" +
3252                  DestTy->getDescription() + "'");
3253   }
3254   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3255   return false;
3256 }
3257
3258 /// ParseSelect
3259 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3260 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3261   LocTy Loc;
3262   Value *Op0, *Op1, *Op2;
3263   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3264       ParseToken(lltok::comma, "expected ',' after select condition") ||
3265       ParseTypeAndValue(Op1, PFS) ||
3266       ParseToken(lltok::comma, "expected ',' after select value") ||
3267       ParseTypeAndValue(Op2, PFS))
3268     return true;
3269
3270   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3271     return Error(Loc, Reason);
3272
3273   Inst = SelectInst::Create(Op0, Op1, Op2);
3274   return false;
3275 }
3276
3277 /// ParseVA_Arg
3278 ///   ::= 'va_arg' TypeAndValue ',' Type
3279 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3280   Value *Op;
3281   PATypeHolder EltTy(Type::getVoidTy(Context));
3282   LocTy TypeLoc;
3283   if (ParseTypeAndValue(Op, PFS) ||
3284       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3285       ParseType(EltTy, TypeLoc))
3286     return true;
3287
3288   if (!EltTy->isFirstClassType())
3289     return Error(TypeLoc, "va_arg requires operand with first class type");
3290
3291   Inst = new VAArgInst(Op, EltTy);
3292   return false;
3293 }
3294
3295 /// ParseExtractElement
3296 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3297 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3298   LocTy Loc;
3299   Value *Op0, *Op1;
3300   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3301       ParseToken(lltok::comma, "expected ',' after extract value") ||
3302       ParseTypeAndValue(Op1, PFS))
3303     return true;
3304
3305   if (!ExtractElementInst::isValidOperands(Op0, Op1))
3306     return Error(Loc, "invalid extractelement operands");
3307
3308   Inst = ExtractElementInst::Create(Op0, Op1);
3309   return false;
3310 }
3311
3312 /// ParseInsertElement
3313 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3314 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3315   LocTy Loc;
3316   Value *Op0, *Op1, *Op2;
3317   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3318       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3319       ParseTypeAndValue(Op1, PFS) ||
3320       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3321       ParseTypeAndValue(Op2, PFS))
3322     return true;
3323
3324   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3325     return Error(Loc, "invalid insertelement operands");
3326
3327   Inst = InsertElementInst::Create(Op0, Op1, Op2);
3328   return false;
3329 }
3330
3331 /// ParseShuffleVector
3332 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3333 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3334   LocTy Loc;
3335   Value *Op0, *Op1, *Op2;
3336   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3337       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3338       ParseTypeAndValue(Op1, PFS) ||
3339       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3340       ParseTypeAndValue(Op2, PFS))
3341     return true;
3342
3343   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3344     return Error(Loc, "invalid extractelement operands");
3345
3346   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3347   return false;
3348 }
3349
3350 /// ParsePHI
3351 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3352 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3353   PATypeHolder Ty(Type::getVoidTy(Context));
3354   Value *Op0, *Op1;
3355   LocTy TypeLoc = Lex.getLoc();
3356
3357   if (ParseType(Ty) ||
3358       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3359       ParseValue(Ty, Op0, PFS) ||
3360       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3361       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3362       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3363     return true;
3364
3365   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3366   while (1) {
3367     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3368
3369     if (!EatIfPresent(lltok::comma))
3370       break;
3371
3372     if (Lex.getKind() == lltok::NamedOrCustomMD)
3373       break;
3374
3375     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3376         ParseValue(Ty, Op0, PFS) ||
3377         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3378         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3379         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3380       return true;
3381   }
3382
3383   if (Lex.getKind() == lltok::NamedOrCustomMD)
3384     if (ParseOptionalCustomMetadata()) return true;
3385
3386   if (!Ty->isFirstClassType())
3387     return Error(TypeLoc, "phi node must have first class type");
3388
3389   PHINode *PN = PHINode::Create(Ty);
3390   PN->reserveOperandSpace(PHIVals.size());
3391   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3392     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3393   Inst = PN;
3394   return false;
3395 }
3396
3397 /// ParseCall
3398 ///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3399 ///       ParameterList OptionalAttrs
3400 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3401                          bool isTail) {
3402   unsigned RetAttrs, FnAttrs;
3403   CallingConv::ID CC;
3404   PATypeHolder RetType(Type::getVoidTy(Context));
3405   LocTy RetTypeLoc;
3406   ValID CalleeID;
3407   SmallVector<ParamInfo, 16> ArgList;
3408   LocTy CallLoc = Lex.getLoc();
3409
3410   if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3411       ParseOptionalCallingConv(CC) ||
3412       ParseOptionalAttrs(RetAttrs, 1) ||
3413       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3414       ParseValID(CalleeID) ||
3415       ParseParameterList(ArgList, PFS) ||
3416       ParseOptionalAttrs(FnAttrs, 2))
3417     return true;
3418
3419   // If RetType is a non-function pointer type, then this is the short syntax
3420   // for the call, which means that RetType is just the return type.  Infer the
3421   // rest of the function argument types from the arguments that are present.
3422   const PointerType *PFTy = 0;
3423   const FunctionType *Ty = 0;
3424   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3425       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3426     // Pull out the types of all of the arguments...
3427     std::vector<const Type*> ParamTypes;
3428     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3429       ParamTypes.push_back(ArgList[i].V->getType());
3430
3431     if (!FunctionType::isValidReturnType(RetType))
3432       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3433
3434     Ty = FunctionType::get(RetType, ParamTypes, false);
3435     PFTy = PointerType::getUnqual(Ty);
3436   }
3437
3438   // Look up the callee.
3439   Value *Callee;
3440   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3441
3442   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3443   // function attributes.
3444   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3445   if (FnAttrs & ObsoleteFuncAttrs) {
3446     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3447     FnAttrs &= ~ObsoleteFuncAttrs;
3448   }
3449
3450   // Set up the Attributes for the function.
3451   SmallVector<AttributeWithIndex, 8> Attrs;
3452   if (RetAttrs != Attribute::None)
3453     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3454
3455   SmallVector<Value*, 8> Args;
3456
3457   // Loop through FunctionType's arguments and ensure they are specified
3458   // correctly.  Also, gather any parameter attributes.
3459   FunctionType::param_iterator I = Ty->param_begin();
3460   FunctionType::param_iterator E = Ty->param_end();
3461   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3462     const Type *ExpectedTy = 0;
3463     if (I != E) {
3464       ExpectedTy = *I++;
3465     } else if (!Ty->isVarArg()) {
3466       return Error(ArgList[i].Loc, "too many arguments specified");
3467     }
3468
3469     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3470       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3471                    ExpectedTy->getDescription() + "'");
3472     Args.push_back(ArgList[i].V);
3473     if (ArgList[i].Attrs != Attribute::None)
3474       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3475   }
3476
3477   if (I != E)
3478     return Error(CallLoc, "not enough parameters specified for call");
3479
3480   if (FnAttrs != Attribute::None)
3481     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3482
3483   // Finish off the Attributes and check them
3484   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3485
3486   CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3487   CI->setTailCall(isTail);
3488   CI->setCallingConv(CC);
3489   CI->setAttributes(PAL);
3490   Inst = CI;
3491   return false;
3492 }
3493
3494 //===----------------------------------------------------------------------===//
3495 // Memory Instructions.
3496 //===----------------------------------------------------------------------===//
3497
3498 /// ParseAlloc
3499 ///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3500 ///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3501 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3502                           BasicBlock* BB, bool isAlloca) {
3503   PATypeHolder Ty(Type::getVoidTy(Context));
3504   Value *Size = 0;
3505   LocTy SizeLoc;
3506   unsigned Alignment = 0;
3507   if (ParseType(Ty)) return true;
3508
3509   if (EatIfPresent(lltok::comma)) {
3510     if (Lex.getKind() == lltok::kw_align 
3511         || Lex.getKind() == lltok::NamedOrCustomMD) {
3512       if (ParseOptionalInfo(Alignment)) return true;
3513     } else {
3514       if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3515       if (EatIfPresent(lltok::comma))
3516         if (ParseOptionalInfo(Alignment)) return true;
3517     }
3518   }
3519
3520   if (Size && Size->getType() != Type::getInt32Ty(Context))
3521     return Error(SizeLoc, "element count must be i32");
3522
3523   if (isAlloca) {
3524     Inst = new AllocaInst(Ty, Size, Alignment);
3525     return false;
3526   }
3527
3528   // Autoupgrade old malloc instruction to malloc call.
3529   // FIXME: Remove in LLVM 3.0.
3530   const Type *IntPtrTy = Type::getInt32Ty(Context);
3531   if (!MallocF)
3532     // Prototype malloc as "void *(int32)".
3533     // This function is renamed as "malloc" in ValidateEndOfModule().
3534     MallocF = cast<Function>(
3535        M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
3536   Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, Size, MallocF);
3537   return false;
3538 }
3539
3540 /// ParseFree
3541 ///   ::= 'free' TypeAndValue
3542 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3543                          BasicBlock* BB) {
3544   Value *Val; LocTy Loc;
3545   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3546   if (!isa<PointerType>(Val->getType()))
3547     return Error(Loc, "operand to free must be a pointer");
3548   Inst = CallInst::CreateFree(Val, BB);
3549   return false;
3550 }
3551
3552 /// ParseLoad
3553 ///   ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3554 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3555                          bool isVolatile) {
3556   Value *Val; LocTy Loc;
3557   unsigned Alignment = 0;
3558   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3559
3560   if (EatIfPresent(lltok::comma))
3561     if (ParseOptionalInfo(Alignment)) return true;
3562
3563   if (!isa<PointerType>(Val->getType()) ||
3564       !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3565     return Error(Loc, "load operand must be a pointer to a first class type");
3566
3567   Inst = new LoadInst(Val, "", isVolatile, Alignment);
3568   return false;
3569 }
3570
3571 /// ParseStore
3572 ///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3573 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3574                           bool isVolatile) {
3575   Value *Val, *Ptr; LocTy Loc, PtrLoc;
3576   unsigned Alignment = 0;
3577   if (ParseTypeAndValue(Val, Loc, PFS) ||
3578       ParseToken(lltok::comma, "expected ',' after store operand") ||
3579       ParseTypeAndValue(Ptr, PtrLoc, PFS))
3580     return true;
3581
3582   if (EatIfPresent(lltok::comma))
3583     if (ParseOptionalInfo(Alignment)) return true;
3584
3585   if (!isa<PointerType>(Ptr->getType()))
3586     return Error(PtrLoc, "store operand must be a pointer");
3587   if (!Val->getType()->isFirstClassType())
3588     return Error(Loc, "store operand must be a first class value");
3589   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3590     return Error(Loc, "stored value and pointer type do not match");
3591
3592   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3593   return false;
3594 }
3595
3596 /// ParseGetResult
3597 ///   ::= 'getresult' TypeAndValue ',' i32
3598 /// FIXME: Remove support for getresult in LLVM 3.0
3599 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3600   Value *Val; LocTy ValLoc, EltLoc;
3601   unsigned Element;
3602   if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3603       ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3604       ParseUInt32(Element, EltLoc))
3605     return true;
3606
3607   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3608     return Error(ValLoc, "getresult inst requires an aggregate operand");
3609   if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3610     return Error(EltLoc, "invalid getresult index for value");
3611   Inst = ExtractValueInst::Create(Val, Element);
3612   return false;
3613 }
3614
3615 /// ParseGetElementPtr
3616 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3617 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3618   Value *Ptr, *Val; LocTy Loc, EltLoc;
3619
3620   bool InBounds = EatIfPresent(lltok::kw_inbounds);
3621
3622   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3623
3624   if (!isa<PointerType>(Ptr->getType()))
3625     return Error(Loc, "base of getelementptr must be a pointer");
3626
3627   SmallVector<Value*, 16> Indices;
3628   while (EatIfPresent(lltok::comma)) {
3629     if (Lex.getKind() == lltok::NamedOrCustomMD)
3630       break;
3631     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3632     if (!isa<IntegerType>(Val->getType()))
3633       return Error(EltLoc, "getelementptr index must be an integer");
3634     Indices.push_back(Val);
3635   }
3636   if (Lex.getKind() == lltok::NamedOrCustomMD)
3637     if (ParseOptionalCustomMetadata()) return true;
3638
3639   if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3640                                          Indices.begin(), Indices.end()))
3641     return Error(Loc, "invalid getelementptr indices");
3642   Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3643   if (InBounds)
3644     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3645   return false;
3646 }
3647
3648 /// ParseExtractValue
3649 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
3650 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3651   Value *Val; LocTy Loc;
3652   SmallVector<unsigned, 4> Indices;
3653   if (ParseTypeAndValue(Val, Loc, PFS) ||
3654       ParseIndexList(Indices))
3655     return true;
3656
3657   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3658     return Error(Loc, "extractvalue operand must be array or struct");
3659
3660   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3661                                         Indices.end()))
3662     return Error(Loc, "invalid indices for extractvalue");
3663   Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3664   return false;
3665 }
3666
3667 /// ParseInsertValue
3668 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3669 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3670   Value *Val0, *Val1; LocTy Loc0, Loc1;
3671   SmallVector<unsigned, 4> Indices;
3672   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3673       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3674       ParseTypeAndValue(Val1, Loc1, PFS) ||
3675       ParseIndexList(Indices))
3676     return true;
3677
3678   if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3679     return Error(Loc0, "extractvalue operand must be array or struct");
3680
3681   if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3682                                         Indices.end()))
3683     return Error(Loc0, "invalid indices for insertvalue");
3684   Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3685   return false;
3686 }
3687
3688 //===----------------------------------------------------------------------===//
3689 // Embedded metadata.
3690 //===----------------------------------------------------------------------===//
3691
3692 /// ParseMDNodeVector
3693 ///   ::= Element (',' Element)*
3694 /// Element
3695 ///   ::= 'null' | TypeAndValue
3696 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3697   assert(Lex.getKind() == lltok::lbrace);
3698   Lex.Lex();
3699   do {
3700     Value *V = 0;
3701     if (Lex.getKind() == lltok::kw_null) {
3702       Lex.Lex();
3703       V = 0;
3704     } else {
3705       PATypeHolder Ty(Type::getVoidTy(Context));
3706       if (ParseType(Ty)) return true;
3707       if (Lex.getKind() == lltok::Metadata) {
3708         Lex.Lex();
3709         MetadataBase *Node = 0;
3710         if (!ParseMDNode(Node))
3711           V = Node;
3712         else {
3713           MetadataBase *MDS = 0;
3714           if (ParseMDString(MDS)) return true;
3715           V = MDS;
3716         }
3717       } else {
3718         Constant *C;
3719         if (ParseGlobalValue(Ty, C)) return true;
3720         V = C;
3721       }
3722     }
3723     Elts.push_back(V);
3724   } while (EatIfPresent(lltok::comma));
3725
3726   return false;
3727 }