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