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