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