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