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