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