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