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