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