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