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