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