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