fix PR5295 where the .ll parser didn't reject a function after a global
[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 /// FunctionHeader
2416 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2417 ///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2418 ///       OptionalAlign OptGC
2419 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2420   // Parse the linkage.
2421   LocTy LinkageLoc = Lex.getLoc();
2422   unsigned Linkage;
2423
2424   unsigned Visibility, RetAttrs;
2425   CallingConv::ID CC;
2426   PATypeHolder RetType(Type::getVoidTy(Context));
2427   LocTy RetTypeLoc = Lex.getLoc();
2428   if (ParseOptionalLinkage(Linkage) ||
2429       ParseOptionalVisibility(Visibility) ||
2430       ParseOptionalCallingConv(CC) ||
2431       ParseOptionalAttrs(RetAttrs, 1) ||
2432       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2433     return true;
2434
2435   // Verify that the linkage is ok.
2436   switch ((GlobalValue::LinkageTypes)Linkage) {
2437   case GlobalValue::ExternalLinkage:
2438     break; // always ok.
2439   case GlobalValue::DLLImportLinkage:
2440   case GlobalValue::ExternalWeakLinkage:
2441     if (isDefine)
2442       return Error(LinkageLoc, "invalid linkage for function definition");
2443     break;
2444   case GlobalValue::PrivateLinkage:
2445   case GlobalValue::LinkerPrivateLinkage:
2446   case GlobalValue::InternalLinkage:
2447   case GlobalValue::AvailableExternallyLinkage:
2448   case GlobalValue::LinkOnceAnyLinkage:
2449   case GlobalValue::LinkOnceODRLinkage:
2450   case GlobalValue::WeakAnyLinkage:
2451   case GlobalValue::WeakODRLinkage:
2452   case GlobalValue::DLLExportLinkage:
2453     if (!isDefine)
2454       return Error(LinkageLoc, "invalid linkage for function declaration");
2455     break;
2456   case GlobalValue::AppendingLinkage:
2457   case GlobalValue::GhostLinkage:
2458   case GlobalValue::CommonLinkage:
2459     return Error(LinkageLoc, "invalid function linkage type");
2460   }
2461
2462   if (!FunctionType::isValidReturnType(RetType) ||
2463       isa<OpaqueType>(RetType))
2464     return Error(RetTypeLoc, "invalid function return type");
2465
2466   LocTy NameLoc = Lex.getLoc();
2467
2468   std::string FunctionName;
2469   if (Lex.getKind() == lltok::GlobalVar) {
2470     FunctionName = Lex.getStrVal();
2471   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2472     unsigned NameID = Lex.getUIntVal();
2473
2474     if (NameID != NumberedVals.size())
2475       return TokError("function expected to be numbered '%" +
2476                       utostr(NumberedVals.size()) + "'");
2477   } else {
2478     return TokError("expected function name");
2479   }
2480
2481   Lex.Lex();
2482
2483   if (Lex.getKind() != lltok::lparen)
2484     return TokError("expected '(' in function argument list");
2485
2486   std::vector<ArgInfo> ArgList;
2487   bool isVarArg;
2488   unsigned FuncAttrs;
2489   std::string Section;
2490   unsigned Alignment;
2491   std::string GC;
2492
2493   if (ParseArgumentList(ArgList, isVarArg, false) ||
2494       ParseOptionalAttrs(FuncAttrs, 2) ||
2495       (EatIfPresent(lltok::kw_section) &&
2496        ParseStringConstant(Section)) ||
2497       ParseOptionalAlignment(Alignment) ||
2498       (EatIfPresent(lltok::kw_gc) &&
2499        ParseStringConstant(GC)))
2500     return true;
2501
2502   // If the alignment was parsed as an attribute, move to the alignment field.
2503   if (FuncAttrs & Attribute::Alignment) {
2504     Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2505     FuncAttrs &= ~Attribute::Alignment;
2506   }
2507
2508   // Okay, if we got here, the function is syntactically valid.  Convert types
2509   // and do semantic checks.
2510   std::vector<const Type*> ParamTypeList;
2511   SmallVector<AttributeWithIndex, 8> Attrs;
2512   // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2513   // attributes.
2514   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2515   if (FuncAttrs & ObsoleteFuncAttrs) {
2516     RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2517     FuncAttrs &= ~ObsoleteFuncAttrs;
2518   }
2519
2520   if (RetAttrs != Attribute::None)
2521     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2522
2523   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2524     ParamTypeList.push_back(ArgList[i].Type);
2525     if (ArgList[i].Attrs != Attribute::None)
2526       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2527   }
2528
2529   if (FuncAttrs != Attribute::None)
2530     Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2531
2532   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2533
2534   if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2535       RetType != Type::getVoidTy(Context))
2536     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2537
2538   const FunctionType *FT =
2539     FunctionType::get(RetType, ParamTypeList, isVarArg);
2540   const PointerType *PFT = PointerType::getUnqual(FT);
2541
2542   Fn = 0;
2543   if (!FunctionName.empty()) {
2544     // If this was a definition of a forward reference, remove the definition
2545     // from the forward reference table and fill in the forward ref.
2546     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2547       ForwardRefVals.find(FunctionName);
2548     if (FRVI != ForwardRefVals.end()) {
2549       Fn = M->getFunction(FunctionName);
2550       ForwardRefVals.erase(FRVI);
2551     } else if ((Fn = M->getFunction(FunctionName))) {
2552       // If this function already exists in the symbol table, then it is
2553       // multiply defined.  We accept a few cases for old backwards compat.
2554       // FIXME: Remove this stuff for LLVM 3.0.
2555       if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2556           (!Fn->isDeclaration() && isDefine)) {
2557         // If the redefinition has different type or different attributes,
2558         // reject it.  If both have bodies, reject it.
2559         return Error(NameLoc, "invalid redefinition of function '" +
2560                      FunctionName + "'");
2561       } else if (Fn->isDeclaration()) {
2562         // Make sure to strip off any argument names so we can't get conflicts.
2563         for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2564              AI != AE; ++AI)
2565           AI->setName("");
2566       }
2567     } else if (M->getNamedValue(FunctionName)) {
2568       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2569     }
2570
2571   } else {
2572     // If this is a definition of a forward referenced function, make sure the
2573     // types agree.
2574     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2575       = ForwardRefValIDs.find(NumberedVals.size());
2576     if (I != ForwardRefValIDs.end()) {
2577       Fn = cast<Function>(I->second.first);
2578       if (Fn->getType() != PFT)
2579         return Error(NameLoc, "type of definition and forward reference of '@" +
2580                      utostr(NumberedVals.size()) +"' disagree");
2581       ForwardRefValIDs.erase(I);
2582     }
2583   }
2584
2585   if (Fn == 0)
2586     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2587   else // Move the forward-reference to the correct spot in the module.
2588     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2589
2590   if (FunctionName.empty())
2591     NumberedVals.push_back(Fn);
2592
2593   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2594   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2595   Fn->setCallingConv(CC);
2596   Fn->setAttributes(PAL);
2597   Fn->setAlignment(Alignment);
2598   Fn->setSection(Section);
2599   if (!GC.empty()) Fn->setGC(GC.c_str());
2600
2601   // Add all of the arguments we parsed to the function.
2602   Function::arg_iterator ArgIt = Fn->arg_begin();
2603   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2604     // If the argument has a name, insert it into the argument symbol table.
2605     if (ArgList[i].Name.empty()) continue;
2606
2607     // Set the name, if it conflicted, it will be auto-renamed.
2608     ArgIt->setName(ArgList[i].Name);
2609
2610     if (ArgIt->getNameStr() != ArgList[i].Name)
2611       return Error(ArgList[i].Loc, "redefinition of argument '%" +
2612                    ArgList[i].Name + "'");
2613   }
2614
2615   return false;
2616 }
2617
2618
2619 /// ParseFunctionBody
2620 ///   ::= '{' BasicBlock+ '}'
2621 ///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
2622 ///
2623 bool LLParser::ParseFunctionBody(Function &Fn) {
2624   if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2625     return TokError("expected '{' in function body");
2626   Lex.Lex();  // eat the {.
2627
2628   PerFunctionState PFS(*this, Fn);
2629
2630   while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2631     if (ParseBasicBlock(PFS)) return true;
2632
2633   // Eat the }.
2634   Lex.Lex();
2635
2636   // Verify function is ok.
2637   return PFS.VerifyFunctionComplete();
2638 }
2639
2640 /// ParseBasicBlock
2641 ///   ::= LabelStr? Instruction*
2642 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2643   // If this basic block starts out with a name, remember it.
2644   std::string Name;
2645   LocTy NameLoc = Lex.getLoc();
2646   if (Lex.getKind() == lltok::LabelStr) {
2647     Name = Lex.getStrVal();
2648     Lex.Lex();
2649   }
2650
2651   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2652   if (BB == 0) return true;
2653
2654   std::string NameStr;
2655
2656   // Parse the instructions in this block until we get a terminator.
2657   Instruction *Inst;
2658   do {
2659     // This instruction may have three possibilities for a name: a) none
2660     // specified, b) name specified "%foo =", c) number specified: "%4 =".
2661     LocTy NameLoc = Lex.getLoc();
2662     int NameID = -1;
2663     NameStr = "";
2664
2665     if (Lex.getKind() == lltok::LocalVarID) {
2666       NameID = Lex.getUIntVal();
2667       Lex.Lex();
2668       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2669         return true;
2670     } else if (Lex.getKind() == lltok::LocalVar ||
2671                // FIXME: REMOVE IN LLVM 3.0
2672                Lex.getKind() == lltok::StringConstant) {
2673       NameStr = Lex.getStrVal();
2674       Lex.Lex();
2675       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2676         return true;
2677     }
2678
2679     if (ParseInstruction(Inst, BB, PFS)) return true;
2680     if (EatIfPresent(lltok::comma))
2681       ParseOptionalCustomMetadata();
2682
2683     // Set metadata attached with this instruction.
2684     MetadataContext &TheMetadata = M->getContext().getMetadata();
2685     for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
2686            MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
2687       TheMetadata.addMD(MDI->first, MDI->second, Inst);
2688     MDsOnInst.clear();
2689
2690     BB->getInstList().push_back(Inst);
2691
2692     // Set the name on the instruction.
2693     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2694   } while (!isa<TerminatorInst>(Inst));
2695
2696   return false;
2697 }
2698
2699 //===----------------------------------------------------------------------===//
2700 // Instruction Parsing.
2701 //===----------------------------------------------------------------------===//
2702
2703 /// ParseInstruction - Parse one of the many different instructions.
2704 ///
2705 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2706                                 PerFunctionState &PFS) {
2707   lltok::Kind Token = Lex.getKind();
2708   if (Token == lltok::Eof)
2709     return TokError("found end of file when expecting more instructions");
2710   LocTy Loc = Lex.getLoc();
2711   unsigned KeywordVal = Lex.getUIntVal();
2712   Lex.Lex();  // Eat the keyword.
2713
2714   switch (Token) {
2715   default:                    return Error(Loc, "expected instruction opcode");
2716   // Terminator Instructions.
2717   case lltok::kw_unwind:      Inst = new UnwindInst(Context); return false;
2718   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2719   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
2720   case lltok::kw_br:          return ParseBr(Inst, PFS);
2721   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
2722   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
2723   // Binary Operators.
2724   case lltok::kw_add:
2725   case lltok::kw_sub:
2726   case lltok::kw_mul: {
2727     bool NUW = false;
2728     bool NSW = false;
2729     LocTy ModifierLoc = Lex.getLoc();
2730     if (EatIfPresent(lltok::kw_nuw))
2731       NUW = true;
2732     if (EatIfPresent(lltok::kw_nsw)) {
2733       NSW = true;
2734       if (EatIfPresent(lltok::kw_nuw))
2735         NUW = true;
2736     }
2737     // API compatibility: Accept either integer or floating-point types.
2738     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2739     if (!Result) {
2740       if (!Inst->getType()->isIntOrIntVector()) {
2741         if (NUW)
2742           return Error(ModifierLoc, "nuw only applies to integer operations");
2743         if (NSW)
2744           return Error(ModifierLoc, "nsw only applies to integer operations");
2745       }
2746       if (NUW)
2747         cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2748       if (NSW)
2749         cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2750     }
2751     return Result;
2752   }
2753   case lltok::kw_fadd:
2754   case lltok::kw_fsub:
2755   case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2756
2757   case lltok::kw_sdiv: {
2758     bool Exact = false;
2759     if (EatIfPresent(lltok::kw_exact))
2760       Exact = true;
2761     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2762     if (!Result)
2763       if (Exact)
2764         cast<BinaryOperator>(Inst)->setIsExact(true);
2765     return Result;
2766   }
2767
2768   case lltok::kw_udiv:
2769   case lltok::kw_urem:
2770   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2771   case lltok::kw_fdiv:
2772   case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2773   case lltok::kw_shl:
2774   case lltok::kw_lshr:
2775   case lltok::kw_ashr:
2776   case lltok::kw_and:
2777   case lltok::kw_or:
2778   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
2779   case lltok::kw_icmp:
2780   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
2781   // Casts.
2782   case lltok::kw_trunc:
2783   case lltok::kw_zext:
2784   case lltok::kw_sext:
2785   case lltok::kw_fptrunc:
2786   case lltok::kw_fpext:
2787   case lltok::kw_bitcast:
2788   case lltok::kw_uitofp:
2789   case lltok::kw_sitofp:
2790   case lltok::kw_fptoui:
2791   case lltok::kw_fptosi:
2792   case lltok::kw_inttoptr:
2793   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
2794   // Other.
2795   case lltok::kw_select:         return ParseSelect(Inst, PFS);
2796   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
2797   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2798   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
2799   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
2800   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
2801   case lltok::kw_call:           return ParseCall(Inst, PFS, false);
2802   case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
2803   // Memory.
2804   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
2805   case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, BB, false);
2806   case lltok::kw_free:           return ParseFree(Inst, PFS, BB);
2807   case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
2808   case lltok::kw_store:          return ParseStore(Inst, PFS, false);
2809   case lltok::kw_volatile:
2810     if (EatIfPresent(lltok::kw_load))
2811       return ParseLoad(Inst, PFS, true);
2812     else if (EatIfPresent(lltok::kw_store))
2813       return ParseStore(Inst, PFS, true);
2814     else
2815       return TokError("expected 'load' or 'store'");
2816   case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
2817   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2818   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
2819   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
2820   }
2821 }
2822
2823 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2824 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2825   if (Opc == Instruction::FCmp) {
2826     switch (Lex.getKind()) {
2827     default: TokError("expected fcmp predicate (e.g. 'oeq')");
2828     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2829     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2830     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2831     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2832     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2833     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2834     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2835     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2836     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2837     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2838     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2839     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2840     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2841     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2842     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2843     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2844     }
2845   } else {
2846     switch (Lex.getKind()) {
2847     default: TokError("expected icmp predicate (e.g. 'eq')");
2848     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
2849     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
2850     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2851     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2852     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2853     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2854     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2855     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2856     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2857     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2858     }
2859   }
2860   Lex.Lex();
2861   return false;
2862 }
2863
2864 //===----------------------------------------------------------------------===//
2865 // Terminator Instructions.
2866 //===----------------------------------------------------------------------===//
2867
2868 /// ParseRet - Parse a return instruction.
2869 ///   ::= 'ret' void (',' !dbg, !1)
2870 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)
2871 ///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  (',' !dbg, !1)
2872 ///         [[obsolete: LLVM 3.0]]
2873 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2874                         PerFunctionState &PFS) {
2875   PATypeHolder Ty(Type::getVoidTy(Context));
2876   if (ParseType(Ty, true /*void allowed*/)) return true;
2877
2878   if (Ty->isVoidTy()) {
2879     Inst = ReturnInst::Create(Context);
2880     return false;
2881   }
2882
2883   Value *RV;
2884   if (ParseValue(Ty, RV, PFS)) return true;
2885
2886   if (EatIfPresent(lltok::comma)) {
2887     // Parse optional custom metadata, e.g. !dbg
2888     if (Lex.getKind() == lltok::NamedOrCustomMD) {
2889       if (ParseOptionalCustomMetadata()) return true;
2890     } else {
2891       // The normal case is one return value.
2892       // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2893       // of 'ret {i32,i32} {i32 1, i32 2}'
2894       SmallVector<Value*, 8> RVs;
2895       RVs.push_back(RV);
2896
2897       do {
2898         // If optional custom metadata, e.g. !dbg is seen then this is the 
2899         // end of MRV.
2900         if (Lex.getKind() == lltok::NamedOrCustomMD)
2901           break;
2902         if (ParseTypeAndValue(RV, PFS)) return true;
2903         RVs.push_back(RV);
2904       } while (EatIfPresent(lltok::comma));
2905
2906       RV = UndefValue::get(PFS.getFunction().getReturnType());
2907       for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2908         Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2909         BB->getInstList().push_back(I);
2910         RV = I;
2911       }
2912     }
2913   }
2914
2915   Inst = ReturnInst::Create(Context, RV);
2916   return false;
2917 }
2918
2919
2920 /// ParseBr
2921 ///   ::= 'br' TypeAndValue
2922 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2923 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2924   LocTy Loc, Loc2;
2925   Value *Op0, *Op1, *Op2;
2926   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2927
2928   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2929     Inst = BranchInst::Create(BB);
2930     return false;
2931   }
2932
2933   if (Op0->getType() != Type::getInt1Ty(Context))
2934     return Error(Loc, "branch condition must have 'i1' type");
2935
2936   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2937       ParseTypeAndValue(Op1, Loc, PFS) ||
2938       ParseToken(lltok::comma, "expected ',' after true destination") ||
2939       ParseTypeAndValue(Op2, Loc2, PFS))
2940     return true;
2941
2942   if (!isa<BasicBlock>(Op1))
2943     return Error(Loc, "true destination of branch must be a basic block");
2944   if (!isa<BasicBlock>(Op2))
2945     return Error(Loc2, "true destination of branch must be a basic block");
2946
2947   Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2948   return false;
2949 }
2950
2951 /// ParseSwitch
2952 ///  Instruction
2953 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2954 ///  JumpTable
2955 ///    ::= (TypeAndValue ',' TypeAndValue)*
2956 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2957   LocTy CondLoc, BBLoc;
2958   Value *Cond, *DefaultBB;
2959   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2960       ParseToken(lltok::comma, "expected ',' after switch condition") ||
2961       ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2962       ParseToken(lltok::lsquare, "expected '[' with switch table"))
2963     return true;
2964
2965   if (!isa<IntegerType>(Cond->getType()))
2966     return Error(CondLoc, "switch condition must have integer type");
2967   if (!isa<BasicBlock>(DefaultBB))
2968     return Error(BBLoc, "default destination must be a basic block");
2969
2970   // Parse the jump table pairs.
2971   SmallPtrSet<Value*, 32> SeenCases;
2972   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2973   while (Lex.getKind() != lltok::rsquare) {
2974     Value *Constant, *DestBB;
2975
2976     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2977         ParseToken(lltok::comma, "expected ',' after case value") ||
2978         ParseTypeAndValue(DestBB, BBLoc, PFS))
2979       return true;
2980
2981     if (!SeenCases.insert(Constant))
2982       return Error(CondLoc, "duplicate case value in switch");
2983     if (!isa<ConstantInt>(Constant))
2984       return Error(CondLoc, "case value is not a constant integer");
2985     if (!isa<BasicBlock>(DestBB))
2986       return Error(BBLoc, "case destination is not a basic block");
2987
2988     Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2989                                    cast<BasicBlock>(DestBB)));
2990   }
2991
2992   Lex.Lex();  // Eat the ']'.
2993
2994   SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2995                                       Table.size());
2996   for (unsigned i = 0, e = Table.size(); i != e; ++i)
2997     SI->addCase(Table[i].first, Table[i].second);
2998   Inst = SI;
2999   return false;
3000 }
3001
3002 /// ParseInvoke
3003 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3004 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3005 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3006   LocTy CallLoc = Lex.getLoc();
3007   unsigned RetAttrs, FnAttrs;
3008   CallingConv::ID CC;
3009   PATypeHolder RetType(Type::getVoidTy(Context));
3010   LocTy RetTypeLoc;
3011   ValID CalleeID;
3012   SmallVector<ParamInfo, 16> ArgList;
3013
3014   Value *NormalBB, *UnwindBB;
3015   if (ParseOptionalCallingConv(CC) ||
3016       ParseOptionalAttrs(RetAttrs, 1) ||
3017       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3018       ParseValID(CalleeID) ||
3019       ParseParameterList(ArgList, PFS) ||
3020       ParseOptionalAttrs(FnAttrs, 2) ||
3021       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3022       ParseTypeAndValue(NormalBB, PFS) ||
3023       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3024       ParseTypeAndValue(UnwindBB, PFS))
3025     return true;
3026
3027   if (!isa<BasicBlock>(NormalBB))
3028     return Error(CallLoc, "normal destination is not a basic block");
3029   if (!isa<BasicBlock>(UnwindBB))
3030     return Error(CallLoc, "unwind destination is not a basic block");
3031
3032   // If RetType is a non-function pointer type, then this is the short syntax
3033   // for the call, which means that RetType is just the return type.  Infer the
3034   // rest of the function argument types from the arguments that are present.
3035   const PointerType *PFTy = 0;
3036   const FunctionType *Ty = 0;
3037   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3038       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3039     // Pull out the types of all of the arguments...
3040     std::vector<const Type*> ParamTypes;
3041     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3042       ParamTypes.push_back(ArgList[i].V->getType());
3043
3044     if (!FunctionType::isValidReturnType(RetType))
3045       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3046
3047     Ty = FunctionType::get(RetType, ParamTypes, false);
3048     PFTy = PointerType::getUnqual(Ty);
3049   }
3050
3051   // Look up the callee.
3052   Value *Callee;
3053   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3054
3055   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3056   // function attributes.
3057   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3058   if (FnAttrs & ObsoleteFuncAttrs) {
3059     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3060     FnAttrs &= ~ObsoleteFuncAttrs;
3061   }
3062
3063   // Set up the Attributes for the function.
3064   SmallVector<AttributeWithIndex, 8> Attrs;
3065   if (RetAttrs != Attribute::None)
3066     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3067
3068   SmallVector<Value*, 8> Args;
3069
3070   // Loop through FunctionType's arguments and ensure they are specified
3071   // correctly.  Also, gather any parameter attributes.
3072   FunctionType::param_iterator I = Ty->param_begin();
3073   FunctionType::param_iterator E = Ty->param_end();
3074   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3075     const Type *ExpectedTy = 0;
3076     if (I != E) {
3077       ExpectedTy = *I++;
3078     } else if (!Ty->isVarArg()) {
3079       return Error(ArgList[i].Loc, "too many arguments specified");
3080     }
3081
3082     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3083       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3084                    ExpectedTy->getDescription() + "'");
3085     Args.push_back(ArgList[i].V);
3086     if (ArgList[i].Attrs != Attribute::None)
3087       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3088   }
3089
3090   if (I != E)
3091     return Error(CallLoc, "not enough parameters specified for call");
3092
3093   if (FnAttrs != Attribute::None)
3094     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3095
3096   // Finish off the Attributes and check them
3097   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3098
3099   InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3100                                       cast<BasicBlock>(UnwindBB),
3101                                       Args.begin(), Args.end());
3102   II->setCallingConv(CC);
3103   II->setAttributes(PAL);
3104   Inst = II;
3105   return false;
3106 }
3107
3108
3109
3110 //===----------------------------------------------------------------------===//
3111 // Binary Operators.
3112 //===----------------------------------------------------------------------===//
3113
3114 /// ParseArithmetic
3115 ///  ::= ArithmeticOps TypeAndValue ',' Value
3116 ///
3117 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
3118 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3119 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3120                                unsigned Opc, unsigned OperandType) {
3121   LocTy Loc; Value *LHS, *RHS;
3122   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3123       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3124       ParseValue(LHS->getType(), RHS, PFS))
3125     return true;
3126
3127   bool Valid;
3128   switch (OperandType) {
3129   default: llvm_unreachable("Unknown operand type!");
3130   case 0: // int or FP.
3131     Valid = LHS->getType()->isIntOrIntVector() ||
3132             LHS->getType()->isFPOrFPVector();
3133     break;
3134   case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3135   case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3136   }
3137
3138   if (!Valid)
3139     return Error(Loc, "invalid operand type for instruction");
3140
3141   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3142   return false;
3143 }
3144
3145 /// ParseLogical
3146 ///  ::= ArithmeticOps TypeAndValue ',' Value {
3147 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3148                             unsigned Opc) {
3149   LocTy Loc; Value *LHS, *RHS;
3150   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3151       ParseToken(lltok::comma, "expected ',' in logical operation") ||
3152       ParseValue(LHS->getType(), RHS, PFS))
3153     return true;
3154
3155   if (!LHS->getType()->isIntOrIntVector())
3156     return Error(Loc,"instruction requires integer or integer vector operands");
3157
3158   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3159   return false;
3160 }
3161
3162
3163 /// ParseCompare
3164 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3165 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3166 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3167                             unsigned Opc) {
3168   // Parse the integer/fp comparison predicate.
3169   LocTy Loc;
3170   unsigned Pred;
3171   Value *LHS, *RHS;
3172   if (ParseCmpPredicate(Pred, Opc) ||
3173       ParseTypeAndValue(LHS, Loc, PFS) ||
3174       ParseToken(lltok::comma, "expected ',' after compare value") ||
3175       ParseValue(LHS->getType(), RHS, PFS))
3176     return true;
3177
3178   if (Opc == Instruction::FCmp) {
3179     if (!LHS->getType()->isFPOrFPVector())
3180       return Error(Loc, "fcmp requires floating point operands");
3181     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3182   } else {
3183     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3184     if (!LHS->getType()->isIntOrIntVector() &&
3185         !isa<PointerType>(LHS->getType()))
3186       return Error(Loc, "icmp requires integer operands");
3187     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3188   }
3189   return false;
3190 }
3191
3192 //===----------------------------------------------------------------------===//
3193 // Other Instructions.
3194 //===----------------------------------------------------------------------===//
3195
3196
3197 /// ParseCast
3198 ///   ::= CastOpc TypeAndValue 'to' Type
3199 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3200                          unsigned Opc) {
3201   LocTy Loc;  Value *Op;
3202   PATypeHolder DestTy(Type::getVoidTy(Context));
3203   if (ParseTypeAndValue(Op, Loc, PFS) ||
3204       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3205       ParseType(DestTy))
3206     return true;
3207
3208   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3209     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3210     return Error(Loc, "invalid cast opcode for cast from '" +
3211                  Op->getType()->getDescription() + "' to '" +
3212                  DestTy->getDescription() + "'");
3213   }
3214   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3215   return false;
3216 }
3217
3218 /// ParseSelect
3219 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3220 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3221   LocTy Loc;
3222   Value *Op0, *Op1, *Op2;
3223   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3224       ParseToken(lltok::comma, "expected ',' after select condition") ||
3225       ParseTypeAndValue(Op1, PFS) ||
3226       ParseToken(lltok::comma, "expected ',' after select value") ||
3227       ParseTypeAndValue(Op2, PFS))
3228     return true;
3229
3230   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3231     return Error(Loc, Reason);
3232
3233   Inst = SelectInst::Create(Op0, Op1, Op2);
3234   return false;
3235 }
3236
3237 /// ParseVA_Arg
3238 ///   ::= 'va_arg' TypeAndValue ',' Type
3239 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3240   Value *Op;
3241   PATypeHolder EltTy(Type::getVoidTy(Context));
3242   LocTy TypeLoc;
3243   if (ParseTypeAndValue(Op, PFS) ||
3244       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3245       ParseType(EltTy, TypeLoc))
3246     return true;
3247
3248   if (!EltTy->isFirstClassType())
3249     return Error(TypeLoc, "va_arg requires operand with first class type");
3250
3251   Inst = new VAArgInst(Op, EltTy);
3252   return false;
3253 }
3254
3255 /// ParseExtractElement
3256 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3257 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3258   LocTy Loc;
3259   Value *Op0, *Op1;
3260   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3261       ParseToken(lltok::comma, "expected ',' after extract value") ||
3262       ParseTypeAndValue(Op1, PFS))
3263     return true;
3264
3265   if (!ExtractElementInst::isValidOperands(Op0, Op1))
3266     return Error(Loc, "invalid extractelement operands");
3267
3268   Inst = ExtractElementInst::Create(Op0, Op1);
3269   return false;
3270 }
3271
3272 /// ParseInsertElement
3273 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3274 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3275   LocTy Loc;
3276   Value *Op0, *Op1, *Op2;
3277   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3278       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3279       ParseTypeAndValue(Op1, PFS) ||
3280       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3281       ParseTypeAndValue(Op2, PFS))
3282     return true;
3283
3284   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3285     return Error(Loc, "invalid insertelement operands");
3286
3287   Inst = InsertElementInst::Create(Op0, Op1, Op2);
3288   return false;
3289 }
3290
3291 /// ParseShuffleVector
3292 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3293 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3294   LocTy Loc;
3295   Value *Op0, *Op1, *Op2;
3296   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3297       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3298       ParseTypeAndValue(Op1, PFS) ||
3299       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3300       ParseTypeAndValue(Op2, PFS))
3301     return true;
3302
3303   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3304     return Error(Loc, "invalid extractelement operands");
3305
3306   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3307   return false;
3308 }
3309
3310 /// ParsePHI
3311 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3312 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3313   PATypeHolder Ty(Type::getVoidTy(Context));
3314   Value *Op0, *Op1;
3315   LocTy TypeLoc = Lex.getLoc();
3316
3317   if (ParseType(Ty) ||
3318       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3319       ParseValue(Ty, Op0, PFS) ||
3320       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3321       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3322       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3323     return true;
3324
3325   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3326   while (1) {
3327     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3328
3329     if (!EatIfPresent(lltok::comma))
3330       break;
3331
3332     if (Lex.getKind() == lltok::NamedOrCustomMD)
3333       break;
3334
3335     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3336         ParseValue(Ty, Op0, PFS) ||
3337         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3338         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3339         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3340       return true;
3341   }
3342
3343   if (Lex.getKind() == lltok::NamedOrCustomMD)
3344     if (ParseOptionalCustomMetadata()) return true;
3345
3346   if (!Ty->isFirstClassType())
3347     return Error(TypeLoc, "phi node must have first class type");
3348
3349   PHINode *PN = PHINode::Create(Ty);
3350   PN->reserveOperandSpace(PHIVals.size());
3351   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3352     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3353   Inst = PN;
3354   return false;
3355 }
3356
3357 /// ParseCall
3358 ///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3359 ///       ParameterList OptionalAttrs
3360 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3361                          bool isTail) {
3362   unsigned RetAttrs, FnAttrs;
3363   CallingConv::ID CC;
3364   PATypeHolder RetType(Type::getVoidTy(Context));
3365   LocTy RetTypeLoc;
3366   ValID CalleeID;
3367   SmallVector<ParamInfo, 16> ArgList;
3368   LocTy CallLoc = Lex.getLoc();
3369
3370   if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3371       ParseOptionalCallingConv(CC) ||
3372       ParseOptionalAttrs(RetAttrs, 1) ||
3373       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3374       ParseValID(CalleeID) ||
3375       ParseParameterList(ArgList, PFS) ||
3376       ParseOptionalAttrs(FnAttrs, 2))
3377     return true;
3378
3379   // If RetType is a non-function pointer type, then this is the short syntax
3380   // for the call, which means that RetType is just the return type.  Infer the
3381   // rest of the function argument types from the arguments that are present.
3382   const PointerType *PFTy = 0;
3383   const FunctionType *Ty = 0;
3384   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3385       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3386     // Pull out the types of all of the arguments...
3387     std::vector<const Type*> ParamTypes;
3388     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3389       ParamTypes.push_back(ArgList[i].V->getType());
3390
3391     if (!FunctionType::isValidReturnType(RetType))
3392       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3393
3394     Ty = FunctionType::get(RetType, ParamTypes, false);
3395     PFTy = PointerType::getUnqual(Ty);
3396   }
3397
3398   // Look up the callee.
3399   Value *Callee;
3400   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3401
3402   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3403   // function attributes.
3404   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3405   if (FnAttrs & ObsoleteFuncAttrs) {
3406     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3407     FnAttrs &= ~ObsoleteFuncAttrs;
3408   }
3409
3410   // Set up the Attributes for the function.
3411   SmallVector<AttributeWithIndex, 8> Attrs;
3412   if (RetAttrs != Attribute::None)
3413     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3414
3415   SmallVector<Value*, 8> Args;
3416
3417   // Loop through FunctionType's arguments and ensure they are specified
3418   // correctly.  Also, gather any parameter attributes.
3419   FunctionType::param_iterator I = Ty->param_begin();
3420   FunctionType::param_iterator E = Ty->param_end();
3421   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3422     const Type *ExpectedTy = 0;
3423     if (I != E) {
3424       ExpectedTy = *I++;
3425     } else if (!Ty->isVarArg()) {
3426       return Error(ArgList[i].Loc, "too many arguments specified");
3427     }
3428
3429     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3430       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3431                    ExpectedTy->getDescription() + "'");
3432     Args.push_back(ArgList[i].V);
3433     if (ArgList[i].Attrs != Attribute::None)
3434       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3435   }
3436
3437   if (I != E)
3438     return Error(CallLoc, "not enough parameters specified for call");
3439
3440   if (FnAttrs != Attribute::None)
3441     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3442
3443   // Finish off the Attributes and check them
3444   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3445
3446   CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3447   CI->setTailCall(isTail);
3448   CI->setCallingConv(CC);
3449   CI->setAttributes(PAL);
3450   Inst = CI;
3451   return false;
3452 }
3453
3454 //===----------------------------------------------------------------------===//
3455 // Memory Instructions.
3456 //===----------------------------------------------------------------------===//
3457
3458 /// ParseAlloc
3459 ///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3460 ///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3461 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3462                           BasicBlock* BB, bool isAlloca) {
3463   PATypeHolder Ty(Type::getVoidTy(Context));
3464   Value *Size = 0;
3465   LocTy SizeLoc;
3466   unsigned Alignment = 0;
3467   if (ParseType(Ty)) return true;
3468
3469   if (EatIfPresent(lltok::comma)) {
3470     if (Lex.getKind() == lltok::kw_align 
3471         || Lex.getKind() == lltok::NamedOrCustomMD) {
3472       if (ParseOptionalInfo(Alignment)) return true;
3473     } else {
3474       if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3475       if (EatIfPresent(lltok::comma))
3476         if (ParseOptionalInfo(Alignment)) return true;
3477     }
3478   }
3479
3480   if (Size && Size->getType() != Type::getInt32Ty(Context))
3481     return Error(SizeLoc, "element count must be i32");
3482
3483   if (isAlloca) {
3484     Inst = new AllocaInst(Ty, Size, Alignment);
3485     return false;
3486   }
3487
3488   // Autoupgrade old malloc instruction to malloc call.
3489   // FIXME: Remove in LLVM 3.0.
3490   const Type *IntPtrTy = Type::getInt32Ty(Context);
3491   if (!MallocF)
3492     // Prototype malloc as "void *(int32)".
3493     // This function is renamed as "malloc" in ValidateEndOfModule().
3494     MallocF = cast<Function>(
3495        M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
3496   Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, Size, MallocF);
3497   return false;
3498 }
3499
3500 /// ParseFree
3501 ///   ::= 'free' TypeAndValue
3502 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3503                          BasicBlock* BB) {
3504   Value *Val; LocTy Loc;
3505   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3506   if (!isa<PointerType>(Val->getType()))
3507     return Error(Loc, "operand to free must be a pointer");
3508   Inst = CallInst::CreateFree(Val, BB);
3509   return false;
3510 }
3511
3512 /// ParseLoad
3513 ///   ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3514 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3515                          bool isVolatile) {
3516   Value *Val; LocTy Loc;
3517   unsigned Alignment = 0;
3518   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3519
3520   if (EatIfPresent(lltok::comma))
3521     if (ParseOptionalInfo(Alignment)) return true;
3522
3523   if (!isa<PointerType>(Val->getType()) ||
3524       !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3525     return Error(Loc, "load operand must be a pointer to a first class type");
3526
3527   Inst = new LoadInst(Val, "", isVolatile, Alignment);
3528   return false;
3529 }
3530
3531 /// ParseStore
3532 ///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3533 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3534                           bool isVolatile) {
3535   Value *Val, *Ptr; LocTy Loc, PtrLoc;
3536   unsigned Alignment = 0;
3537   if (ParseTypeAndValue(Val, Loc, PFS) ||
3538       ParseToken(lltok::comma, "expected ',' after store operand") ||
3539       ParseTypeAndValue(Ptr, PtrLoc, PFS))
3540     return true;
3541
3542   if (EatIfPresent(lltok::comma))
3543     if (ParseOptionalInfo(Alignment)) return true;
3544
3545   if (!isa<PointerType>(Ptr->getType()))
3546     return Error(PtrLoc, "store operand must be a pointer");
3547   if (!Val->getType()->isFirstClassType())
3548     return Error(Loc, "store operand must be a first class value");
3549   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3550     return Error(Loc, "stored value and pointer type do not match");
3551
3552   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3553   return false;
3554 }
3555
3556 /// ParseGetResult
3557 ///   ::= 'getresult' TypeAndValue ',' i32
3558 /// FIXME: Remove support for getresult in LLVM 3.0
3559 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3560   Value *Val; LocTy ValLoc, EltLoc;
3561   unsigned Element;
3562   if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3563       ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3564       ParseUInt32(Element, EltLoc))
3565     return true;
3566
3567   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3568     return Error(ValLoc, "getresult inst requires an aggregate operand");
3569   if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3570     return Error(EltLoc, "invalid getresult index for value");
3571   Inst = ExtractValueInst::Create(Val, Element);
3572   return false;
3573 }
3574
3575 /// ParseGetElementPtr
3576 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3577 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3578   Value *Ptr, *Val; LocTy Loc, EltLoc;
3579
3580   bool InBounds = EatIfPresent(lltok::kw_inbounds);
3581
3582   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3583
3584   if (!isa<PointerType>(Ptr->getType()))
3585     return Error(Loc, "base of getelementptr must be a pointer");
3586
3587   SmallVector<Value*, 16> Indices;
3588   while (EatIfPresent(lltok::comma)) {
3589     if (Lex.getKind() == lltok::NamedOrCustomMD)
3590       break;
3591     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3592     if (!isa<IntegerType>(Val->getType()))
3593       return Error(EltLoc, "getelementptr index must be an integer");
3594     Indices.push_back(Val);
3595   }
3596   if (Lex.getKind() == lltok::NamedOrCustomMD)
3597     if (ParseOptionalCustomMetadata()) return true;
3598
3599   if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3600                                          Indices.begin(), Indices.end()))
3601     return Error(Loc, "invalid getelementptr indices");
3602   Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3603   if (InBounds)
3604     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3605   return false;
3606 }
3607
3608 /// ParseExtractValue
3609 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
3610 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3611   Value *Val; LocTy Loc;
3612   SmallVector<unsigned, 4> Indices;
3613   if (ParseTypeAndValue(Val, Loc, PFS) ||
3614       ParseIndexList(Indices))
3615     return true;
3616
3617   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3618     return Error(Loc, "extractvalue operand must be array or struct");
3619
3620   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3621                                         Indices.end()))
3622     return Error(Loc, "invalid indices for extractvalue");
3623   Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3624   return false;
3625 }
3626
3627 /// ParseInsertValue
3628 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3629 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3630   Value *Val0, *Val1; LocTy Loc0, Loc1;
3631   SmallVector<unsigned, 4> Indices;
3632   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3633       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3634       ParseTypeAndValue(Val1, Loc1, PFS) ||
3635       ParseIndexList(Indices))
3636     return true;
3637
3638   if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3639     return Error(Loc0, "extractvalue operand must be array or struct");
3640
3641   if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3642                                         Indices.end()))
3643     return Error(Loc0, "invalid indices for insertvalue");
3644   Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3645   return false;
3646 }
3647
3648 //===----------------------------------------------------------------------===//
3649 // Embedded metadata.
3650 //===----------------------------------------------------------------------===//
3651
3652 /// ParseMDNodeVector
3653 ///   ::= Element (',' Element)*
3654 /// Element
3655 ///   ::= 'null' | TypeAndValue
3656 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3657   assert(Lex.getKind() == lltok::lbrace);
3658   Lex.Lex();
3659   do {
3660     Value *V = 0;
3661     if (Lex.getKind() == lltok::kw_null) {
3662       Lex.Lex();
3663       V = 0;
3664     } else {
3665       PATypeHolder Ty(Type::getVoidTy(Context));
3666       if (ParseType(Ty)) return true;
3667       if (Lex.getKind() == lltok::Metadata) {
3668         Lex.Lex();
3669         MetadataBase *Node = 0;
3670         if (!ParseMDNode(Node))
3671           V = Node;
3672         else {
3673           MetadataBase *MDS = 0;
3674           if (ParseMDString(MDS)) return true;
3675           V = MDS;
3676         }
3677       } else {
3678         Constant *C;
3679         if (ParseGlobalValue(Ty, C)) return true;
3680         V = C;
3681       }
3682     }
3683     Elts.push_back(V);
3684   } while (EatIfPresent(lltok::comma));
3685
3686   return false;
3687 }